posthog-node 6.2.3 → 6.4.0

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 (41) hide show
  1. package/MIGRATION.md +4 -2
  2. package/dist/capture-lane/ai-content-removal.d.ts +8 -0
  3. package/dist/capture-lane/ai-content-removal.d.ts.map +1 -0
  4. package/dist/capture-lane/ai-content-removal.js +68 -0
  5. package/dist/capture-lane/ai-content-removal.mjs +26 -0
  6. package/dist/capture-lane/lane.d.ts +5 -0
  7. package/dist/capture-lane/lane.d.ts.map +1 -1
  8. package/dist/capture-lane/lane.js +22 -4
  9. package/dist/capture-lane/lane.mjs +22 -4
  10. package/dist/client.d.ts +14 -6
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js +58 -13
  13. package/dist/client.mjs +59 -14
  14. package/dist/emails/emails.d.ts.map +1 -1
  15. package/dist/emails/emails.js +28 -3
  16. package/dist/emails/emails.mjs +29 -4
  17. package/dist/emails/types.d.ts +41 -0
  18. package/dist/emails/types.d.ts.map +1 -1
  19. package/dist/extensions/feature-flags/feature-flags-v2.d.ts +4 -0
  20. package/dist/extensions/feature-flags/feature-flags-v2.d.ts.map +1 -1
  21. package/dist/extensions/feature-flags/feature-flags-v2.js +5 -3
  22. package/dist/extensions/feature-flags/feature-flags-v2.mjs +5 -3
  23. package/dist/extensions/feature-flags/feature-flags.d.ts +14 -3
  24. package/dist/extensions/feature-flags/feature-flags.d.ts.map +1 -1
  25. package/dist/extensions/feature-flags/feature-flags.js +130 -41
  26. package/dist/extensions/feature-flags/feature-flags.mjs +128 -42
  27. package/dist/types.d.ts +45 -1
  28. package/dist/types.d.ts.map +1 -1
  29. package/dist/version.d.ts +1 -1
  30. package/dist/version.js +1 -1
  31. package/dist/version.mjs +1 -1
  32. package/package.json +4 -4
  33. package/src/capture-lane/ai-content-removal.ts +40 -0
  34. package/src/capture-lane/lane.ts +40 -3
  35. package/src/client.ts +122 -16
  36. package/src/emails/emails.ts +40 -5
  37. package/src/emails/types.ts +41 -0
  38. package/src/extensions/feature-flags/feature-flags-v2.ts +16 -5
  39. package/src/extensions/feature-flags/feature-flags.ts +340 -63
  40. package/src/types.ts +45 -1
  41. package/src/version.ts +1 -1
@@ -4,6 +4,7 @@ import { CaptureError, CaptureLossTally, type CaptureDroppedEvent, describeCaptu
4
4
  import type { V1SendOptions } from '../capture-v1/sender'
5
5
  import { type SerializedV1Event, serializeV1Event, wireProblem } from '../capture-v1/serialize'
6
6
  import type { CaptureEndpoint } from '../capture-v1/types'
7
+ import { removeAiContent } from './ai-content-removal'
7
8
 
8
9
  /** Upper bound on the uuids one local-drop report lists; the message still carries the full count. */
9
10
  const MAX_REPORTED_LOCAL_DROPS = 100
@@ -28,6 +29,8 @@ export interface CaptureLaneConfig {
28
29
  maxEventBytes: number
29
30
  /** Whether `maxEventBytes` applies to the whole serialized event or to its `properties` only. */
30
31
  maxEventBytesOf: 'event' | 'properties'
32
+ /** Whether an over-size event is retried without its heavy AI properties before it is dropped. */
33
+ removeAiContentWhenTooLarge: boolean
31
34
  }
32
35
 
33
36
  export interface CaptureLaneHooks {
@@ -41,6 +44,8 @@ export interface CaptureLaneHooks {
41
44
  onError: (error: unknown) => void
42
45
  /** The messages one flush cycle sent. */
43
46
  onFlush: (messages: PostHogEventProperties[]) => void
47
+ /** An over-size event the lane sends without its AI content. Not a loss, so it is not reported as a drop. */
48
+ onAiContentRemoved?: (event: string, bytesBeforeRemoval: number, bytesAfterRemoval: number, limit: number) => void
44
49
  /** Each flush the lane starts on its own, from its timer or `flushAt`. */
45
50
  onBackgroundFlush?: (flush: Promise<void>) => void
46
51
  logger: Logger
@@ -71,7 +76,9 @@ const LOCAL_DROP_DETAILS: Record<LocalDropReason, string> = {
71
76
  }
72
77
 
73
78
  /** An event ready to send, or the uuid and reason of one dropped before sending. */
74
- type CheckedEvent = { event: SerializedV1Event } | { uuid: string; drop: LocalDropReason }
79
+ type CheckedEvent =
80
+ | { event: SerializedV1Event; message?: PostHogEventProperties }
81
+ | { uuid: string; drop: LocalDropReason }
75
82
 
76
83
  /**
77
84
  * One capture endpoint's in-memory queue, flush timer, `flushAt` trigger, batching and
@@ -119,7 +126,7 @@ export class CaptureLane {
119
126
  if (this.queue.length >= this.config.maxQueueSize) {
120
127
  this.recordLocalDrop(this.queue.shift()!.uuid, 'queueFull')
121
128
  }
122
- this.queue.push({ ...checked.event, message })
129
+ this.queue.push({ ...checked.event, message: checked.message ?? message })
123
130
 
124
131
  if (this.queue.length >= this.config.flushAt) {
125
132
  this.flushInBackground()
@@ -172,7 +179,37 @@ export class CaptureLane {
172
179
  } catch {
173
180
  return { uuid: String(message.uuid), drop: 'unserializable' }
174
181
  }
175
- return this.isTooLarge(event) ? { uuid: event.uuid, drop: 'tooLarge' } : { event }
182
+ if (!this.isTooLarge(event)) {
183
+ return { event }
184
+ }
185
+ return this.stripAiContent(message, event) ?? { uuid: event.uuid, drop: 'tooLarge' }
186
+ }
187
+
188
+ private stripAiContent(message: PostHogEventProperties, event: SerializedV1Event): CheckedEvent | undefined {
189
+ if (!this.config.removeAiContentWhenTooLarge) {
190
+ return undefined
191
+ }
192
+ try {
193
+ const stripped = removeAiContent(message, event.propertiesBytes)
194
+ if (!stripped) {
195
+ return undefined
196
+ }
197
+ const strippedEvent = serializeV1Event(stripped)
198
+ if (this.isTooLarge(strippedEvent)) {
199
+ return undefined
200
+ }
201
+ this.safely(() =>
202
+ this.hooks.onAiContentRemoved?.(
203
+ String(message.event),
204
+ event.propertiesBytes,
205
+ strippedEvent.propertiesBytes,
206
+ this.config.maxEventBytes
207
+ )
208
+ )
209
+ return { event: strippedEvent, message: stripped }
210
+ } catch {
211
+ return undefined
212
+ }
176
213
  }
177
214
 
178
215
  /** Sends everything queued when the returned flush starts. Never rejects. */
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()
@@ -964,6 +1018,11 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
964
1018
  onLocalDrops: (errors, summary) => this._reportCaptureLoss(errors, summary),
965
1019
  onError: (error) => this._events.emit('error', error),
966
1020
  onFlush: (messages) => this._events.emit('flush', messages),
1021
+ onAiContentRemoved: (event, bytesBeforeRemoval, bytesAfterRemoval, limit) =>
1022
+ // console.warn, not this._logger: the logger only prints in debug mode. Names and sizes only, never content.
1023
+ console.warn(
1024
+ `[PostHog] Event ${event} has ${bytesBeforeRemoval} bytes of properties, over the ${limit} byte limit for AI events, so it is sent without its content (${bytesAfterRemoval} bytes)`
1025
+ ),
967
1026
  onBackgroundFlush: (flush) => this._onLaneBackgroundFlush(flush),
968
1027
  logger: this._logger,
969
1028
  })
@@ -988,6 +1047,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
988
1047
  targetBatchBytes: CAPTURE_BATCH_TARGET_BYTES,
989
1048
  maxEventBytes: isAi ? AI_MAX_PROPERTIES_BYTES : ANALYTICS_MAX_EVENT_BYTES,
990
1049
  maxEventBytesOf: isAi ? 'properties' : 'event',
1050
+ removeAiContentWhenTooLarge: isAi,
991
1051
  }
992
1052
  }
993
1053
 
@@ -1187,8 +1247,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1187
1247
  * const client = new PostHog('phc_...', { secretKey: 'phs_...', host: 'https://eu.i.posthog.com' })
1188
1248
  * const { data, error } = await client.emails.send({
1189
1249
  * to: 'user@example.com',
1190
- * templateId: '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b',
1191
- * templateData: { name: 'Ada' },
1250
+ * templateKey: 'welcome',
1251
+ * subject: 'Welcome to Acme',
1252
+ * html: '<p>Hi Ada, welcome to Acme.</p>',
1192
1253
  * distinctId: 'user_123',
1193
1254
  * idempotencyKey: 'welcome:user_123',
1194
1255
  * })
@@ -1886,8 +1947,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1886
1947
  * Capture an AI event on the dedicated AI capture endpoint.
1887
1948
  *
1888
1949
  * Beta: the signature is stable; operational limits (per-event size cap,
1889
- * batching, endpoint) may change without notice. Delivery is async, and no
1890
- * redaction or truncation is applied to the payload.
1950
+ * batching, endpoint) may change without notice. Delivery is async. The
1951
+ * payload is sent as given, except that an event whose properties exceed the
1952
+ * per-event size cap is sent without its content properties.
1891
1953
  *
1892
1954
  * {@label Capture}
1893
1955
  *
@@ -2291,7 +2353,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2291
2353
  personProperties: Record<string, string> = {},
2292
2354
  groupProperties: Record<string, Record<string, string>> = {},
2293
2355
  disableGeoip?: boolean,
2294
- flagKeysToEvaluate?: string[]
2356
+ flagKeysToEvaluate?: string[],
2357
+ knownAbsentPropertyKeys?: PostHogFlagsKnownAbsentPropertyKeys
2295
2358
  ): Promise<PostHogFeatureFlagDetails | undefined> {
2296
2359
  const details = await super.getFeatureFlagDetailsStateless(
2297
2360
  distinctId,
@@ -2299,7 +2362,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2299
2362
  personProperties,
2300
2363
  groupProperties,
2301
2364
  disableGeoip,
2302
- flagKeysToEvaluate
2365
+ flagKeysToEvaluate,
2366
+ knownAbsentPropertyKeys
2303
2367
  )
2304
2368
  if (details !== undefined && !isPlainObject(details.flags)) {
2305
2369
  const message = '/flags response has a non-object `flags` field, treating it as a failed request'
@@ -2327,6 +2391,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2327
2391
  groups?: Record<string, string>
2328
2392
  personProperties?: Properties
2329
2393
  groupProperties?: Record<string, Properties>
2394
+ personPropertyKeysKnownAbsent?: string[]
2395
+ groupPropertyKeysKnownAbsent?: Record<string, string[]>
2330
2396
  onlyEvaluateLocally?: boolean
2331
2397
  sendFeatureFlagEvents?: boolean
2332
2398
  disableGeoip?: boolean
@@ -2338,6 +2404,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2338
2404
  return undefined
2339
2405
  }
2340
2406
 
2407
+ const knownAbsentPropertyKeys = readKnownAbsentPropertyKeys(options)
2341
2408
  const sendFeatureFlagEvents = options.sendFeatureFlagEvents ?? true
2342
2409
  // Check for overrides first - they take precedence over all evaluation
2343
2410
  if (this._flagOverrides !== undefined && key in this._flagOverrides) {
@@ -2371,7 +2438,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2371
2438
  distinctId,
2372
2439
  groups,
2373
2440
  this.personPropertiesForLocalEvaluation(distinctId, personProperties),
2374
- groupProperties
2441
+ groupProperties,
2442
+ knownAbsentPropertyKeys
2375
2443
  )
2376
2444
 
2377
2445
  // set defaults
@@ -2446,7 +2514,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2446
2514
  personProperties,
2447
2515
  groupProperties,
2448
2516
  disableGeoip,
2449
- [key]
2517
+ [key],
2518
+ knownAbsentPropertyKeys.request
2450
2519
  )
2451
2520
 
2452
2521
  if (flagsResponse === undefined) {
@@ -2628,6 +2697,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2628
2697
  groups?: Record<string, string>
2629
2698
  personProperties?: Properties
2630
2699
  groupProperties?: Record<string, Properties>
2700
+ personPropertyKeysKnownAbsent?: string[]
2701
+ groupPropertyKeysKnownAbsent?: Record<string, string[]>
2631
2702
  onlyEvaluateLocally?: boolean
2632
2703
  sendFeatureFlagEvents?: boolean
2633
2704
  disableGeoip?: boolean
@@ -2699,6 +2770,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2699
2770
  groups?: Record<string, string>
2700
2771
  personProperties?: Properties
2701
2772
  groupProperties?: Record<string, Properties>
2773
+ personPropertyKeysKnownAbsent?: string[]
2774
+ groupPropertyKeysKnownAbsent?: Record<string, string[]>
2702
2775
  onlyEvaluateLocally?: boolean
2703
2776
  /** @deprecated THIS OPTION HAS NO EFFECT, kept here for backwards compatibility reasons. */
2704
2777
  sendFeatureFlagEvents?: boolean
@@ -2913,6 +2986,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2913
2986
  groups?: Record<string, string>
2914
2987
  personProperties?: Properties
2915
2988
  groupProperties?: Record<string, Properties>
2989
+ personPropertyKeysKnownAbsent?: string[]
2990
+ groupPropertyKeysKnownAbsent?: Record<string, string[]>
2916
2991
  onlyEvaluateLocally?: boolean
2917
2992
  sendFeatureFlagEvents?: boolean
2918
2993
  disableGeoip?: boolean
@@ -3051,6 +3126,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3051
3126
 
3052
3127
  const { groups, disableGeoip, flagKeys } = resolvedOptions || {}
3053
3128
  let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {}
3129
+ const knownAbsentPropertyKeys = readKnownAbsentPropertyKeys(resolvedOptions || {})
3054
3130
 
3055
3131
  const adjustedProperties = this.addLocalPersonAndGroupProperties(
3056
3132
  resolvedDistinctId,
@@ -3065,7 +3141,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3065
3141
  resolvedDistinctId,
3066
3142
  groups,
3067
3143
  this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties),
3068
- groupProperties
3144
+ groupProperties,
3145
+ knownAbsentPropertyKeys
3069
3146
  )
3070
3147
 
3071
3148
  // set defaults
@@ -3091,7 +3168,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3091
3168
  personProperties,
3092
3169
  groupProperties,
3093
3170
  disableGeoip,
3094
- flagKeys
3171
+ flagKeys,
3172
+ knownAbsentPropertyKeys.request
3095
3173
  )
3096
3174
  featureFlags = {
3097
3175
  ...featureFlags,
@@ -3233,6 +3311,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3233
3311
 
3234
3312
  const { groups, disableGeoip } = resolvedOptions || {}
3235
3313
  const flagKeys = resolvedOptions?.flagKeys ?? undefined
3314
+ const knownAbsentPropertyKeys = readKnownAbsentPropertyKeys(resolvedOptions || {})
3236
3315
 
3237
3316
  if (flagKeys?.length === 0) {
3238
3317
  return new FeatureFlagEvaluations({
@@ -3258,7 +3337,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3258
3337
  resolvedDistinctId,
3259
3338
  groups,
3260
3339
  this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties),
3261
- groupProperties
3340
+ groupProperties,
3341
+ knownAbsentPropertyKeys
3262
3342
  )
3263
3343
 
3264
3344
  if (onlyEvaluateLocally == undefined) {
@@ -3314,7 +3394,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3314
3394
  personProperties,
3315
3395
  groupProperties,
3316
3396
  disableGeoip,
3317
- flagKeys
3397
+ flagKeys,
3398
+ knownAbsentPropertyKeys.request
3318
3399
  )
3319
3400
  if (details) {
3320
3401
  this._minimalFlagCalledEvents = details.minimalFlagCalledEvents === true
@@ -4195,6 +4276,11 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
4195
4276
  const finalPersonProperties = sendFeatureFlagsOptions?.personProperties || {}
4196
4277
  const finalGroupProperties = sendFeatureFlagsOptions?.groupProperties || {}
4197
4278
  const flagKeys = sendFeatureFlagsOptions?.flagKeys
4279
+ const { personPropertyKeysKnownAbsent, groupPropertyKeysKnownAbsent } = sendFeatureFlagsOptions || {}
4280
+ const knownAbsentPropertyKeys = readKnownAbsentPropertyKeys({
4281
+ personPropertyKeysKnownAbsent,
4282
+ groupPropertyKeysKnownAbsent,
4283
+ })
4198
4284
 
4199
4285
  // Check if we should only evaluate locally
4200
4286
  const onlyEvaluateLocally =
@@ -4205,13 +4291,17 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
4205
4291
  if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
4206
4292
  const groupsWithStringValues: Record<string, string> = {}
4207
4293
  for (const [key, value] of Object.entries(groups || {})) {
4208
- groupsWithStringValues[key] = String(value)
4294
+ if (isUsableGroupKey(value)) {
4295
+ groupsWithStringValues[key] = String(value)
4296
+ }
4209
4297
  }
4210
4298
 
4211
4299
  return await this.getAllFlags(distinctId, {
4212
4300
  groups: groupsWithStringValues,
4213
4301
  personProperties: finalPersonProperties,
4214
4302
  groupProperties: finalGroupProperties,
4303
+ personPropertyKeysKnownAbsent,
4304
+ groupPropertyKeysKnownAbsent,
4215
4305
  disableGeoip,
4216
4306
  onlyEvaluateLocally: true,
4217
4307
  flagKeys,
@@ -4226,13 +4316,17 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
4226
4316
  if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
4227
4317
  const groupsWithStringValues: Record<string, string> = {}
4228
4318
  for (const [key, value] of Object.entries(groups || {})) {
4229
- groupsWithStringValues[key] = String(value)
4319
+ if (isUsableGroupKey(value)) {
4320
+ groupsWithStringValues[key] = String(value)
4321
+ }
4230
4322
  }
4231
4323
 
4232
4324
  return await this.getAllFlags(distinctId, {
4233
4325
  groups: groupsWithStringValues,
4234
4326
  personProperties: finalPersonProperties,
4235
4327
  groupProperties: finalGroupProperties,
4328
+ personPropertyKeysKnownAbsent,
4329
+ groupPropertyKeysKnownAbsent,
4236
4330
  disableGeoip,
4237
4331
  onlyEvaluateLocally: true,
4238
4332
  flagKeys,
@@ -4246,7 +4340,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
4246
4340
  groups,
4247
4341
  finalPersonProperties,
4248
4342
  finalGroupProperties,
4249
- disableGeoip
4343
+ disableGeoip,
4344
+ undefined,
4345
+ knownAbsentPropertyKeys.request
4250
4346
  )
4251
4347
  ).flags
4252
4348
  }
@@ -4259,7 +4355,14 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
4259
4355
  ): { allPersonProperties: Properties; allGroupProperties: Record<string, Properties> } {
4260
4356
  const allPersonProperties = { ...(personProperties || {}) }
4261
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.
4262
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
+ }
4263
4366
  if (groups) {
4264
4367
  for (const groupName of Object.keys(groups)) {
4265
4368
  allGroupProperties[groupName] = {
@@ -4280,13 +4383,16 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
4280
4383
  distinctId: string,
4281
4384
  groups?: Record<string, string>,
4282
4385
  personProperties?: Properties,
4283
- groupProperties?: Record<string, Properties>
4386
+ groupProperties?: Record<string, Properties>,
4387
+ knownAbsentPropertyKeys?: KnownAbsentPropertyKeys
4284
4388
  ): FeatureFlagEvaluationContext {
4285
4389
  return {
4286
4390
  distinctId,
4287
4391
  groups: groups || {},
4288
4392
  personProperties: personProperties || {},
4289
4393
  groupProperties: groupProperties || {},
4394
+ personPropertyKeysKnownAbsent: knownAbsentPropertyKeys?.person,
4395
+ groupPropertyKeysKnownAbsent: knownAbsentPropertyKeys?.groups,
4290
4396
  evaluationCache: {},
4291
4397
  }
4292
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,6 +83,8 @@ 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,
@@ -561,9 +564,12 @@ function contentOf(send: UncheckedSend, distinctId: string | undefined): SendCon
561
564
  message: 'Send either templateId, or templateKey with subject and html, text or react.',
562
565
  })
563
566
  }
564
- return send.templateKey === undefined
565
- ? { content: templateContent(send, distinctId), files: [] }
566
- : 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
567
573
  }
568
574
 
569
575
  function templateContent(send: UncheckedSend, distinctId: string | undefined): Record<string, unknown> {
@@ -624,7 +630,7 @@ function codeContent(send: UncheckedSend, distinctId: string | undefined): SendC
624
630
  }
625
631
 
626
632
  function codeFormFields(send: UncheckedSend): Record<string, unknown> {
627
- const { from, replyTo, cc, bcc, captureEngagement, sensitive, tracking } = send
633
+ const { from, replyTo, cc, bcc, captureEngagement, sensitive, tracking, headers, tags } = send
628
634
  return {
629
635
  ...(from !== undefined && { from }),
630
636
  ...(replyTo !== undefined && unlessEmpty('reply_to', addressList(replyTo))),
@@ -633,9 +639,19 @@ function codeFormFields(send: UncheckedSend): Record<string, unknown> {
633
639
  ...(captureEngagement !== undefined && { capture_engagement: captureEngagement }),
634
640
  ...(sensitive !== undefined && { sensitive }),
635
641
  ...(tracking !== undefined && { tracking }),
642
+ ...(headers !== undefined && unlessEmptyObject('headers', headers, 'invalid_header')),
643
+ ...(tags !== undefined && unlessEmptyObject('tags', tags, 'invalid_tag')),
636
644
  }
637
645
  }
638
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)
651
+ }
652
+ return Object.keys(value).length === 0 ? {} : { [field]: value }
653
+ }
654
+
639
655
  function unlessEmpty(field: string, list: unknown): Record<string, unknown> {
640
656
  return Array.isArray(list) && list.length === 0 ? {} : { [field]: list }
641
657
  }
@@ -741,11 +757,30 @@ async function loadReactRenderer(logger: Logger): Promise<EmailReactRenderer> {
741
757
  }
742
758
  }
743
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
+
744
776
  function refuseFieldsOutside(send: UncheckedSend, form: SendForm, otherForm: SendForm): void {
745
777
  const field = Object.entries(send).find(([name, value]) => value !== undefined && !form.fields.has(name))?.[0]
746
778
  if (field === undefined) {
747
779
  return
748
780
  }
781
+ if (field === 'category') {
782
+ throw categoryRefusal()
783
+ }
749
784
  const message = `A send with ${form.name} doesn't take ${field}, so no email was sent.`
750
785
  if (!otherForm.fields.has(field)) {
751
786
  throw new EmailError({ code: 'invalid_form', message, field, fix: `Remove ${field} and send again.` })
@@ -89,6 +89,47 @@ interface CodeEmailFields {
89
89
  * click tracking. Needs posthog-node 5.71.0 or later.
90
90
  */
91
91
  tracking?: boolean | EmailTracking
92
+ /**
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.
96
+ */
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>
92
133
  }
93
134
 
94
135
  /** Which kinds of tracking a send with `templateKey` turns on. */
@@ -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
  },