posthog-node 5.0.0-alpha.1 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/lib/edge/index.cjs +3455 -0
  3. package/lib/edge/index.cjs.map +1 -0
  4. package/lib/edge/index.mjs +3429 -0
  5. package/lib/edge/index.mjs.map +1 -0
  6. package/lib/index.d.ts +938 -810
  7. package/lib/{index.cjs.js → node/index.cjs} +2910 -3107
  8. package/lib/node/index.cjs.map +1 -0
  9. package/lib/{index.esm.js → node/index.mjs} +2911 -3105
  10. package/lib/node/index.mjs.map +1 -0
  11. package/package.json +33 -6
  12. package/index.ts +0 -3
  13. package/lib/index.cjs.js.map +0 -1
  14. package/lib/index.esm.js.map +0 -1
  15. package/lib/posthog-core/src/eventemitter.d.ts +0 -8
  16. package/lib/posthog-core/src/featureFlagUtils.d.ts +0 -34
  17. package/lib/posthog-core/src/index.d.ts +0 -242
  18. package/lib/posthog-core/src/lz-string.d.ts +0 -8
  19. package/lib/posthog-core/src/storage-memory.d.ts +0 -6
  20. package/lib/posthog-core/src/types.d.ts +0 -422
  21. package/lib/posthog-core/src/utils.d.ts +0 -19
  22. package/lib/posthog-core/src/vendor/uuidv7.d.ts +0 -179
  23. package/lib/posthog-node/index.d.ts +0 -3
  24. package/lib/posthog-node/src/crypto-helpers.d.ts +0 -3
  25. package/lib/posthog-node/src/crypto.d.ts +0 -2
  26. package/lib/posthog-node/src/error-tracking.d.ts +0 -12
  27. package/lib/posthog-node/src/extensions/error-tracking/autocapture.d.ts +0 -3
  28. package/lib/posthog-node/src/extensions/error-tracking/context-lines.d.ts +0 -6
  29. package/lib/posthog-node/src/extensions/error-tracking/error-conversion.d.ts +0 -2
  30. package/lib/posthog-node/src/extensions/error-tracking/reduceable-cache.d.ts +0 -12
  31. package/lib/posthog-node/src/extensions/error-tracking/stack-trace.d.ts +0 -15
  32. package/lib/posthog-node/src/extensions/error-tracking/type-checking.d.ts +0 -7
  33. package/lib/posthog-node/src/extensions/error-tracking/types.d.ts +0 -57
  34. package/lib/posthog-node/src/extensions/express.d.ts +0 -17
  35. package/lib/posthog-node/src/extensions/sentry-integration.d.ts +0 -51
  36. package/lib/posthog-node/src/feature-flags.d.ts +0 -84
  37. package/lib/posthog-node/src/lazy.d.ts +0 -23
  38. package/lib/posthog-node/src/posthog-node.d.ts +0 -91
  39. package/lib/posthog-node/src/types.d.ts +0 -203
  40. package/lib/posthog-node/test/test-utils.d.ts +0 -17
  41. package/src/crypto-helpers.ts +0 -36
  42. package/src/crypto.ts +0 -22
  43. package/src/error-tracking.ts +0 -67
  44. package/src/extensions/error-tracking/autocapture.ts +0 -65
  45. package/src/extensions/error-tracking/context-lines.ts +0 -425
  46. package/src/extensions/error-tracking/error-conversion.ts +0 -262
  47. package/src/extensions/error-tracking/reduceable-cache.ts +0 -39
  48. package/src/extensions/error-tracking/stack-trace.ts +0 -269
  49. package/src/extensions/error-tracking/type-checking.ts +0 -40
  50. package/src/extensions/error-tracking/types.ts +0 -65
  51. package/src/extensions/express.ts +0 -37
  52. package/src/extensions/sentry-integration.ts +0 -196
  53. package/src/feature-flags.ts +0 -863
  54. package/src/lazy.ts +0 -55
  55. package/src/posthog-node.ts +0 -567
  56. package/src/types.ts +0 -231
  57. package/test/crypto.spec.ts +0 -36
  58. package/test/extensions/error-conversion.spec.ts +0 -44
  59. package/test/extensions/sentry-integration.spec.ts +0 -162
  60. package/test/feature-flags.decide.spec.ts +0 -378
  61. package/test/feature-flags.spec.ts +0 -4681
  62. package/test/lazy.spec.ts +0 -71
  63. package/test/posthog-node.spec.ts +0 -1341
  64. package/test/test-utils.ts +0 -106
  65. package/tsconfig.json +0 -7
package/lib/index.d.ts CHANGED
@@ -1,831 +1,959 @@
1
- /// <reference types="node" />
2
- import { SeverityLevel } from 'posthog-node/src/extensions/error-tracking/types';
3
1
  import * as http from 'node:http';
4
2
 
5
- type PostHogCoreOptions = {
6
- /** PostHog API host, usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' */
7
- host?: string;
8
- /** The number of events to queue before sending to PostHog (flushing) */
9
- flushAt?: number;
10
- /** The interval in milliseconds between periodic flushes */
11
- flushInterval?: number;
12
- /** The maximum number of queued messages to be flushed as part of a single batch (must be higher than `flushAt`) */
13
- maxBatchSize?: number;
14
- /** The maximum number of cached messages either in memory or on the local storage.
15
- * Defaults to 1000, (must be higher than `flushAt`)
16
- */
17
- maxQueueSize?: number;
18
- /** If set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) */
19
- disabled?: boolean;
20
- /** If set to false the SDK will not track until the `optIn` function is called. */
21
- defaultOptIn?: boolean;
22
- /** Whether to track that `getFeatureFlag` was called (used by Experiments) */
23
- sendFeatureFlagEvent?: boolean;
24
- /** Whether to load feature flags when initialized or not */
25
- preloadFeatureFlags?: boolean;
26
- /**
27
- * Whether to load remote config when initialized or not
28
- * Experimental support
29
- * Default: false - Remote config is loaded by default
30
- */
31
- disableRemoteConfig?: boolean;
32
- /**
33
- * Whether to load surveys when initialized or not
34
- * Experimental support
35
- * Default: false - Surveys are loaded by default, but requires the `PostHogSurveyProvider` to be used
36
- */
37
- disableSurveys?: boolean;
38
- /** Option to bootstrap the library with given distinctId and feature flags */
39
- bootstrap?: {
40
- distinctId?: string;
41
- isIdentifiedId?: boolean;
42
- featureFlags?: Record<string, FeatureFlagValue>;
43
- featureFlagPayloads?: Record<string, JsonType>;
44
- };
45
- /** How many times we will retry HTTP requests. Defaults to 3. */
46
- fetchRetryCount?: number;
47
- /** The delay between HTTP request retries, Defaults to 3 seconds. */
48
- fetchRetryDelay?: number;
49
- /** Timeout in milliseconds for any calls. Defaults to 10 seconds. */
50
- requestTimeout?: number;
51
- /** Timeout in milliseconds for feature flag calls. Defaults to 10 seconds for stateful clients, and 3 seconds for stateless. */
52
- featureFlagsRequestTimeoutMs?: number;
53
- /** Timeout in milliseconds for remote config calls. Defaults to 3 seconds. */
54
- remoteConfigRequestTimeoutMs?: number;
55
- /** For Session Analysis how long before we expire a session (defaults to 30 mins) */
56
- sessionExpirationTimeSeconds?: number;
57
- /** Whether to post events to PostHog in JSON or compressed format. Defaults to 'json' */
58
- captureMode?: 'json' | 'form';
59
- disableGeoip?: boolean;
60
- /** Special flag to indicate ingested data is for a historical migration. */
61
- historicalMigration?: boolean;
62
- };
63
- declare enum PostHogPersistedProperty {
64
- AnonymousId = "anonymous_id",
65
- DistinctId = "distinct_id",
66
- Props = "props",
67
- FeatureFlagDetails = "feature_flag_details",
68
- FeatureFlags = "feature_flags",
69
- FeatureFlagPayloads = "feature_flag_payloads",
70
- BootstrapFeatureFlagDetails = "bootstrap_feature_flag_details",
71
- BootstrapFeatureFlags = "bootstrap_feature_flags",
72
- BootstrapFeatureFlagPayloads = "bootstrap_feature_flag_payloads",
73
- OverrideFeatureFlags = "override_feature_flags",
74
- Queue = "queue",
75
- OptedOut = "opted_out",
76
- SessionId = "session_id",
77
- SessionLastTimestamp = "session_timestamp",
78
- PersonProperties = "person_properties",
79
- GroupProperties = "group_properties",
80
- InstalledAppBuild = "installed_app_build",
81
- InstalledAppVersion = "installed_app_version",
82
- SessionReplay = "session_replay",
83
- DecideEndpointWasHit = "decide_endpoint_was_hit",
84
- SurveyLastSeenDate = "survey_last_seen_date",
85
- SurveysSeen = "surveys_seen",
86
- Surveys = "surveys",
87
- RemoteConfig = "remote_config"
88
- }
89
- type PostHogFetchOptions = {
90
- method: 'GET' | 'POST' | 'PUT' | 'PATCH';
91
- mode?: 'no-cors';
92
- credentials?: 'omit';
93
- headers: {
94
- [key: string]: string;
95
- };
96
- body?: string;
97
- signal?: AbortSignal;
98
- };
99
- type PostHogCaptureOptions = {
100
- /** If provided overrides the auto-generated event ID */
101
- uuid?: string;
102
- /** If provided overrides the auto-generated timestamp */
103
- timestamp?: Date;
104
- disableGeoip?: boolean;
105
- };
106
- type PostHogFetchResponse = {
107
- status: number;
108
- text: () => Promise<string>;
109
- json: () => Promise<any>;
110
- };
111
- type PostHogEventProperties = {
112
- [key: string]: any;
113
- };
114
- type PostHogRemoteConfig = {
115
- sessionRecording?: boolean | {
116
- [key: string]: JsonType;
117
- };
118
- /**
119
- * Whether surveys are enabled
120
- */
121
- surveys?: boolean | Survey[];
122
- /**
123
- * Indicates if the team has any flags enabled (if not we don't need to load them)
124
- */
125
- hasFeatureFlags?: boolean;
126
- };
127
- type FeatureFlagValue = string | boolean;
128
- type PostHogDecideResponse = Omit<PostHogRemoteConfig, 'surveys' | 'hasFeatureFlags'> & {
129
- featureFlags: {
130
- [key: string]: FeatureFlagValue;
131
- };
132
- featureFlagPayloads: {
133
- [key: string]: JsonType;
134
- };
135
- flags: {
136
- [key: string]: FeatureFlagDetail;
137
- };
138
- errorsWhileComputingFlags: boolean;
139
- sessionRecording?: boolean | {
140
- [key: string]: JsonType;
141
- };
142
- quotaLimited?: string[];
143
- requestId?: string;
144
- };
145
- /**
146
- * Creates a type with all properties of T, but makes only K properties required while the rest remain optional.
147
- *
148
- * @template T - The base type containing all properties
149
- * @template K - Union type of keys from T that should be required
150
- *
151
- * @example
152
- * interface User {
153
- * id: number;
154
- * name: string;
155
- * email?: string;
156
- * age?: number;
157
- * }
158
- *
159
- * // Makes 'id' and 'name' required, but 'email' and 'age' optional
160
- * type RequiredUser = PartialWithRequired<User, 'id' | 'name'>;
161
- *
162
- * const user: RequiredUser = {
163
- * id: 1, // Must be provided
164
- * name: "John" // Must be provided
165
- * // email and age are optional
166
- * };
167
- */
168
- type PartialWithRequired<T, K extends keyof T> = {
169
- [P in K]: T[P];
170
- } & {
171
- [P in Exclude<keyof T, K>]?: T[P];
172
- };
173
- /**
174
- * These are the fields we care about from PostHogDecideResponse for feature flags.
175
- */
176
- type PostHogFeatureFlagDetails = PartialWithRequired<PostHogDecideResponse, 'flags' | 'featureFlags' | 'featureFlagPayloads' | 'requestId'>;
177
- /**
178
- * Models legacy flags and payloads return type for many public methods.
179
- */
180
- type PostHogFlagsAndPayloadsResponse = Partial<Pick<PostHogDecideResponse, 'featureFlags' | 'featureFlagPayloads'>>;
181
- type JsonType = string | number | boolean | null | {
182
- [key: string]: JsonType;
183
- } | Array<JsonType>;
184
- type FeatureFlagDetail = {
185
- key: string;
186
- enabled: boolean;
187
- variant: string | undefined;
188
- reason: EvaluationReason | undefined;
189
- metadata: FeatureFlagMetadata | undefined;
190
- };
191
- type FeatureFlagMetadata = {
192
- id: number | undefined;
193
- version: number | undefined;
194
- description: string | undefined;
195
- payload: string | undefined;
196
- };
197
- type EvaluationReason = {
198
- code: string | undefined;
199
- condition_index: number | undefined;
200
- description: string | undefined;
201
- };
202
- type SurveyAppearance = {
203
- backgroundColor?: string;
204
- submitButtonColor?: string;
205
- submitButtonText?: string;
206
- submitButtonTextColor?: string;
207
- ratingButtonColor?: string;
208
- ratingButtonActiveColor?: string;
209
- autoDisappear?: boolean;
210
- displayThankYouMessage?: boolean;
211
- thankYouMessageHeader?: string;
212
- thankYouMessageDescription?: string;
213
- thankYouMessageDescriptionContentType?: SurveyQuestionDescriptionContentType;
214
- thankYouMessageCloseButtonText?: string;
215
- borderColor?: string;
216
- position?: SurveyPosition;
217
- placeholder?: string;
218
- shuffleQuestions?: boolean;
219
- surveyPopupDelaySeconds?: number;
220
- widgetType?: SurveyWidgetType;
221
- widgetSelector?: string;
222
- widgetLabel?: string;
223
- widgetColor?: string;
224
- };
225
- declare enum SurveyPosition {
226
- Left = "left",
227
- Right = "right",
228
- Center = "center"
229
- }
230
- declare enum SurveyWidgetType {
231
- Button = "button",
232
- Tab = "tab",
233
- Selector = "selector"
234
- }
235
- declare enum SurveyType {
236
- Popover = "popover",
237
- API = "api",
238
- Widget = "widget"
239
- }
240
- type SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion;
241
- declare enum SurveyQuestionDescriptionContentType {
242
- Html = "html",
243
- Text = "text"
244
- }
245
- type SurveyQuestionBase = {
246
- question: string;
247
- id?: string;
248
- description?: string;
249
- descriptionContentType?: SurveyQuestionDescriptionContentType;
250
- optional?: boolean;
251
- buttonText?: string;
252
- originalQuestionIndex: number;
253
- branching?: NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching;
254
- };
255
- type BasicSurveyQuestion = SurveyQuestionBase & {
256
- type: SurveyQuestionType.Open;
257
- };
258
- type LinkSurveyQuestion = SurveyQuestionBase & {
259
- type: SurveyQuestionType.Link;
260
- link?: string;
261
- };
262
- type RatingSurveyQuestion = SurveyQuestionBase & {
263
- type: SurveyQuestionType.Rating;
264
- display: SurveyRatingDisplay;
265
- scale: 3 | 5 | 7 | 10;
266
- lowerBoundLabel: string;
267
- upperBoundLabel: string;
268
- };
269
- declare enum SurveyRatingDisplay {
270
- Number = "number",
271
- Emoji = "emoji"
272
- }
273
- type MultipleSurveyQuestion = SurveyQuestionBase & {
274
- type: SurveyQuestionType.SingleChoice | SurveyQuestionType.MultipleChoice;
275
- choices: string[];
276
- hasOpenChoice?: boolean;
277
- shuffleOptions?: boolean;
278
- };
279
- declare enum SurveyQuestionType {
280
- Open = "open",
281
- MultipleChoice = "multiple_choice",
282
- SingleChoice = "single_choice",
283
- Rating = "rating",
284
- Link = "link"
285
- }
286
- declare enum SurveyQuestionBranchingType {
287
- NextQuestion = "next_question",
288
- End = "end",
289
- ResponseBased = "response_based",
290
- SpecificQuestion = "specific_question"
291
- }
292
- type NextQuestionBranching = {
293
- type: SurveyQuestionBranchingType.NextQuestion;
294
- };
295
- type EndBranching = {
296
- type: SurveyQuestionBranchingType.End;
297
- };
298
- type ResponseBasedBranching = {
299
- type: SurveyQuestionBranchingType.ResponseBased;
300
- responseValues: Record<string, any>;
301
- };
302
- type SpecificQuestionBranching = {
303
- type: SurveyQuestionBranchingType.SpecificQuestion;
304
- index: number;
305
- };
306
- type SurveyResponse = {
307
- surveys: Survey[];
308
- };
309
- declare enum SurveyMatchType {
310
- Regex = "regex",
311
- NotRegex = "not_regex",
312
- Exact = "exact",
313
- IsNot = "is_not",
314
- Icontains = "icontains",
315
- NotIcontains = "not_icontains"
316
- }
317
- type Survey = {
318
- id: string;
319
- name: string;
320
- description?: string;
321
- type: SurveyType;
322
- feature_flag_keys?: {
323
- key: string;
324
- value?: string;
325
- }[];
326
- linked_flag_key?: string;
327
- targeting_flag_key?: string;
328
- internal_targeting_flag_key?: string;
329
- questions: SurveyQuestion[];
330
- appearance?: SurveyAppearance;
331
- conditions?: {
332
- url?: string;
333
- selector?: string;
334
- seenSurveyWaitPeriodInDays?: number;
335
- urlMatchType?: SurveyMatchType;
336
- events?: {
337
- repeatedActivation?: boolean;
338
- values?: {
339
- name: string;
340
- }[];
341
- };
342
- actions?: {
343
- values: SurveyActionType[];
344
- };
345
- deviceTypes?: string[];
346
- deviceTypesMatchType?: SurveyMatchType;
347
- };
348
- start_date?: string;
349
- end_date?: string;
350
- current_iteration?: number;
351
- current_iteration_start_date?: string;
352
- };
353
- type SurveyActionType = {
354
- id: number;
355
- name?: string;
356
- steps?: ActionStepType[];
357
- };
358
- /** Sync with plugin-server/src/types.ts */
359
- declare enum ActionStepStringMatching {
360
- Contains = "contains",
361
- Exact = "exact",
362
- Regex = "regex"
363
- }
364
- type ActionStepType = {
365
- event?: string;
366
- selector?: string;
367
- /** @deprecated Only `selector` should be used now. */
368
- tag_name?: string;
369
- text?: string;
370
- /** @default StringMatching.Exact */
371
- text_matching?: ActionStepStringMatching;
372
- href?: string;
373
- /** @default ActionStepStringMatching.Exact */
374
- href_matching?: ActionStepStringMatching;
375
- url?: string;
376
- /** @default StringMatching.Contains */
377
- url_matching?: ActionStepStringMatching;
3
+ type PostHogCoreOptions = {
4
+ /** PostHog API host, usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' */
5
+ host?: string;
6
+ /** The number of events to queue before sending to PostHog (flushing) */
7
+ flushAt?: number;
8
+ /** The interval in milliseconds between periodic flushes */
9
+ flushInterval?: number;
10
+ /** The maximum number of queued messages to be flushed as part of a single batch (must be higher than `flushAt`) */
11
+ maxBatchSize?: number;
12
+ /** The maximum number of cached messages either in memory or on the local storage.
13
+ * Defaults to 1000, (must be higher than `flushAt`)
14
+ */
15
+ maxQueueSize?: number;
16
+ /** If set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) */
17
+ disabled?: boolean;
18
+ /** If set to false the SDK will not track until the `optIn` function is called. */
19
+ defaultOptIn?: boolean;
20
+ /** Whether to track that `getFeatureFlag` was called (used by Experiments) */
21
+ sendFeatureFlagEvent?: boolean;
22
+ /** Whether to load feature flags when initialized or not */
23
+ preloadFeatureFlags?: boolean;
24
+ /**
25
+ * Whether to load remote config when initialized or not
26
+ * Experimental support
27
+ * Default: false - Remote config is loaded by default
28
+ */
29
+ disableRemoteConfig?: boolean;
30
+ /**
31
+ * Whether to load surveys when initialized or not
32
+ * Experimental support
33
+ * Default: false - Surveys are loaded by default, but requires the `PostHogSurveyProvider` to be used
34
+ */
35
+ disableSurveys?: boolean;
36
+ /** Option to bootstrap the library with given distinctId and feature flags */
37
+ bootstrap?: {
38
+ distinctId?: string;
39
+ isIdentifiedId?: boolean;
40
+ featureFlags?: Record<string, FeatureFlagValue>;
41
+ featureFlagPayloads?: Record<string, JsonType>;
42
+ };
43
+ /** How many times we will retry HTTP requests. Defaults to 3. */
44
+ fetchRetryCount?: number;
45
+ /** The delay between HTTP request retries, Defaults to 3 seconds. */
46
+ fetchRetryDelay?: number;
47
+ /** Timeout in milliseconds for any calls. Defaults to 10 seconds. */
48
+ requestTimeout?: number;
49
+ /** Timeout in milliseconds for feature flag calls. Defaults to 10 seconds for stateful clients, and 3 seconds for stateless. */
50
+ featureFlagsRequestTimeoutMs?: number;
51
+ /** Timeout in milliseconds for remote config calls. Defaults to 3 seconds. */
52
+ remoteConfigRequestTimeoutMs?: number;
53
+ /** For Session Analysis how long before we expire a session (defaults to 30 mins) */
54
+ sessionExpirationTimeSeconds?: number;
55
+ /** Whether to disable GZIP compression */
56
+ disableCompression?: boolean;
57
+ disableGeoip?: boolean;
58
+ /** Special flag to indicate ingested data is for a historical migration. */
59
+ historicalMigration?: boolean;
60
+ };
61
+ declare enum PostHogPersistedProperty {
62
+ AnonymousId = "anonymous_id",
63
+ DistinctId = "distinct_id",
64
+ Props = "props",
65
+ FeatureFlagDetails = "feature_flag_details",
66
+ FeatureFlags = "feature_flags",
67
+ FeatureFlagPayloads = "feature_flag_payloads",
68
+ BootstrapFeatureFlagDetails = "bootstrap_feature_flag_details",
69
+ BootstrapFeatureFlags = "bootstrap_feature_flags",
70
+ BootstrapFeatureFlagPayloads = "bootstrap_feature_flag_payloads",
71
+ OverrideFeatureFlags = "override_feature_flags",
72
+ Queue = "queue",
73
+ OptedOut = "opted_out",
74
+ SessionId = "session_id",
75
+ SessionStartTimestamp = "session_start_timestamp",
76
+ SessionLastTimestamp = "session_timestamp",
77
+ PersonProperties = "person_properties",
78
+ GroupProperties = "group_properties",
79
+ InstalledAppBuild = "installed_app_build",
80
+ InstalledAppVersion = "installed_app_version",
81
+ SessionReplay = "session_replay",
82
+ SurveyLastSeenDate = "survey_last_seen_date",
83
+ SurveysSeen = "surveys_seen",
84
+ Surveys = "surveys",
85
+ RemoteConfig = "remote_config",
86
+ FlagsEndpointWasHit = "flags_endpoint_was_hit"
87
+ }
88
+ type PostHogFetchOptions = {
89
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH';
90
+ mode?: 'no-cors';
91
+ credentials?: 'omit';
92
+ headers: {
93
+ [key: string]: string;
94
+ };
95
+ body?: string | Blob;
96
+ signal?: AbortSignal;
97
+ };
98
+ type PostHogCaptureOptions = {
99
+ /** If provided overrides the auto-generated event ID */
100
+ uuid?: string;
101
+ /** If provided overrides the auto-generated timestamp */
102
+ timestamp?: Date;
103
+ disableGeoip?: boolean;
104
+ };
105
+ type PostHogFetchResponse = {
106
+ status: number;
107
+ text: () => Promise<string>;
108
+ json: () => Promise<any>;
109
+ };
110
+ type PostHogEventProperties = {
111
+ [key: string]: JsonType;
112
+ };
113
+ declare enum Compression {
114
+ GZipJS = "gzip-js",
115
+ Base64 = "base64"
116
+ }
117
+ type PostHogRemoteConfig = {
118
+ sessionRecording?: boolean | {
119
+ [key: string]: JsonType;
120
+ };
121
+ /**
122
+ * Supported compression algorithms
123
+ */
124
+ supportedCompression?: Compression[];
125
+ /**
126
+ * Whether surveys are enabled
127
+ */
128
+ surveys?: boolean | Survey[];
129
+ /**
130
+ * Indicates if the team has any flags enabled (if not we don't need to load them)
131
+ */
132
+ hasFeatureFlags?: boolean;
133
+ };
134
+ type FeatureFlagValue = string | boolean;
135
+ type PostHogFlagsResponse = Omit<PostHogRemoteConfig, 'surveys' | 'hasFeatureFlags'> & {
136
+ featureFlags: {
137
+ [key: string]: FeatureFlagValue;
138
+ };
139
+ featureFlagPayloads: {
140
+ [key: string]: JsonType;
141
+ };
142
+ flags: {
143
+ [key: string]: FeatureFlagDetail;
144
+ };
145
+ errorsWhileComputingFlags: boolean;
146
+ sessionRecording?: boolean | {
147
+ [key: string]: JsonType;
148
+ };
149
+ quotaLimited?: string[];
150
+ requestId?: string;
151
+ };
152
+ /**
153
+ * Creates a type with all properties of T, but makes only K properties required while the rest remain optional.
154
+ *
155
+ * @template T - The base type containing all properties
156
+ * @template K - Union type of keys from T that should be required
157
+ *
158
+ * @example
159
+ * interface User {
160
+ * id: number;
161
+ * name: string;
162
+ * email?: string;
163
+ * age?: number;
164
+ * }
165
+ *
166
+ * // Makes 'id' and 'name' required, but 'email' and 'age' optional
167
+ * type RequiredUser = PartialWithRequired<User, 'id' | 'name'>;
168
+ *
169
+ * const user: RequiredUser = {
170
+ * id: 1, // Must be provided
171
+ * name: "John" // Must be provided
172
+ * // email and age are optional
173
+ * };
174
+ */
175
+ type PartialWithRequired<T, K extends keyof T> = {
176
+ [P in K]: T[P];
177
+ } & {
178
+ [P in Exclude<keyof T, K>]?: T[P];
179
+ };
180
+ /**
181
+ * These are the fields we care about from PostHogFlagsResponse for feature flags.
182
+ */
183
+ type PostHogFeatureFlagDetails = PartialWithRequired<PostHogFlagsResponse, 'flags' | 'featureFlags' | 'featureFlagPayloads' | 'requestId'>;
184
+ /**
185
+ * Models legacy flags and payloads return type for many public methods.
186
+ */
187
+ type PostHogFlagsAndPayloadsResponse = Partial<Pick<PostHogFlagsResponse, 'featureFlags' | 'featureFlagPayloads'>>;
188
+ type JsonType = string | number | boolean | null | {
189
+ [key: string]: JsonType;
190
+ } | Array<JsonType> | JsonType[];
191
+ type FeatureFlagDetail = {
192
+ key: string;
193
+ enabled: boolean;
194
+ variant: string | undefined;
195
+ reason: EvaluationReason | undefined;
196
+ metadata: FeatureFlagMetadata | undefined;
197
+ };
198
+ type FeatureFlagMetadata = {
199
+ id: number | undefined;
200
+ version: number | undefined;
201
+ description: string | undefined;
202
+ payload: string | undefined;
203
+ };
204
+ type EvaluationReason = {
205
+ code: string | undefined;
206
+ condition_index: number | undefined;
207
+ description: string | undefined;
208
+ };
209
+ type SurveyAppearance = {
210
+ backgroundColor?: string;
211
+ submitButtonColor?: string;
212
+ submitButtonText?: string;
213
+ submitButtonTextColor?: string;
214
+ ratingButtonColor?: string;
215
+ ratingButtonActiveColor?: string;
216
+ autoDisappear?: boolean;
217
+ displayThankYouMessage?: boolean;
218
+ thankYouMessageHeader?: string;
219
+ thankYouMessageDescription?: string;
220
+ thankYouMessageDescriptionContentType?: SurveyQuestionDescriptionContentType;
221
+ thankYouMessageCloseButtonText?: string;
222
+ borderColor?: string;
223
+ position?: SurveyPosition;
224
+ placeholder?: string;
225
+ shuffleQuestions?: boolean;
226
+ surveyPopupDelaySeconds?: number;
227
+ widgetType?: SurveyWidgetType;
228
+ widgetSelector?: string;
229
+ widgetLabel?: string;
230
+ widgetColor?: string;
231
+ };
232
+ declare enum SurveyPosition {
233
+ Left = "left",
234
+ Right = "right",
235
+ Center = "center"
236
+ }
237
+ declare enum SurveyWidgetType {
238
+ Button = "button",
239
+ Tab = "tab",
240
+ Selector = "selector"
241
+ }
242
+ declare enum SurveyType {
243
+ Popover = "popover",
244
+ API = "api",
245
+ Widget = "widget"
246
+ }
247
+ type SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion;
248
+ declare enum SurveyQuestionDescriptionContentType {
249
+ Html = "html",
250
+ Text = "text"
251
+ }
252
+ type SurveyQuestionBase = {
253
+ question: string;
254
+ id?: string;
255
+ description?: string;
256
+ descriptionContentType?: SurveyQuestionDescriptionContentType;
257
+ optional?: boolean;
258
+ buttonText?: string;
259
+ originalQuestionIndex: number;
260
+ branching?: NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching;
261
+ };
262
+ type BasicSurveyQuestion = SurveyQuestionBase & {
263
+ type: SurveyQuestionType.Open;
264
+ };
265
+ type LinkSurveyQuestion = SurveyQuestionBase & {
266
+ type: SurveyQuestionType.Link;
267
+ link?: string;
268
+ };
269
+ type RatingSurveyQuestion = SurveyQuestionBase & {
270
+ type: SurveyQuestionType.Rating;
271
+ display: SurveyRatingDisplay;
272
+ scale: 3 | 5 | 7 | 10;
273
+ lowerBoundLabel: string;
274
+ upperBoundLabel: string;
275
+ };
276
+ declare enum SurveyRatingDisplay {
277
+ Number = "number",
278
+ Emoji = "emoji"
279
+ }
280
+ type MultipleSurveyQuestion = SurveyQuestionBase & {
281
+ type: SurveyQuestionType.SingleChoice | SurveyQuestionType.MultipleChoice;
282
+ choices: string[];
283
+ hasOpenChoice?: boolean;
284
+ shuffleOptions?: boolean;
285
+ };
286
+ declare enum SurveyQuestionType {
287
+ Open = "open",
288
+ MultipleChoice = "multiple_choice",
289
+ SingleChoice = "single_choice",
290
+ Rating = "rating",
291
+ Link = "link"
292
+ }
293
+ declare enum SurveyQuestionBranchingType {
294
+ NextQuestion = "next_question",
295
+ End = "end",
296
+ ResponseBased = "response_based",
297
+ SpecificQuestion = "specific_question"
298
+ }
299
+ type NextQuestionBranching = {
300
+ type: SurveyQuestionBranchingType.NextQuestion;
301
+ };
302
+ type EndBranching = {
303
+ type: SurveyQuestionBranchingType.End;
304
+ };
305
+ type ResponseBasedBranching = {
306
+ type: SurveyQuestionBranchingType.ResponseBased;
307
+ responseValues: Record<string, any>;
308
+ };
309
+ type SpecificQuestionBranching = {
310
+ type: SurveyQuestionBranchingType.SpecificQuestion;
311
+ index: number;
312
+ };
313
+ type SurveyResponse = {
314
+ surveys: Survey[];
315
+ };
316
+ declare enum SurveyMatchType {
317
+ Regex = "regex",
318
+ NotRegex = "not_regex",
319
+ Exact = "exact",
320
+ IsNot = "is_not",
321
+ Icontains = "icontains",
322
+ NotIcontains = "not_icontains"
323
+ }
324
+ type Survey = {
325
+ id: string;
326
+ name: string;
327
+ description?: string;
328
+ type: SurveyType;
329
+ feature_flag_keys?: {
330
+ key: string;
331
+ value?: string;
332
+ }[];
333
+ linked_flag_key?: string;
334
+ targeting_flag_key?: string;
335
+ internal_targeting_flag_key?: string;
336
+ questions: SurveyQuestion[];
337
+ appearance?: SurveyAppearance;
338
+ conditions?: {
339
+ url?: string;
340
+ selector?: string;
341
+ seenSurveyWaitPeriodInDays?: number;
342
+ urlMatchType?: SurveyMatchType;
343
+ events?: {
344
+ repeatedActivation?: boolean;
345
+ values?: {
346
+ name: string;
347
+ }[];
348
+ };
349
+ actions?: {
350
+ values: SurveyActionType[];
351
+ };
352
+ deviceTypes?: string[];
353
+ deviceTypesMatchType?: SurveyMatchType;
354
+ };
355
+ start_date?: string;
356
+ end_date?: string;
357
+ current_iteration?: number;
358
+ current_iteration_start_date?: string;
359
+ };
360
+ type SurveyActionType = {
361
+ id: number;
362
+ name?: string;
363
+ steps?: ActionStepType[];
364
+ };
365
+ /** Sync with plugin-server/src/types.ts */
366
+ declare enum ActionStepStringMatching {
367
+ Contains = "contains",
368
+ Exact = "exact",
369
+ Regex = "regex"
370
+ }
371
+ type ActionStepType = {
372
+ event?: string;
373
+ selector?: string;
374
+ text?: string;
375
+ /** @default StringMatching.Exact */
376
+ text_matching?: ActionStepStringMatching;
377
+ href?: string;
378
+ /** @default ActionStepStringMatching.Exact */
379
+ href_matching?: ActionStepStringMatching;
380
+ url?: string;
381
+ /** @default StringMatching.Contains */
382
+ url_matching?: ActionStepStringMatching;
378
383
  };
379
384
 
380
- interface RetriableOptions {
381
- retryCount: number;
382
- retryDelay: number;
383
- retryCheck: (err: any) => boolean;
385
+ declare const severityLevels: readonly ["fatal", "error", "warning", "log", "info", "debug"];
386
+ declare type SeverityLevel = (typeof severityLevels)[number];
387
+ interface EventHint {
388
+ mechanism?: Partial<Mechanism>;
389
+ syntheticException?: Error | null;
390
+ }
391
+ interface Mechanism {
392
+ handled?: boolean;
393
+ type?: string;
394
+ source?: string;
395
+ synthetic?: boolean;
396
+ }
397
+ type StackParser = (stack: string, skipFirstLines?: number) => StackFrame[];
398
+ type StackFrameModifierFn = (frames: StackFrame[]) => Promise<StackFrame[]>;
399
+ interface StackFrame {
400
+ platform: string;
401
+ filename?: string;
402
+ function?: string;
403
+ module?: string;
404
+ lineno?: number;
405
+ colno?: number;
406
+ abs_path?: string;
407
+ context_line?: string;
408
+ pre_context?: string[];
409
+ post_context?: string[];
410
+ in_app?: boolean;
411
+ instruction_addr?: string;
412
+ addr_mode?: string;
413
+ vars?: {
414
+ [key: string]: JsonType;
415
+ };
416
+ chunk_id?: string;
384
417
  }
385
418
 
386
- declare class SimpleEventEmitter {
387
- events: {
388
- [key: string]: ((...args: any[]) => void)[];
389
- };
390
- constructor();
391
- on(event: string, listener: (...args: any[]) => void): () => void;
392
- emit(event: string, payload: any): void;
419
+ interface RetriableOptions {
420
+ retryCount: number;
421
+ retryDelay: number;
422
+ retryCheck: (err: unknown) => boolean;
393
423
  }
394
424
 
395
- declare abstract class PostHogCoreStateless {
396
- readonly apiKey: string;
397
- readonly host: string;
398
- readonly flushAt: number;
399
- readonly preloadFeatureFlags: boolean;
400
- readonly disableSurveys: boolean;
401
- private maxBatchSize;
402
- private maxQueueSize;
403
- private flushInterval;
404
- private flushPromise;
405
- private requestTimeout;
406
- private featureFlagsRequestTimeoutMs;
407
- private remoteConfigRequestTimeoutMs;
408
- private captureMode;
409
- private removeDebugCallback?;
410
- private disableGeoip;
411
- private historicalMigration;
412
- protected disabled: boolean;
413
- private defaultOptIn;
414
- private pendingPromises;
415
- protected _events: SimpleEventEmitter;
416
- protected _flushTimer?: any;
417
- protected _retryOptions: RetriableOptions;
418
- protected _initPromise: Promise<void>;
419
- protected _isInitialized: boolean;
420
- protected _remoteConfigResponsePromise?: Promise<PostHogRemoteConfig | undefined>;
421
- abstract fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse>;
422
- abstract getLibraryId(): string;
423
- abstract getLibraryVersion(): string;
424
- abstract getCustomUserAgent(): string | void;
425
- abstract getPersistedProperty<T>(key: PostHogPersistedProperty): T | undefined;
426
- abstract setPersistedProperty<T>(key: PostHogPersistedProperty, value: T | null): void;
427
- constructor(apiKey: string, options?: PostHogCoreOptions);
428
- protected logMsgIfDebug(fn: () => void): void;
429
- protected wrap(fn: () => void): void;
430
- protected getCommonEventProperties(): any;
431
- get optedOut(): boolean;
432
- optIn(): Promise<void>;
433
- optOut(): Promise<void>;
434
- on(event: string, cb: (...args: any[]) => void): () => void;
435
- debug(enabled?: boolean): void;
436
- get isDebug(): boolean;
437
- get isDisabled(): boolean;
438
- private buildPayload;
439
- protected addPendingPromise<T>(promise: Promise<T>): Promise<T>;
440
- /***
441
- *** TRACKING
442
- ***/
443
- protected identifyStateless(distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void;
444
- protected captureStateless(distinctId: string, event: string, properties?: {
445
- [key: string]: any;
446
- }, options?: PostHogCaptureOptions): void;
447
- protected aliasStateless(alias: string, distinctId: string, properties?: {
448
- [key: string]: any;
449
- }, options?: PostHogCaptureOptions): void;
450
- /***
451
- *** GROUPS
452
- ***/
453
- protected groupIdentifyStateless(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties, options?: PostHogCaptureOptions, distinctId?: string, eventProperties?: PostHogEventProperties): void;
454
- protected getRemoteConfig(): Promise<PostHogRemoteConfig | undefined>;
455
- /***
456
- *** FEATURE FLAGS
457
- ***/
458
- protected getDecide(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, extraPayload?: Record<string, any>): Promise<PostHogDecideResponse | undefined>;
459
- protected getFeatureFlagStateless(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean): Promise<{
460
- response: FeatureFlagValue | undefined;
461
- requestId: string | undefined;
462
- }>;
463
- protected getFeatureFlagDetailStateless(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean): Promise<{
464
- response: FeatureFlagDetail | undefined;
465
- requestId: string | undefined;
466
- } | undefined>;
467
- protected getFeatureFlagPayloadStateless(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean): Promise<JsonType | undefined>;
468
- protected getFeatureFlagPayloadsStateless(distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<PostHogDecideResponse['featureFlagPayloads'] | undefined>;
469
- protected getFeatureFlagsStateless(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<{
470
- flags: PostHogDecideResponse['featureFlags'] | undefined;
471
- payloads: PostHogDecideResponse['featureFlagPayloads'] | undefined;
472
- requestId: PostHogDecideResponse['requestId'] | undefined;
473
- }>;
474
- protected getFeatureFlagsAndPayloadsStateless(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<{
475
- flags: PostHogDecideResponse['featureFlags'] | undefined;
476
- payloads: PostHogDecideResponse['featureFlagPayloads'] | undefined;
477
- requestId: PostHogDecideResponse['requestId'] | undefined;
478
- }>;
479
- protected getFeatureFlagDetailsStateless(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<PostHogFeatureFlagDetails | undefined>;
480
- /***
481
- *** SURVEYS
482
- ***/
483
- getSurveysStateless(): Promise<SurveyResponse['surveys']>;
484
- /***
485
- *** SUPER PROPERTIES
486
- ***/
487
- private _props;
488
- protected get props(): PostHogEventProperties;
489
- protected set props(val: PostHogEventProperties | undefined);
490
- register(properties: {
491
- [key: string]: any;
492
- }): Promise<void>;
493
- unregister(property: string): Promise<void>;
494
- /***
495
- *** QUEUEING AND FLUSHING
496
- ***/
497
- protected enqueue(type: string, _message: any, options?: PostHogCaptureOptions): void;
498
- private clearFlushTimer;
499
- /**
500
- * Helper for flushing the queue in the background
501
- * Avoids unnecessary promise errors
502
- */
503
- private flushBackground;
504
- flush(): Promise<any[]>;
505
- protected getCustomHeaders(): {
506
- [key: string]: string;
507
- };
508
- private _flush;
509
- private fetchWithRetry;
510
- shutdown(shutdownTimeoutMs?: number): Promise<void>;
425
+ declare class SimpleEventEmitter {
426
+ events: {
427
+ [key: string]: ((...args: any[]) => void)[];
428
+ };
429
+ constructor();
430
+ on(event: string, listener: (...args: any[]) => void): () => void;
431
+ emit(event: string, payload: any): void;
511
432
  }
512
433
 
513
- interface IdentifyMessage {
514
- distinctId: string;
515
- properties?: Record<string | number, any>;
516
- disableGeoip?: boolean;
517
- }
518
- interface EventMessage extends IdentifyMessage {
519
- event: string;
520
- groups?: Record<string, string | number>;
521
- sendFeatureFlags?: boolean;
522
- timestamp?: Date;
523
- uuid?: string;
524
- }
525
- interface GroupIdentifyMessage {
526
- groupType: string;
527
- groupKey: string;
528
- properties?: Record<string | number, any>;
529
- distinctId?: string;
530
- disableGeoip?: boolean;
531
- }
532
- type PostHogNodeV1 = {
533
- /**
534
- * @description Capture allows you to capture anything a user does within your system,
535
- * which you can later use in PostHog to find patterns in usage,
536
- * work out which features to improve or where people are giving up.
537
- * A capture call requires:
538
- * @param distinctId which uniquely identifies your user
539
- * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on.
540
- * @param properties OPTIONAL | which can be a object with any information you'd like to add
541
- * @param groups OPTIONAL | object of what groups are related to this event, example: { company: 'id:5' }. Can be used to analyze companies instead of users.
542
- * @param sendFeatureFlags OPTIONAL | Used with experiments. Determines whether to send feature flag values with the event.
543
- */
544
- capture({ distinctId, event, properties, groups, sendFeatureFlags }: EventMessage): void;
545
- /**
546
- * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog,
547
- * and even do things like segment users by these properties.
548
- * An identify call requires:
549
- * @param distinctId which uniquely identifies your user
550
- * @param properties with a dict with any key: value pairs
551
- */
552
- identify({ distinctId, properties }: IdentifyMessage): void;
553
- /**
554
- * @description To marry up whatever a user does before they sign up or log in with what they do after you need to make an alias call.
555
- * This will allow you to answer questions like "Which marketing channels leads to users churning after a month?"
556
- * or "What do users do on our website before signing up?"
557
- * In a purely back-end implementation, this means whenever an anonymous user does something, you'll want to send a session ID with the capture call.
558
- * Then, when that users signs up, you want to do an alias call with the session ID and the newly created user ID.
559
- * The same concept applies for when a user logs in. If you're using PostHog in the front-end and back-end,
560
- * doing the identify call in the frontend will be enough.:
561
- * @param distinctId the current unique id
562
- * @param alias the unique ID of the user before
563
- */
564
- alias(data: {
565
- distinctId: string;
566
- alias: string;
567
- }): void;
568
- /**
569
- * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
570
- * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
571
- * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
572
- * features on and off for different user groups or individual users.
573
- * @param key the unique key of your feature flag
574
- * @param distinctId the current unique id
575
- * @param options: dict with optional parameters below
576
- * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups.
577
- * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present.
578
- * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present.
579
- * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
580
- * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true.
581
- *
582
- * @returns true if the flag is on, false if the flag is off, undefined if there was an error.
583
- */
584
- isFeatureEnabled(key: string, distinctId: string, options?: {
585
- groups?: Record<string, string>;
586
- personProperties?: Record<string, string>;
587
- groupProperties?: Record<string, Record<string, string>>;
588
- onlyEvaluateLocally?: boolean;
589
- sendFeatureFlagEvents?: boolean;
590
- }): Promise<boolean | undefined>;
591
- /**
592
- * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
593
- * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
594
- * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
595
- * features on and off for different user groups or individual users.
596
- * @param key the unique key of your feature flag
597
- * @param distinctId the current unique id
598
- * @param options: dict with optional parameters below
599
- * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups.
600
- * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present.
601
- * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present.
602
- * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
603
- * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true.
604
- *
605
- * @returns true or string(for multivariates) if the flag is on, false if the flag is off, undefined if there was an error.
606
- */
607
- getFeatureFlag(key: string, distinctId: string, options?: {
608
- groups?: Record<string, string>;
609
- personProperties?: Record<string, string>;
610
- groupProperties?: Record<string, Record<string, string>>;
611
- onlyEvaluateLocally?: boolean;
612
- sendFeatureFlagEvents?: boolean;
613
- }): Promise<FeatureFlagValue | undefined>;
614
- /**
615
- * @description Retrieves payload associated with the specified flag and matched value that is passed in.
616
- *
617
- * IMPORTANT: The `matchValue` parameter should be the value you previously obtained from `getFeatureFlag()`.
618
- * If matchValue isn't passed (or is undefined), this method will automatically call `getFeatureFlag()`
619
- * internally to fetch the flag value, which could result in a network call to the PostHog server if this flag can
620
- * not be evaluated locally. This means that omitting `matchValue` will potentially:
621
- * - Bypass local evaluation
622
- * - Count as an additional flag evaluation against your quota
623
- * - Impact performance due to the extra network request
624
- *
625
- * Example usage:
626
- * ```js
627
- * const flagValue = await client.getFeatureFlag('my-flag', distinctId);
628
- * const payload = await client.getFeatureFlagPayload('my-flag', distinctId, flagValue);
629
- * ```
630
- *
631
- * @param key the unique key of your feature flag
632
- * @param distinctId the current unique id
633
- * @param matchValue The flag value previously obtained from calling `getFeatureFlag()`. Can be a string or boolean.
634
- * To avoid extra network calls, pass this parameter when you can.
635
- * @param options: dict with optional parameters below
636
- * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
637
- *
638
- * @returns payload of a json type object
639
- */
640
- getFeatureFlagPayload(key: string, distinctId: string, matchValue?: FeatureFlagValue, options?: {
641
- onlyEvaluateLocally?: boolean;
642
- }): Promise<JsonType | undefined>;
643
- /**
644
- * @description Sets a groups properties, which allows asking questions like "Who are the most active companies"
645
- * using my product in PostHog.
646
- *
647
- * @param groupType Type of group (ex: 'company'). Limited to 5 per project
648
- * @param groupKey Unique identifier for that type of group (ex: 'id:5')
649
- * @param properties OPTIONAL | which can be a object with any information you'd like to add
650
- */
651
- groupIdentify({ groupType, groupKey, properties }: GroupIdentifyMessage): void;
652
- /**
653
- * @description Force an immediate reload of the polled feature flags. Please note that they are
654
- * already polled automatically at a regular interval.
655
- */
656
- reloadFeatureFlags(): Promise<void>;
657
- /**
658
- * @description Flushes the events still in the queue and clears the feature flags poller to allow for
659
- * a clean shutdown.
660
- *
661
- * @param shutdownTimeoutMs The shutdown timeout, in milliseconds. Defaults to 30000 (30s).
662
- */
663
- shutdown(shutdownTimeoutMs?: number): void;
664
- /**
665
- * @description Waits for local evaluation to be ready, with an optional timeout.
666
- * @param timeoutMs - Maximum time to wait in milliseconds. Defaults to 30 seconds.
667
- * @returns A promise that resolves to true if local evaluation is ready, false if the timeout was reached.
668
- */
669
- waitForLocalEvaluationReady(timeoutMs?: number): Promise<boolean>;
670
- /**
671
- * @description Returns true if local evaluation is ready, false if it's not.
672
- * @returns true if local evaluation is ready, false if it's not.
673
- */
674
- isLocalEvaluationReady(): boolean;
675
- };
434
+ declare abstract class PostHogCoreStateless {
435
+ readonly apiKey: string;
436
+ readonly host: string;
437
+ readonly flushAt: number;
438
+ readonly preloadFeatureFlags: boolean;
439
+ readonly disableSurveys: boolean;
440
+ private maxBatchSize;
441
+ private maxQueueSize;
442
+ private flushInterval;
443
+ private flushPromise;
444
+ private shutdownPromise;
445
+ private requestTimeout;
446
+ private featureFlagsRequestTimeoutMs;
447
+ private remoteConfigRequestTimeoutMs;
448
+ private removeDebugCallback?;
449
+ private disableGeoip;
450
+ private historicalMigration;
451
+ protected disabled: boolean;
452
+ protected disableCompression: boolean;
453
+ private defaultOptIn;
454
+ private pendingPromises;
455
+ protected _events: SimpleEventEmitter;
456
+ protected _flushTimer?: any;
457
+ protected _retryOptions: RetriableOptions;
458
+ protected _initPromise: Promise<void>;
459
+ protected _isInitialized: boolean;
460
+ protected _remoteConfigResponsePromise?: Promise<PostHogRemoteConfig | undefined>;
461
+ abstract fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse>;
462
+ abstract getLibraryId(): string;
463
+ abstract getLibraryVersion(): string;
464
+ abstract getCustomUserAgent(): string | void;
465
+ abstract getPersistedProperty<T>(key: PostHogPersistedProperty): T | undefined;
466
+ abstract setPersistedProperty<T>(key: PostHogPersistedProperty, value: T | null): void;
467
+ constructor(apiKey: string, options?: PostHogCoreOptions);
468
+ protected logMsgIfDebug(fn: () => void): void;
469
+ protected wrap(fn: () => void): void;
470
+ protected getCommonEventProperties(): PostHogEventProperties;
471
+ get optedOut(): boolean;
472
+ optIn(): Promise<void>;
473
+ optOut(): Promise<void>;
474
+ on(event: string, cb: (...args: any[]) => void): () => void;
475
+ debug(enabled?: boolean): void;
476
+ get isDebug(): boolean;
477
+ get isDisabled(): boolean;
478
+ private buildPayload;
479
+ protected addPendingPromise<T>(promise: Promise<T>): Promise<T>;
480
+ /***
481
+ *** TRACKING
482
+ ***/
483
+ protected identifyStateless(distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void;
484
+ protected identifyStatelessImmediate(distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): Promise<void>;
485
+ protected captureStateless(distinctId: string, event: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void;
486
+ protected captureStatelessImmediate(distinctId: string, event: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): Promise<void>;
487
+ protected aliasStateless(alias: string, distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): void;
488
+ protected aliasStatelessImmediate(alias: string, distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): Promise<void>;
489
+ /***
490
+ *** GROUPS
491
+ ***/
492
+ protected groupIdentifyStateless(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties, options?: PostHogCaptureOptions, distinctId?: string, eventProperties?: PostHogEventProperties): void;
493
+ protected getRemoteConfig(): Promise<PostHogRemoteConfig | undefined>;
494
+ /***
495
+ *** FEATURE FLAGS
496
+ ***/
497
+ protected getFlags(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, extraPayload?: Record<string, any>): Promise<PostHogFlagsResponse | undefined>;
498
+ protected getFeatureFlagStateless(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean): Promise<{
499
+ response: FeatureFlagValue | undefined;
500
+ requestId: string | undefined;
501
+ }>;
502
+ protected getFeatureFlagDetailStateless(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean): Promise<{
503
+ response: FeatureFlagDetail | undefined;
504
+ requestId: string | undefined;
505
+ } | undefined>;
506
+ protected getFeatureFlagPayloadStateless(key: string, distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean): Promise<JsonType | undefined>;
507
+ protected getFeatureFlagPayloadsStateless(distinctId: string, groups?: Record<string, string>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<PostHogFlagsResponse['featureFlagPayloads'] | undefined>;
508
+ protected getFeatureFlagsStateless(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<{
509
+ flags: PostHogFlagsResponse['featureFlags'] | undefined;
510
+ payloads: PostHogFlagsResponse['featureFlagPayloads'] | undefined;
511
+ requestId: PostHogFlagsResponse['requestId'] | undefined;
512
+ }>;
513
+ protected getFeatureFlagsAndPayloadsStateless(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<{
514
+ flags: PostHogFlagsResponse['featureFlags'] | undefined;
515
+ payloads: PostHogFlagsResponse['featureFlagPayloads'] | undefined;
516
+ requestId: PostHogFlagsResponse['requestId'] | undefined;
517
+ }>;
518
+ protected getFeatureFlagDetailsStateless(distinctId: string, groups?: Record<string, string | number>, personProperties?: Record<string, string>, groupProperties?: Record<string, Record<string, string>>, disableGeoip?: boolean, flagKeysToEvaluate?: string[]): Promise<PostHogFeatureFlagDetails | undefined>;
519
+ /***
520
+ *** SURVEYS
521
+ ***/
522
+ getSurveysStateless(): Promise<SurveyResponse['surveys']>;
523
+ /***
524
+ *** SUPER PROPERTIES
525
+ ***/
526
+ private _props;
527
+ protected get props(): PostHogEventProperties;
528
+ protected set props(val: PostHogEventProperties | undefined);
529
+ register(properties: PostHogEventProperties): Promise<void>;
530
+ unregister(property: string): Promise<void>;
531
+ /***
532
+ *** QUEUEING AND FLUSHING
533
+ ***/
534
+ protected enqueue(type: string, _message: any, options?: PostHogCaptureOptions): void;
535
+ protected sendImmediate(type: string, _message: any, options?: PostHogCaptureOptions): Promise<void>;
536
+ private prepareMessage;
537
+ private clearFlushTimer;
538
+ /**
539
+ * Helper for flushing the queue in the background
540
+ * Avoids unnecessary promise errors
541
+ */
542
+ private flushBackground;
543
+ /**
544
+ * Flushes the queue
545
+ *
546
+ * This function will return a promise that will resolve when the flush is complete,
547
+ * or reject if there was an error (for example if the server or network is down).
548
+ *
549
+ * If there is already a flush in progress, this function will wait for that flush to complete.
550
+ *
551
+ * It's recommended to do error handling in the callback of the promise.
552
+ *
553
+ * @example
554
+ * posthog.flush().then(() => {
555
+ * console.log('Flush complete')
556
+ * }).catch((err) => {
557
+ * console.error('Flush failed', err)
558
+ * })
559
+ *
560
+ *
561
+ * @throws PostHogFetchHttpError
562
+ * @throws PostHogFetchNetworkError
563
+ * @throws Error
564
+ */
565
+ flush(): Promise<void>;
566
+ protected getCustomHeaders(): {
567
+ [key: string]: string;
568
+ };
569
+ private _flush;
570
+ private fetchWithRetry;
571
+ _shutdown(shutdownTimeoutMs?: number): Promise<void>;
572
+ /**
573
+ * Call shutdown() once before the node process exits, so ensure that all events have been sent and all promises
574
+ * have resolved. Do not use this function if you intend to keep using this PostHog instance after calling it.
575
+ * @param shutdownTimeoutMs
576
+ */
577
+ shutdown(shutdownTimeoutMs?: number): Promise<void>;
578
+ }
676
579
 
677
- interface EventHint {
678
- mechanism?: Partial<Mechanism>;
679
- syntheticException?: Error | null;
680
- }
681
- interface Mechanism {
682
- handled?: boolean;
683
- type?: string;
684
- source?: string;
685
- synthetic?: boolean;
580
+ interface IdentifyMessage {
581
+ distinctId: string;
582
+ properties?: Record<string | number, any>;
583
+ disableGeoip?: boolean;
584
+ }
585
+ interface EventMessage extends IdentifyMessage {
586
+ event: string;
587
+ groups?: Record<string, string | number>;
588
+ sendFeatureFlags?: boolean;
589
+ timestamp?: Date;
590
+ uuid?: string;
591
+ }
592
+ interface GroupIdentifyMessage {
593
+ groupType: string;
594
+ groupKey: string;
595
+ properties?: Record<string | number, any>;
596
+ distinctId?: string;
597
+ disableGeoip?: boolean;
598
+ }
599
+ type PropertyGroup = {
600
+ type: 'AND' | 'OR';
601
+ values: PropertyGroup[] | FlagProperty[];
602
+ };
603
+ type FlagProperty = {
604
+ key: string;
605
+ type?: string;
606
+ value: string | number | (string | number)[];
607
+ operator?: string;
608
+ negation?: boolean;
609
+ };
610
+ type FeatureFlagCondition = {
611
+ properties: FlagProperty[];
612
+ rollout_percentage?: number;
613
+ variant?: string;
614
+ };
615
+ type PostHogOptions = PostHogCoreOptions & {
616
+ persistence?: 'memory';
617
+ personalApiKey?: string;
618
+ privacyMode?: boolean;
619
+ enableExceptionAutocapture?: boolean;
620
+ featureFlagsPollingInterval?: number;
621
+ maxCacheSize?: number;
622
+ fetch?: (url: string, options: PostHogFetchOptions) => Promise<PostHogFetchResponse>;
623
+ };
624
+ type PostHogFeatureFlag = {
625
+ id: number;
626
+ name: string;
627
+ key: string;
628
+ filters?: {
629
+ aggregation_group_type_index?: number;
630
+ groups?: FeatureFlagCondition[];
631
+ multivariate?: {
632
+ variants: {
633
+ key: string;
634
+ rollout_percentage: number;
635
+ }[];
636
+ };
637
+ payloads?: Record<string, string>;
638
+ };
639
+ deleted: boolean;
640
+ active: boolean;
641
+ rollout_percentage: null | number;
642
+ ensure_experience_continuity: boolean;
643
+ experiment_set: number[];
644
+ };
645
+ interface IPostHog {
646
+ /**
647
+ * @description Capture allows you to capture anything a user does within your system,
648
+ * which you can later use in PostHog to find patterns in usage,
649
+ * work out which features to improve or where people are giving up.
650
+ * A capture call requires:
651
+ * @param distinctId which uniquely identifies your user
652
+ * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on.
653
+ * @param properties OPTIONAL | which can be a object with any information you'd like to add
654
+ * @param groups OPTIONAL | object of what groups are related to this event, example: { company: 'id:5' }. Can be used to analyze companies instead of users.
655
+ * @param sendFeatureFlags OPTIONAL | Used with experiments. Determines whether to send feature flag values with the event.
656
+ */
657
+ capture({ distinctId, event, properties, groups, sendFeatureFlags }: EventMessage): void;
658
+ /**
659
+ * @description Capture an event immediately. Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls.
660
+ * @param distinctId which uniquely identifies your user
661
+ * @param event We recommend using [verb] [noun], like movie played or movie updated to easily identify what your events mean later on.
662
+ * @param properties OPTIONAL | which can be a object with any information you'd like to add
663
+ * @param groups OPTIONAL | object of what groups are related to this event, example: { company: 'id:5' }. Can be used to analyze companies instead of users.
664
+ * @param sendFeatureFlags OPTIONAL | Used with experiments. Determines whether to send feature flag values with the event.
665
+ */
666
+ captureImmediate({ distinctId, event, properties, groups, sendFeatureFlags }: EventMessage): Promise<void>;
667
+ /**
668
+ * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog,
669
+ * and even do things like segment users by these properties.
670
+ * An identify call requires:
671
+ * @param distinctId which uniquely identifies your user
672
+ * @param properties with a dict with any key: value pairs
673
+ */
674
+ identify({ distinctId, properties }: IdentifyMessage): void;
675
+ /**
676
+ * @description Identify lets you add metadata on your users so you can more easily identify who they are in PostHog.
677
+ * Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls.
678
+ * @param distinctId which uniquely identifies your user
679
+ * @param properties with a dict with any key: value pairs
680
+ */
681
+ identifyImmediate({ distinctId, properties }: IdentifyMessage): Promise<void>;
682
+ /**
683
+ * @description To marry up whatever a user does before they sign up or log in with what they do after you need to make an alias call.
684
+ * This will allow you to answer questions like "Which marketing channels leads to users churning after a month?"
685
+ * or "What do users do on our website before signing up?"
686
+ * In a purely back-end implementation, this means whenever an anonymous user does something, you'll want to send a session ID with the capture call.
687
+ * Then, when that users signs up, you want to do an alias call with the session ID and the newly created user ID.
688
+ * The same concept applies for when a user logs in. If you're using PostHog in the front-end and back-end,
689
+ * doing the identify call in the frontend will be enough.:
690
+ * @param distinctId the current unique id
691
+ * @param alias the unique ID of the user before
692
+ */
693
+ alias(data: {
694
+ distinctId: string;
695
+ alias: string;
696
+ }): void;
697
+ /**
698
+ * @description To marry up whatever a user does before they sign up or log in with what they do after you need to make an alias call.
699
+ * Useful for edge environments where the usual queue-based sending is not preferable. Do not mix immediate and non-immediate calls.
700
+ * @param distinctId the current unique id
701
+ * @param alias the unique ID of the user before
702
+ */
703
+ aliasImmediate(data: {
704
+ distinctId: string;
705
+ alias: string;
706
+ }): Promise<void>;
707
+ /**
708
+ * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
709
+ * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
710
+ * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
711
+ * features on and off for different user groups or individual users.
712
+ * @param key the unique key of your feature flag
713
+ * @param distinctId the current unique id
714
+ * @param options: dict with optional parameters below
715
+ * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups.
716
+ * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present.
717
+ * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present.
718
+ * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
719
+ * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true.
720
+ *
721
+ * @returns true if the flag is on, false if the flag is off, undefined if there was an error.
722
+ */
723
+ isFeatureEnabled(key: string, distinctId: string, options?: {
724
+ groups?: Record<string, string>;
725
+ personProperties?: Record<string, string>;
726
+ groupProperties?: Record<string, Record<string, string>>;
727
+ onlyEvaluateLocally?: boolean;
728
+ sendFeatureFlagEvents?: boolean;
729
+ }): Promise<boolean | undefined>;
730
+ /**
731
+ * @description PostHog feature flags (https://posthog.com/docs/features/feature-flags)
732
+ * allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog,
733
+ * you can use this method to check if the flag is on for a given user, allowing you to create logic to turn
734
+ * features on and off for different user groups or individual users.
735
+ * @param key the unique key of your feature flag
736
+ * @param distinctId the current unique id
737
+ * @param options: dict with optional parameters below
738
+ * @param groups optional - what groups are currently active (group analytics). Required if the flag depends on groups.
739
+ * @param personProperties optional - what person properties are known. Used to compute flags locally, if personalApiKey is present.
740
+ * @param groupProperties optional - what group properties are known. Used to compute flags locally, if personalApiKey is present.
741
+ * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
742
+ * @param sendFeatureFlagEvents optional - whether to send feature flag events. Used for Experiments. Defaults to true.
743
+ *
744
+ * @returns true or string(for multivariates) if the flag is on, false if the flag is off, undefined if there was an error.
745
+ */
746
+ getFeatureFlag(key: string, distinctId: string, options?: {
747
+ groups?: Record<string, string>;
748
+ personProperties?: Record<string, string>;
749
+ groupProperties?: Record<string, Record<string, string>>;
750
+ onlyEvaluateLocally?: boolean;
751
+ sendFeatureFlagEvents?: boolean;
752
+ }): Promise<FeatureFlagValue | undefined>;
753
+ /**
754
+ * @description Retrieves payload associated with the specified flag and matched value that is passed in.
755
+ *
756
+ * IMPORTANT: The `matchValue` parameter should be the value you previously obtained from `getFeatureFlag()`.
757
+ * If matchValue isn't passed (or is undefined), this method will automatically call `getFeatureFlag()`
758
+ * internally to fetch the flag value, which could result in a network call to the PostHog server if this flag can
759
+ * not be evaluated locally. This means that omitting `matchValue` will potentially:
760
+ * - Bypass local evaluation
761
+ * - Count as an additional flag evaluation against your quota
762
+ * - Impact performance due to the extra network request
763
+ *
764
+ * Example usage:
765
+ * ```js
766
+ * const flagValue = await client.getFeatureFlag('my-flag', distinctId);
767
+ * const payload = await client.getFeatureFlagPayload('my-flag', distinctId, flagValue);
768
+ * ```
769
+ *
770
+ * @param key the unique key of your feature flag
771
+ * @param distinctId the current unique id
772
+ * @param matchValue The flag value previously obtained from calling `getFeatureFlag()`. Can be a string or boolean.
773
+ * To avoid extra network calls, pass this parameter when you can.
774
+ * @param options: dict with optional parameters below
775
+ * @param onlyEvaluateLocally optional - whether to only evaluate the flag locally. Defaults to false.
776
+ *
777
+ * @returns payload of a json type object
778
+ */
779
+ getFeatureFlagPayload(key: string, distinctId: string, matchValue?: FeatureFlagValue, options?: {
780
+ onlyEvaluateLocally?: boolean;
781
+ }): Promise<JsonType | undefined>;
782
+ /**
783
+ * @description Sets a groups properties, which allows asking questions like "Who are the most active companies"
784
+ * using my product in PostHog.
785
+ *
786
+ * @param groupType Type of group (ex: 'company'). Limited to 5 per project
787
+ * @param groupKey Unique identifier for that type of group (ex: 'id:5')
788
+ * @param properties OPTIONAL | which can be a object with any information you'd like to add
789
+ */
790
+ groupIdentify({ groupType, groupKey, properties }: GroupIdentifyMessage): void;
791
+ /**
792
+ * @description Force an immediate reload of the polled feature flags. Please note that they are
793
+ * already polled automatically at a regular interval.
794
+ */
795
+ reloadFeatureFlags(): Promise<void>;
796
+ /**
797
+ * @description Flushes the events still in the queue and clears the feature flags poller to allow for
798
+ * a clean shutdown.
799
+ *
800
+ * @param shutdownTimeoutMs The shutdown timeout, in milliseconds. Defaults to 30000 (30s).
801
+ */
802
+ shutdown(shutdownTimeoutMs?: number): void;
803
+ /**
804
+ * @description Waits for local evaluation to be ready, with an optional timeout.
805
+ * @param timeoutMs - Maximum time to wait in milliseconds. Defaults to 30 seconds.
806
+ * @returns A promise that resolves to true if local evaluation is ready, false if the timeout was reached.
807
+ */
808
+ waitForLocalEvaluationReady(timeoutMs?: number): Promise<boolean>;
809
+ /**
810
+ * @description Returns true if local evaluation is ready, false if it's not.
811
+ * @returns true if local evaluation is ready, false if it's not.
812
+ */
813
+ isLocalEvaluationReady(): boolean;
686
814
  }
687
815
 
688
- declare class ErrorTracking {
689
- private client;
690
- private _exceptionAutocaptureEnabled;
691
- static captureException(client: PostHog, error: unknown, hint: EventHint, distinctId?: string, additionalProperties?: Record<string | number, any>): Promise<void>;
692
- constructor(client: PostHog, options: PostHogOptions);
693
- private startAutocaptureIfEnabled;
694
- private onException;
695
- private onFatalError;
696
- isEnabled(): boolean;
816
+ declare class ErrorTracking {
817
+ private client;
818
+ private _exceptionAutocaptureEnabled;
819
+ static stackParser: StackParser;
820
+ static frameModifiers: StackFrameModifierFn[];
821
+ static captureException(client: PostHogBackendClient, error: unknown, hint: EventHint, distinctId?: string, additionalProperties?: Record<string | number, any>): Promise<void>;
822
+ constructor(client: PostHogBackendClient, options: PostHogOptions);
823
+ private startAutocaptureIfEnabled;
824
+ private onException;
825
+ private onFatalError;
826
+ isEnabled(): boolean;
697
827
  }
698
828
 
699
- type PostHogOptions = PostHogCoreOptions & {
700
- persistence?: 'memory';
701
- personalApiKey?: string;
702
- privacyMode?: boolean;
703
- enableExceptionAutocapture?: boolean;
704
- featureFlagsPollingInterval?: number;
705
- maxCacheSize?: number;
706
- fetch?: (url: string, options: PostHogFetchOptions) => Promise<PostHogFetchResponse>;
707
- };
708
- declare const MINIMUM_POLLING_INTERVAL = 100;
709
- declare const THIRTY_SECONDS: number;
710
- declare const SIXTY_SECONDS: number;
711
- declare class PostHog extends PostHogCoreStateless implements PostHogNodeV1 {
712
- private _memoryStorage;
713
- private featureFlagsPoller?;
714
- protected errorTracking: ErrorTracking;
715
- private maxCacheSize;
716
- readonly options: PostHogOptions;
717
- distinctIdHasSentFlagCalls: Record<string, string[]>;
718
- constructor(apiKey: string, options?: PostHogOptions);
719
- getPersistedProperty(key: PostHogPersistedProperty): any | undefined;
720
- setPersistedProperty(key: PostHogPersistedProperty, value: any | null): void;
721
- fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse>;
722
- getLibraryId(): string;
723
- getLibraryVersion(): string;
724
- getCustomUserAgent(): string;
725
- enable(): Promise<void>;
726
- disable(): Promise<void>;
727
- debug(enabled?: boolean): void;
728
- capture(props: EventMessage): void;
729
- identify({ distinctId, properties, disableGeoip }: IdentifyMessage): void;
730
- alias(data: {
731
- distinctId: string;
732
- alias: string;
733
- disableGeoip?: boolean;
734
- }): void;
735
- isLocalEvaluationReady(): boolean;
736
- waitForLocalEvaluationReady(timeoutMs?: number): Promise<boolean>;
737
- getFeatureFlag(key: string, distinctId: string, options?: {
738
- groups?: Record<string, string>;
739
- personProperties?: Record<string, string>;
740
- groupProperties?: Record<string, Record<string, string>>;
741
- onlyEvaluateLocally?: boolean;
742
- sendFeatureFlagEvents?: boolean;
743
- disableGeoip?: boolean;
744
- }): Promise<FeatureFlagValue | undefined>;
745
- getFeatureFlagPayload(key: string, distinctId: string, matchValue?: FeatureFlagValue, options?: {
746
- groups?: Record<string, string>;
747
- personProperties?: Record<string, string>;
748
- groupProperties?: Record<string, Record<string, string>>;
749
- onlyEvaluateLocally?: boolean;
750
- sendFeatureFlagEvents?: boolean;
751
- disableGeoip?: boolean;
752
- }): Promise<JsonType | undefined>;
753
- getRemoteConfigPayload(flagKey: string): Promise<JsonType | undefined>;
754
- isFeatureEnabled(key: string, distinctId: string, options?: {
755
- groups?: Record<string, string>;
756
- personProperties?: Record<string, string>;
757
- groupProperties?: Record<string, Record<string, string>>;
758
- onlyEvaluateLocally?: boolean;
759
- sendFeatureFlagEvents?: boolean;
760
- disableGeoip?: boolean;
761
- }): Promise<boolean | undefined>;
762
- getAllFlags(distinctId: string, options?: {
763
- groups?: Record<string, string>;
764
- personProperties?: Record<string, string>;
765
- groupProperties?: Record<string, Record<string, string>>;
766
- onlyEvaluateLocally?: boolean;
767
- disableGeoip?: boolean;
768
- }): Promise<Record<string, FeatureFlagValue>>;
769
- getAllFlagsAndPayloads(distinctId: string, options?: {
770
- groups?: Record<string, string>;
771
- personProperties?: Record<string, string>;
772
- groupProperties?: Record<string, Record<string, string>>;
773
- onlyEvaluateLocally?: boolean;
774
- disableGeoip?: boolean;
775
- }): Promise<PostHogFlagsAndPayloadsResponse>;
776
- groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }: GroupIdentifyMessage): void;
777
- /**
778
- * Reloads the feature flag definitions from the server for local evaluation.
779
- * This is useful to call if you want to ensure that the feature flags are up to date before calling getFeatureFlag.
780
- */
781
- reloadFeatureFlags(): Promise<void>;
782
- shutdown(shutdownTimeoutMs?: number): Promise<void>;
783
- private addLocalPersonAndGroupProperties;
784
- captureException(error: unknown, distinctId?: string, additionalProperties?: Record<string | number, any>): void;
829
+ declare abstract class PostHogBackendClient extends PostHogCoreStateless implements IPostHog {
830
+ private _memoryStorage;
831
+ private featureFlagsPoller?;
832
+ protected errorTracking: ErrorTracking;
833
+ private maxCacheSize;
834
+ readonly options: PostHogOptions;
835
+ distinctIdHasSentFlagCalls: Record<string, string[]>;
836
+ constructor(apiKey: string, options?: PostHogOptions);
837
+ getPersistedProperty(key: PostHogPersistedProperty): any | undefined;
838
+ setPersistedProperty(key: PostHogPersistedProperty, value: any | null): void;
839
+ fetch(url: string, options: PostHogFetchOptions): Promise<PostHogFetchResponse>;
840
+ getLibraryVersion(): string;
841
+ getCustomUserAgent(): string;
842
+ enable(): Promise<void>;
843
+ disable(): Promise<void>;
844
+ debug(enabled?: boolean): void;
845
+ capture(props: EventMessage): void;
846
+ captureImmediate(props: EventMessage): Promise<void>;
847
+ identify({ distinctId, properties, disableGeoip }: IdentifyMessage): void;
848
+ identifyImmediate({ distinctId, properties, disableGeoip }: IdentifyMessage): Promise<void>;
849
+ alias(data: {
850
+ distinctId: string;
851
+ alias: string;
852
+ disableGeoip?: boolean;
853
+ }): void;
854
+ aliasImmediate(data: {
855
+ distinctId: string;
856
+ alias: string;
857
+ disableGeoip?: boolean;
858
+ }): Promise<void>;
859
+ isLocalEvaluationReady(): boolean;
860
+ waitForLocalEvaluationReady(timeoutMs?: number): Promise<boolean>;
861
+ getFeatureFlag(key: string, distinctId: string, options?: {
862
+ groups?: Record<string, string>;
863
+ personProperties?: Record<string, string>;
864
+ groupProperties?: Record<string, Record<string, string>>;
865
+ onlyEvaluateLocally?: boolean;
866
+ sendFeatureFlagEvents?: boolean;
867
+ disableGeoip?: boolean;
868
+ }): Promise<FeatureFlagValue | undefined>;
869
+ getFeatureFlagPayload(key: string, distinctId: string, matchValue?: FeatureFlagValue, options?: {
870
+ groups?: Record<string, string>;
871
+ personProperties?: Record<string, string>;
872
+ groupProperties?: Record<string, Record<string, string>>;
873
+ onlyEvaluateLocally?: boolean;
874
+ sendFeatureFlagEvents?: boolean;
875
+ disableGeoip?: boolean;
876
+ }): Promise<JsonType | undefined>;
877
+ getRemoteConfigPayload(flagKey: string): Promise<JsonType | undefined>;
878
+ isFeatureEnabled(key: string, distinctId: string, options?: {
879
+ groups?: Record<string, string>;
880
+ personProperties?: Record<string, string>;
881
+ groupProperties?: Record<string, Record<string, string>>;
882
+ onlyEvaluateLocally?: boolean;
883
+ sendFeatureFlagEvents?: boolean;
884
+ disableGeoip?: boolean;
885
+ }): Promise<boolean | undefined>;
886
+ getAllFlags(distinctId: string, options?: {
887
+ groups?: Record<string, string>;
888
+ personProperties?: Record<string, string>;
889
+ groupProperties?: Record<string, Record<string, string>>;
890
+ onlyEvaluateLocally?: boolean;
891
+ disableGeoip?: boolean;
892
+ }): Promise<Record<string, FeatureFlagValue>>;
893
+ getAllFlagsAndPayloads(distinctId: string, options?: {
894
+ groups?: Record<string, string>;
895
+ personProperties?: Record<string, string>;
896
+ groupProperties?: Record<string, Record<string, string>>;
897
+ onlyEvaluateLocally?: boolean;
898
+ disableGeoip?: boolean;
899
+ }): Promise<PostHogFlagsAndPayloadsResponse>;
900
+ groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }: GroupIdentifyMessage): void;
901
+ /**
902
+ * Reloads the feature flag definitions from the server for local evaluation.
903
+ * This is useful to call if you want to ensure that the feature flags are up to date before calling getFeatureFlag.
904
+ */
905
+ reloadFeatureFlags(): Promise<void>;
906
+ _shutdown(shutdownTimeoutMs?: number): Promise<void>;
907
+ private addLocalPersonAndGroupProperties;
908
+ captureException(error: unknown, distinctId?: string, additionalProperties?: Record<string | number, any>): void;
785
909
  }
786
910
 
787
- /**
788
- * @file Adapted from [posthog-js](https://github.com/PostHog/posthog-js/blob/8157df935a4d0e71d2fefef7127aa85ee51c82d1/src/extensions/sentry-integration.ts) with modifications for the Node SDK.
789
- */
790
-
791
- type _SentryEvent = any;
792
- type _SentryEventProcessor = any;
793
- type _SentryHub = any;
794
- interface _SentryIntegration {
795
- name: string;
796
- processEvent(event: _SentryEvent): _SentryEvent;
797
- }
798
- interface _SentryIntegrationClass {
799
- name: string;
800
- setupOnce(addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub): void;
801
- }
802
- type SentryIntegrationOptions = {
803
- organization?: string;
804
- projectId?: number;
805
- prefix?: string;
806
- severityAllowList?: SeverityLevel[] | '*';
807
- };
808
- declare function createEventProcessor(_posthog: PostHog, { organization, projectId, prefix, severityAllowList }?: SentryIntegrationOptions): (event: _SentryEvent) => _SentryEvent;
809
- declare function sentryIntegration(_posthog: PostHog, options?: SentryIntegrationOptions): _SentryIntegration;
810
- declare class PostHogSentryIntegration implements _SentryIntegrationClass {
811
- readonly name = "posthog-node";
812
- static readonly POSTHOG_ID_TAG = "posthog_distinct_id";
813
- setupOnce: (addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub) => void;
814
- constructor(_posthog: PostHog, organization?: string, prefix?: string, severityAllowList?: SeverityLevel[] | '*');
911
+ /**
912
+ * @file Adapted from [posthog-js](https://github.com/PostHog/posthog-js/blob/8157df935a4d0e71d2fefef7127aa85ee51c82d1/src/extensions/sentry-integration.ts) with modifications for the Node SDK.
913
+ */
914
+
915
+ type _SentryEvent = any;
916
+ type _SentryEventProcessor = any;
917
+ type _SentryHub = any;
918
+ interface _SentryIntegration {
919
+ name: string;
920
+ processEvent(event: _SentryEvent): _SentryEvent;
921
+ }
922
+ interface _SentryIntegrationClass {
923
+ name: string;
924
+ setupOnce(addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub): void;
925
+ }
926
+ type SentryIntegrationOptions = {
927
+ organization?: string;
928
+ projectId?: number;
929
+ prefix?: string;
930
+ severityAllowList?: SeverityLevel[] | '*';
931
+ };
932
+ declare function createEventProcessor(_posthog: PostHogBackendClient, { organization, projectId, prefix, severityAllowList }?: SentryIntegrationOptions): (event: _SentryEvent) => _SentryEvent;
933
+ declare function sentryIntegration(_posthog: PostHogBackendClient, options?: SentryIntegrationOptions): _SentryIntegration;
934
+ declare class PostHogSentryIntegration implements _SentryIntegrationClass {
935
+ readonly name = "posthog-node";
936
+ static readonly POSTHOG_ID_TAG = "posthog_distinct_id";
937
+ setupOnce: (addGlobalEventProcessor: (callback: _SentryEventProcessor) => void, getCurrentHub: () => _SentryHub) => void;
938
+ constructor(_posthog: PostHogBackendClient, organization?: string, prefix?: string, severityAllowList?: SeverityLevel[] | '*');
815
939
  }
816
940
 
817
- type ExpressMiddleware = (req: http.IncomingMessage, res: http.ServerResponse, next: () => void) => void;
818
- type ExpressErrorMiddleware = (error: MiddlewareError, req: http.IncomingMessage, res: http.ServerResponse, next: (error: MiddlewareError) => void) => void;
819
- interface MiddlewareError extends Error {
820
- status?: number | string;
821
- statusCode?: number | string;
822
- status_code?: number | string;
823
- output?: {
824
- statusCode?: number | string;
825
- };
826
- }
827
- declare function setupExpressErrorHandler(_posthog: PostHog, app: {
828
- use: (middleware: ExpressMiddleware | ExpressErrorMiddleware) => unknown;
941
+ type ExpressMiddleware = (req: http.IncomingMessage, res: http.ServerResponse, next: () => void) => void;
942
+ type ExpressErrorMiddleware = (error: MiddlewareError, req: http.IncomingMessage, res: http.ServerResponse, next: (error: MiddlewareError) => void) => void;
943
+ interface MiddlewareError extends Error {
944
+ status?: number | string;
945
+ statusCode?: number | string;
946
+ status_code?: number | string;
947
+ output?: {
948
+ statusCode?: number | string;
949
+ };
950
+ }
951
+ declare function setupExpressErrorHandler(_posthog: PostHogBackendClient, app: {
952
+ use: (middleware: ExpressMiddleware | ExpressErrorMiddleware) => unknown;
829
953
  }): void;
830
954
 
831
- export { MINIMUM_POLLING_INTERVAL, PostHog, PostHogOptions, PostHogSentryIntegration, SIXTY_SECONDS, SentryIntegrationOptions, THIRTY_SECONDS, createEventProcessor, sentryIntegration, setupExpressErrorHandler };
955
+ declare class PostHog extends PostHogBackendClient {
956
+ getLibraryId(): string;
957
+ }
958
+
959
+ export { EventMessage, FeatureFlagCondition, FlagProperty, GroupIdentifyMessage, IPostHog, IdentifyMessage, PostHog, PostHogFeatureFlag, PostHogOptions, PostHogSentryIntegration, PropertyGroup, SentryIntegrationOptions, createEventProcessor, sentryIntegration, setupExpressErrorHandler };