posthog-node 6.1.1 → 6.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/client.d.ts +251 -124
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +23 -4
  4. package/dist/client.mjs +23 -4
  5. package/dist/emails/emails.d.ts +2 -1
  6. package/dist/emails/emails.d.ts.map +1 -1
  7. package/dist/emails/emails.js +27 -11
  8. package/dist/emails/emails.mjs +27 -11
  9. package/dist/emails/react-renderer-import.d.ts +3 -0
  10. package/dist/emails/react-renderer-import.d.ts.map +1 -0
  11. package/dist/emails/react-renderer-import.js +50 -0
  12. package/dist/emails/react-renderer-import.mjs +6 -0
  13. package/dist/emails/types.d.ts +15 -1
  14. package/dist/emails/types.d.ts.map +1 -1
  15. package/dist/entrypoints/otel.d.ts +20 -0
  16. package/dist/entrypoints/otel.d.ts.map +1 -1
  17. package/dist/exports.d.ts +3 -2
  18. package/dist/exports.d.ts.map +1 -1
  19. package/dist/extensions/context/listeners.d.ts +3 -2
  20. package/dist/extensions/context/listeners.d.ts.map +1 -1
  21. package/dist/extensions/context/types.d.ts +2 -0
  22. package/dist/extensions/context/types.d.ts.map +1 -1
  23. package/dist/extensions/express.d.ts +30 -4
  24. package/dist/extensions/express.d.ts.map +1 -1
  25. package/dist/extensions/nestjs.d.ts +23 -0
  26. package/dist/extensions/nestjs.d.ts.map +1 -1
  27. package/dist/types.d.ts +133 -96
  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/client.ts +276 -130
  34. package/src/emails/emails.ts +35 -13
  35. package/src/emails/react-renderer-import.ts +7 -0
  36. package/src/emails/types.ts +16 -1
  37. package/src/entrypoints/otel.ts +20 -0
  38. package/src/exports.ts +3 -1
  39. package/src/extensions/context/listeners.ts +3 -2
  40. package/src/extensions/context/types.ts +2 -0
  41. package/src/extensions/express.ts +30 -4
  42. package/src/extensions/nestjs.ts +23 -0
  43. package/src/types.ts +138 -105
  44. 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
@@ -1206,6 +1214,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1206
1214
  requestTimeoutMs: positiveNumberOr(this.options.emailRequestTimeoutMs, DEFAULT_EMAIL_REQUEST_TIMEOUT_MS),
1207
1215
  maxRetries: nonNegativeIntegerOr(this.options.emailRequestMaxRetries, DEFAULT_EMAIL_REQUEST_MAX_RETRIES),
1208
1216
  migratedFrom: this.options.migratedFrom,
1217
+ reactRenderer: this.options.reactEmailRenderer,
1209
1218
  },
1210
1219
  {
1211
1220
  fetch: (url, fetchOptions) => this.fetch(url, fetchOptions),
@@ -1440,8 +1449,8 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1440
1449
  /**
1441
1450
  * The properties the SDK adds to an event: `$is_server` (unless the `isServer` option is
1442
1451
  * `false`), `$geoip_disable` (when the `disableGeoip` option is on), feature flag properties,
1443
- * and for `$exception` events the active OpenTelemetry trace ids and the injected release id.
1444
- * 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.
1445
1454
  */
1446
1455
  private async _sdkEventProperties(
1447
1456
  event: string,
@@ -1459,15 +1468,14 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1459
1468
  if (this.options.disableGeoip ?? true) {
1460
1469
  sdkProperties.$geoip_disable = true
1461
1470
  }
1471
+ if (this._releaseId) {
1472
+ sdkProperties.$release_id = this._releaseId
1473
+ }
1462
1474
  if (event === '$exception') {
1463
1475
  // Both ids or neither, so a trace id is never paired with another trace's span id.
1464
1476
  if (isUnsetProperty(properties, '$trace_id') && isUnsetProperty(properties, '$span_id')) {
1465
1477
  Object.assign(sdkProperties, await getActiveTraceProperties())
1466
1478
  }
1467
- const releaseId = CoreErrorTracking.getInjectedReleaseId()
1468
- if (releaseId) {
1469
- sdkProperties.$release_id = releaseId
1470
- }
1471
1479
  }
1472
1480
  return sdkProperties
1473
1481
  }
@@ -1579,6 +1587,96 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1579
1587
  this.featureFlagsPoller?.debug(enabled)
1580
1588
  }
1581
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
+
1582
1680
  protected describeDebugPayload(payload: unknown): unknown {
1583
1681
  return summarizeForDebugLog(payload)
1584
1682
  }
@@ -1687,21 +1785,42 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1687
1785
  }
1688
1786
 
1689
1787
  /**
1690
- * 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.
1691
1795
  *
1692
1796
  * @example
1693
1797
  * ```ts
1694
- * // Basic capture
1798
+ * // Basic capture with person properties and groups
1695
1799
  * client.capture({
1696
1800
  * distinctId: 'user_123',
1697
- * event: 'button_clicked',
1698
- * 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 },
1699
1818
  * })
1700
1819
  * ```
1701
1820
  *
1702
1821
  * {@label Capture}
1703
1822
  *
1704
- * @param props - The event properties
1823
+ * @param props - The event payload
1705
1824
  * @returns void
1706
1825
  */
1707
1826
  capture(props: EventMessage): void {
@@ -1714,7 +1833,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1714
1833
  }
1715
1834
 
1716
1835
  /**
1717
- * 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.
1718
1839
  *
1719
1840
  * @example
1720
1841
  * ```ts
@@ -1722,39 +1843,35 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1722
1843
  * await client.captureImmediate({
1723
1844
  * distinctId: 'user_123',
1724
1845
  * event: 'button_clicked',
1725
- * properties: { button_color: 'red' }
1846
+ * properties: { button_color: 'red' },
1726
1847
  * })
1727
1848
  * ```
1728
1849
  *
1729
1850
  * @example
1730
1851
  * ```ts
1731
- * // With feature flags
1852
+ * // With an evaluated flags snapshot
1853
+ * const flags = await client.evaluateFlags('user_123')
1732
1854
  * await client.captureImmediate({
1733
1855
  * distinctId: 'user_123',
1734
1856
  * event: 'user_action',
1735
- * sendFeatureFlags: true
1857
+ * flags,
1736
1858
  * })
1737
1859
  * ```
1738
1860
  *
1739
1861
  * @example
1740
1862
  * ```ts
1741
- * // With custom feature flags options
1863
+ * // Personless immediate capture
1742
1864
  * await client.captureImmediate({
1743
1865
  * distinctId: 'user_123',
1744
- * event: 'user_action',
1745
- * sendFeatureFlags: {
1746
- * onlyEvaluateLocally: true,
1747
- * personProperties: { plan: 'premium' },
1748
- * groupProperties: { org: { tier: 'enterprise' } },
1749
- * flagKeys: ['flag1', 'flag2']
1750
- * }
1866
+ * event: 'webhook_received',
1867
+ * options: { process_person_profile: false },
1751
1868
  * })
1752
1869
  * ```
1753
1870
  *
1754
1871
  * {@label Capture}
1755
1872
  *
1756
- * @param props - The event properties
1757
- * @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
1758
1875
  */
1759
1876
  async captureImmediate(props: EventMessage): Promise<void> {
1760
1877
  this._warnIfInvalidCapture(
@@ -1813,7 +1930,11 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1813
1930
  }
1814
1931
 
1815
1932
  /**
1816
- * 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.
1817
1938
  *
1818
1939
  * @example
1819
1940
  * ```ts
@@ -1823,27 +1944,27 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1823
1944
  * properties: {
1824
1945
  * name: 'John Doe',
1825
1946
  * email: 'john@example.com',
1826
- * plan: 'premium'
1827
- * }
1947
+ * plan: 'premium',
1948
+ * },
1828
1949
  * })
1829
1950
  * ```
1830
1951
  *
1831
1952
  * @example
1832
1953
  * ```ts
1833
- * // Using $set and $set_once
1954
+ * // Using $set, $set_once, and $anon_distinct_id
1834
1955
  * client.identify({
1835
1956
  * distinctId: 'user_123',
1836
1957
  * properties: {
1837
1958
  * $set: { name: 'John Doe', email: 'john@example.com' },
1838
1959
  * $set_once: { first_login: new Date().toISOString() },
1839
- * $anon_distinct_id: 'anonymous_user_456'
1840
- * }
1960
+ * $anon_distinct_id: 'anonymous_user_456',
1961
+ * },
1841
1962
  * })
1842
1963
  * ```
1843
1964
  *
1844
1965
  * {@label Identification}
1845
1966
  *
1846
- * @param data - The identify data containing distinctId and properties
1967
+ * @param data - The identify payload containing `distinctId` and `properties`
1847
1968
  */
1848
1969
  identify({ distinctId, properties = {}, disableGeoip, options }: IdentifyMessage): void {
1849
1970
  const eventProperties = identifyEventProperties(properties)
@@ -1855,7 +1976,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1855
1976
  }
1856
1977
 
1857
1978
  /**
1858
- * 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()`.
1859
1982
  *
1860
1983
  * @example
1861
1984
  * ```ts
@@ -1864,15 +1987,15 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1864
1987
  * distinctId: 'user_123',
1865
1988
  * properties: {
1866
1989
  * name: 'John Doe',
1867
- * email: 'john@example.com'
1868
- * }
1990
+ * email: 'john@example.com',
1991
+ * },
1869
1992
  * })
1870
1993
  * ```
1871
1994
  *
1872
1995
  * {@label Identification}
1873
1996
  *
1874
- * @param data - The identify data containing distinctId and properties
1875
- * @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
1876
1999
  */
1877
2000
  async identifyImmediate({ distinctId, properties = {}, disableGeoip, options }: IdentifyMessage): Promise<void> {
1878
2001
  const eventProperties = identifyEventProperties(properties)
@@ -1884,20 +2007,22 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1884
2007
  }
1885
2008
 
1886
2009
  /**
1887
- * 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.
1888
2013
  *
1889
2014
  * @example
1890
2015
  * ```ts
1891
2016
  * client.setPersonProperties({
1892
2017
  * distinctId: 'user_123',
1893
2018
  * properties: { plan: 'premium' },
1894
- * propertiesOnce: { first_seen: '2026-06-15' }
2019
+ * propertiesOnce: { first_seen: '2026-06-15' },
1895
2020
  * })
1896
2021
  * ```
1897
2022
  *
1898
2023
  * {@label Identification}
1899
2024
  *
1900
- * @param data - The data containing distinctId and properties to set
2025
+ * @param data - Distinct ID and person properties to set
1901
2026
  */
1902
2027
  setPersonProperties({ distinctId, properties = {}, propertiesOnce = {}, options }: SetPersonPropertiesMessage): void {
1903
2028
  if (Object.keys(properties).length === 0 && Object.keys(propertiesOnce).length === 0) {
@@ -1921,19 +2046,21 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1921
2046
  }
1922
2047
 
1923
2048
  /**
1924
- * 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.
1925
2052
  *
1926
2053
  * @example
1927
2054
  * ```ts
1928
2055
  * client.unsetPersonProperties({
1929
2056
  * distinctId: 'user_123',
1930
- * properties: ['plan', 'email']
2057
+ * properties: ['plan', 'email'],
1931
2058
  * })
1932
2059
  * ```
1933
2060
  *
1934
2061
  * {@label Identification}
1935
2062
  *
1936
- * @param data - The data containing distinctId and property names to unset
2063
+ * @param data - Distinct ID and property names to unset
1937
2064
  */
1938
2065
  unsetPersonProperties({ distinctId, properties, options }: UnsetPersonPropertiesMessage): void {
1939
2066
  const propertyNames = normalizeUnsetPersonProperties(properties)
@@ -1945,20 +2072,22 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1945
2072
  }
1946
2073
 
1947
2074
  /**
1948
- * 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.
1949
2078
  *
1950
2079
  * @example
1951
2080
  * ```ts
1952
- * // Link an anonymous user to an identified user
2081
+ * // Link an anonymous user ID to a primary user ID
1953
2082
  * client.alias({
1954
- * distinctId: 'anonymous_123',
1955
- * alias: 'user_456'
2083
+ * distinctId: 'user_456',
2084
+ * alias: 'anonymous_123',
1956
2085
  * })
1957
2086
  * ```
1958
2087
  *
1959
2088
  * {@label Identification}
1960
2089
  *
1961
- * @param data - The alias data containing distinctId and alias
2090
+ * @param data - Primary `distinctId`, previous `alias`, and optional flags or options
1962
2091
  */
1963
2092
  alias(data: { distinctId: string; alias: string; disableGeoip?: boolean; options?: EventOptions }): void {
1964
2093
  this._sendPreparedEvent(
@@ -1976,21 +2105,23 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
1976
2105
  }
1977
2106
 
1978
2107
  /**
1979
- * 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.
1980
2111
  *
1981
2112
  * @example
1982
2113
  * ```ts
1983
- * // Link an anonymous user to an identified user immediately
2114
+ * // Link an anonymous user ID to a primary user ID immediately
1984
2115
  * await client.aliasImmediate({
1985
- * distinctId: 'anonymous_123',
1986
- * alias: 'user_456'
2116
+ * distinctId: 'user_456',
2117
+ * alias: 'anonymous_123',
1987
2118
  * })
1988
2119
  * ```
1989
2120
  *
1990
2121
  * {@label Identification}
1991
2122
  *
1992
- * @param data - The alias data containing distinctId and alias
1993
- * @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
1994
2125
  */
1995
2126
  async aliasImmediate(data: {
1996
2127
  distinctId: string
@@ -2017,26 +2148,22 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2017
2148
  *
2018
2149
  * @example
2019
2150
  * ```ts
2020
- * // Check if ready
2151
+ * // Check if ready before evaluating
2021
2152
  * if (client.isLocalEvaluationReady()) {
2022
- * // Local evaluation is ready, can evaluate flags locally
2023
- * 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')
2024
2155
  * } else {
2025
- * // Local evaluation not ready, will use remote evaluation
2026
- * const flag = await client.getFeatureFlag('flag-key', 'user_123')
2156
+ * const flags = await client.evaluateFlags('user_123')
2157
+ * const value = flags.getFlag('flag-key')
2027
2158
  * }
2028
2159
  * ```
2029
2160
  *
2030
2161
  * @remarks
2031
- * Readiness requires at least one loaded flag definition. A successful load that returns no
2032
- * flags (for example, after every flag is deleted) does not count as ready, and readiness
2033
- * returns to `false` if a later load returns no flags. To react to every successful load,
2034
- * including empty ones, listen for the `localEvaluationFlagsLoaded` event, which reports the
2035
- * 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.
2036
2163
  *
2037
2164
  * {@label Feature flags}
2038
2165
  *
2039
- * @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
2040
2167
  */
2041
2168
  isLocalEvaluationReady(): boolean {
2042
2169
  return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false
@@ -2117,10 +2244,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2117
2244
  *
2118
2245
  * {@label Feature flags}
2119
2246
  *
2120
- * @param timeoutMs - Timeout in milliseconds (default: 30000)
2247
+ * @param timeoutMs - Timeout in milliseconds
2121
2248
  * @returns Promise that resolves to true if ready, false if timed out or if the next load returned no flags
2122
2249
  */
2123
- async waitForLocalEvaluationReady(timeoutMs: number = THIRTY_SECONDS): Promise<boolean> {
2250
+ async waitForLocalEvaluationReady(timeoutMs: number = 30000): Promise<boolean> {
2124
2251
  if (this.isLocalEvaluationReady()) {
2125
2252
  return true
2126
2253
  }
@@ -2683,7 +2810,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
2683
2810
  * - `undefined`, when the flag has no payload, or the request failed. A response with a status
2684
2811
  * outside 200 to 299 emits a `RemoteConfigPayloadError` carrying the `statusCode` and `flagKey` on the
2685
2812
  * client's `error` event; a network error, a timeout or an unreadable body emits the underlying error there.
2686
- * @throws Error if personal API key is not provided
2813
+ * @throws Error if neither `secretKey` nor `personalApiKey` is configured. Set `enableLocalEvaluation: false` when `secretKey` is only for remote config or email.
2687
2814
  */
2688
2815
  async getRemoteConfigPayload(flagKey: string): Promise<JsonType | undefined> {
2689
2816
  if (this.disabled) {
@@ -3459,39 +3586,41 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3459
3586
  }
3460
3587
 
3461
3588
  /**
3462
- * Create or update a group and its properties.
3589
+ * Queue a `$groupidentify` event to create or update a group and its properties (requires Group Analytics).
3590
+ *
3591
+ * 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.
3463
3592
  *
3464
3593
  * @example
3465
3594
  * ```ts
3466
- * // Create a company group
3595
+ * // Create or update a company group
3467
3596
  * client.groupIdentify({
3468
3597
  * groupType: 'company',
3469
3598
  * groupKey: 'acme-corp',
3470
3599
  * properties: {
3471
3600
  * name: 'Acme Corporation',
3472
3601
  * industry: 'Technology',
3473
- * employee_count: 500
3602
+ * employee_count: 500,
3474
3603
  * },
3475
- * distinctId: 'user_123'
3604
+ * distinctId: 'user_123',
3476
3605
  * })
3477
3606
  * ```
3478
3607
  *
3479
3608
  * @example
3480
3609
  * ```ts
3481
- * // Update organization properties
3610
+ * // Update organization properties using fallback distinctId ($organization_org-456)
3482
3611
  * client.groupIdentify({
3483
3612
  * groupType: 'organization',
3484
3613
  * groupKey: 'org-456',
3485
3614
  * properties: {
3486
3615
  * plan: 'enterprise',
3487
- * region: 'US-West'
3488
- * }
3616
+ * region: 'US-West',
3617
+ * },
3489
3618
  * })
3490
3619
  * ```
3491
3620
  *
3492
3621
  * {@label Identification}
3493
3622
  *
3494
- * @param data - The group identify data
3623
+ * @param data - Group identify payload
3495
3624
  */
3496
3625
  groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip, options }: GroupIdentifyMessage): void {
3497
3626
  this._sendPreparedEvent(
@@ -3513,7 +3642,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3513
3642
  }
3514
3643
 
3515
3644
  /**
3516
- * Create or update a group and its properties immediately (synchronously).
3645
+ * Send a `$groupidentify` event immediately and wait for the HTTP send attempt to settle.
3646
+ *
3647
+ * 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.
3517
3648
  *
3518
3649
  * @example
3519
3650
  * ```ts
@@ -3524,15 +3655,15 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3524
3655
  * properties: {
3525
3656
  * name: 'Acme Corporation',
3526
3657
  * industry: 'Technology',
3527
- * employee_count: 500
3528
- * }
3658
+ * employee_count: 500,
3659
+ * },
3529
3660
  * })
3530
3661
  * ```
3531
3662
  *
3532
3663
  * {@label Identification}
3533
3664
  *
3534
- * @param data - The group identify data
3535
- * @returns Promise that resolves when the group identify is processed
3665
+ * @param data - Group identify payload
3666
+ * @returns Promise that resolves when the group identify call settles
3536
3667
  */
3537
3668
  async groupIdentifyImmediate({
3538
3669
  groupType,
@@ -3572,9 +3703,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3572
3703
  *
3573
3704
  * @example
3574
3705
  * ```ts
3575
- * // Reload before checking a specific flag
3706
+ * // Reload before evaluating flags
3576
3707
  * await client.reloadFeatureFlags()
3577
- * const flag = await client.getFeatureFlag('flag-key', 'user_123')
3708
+ * const flags = await client.evaluateFlags('user_123')
3709
+ * const value = flags.getFlag('flag-key')
3578
3710
  * ```
3579
3711
  *
3580
3712
  * {@label Feature flags}
@@ -3778,19 +3910,18 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3778
3910
  protected abstract initializeContext(): IPostHogContext | undefined
3779
3911
 
3780
3912
  /**
3781
- * Run a function with specific context that will be applied to all events captured within that context.
3782
- * It propagates the context to all subsequent calls down the call stack.
3783
- * Context properties like tags and sessionId will be automatically attached to all events.
3784
- * By default, nested contexts inherit from parent contexts. Use `{ fresh: true }` to start with a clean context.
3913
+ * Run a function with request-scoped context using `AsyncLocalStorage` so state propagates down function calls and `await`.
3914
+ *
3915
+ * 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.
3916
+ *
3917
+ * 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.
3918
+ *
3919
+ * On `posthog-node/edge`, `withContext()` runs `fn` directly without `AsyncLocalStorage`, so nested calls won't see context data.
3785
3920
  *
3786
3921
  * @remarks
3787
- * Context `properties` and `options` fill only what an event left unset: the event's own values
3788
- * win, and context values beat `register()` and `registerOptions()` values and the values the SDK
3789
- * adds. `beforeSend` sees the result and can change it.
3922
+ * 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.
3790
3923
  *
3791
- * On `$identify`, `$create_alias`, `$merge_dangerously`, `$groupidentify`, `$set` and `$set_once`
3792
- * events, a context `process_person_profile` option applies only when the distinct id is
3793
- * generated, and a `$process_person_profile` property never applies (see `registerOptions()`).
3924
+ * 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()`).
3794
3925
  *
3795
3926
  * @example
3796
3927
  * ```ts
@@ -3801,9 +3932,9 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3801
3932
  *
3802
3933
  * {@label Context}
3803
3934
  *
3804
- * @param data - Context data to apply (sessionId, distinctId, properties, options)
3935
+ * @param data - Context data to apply (`sessionId`, `distinctId`, `properties`, `options`)
3805
3936
  * @param fn - Function to run with the context
3806
- * @param options - Context options (fresh: true to start with clean context instead of inheriting)
3937
+ * @param options - Context options (`fresh: true` to clear inherited state, `signal` to expire on abort)
3807
3938
  * @returns The return value of the function
3808
3939
  */
3809
3940
  withContext<T>(data: Partial<ContextData>, fn: () => T, options?: ContextOptions): T {
@@ -3823,7 +3954,7 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3823
3954
  }
3824
3955
 
3825
3956
  /**
3826
- * Get the current context data.
3957
+ * Read the active `withContext()` data, or `undefined` outside a context (and always `undefined` on `posthog-node/edge`).
3827
3958
  *
3828
3959
  * @example
3829
3960
  * ```ts
@@ -3836,31 +3967,46 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen
3836
3967
  *
3837
3968
  * {@label Context}
3838
3969
  *
3839
- * @returns The current context data, or undefined if no context is set
3970
+ * @returns The current context data, or `undefined` if no context is active
3840
3971
  */
3841
3972
  getContext(): ContextData | undefined {
3842
3973
  return this.context?.get()
3843
3974
  }
3844
3975
 
3845
3976
  /**
3846
- * Shutdown the PostHog client gracefully.
3977
+ * Shuts down the client, drains pending queues, and flushes queued telemetry before exit.
3978
+ *
3979
+ * Call `shutdown()` once on process exit. Use `flush()` when you'll keep reusing the client.
3980
+ *
3981
+ * - **What it stops and drains.** Halts flag polling, calls `flagDefinitionCacheProvider.shutdown()`, and drains analytics events, AI events, logs, metrics, and ended spans.
3982
+ * - **Shared timeout budget.** Analytics queues and OTel signal flushing share `shutdownTimeoutMs`. Open spans that haven't ended are discarded.
3983
+ * - **Delivery vs. ingestion.** Resolving confirms the client tried to drain within `shutdownTimeoutMs`, not that PostHog ingested every event.
3847
3984
  *
3848
3985
  * @example
3849
3986
  * ```ts
3850
- * // Shutdown with default timeout
3851
- * await client._shutdown()
3987
+ * await client.shutdown()
3852
3988
  * ```
3853
3989
  *
3854
3990
  * @example
3855
3991
  * ```ts
3856
- * // Shutdown with custom timeout
3857
- * await client._shutdown(5000) // 5 seconds
3992
+ * // Shutdown with a 5-second timeout
3993
+ * await client.shutdown(5000)
3858
3994
  * ```
3859
3995
  *
3860
3996
  * {@label Shutdown}
3861
3997
  *
3862
- * @param shutdownTimeoutMs - Timeout in milliseconds for shutdown
3863
- * @returns Promise that resolves when shutdown is complete
3998
+ * @param shutdownTimeoutMs - Maximum wait in milliseconds, defaulting to `30000`
3999
+ * @returns Promise that resolves when shutdown finishes or hits `shutdownTimeoutMs`
4000
+ */
4001
+ override shutdown(shutdownTimeoutMs: number = 30000): Promise<void> {
4002
+ return super.shutdown(shutdownTimeoutMs)
4003
+ }
4004
+
4005
+ /**
4006
+ * Internal shutdown hook invoked by `shutdown()`.
4007
+ *
4008
+ * @param shutdownTimeoutMs - Maximum wait in milliseconds
4009
+ * @returns Promise that resolves when internal shutdown completes
3864
4010
  */
3865
4011
  async _shutdown(shutdownTimeoutMs?: number): Promise<void> {
3866
4012
  // One absolute deadline for the whole shutdown: the metrics flush race and