posthog-node 6.2.1 → 6.2.3

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 (37) hide show
  1. package/dist/client.d.ts +1 -1
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +14 -3
  4. package/dist/client.mjs +14 -3
  5. package/dist/emails/errors.d.ts +8 -1
  6. package/dist/emails/errors.d.ts.map +1 -1
  7. package/dist/emails/types.d.ts +41 -15
  8. package/dist/emails/types.d.ts.map +1 -1
  9. package/dist/extensions/feature-flags/feature-flags-v2.d.ts +254 -0
  10. package/dist/extensions/feature-flags/feature-flags-v2.d.ts.map +1 -0
  11. package/dist/extensions/feature-flags/feature-flags-v2.js +1408 -0
  12. package/dist/extensions/feature-flags/feature-flags-v2.mjs +1331 -0
  13. package/dist/extensions/feature-flags/feature-flags.d.ts +15 -4
  14. package/dist/extensions/feature-flags/feature-flags.d.ts.map +1 -1
  15. package/dist/extensions/feature-flags/feature-flags.js +55 -7
  16. package/dist/extensions/feature-flags/feature-flags.mjs +55 -7
  17. package/dist/feature-flag-evaluations.d.ts +8 -6
  18. package/dist/feature-flag-evaluations.d.ts.map +1 -1
  19. package/dist/flag-events.d.ts +2 -2
  20. package/dist/flag-events.d.ts.map +1 -1
  21. package/dist/flag-events.js +2 -1
  22. package/dist/flag-events.mjs +2 -1
  23. package/dist/types.d.ts +15 -7
  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 +2 -2
  29. package/src/client.ts +18 -6
  30. package/src/emails/errors.ts +8 -1
  31. package/src/emails/types.ts +41 -15
  32. package/src/extensions/feature-flags/feature-flags-v2.ts +2086 -0
  33. package/src/extensions/feature-flags/feature-flags.ts +110 -20
  34. package/src/feature-flag-evaluations.ts +8 -6
  35. package/src/flag-events.ts +3 -2
  36. package/src/types.ts +15 -7
  37. package/src/version.ts +1 -1
@@ -28,6 +28,22 @@ import {
28
28
  safeSetTimeout,
29
29
  } from '@posthog/core'
30
30
  import { FlagDefinitionCacheProvider, FlagDefinitionCacheData, FlagDefinitionCacheInput } from './cache'
31
+ import {
32
+ configV2HasPayloads,
33
+ ConfigV2LocalResult,
34
+ configV2UnresolvedReason,
35
+ evaluateConfigV2Definition,
36
+ isConfigVersion1,
37
+ ParsedConfigV2Definition,
38
+ parseConfigV2Definitions,
39
+ } from './feature-flags-v2'
40
+
41
+ // The field of the external definition cache that holds the definitions whose config version is
42
+ // not 1. `flags` keeps the version 1 definitions only, so a release that reads only `flags` never
43
+ // evaluates a definition it cannot read. Not part of the public cache types.
44
+ const CONFIG_V2_FLAGS_CACHE_FIELD = 'flags_v2'
45
+
46
+ type FlagDefinitionCacheDataWithConfigV2 = FlagDefinitionCacheData & { [CONFIG_V2_FLAGS_CACHE_FIELD]?: unknown }
31
47
 
32
48
  const SIXTY_SECONDS = 60 * 1000
33
49
 
@@ -135,6 +151,8 @@ type FlagEvaluationSnapshot = {
135
151
  cohorts: Record<string, PropertyGroup>
136
152
  filteredOutFlagKeys: Set<string>
137
153
  propertyMatchingVersion?: number
154
+ // The config version 2 definitions of `featureFlagsByKey`, parsed when they loaded.
155
+ parsedConfigV2Definitions: ReadonlyMap<string, ParsedConfigV2Definition>
138
156
  }
139
157
 
140
158
  export type FeatureFlagEvaluationContext = {
@@ -151,6 +169,16 @@ type ComputeFlagAndPayloadOptions = {
151
169
  skipLoadCheck?: boolean
152
170
  }
153
171
 
172
+ /**
173
+ * A locally computed flag. `record` is the `/flags?v=4` record of a config version 2 flag, which
174
+ * the client reads and sends flag events from as for a remote record. A version 1 flag has none.
175
+ */
176
+ type LocalFlagResult = {
177
+ value: FeatureFlagValue
178
+ payload: JsonType | null
179
+ record?: ConfigV2LocalResult
180
+ }
181
+
154
182
  class FeatureFlagsPoller {
155
183
  pollingInterval: number | null
156
184
  personalApiKey?: string
@@ -186,6 +214,7 @@ class FeatureFlagsPoller {
186
214
  private filteredOutFlagKeys: Set<string> = new Set()
187
215
  // Definition fingerprint per flag key already warned about as never locally resolvable.
188
216
  private warnedUnresolvableFlags: Map<string, string> = new Map()
217
+ private parsedConfigV2Definitions: ReadonlyMap<string, ParsedConfigV2Definition> = new Map()
189
218
 
190
219
  constructor({
191
220
  pollingInterval,
@@ -235,6 +264,7 @@ class FeatureFlagsPoller {
235
264
  cohorts: this.cohorts,
236
265
  filteredOutFlagKeys: this.filteredOutFlagKeys,
237
266
  propertyMatchingVersion: this.propertyMatchingVersion,
267
+ parsedConfigV2Definitions: this.parsedConfigV2Definitions,
238
268
  }
239
269
  }
240
270
 
@@ -308,6 +338,8 @@ class FeatureFlagsPoller {
308
338
  response: Record<string, FeatureFlagValue>
309
339
  payloads: Record<string, JsonType>
310
340
  unresolved: Record<string, UnresolvedFlagReason>
341
+ /** The `/flags?v=4` record of each config version 2 flag in `response`. */
342
+ records: Record<string, ConfigV2LocalResult>
311
343
  fallbackToFlags: boolean
312
344
  }> {
313
345
  await this.loadFeatureFlags()
@@ -315,6 +347,7 @@ class FeatureFlagsPoller {
315
347
  const response: Record<string, FeatureFlagValue> = {}
316
348
  const payloads: Record<string, JsonType> = {}
317
349
  const unresolved: Record<string, UnresolvedFlagReason> = {}
350
+ const records: Record<string, ConfigV2LocalResult> = {}
318
351
  let fallbackToFlags = this.featureFlags.length == 0
319
352
 
320
353
  const flagsToEvaluate = flagKeysToExplicitlyEvaluate
@@ -329,15 +362,18 @@ class FeatureFlagsPoller {
329
362
  await Promise.all(
330
363
  flagsToEvaluate.map(async (flag) => {
331
364
  try {
332
- const { value: matchValue, payload: matchPayload } = await this.computeFlagAndPayloadLocally(
333
- flag,
334
- sharedEvaluationContext,
335
- { skipLoadCheck: true }
336
- )
365
+ const {
366
+ value: matchValue,
367
+ payload: matchPayload,
368
+ record,
369
+ } = await this.computeFlagAndPayloadLocally(flag, sharedEvaluationContext, { skipLoadCheck: true })
337
370
  response[flag.key] = matchValue
338
371
  if (matchPayload !== undefined && matchPayload !== null) {
339
372
  payloads[flag.key] = matchPayload
340
373
  }
374
+ if (record !== undefined) {
375
+ records[flag.key] = record
376
+ }
341
377
  } catch (e) {
342
378
  if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) {
343
379
  this.logMsgIfDebug(() => console.debug(`${e.name} when computing flag locally: ${flag.key}: ${e.message}`))
@@ -352,17 +388,14 @@ class FeatureFlagsPoller {
352
388
  })
353
389
  )
354
390
 
355
- return { response, payloads, unresolved, fallbackToFlags }
391
+ return { response, payloads, unresolved, records, fallbackToFlags }
356
392
  }
357
393
 
358
394
  async computeFlagAndPayloadLocally(
359
395
  flag: PostHogFeatureFlag,
360
396
  evaluationContext: FeatureFlagEvaluationContext,
361
397
  options: ComputeFlagAndPayloadOptions = {}
362
- ): Promise<{
363
- value: FeatureFlagValue
364
- payload: JsonType | null
365
- }> {
398
+ ): Promise<LocalFlagResult> {
366
399
  const { matchValue, skipLoadCheck = false } = options
367
400
  if (this.loadedSuccessfullyOnce) {
368
401
  evaluationContext = this.withEvaluationSnapshot(evaluationContext)
@@ -379,6 +412,32 @@ class FeatureFlagsPoller {
379
412
 
380
413
  evaluationContext = this.withEvaluationSnapshot(evaluationContext)
381
414
  flag = evaluationContext.definitions!.featureFlagsByKey[flag.key] ?? flag
415
+
416
+ if (!isConfigVersion1(flag)) {
417
+ const parsed = evaluationContext.definitions!.parsedConfigV2Definitions
418
+ // A config version 2 definition has no payloads to look a match value up in. Only a number
419
+ // or object value has a payload, the value itself, rendered as `true`. So a readable
420
+ // definition is evaluated for a match value only when that value is `true` and the flag
421
+ // returns a number or an object. Any other match value has no payload.
422
+ if (
423
+ matchValue !== undefined &&
424
+ !(matchValue === true && configV2HasPayloads(flag)) &&
425
+ configV2UnresolvedReason(flag, parsed) === undefined
426
+ ) {
427
+ return { value: matchValue, payload: null }
428
+ }
429
+ const record = await evaluateConfigV2Definition(flag, parsed, {
430
+ distinctId: evaluationContext.distinctId,
431
+ properties: evaluationContext.personProperties,
432
+ propertyMatchingVersion: evaluationContext.definitions!.propertyMatchingVersion,
433
+ })
434
+ if (matchValue !== undefined) {
435
+ // The payload of `true`, without the record's attribution.
436
+ return { value: matchValue, payload: record.value === true ? record.payload : null }
437
+ }
438
+ return { value: record.value, payload: record.payload, record }
439
+ }
440
+
382
441
  let flagValue: FeatureFlagValue
383
442
 
384
443
  // If matchValue is provided, use it directly; otherwise evaluate the flag
@@ -542,6 +601,19 @@ class FeatureFlagsPoller {
542
601
  throw new InconclusiveMatchError(`Missing flag dependency '${missingDependency}' for flag '${targetFlagKey}'`)
543
602
  }
544
603
 
604
+ // A config version 1 flag cannot depend on a flag of another config version. Reading one here
605
+ // as version 1 would give it a value, and a later condition must not answer for the flag
606
+ // either, so the whole flag goes to the server.
607
+ const otherVersionDependency = dependencyChain.find((depFlagKey) => {
608
+ const depFlag = evaluationContext.definitions!.featureFlagsByKey[depFlagKey]
609
+ return depFlag !== undefined && !isConfigVersion1(depFlag)
610
+ })
611
+ if (otherVersionDependency !== undefined) {
612
+ throw new RequiresServerEvaluation(
613
+ `Flag dependency '${otherVersionDependency}' for flag '${targetFlagKey}' is not a config version 1 flag`
614
+ )
615
+ }
616
+
545
617
  // Evaluate all dependencies in the chain order
546
618
  for (const depFlagKey of dependencyChain) {
547
619
  if (!(depFlagKey in evaluationCache)) {
@@ -907,7 +979,12 @@ class FeatureFlagsPoller {
907
979
  }
908
980
 
909
981
  private updateFlagState(flagData: FlagDefinitionCacheInput): void {
910
- const flags = this.filterFlagsByEvaluationContexts(flagData.flags)
982
+ // The cache keeps definitions of another config version apart; evaluation reads them all.
983
+ const configV2Flags = (flagData as FlagDefinitionCacheDataWithConfigV2)[CONFIG_V2_FLAGS_CACHE_FIELD]
984
+ const allFlags = Array.isArray(configV2Flags)
985
+ ? [...flagData.flags, ...(configV2Flags as PostHogFeatureFlag[])]
986
+ : flagData.flags
987
+ const flags = this.filterFlagsByEvaluationContexts(allFlags)
911
988
  const featureFlagsByKey = flags.reduce<Record<string, PostHogFeatureFlag>>(
912
989
  (acc, curr) => ((acc[curr.key] = curr), acc),
913
990
  {}
@@ -915,11 +992,10 @@ class FeatureFlagsPoller {
915
992
  // Remember which definitions were dropped by context filtering so dependency evaluation can
916
993
  // treat them as false (mirroring the remote path) rather than as genuinely missing.
917
994
  const keptKeys = new Set(flags.map((flag) => flag.key))
918
- const filteredOutFlagKeys = new Set(
919
- flagData.flags.filter((flag) => !keptKeys.has(flag.key)).map((flag) => flag.key)
920
- )
995
+ const filteredOutFlagKeys = new Set(allFlags.filter((flag) => !keptKeys.has(flag.key)).map((flag) => flag.key))
921
996
  this.featureFlags = flags
922
997
  this.featureFlagsByKey = featureFlagsByKey
998
+ this.parsedConfigV2Definitions = parseConfigV2Definitions(flags)
923
999
  this.filteredOutFlagKeys = filteredOutFlagKeys
924
1000
  this.groupTypeMapping = flagData.group_type_mapping ?? flagData.groupTypeMapping ?? {}
925
1001
  this.cohorts = flagData.cohorts
@@ -1007,7 +1083,7 @@ class FeatureFlagsPoller {
1007
1083
  const cached = await this.cacheProvider.getFlagDefinitions()
1008
1084
  if (cached) {
1009
1085
  this.updateFlagState(cached)
1010
- this.logMsgIfDebug(() => console.debug(`[FEATURE FLAGS] ${debugMessage} (${cached.flags.length} flags)`))
1086
+ this.logMsgIfDebug(() => console.debug(`[FEATURE FLAGS] ${debugMessage} (${this.featureFlags.length} flags)`))
1011
1087
  this.onLoad?.(this.featureFlags.length)
1012
1088
  // Warn only about flags this instance actually evaluates locally; context-filtered flags
1013
1089
  // are absent from the kept set and never take the server-fallback path.
@@ -1192,6 +1268,7 @@ class FeatureFlagsPoller {
1192
1268
  )
1193
1269
  this.featureFlags = []
1194
1270
  this.featureFlagsByKey = {}
1271
+ this.parsedConfigV2Definitions = new Map()
1195
1272
  this.filteredOutFlagKeys = new Set()
1196
1273
  this.groupTypeMapping = {}
1197
1274
  this.cohorts = {}
@@ -1228,8 +1305,9 @@ class FeatureFlagsPoller {
1228
1305
  const groupTypeMapping = (responseJson.group_type_mapping as Record<string, string>) || {}
1229
1306
  // Absence of the field always flips the gate off — fail safe to full events.
1230
1307
  const minimalFlagCalledEvents = responseJson.minimal_flag_called_events === true
1231
- const flagData: FlagDefinitionCacheData = {
1232
- flags: (responseJson.flags as PostHogFeatureFlag[]) ?? [],
1308
+ const flags: PostHogFeatureFlag[] = (responseJson.flags as PostHogFeatureFlag[]) ?? []
1309
+ const flagData: FlagDefinitionCacheDataWithConfigV2 = {
1310
+ flags: flags.filter(isConfigVersion1),
1233
1311
  group_type_mapping: groupTypeMapping,
1234
1312
  cohorts: (responseJson.cohorts as Record<string, PropertyGroup>) || {},
1235
1313
  minimal_flag_called_events: minimalFlagCalledEvents,
@@ -1239,6 +1317,11 @@ class FeatureFlagsPoller {
1239
1317
  groupTypeMapping,
1240
1318
  minimalFlagCalledEvents,
1241
1319
  }
1320
+ const configV2Flags = flags.filter((flag) => !isConfigVersion1(flag))
1321
+ if (configV2Flags.length > 0) {
1322
+ // Left out without such flags, so the data stays as before for them.
1323
+ flagData[CONFIG_V2_FLAGS_CACHE_FIELD] = configV2Flags
1324
+ }
1242
1325
 
1243
1326
  this.updateFlagState(flagData)
1244
1327
  // Set timestamp to when definitions were actually fetched from server
@@ -1388,6 +1471,9 @@ function getDefinitionUnresolvedReason(
1388
1471
  flag: PostHogFeatureFlag,
1389
1472
  definitions: FlagEvaluationSnapshot
1390
1473
  ): UnresolvedFlagReason | undefined {
1474
+ if (!isConfigVersion1(flag)) {
1475
+ return configV2UnresolvedReason(flag, definitions.parsedConfigV2Definitions)
1476
+ }
1391
1477
  if (!flag.active) {
1392
1478
  return undefined
1393
1479
  }
@@ -1435,9 +1521,13 @@ function isUnsupportedProperty(
1435
1521
  if (!Array.isArray(dependencyChain) || dependencyChain.length === 0) {
1436
1522
  return true
1437
1523
  }
1438
- return dependencyChain.some(
1439
- (key) => !definitions.featureFlagsByKey[key] && !definitions.filteredOutFlagKeys.has(key)
1440
- )
1524
+ return dependencyChain.some((key) => {
1525
+ const dependency = definitions.featureFlagsByKey[key]
1526
+ if (dependency === undefined) {
1527
+ return !definitions.filteredOutFlagKeys.has(key)
1528
+ }
1529
+ return !isConfigVersion1(dependency)
1530
+ })
1441
1531
  }
1442
1532
  if (property.type !== 'cohort') {
1443
1533
  try {
@@ -21,9 +21,10 @@ export type EvaluatedFlagRecord = {
21
21
  /** Whether the flag is linked to an experiment; undefined when the server did not report it. */
22
22
  hasExperiment: boolean | undefined
23
23
  /**
24
- * The parsed `/flags` record of a remotely evaluated flag, with its typed value, failure
25
- * state, reason and rule metadata, for the typed flag API and flag events. Absent for locally
26
- * evaluated flags and flags with a value override.
24
+ * The parsed `/flags` record of a remotely evaluated flag, or the same record of a locally
25
+ * evaluated config version 2 flag, with its typed value, failure state, reason and rule
26
+ * metadata, for the typed flag API and flag events. Absent for locally evaluated version 1
27
+ * flags and flags with a value override.
27
28
  */
28
29
  parsed?: ParsedFlagRecord
29
30
  }
@@ -41,9 +42,10 @@ export type FlagCalledEventParams = {
41
42
  disableGeoip: boolean | undefined
42
43
  properties: Record<string, any>
43
44
  /**
44
- * The parsed `/flags` record supplying the read's value or failure diagnostics. Absent for
45
- * local evaluation, overrides and missing flags. A failed record keeps config/reason
46
- * attribution, but only a successful experiment split sends `$experiment_exposure`.
45
+ * The parsed `/flags` record supplying the read's value or failure diagnostics, or the same
46
+ * record of a locally evaluated config version 2 flag. Absent for local evaluation of version 1
47
+ * flags, overrides and missing flags. A failed record keeps config/reason attribution, but only
48
+ * a successful experiment split sends `$experiment_exposure`.
47
49
  */
48
50
  record?: ParsedFlagRecord
49
51
  }
@@ -68,6 +68,7 @@ const EXPOSURE_PROPERTIES_FROM_FLAG_CALLED = [
68
68
  '$feature_flag_version',
69
69
  '$feature_flag_request_id',
70
70
  '$feature_flag_evaluated_at',
71
+ '$feature_flag_definitions_loaded_at',
71
72
  ]
72
73
 
73
74
  // The rule ID's wire format: a hyphenated UUID, as the contract's event schemas require.
@@ -191,8 +192,8 @@ export type ConfigVersion2FlagEvents = {
191
192
  *
192
193
  * Returns `undefined` when `record` has no config version 2 attribution (see
193
194
  * {@link ruleAttribution}), including when it is absent because the value came from local
194
- * evaluation, an override or no flag at all. The caller then sends its `$feature_flag_called` as
195
- * before.
195
+ * evaluation of a version 1 flag, an override or no flag at all. The caller then sends its
196
+ * `$feature_flag_called` as before.
196
197
  *
197
198
  * `$feature_flag_called` gets the record's attribution in place of the human-readable
198
199
  * `$feature_flag_reason`. Its dedupe key is the flag key, the response, the groups, the config
package/src/types.ts CHANGED
@@ -497,20 +497,28 @@ export type PostHogOptions = Omit<
497
497
  *
498
498
  * Needed only when `host` is not PostHog Cloud, for example a reverse proxy, which must not
499
499
  * receive the secret key. On PostHog Cloud, the client derives `https://us.posthog.com` or
500
- * `https://eu.posthog.com` from `host`.
500
+ * `https://eu.posthog.com` from `host`. When `host` is not PostHog Cloud and `appHost` is not set,
501
+ * every `posthog.emails` call fails with `missing_app_host` and sends nothing. A self-hosted PostHog
502
+ * needs a version from 2026-11-18 or later, and an older one answers email calls with a 404.
503
+ *
504
+ * With `enableLocalEvaluation` on, the client polls flag definitions from `host` with `secretKey`,
505
+ * and `getRemoteConfigPayload()` always sends `secretKey` to `host`. When `host` is a proxy that
506
+ * must not see the key, set `enableLocalEvaluation: false` and don't call `getRemoteConfigPayload()`
507
+ * on this client.
501
508
  */
502
509
  appHost?: string
503
510
  /**
504
- * Timeout in milliseconds for each `emails.send` request. Each attachment upload is one request,
505
- * so raise it when large files upload slowly.
511
+ * Timeout in milliseconds for each `posthog.emails` request: a send, a status read, a preferences
512
+ * change, or one attachment upload. Raise it when large files upload slowly. Rendering a `react`
513
+ * element has the same limit.
506
514
  *
507
515
  * @default 15000
508
516
  */
509
517
  emailRequestTimeoutMs?: number
510
518
  /**
511
- * Number of retries for an `emails.send` after a network error, a rate limit, or an
512
- * unavailable service. Every retry sends the same idempotency key. Set to 0 when a job
513
- * runner already retries the send.
519
+ * Number of retries for a `posthog.emails` call after a network error, a rate limit, or an
520
+ * unavailable service. Every retry of a send carries the same idempotency key. Set to 0 when a
521
+ * job runner already retries the send. A send's own `maxRetries` overrides it.
514
522
  *
515
523
  * @default 2
516
524
  */
@@ -521,7 +529,7 @@ export type PostHogOptions = Omit<
521
529
  * Renders the `react` element of an `emails.send`. Set it when you bundle your app, such as
522
530
  * for Cloudflare Workers, Convex, or Vercel Edge: posthog-node doesn't bundle `@react-email/render`,
523
531
  * so apps that never send `react` don't carry it. Without it, posthog-node loads
524
- * `@react-email/render` from `node_modules` when a send has `react`.
532
+ * `@react-email/render` from `node_modules` when a send has `react`. Needs posthog-node 6.2.0 or later.
525
533
  *
526
534
  * @example
527
535
  * ```ts
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = "6.2.1"
1
+ export const version = "6.2.3"