posthog-node 6.2.0 → 6.2.2

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 (49) hide show
  1. package/dist/client.d.ts +252 -125
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +35 -6
  4. package/dist/client.mjs +35 -6
  5. package/dist/entrypoints/otel.d.ts +20 -0
  6. package/dist/entrypoints/otel.d.ts.map +1 -1
  7. package/dist/exports.d.ts +2 -1
  8. package/dist/exports.d.ts.map +1 -1
  9. package/dist/extensions/context/listeners.d.ts +3 -2
  10. package/dist/extensions/context/listeners.d.ts.map +1 -1
  11. package/dist/extensions/context/types.d.ts +2 -0
  12. package/dist/extensions/context/types.d.ts.map +1 -1
  13. package/dist/extensions/express.d.ts +30 -4
  14. package/dist/extensions/express.d.ts.map +1 -1
  15. package/dist/extensions/feature-flags/feature-flags-v2.d.ts +254 -0
  16. package/dist/extensions/feature-flags/feature-flags-v2.d.ts.map +1 -0
  17. package/dist/extensions/feature-flags/feature-flags-v2.js +1408 -0
  18. package/dist/extensions/feature-flags/feature-flags-v2.mjs +1331 -0
  19. package/dist/extensions/feature-flags/feature-flags.d.ts +15 -4
  20. package/dist/extensions/feature-flags/feature-flags.d.ts.map +1 -1
  21. package/dist/extensions/feature-flags/feature-flags.js +55 -7
  22. package/dist/extensions/feature-flags/feature-flags.mjs +55 -7
  23. package/dist/extensions/nestjs.d.ts +23 -0
  24. package/dist/extensions/nestjs.d.ts.map +1 -1
  25. package/dist/feature-flag-evaluations.d.ts +8 -6
  26. package/dist/feature-flag-evaluations.d.ts.map +1 -1
  27. package/dist/flag-events.d.ts +2 -2
  28. package/dist/flag-events.d.ts.map +1 -1
  29. package/dist/flag-events.js +2 -1
  30. package/dist/flag-events.mjs +2 -1
  31. package/dist/types.d.ts +120 -95
  32. package/dist/types.d.ts.map +1 -1
  33. package/dist/version.d.ts +1 -1
  34. package/dist/version.js +1 -1
  35. package/dist/version.mjs +1 -1
  36. package/package.json +4 -4
  37. package/src/client.ts +293 -136
  38. package/src/entrypoints/otel.ts +20 -0
  39. package/src/exports.ts +2 -1
  40. package/src/extensions/context/listeners.ts +3 -2
  41. package/src/extensions/context/types.ts +2 -0
  42. package/src/extensions/express.ts +30 -4
  43. package/src/extensions/feature-flags/feature-flags-v2.ts +2086 -0
  44. package/src/extensions/feature-flags/feature-flags.ts +110 -20
  45. package/src/extensions/nestjs.ts +23 -0
  46. package/src/feature-flag-evaluations.ts +8 -6
  47. package/src/flag-events.ts +3 -2
  48. package/src/types.ts +125 -104
  49. package/src/version.ts +1 -1
package/src/client.ts CHANGED
@@ -434,6 +434,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
434
434
  private _captureLogger?: CaptureLogger
435
435
  /** Resolved once on first event; `null` means no service name is configured. */
436
436
  private _serviceName?: string | null
437
+ /** Read once while the client is constructed, so one process release id holds for its lifetime. */
438
+ private readonly _releaseId?: string
437
439
  private _spanContext?: SpanContextManager
438
440
 
439
441
  // Created on first use, so a client that never calls captureAi has no AI lane.
@@ -493,32 +495,43 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
493
495
  }
494
496
 
495
497
  /**
496
- * Initialize a new PostHog client instance.
498
+ * Create a `PostHog` server client (`import { PostHog } from 'posthog-node'`).
499
+ *
500
+ * Keep one client for your server's lifetime and call `await client.shutdown()` on exit. For serverless handlers, reuse a module-scope client and call `await client.flush()`, or pass `waitUntil` in `PostHogOptions`.
501
+ *
502
+ * Passing an empty `apiKey` or a `phx_...` personal API key logs one error and disables the client (`isDisabled === true`). Passing a `phc_...` project token as `secretKey` throws an `Error`.
503
+ *
504
+ * #### Know what to await
505
+ *
506
+ * | Call | Methods | Reach for it when |
507
+ * | --- | --- | --- |
508
+ * | Don't `await` | `capture`, `captureAi`, `identify`, `alias`, `groupIdentify`, `setPersonProperties`, `unsetPersonProperties`, `captureException`, `captureLog`, `logger.*` | Queueing telemetry in memory on the request path without waiting on HTTP |
509
+ * | `await` | `captureImmediate`, `captureAiImmediate`, `identifyImmediate`, `aliasImmediate`, `groupIdentifyImmediate`, `captureExceptionImmediate` | Waiting for an upload attempt to finish before a short-lived handler exits |
510
+ * | `await` | `evaluateFlags`, `getFeatureFlagResult`, `getAllFlags`, `getAllFlagsAndPayloads`, `getRemoteConfigPayload`, `flush`, `shutdown`, `reloadFeatureFlags`, `waitForLocalEvaluationReady` | Reading flags, remote config, or draining queues |
511
+ * | `await` (`{ data, error }`) | `emails.send`, `emails.get`, `emails.setPreferences` | Sending transactional email or updating preferences (never rejects) |
497
512
  *
498
513
  * @example
499
514
  * ```ts
500
515
  * // Basic initialization
501
- * const client = new PostHogBackendClient(
502
- * 'your-api-key',
503
- * { host: 'https://app.posthog.com' }
504
- * )
516
+ * import { PostHog } from 'posthog-node'
517
+ *
518
+ * const client = new PostHog('<ph_project_api_key>', {
519
+ * host: 'https://us.i.posthog.com',
520
+ * })
505
521
  * ```
506
522
  *
507
523
  * @example
508
524
  * ```ts
509
- * // With a secret key (Personal API Key or Project Secret API Key) for local evaluation
510
- * const client = new PostHogBackendClient(
511
- * 'your-api-key',
512
- * {
513
- * host: 'https://app.posthog.com',
514
- * secretKey: 'your-secret-key'
515
- * }
516
- * )
525
+ * // With a secret key (Project Secret API Key or Personal API Key) for local evaluation and emails
526
+ * const client = new PostHog('<ph_project_api_key>', {
527
+ * host: 'https://us.i.posthog.com',
528
+ * secretKey: 'phs_...',
529
+ * })
517
530
  * ```
518
531
  *
519
532
  * {@label Initialization}
520
533
  *
521
- * @param apiKey - Your PostHog project API key
534
+ * @param apiKey - Your PostHog project API key (`phc_...`)
522
535
  * @param options - Configuration options for the client
523
536
  */
524
537
  constructor(apiKey: string, options: PostHogOptions = {}) {
@@ -603,6 +616,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
603
616
  }
604
617
  }
605
618
 
619
+ this._releaseId = CoreErrorTracking.getInjectedReleaseId()
606
620
  this.errorTracking = new ErrorTracking(this, normalizedOptions, this._logger)
607
621
  this._distinctIdHasSentFlagCalls = new Map()
608
622
  this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE
@@ -1161,18 +1175,12 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1161
1175
  }
1162
1176
 
1163
1177
  /**
1164
- * The `posthog.emails` API: sends transactional email from PostHog email templates, reads
1165
- * the status of each email it sent, and sets a recipient's topic preferences.
1166
- *
1167
- * Needs `secretKey`, a project secret API key. `send` needs the `transactional_email:write` scope
1168
- * (the "Send transactional email" preset), and `get` needs `transactional_email:read` or
1169
- * `transactional_email:write`. `setPreferences` needs the
1170
- * `messaging_preference:write` scope, which cannot send email. Keys made with `hog_flow:write` still
1171
- * work for all three. Requests go to `appHost`, or to the PostHog Cloud app host of `host`. `send`,
1172
- * `get` and `setPreferences` resolve to `{ data, error }` and do not reject.
1173
- * `data.id` is the queued email's message ID, which `get` takes. A disabled client sends nothing
1174
- * and returns the error `client_disabled`. After `shutdown()`, the client sends nothing and
1175
- * returns the error `client_closed`.
1178
+ * Send transactional email from PostHog templates or inline code, read send status, and update topic preferences.
1179
+ *
1180
+ * - **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.
1181
+ * - **Routing and retries.** Requests go to `appHost`, or the PostHog Cloud app host for `host`. Configure `emailRequestTimeoutMs` and `emailRequestMaxRetries` per client.
1182
+ * - **Result handling.** `send`, `get`, and `setPreferences` resolve to `{ data, error }` and never reject. `data.id` is the queued email's ID for `get`.
1183
+ * - **Lifecycle.** A disabled client returns `client_disabled`, and a shut-down client returns `client_closed`.
1176
1184
  *
1177
1185
  * @example
1178
1186
  * ```ts
@@ -1441,8 +1449,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1441
1449
  /**
1442
1450
  * The properties the SDK adds to an event: `$is_server` (unless the `isServer` option is
1443
1451
  * `false`), `$geoip_disable` (when the `disableGeoip` option is on), feature flag properties,
1444
- * and for `$exception` events the active OpenTelemetry trace ids and the injected release id.
1445
- * They fill only the keys every other layer left unset.
1452
+ * the release id when one is configured, and for `$exception` events the active OpenTelemetry
1453
+ * trace ids. They fill only the keys every other layer left unset.
1446
1454
  */
1447
1455
  private async _sdkEventProperties(
1448
1456
  event: string,
@@ -1460,15 +1468,14 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1460
1468
  if (this.options.disableGeoip ?? true) {
1461
1469
  sdkProperties.$geoip_disable = true
1462
1470
  }
1471
+ if (this._releaseId) {
1472
+ sdkProperties.$release_id = this._releaseId
1473
+ }
1463
1474
  if (event === '$exception') {
1464
1475
  // Both ids or neither, so a trace id is never paired with another trace's span id.
1465
1476
  if (isUnsetProperty(properties, '$trace_id') && isUnsetProperty(properties, '$span_id')) {
1466
1477
  Object.assign(sdkProperties, await getActiveTraceProperties())
1467
1478
  }
1468
- const releaseId = CoreErrorTracking.getInjectedReleaseId()
1469
- if (releaseId) {
1470
- sdkProperties.$release_id = releaseId
1471
- }
1472
1479
  }
1473
1480
  return sdkProperties
1474
1481
  }
@@ -1580,6 +1587,96 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1580
1587
  this.featureFlagsPoller?.debug(enabled)
1581
1588
  }
1582
1589
 
1590
+ /**
1591
+ * Checks whether the client is disabled from capturing events.
1592
+ *
1593
+ * {@label Privacy}
1594
+ *
1595
+ * @example
1596
+ * ```ts
1597
+ * if (!client.isDisabled) {
1598
+ * client.capture({ distinctId: 'user_123', event: 'page_viewed' })
1599
+ * }
1600
+ * ```
1601
+ *
1602
+ * @returns `true` when capture and network requests are disabled
1603
+ */
1604
+ override get isDisabled(): boolean {
1605
+ return super.isDisabled
1606
+ }
1607
+
1608
+ /**
1609
+ * Checks whether debug logging is enabled on this client.
1610
+ *
1611
+ * {@label Initialization}
1612
+ *
1613
+ * @example
1614
+ * ```ts
1615
+ * if (client.isDebug) {
1616
+ * console.log('PostHog debug logging is active')
1617
+ * }
1618
+ * ```
1619
+ *
1620
+ * @returns `true` when debug logging is active
1621
+ */
1622
+ override get isDebug(): boolean {
1623
+ return super.isDebug
1624
+ }
1625
+
1626
+ /**
1627
+ * Checks whether the client is currently opted out.
1628
+ *
1629
+ * {@label Privacy}
1630
+ *
1631
+ * @example
1632
+ * ```ts
1633
+ * if (client.optedOut) {
1634
+ * console.log('Capture is paused for this client')
1635
+ * }
1636
+ * ```
1637
+ *
1638
+ * @returns `true` when the client is opted out
1639
+ */
1640
+ override get optedOut(): boolean {
1641
+ return super.optedOut
1642
+ }
1643
+
1644
+ /**
1645
+ * Opts the client in so it resumes capturing events.
1646
+ *
1647
+ * Equivalent to `enable()`.
1648
+ *
1649
+ * {@label Privacy}
1650
+ *
1651
+ * @example
1652
+ * ```ts
1653
+ * await client.optIn()
1654
+ * ```
1655
+ *
1656
+ * @returns Promise that resolves when the client opts back in
1657
+ */
1658
+ override optIn(): Promise<void> {
1659
+ return super.optIn()
1660
+ }
1661
+
1662
+ /**
1663
+ * Opts the client out so it stops capturing events.
1664
+ *
1665
+ * Equivalent to `disable()`.
1666
+ *
1667
+ * {@label Privacy}
1668
+ *
1669
+ * @example
1670
+ * ```ts
1671
+ * await client.optOut()
1672
+ * ```
1673
+ *
1674
+ * @returns Promise that resolves when the client opts out
1675
+ */
1676
+ override optOut(): Promise<void> {
1677
+ return super.optOut()
1678
+ }
1679
+
1583
1680
  protected describeDebugPayload(payload: unknown): unknown {
1584
1681
  return summarizeForDebugLog(payload)
1585
1682
  }
@@ -1688,21 +1785,42 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1688
1785
  }
1689
1786
 
1690
1787
  /**
1691
- * Capture an event manually.
1788
+ * Queue an event in memory to send asynchronously without blocking the caller.
1789
+ *
1790
+ * Events with a `distinctId` (explicit or from `withContext()`) create or update person profiles by default unless `options.process_person_profile` is `false` on the call, in `withContext()`, or via `registerOptions()`. Pass `$set` and `$set_once` inside `properties` to set person properties, pass `groups` (such as `{ company: 'acme' }`) to link groups, or send `event: '$pageview'` with `$current_url` for backend-only pageviews.
1791
+ *
1792
+ * Omitting `distinctId` outside an identified context generates a UUIDv7 and sends a personless event (`options: { process_person_profile: false }`). Pass `options: { process_person_profile: false }` to send a personless event for a known `distinctId`.
1793
+ *
1794
+ * Pass `flags` from `evaluateFlags()` to attach evaluated flags without extra requests. Use `captureException()` instead of `capture({ event: '$exception' })`, and don't mix `capture()` with `captureImmediate()` when event order matters.
1692
1795
  *
1693
1796
  * @example
1694
1797
  * ```ts
1695
- * // Basic capture
1798
+ * // Basic capture with person properties and groups
1696
1799
  * client.capture({
1697
1800
  * distinctId: 'user_123',
1698
- * event: 'button_clicked',
1699
- * properties: { button_color: 'red' }
1801
+ * event: 'movie_played',
1802
+ * properties: {
1803
+ * movie_id: '123',
1804
+ * $set: { name: 'Max Hedgehog' },
1805
+ * $set_once: { initial_url: '/blog' },
1806
+ * },
1807
+ * groups: { company: 'acme' },
1808
+ * })
1809
+ * ```
1810
+ *
1811
+ * @example
1812
+ * ```ts
1813
+ * // Personless event for a known user
1814
+ * client.capture({
1815
+ * distinctId: 'user_123',
1816
+ * event: 'background_job',
1817
+ * options: { process_person_profile: false },
1700
1818
  * })
1701
1819
  * ```
1702
1820
  *
1703
1821
  * {@label Capture}
1704
1822
  *
1705
- * @param props - The event properties
1823
+ * @param props - The event payload
1706
1824
  * @returns void
1707
1825
  */
1708
1826
  capture(props: EventMessage): void {
@@ -1715,7 +1833,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1715
1833
  }
1716
1834
 
1717
1835
  /**
1718
- * Capture an event immediately (synchronously).
1836
+ * Send an event immediately and wait for the HTTP send attempt to settle.
1837
+ *
1838
+ * Use in short-lived runtimes where the process can freeze before a background flush. Follows the same `distinctId`, person-profile, `properties`, `groups`, and `flags` rules as `capture()`, and shouldn't be mixed with queued `capture()` calls when order matters.
1719
1839
  *
1720
1840
  * @example
1721
1841
  * ```ts
@@ -1723,39 +1843,35 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1723
1843
  * await client.captureImmediate({
1724
1844
  * distinctId: 'user_123',
1725
1845
  * event: 'button_clicked',
1726
- * properties: { button_color: 'red' }
1846
+ * properties: { button_color: 'red' },
1727
1847
  * })
1728
1848
  * ```
1729
1849
  *
1730
1850
  * @example
1731
1851
  * ```ts
1732
- * // With feature flags
1852
+ * // With an evaluated flags snapshot
1853
+ * const flags = await client.evaluateFlags('user_123')
1733
1854
  * await client.captureImmediate({
1734
1855
  * distinctId: 'user_123',
1735
1856
  * event: 'user_action',
1736
- * sendFeatureFlags: true
1857
+ * flags,
1737
1858
  * })
1738
1859
  * ```
1739
1860
  *
1740
1861
  * @example
1741
1862
  * ```ts
1742
- * // With custom feature flags options
1863
+ * // Personless immediate capture
1743
1864
  * await client.captureImmediate({
1744
1865
  * distinctId: 'user_123',
1745
- * event: 'user_action',
1746
- * sendFeatureFlags: {
1747
- * onlyEvaluateLocally: true,
1748
- * personProperties: { plan: 'premium' },
1749
- * groupProperties: { org: { tier: 'enterprise' } },
1750
- * flagKeys: ['flag1', 'flag2']
1751
- * }
1866
+ * event: 'webhook_received',
1867
+ * options: { process_person_profile: false },
1752
1868
  * })
1753
1869
  * ```
1754
1870
  *
1755
1871
  * {@label Capture}
1756
1872
  *
1757
- * @param props - The event properties
1758
- * @returns Promise that resolves when the event is captured
1873
+ * @param props - The event payload
1874
+ * @returns Promise that resolves when the send attempt completes
1759
1875
  */
1760
1876
  async captureImmediate(props: EventMessage): Promise<void> {
1761
1877
  this._warnIfInvalidCapture(
@@ -1814,7 +1930,11 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1814
1930
  }
1815
1931
 
1816
1932
  /**
1817
- * Identify a user and set their properties.
1933
+ * Queue an `$identify` event setting person properties for `distinctId`.
1934
+ *
1935
+ * Use the same `distinctId` your frontend passes to `posthog.identify()` so server events, session replays, error tracking, and traces link to one person. Server `identify()` holds no ambient anonymous ID and only merges one when `$anon_distinct_id` is passed in `properties`.
1936
+ *
1937
+ * Prefer `$set` or `$set_once` on `capture()` (or `setPersonProperties()`) when you only need to update properties without linking an anonymous ID.
1818
1938
  *
1819
1939
  * @example
1820
1940
  * ```ts
@@ -1824,27 +1944,27 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1824
1944
  * properties: {
1825
1945
  * name: 'John Doe',
1826
1946
  * email: 'john@example.com',
1827
- * plan: 'premium'
1828
- * }
1947
+ * plan: 'premium',
1948
+ * },
1829
1949
  * })
1830
1950
  * ```
1831
1951
  *
1832
1952
  * @example
1833
1953
  * ```ts
1834
- * // Using $set and $set_once
1954
+ * // Using $set, $set_once, and $anon_distinct_id
1835
1955
  * client.identify({
1836
1956
  * distinctId: 'user_123',
1837
1957
  * properties: {
1838
1958
  * $set: { name: 'John Doe', email: 'john@example.com' },
1839
1959
  * $set_once: { first_login: new Date().toISOString() },
1840
- * $anon_distinct_id: 'anonymous_user_456'
1841
- * }
1960
+ * $anon_distinct_id: 'anonymous_user_456',
1961
+ * },
1842
1962
  * })
1843
1963
  * ```
1844
1964
  *
1845
1965
  * {@label Identification}
1846
1966
  *
1847
- * @param data - The identify data containing distinctId and properties
1967
+ * @param data - The identify payload containing `distinctId` and `properties`
1848
1968
  */
1849
1969
  identify({ distinctId, properties = {}, disableGeoip, options }: IdentifyMessage): void {
1850
1970
  const eventProperties = identifyEventProperties(properties)
@@ -1856,7 +1976,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1856
1976
  }
1857
1977
 
1858
1978
  /**
1859
- * Identify a user and set their properties immediately (synchronously).
1979
+ * Send an `$identify` event immediately and wait for the HTTP send attempt to settle.
1980
+ *
1981
+ * Use in short-lived runtimes where the process can freeze before a background flush. Follows the same `distinctId` matching and `$anon_distinct_id` rules as `identify()`.
1860
1982
  *
1861
1983
  * @example
1862
1984
  * ```ts
@@ -1865,15 +1987,15 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1865
1987
  * distinctId: 'user_123',
1866
1988
  * properties: {
1867
1989
  * name: 'John Doe',
1868
- * email: 'john@example.com'
1869
- * }
1990
+ * email: 'john@example.com',
1991
+ * },
1870
1992
  * })
1871
1993
  * ```
1872
1994
  *
1873
1995
  * {@label Identification}
1874
1996
  *
1875
- * @param data - The identify data containing distinctId and properties
1876
- * @returns Promise that resolves when the identify is processed
1997
+ * @param data - The identify payload containing `distinctId` and `properties`
1998
+ * @returns Promise that resolves when the identify call settles
1877
1999
  */
1878
2000
  async identifyImmediate({ distinctId, properties = {}, disableGeoip, options }: IdentifyMessage): Promise<void> {
1879
2001
  const eventProperties = identifyEventProperties(properties)
@@ -1885,20 +2007,22 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1885
2007
  }
1886
2008
 
1887
2009
  /**
1888
- * Set properties on a person profile.
2010
+ * Queue a `$set` event to set or set-once properties on a person profile.
2011
+ *
2012
+ * Falls back to `withContext()` when `distinctId` is blank, and no-ops when both `properties` and `propertiesOnce` are empty.
1889
2013
  *
1890
2014
  * @example
1891
2015
  * ```ts
1892
2016
  * client.setPersonProperties({
1893
2017
  * distinctId: 'user_123',
1894
2018
  * properties: { plan: 'premium' },
1895
- * propertiesOnce: { first_seen: '2026-06-15' }
2019
+ * propertiesOnce: { first_seen: '2026-06-15' },
1896
2020
  * })
1897
2021
  * ```
1898
2022
  *
1899
2023
  * {@label Identification}
1900
2024
  *
1901
- * @param data - The data containing distinctId and properties to set
2025
+ * @param data - Distinct ID and person properties to set
1902
2026
  */
1903
2027
  setPersonProperties({ distinctId, properties = {}, propertiesOnce = {}, options }: SetPersonPropertiesMessage): void {
1904
2028
  if (Object.keys(properties).length === 0 && Object.keys(propertiesOnce).length === 0) {
@@ -1922,19 +2046,21 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1922
2046
  }
1923
2047
 
1924
2048
  /**
1925
- * Remove properties from a person profile.
2049
+ * Queue a `$set` event carrying `$unset` to remove properties from a person profile.
2050
+ *
2051
+ * Falls back to `withContext()` when `distinctId` is blank, and no-ops when `properties` is empty.
1926
2052
  *
1927
2053
  * @example
1928
2054
  * ```ts
1929
2055
  * client.unsetPersonProperties({
1930
2056
  * distinctId: 'user_123',
1931
- * properties: ['plan', 'email']
2057
+ * properties: ['plan', 'email'],
1932
2058
  * })
1933
2059
  * ```
1934
2060
  *
1935
2061
  * {@label Identification}
1936
2062
  *
1937
- * @param data - The data containing distinctId and property names to unset
2063
+ * @param data - Distinct ID and property names to unset
1938
2064
  */
1939
2065
  unsetPersonProperties({ distinctId, properties, options }: UnsetPersonPropertiesMessage): void {
1940
2066
  const propertyNames = normalizeUnsetPersonProperties(properties)
@@ -1946,20 +2072,22 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1946
2072
  }
1947
2073
 
1948
2074
  /**
1949
- * Create an alias to link two distinct IDs together.
2075
+ * Queue a `$create_alias` event linking `alias` (the previous or secondary ID) to `distinctId` (the primary user ID).
2076
+ *
2077
+ * `distinctId` falls back to `withContext()` when blank, while `alias` never reads from context or `register()`. Never alias to shared placeholder values such as `'anonymous'` or `'null'`. Frontend `posthog.identify()` already links anonymous users, so backend `alias()` is mainly for backend-only flows.
1950
2078
  *
1951
2079
  * @example
1952
2080
  * ```ts
1953
- * // Link an anonymous user to an identified user
2081
+ * // Link an anonymous user ID to a primary user ID
1954
2082
  * client.alias({
1955
- * distinctId: 'anonymous_123',
1956
- * alias: 'user_456'
2083
+ * distinctId: 'user_456',
2084
+ * alias: 'anonymous_123',
1957
2085
  * })
1958
2086
  * ```
1959
2087
  *
1960
2088
  * {@label Identification}
1961
2089
  *
1962
- * @param data - The alias data containing distinctId and alias
2090
+ * @param data - Primary `distinctId`, previous `alias`, and optional flags or options
1963
2091
  */
1964
2092
  alias(data: { distinctId: string; alias: string; disableGeoip?: boolean; options?: EventOptions }): void {
1965
2093
  this._sendPreparedEvent(
@@ -1977,21 +2105,23 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1977
2105
  }
1978
2106
 
1979
2107
  /**
1980
- * Create an alias to link two distinct IDs together immediately (synchronously).
2108
+ * Send a `$create_alias` event immediately to link `alias` to `distinctId`.
2109
+ *
2110
+ * Follows the same ID precedence and placeholder warnings as `alias()`. Use in short-lived runtimes where the process can freeze before a background flush.
1981
2111
  *
1982
2112
  * @example
1983
2113
  * ```ts
1984
- * // Link an anonymous user to an identified user immediately
2114
+ * // Link an anonymous user ID to a primary user ID immediately
1985
2115
  * await client.aliasImmediate({
1986
- * distinctId: 'anonymous_123',
1987
- * alias: 'user_456'
2116
+ * distinctId: 'user_456',
2117
+ * alias: 'anonymous_123',
1988
2118
  * })
1989
2119
  * ```
1990
2120
  *
1991
2121
  * {@label Identification}
1992
2122
  *
1993
- * @param data - The alias data containing distinctId and alias
1994
- * @returns Promise that resolves when the alias is processed
2123
+ * @param data - Primary `distinctId`, previous `alias`, and optional flags or options
2124
+ * @returns Promise that resolves when the alias call settles
1995
2125
  */
1996
2126
  async aliasImmediate(data: {
1997
2127
  distinctId: string
@@ -2018,26 +2148,22 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2018
2148
  *
2019
2149
  * @example
2020
2150
  * ```ts
2021
- * // Check if ready
2151
+ * // Check if ready before evaluating
2022
2152
  * if (client.isLocalEvaluationReady()) {
2023
- * // Local evaluation is ready, can evaluate flags locally
2024
- * const flag = await client.getFeatureFlag('flag-key', 'user_123')
2153
+ * const flags = await client.evaluateFlags('user_123', { onlyEvaluateLocally: true })
2154
+ * const value = flags.getFlag('flag-key')
2025
2155
  * } else {
2026
- * // Local evaluation not ready, will use remote evaluation
2027
- * const flag = await client.getFeatureFlag('flag-key', 'user_123')
2156
+ * const flags = await client.evaluateFlags('user_123')
2157
+ * const value = flags.getFlag('flag-key')
2028
2158
  * }
2029
2159
  * ```
2030
2160
  *
2031
2161
  * @remarks
2032
- * Readiness requires at least one loaded flag definition. A successful load that returns no
2033
- * flags (for example, after every flag is deleted) does not count as ready, and readiness
2034
- * returns to `false` if a later load returns no flags. To react to every successful load,
2035
- * including empty ones, listen for the `localEvaluationFlagsLoaded` event, which reports the
2036
- * number of loaded flags.
2162
+ * Readiness requires at least one loaded flag definition. A successful load that returns no flags (for example, after every flag is deleted) doesn't count as ready, and readiness returns to `false` if a later load returns no flags. To react to every successful load, including empty ones, listen for the `localEvaluationFlagsLoaded` event, which reports the number of loaded flags.
2037
2163
  *
2038
2164
  * {@label Feature flags}
2039
2165
  *
2040
- * @returns true if flag definitions have loaded successfully and include at least one flag, false otherwise
2166
+ * @returns `true` if flag definitions have loaded and include at least one flag, `false` otherwise
2041
2167
  */
2042
2168
  isLocalEvaluationReady(): boolean {
2043
2169
  return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false
@@ -2118,10 +2244,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2118
2244
  *
2119
2245
  * {@label Feature flags}
2120
2246
  *
2121
- * @param timeoutMs - Timeout in milliseconds (default: 30000)
2247
+ * @param timeoutMs - Timeout in milliseconds
2122
2248
  * @returns Promise that resolves to true if ready, false if timed out or if the next load returned no flags
2123
2249
  */
2124
- async waitForLocalEvaluationReady(timeoutMs: number = THIRTY_SECONDS): Promise<boolean> {
2250
+ async waitForLocalEvaluationReady(timeoutMs: number = 30000): Promise<boolean> {
2125
2251
  if (this.isLocalEvaluationReady()) {
2126
2252
  return true
2127
2253
  }
@@ -2292,6 +2418,14 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2292
2418
  reason: flagReason,
2293
2419
  reasonCode: flag.active === false ? 'flag_disabled' : undefined,
2294
2420
  }
2421
+ if (localResult.record !== undefined) {
2422
+ // A config version 2 flag: its record is read, and its events built, as a remote one.
2423
+ flagRecord = localResult.record.record
2424
+ flagId = flagRecord.metadata.id
2425
+ flagVersion = flagRecord.metadata.version
2426
+ flagHasExperiment = flagRecord.metadata.hasExperiment
2427
+ result.reasonCode = flagRecord.reason?.code
2428
+ }
2295
2429
  }
2296
2430
  } catch (e) {
2297
2431
  if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) {
@@ -2684,7 +2818,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2684
2818
  * - `undefined`, when the flag has no payload, or the request failed. A response with a status
2685
2819
  * outside 200 to 299 emits a `RemoteConfigPayloadError` carrying the `statusCode` and `flagKey` on the
2686
2820
  * client's `error` event; a network error, a timeout or an unreadable body emits the underlying error there.
2687
- * @throws Error if personal API key is not provided
2821
+ * @throws Error if neither `secretKey` nor `personalApiKey` is configured. Set `enableLocalEvaluation: false` when `secretKey` is only for remote config or email.
2688
2822
  */
2689
2823
  async getRemoteConfigPayload(flagKey: string): Promise<JsonType | undefined> {
2690
2824
  if (this.disabled) {
@@ -3006,7 +3140,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3006
3140
  *
3007
3141
  * **Exposure events.** `isEnabled()` and `getFlag()` send a `$feature_flag_called` event the
3008
3142
  * first time each flag value is read for a user. Experiments use these events as exposures.
3009
- * When a remotely evaluated config version 2 flag assigns an experiment variant, the read also
3143
+ * When a config version 2 flag assigns an experiment variant, locally or remotely, the read also
3010
3144
  * sends `$experiment_exposure`, once per user, groups, flag, rule and variant.
3011
3145
  * The client's `sendFeatureFlagEvent` option sets the default for these reads. Pass
3012
3146
  * `{ sendFeatureFlagEvents: true }` or `{ sendFeatureFlagEvents: false }` to a read to override
@@ -3145,18 +3279,22 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3145
3279
  if (localResult) {
3146
3280
  for (const [key, value] of Object.entries(localResult.response)) {
3147
3281
  const flagDef = this.featureFlagsPoller?.featureFlagsByKey[key]
3282
+ // A config version 2 flag has the record a /flags?v=4 response gives, which supplies its
3283
+ // id, version, experiment link and flag events.
3284
+ const parsed = localResult.records[key]?.record
3148
3285
  records[key] = {
3149
3286
  key,
3150
3287
  enabled: value !== false,
3151
3288
  variant: typeof value === 'string' ? value : undefined,
3152
3289
  payload: localResult.payloads[key],
3153
- id: flagDef?.id,
3154
- // The local-evaluation flag definition (`PostHogFeatureFlag`) does not carry a
3155
- // version field; only the remote `/flags` response does via `metadata.version`.
3156
- version: undefined,
3290
+ id: parsed !== undefined ? parsed.metadata.id : flagDef?.id,
3291
+ // The version 1 local-evaluation definition is read without a version field; only the
3292
+ // remote `/flags` response and a config version 2 record carry `metadata.version`.
3293
+ version: parsed?.metadata.version,
3157
3294
  reason: 'Evaluated locally',
3158
3295
  locallyEvaluated: true,
3159
- hasExperiment: flagDef?.has_experiment,
3296
+ hasExperiment: parsed !== undefined ? parsed.metadata.hasExperiment : flagDef?.has_experiment,
3297
+ ...(parsed !== undefined ? { parsed } : {}),
3160
3298
  }
3161
3299
  locallyEvaluatedKeys.add(key)
3162
3300
  }
@@ -3460,39 +3598,41 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3460
3598
  }
3461
3599
 
3462
3600
  /**
3463
- * Create or update a group and its properties.
3601
+ * Queue a `$groupidentify` event to create or update a group and its properties (requires Group Analytics).
3602
+ *
3603
+ * Projects support up to 5 group types. Set `name` in `properties` for the group's display name in PostHog, otherwise PostHog shows `groupKey`. When `distinctId` is omitted outside `withContext()`, it falls back to `$<groupType>_<groupKey>`. Group identify events don't inherit context `sessionId`. Pass `groups` on `capture()` and `evaluateFlags()` to link events and flags to the group.
3464
3604
  *
3465
3605
  * @example
3466
3606
  * ```ts
3467
- * // Create a company group
3607
+ * // Create or update a company group
3468
3608
  * client.groupIdentify({
3469
3609
  * groupType: 'company',
3470
3610
  * groupKey: 'acme-corp',
3471
3611
  * properties: {
3472
3612
  * name: 'Acme Corporation',
3473
3613
  * industry: 'Technology',
3474
- * employee_count: 500
3614
+ * employee_count: 500,
3475
3615
  * },
3476
- * distinctId: 'user_123'
3616
+ * distinctId: 'user_123',
3477
3617
  * })
3478
3618
  * ```
3479
3619
  *
3480
3620
  * @example
3481
3621
  * ```ts
3482
- * // Update organization properties
3622
+ * // Update organization properties using fallback distinctId ($organization_org-456)
3483
3623
  * client.groupIdentify({
3484
3624
  * groupType: 'organization',
3485
3625
  * groupKey: 'org-456',
3486
3626
  * properties: {
3487
3627
  * plan: 'enterprise',
3488
- * region: 'US-West'
3489
- * }
3628
+ * region: 'US-West',
3629
+ * },
3490
3630
  * })
3491
3631
  * ```
3492
3632
  *
3493
3633
  * {@label Identification}
3494
3634
  *
3495
- * @param data - The group identify data
3635
+ * @param data - Group identify payload
3496
3636
  */
3497
3637
  groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip, options }: GroupIdentifyMessage): void {
3498
3638
  this._sendPreparedEvent(
@@ -3514,7 +3654,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3514
3654
  }
3515
3655
 
3516
3656
  /**
3517
- * Create or update a group and its properties immediately (synchronously).
3657
+ * Send a `$groupidentify` event immediately and wait for the HTTP send attempt to settle.
3658
+ *
3659
+ * Follows the same `name` property, `distinctId` fallback (`$<groupType>_<groupKey>`), and `groups` linking rules as `groupIdentify()`. Use in short-lived runtimes where the process can freeze before a background flush.
3518
3660
  *
3519
3661
  * @example
3520
3662
  * ```ts
@@ -3525,15 +3667,15 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3525
3667
  * properties: {
3526
3668
  * name: 'Acme Corporation',
3527
3669
  * industry: 'Technology',
3528
- * employee_count: 500
3529
- * }
3670
+ * employee_count: 500,
3671
+ * },
3530
3672
  * })
3531
3673
  * ```
3532
3674
  *
3533
3675
  * {@label Identification}
3534
3676
  *
3535
- * @param data - The group identify data
3536
- * @returns Promise that resolves when the group identify is processed
3677
+ * @param data - Group identify payload
3678
+ * @returns Promise that resolves when the group identify call settles
3537
3679
  */
3538
3680
  async groupIdentifyImmediate({
3539
3681
  groupType,
@@ -3573,9 +3715,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3573
3715
  *
3574
3716
  * @example
3575
3717
  * ```ts
3576
- * // Reload before checking a specific flag
3718
+ * // Reload before evaluating flags
3577
3719
  * await client.reloadFeatureFlags()
3578
- * const flag = await client.getFeatureFlag('flag-key', 'user_123')
3720
+ * const flags = await client.evaluateFlags('user_123')
3721
+ * const value = flags.getFlag('flag-key')
3579
3722
  * ```
3580
3723
  *
3581
3724
  * {@label Feature flags}
@@ -3779,19 +3922,18 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3779
3922
  protected abstract initializeContext(): IPostHogContext | undefined
3780
3923
 
3781
3924
  /**
3782
- * Run a function with specific context that will be applied to all events captured within that context.
3783
- * It propagates the context to all subsequent calls down the call stack.
3784
- * Context properties like tags and sessionId will be automatically attached to all events.
3785
- * By default, nested contexts inherit from parent contexts. Use `{ fresh: true }` to start with a clean context.
3925
+ * Run a function with request-scoped context using `AsyncLocalStorage` so state propagates down function calls and `await`.
3926
+ *
3927
+ * By default, nested contexts inherit parent state while overriding keys locally without mutating the parent. Pass `{ fresh: true }` at request or job boundaries to clear inherited state, and pass `{ signal }` to end a context when an `AbortSignal` aborts.
3928
+ *
3929
+ * Events and exceptions inherit `distinctId`, `sessionId` (`$session_id`, except `groupIdentify()`), `properties`, and `options`. `evaluateFlags()`, `getAllFlags()`, `getAllFlagsAndPayloads()`, and `getFeatureFlagResult()` read `distinctId` when omitted. Logs and spans inherit `distinctId` and `sessionId`. Pass a UUIDv7 `sessionId` (such as `x-posthog-session-id` from `posthog-js`) to link backend telemetry to Session Replay.
3930
+ *
3931
+ * On `posthog-node/edge`, `withContext()` runs `fn` directly without `AsyncLocalStorage`, so nested calls won't see context data.
3786
3932
  *
3787
3933
  * @remarks
3788
- * Context `properties` and `options` fill only what an event left unset: the event's own values
3789
- * win, and context values beat `register()` and `registerOptions()` values and the values the SDK
3790
- * adds. `beforeSend` sees the result and can change it.
3934
+ * Context `properties` and `options` fill only what an event left unset: the event's own values win, and context values beat `register()`, `registerOptions()`, and SDK defaults. `beforeSend` sees the result and can change it.
3791
3935
  *
3792
- * On `$identify`, `$create_alias`, `$merge_dangerously`, `$groupidentify`, `$set` and `$set_once`
3793
- * events, a context `process_person_profile` option applies only when the distinct id is
3794
- * generated, and a `$process_person_profile` property never applies (see `registerOptions()`).
3936
+ * On `$identify`, `$create_alias`, `$merge_dangerously`, `$groupidentify`, `$set`, and `$set_once` events, a context `process_person_profile` option applies only when the distinct ID is generated, and a `$process_person_profile` property never applies (see `registerOptions()`).
3795
3937
  *
3796
3938
  * @example
3797
3939
  * ```ts
@@ -3802,9 +3944,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3802
3944
  *
3803
3945
  * {@label Context}
3804
3946
  *
3805
- * @param data - Context data to apply (sessionId, distinctId, properties, options)
3947
+ * @param data - Context data to apply (`sessionId`, `distinctId`, `properties`, `options`)
3806
3948
  * @param fn - Function to run with the context
3807
- * @param options - Context options (fresh: true to start with clean context instead of inheriting)
3949
+ * @param options - Context options (`fresh: true` to clear inherited state, `signal` to expire on abort)
3808
3950
  * @returns The return value of the function
3809
3951
  */
3810
3952
  withContext<T>(data: Partial<ContextData>, fn: () => T, options?: ContextOptions): T {
@@ -3824,7 +3966,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3824
3966
  }
3825
3967
 
3826
3968
  /**
3827
- * Get the current context data.
3969
+ * Read the active `withContext()` data, or `undefined` outside a context (and always `undefined` on `posthog-node/edge`).
3828
3970
  *
3829
3971
  * @example
3830
3972
  * ```ts
@@ -3837,31 +3979,46 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3837
3979
  *
3838
3980
  * {@label Context}
3839
3981
  *
3840
- * @returns The current context data, or undefined if no context is set
3982
+ * @returns The current context data, or `undefined` if no context is active
3841
3983
  */
3842
3984
  getContext(): ContextData | undefined {
3843
3985
  return this.context?.get()
3844
3986
  }
3845
3987
 
3846
3988
  /**
3847
- * Shutdown the PostHog client gracefully.
3989
+ * Shuts down the client, drains pending queues, and flushes queued telemetry before exit.
3990
+ *
3991
+ * Call `shutdown()` once on process exit. Use `flush()` when you'll keep reusing the client.
3992
+ *
3993
+ * - **What it stops and drains.** Halts flag polling, calls `flagDefinitionCacheProvider.shutdown()`, and drains analytics events, AI events, logs, metrics, and ended spans.
3994
+ * - **Shared timeout budget.** Analytics queues and OTel signal flushing share `shutdownTimeoutMs`. Open spans that haven't ended are discarded.
3995
+ * - **Delivery vs. ingestion.** Resolving confirms the client tried to drain within `shutdownTimeoutMs`, not that PostHog ingested every event.
3848
3996
  *
3849
3997
  * @example
3850
3998
  * ```ts
3851
- * // Shutdown with default timeout
3852
- * await client._shutdown()
3999
+ * await client.shutdown()
3853
4000
  * ```
3854
4001
  *
3855
4002
  * @example
3856
4003
  * ```ts
3857
- * // Shutdown with custom timeout
3858
- * await client._shutdown(5000) // 5 seconds
4004
+ * // Shutdown with a 5-second timeout
4005
+ * await client.shutdown(5000)
3859
4006
  * ```
3860
4007
  *
3861
4008
  * {@label Shutdown}
3862
4009
  *
3863
- * @param shutdownTimeoutMs - Timeout in milliseconds for shutdown
3864
- * @returns Promise that resolves when shutdown is complete
4010
+ * @param shutdownTimeoutMs - Maximum wait in milliseconds, defaulting to `30000`
4011
+ * @returns Promise that resolves when shutdown finishes or hits `shutdownTimeoutMs`
4012
+ */
4013
+ override shutdown(shutdownTimeoutMs: number = 30000): Promise<void> {
4014
+ return super.shutdown(shutdownTimeoutMs)
4015
+ }
4016
+
4017
+ /**
4018
+ * Internal shutdown hook invoked by `shutdown()`.
4019
+ *
4020
+ * @param shutdownTimeoutMs - Maximum wait in milliseconds
4021
+ * @returns Promise that resolves when internal shutdown completes
3865
4022
  */
3866
4023
  async _shutdown(shutdownTimeoutMs?: number): Promise<void> {
3867
4024
  // One absolute deadline for the whole shutdown: the metrics flush race and