posthog-node 6.3.0 → 6.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/MIGRATION.md +3 -1
  2. package/dist/client.d.ts +14 -8
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +55 -12
  5. package/dist/client.mjs +56 -13
  6. package/dist/emails/emails.d.ts +3 -3
  7. package/dist/emails/emails.d.ts.map +1 -1
  8. package/dist/emails/emails.js +29 -9
  9. package/dist/emails/emails.mjs +30 -10
  10. package/dist/emails/types.d.ts +42 -15
  11. package/dist/emails/types.d.ts.map +1 -1
  12. package/dist/extensions/feature-flags/feature-flags-v2.d.ts +4 -0
  13. package/dist/extensions/feature-flags/feature-flags-v2.d.ts.map +1 -1
  14. package/dist/extensions/feature-flags/feature-flags-v2.js +5 -3
  15. package/dist/extensions/feature-flags/feature-flags-v2.mjs +5 -3
  16. package/dist/extensions/feature-flags/feature-flags.d.ts +14 -3
  17. package/dist/extensions/feature-flags/feature-flags.d.ts.map +1 -1
  18. package/dist/extensions/feature-flags/feature-flags.js +130 -41
  19. package/dist/extensions/feature-flags/feature-flags.mjs +128 -42
  20. package/dist/extensions/nestjs.d.ts.map +1 -1
  21. package/dist/extensions/nestjs.js +1 -0
  22. package/dist/extensions/nestjs.mjs +1 -0
  23. package/dist/types.d.ts +46 -2
  24. package/dist/types.d.ts.map +1 -1
  25. package/dist/version.d.ts +1 -1
  26. package/dist/version.js +1 -1
  27. package/dist/version.mjs +1 -1
  28. package/package.json +3 -3
  29. package/src/client.ts +116 -18
  30. package/src/emails/emails.ts +44 -14
  31. package/src/emails/types.ts +42 -15
  32. package/src/extensions/feature-flags/feature-flags-v2.ts +16 -5
  33. package/src/extensions/feature-flags/feature-flags.ts +340 -63
  34. package/src/extensions/nestjs.ts +12 -0
  35. package/src/types.ts +46 -2
  36. package/src/version.ts +1 -1
package/src/client.ts CHANGED
@@ -40,6 +40,7 @@ import type {
40
40
  StartSpanOptions,
41
41
  TraceSdkContext,
42
42
  UnresolvedFlagReason,
43
+ PostHogFlagsKnownAbsentPropertyKeys,
43
44
  } from '@posthog/core'
44
45
  import {
45
46
  AllFlagsOptions,
@@ -87,6 +88,7 @@ import {
87
88
  type FeatureFlagEvaluationContext,
88
89
  FeatureFlagsPoller,
89
90
  InconclusiveMatchError,
91
+ isUsableGroupKey,
90
92
  RequiresServerEvaluation,
91
93
  } from './extensions/feature-flags/feature-flags'
92
94
  import ErrorTracking from './extensions/error-tracking'
@@ -419,6 +421,58 @@ function buildFlagEventProperties(flagValues: Record<string, FeatureFlagValue> |
419
421
  return additionalProperties
420
422
  }
421
423
 
424
+ // The flags service rejects longer lists, so they fail here instead of on a remote fallback.
425
+ const MAX_KNOWN_ABSENT_PROPERTY_KEYS = 1000
426
+ // Persons-table fields such as `created_at` are not person properties, so known absence never hides them.
427
+ const PERSON_METADATA_KEY_PREFIX = '__posthog_person_metadata__'
428
+
429
+ type KnownAbsentPropertyKeys = {
430
+ /** The caller's lists, unchanged, for the `/flags` request. */
431
+ request: PostHogFlagsKnownAbsentPropertyKeys
432
+ person?: ReadonlySet<string>
433
+ groups?: Record<string, ReadonlySet<string>>
434
+ }
435
+
436
+ /** Throws when a list is over the flags service limit; never truncates. */
437
+ function readKnownAbsentPropertyKeys(options: {
438
+ personPropertyKeysKnownAbsent?: string[]
439
+ groupPropertyKeysKnownAbsent?: Record<string, string[]>
440
+ }): KnownAbsentPropertyKeys {
441
+ // Copies, so the keys sent to `/flags` are the ones validated and used locally.
442
+ const personPropertyKeysKnownAbsent = options.personPropertyKeysKnownAbsent?.slice()
443
+ const groupPropertyKeysKnownAbsent = options.groupPropertyKeysKnownAbsent
444
+ ? Object.fromEntries(
445
+ Object.entries(options.groupPropertyKeysKnownAbsent)
446
+ // Plain JavaScript callers can pass an undefined list; skip it as the `/flags` body does.
447
+ .filter(([, keys]) => keys !== undefined)
448
+ .map(([groupType, keys]) => [groupType, keys.slice()])
449
+ )
450
+ : undefined
451
+ const result: KnownAbsentPropertyKeys = {
452
+ request: { personPropertyKeysKnownAbsent, groupPropertyKeysKnownAbsent },
453
+ }
454
+ if (personPropertyKeysKnownAbsent) {
455
+ if (personPropertyKeysKnownAbsent.length > MAX_KNOWN_ABSENT_PROPERTY_KEYS) {
456
+ throw new Error(`personPropertyKeysKnownAbsent allows at most ${MAX_KNOWN_ABSENT_PROPERTY_KEYS} keys`)
457
+ }
458
+ result.person = new Set(personPropertyKeysKnownAbsent.filter((key) => !key.startsWith(PERSON_METADATA_KEY_PREFIX)))
459
+ }
460
+ if (groupPropertyKeysKnownAbsent) {
461
+ // No prototype, so a group type such as `constructor` has no inherited entry.
462
+ const groups: Record<string, ReadonlySet<string>> = Object.create(null)
463
+ for (const [groupType, keys] of Object.entries(groupPropertyKeysKnownAbsent)) {
464
+ if (keys.length > MAX_KNOWN_ABSENT_PROPERTY_KEYS) {
465
+ throw new Error(
466
+ `groupPropertyKeysKnownAbsent allows at most ${MAX_KNOWN_ABSENT_PROPERTY_KEYS} keys per group type`
467
+ )
468
+ }
469
+ groups[groupType] = new Set(keys)
470
+ }
471
+ result.groups = groups
472
+ }
473
+ return result
474
+ }
475
+
422
476
  // The actual exported Nodejs API.
423
477
  export abstract class PostHogBackendClient extends PostHogCoreStateless implements IPostHog {
424
478
  private _memoryStorage = new PostHogMemoryStorage()
@@ -1181,8 +1235,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1181
1235
  }
1182
1236
 
1183
1237
  /**
1184
- * Send transactional email from PostHog templates, or transactional and marketing email from inline code, read send
1185
- * status, and update topic preferences.
1238
+ * Send transactional email from PostHog templates or inline code, read send status, and update topic preferences.
1186
1239
  *
1187
1240
  * - **Credentials and scopes.** Needs `secretKey` (`phs_...`). `send` needs `transactional_email:write`, `get` needs `transactional_email:read` or `transactional_email:write`, `setPreferences` needs `messaging_preference:write`, and `hog_flow:write` keys cover all three. Set `enableLocalEvaluation: false` when the key is only for email.
1188
1241
  * - **Routing and retries.** Requests go to `appHost`, or the PostHog Cloud app host for `host`. Configure `emailRequestTimeoutMs` and `emailRequestMaxRetries` per client.
@@ -1194,17 +1247,18 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1194
1247
  * const client = new PostHog('phc_...', { secretKey: 'phs_...', host: 'https://eu.i.posthog.com' })
1195
1248
  * const { data, error } = await client.emails.send({
1196
1249
  * to: 'user@example.com',
1197
- * templateId: '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b',
1198
- * templateData: { name: 'Ada' },
1250
+ * templateKey: 'welcome',
1251
+ * subject: 'Welcome to Acme',
1252
+ * html: '<p>Hi Ada, welcome to Acme.</p>',
1199
1253
  * distinctId: 'user_123',
1200
1254
  * idempotencyKey: 'welcome:user_123',
1201
1255
  * })
1202
1256
  * if (error) {
1203
1257
  * console.error(error.code, error.message)
1258
+ * } else {
1259
+ * const status = await client.emails.get(data.id) // later, for example from a job
1204
1260
  * }
1205
1261
  *
1206
- * const status = await client.emails.get(data.id) // later, for example from a job
1207
- *
1208
1262
  * // From a preference center: opt out of one topic, keep the rest
1209
1263
  * await client.emails.setPreferences({ to: 'user@example.com', topics: { newsletter: false } })
1210
1264
  * ```
@@ -2299,7 +2353,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2299
2353
  personProperties: Record<string, string> = {},
2300
2354
  groupProperties: Record<string, Record<string, string>> = {},
2301
2355
  disableGeoip?: boolean,
2302
- flagKeysToEvaluate?: string[]
2356
+ flagKeysToEvaluate?: string[],
2357
+ knownAbsentPropertyKeys?: PostHogFlagsKnownAbsentPropertyKeys
2303
2358
  ): Promise<PostHogFeatureFlagDetails | undefined> {
2304
2359
  const details = await super.getFeatureFlagDetailsStateless(
2305
2360
  distinctId,
@@ -2307,7 +2362,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2307
2362
  personProperties,
2308
2363
  groupProperties,
2309
2364
  disableGeoip,
2310
- flagKeysToEvaluate
2365
+ flagKeysToEvaluate,
2366
+ knownAbsentPropertyKeys
2311
2367
  )
2312
2368
  if (details !== undefined && !isPlainObject(details.flags)) {
2313
2369
  const message = '/flags response has a non-object `flags` field, treating it as a failed request'
@@ -2335,6 +2391,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2335
2391
  groups?: Record<string, string>
2336
2392
  personProperties?: Properties
2337
2393
  groupProperties?: Record<string, Properties>
2394
+ personPropertyKeysKnownAbsent?: string[]
2395
+ groupPropertyKeysKnownAbsent?: Record<string, string[]>
2338
2396
  onlyEvaluateLocally?: boolean
2339
2397
  sendFeatureFlagEvents?: boolean
2340
2398
  disableGeoip?: boolean
@@ -2346,6 +2404,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2346
2404
  return undefined
2347
2405
  }
2348
2406
 
2407
+ const knownAbsentPropertyKeys = readKnownAbsentPropertyKeys(options)
2349
2408
  const sendFeatureFlagEvents = options.sendFeatureFlagEvents ?? true
2350
2409
  // Check for overrides first - they take precedence over all evaluation
2351
2410
  if (this._flagOverrides !== undefined && key in this._flagOverrides) {
@@ -2379,7 +2438,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2379
2438
  distinctId,
2380
2439
  groups,
2381
2440
  this.personPropertiesForLocalEvaluation(distinctId, personProperties),
2382
- groupProperties
2441
+ groupProperties,
2442
+ knownAbsentPropertyKeys
2383
2443
  )
2384
2444
 
2385
2445
  // set defaults
@@ -2454,7 +2514,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2454
2514
  personProperties,
2455
2515
  groupProperties,
2456
2516
  disableGeoip,
2457
- [key]
2517
+ [key],
2518
+ knownAbsentPropertyKeys.request
2458
2519
  )
2459
2520
 
2460
2521
  if (flagsResponse === undefined) {
@@ -2636,6 +2697,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2636
2697
  groups?: Record<string, string>
2637
2698
  personProperties?: Properties
2638
2699
  groupProperties?: Record<string, Properties>
2700
+ personPropertyKeysKnownAbsent?: string[]
2701
+ groupPropertyKeysKnownAbsent?: Record<string, string[]>
2639
2702
  onlyEvaluateLocally?: boolean
2640
2703
  sendFeatureFlagEvents?: boolean
2641
2704
  disableGeoip?: boolean
@@ -2707,6 +2770,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2707
2770
  groups?: Record<string, string>
2708
2771
  personProperties?: Properties
2709
2772
  groupProperties?: Record<string, Properties>
2773
+ personPropertyKeysKnownAbsent?: string[]
2774
+ groupPropertyKeysKnownAbsent?: Record<string, string[]>
2710
2775
  onlyEvaluateLocally?: boolean
2711
2776
  /** @deprecated THIS OPTION HAS NO EFFECT, kept here for backwards compatibility reasons. */
2712
2777
  sendFeatureFlagEvents?: boolean
@@ -2921,6 +2986,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2921
2986
  groups?: Record<string, string>
2922
2987
  personProperties?: Properties
2923
2988
  groupProperties?: Record<string, Properties>
2989
+ personPropertyKeysKnownAbsent?: string[]
2990
+ groupPropertyKeysKnownAbsent?: Record<string, string[]>
2924
2991
  onlyEvaluateLocally?: boolean
2925
2992
  sendFeatureFlagEvents?: boolean
2926
2993
  disableGeoip?: boolean
@@ -3059,6 +3126,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3059
3126
 
3060
3127
  const { groups, disableGeoip, flagKeys } = resolvedOptions || {}
3061
3128
  let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {}
3129
+ const knownAbsentPropertyKeys = readKnownAbsentPropertyKeys(resolvedOptions || {})
3062
3130
 
3063
3131
  const adjustedProperties = this.addLocalPersonAndGroupProperties(
3064
3132
  resolvedDistinctId,
@@ -3073,7 +3141,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3073
3141
  resolvedDistinctId,
3074
3142
  groups,
3075
3143
  this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties),
3076
- groupProperties
3144
+ groupProperties,
3145
+ knownAbsentPropertyKeys
3077
3146
  )
3078
3147
 
3079
3148
  // set defaults
@@ -3099,7 +3168,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3099
3168
  personProperties,
3100
3169
  groupProperties,
3101
3170
  disableGeoip,
3102
- flagKeys
3171
+ flagKeys,
3172
+ knownAbsentPropertyKeys.request
3103
3173
  )
3104
3174
  featureFlags = {
3105
3175
  ...featureFlags,
@@ -3241,6 +3311,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3241
3311
 
3242
3312
  const { groups, disableGeoip } = resolvedOptions || {}
3243
3313
  const flagKeys = resolvedOptions?.flagKeys ?? undefined
3314
+ const knownAbsentPropertyKeys = readKnownAbsentPropertyKeys(resolvedOptions || {})
3244
3315
 
3245
3316
  if (flagKeys?.length === 0) {
3246
3317
  return new FeatureFlagEvaluations({
@@ -3266,7 +3337,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3266
3337
  resolvedDistinctId,
3267
3338
  groups,
3268
3339
  this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties),
3269
- groupProperties
3340
+ groupProperties,
3341
+ knownAbsentPropertyKeys
3270
3342
  )
3271
3343
 
3272
3344
  if (onlyEvaluateLocally == undefined) {
@@ -3322,7 +3394,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3322
3394
  personProperties,
3323
3395
  groupProperties,
3324
3396
  disableGeoip,
3325
- flagKeys
3397
+ flagKeys,
3398
+ knownAbsentPropertyKeys.request
3326
3399
  )
3327
3400
  if (details) {
3328
3401
  this._minimalFlagCalledEvents = details.minimalFlagCalledEvents === true
@@ -4203,6 +4276,11 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
4203
4276
  const finalPersonProperties = sendFeatureFlagsOptions?.personProperties || {}
4204
4277
  const finalGroupProperties = sendFeatureFlagsOptions?.groupProperties || {}
4205
4278
  const flagKeys = sendFeatureFlagsOptions?.flagKeys
4279
+ const { personPropertyKeysKnownAbsent, groupPropertyKeysKnownAbsent } = sendFeatureFlagsOptions || {}
4280
+ const knownAbsentPropertyKeys = readKnownAbsentPropertyKeys({
4281
+ personPropertyKeysKnownAbsent,
4282
+ groupPropertyKeysKnownAbsent,
4283
+ })
4206
4284
 
4207
4285
  // Check if we should only evaluate locally
4208
4286
  const onlyEvaluateLocally =
@@ -4213,13 +4291,17 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
4213
4291
  if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
4214
4292
  const groupsWithStringValues: Record<string, string> = {}
4215
4293
  for (const [key, value] of Object.entries(groups || {})) {
4216
- groupsWithStringValues[key] = String(value)
4294
+ if (isUsableGroupKey(value)) {
4295
+ groupsWithStringValues[key] = String(value)
4296
+ }
4217
4297
  }
4218
4298
 
4219
4299
  return await this.getAllFlags(distinctId, {
4220
4300
  groups: groupsWithStringValues,
4221
4301
  personProperties: finalPersonProperties,
4222
4302
  groupProperties: finalGroupProperties,
4303
+ personPropertyKeysKnownAbsent,
4304
+ groupPropertyKeysKnownAbsent,
4223
4305
  disableGeoip,
4224
4306
  onlyEvaluateLocally: true,
4225
4307
  flagKeys,
@@ -4234,13 +4316,17 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
4234
4316
  if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
4235
4317
  const groupsWithStringValues: Record<string, string> = {}
4236
4318
  for (const [key, value] of Object.entries(groups || {})) {
4237
- groupsWithStringValues[key] = String(value)
4319
+ if (isUsableGroupKey(value)) {
4320
+ groupsWithStringValues[key] = String(value)
4321
+ }
4238
4322
  }
4239
4323
 
4240
4324
  return await this.getAllFlags(distinctId, {
4241
4325
  groups: groupsWithStringValues,
4242
4326
  personProperties: finalPersonProperties,
4243
4327
  groupProperties: finalGroupProperties,
4328
+ personPropertyKeysKnownAbsent,
4329
+ groupPropertyKeysKnownAbsent,
4244
4330
  disableGeoip,
4245
4331
  onlyEvaluateLocally: true,
4246
4332
  flagKeys,
@@ -4254,7 +4340,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
4254
4340
  groups,
4255
4341
  finalPersonProperties,
4256
4342
  finalGroupProperties,
4257
- disableGeoip
4343
+ disableGeoip,
4344
+ undefined,
4345
+ knownAbsentPropertyKeys.request
4258
4346
  )
4259
4347
  ).flags
4260
4348
  }
@@ -4267,7 +4355,14 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
4267
4355
  ): { allPersonProperties: Properties; allGroupProperties: Record<string, Properties> } {
4268
4356
  const allPersonProperties = { ...(personProperties || {}) }
4269
4357
 
4358
+ // Properties of a group type without a key still give the flags service group context and the
4359
+ // values that group filters of that group type read.
4270
4360
  const allGroupProperties: Record<string, Properties> = {}
4361
+ for (const [groupName, properties] of Object.entries(groupProperties || {})) {
4362
+ if (properties != null) {
4363
+ allGroupProperties[groupName] = properties
4364
+ }
4365
+ }
4271
4366
  if (groups) {
4272
4367
  for (const groupName of Object.keys(groups)) {
4273
4368
  allGroupProperties[groupName] = {
@@ -4288,13 +4383,16 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
4288
4383
  distinctId: string,
4289
4384
  groups?: Record<string, string>,
4290
4385
  personProperties?: Properties,
4291
- groupProperties?: Record<string, Properties>
4386
+ groupProperties?: Record<string, Properties>,
4387
+ knownAbsentPropertyKeys?: KnownAbsentPropertyKeys
4292
4388
  ): FeatureFlagEvaluationContext {
4293
4389
  return {
4294
4390
  distinctId,
4295
4391
  groups: groups || {},
4296
4392
  personProperties: personProperties || {},
4297
4393
  groupProperties: groupProperties || {},
4394
+ personPropertyKeysKnownAbsent: knownAbsentPropertyKeys?.person,
4395
+ groupPropertyKeysKnownAbsent: knownAbsentPropertyKeys?.groups,
4298
4396
  evaluationCache: {},
4299
4397
  }
4300
4398
  }
@@ -2,6 +2,7 @@ import {
2
2
  type Logger,
3
3
  type PostHogFetchOptions,
4
4
  type PostHogFetchResponse,
5
+ isPlainObject,
5
6
  parseRetryAfterMs,
6
7
  removeTrailingSlash,
7
8
  safeJsonStringify,
@@ -71,7 +72,7 @@ const SHARED_FIELDS: EveryField<SendEmailBase> = {
71
72
  maxRetries: true,
72
73
  }
73
74
  const TEMPLATE_FIELDS: EveryField<TemplateEmailForm> = { templateId: true, templateData: true }
74
- const CODE_FIELDS: EveryField<CodeEmailForm> = {
75
+ const CODE_FIELDS: EveryField<Omit<CodeEmailForm, 'category'>> = {
75
76
  templateKey: true,
76
77
  subject: true,
77
78
  from: true,
@@ -82,15 +83,16 @@ const CODE_FIELDS: EveryField<CodeEmailForm> = {
82
83
  attachments: true,
83
84
  sensitive: true,
84
85
  tracking: true,
86
+ headers: true,
87
+ tags: true,
85
88
  html: true,
86
89
  text: true,
87
90
  react: true,
88
- category: true,
89
91
  }
90
92
  const TEMPLATE_FORM: SendForm = {
91
93
  name: 'templateId',
92
94
  fields: fieldSet(SHARED_FIELDS, TEMPLATE_FIELDS),
93
- why: "A template made in PostHog sets its own sender, subject, content and category, and follows the project's engagement setting.",
95
+ why: "A template made in PostHog sets its own sender, subject and content, and follows the project's engagement setting.",
94
96
  howToSend: 'send a template made in PostHog with templateId',
95
97
  }
96
98
  const CODE_FORM: SendForm = {
@@ -148,9 +150,9 @@ interface Reply {
148
150
  }
149
151
 
150
152
  /**
151
- * Sends one transactional or marketing email per call to the messaging send API on the app host,
152
- * reads the status of a sent email, and sets a recipient's topic preferences. Owns the attempt
153
- * loop, so every attempt of a send carries the same idempotency key.
153
+ * Sends one transactional email per call to the messaging send API on the app host, reads the
154
+ * status of a sent email, and sets a recipient's topic preferences. Owns the attempt loop, so every
155
+ * attempt of a send carries the same idempotency key.
154
156
  */
155
157
  export class EmailSender implements Emails {
156
158
  private readonly config: EmailSenderConfig
@@ -562,9 +564,12 @@ function contentOf(send: UncheckedSend, distinctId: string | undefined): SendCon
562
564
  message: 'Send either templateId, or templateKey with subject and html, text or react.',
563
565
  })
564
566
  }
565
- return send.templateKey === undefined
566
- ? { content: templateContent(send, distinctId), files: [] }
567
- : codeContent(send, distinctId)
567
+ const content =
568
+ send.templateKey === undefined
569
+ ? { content: templateContent(send, distinctId), files: [] }
570
+ : codeContent(send, distinctId)
571
+ refuseCategory(send)
572
+ return content
568
573
  }
569
574
 
570
575
  function templateContent(send: UncheckedSend, distinctId: string | undefined): Record<string, unknown> {
@@ -625,10 +630,7 @@ function codeContent(send: UncheckedSend, distinctId: string | undefined): SendC
625
630
  }
626
631
 
627
632
  function codeFormFields(send: UncheckedSend): Record<string, unknown> {
628
- const { from, replyTo, cc, bcc, captureEngagement, sensitive, tracking, category } = send
629
- if (category !== undefined && typeof category !== 'string') {
630
- throw invalid('invalid_form', 'category must be the key of a message category, as a string.', 'category')
631
- }
633
+ const { from, replyTo, cc, bcc, captureEngagement, sensitive, tracking, headers, tags } = send
632
634
  return {
633
635
  ...(from !== undefined && { from }),
634
636
  ...(replyTo !== undefined && unlessEmpty('reply_to', addressList(replyTo))),
@@ -637,8 +639,17 @@ function codeFormFields(send: UncheckedSend): Record<string, unknown> {
637
639
  ...(captureEngagement !== undefined && { capture_engagement: captureEngagement }),
638
640
  ...(sensitive !== undefined && { sensitive }),
639
641
  ...(tracking !== undefined && { tracking }),
640
- ...(category !== undefined && { category }),
642
+ ...(headers !== undefined && unlessEmptyObject('headers', headers, 'invalid_header')),
643
+ ...(tags !== undefined && unlessEmptyObject('tags', tags, 'invalid_tag')),
644
+ }
645
+ }
646
+
647
+ // PostHog owns the names, values and limits, so the client only checks the shape.
648
+ function unlessEmptyObject(field: string, value: unknown, code: string): Record<string, unknown> {
649
+ if (!isPlainObject(value)) {
650
+ throw invalid(code, `${field} must be an object of names to string values.`, field)
641
651
  }
652
+ return Object.keys(value).length === 0 ? {} : { [field]: value }
642
653
  }
643
654
 
644
655
  function unlessEmpty(field: string, list: unknown): Record<string, unknown> {
@@ -746,11 +757,30 @@ async function loadReactRenderer(logger: Logger): Promise<EmailReactRenderer> {
746
757
  }
747
758
  }
748
759
 
760
+ function refuseCategory(send: UncheckedSend): void {
761
+ if (send.category !== undefined) {
762
+ throw categoryRefusal()
763
+ }
764
+ }
765
+
766
+ function categoryRefusal(): EmailError {
767
+ return new EmailError({
768
+ code: 'invalid_form',
769
+ message: "posthog.emails.send doesn't take category, so no email was sent.",
770
+ field: 'category',
771
+ why: 'Code-sent emails are transactional only.',
772
+ fix: 'Send marketing email through a PostHog workflow.',
773
+ })
774
+ }
775
+
749
776
  function refuseFieldsOutside(send: UncheckedSend, form: SendForm, otherForm: SendForm): void {
750
777
  const field = Object.entries(send).find(([name, value]) => value !== undefined && !form.fields.has(name))?.[0]
751
778
  if (field === undefined) {
752
779
  return
753
780
  }
781
+ if (field === 'category') {
782
+ throw categoryRefusal()
783
+ }
754
784
  const message = `A send with ${form.name} doesn't take ${field}, so no email was sent.`
755
785
  if (!otherForm.fields.has(field)) {
756
786
  throw new EmailError({ code: 'invalid_form', message, field, fix: `Remove ${field} and send again.` })
@@ -90,18 +90,46 @@ interface CodeEmailFields {
90
90
  */
91
91
  tracking?: boolean | EmailTracking
92
92
  /**
93
- * The key of one of the project's message categories, such as `'newsletter'`, for the email
94
- * your code rendered. A marketing category skips recipients who opted out of it or of all
95
- * marketing email, fills `{{ unsubscribe_url }}` with the recipient's preferences link, and
96
- * adds List-Unsubscribe headers. A marketing email can't have `cc` or `bcc`.
97
- *
98
- * PostHog refuses the send with `category_not_found` when the project has no category with this
99
- * key, `marketing_copies_unsupported` when a marketing email has `cc` or `bcc`, and
100
- * `sandbox_fields_unsupported` when a marketing email would go out from PostHog's test sender
101
- * because the project has no verified sending domain. A marketing email with `attachments` is
102
- * refused with `workflow_can_wait` (verified sender) or `sandbox_fields_unsupported` (test sender).
93
+ * @deprecated Code-sent emails are transactional only. A send that sets `category` is refused
94
+ * with `invalid_form` before any request, and no email is sent. Send marketing email through a
95
+ * PostHog workflow.
103
96
  */
104
97
  category?: string
98
+ /**
99
+ * Email headers that PostHog puts on the email itself, not on the request, such as
100
+ * `{ 'X-Entity-Ref-ID': 'order-1234' }`. The client leaves an empty object out and sends the
101
+ * rest as given. PostHog checks the names and values:
102
+ *
103
+ * - At most 8 headers. Allowed names are `In-Reply-To`, `References`, `List-Unsubscribe`,
104
+ * `List-Unsubscribe-Post`, `List-Id`, and any name that starts with `X-`, except `X-PostHog-`
105
+ * and `X-SES-`.
106
+ * - Each value is at most 870 ASCII characters, without line breaks. Only an `X-` header takes
107
+ * non-ASCII text, up to 200 UTF-8 bytes.
108
+ * - A header that PostHog sets itself keeps PostHog's value.
109
+ *
110
+ * PostHog refuses a header it doesn't take with code `invalid_header`, and the client refuses a
111
+ * value that isn't an object with the same code. A send with `templateId` doesn't take headers,
112
+ * and the PostHog test sender refuses them with `sandbox_fields_unsupported`. A PostHog that
113
+ * doesn't take headers yet refuses them with `field_not_accepted`. Needs posthog-node 6.4.0 or
114
+ * later.
115
+ */
116
+ headers?: Record<string, string>
117
+ /**
118
+ * Tags that PostHog adds to the email's events, such as `{ plan: 'pro' }`. They come back as
119
+ * `$email_tags` on the sent, delivered, opened, clicked and bounced events, so you can break them
120
+ * down by `properties.$email_tags.plan`. The client leaves an empty object out and sends the
121
+ * rest as given. PostHog checks the names and values:
122
+ *
123
+ * - At most 10 tags.
124
+ * - A name is 1 to 64 letters, digits, `_` and `-`, and starts with a letter or digit.
125
+ * - A value is 1 to 256 of the same characters.
126
+ *
127
+ * PostHog refuses a tag it doesn't take with code `invalid_tag`, and the client refuses a value
128
+ * that isn't an object with the same code. A send with `templateId` doesn't take tags, and the
129
+ * PostHog test sender refuses them with `sandbox_fields_unsupported`. A PostHog that doesn't take
130
+ * tags yet refuses them with `field_not_accepted`. Needs posthog-node 6.4.0 or later.
131
+ */
132
+ tags?: Record<string, string>
105
133
  }
106
134
 
107
135
  /** Which kinds of tracking a send with `templateKey` turns on. */
@@ -290,14 +318,13 @@ export interface EmailPreferences {
290
318
  export type SetEmailPreferencesResponse = { data: EmailPreferences; error: null } | { data: null; error: EmailError }
291
319
 
292
320
  /**
293
- * The `posthog.emails` API: sends transactional email from PostHog email templates, or
294
- * transactional and marketing email from content your code rendered, reads the status of each
295
- * email it sent, and sets a recipient's topic preferences.
321
+ * The `posthog.emails` API: sends transactional email from PostHog email templates or from
322
+ * content your code rendered, reads the status of each email it sent, and sets a recipient's
323
+ * topic preferences.
296
324
  */
297
325
  export interface Emails {
298
326
  /**
299
- * Queue one email: a transactional email from a PostHog email template, or a transactional or
300
- * marketing email from content your code rendered.
327
+ * Queue one email, from a transactional email template or from content your code rendered.
301
328
  *
302
329
  * Resolves to `{ data, error }` and does not reject. `data` means PostHog queued the email,
303
330
  * not that it was delivered. `error` is an `EmailError`: branch on its `code`.
@@ -265,6 +265,8 @@ export type ConfigV2 = {
265
265
  * - `propertiesComplete`: whether `properties` holds every property of the person. A complete map
266
266
  * shows that a property is absent. A partial map does not, so a filter on a key it lacks is
267
267
  * inconclusive.
268
+ * - `knownAbsentKeys`: keys the person is known not to have. Each one is absent, even over a value
269
+ * in `properties`.
268
270
  * - `explicitExactMatching`: the project's setting for the `exact` and `is_not` operators. When
269
271
  * false, a filter value that looks like a boolean matches by truthiness.
270
272
  * - `timeZone`: the project's timezone, as an IANA name. Dates without a UTC offset and relative
@@ -276,6 +278,7 @@ export type ConfigV2Context = {
276
278
  readonly identifier: string
277
279
  readonly properties: Readonly<Record<string, unknown>> | null
278
280
  readonly propertiesComplete: boolean
281
+ readonly knownAbsentKeys?: ReadonlySet<string>
279
282
  readonly explicitExactMatching: boolean
280
283
  readonly timeZone?: string
281
284
  readonly now?: Date
@@ -890,11 +893,13 @@ class Draws {
890
893
  /** Whether a predicate holds for the person, after its negation. */
891
894
  function matches(predicate: Predicate, context: ConfigV2Context): boolean {
892
895
  const properties = context.properties
893
- if (properties === null || properties === undefined) {
896
+ const knownAbsent = context.knownAbsentKeys?.has(predicate.key) === true
897
+ if ((properties === null || properties === undefined) && !knownAbsent) {
894
898
  throw unusableContext('No person properties were passed')
895
899
  }
896
- const present = hasOwn(properties, predicate.key) && isKeptByJson(properties[predicate.key])
897
- if (!present && !context.propertiesComplete) {
900
+ // A listed key is absent even over a supplied value.
901
+ const present = !knownAbsent && hasOwn(properties!, predicate.key) && isKeptByJson(properties![predicate.key])
902
+ if (!present && !knownAbsent && !context.propertiesComplete) {
898
903
  throw unusableContext(`The person property '${predicate.key}' was not passed`)
899
904
  }
900
905
  // An invalid pattern is an error even when the person lacks the property, and negation does
@@ -906,7 +911,7 @@ function matches(predicate: Predicate, context: ConfigV2Context): boolean {
906
911
  detail: `The pattern for '${predicate.key}' is not valid`,
907
912
  })
908
913
  }
909
- const matched = matchOperator(predicate, present, present ? properties[predicate.key] : undefined, context)
914
+ const matched = matchOperator(predicate, present, present ? properties![predicate.key] : undefined, context)
910
915
  return matched !== predicate.negation
911
916
  }
912
917
 
@@ -1990,7 +1995,12 @@ export function configV2HasPayloads(flag: PostHogFeatureFlag): boolean {
1990
1995
  export async function evaluateConfigV2Definition(
1991
1996
  flag: PostHogFeatureFlag,
1992
1997
  parsed: ReadonlyMap<string, ParsedConfigV2Definition>,
1993
- context: { distinctId: string; properties: Record<string, unknown>; propertyMatchingVersion: number | undefined }
1998
+ context: {
1999
+ distinctId: string
2000
+ properties: Record<string, unknown>
2001
+ knownAbsentKeys?: ReadonlySet<string>
2002
+ propertyMatchingVersion: number | undefined
2003
+ }
1994
2004
  ): Promise<ConfigV2LocalResult> {
1995
2005
  const version = configVersionOf(flag)
1996
2006
  if (version !== CONFIG_VERSION) {
@@ -2005,6 +2015,7 @@ export async function evaluateConfigV2Definition(
2005
2015
  identifier: String(context.distinctId),
2006
2016
  properties: context.properties,
2007
2017
  propertiesComplete: false,
2018
+ knownAbsentKeys: context.knownAbsentKeys,
2008
2019
  explicitExactMatching: context.propertyMatchingVersion === 2,
2009
2020
  timeZone: 'UTC',
2010
2021
  },