posthog-node 6.2.0 → 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.
package/dist/client.d.ts CHANGED
@@ -23,6 +23,8 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
23
23
  private _captureLogger?;
24
24
  /** Resolved once on first event; `null` means no service name is configured. */
25
25
  private _serviceName?;
26
+ /** Read once while the client is constructed, so one process release id holds for its lifetime. */
27
+ private readonly _releaseId?;
26
28
  private _spanContext?;
27
29
  private readonly _captureLanes;
28
30
  private readonly _captureSettings;
@@ -50,32 +52,43 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
50
52
  set distinctIdHasSentFlagCalls(value: Record<string, Set<string>>);
51
53
  private _waitUntilCycle?;
52
54
  /**
53
- * Initialize a new PostHog client instance.
55
+ * Create a `PostHog` server client (`import { PostHog } from 'posthog-node'`).
56
+ *
57
+ * 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`.
58
+ *
59
+ * 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`.
60
+ *
61
+ * #### Know what to await
62
+ *
63
+ * | Call | Methods | Reach for it when |
64
+ * | --- | --- | --- |
65
+ * | 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 |
66
+ * | `await` | `captureImmediate`, `captureAiImmediate`, `identifyImmediate`, `aliasImmediate`, `groupIdentifyImmediate`, `captureExceptionImmediate` | Waiting for an upload attempt to finish before a short-lived handler exits |
67
+ * | `await` | `evaluateFlags`, `getFeatureFlagResult`, `getAllFlags`, `getAllFlagsAndPayloads`, `getRemoteConfigPayload`, `flush`, `shutdown`, `reloadFeatureFlags`, `waitForLocalEvaluationReady` | Reading flags, remote config, or draining queues |
68
+ * | `await` (`{ data, error }`) | `emails.send`, `emails.get`, `emails.setPreferences` | Sending transactional email or updating preferences (never rejects) |
54
69
  *
55
70
  * @example
56
71
  * ```ts
57
72
  * // Basic initialization
58
- * const client = new PostHogBackendClient(
59
- * 'your-api-key',
60
- * { host: 'https://app.posthog.com' }
61
- * )
73
+ * import { PostHog } from 'posthog-node'
74
+ *
75
+ * const client = new PostHog('<ph_project_api_key>', {
76
+ * host: 'https://us.i.posthog.com',
77
+ * })
62
78
  * ```
63
79
  *
64
80
  * @example
65
81
  * ```ts
66
- * // With a secret key (Personal API Key or Project Secret API Key) for local evaluation
67
- * const client = new PostHogBackendClient(
68
- * 'your-api-key',
69
- * {
70
- * host: 'https://app.posthog.com',
71
- * secretKey: 'your-secret-key'
72
- * }
73
- * )
82
+ * // With a secret key (Project Secret API Key or Personal API Key) for local evaluation and emails
83
+ * const client = new PostHog('<ph_project_api_key>', {
84
+ * host: 'https://us.i.posthog.com',
85
+ * secretKey: 'phs_...',
86
+ * })
74
87
  * ```
75
88
  *
76
89
  * {@label Initialization}
77
90
  *
78
- * @param apiKey - Your PostHog project API key
91
+ * @param apiKey - Your PostHog project API key (`phc_...`)
79
92
  * @param options - Configuration options for the client
80
93
  */
81
94
  constructor(apiKey: string, options?: PostHogOptions);
@@ -276,18 +289,12 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
276
289
  */
277
290
  get logger(): CaptureLogger;
278
291
  /**
279
- * The `posthog.emails` API: sends transactional email from PostHog email templates, reads
280
- * the status of each email it sent, and sets a recipient's topic preferences.
292
+ * Send transactional email from PostHog templates or inline code, read send status, and update topic preferences.
281
293
  *
282
- * Needs `secretKey`, a project secret API key. `send` needs the `transactional_email:write` scope
283
- * (the "Send transactional email" preset), and `get` needs `transactional_email:read` or
284
- * `transactional_email:write`. `setPreferences` needs the
285
- * `messaging_preference:write` scope, which cannot send email. Keys made with `hog_flow:write` still
286
- * work for all three. Requests go to `appHost`, or to the PostHog Cloud app host of `host`. `send`,
287
- * `get` and `setPreferences` resolve to `{ data, error }` and do not reject.
288
- * `data.id` is the queued email's message ID, which `get` takes. A disabled client sends nothing
289
- * and returns the error `client_disabled`. After `shutdown()`, the client sends nothing and
290
- * returns the error `client_closed`.
294
+ * - **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.
295
+ * - **Routing and retries.** Requests go to `appHost`, or the PostHog Cloud app host for `host`. Configure `emailRequestTimeoutMs` and `emailRequestMaxRetries` per client.
296
+ * - **Result handling.** `send`, `get`, and `setPreferences` resolve to `{ data, error }` and never reject. `data.id` is the queued email's ID for `get`.
297
+ * - **Lifecycle.** A disabled client returns `client_disabled`, and a shut-down client returns `client_closed`.
291
298
  *
292
299
  * @example
293
300
  * ```ts
@@ -449,8 +456,8 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
449
456
  /**
450
457
  * The properties the SDK adds to an event: `$is_server` (unless the `isServer` option is
451
458
  * `false`), `$geoip_disable` (when the `disableGeoip` option is on), feature flag properties,
452
- * and for `$exception` events the active OpenTelemetry trace ids and the injected release id.
453
- * They fill only the keys every other layer left unset.
459
+ * the release id when one is configured, and for `$exception` events the active OpenTelemetry
460
+ * trace ids. They fill only the keys every other layer left unset.
454
461
  */
455
462
  private _sdkEventProperties;
456
463
  /**
@@ -508,6 +515,81 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
508
515
  * @param enabled - Whether to enable debug logging
509
516
  */
510
517
  debug(enabled?: boolean): void;
518
+ /**
519
+ * Checks whether the client is disabled from capturing events.
520
+ *
521
+ * {@label Privacy}
522
+ *
523
+ * @example
524
+ * ```ts
525
+ * if (!client.isDisabled) {
526
+ * client.capture({ distinctId: 'user_123', event: 'page_viewed' })
527
+ * }
528
+ * ```
529
+ *
530
+ * @returns `true` when capture and network requests are disabled
531
+ */
532
+ get isDisabled(): boolean;
533
+ /**
534
+ * Checks whether debug logging is enabled on this client.
535
+ *
536
+ * {@label Initialization}
537
+ *
538
+ * @example
539
+ * ```ts
540
+ * if (client.isDebug) {
541
+ * console.log('PostHog debug logging is active')
542
+ * }
543
+ * ```
544
+ *
545
+ * @returns `true` when debug logging is active
546
+ */
547
+ get isDebug(): boolean;
548
+ /**
549
+ * Checks whether the client is currently opted out.
550
+ *
551
+ * {@label Privacy}
552
+ *
553
+ * @example
554
+ * ```ts
555
+ * if (client.optedOut) {
556
+ * console.log('Capture is paused for this client')
557
+ * }
558
+ * ```
559
+ *
560
+ * @returns `true` when the client is opted out
561
+ */
562
+ get optedOut(): boolean;
563
+ /**
564
+ * Opts the client in so it resumes capturing events.
565
+ *
566
+ * Equivalent to `enable()`.
567
+ *
568
+ * {@label Privacy}
569
+ *
570
+ * @example
571
+ * ```ts
572
+ * await client.optIn()
573
+ * ```
574
+ *
575
+ * @returns Promise that resolves when the client opts back in
576
+ */
577
+ optIn(): Promise<void>;
578
+ /**
579
+ * Opts the client out so it stops capturing events.
580
+ *
581
+ * Equivalent to `disable()`.
582
+ *
583
+ * {@label Privacy}
584
+ *
585
+ * @example
586
+ * ```ts
587
+ * await client.optOut()
588
+ * ```
589
+ *
590
+ * @returns Promise that resolves when the client opts out
591
+ */
592
+ optOut(): Promise<void>;
511
593
  protected describeDebugPayload(payload: unknown): unknown;
512
594
  private _warnIfInvalidCapture;
513
595
  private _sendPreparedEvent;
@@ -521,26 +603,49 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
521
603
  */
522
604
  _captureIntegrationException(error: unknown, buildEvent: () => Promise<EventMessage>, callOnlyProperties?: readonly string[]): Promise<void>;
523
605
  /**
524
- * Capture an event manually.
606
+ * Queue an event in memory to send asynchronously without blocking the caller.
607
+ *
608
+ * 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.
609
+ *
610
+ * 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`.
611
+ *
612
+ * 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.
525
613
  *
526
614
  * @example
527
615
  * ```ts
528
- * // Basic capture
616
+ * // Basic capture with person properties and groups
529
617
  * client.capture({
530
618
  * distinctId: 'user_123',
531
- * event: 'button_clicked',
532
- * properties: { button_color: 'red' }
619
+ * event: 'movie_played',
620
+ * properties: {
621
+ * movie_id: '123',
622
+ * $set: { name: 'Max Hedgehog' },
623
+ * $set_once: { initial_url: '/blog' },
624
+ * },
625
+ * groups: { company: 'acme' },
626
+ * })
627
+ * ```
628
+ *
629
+ * @example
630
+ * ```ts
631
+ * // Personless event for a known user
632
+ * client.capture({
633
+ * distinctId: 'user_123',
634
+ * event: 'background_job',
635
+ * options: { process_person_profile: false },
533
636
  * })
534
637
  * ```
535
638
  *
536
639
  * {@label Capture}
537
640
  *
538
- * @param props - The event properties
641
+ * @param props - The event payload
539
642
  * @returns void
540
643
  */
541
644
  capture(props: EventMessage): void;
542
645
  /**
543
- * Capture an event immediately (synchronously).
646
+ * Send an event immediately and wait for the HTTP send attempt to settle.
647
+ *
648
+ * 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.
544
649
  *
545
650
  * @example
546
651
  * ```ts
@@ -548,39 +653,35 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
548
653
  * await client.captureImmediate({
549
654
  * distinctId: 'user_123',
550
655
  * event: 'button_clicked',
551
- * properties: { button_color: 'red' }
656
+ * properties: { button_color: 'red' },
552
657
  * })
553
658
  * ```
554
659
  *
555
660
  * @example
556
661
  * ```ts
557
- * // With feature flags
662
+ * // With an evaluated flags snapshot
663
+ * const flags = await client.evaluateFlags('user_123')
558
664
  * await client.captureImmediate({
559
665
  * distinctId: 'user_123',
560
666
  * event: 'user_action',
561
- * sendFeatureFlags: true
667
+ * flags,
562
668
  * })
563
669
  * ```
564
670
  *
565
671
  * @example
566
672
  * ```ts
567
- * // With custom feature flags options
673
+ * // Personless immediate capture
568
674
  * await client.captureImmediate({
569
675
  * distinctId: 'user_123',
570
- * event: 'user_action',
571
- * sendFeatureFlags: {
572
- * onlyEvaluateLocally: true,
573
- * personProperties: { plan: 'premium' },
574
- * groupProperties: { org: { tier: 'enterprise' } },
575
- * flagKeys: ['flag1', 'flag2']
576
- * }
676
+ * event: 'webhook_received',
677
+ * options: { process_person_profile: false },
577
678
  * })
578
679
  * ```
579
680
  *
580
681
  * {@label Capture}
581
682
  *
582
- * @param props - The event properties
583
- * @returns Promise that resolves when the event is captured
683
+ * @param props - The event payload
684
+ * @returns Promise that resolves when the send attempt completes
584
685
  */
585
686
  captureImmediate(props: EventMessage): Promise<void>;
586
687
  /**
@@ -609,7 +710,11 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
609
710
  captureAiImmediate(props: EventMessage): Promise<string | undefined>;
610
711
  private _sendPreparedAiEvent;
611
712
  /**
612
- * Identify a user and set their properties.
713
+ * Queue an `$identify` event setting person properties for `distinctId`.
714
+ *
715
+ * 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`.
716
+ *
717
+ * Prefer `$set` or `$set_once` on `capture()` (or `setPersonProperties()`) when you only need to update properties without linking an anonymous ID.
613
718
  *
614
719
  * @example
615
720
  * ```ts
@@ -619,31 +724,33 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
619
724
  * properties: {
620
725
  * name: 'John Doe',
621
726
  * email: 'john@example.com',
622
- * plan: 'premium'
623
- * }
727
+ * plan: 'premium',
728
+ * },
624
729
  * })
625
730
  * ```
626
731
  *
627
732
  * @example
628
733
  * ```ts
629
- * // Using $set and $set_once
734
+ * // Using $set, $set_once, and $anon_distinct_id
630
735
  * client.identify({
631
736
  * distinctId: 'user_123',
632
737
  * properties: {
633
738
  * $set: { name: 'John Doe', email: 'john@example.com' },
634
739
  * $set_once: { first_login: new Date().toISOString() },
635
- * $anon_distinct_id: 'anonymous_user_456'
636
- * }
740
+ * $anon_distinct_id: 'anonymous_user_456',
741
+ * },
637
742
  * })
638
743
  * ```
639
744
  *
640
745
  * {@label Identification}
641
746
  *
642
- * @param data - The identify data containing distinctId and properties
747
+ * @param data - The identify payload containing `distinctId` and `properties`
643
748
  */
644
749
  identify({ distinctId, properties, disableGeoip, options }: IdentifyMessage): void;
645
750
  /**
646
- * Identify a user and set their properties immediately (synchronously).
751
+ * Send an `$identify` event immediately and wait for the HTTP send attempt to settle.
752
+ *
753
+ * 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()`.
647
754
  *
648
755
  * @example
649
756
  * ```ts
@@ -652,65 +759,71 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
652
759
  * distinctId: 'user_123',
653
760
  * properties: {
654
761
  * name: 'John Doe',
655
- * email: 'john@example.com'
656
- * }
762
+ * email: 'john@example.com',
763
+ * },
657
764
  * })
658
765
  * ```
659
766
  *
660
767
  * {@label Identification}
661
768
  *
662
- * @param data - The identify data containing distinctId and properties
663
- * @returns Promise that resolves when the identify is processed
769
+ * @param data - The identify payload containing `distinctId` and `properties`
770
+ * @returns Promise that resolves when the identify call settles
664
771
  */
665
772
  identifyImmediate({ distinctId, properties, disableGeoip, options }: IdentifyMessage): Promise<void>;
666
773
  /**
667
- * Set properties on a person profile.
774
+ * Queue a `$set` event to set or set-once properties on a person profile.
775
+ *
776
+ * Falls back to `withContext()` when `distinctId` is blank, and no-ops when both `properties` and `propertiesOnce` are empty.
668
777
  *
669
778
  * @example
670
779
  * ```ts
671
780
  * client.setPersonProperties({
672
781
  * distinctId: 'user_123',
673
782
  * properties: { plan: 'premium' },
674
- * propertiesOnce: { first_seen: '2026-06-15' }
783
+ * propertiesOnce: { first_seen: '2026-06-15' },
675
784
  * })
676
785
  * ```
677
786
  *
678
787
  * {@label Identification}
679
788
  *
680
- * @param data - The data containing distinctId and properties to set
789
+ * @param data - Distinct ID and person properties to set
681
790
  */
682
791
  setPersonProperties({ distinctId, properties, propertiesOnce, options }: SetPersonPropertiesMessage): void;
683
792
  /**
684
- * Remove properties from a person profile.
793
+ * Queue a `$set` event carrying `$unset` to remove properties from a person profile.
794
+ *
795
+ * Falls back to `withContext()` when `distinctId` is blank, and no-ops when `properties` is empty.
685
796
  *
686
797
  * @example
687
798
  * ```ts
688
799
  * client.unsetPersonProperties({
689
800
  * distinctId: 'user_123',
690
- * properties: ['plan', 'email']
801
+ * properties: ['plan', 'email'],
691
802
  * })
692
803
  * ```
693
804
  *
694
805
  * {@label Identification}
695
806
  *
696
- * @param data - The data containing distinctId and property names to unset
807
+ * @param data - Distinct ID and property names to unset
697
808
  */
698
809
  unsetPersonProperties({ distinctId, properties, options }: UnsetPersonPropertiesMessage): void;
699
810
  /**
700
- * Create an alias to link two distinct IDs together.
811
+ * Queue a `$create_alias` event linking `alias` (the previous or secondary ID) to `distinctId` (the primary user ID).
812
+ *
813
+ * `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.
701
814
  *
702
815
  * @example
703
816
  * ```ts
704
- * // Link an anonymous user to an identified user
817
+ * // Link an anonymous user ID to a primary user ID
705
818
  * client.alias({
706
- * distinctId: 'anonymous_123',
707
- * alias: 'user_456'
819
+ * distinctId: 'user_456',
820
+ * alias: 'anonymous_123',
708
821
  * })
709
822
  * ```
710
823
  *
711
824
  * {@label Identification}
712
825
  *
713
- * @param data - The alias data containing distinctId and alias
826
+ * @param data - Primary `distinctId`, previous `alias`, and optional flags or options
714
827
  */
715
828
  alias(data: {
716
829
  distinctId: string;
@@ -719,21 +832,23 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
719
832
  options?: EventOptions;
720
833
  }): void;
721
834
  /**
722
- * Create an alias to link two distinct IDs together immediately (synchronously).
835
+ * Send a `$create_alias` event immediately to link `alias` to `distinctId`.
836
+ *
837
+ * Follows the same ID precedence and placeholder warnings as `alias()`. Use in short-lived runtimes where the process can freeze before a background flush.
723
838
  *
724
839
  * @example
725
840
  * ```ts
726
- * // Link an anonymous user to an identified user immediately
841
+ * // Link an anonymous user ID to a primary user ID immediately
727
842
  * await client.aliasImmediate({
728
- * distinctId: 'anonymous_123',
729
- * alias: 'user_456'
843
+ * distinctId: 'user_456',
844
+ * alias: 'anonymous_123',
730
845
  * })
731
846
  * ```
732
847
  *
733
848
  * {@label Identification}
734
849
  *
735
- * @param data - The alias data containing distinctId and alias
736
- * @returns Promise that resolves when the alias is processed
850
+ * @param data - Primary `distinctId`, previous `alias`, and optional flags or options
851
+ * @returns Promise that resolves when the alias call settles
737
852
  */
738
853
  aliasImmediate(data: {
739
854
  distinctId: string;
@@ -746,26 +861,22 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
746
861
  *
747
862
  * @example
748
863
  * ```ts
749
- * // Check if ready
864
+ * // Check if ready before evaluating
750
865
  * if (client.isLocalEvaluationReady()) {
751
- * // Local evaluation is ready, can evaluate flags locally
752
- * const flag = await client.getFeatureFlag('flag-key', 'user_123')
866
+ * const flags = await client.evaluateFlags('user_123', { onlyEvaluateLocally: true })
867
+ * const value = flags.getFlag('flag-key')
753
868
  * } else {
754
- * // Local evaluation not ready, will use remote evaluation
755
- * const flag = await client.getFeatureFlag('flag-key', 'user_123')
869
+ * const flags = await client.evaluateFlags('user_123')
870
+ * const value = flags.getFlag('flag-key')
756
871
  * }
757
872
  * ```
758
873
  *
759
874
  * @remarks
760
- * Readiness requires at least one loaded flag definition. A successful load that returns no
761
- * flags (for example, after every flag is deleted) does not count as ready, and readiness
762
- * returns to `false` if a later load returns no flags. To react to every successful load,
763
- * including empty ones, listen for the `localEvaluationFlagsLoaded` event, which reports the
764
- * number of loaded flags.
875
+ * 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.
765
876
  *
766
877
  * {@label Feature flags}
767
878
  *
768
- * @returns true if flag definitions have loaded successfully and include at least one flag, false otherwise
879
+ * @returns `true` if flag definitions have loaded and include at least one flag, `false` otherwise
769
880
  */
770
881
  isLocalEvaluationReady(): boolean;
771
882
  /**
@@ -837,7 +948,7 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
837
948
  *
838
949
  * {@label Feature flags}
839
950
  *
840
- * @param timeoutMs - Timeout in milliseconds (default: 30000)
951
+ * @param timeoutMs - Timeout in milliseconds
841
952
  * @returns Promise that resolves to true if ready, false if timed out or if the next load returned no flags
842
953
  */
843
954
  waitForLocalEvaluationReady(timeoutMs?: number): Promise<boolean>;
@@ -1023,7 +1134,7 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
1023
1134
  * - `undefined`, when the flag has no payload, or the request failed. A response with a status
1024
1135
  * outside 200 to 299 emits a `RemoteConfigPayloadError` carrying the `statusCode` and `flagKey` on the
1025
1136
  * client's `error` event; a network error, a timeout or an unreadable body emits the underlying error there.
1026
- * @throws Error if personal API key is not provided
1137
+ * @throws Error if neither `secretKey` nor `personalApiKey` is configured. Set `enableLocalEvaluation: false` when `secretKey` is only for remote config or email.
1027
1138
  */
1028
1139
  getRemoteConfigPayload(flagKey: string): Promise<JsonType | undefined>;
1029
1140
  /**
@@ -1277,43 +1388,47 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
1277
1388
  private _featureFlagEvaluationsHost?;
1278
1389
  private _getFeatureFlagEvaluationsHost;
1279
1390
  /**
1280
- * Create or update a group and its properties.
1391
+ * Queue a `$groupidentify` event to create or update a group and its properties (requires Group Analytics).
1392
+ *
1393
+ * 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.
1281
1394
  *
1282
1395
  * @example
1283
1396
  * ```ts
1284
- * // Create a company group
1397
+ * // Create or update a company group
1285
1398
  * client.groupIdentify({
1286
1399
  * groupType: 'company',
1287
1400
  * groupKey: 'acme-corp',
1288
1401
  * properties: {
1289
1402
  * name: 'Acme Corporation',
1290
1403
  * industry: 'Technology',
1291
- * employee_count: 500
1404
+ * employee_count: 500,
1292
1405
  * },
1293
- * distinctId: 'user_123'
1406
+ * distinctId: 'user_123',
1294
1407
  * })
1295
1408
  * ```
1296
1409
  *
1297
1410
  * @example
1298
1411
  * ```ts
1299
- * // Update organization properties
1412
+ * // Update organization properties using fallback distinctId ($organization_org-456)
1300
1413
  * client.groupIdentify({
1301
1414
  * groupType: 'organization',
1302
1415
  * groupKey: 'org-456',
1303
1416
  * properties: {
1304
1417
  * plan: 'enterprise',
1305
- * region: 'US-West'
1306
- * }
1418
+ * region: 'US-West',
1419
+ * },
1307
1420
  * })
1308
1421
  * ```
1309
1422
  *
1310
1423
  * {@label Identification}
1311
1424
  *
1312
- * @param data - The group identify data
1425
+ * @param data - Group identify payload
1313
1426
  */
1314
1427
  groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip, options }: GroupIdentifyMessage): void;
1315
1428
  /**
1316
- * Create or update a group and its properties immediately (synchronously).
1429
+ * Send a `$groupidentify` event immediately and wait for the HTTP send attempt to settle.
1430
+ *
1431
+ * 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.
1317
1432
  *
1318
1433
  * @example
1319
1434
  * ```ts
@@ -1324,15 +1439,15 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
1324
1439
  * properties: {
1325
1440
  * name: 'Acme Corporation',
1326
1441
  * industry: 'Technology',
1327
- * employee_count: 500
1328
- * }
1442
+ * employee_count: 500,
1443
+ * },
1329
1444
  * })
1330
1445
  * ```
1331
1446
  *
1332
1447
  * {@label Identification}
1333
1448
  *
1334
- * @param data - The group identify data
1335
- * @returns Promise that resolves when the group identify is processed
1449
+ * @param data - Group identify payload
1450
+ * @returns Promise that resolves when the group identify call settles
1336
1451
  */
1337
1452
  groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip, options, }: GroupIdentifyMessage): Promise<void>;
1338
1453
  /**
@@ -1347,9 +1462,10 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
1347
1462
  *
1348
1463
  * @example
1349
1464
  * ```ts
1350
- * // Reload before checking a specific flag
1465
+ * // Reload before evaluating flags
1351
1466
  * await client.reloadFeatureFlags()
1352
- * const flag = await client.getFeatureFlag('flag-key', 'user_123')
1467
+ * const flags = await client.evaluateFlags('user_123')
1468
+ * const value = flags.getFlag('flag-key')
1353
1469
  * ```
1354
1470
  *
1355
1471
  * {@label Feature flags}
@@ -1455,19 +1571,18 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
1455
1571
  unregisterOptions(key: string): Promise<void>;
1456
1572
  protected abstract initializeContext(): IPostHogContext | undefined;
1457
1573
  /**
1458
- * Run a function with specific context that will be applied to all events captured within that context.
1459
- * It propagates the context to all subsequent calls down the call stack.
1460
- * Context properties like tags and sessionId will be automatically attached to all events.
1461
- * By default, nested contexts inherit from parent contexts. Use `{ fresh: true }` to start with a clean context.
1574
+ * Run a function with request-scoped context using `AsyncLocalStorage` so state propagates down function calls and `await`.
1575
+ *
1576
+ * 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.
1577
+ *
1578
+ * 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.
1579
+ *
1580
+ * On `posthog-node/edge`, `withContext()` runs `fn` directly without `AsyncLocalStorage`, so nested calls won't see context data.
1462
1581
  *
1463
1582
  * @remarks
1464
- * Context `properties` and `options` fill only what an event left unset: the event's own values
1465
- * win, and context values beat `register()` and `registerOptions()` values and the values the SDK
1466
- * adds. `beforeSend` sees the result and can change it.
1583
+ * 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.
1467
1584
  *
1468
- * On `$identify`, `$create_alias`, `$merge_dangerously`, `$groupidentify`, `$set` and `$set_once`
1469
- * events, a context `process_person_profile` option applies only when the distinct id is
1470
- * generated, and a `$process_person_profile` property never applies (see `registerOptions()`).
1585
+ * 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()`).
1471
1586
  *
1472
1587
  * @example
1473
1588
  * ```ts
@@ -1478,14 +1593,14 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
1478
1593
  *
1479
1594
  * {@label Context}
1480
1595
  *
1481
- * @param data - Context data to apply (sessionId, distinctId, properties, options)
1596
+ * @param data - Context data to apply (`sessionId`, `distinctId`, `properties`, `options`)
1482
1597
  * @param fn - Function to run with the context
1483
- * @param options - Context options (fresh: true to start with clean context instead of inheriting)
1598
+ * @param options - Context options (`fresh: true` to clear inherited state, `signal` to expire on abort)
1484
1599
  * @returns The return value of the function
1485
1600
  */
1486
1601
  withContext<T>(data: Partial<ContextData>, fn: () => T, options?: ContextOptions): T;
1487
1602
  /**
1488
- * Get the current context data.
1603
+ * Read the active `withContext()` data, or `undefined` outside a context (and always `undefined` on `posthog-node/edge`).
1489
1604
  *
1490
1605
  * @example
1491
1606
  * ```ts
@@ -1498,28 +1613,40 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
1498
1613
  *
1499
1614
  * {@label Context}
1500
1615
  *
1501
- * @returns The current context data, or undefined if no context is set
1616
+ * @returns The current context data, or `undefined` if no context is active
1502
1617
  */
1503
1618
  getContext(): ContextData | undefined;
1504
1619
  /**
1505
- * Shutdown the PostHog client gracefully.
1620
+ * Shuts down the client, drains pending queues, and flushes queued telemetry before exit.
1621
+ *
1622
+ * Call `shutdown()` once on process exit. Use `flush()` when you'll keep reusing the client.
1623
+ *
1624
+ * - **What it stops and drains.** Halts flag polling, calls `flagDefinitionCacheProvider.shutdown()`, and drains analytics events, AI events, logs, metrics, and ended spans.
1625
+ * - **Shared timeout budget.** Analytics queues and OTel signal flushing share `shutdownTimeoutMs`. Open spans that haven't ended are discarded.
1626
+ * - **Delivery vs. ingestion.** Resolving confirms the client tried to drain within `shutdownTimeoutMs`, not that PostHog ingested every event.
1506
1627
  *
1507
1628
  * @example
1508
1629
  * ```ts
1509
- * // Shutdown with default timeout
1510
- * await client._shutdown()
1630
+ * await client.shutdown()
1511
1631
  * ```
1512
1632
  *
1513
1633
  * @example
1514
1634
  * ```ts
1515
- * // Shutdown with custom timeout
1516
- * await client._shutdown(5000) // 5 seconds
1635
+ * // Shutdown with a 5-second timeout
1636
+ * await client.shutdown(5000)
1517
1637
  * ```
1518
1638
  *
1519
1639
  * {@label Shutdown}
1520
1640
  *
1521
- * @param shutdownTimeoutMs - Timeout in milliseconds for shutdown
1522
- * @returns Promise that resolves when shutdown is complete
1641
+ * @param shutdownTimeoutMs - Maximum wait in milliseconds, defaulting to `30000`
1642
+ * @returns Promise that resolves when shutdown finishes or hits `shutdownTimeoutMs`
1643
+ */
1644
+ shutdown(shutdownTimeoutMs?: number): Promise<void>;
1645
+ /**
1646
+ * Internal shutdown hook invoked by `shutdown()`.
1647
+ *
1648
+ * @param shutdownTimeoutMs - Maximum wait in milliseconds
1649
+ * @returns Promise that resolves when internal shutdown completes
1523
1650
  */
1524
1651
  _shutdown(shutdownTimeoutMs?: number): Promise<void>;
1525
1652
  private _drainCaptureLanes;