posthog-node 4.16.0 → 4.17.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 (69) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/lib/edge/index.cjs.js +3919 -0
  3. package/lib/edge/index.cjs.js.map +1 -0
  4. package/lib/edge/index.esm.js +3893 -0
  5. package/lib/edge/index.esm.js.map +1 -0
  6. package/lib/index.d.ts +921 -859
  7. package/lib/{index.cjs.js → node/index.cjs.js} +3575 -3594
  8. package/lib/node/index.cjs.js.map +1 -0
  9. package/lib/{index.esm.js → node/index.esm.js} +3576 -3592
  10. package/lib/node/index.esm.js.map +1 -0
  11. package/package.json +31 -4
  12. package/src/{posthog-node.ts → client.ts} +10 -28
  13. package/src/entrypoints/index.edge.ts +15 -0
  14. package/src/entrypoints/index.node.ts +17 -0
  15. package/src/exports.ts +3 -0
  16. package/src/extensions/error-tracking/autocapture.ts +1 -1
  17. package/src/extensions/error-tracking/{context-lines.ts → context-lines.node.ts} +64 -97
  18. package/src/extensions/error-tracking/error-conversion.ts +22 -5
  19. package/src/extensions/error-tracking/get-module.node.ts +57 -0
  20. package/src/{error-tracking.ts → extensions/error-tracking/index.ts} +12 -10
  21. package/src/extensions/error-tracking/{stack-trace.ts → stack-parser.ts} +7 -64
  22. package/src/extensions/error-tracking/types.ts +4 -0
  23. package/src/extensions/express.ts +3 -3
  24. package/src/{crypto-helpers.ts → extensions/feature-flags/crypto-helpers.ts} +1 -1
  25. package/src/{feature-flags.ts → extensions/feature-flags/feature-flags.ts} +7 -6
  26. package/src/extensions/sentry-integration.ts +13 -5
  27. package/src/fetch.ts +2 -2
  28. package/src/storage-memory.ts +13 -0
  29. package/src/types.ts +19 -1
  30. package/test/crypto.spec.ts +2 -2
  31. package/test/extensions/error-conversion.spec.ts +2 -2
  32. package/test/extensions/sentry-integration.spec.ts +1 -2
  33. package/test/feature-flags.decide.spec.ts +2 -1
  34. package/test/feature-flags.spec.ts +7 -4
  35. package/test/lazy.spec.ts +1 -1
  36. package/test/posthog-node.spec.ts +3 -3
  37. package/tsconfig.json +1 -0
  38. package/index.ts +0 -3
  39. package/lib/index.cjs.js.map +0 -1
  40. package/lib/index.esm.js.map +0 -1
  41. package/lib/posthog-core/src/eventemitter.d.ts +0 -8
  42. package/lib/posthog-core/src/featureFlagUtils.d.ts +0 -34
  43. package/lib/posthog-core/src/index.d.ts +0 -259
  44. package/lib/posthog-core/src/lz-string.d.ts +0 -8
  45. package/lib/posthog-core/src/storage-memory.d.ts +0 -6
  46. package/lib/posthog-core/src/types.d.ts +0 -422
  47. package/lib/posthog-core/src/utils.d.ts +0 -20
  48. package/lib/posthog-core/src/vendor/uuidv7.d.ts +0 -179
  49. package/lib/posthog-node/index.d.ts +0 -3
  50. package/lib/posthog-node/src/crypto-helpers.d.ts +0 -3
  51. package/lib/posthog-node/src/crypto.d.ts +0 -2
  52. package/lib/posthog-node/src/error-tracking.d.ts +0 -12
  53. package/lib/posthog-node/src/extensions/error-tracking/autocapture.d.ts +0 -3
  54. package/lib/posthog-node/src/extensions/error-tracking/context-lines.d.ts +0 -6
  55. package/lib/posthog-node/src/extensions/error-tracking/error-conversion.d.ts +0 -2
  56. package/lib/posthog-node/src/extensions/error-tracking/reduceable-cache.d.ts +0 -12
  57. package/lib/posthog-node/src/extensions/error-tracking/stack-trace.d.ts +0 -15
  58. package/lib/posthog-node/src/extensions/error-tracking/type-checking.d.ts +0 -7
  59. package/lib/posthog-node/src/extensions/error-tracking/types.d.ts +0 -57
  60. package/lib/posthog-node/src/extensions/express.d.ts +0 -17
  61. package/lib/posthog-node/src/extensions/sentry-integration.d.ts +0 -51
  62. package/lib/posthog-node/src/feature-flags.d.ts +0 -84
  63. package/lib/posthog-node/src/fetch.d.ts +0 -11
  64. package/lib/posthog-node/src/lazy.d.ts +0 -23
  65. package/lib/posthog-node/src/posthog-node.d.ts +0 -98
  66. package/lib/posthog-node/src/types.d.ts +0 -229
  67. package/lib/posthog-node/test/test-utils.d.ts +0 -18
  68. /package/src/{crypto.ts → extensions/feature-flags/crypto.ts} +0 -0
  69. /package/src/{lazy.ts → extensions/feature-flags/lazy.ts} +0 -0
@@ -0,0 +1,3919 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ function _interopNamespace(e) {
6
+ if (e && e.__esModule) return e;
7
+ var n = Object.create(null);
8
+ if (e) {
9
+ Object.keys(e).forEach(function (k) {
10
+ if (k !== 'default') {
11
+ var d = Object.getOwnPropertyDescriptor(e, k);
12
+ Object.defineProperty(n, k, d.get ? d : {
13
+ enumerable: true,
14
+ get: function () { return e[k]; }
15
+ });
16
+ }
17
+ });
18
+ }
19
+ n["default"] = e;
20
+ return Object.freeze(n);
21
+ }
22
+
23
+ /**
24
+ * @file Adapted from [posthog-js](https://github.com/PostHog/posthog-js/blob/8157df935a4d0e71d2fefef7127aa85ee51c82d1/src/extensions/sentry-integration.ts) with modifications for the Node SDK.
25
+ */
26
+ /**
27
+ * Integrate Sentry with PostHog. This will add a direct link to the person in Sentry, and an $exception event in PostHog.
28
+ *
29
+ * ### Usage
30
+ *
31
+ * Sentry.init({
32
+ * dsn: 'https://example',
33
+ * integrations: [
34
+ * new PostHogSentryIntegration(posthog)
35
+ * ]
36
+ * })
37
+ *
38
+ * Sentry.setTag(PostHogSentryIntegration.POSTHOG_ID_TAG, 'some distinct id');
39
+ *
40
+ * @param {Object} [posthog] The posthog object
41
+ * @param {string} [organization] Optional: The Sentry organization, used to send a direct link from PostHog to Sentry
42
+ * @param {Number} [projectId] Optional: The Sentry project id, used to send a direct link from PostHog to Sentry
43
+ * @param {string} [prefix] Optional: Url of a self-hosted sentry instance (default: https://sentry.io/organizations/)
44
+ * @param {SeverityLevel[] | '*'} [severityAllowList] Optional: send events matching the provided levels. Use '*' to send all events (default: ['error'])
45
+ */
46
+ const NAME = 'posthog-node';
47
+ function createEventProcessor(_posthog, {
48
+ organization,
49
+ projectId,
50
+ prefix,
51
+ severityAllowList = ['error']
52
+ } = {}) {
53
+ return event => {
54
+ const shouldProcessLevel = severityAllowList === '*' || severityAllowList.includes(event.level);
55
+ if (!shouldProcessLevel) {
56
+ return event;
57
+ }
58
+ if (!event.tags) {
59
+ event.tags = {};
60
+ }
61
+ // Get the PostHog user ID from a specific tag, which users can set on their Sentry scope as they need.
62
+ const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG];
63
+ if (userId === undefined) {
64
+ // If we can't find a user ID, don't bother linking the event. We won't be able to send anything meaningful to PostHog without it.
65
+ return event;
66
+ }
67
+ const uiHost = _posthog.options.host ?? 'https://us.i.posthog.com';
68
+ const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString();
69
+ event.tags['PostHog Person URL'] = personUrl;
70
+ const exceptions = event.exception?.values || [];
71
+ const exceptionList = exceptions.map(exception => ({
72
+ ...exception,
73
+ stacktrace: exception.stacktrace ? {
74
+ ...exception.stacktrace,
75
+ type: 'raw',
76
+ frames: (exception.stacktrace.frames || []).map(frame => {
77
+ return {
78
+ ...frame,
79
+ platform: 'node:javascript'
80
+ };
81
+ })
82
+ } : undefined
83
+ }));
84
+ const properties = {
85
+ // PostHog Exception Properties,
86
+ $exception_message: exceptions[0]?.value || event.message,
87
+ $exception_type: exceptions[0]?.type,
88
+ $exception_personURL: personUrl,
89
+ $exception_level: event.level,
90
+ $exception_list: exceptionList,
91
+ // Sentry Exception Properties
92
+ $sentry_event_id: event.event_id,
93
+ $sentry_exception: event.exception,
94
+ $sentry_exception_message: exceptions[0]?.value || event.message,
95
+ $sentry_exception_type: exceptions[0]?.type,
96
+ $sentry_tags: event.tags
97
+ };
98
+ if (organization && projectId) {
99
+ properties['$sentry_url'] = (prefix || 'https://sentry.io/organizations/') + organization + '/issues/?project=' + projectId + '&query=' + event.event_id;
100
+ }
101
+ _posthog.capture({
102
+ event: '$exception',
103
+ distinctId: userId,
104
+ properties
105
+ });
106
+ return event;
107
+ };
108
+ }
109
+ // V8 integration - function based
110
+ function sentryIntegration(_posthog, options) {
111
+ const processor = createEventProcessor(_posthog, options);
112
+ return {
113
+ name: NAME,
114
+ processEvent(event) {
115
+ return processor(event);
116
+ }
117
+ };
118
+ }
119
+ // V7 integration - class based
120
+ class PostHogSentryIntegration {
121
+ constructor(_posthog, organization, prefix, severityAllowList) {
122
+ this.name = NAME;
123
+ // setupOnce gets called by Sentry when it intializes the plugin
124
+ this.name = NAME;
125
+ this.setupOnce = function (addGlobalEventProcessor, getCurrentHub) {
126
+ const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId;
127
+ addGlobalEventProcessor(createEventProcessor(_posthog, {
128
+ organization,
129
+ projectId,
130
+ prefix,
131
+ severityAllowList
132
+ }));
133
+ };
134
+ }
135
+ }
136
+ PostHogSentryIntegration.POSTHOG_ID_TAG = 'posthog_distinct_id';
137
+
138
+ // vendor from: https://github.com/LiosK/uuidv7/blob/f30b7a7faff73afbce0b27a46c638310f96912ba/src/index.ts
139
+ // https://github.com/LiosK/uuidv7#license
140
+ /**
141
+ * uuidv7: An experimental implementation of the proposed UUID Version 7
142
+ *
143
+ * @license Apache-2.0
144
+ * @copyright 2021-2023 LiosK
145
+ * @packageDocumentation
146
+ */
147
+ const DIGITS = "0123456789abcdef";
148
+ /** Represents a UUID as a 16-byte byte array. */
149
+ class UUID {
150
+ /** @param bytes - The 16-byte byte array representation. */
151
+ constructor(bytes) {
152
+ this.bytes = bytes;
153
+ }
154
+ /**
155
+ * Creates an object from the internal representation, a 16-byte byte array
156
+ * containing the binary UUID representation in the big-endian byte order.
157
+ *
158
+ * This method does NOT shallow-copy the argument, and thus the created object
159
+ * holds the reference to the underlying buffer.
160
+ *
161
+ * @throws TypeError if the length of the argument is not 16.
162
+ */
163
+ static ofInner(bytes) {
164
+ if (bytes.length !== 16) {
165
+ throw new TypeError("not 128-bit length");
166
+ }
167
+ else {
168
+ return new UUID(bytes);
169
+ }
170
+ }
171
+ /**
172
+ * Builds a byte array from UUIDv7 field values.
173
+ *
174
+ * @param unixTsMs - A 48-bit `unix_ts_ms` field value.
175
+ * @param randA - A 12-bit `rand_a` field value.
176
+ * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.
177
+ * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
178
+ * @throws RangeError if any field value is out of the specified range.
179
+ */
180
+ static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
181
+ if (!Number.isInteger(unixTsMs) ||
182
+ !Number.isInteger(randA) ||
183
+ !Number.isInteger(randBHi) ||
184
+ !Number.isInteger(randBLo) ||
185
+ unixTsMs < 0 ||
186
+ randA < 0 ||
187
+ randBHi < 0 ||
188
+ randBLo < 0 ||
189
+ unixTsMs > 281474976710655 ||
190
+ randA > 0xfff ||
191
+ randBHi > 1073741823 ||
192
+ randBLo > 4294967295) {
193
+ throw new RangeError("invalid field value");
194
+ }
195
+ const bytes = new Uint8Array(16);
196
+ bytes[0] = unixTsMs / 2 ** 40;
197
+ bytes[1] = unixTsMs / 2 ** 32;
198
+ bytes[2] = unixTsMs / 2 ** 24;
199
+ bytes[3] = unixTsMs / 2 ** 16;
200
+ bytes[4] = unixTsMs / 2 ** 8;
201
+ bytes[5] = unixTsMs;
202
+ bytes[6] = 0x70 | (randA >>> 8);
203
+ bytes[7] = randA;
204
+ bytes[8] = 0x80 | (randBHi >>> 24);
205
+ bytes[9] = randBHi >>> 16;
206
+ bytes[10] = randBHi >>> 8;
207
+ bytes[11] = randBHi;
208
+ bytes[12] = randBLo >>> 24;
209
+ bytes[13] = randBLo >>> 16;
210
+ bytes[14] = randBLo >>> 8;
211
+ bytes[15] = randBLo;
212
+ return new UUID(bytes);
213
+ }
214
+ /**
215
+ * Builds a byte array from a string representation.
216
+ *
217
+ * This method accepts the following formats:
218
+ *
219
+ * - 32-digit hexadecimal format without hyphens: `0189dcd553117d408db09496a2eef37b`
220
+ * - 8-4-4-4-12 hyphenated format: `0189dcd5-5311-7d40-8db0-9496a2eef37b`
221
+ * - Hyphenated format with surrounding braces: `{0189dcd5-5311-7d40-8db0-9496a2eef37b}`
222
+ * - RFC 4122 URN format: `urn:uuid:0189dcd5-5311-7d40-8db0-9496a2eef37b`
223
+ *
224
+ * Leading and trailing whitespaces represents an error.
225
+ *
226
+ * @throws SyntaxError if the argument could not parse as a valid UUID string.
227
+ */
228
+ static parse(uuid) {
229
+ let hex = undefined;
230
+ switch (uuid.length) {
231
+ case 32:
232
+ hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];
233
+ break;
234
+ case 36:
235
+ hex =
236
+ /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
237
+ .exec(uuid)
238
+ ?.slice(1, 6)
239
+ .join("");
240
+ break;
241
+ case 38:
242
+ hex =
243
+ /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i
244
+ .exec(uuid)
245
+ ?.slice(1, 6)
246
+ .join("");
247
+ break;
248
+ case 45:
249
+ hex =
250
+ /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
251
+ .exec(uuid)
252
+ ?.slice(1, 6)
253
+ .join("");
254
+ break;
255
+ }
256
+ if (hex) {
257
+ const inner = new Uint8Array(16);
258
+ for (let i = 0; i < 16; i += 4) {
259
+ const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
260
+ inner[i + 0] = n >>> 24;
261
+ inner[i + 1] = n >>> 16;
262
+ inner[i + 2] = n >>> 8;
263
+ inner[i + 3] = n;
264
+ }
265
+ return new UUID(inner);
266
+ }
267
+ else {
268
+ throw new SyntaxError("could not parse UUID string");
269
+ }
270
+ }
271
+ /**
272
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
273
+ * (`0189dcd5-5311-7d40-8db0-9496a2eef37b`).
274
+ */
275
+ toString() {
276
+ let text = "";
277
+ for (let i = 0; i < this.bytes.length; i++) {
278
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
279
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
280
+ if (i === 3 || i === 5 || i === 7 || i === 9) {
281
+ text += "-";
282
+ }
283
+ }
284
+ return text;
285
+ }
286
+ /**
287
+ * @returns The 32-digit hexadecimal representation without hyphens
288
+ * (`0189dcd553117d408db09496a2eef37b`).
289
+ */
290
+ toHex() {
291
+ let text = "";
292
+ for (let i = 0; i < this.bytes.length; i++) {
293
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
294
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
295
+ }
296
+ return text;
297
+ }
298
+ /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
299
+ toJSON() {
300
+ return this.toString();
301
+ }
302
+ /**
303
+ * Reports the variant field value of the UUID or, if appropriate, "NIL" or
304
+ * "MAX".
305
+ *
306
+ * For convenience, this method reports "NIL" or "MAX" if `this` represents
307
+ * the Nil or Max UUID, although the Nil and Max UUIDs are technically
308
+ * subsumed under the variants `0b0` and `0b111`, respectively.
309
+ */
310
+ getVariant() {
311
+ const n = this.bytes[8] >>> 4;
312
+ if (n < 0) {
313
+ throw new Error("unreachable");
314
+ }
315
+ else if (n <= 0b0111) {
316
+ return this.bytes.every((e) => e === 0) ? "NIL" : "VAR_0";
317
+ }
318
+ else if (n <= 0b1011) {
319
+ return "VAR_10";
320
+ }
321
+ else if (n <= 0b1101) {
322
+ return "VAR_110";
323
+ }
324
+ else if (n <= 0b1111) {
325
+ return this.bytes.every((e) => e === 0xff) ? "MAX" : "VAR_RESERVED";
326
+ }
327
+ else {
328
+ throw new Error("unreachable");
329
+ }
330
+ }
331
+ /**
332
+ * Returns the version field value of the UUID or `undefined` if the UUID does
333
+ * not have the variant field value of `0b10`.
334
+ */
335
+ getVersion() {
336
+ return this.getVariant() === "VAR_10" ? this.bytes[6] >>> 4 : undefined;
337
+ }
338
+ /** Creates an object from `this`. */
339
+ clone() {
340
+ return new UUID(this.bytes.slice(0));
341
+ }
342
+ /** Returns true if `this` is equivalent to `other`. */
343
+ equals(other) {
344
+ return this.compareTo(other) === 0;
345
+ }
346
+ /**
347
+ * Returns a negative integer, zero, or positive integer if `this` is less
348
+ * than, equal to, or greater than `other`, respectively.
349
+ */
350
+ compareTo(other) {
351
+ for (let i = 0; i < 16; i++) {
352
+ const diff = this.bytes[i] - other.bytes[i];
353
+ if (diff !== 0) {
354
+ return Math.sign(diff);
355
+ }
356
+ }
357
+ return 0;
358
+ }
359
+ }
360
+ /**
361
+ * Encapsulates the monotonic counter state.
362
+ *
363
+ * This class provides APIs to utilize a separate counter state from that of the
364
+ * global generator used by {@link uuidv7} and {@link uuidv7obj}. In addition to
365
+ * the default {@link generate} method, this class has {@link generateOrAbort}
366
+ * that is useful to absolutely guarantee the monotonically increasing order of
367
+ * generated UUIDs. See their respective documentation for details.
368
+ */
369
+ class V7Generator {
370
+ /**
371
+ * Creates a generator object with the default random number generator, or
372
+ * with the specified one if passed as an argument. The specified random
373
+ * number generator should be cryptographically strong and securely seeded.
374
+ */
375
+ constructor(randomNumberGenerator) {
376
+ this.timestamp = 0;
377
+ this.counter = 0;
378
+ this.random = randomNumberGenerator ?? getDefaultRandom();
379
+ }
380
+ /**
381
+ * Generates a new UUIDv7 object from the current timestamp, or resets the
382
+ * generator upon significant timestamp rollback.
383
+ *
384
+ * This method returns a monotonically increasing UUID by reusing the previous
385
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
386
+ * preceding UUID's. However, when such a clock rollback is considered
387
+ * significant (i.e., by more than ten seconds), this method resets the
388
+ * generator and returns a new UUID based on the given timestamp, breaking the
389
+ * increasing order of UUIDs.
390
+ *
391
+ * See {@link generateOrAbort} for the other mode of generation and
392
+ * {@link generateOrResetCore} for the low-level primitive.
393
+ */
394
+ generate() {
395
+ return this.generateOrResetCore(Date.now(), 10000);
396
+ }
397
+ /**
398
+ * Generates a new UUIDv7 object from the current timestamp, or returns
399
+ * `undefined` upon significant timestamp rollback.
400
+ *
401
+ * This method returns a monotonically increasing UUID by reusing the previous
402
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
403
+ * preceding UUID's. However, when such a clock rollback is considered
404
+ * significant (i.e., by more than ten seconds), this method aborts and
405
+ * returns `undefined` immediately.
406
+ *
407
+ * See {@link generate} for the other mode of generation and
408
+ * {@link generateOrAbortCore} for the low-level primitive.
409
+ */
410
+ generateOrAbort() {
411
+ return this.generateOrAbortCore(Date.now(), 10000);
412
+ }
413
+ /**
414
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or resets the
415
+ * generator upon significant timestamp rollback.
416
+ *
417
+ * This method is equivalent to {@link generate} except that it takes a custom
418
+ * timestamp and clock rollback allowance.
419
+ *
420
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
421
+ * considered significant. A suggested value is `10_000` (milliseconds).
422
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
423
+ */
424
+ generateOrResetCore(unixTsMs, rollbackAllowance) {
425
+ let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
426
+ if (value === undefined) {
427
+ // reset state and resume
428
+ this.timestamp = 0;
429
+ value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
430
+ }
431
+ return value;
432
+ }
433
+ /**
434
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or returns
435
+ * `undefined` upon significant timestamp rollback.
436
+ *
437
+ * This method is equivalent to {@link generateOrAbort} except that it takes a
438
+ * custom timestamp and clock rollback allowance.
439
+ *
440
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
441
+ * considered significant. A suggested value is `10_000` (milliseconds).
442
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
443
+ */
444
+ generateOrAbortCore(unixTsMs, rollbackAllowance) {
445
+ const MAX_COUNTER = 4398046511103;
446
+ if (!Number.isInteger(unixTsMs) ||
447
+ unixTsMs < 1 ||
448
+ unixTsMs > 281474976710655) {
449
+ throw new RangeError("`unixTsMs` must be a 48-bit positive integer");
450
+ }
451
+ else if (rollbackAllowance < 0 || rollbackAllowance > 281474976710655) {
452
+ throw new RangeError("`rollbackAllowance` out of reasonable range");
453
+ }
454
+ if (unixTsMs > this.timestamp) {
455
+ this.timestamp = unixTsMs;
456
+ this.resetCounter();
457
+ }
458
+ else if (unixTsMs + rollbackAllowance >= this.timestamp) {
459
+ // go on with previous timestamp if new one is not much smaller
460
+ this.counter++;
461
+ if (this.counter > MAX_COUNTER) {
462
+ // increment timestamp at counter overflow
463
+ this.timestamp++;
464
+ this.resetCounter();
465
+ }
466
+ }
467
+ else {
468
+ // abort if clock went backwards to unbearable extent
469
+ return undefined;
470
+ }
471
+ return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & (2 ** 30 - 1), this.random.nextUint32());
472
+ }
473
+ /** Initializes the counter at a 42-bit random integer. */
474
+ resetCounter() {
475
+ this.counter =
476
+ this.random.nextUint32() * 0x400 + (this.random.nextUint32() & 0x3ff);
477
+ }
478
+ /**
479
+ * Generates a new UUIDv4 object utilizing the random number generator inside.
480
+ *
481
+ * @internal
482
+ */
483
+ generateV4() {
484
+ const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
485
+ bytes[6] = 0x40 | (bytes[6] >>> 4);
486
+ bytes[8] = 0x80 | (bytes[8] >>> 2);
487
+ return UUID.ofInner(bytes);
488
+ }
489
+ }
490
+ /** A global flag to force use of cryptographically strong RNG. */
491
+ // declare const UUIDV7_DENY_WEAK_RNG: boolean;
492
+ /** Returns the default random number generator available in the environment. */
493
+ const getDefaultRandom = () => {
494
+ // fix: crypto isn't available in react-native, always use Math.random
495
+ // // detect Web Crypto API
496
+ // if (
497
+ // typeof crypto !== "undefined" &&
498
+ // typeof crypto.getRandomValues !== "undefined"
499
+ // ) {
500
+ // return new BufferedCryptoRandom();
501
+ // } else {
502
+ // // fall back on Math.random() unless the flag is set to true
503
+ // if (typeof UUIDV7_DENY_WEAK_RNG !== "undefined" && UUIDV7_DENY_WEAK_RNG) {
504
+ // throw new Error("no cryptographically strong RNG available");
505
+ // }
506
+ // return {
507
+ // nextUint32: (): number =>
508
+ // Math.trunc(Math.random() * 0x1_0000) * 0x1_0000 +
509
+ // Math.trunc(Math.random() * 0x1_0000),
510
+ // };
511
+ // }
512
+ return {
513
+ nextUint32: () => Math.trunc(Math.random() * 65536) * 65536 +
514
+ Math.trunc(Math.random() * 65536),
515
+ };
516
+ };
517
+ // /**
518
+ // * Wraps `crypto.getRandomValues()` to enable buffering; this uses a small
519
+ // * buffer by default to avoid both unbearable throughput decline in some
520
+ // * environments and the waste of time and space for unused values.
521
+ // */
522
+ // class BufferedCryptoRandom {
523
+ // private readonly buffer = new Uint32Array(8);
524
+ // private cursor = 0xffff;
525
+ // nextUint32(): number {
526
+ // if (this.cursor >= this.buffer.length) {
527
+ // crypto.getRandomValues(this.buffer);
528
+ // this.cursor = 0;
529
+ // }
530
+ // return this.buffer[this.cursor++];
531
+ // }
532
+ // }
533
+ let defaultGenerator;
534
+ /**
535
+ * Generates a UUIDv7 string.
536
+ *
537
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
538
+ * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
539
+ */
540
+ const uuidv7 = () => uuidv7obj().toString();
541
+ /** Generates a UUIDv7 object. */
542
+ const uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
543
+
544
+ // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
545
+ // Licensed under the MIT License
546
+ function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
547
+ let calledFatalError = false;
548
+ return Object.assign(error => {
549
+ // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not
550
+ // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust
551
+ // exit behaviour of the SDK accordingly:
552
+ // - If other listeners are attached, do not exit.
553
+ // - If the only listener attached is ours, exit.
554
+ const userProvidedListenersCount = global.process.listeners('uncaughtException').filter(listener => {
555
+ // There are 2 listeners we ignore:
556
+ return (
557
+ // as soon as we're using domains this listener is attached by node itself
558
+ listener.name !== 'domainUncaughtExceptionClear' &&
559
+ // the handler we register in this integration
560
+ listener._posthogErrorHandler !== true
561
+ );
562
+ }).length;
563
+ const processWouldExit = userProvidedListenersCount === 0;
564
+ captureFn(error, {
565
+ mechanism: {
566
+ type: 'onuncaughtexception',
567
+ handled: false
568
+ }
569
+ });
570
+ if (!calledFatalError && processWouldExit) {
571
+ calledFatalError = true;
572
+ onFatalFn();
573
+ }
574
+ }, {
575
+ _posthogErrorHandler: true
576
+ });
577
+ }
578
+ function addUncaughtExceptionListener(captureFn, onFatalFn) {
579
+ global.process.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn));
580
+ }
581
+ function addUnhandledRejectionListener(captureFn) {
582
+ global.process.on('unhandledRejection', reason => {
583
+ captureFn(reason, {
584
+ mechanism: {
585
+ type: 'onunhandledrejection',
586
+ handled: false
587
+ }
588
+ });
589
+ });
590
+ }
591
+
592
+ // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
593
+ // Licensed under the MIT License
594
+ function isEvent(candidate) {
595
+ return typeof Event !== 'undefined' && isInstanceOf(candidate, Event);
596
+ }
597
+ function isPlainObject(candidate) {
598
+ return isBuiltin(candidate, 'Object');
599
+ }
600
+ function isError(candidate) {
601
+ switch (Object.prototype.toString.call(candidate)) {
602
+ case '[object Error]':
603
+ case '[object Exception]':
604
+ case '[object DOMException]':
605
+ case '[object WebAssembly.Exception]':
606
+ return true;
607
+ default:
608
+ return isInstanceOf(candidate, Error);
609
+ }
610
+ }
611
+ function isInstanceOf(candidate, base) {
612
+ try {
613
+ return candidate instanceof base;
614
+ } catch {
615
+ return false;
616
+ }
617
+ }
618
+ function isErrorEvent(event) {
619
+ return isBuiltin(event, 'ErrorEvent');
620
+ }
621
+ function isBuiltin(candidate, className) {
622
+ return Object.prototype.toString.call(candidate) === `[object ${className}]`;
623
+ }
624
+
625
+ // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
626
+ async function propertiesFromUnknownInput(stackParser, frameModifiers, input, hint) {
627
+ const providedMechanism = hint && hint.mechanism;
628
+ const mechanism = providedMechanism || {
629
+ handled: true,
630
+ type: 'generic'
631
+ };
632
+ const errorList = getErrorList(mechanism, input, hint);
633
+ const exceptionList = await Promise.all(errorList.map(async error => {
634
+ const exception = await exceptionFromError(stackParser, frameModifiers, error);
635
+ exception.value = exception.value || '';
636
+ exception.type = exception.type || 'Error';
637
+ exception.mechanism = mechanism;
638
+ return exception;
639
+ }));
640
+ const properties = {
641
+ $exception_list: exceptionList
642
+ };
643
+ return properties;
644
+ }
645
+ // Flatten error causes into a list of errors
646
+ // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause
647
+ function getErrorList(mechanism, input, hint) {
648
+ const error = getError(mechanism, input, hint);
649
+ if (error.cause) {
650
+ return [error, ...getErrorList(mechanism, error.cause, hint)];
651
+ }
652
+ return [error];
653
+ }
654
+ function getError(mechanism, exception, hint) {
655
+ if (isError(exception)) {
656
+ return exception;
657
+ }
658
+ mechanism.synthetic = true;
659
+ if (isPlainObject(exception)) {
660
+ const errorFromProp = getErrorPropertyFromObject(exception);
661
+ if (errorFromProp) {
662
+ return errorFromProp;
663
+ }
664
+ const message = getMessageForObject(exception);
665
+ const ex = hint?.syntheticException || new Error(message);
666
+ ex.message = message;
667
+ return ex;
668
+ }
669
+ // This handles when someone does: `throw "something awesome";`
670
+ // We use synthesized Error here so we can extract a (rough) stack trace.
671
+ const ex = hint?.syntheticException || new Error(exception);
672
+ ex.message = `${exception}`;
673
+ return ex;
674
+ }
675
+ /** If a plain object has a property that is an `Error`, return this error. */
676
+ function getErrorPropertyFromObject(obj) {
677
+ for (const prop in obj) {
678
+ if (Object.prototype.hasOwnProperty.call(obj, prop)) {
679
+ const value = obj[prop];
680
+ if (isError(value)) {
681
+ return value;
682
+ }
683
+ }
684
+ }
685
+ return undefined;
686
+ }
687
+ function getMessageForObject(exception) {
688
+ if ('name' in exception && typeof exception.name === 'string') {
689
+ let message = `'${exception.name}' captured as exception`;
690
+ if ('message' in exception && typeof exception.message === 'string') {
691
+ message += ` with message '${exception.message}'`;
692
+ }
693
+ return message;
694
+ } else if ('message' in exception && typeof exception.message === 'string') {
695
+ return exception.message;
696
+ }
697
+ const keys = extractExceptionKeysForMessage(exception);
698
+ // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before
699
+ // We still want to try to get a decent message for these cases
700
+ if (isErrorEvent(exception)) {
701
+ return `Event \`ErrorEvent\` captured as exception with message \`${exception.message}\``;
702
+ }
703
+ const className = getObjectClassName(exception);
704
+ return `${className && className !== 'Object' ? `'${className}'` : 'Object'} captured as exception with keys: ${keys}`;
705
+ }
706
+ function getObjectClassName(obj) {
707
+ try {
708
+ const prototype = Object.getPrototypeOf(obj);
709
+ return prototype ? prototype.constructor.name : undefined;
710
+ } catch (e) {
711
+ // ignore errors here
712
+ }
713
+ }
714
+ /**
715
+ * Given any captured exception, extract its keys and create a sorted
716
+ * and truncated list that will be used inside the event message.
717
+ * eg. `Non-error exception captured with keys: foo, bar, baz`
718
+ */
719
+ function extractExceptionKeysForMessage(exception, maxLength = 40) {
720
+ const keys = Object.keys(convertToPlainObject(exception));
721
+ keys.sort();
722
+ const firstKey = keys[0];
723
+ if (!firstKey) {
724
+ return '[object has no keys]';
725
+ }
726
+ if (firstKey.length >= maxLength) {
727
+ return truncate(firstKey, maxLength);
728
+ }
729
+ for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {
730
+ const serialized = keys.slice(0, includedKeys).join(', ');
731
+ if (serialized.length > maxLength) {
732
+ continue;
733
+ }
734
+ if (includedKeys === keys.length) {
735
+ return serialized;
736
+ }
737
+ return truncate(serialized, maxLength);
738
+ }
739
+ return '';
740
+ }
741
+ function truncate(str, max = 0) {
742
+ if (typeof str !== 'string' || max === 0) {
743
+ return str;
744
+ }
745
+ return str.length <= max ? str : `${str.slice(0, max)}...`;
746
+ }
747
+ /**
748
+ * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their
749
+ * non-enumerable properties attached.
750
+ *
751
+ * @param value Initial source that we have to transform in order for it to be usable by the serializer
752
+ * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor
753
+ * an Error.
754
+ */
755
+ function convertToPlainObject(value) {
756
+ if (isError(value)) {
757
+ return {
758
+ message: value.message,
759
+ name: value.name,
760
+ stack: value.stack,
761
+ ...getOwnProperties(value)
762
+ };
763
+ } else if (isEvent(value)) {
764
+ const newObj = {
765
+ type: value.type,
766
+ target: serializeEventTarget(value.target),
767
+ currentTarget: serializeEventTarget(value.currentTarget),
768
+ ...getOwnProperties(value)
769
+ };
770
+ // TODO: figure out why this fails typing (I think CustomEvent is only supported in Node 19 onwards)
771
+ // if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {
772
+ // newObj.detail = (value as unknown as CustomEvent).detail
773
+ // }
774
+ return newObj;
775
+ } else {
776
+ return value;
777
+ }
778
+ }
779
+ /** Filters out all but an object's own properties */
780
+ function getOwnProperties(obj) {
781
+ if (typeof obj === 'object' && obj !== null) {
782
+ const extractedProps = {};
783
+ for (const property in obj) {
784
+ if (Object.prototype.hasOwnProperty.call(obj, property)) {
785
+ extractedProps[property] = obj[property];
786
+ }
787
+ }
788
+ return extractedProps;
789
+ } else {
790
+ return {};
791
+ }
792
+ }
793
+ /** Creates a string representation of the target of an `Event` object */
794
+ function serializeEventTarget(target) {
795
+ try {
796
+ return Object.prototype.toString.call(target);
797
+ } catch (_oO) {
798
+ return '<unknown>';
799
+ }
800
+ }
801
+ /**
802
+ * Extracts stack frames from the error and builds an Exception
803
+ */
804
+ async function exceptionFromError(stackParser, frameModifiers, error) {
805
+ const exception = {
806
+ type: error.name || error.constructor.name,
807
+ value: error.message
808
+ };
809
+ let frames = parseStackFrames(stackParser, error);
810
+ for (const modifier of frameModifiers) {
811
+ frames = await modifier(frames);
812
+ }
813
+ if (frames.length) {
814
+ exception.stacktrace = {
815
+ frames,
816
+ type: 'raw'
817
+ };
818
+ }
819
+ return exception;
820
+ }
821
+ /**
822
+ * Extracts stack frames from the error.stack string
823
+ */
824
+ function parseStackFrames(stackParser, error) {
825
+ return stackParser(error.stack || '', 1);
826
+ }
827
+
828
+ const SHUTDOWN_TIMEOUT = 2000;
829
+ class ErrorTracking {
830
+ static async captureException(client, error, hint, distinctId, additionalProperties) {
831
+ const properties = {
832
+ ...additionalProperties
833
+ };
834
+ // Given stateless nature of Node SDK we capture exceptions using personless processing when no
835
+ // user can be determined because a distinct_id is not provided e.g. exception autocapture
836
+ if (!distinctId) {
837
+ properties.$process_person_profile = false;
838
+ }
839
+ const exceptionProperties = await propertiesFromUnknownInput(this.stackParser, this.frameModifiers, error, hint);
840
+ client.capture({
841
+ event: '$exception',
842
+ distinctId: distinctId || uuidv7(),
843
+ properties: {
844
+ ...exceptionProperties,
845
+ ...properties
846
+ }
847
+ });
848
+ }
849
+ constructor(client, options) {
850
+ this.client = client;
851
+ this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;
852
+ this.startAutocaptureIfEnabled();
853
+ }
854
+ startAutocaptureIfEnabled() {
855
+ if (this.isEnabled()) {
856
+ addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));
857
+ addUnhandledRejectionListener(this.onException.bind(this));
858
+ }
859
+ }
860
+ onException(exception, hint) {
861
+ ErrorTracking.captureException(this.client, exception, hint);
862
+ }
863
+ async onFatalError() {
864
+ await this.client.shutdown(SHUTDOWN_TIMEOUT);
865
+ }
866
+ isEnabled() {
867
+ return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
868
+ }
869
+ }
870
+
871
+ function setupExpressErrorHandler(_posthog, app) {
872
+ app.use((error, _, __, next) => {
873
+ const hint = {
874
+ mechanism: {
875
+ type: 'middleware',
876
+ handled: false
877
+ }
878
+ };
879
+ // Given stateless nature of Node SDK we capture exceptions using personless processing
880
+ // when no user can be determined e.g. in the case of exception autocapture
881
+ ErrorTracking.captureException(_posthog, error, hint, uuidv7(), {
882
+ $process_person_profile: false
883
+ });
884
+ next(error);
885
+ });
886
+ }
887
+
888
+ var version = "4.17.0";
889
+
890
+ var PostHogPersistedProperty;
891
+ (function (PostHogPersistedProperty) {
892
+ PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
893
+ PostHogPersistedProperty["DistinctId"] = "distinct_id";
894
+ PostHogPersistedProperty["Props"] = "props";
895
+ PostHogPersistedProperty["FeatureFlagDetails"] = "feature_flag_details";
896
+ PostHogPersistedProperty["FeatureFlags"] = "feature_flags";
897
+ PostHogPersistedProperty["FeatureFlagPayloads"] = "feature_flag_payloads";
898
+ PostHogPersistedProperty["BootstrapFeatureFlagDetails"] = "bootstrap_feature_flag_details";
899
+ PostHogPersistedProperty["BootstrapFeatureFlags"] = "bootstrap_feature_flags";
900
+ PostHogPersistedProperty["BootstrapFeatureFlagPayloads"] = "bootstrap_feature_flag_payloads";
901
+ PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
902
+ PostHogPersistedProperty["Queue"] = "queue";
903
+ PostHogPersistedProperty["OptedOut"] = "opted_out";
904
+ PostHogPersistedProperty["SessionId"] = "session_id";
905
+ PostHogPersistedProperty["SessionLastTimestamp"] = "session_timestamp";
906
+ PostHogPersistedProperty["PersonProperties"] = "person_properties";
907
+ PostHogPersistedProperty["GroupProperties"] = "group_properties";
908
+ PostHogPersistedProperty["InstalledAppBuild"] = "installed_app_build";
909
+ PostHogPersistedProperty["InstalledAppVersion"] = "installed_app_version";
910
+ PostHogPersistedProperty["SessionReplay"] = "session_replay";
911
+ PostHogPersistedProperty["DecideEndpointWasHit"] = "decide_endpoint_was_hit";
912
+ PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
913
+ PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
914
+ PostHogPersistedProperty["Surveys"] = "surveys";
915
+ PostHogPersistedProperty["RemoteConfig"] = "remote_config";
916
+ })(PostHogPersistedProperty || (PostHogPersistedProperty = {}));
917
+ var SurveyPosition;
918
+ (function (SurveyPosition) {
919
+ SurveyPosition["Left"] = "left";
920
+ SurveyPosition["Right"] = "right";
921
+ SurveyPosition["Center"] = "center";
922
+ })(SurveyPosition || (SurveyPosition = {}));
923
+ var SurveyWidgetType;
924
+ (function (SurveyWidgetType) {
925
+ SurveyWidgetType["Button"] = "button";
926
+ SurveyWidgetType["Tab"] = "tab";
927
+ SurveyWidgetType["Selector"] = "selector";
928
+ })(SurveyWidgetType || (SurveyWidgetType = {}));
929
+ var SurveyType;
930
+ (function (SurveyType) {
931
+ SurveyType["Popover"] = "popover";
932
+ SurveyType["API"] = "api";
933
+ SurveyType["Widget"] = "widget";
934
+ })(SurveyType || (SurveyType = {}));
935
+ var SurveyQuestionDescriptionContentType;
936
+ (function (SurveyQuestionDescriptionContentType) {
937
+ SurveyQuestionDescriptionContentType["Html"] = "html";
938
+ SurveyQuestionDescriptionContentType["Text"] = "text";
939
+ })(SurveyQuestionDescriptionContentType || (SurveyQuestionDescriptionContentType = {}));
940
+ var SurveyRatingDisplay;
941
+ (function (SurveyRatingDisplay) {
942
+ SurveyRatingDisplay["Number"] = "number";
943
+ SurveyRatingDisplay["Emoji"] = "emoji";
944
+ })(SurveyRatingDisplay || (SurveyRatingDisplay = {}));
945
+ var SurveyQuestionType;
946
+ (function (SurveyQuestionType) {
947
+ SurveyQuestionType["Open"] = "open";
948
+ SurveyQuestionType["MultipleChoice"] = "multiple_choice";
949
+ SurveyQuestionType["SingleChoice"] = "single_choice";
950
+ SurveyQuestionType["Rating"] = "rating";
951
+ SurveyQuestionType["Link"] = "link";
952
+ })(SurveyQuestionType || (SurveyQuestionType = {}));
953
+ var SurveyQuestionBranchingType;
954
+ (function (SurveyQuestionBranchingType) {
955
+ SurveyQuestionBranchingType["NextQuestion"] = "next_question";
956
+ SurveyQuestionBranchingType["End"] = "end";
957
+ SurveyQuestionBranchingType["ResponseBased"] = "response_based";
958
+ SurveyQuestionBranchingType["SpecificQuestion"] = "specific_question";
959
+ })(SurveyQuestionBranchingType || (SurveyQuestionBranchingType = {}));
960
+ var SurveyMatchType;
961
+ (function (SurveyMatchType) {
962
+ SurveyMatchType["Regex"] = "regex";
963
+ SurveyMatchType["NotRegex"] = "not_regex";
964
+ SurveyMatchType["Exact"] = "exact";
965
+ SurveyMatchType["IsNot"] = "is_not";
966
+ SurveyMatchType["Icontains"] = "icontains";
967
+ SurveyMatchType["NotIcontains"] = "not_icontains";
968
+ })(SurveyMatchType || (SurveyMatchType = {}));
969
+ /** Sync with plugin-server/src/types.ts */
970
+ var ActionStepStringMatching;
971
+ (function (ActionStepStringMatching) {
972
+ ActionStepStringMatching["Contains"] = "contains";
973
+ ActionStepStringMatching["Exact"] = "exact";
974
+ ActionStepStringMatching["Regex"] = "regex";
975
+ })(ActionStepStringMatching || (ActionStepStringMatching = {}));
976
+
977
+ const normalizeDecideResponse = (decideResponse) => {
978
+ if ('flags' in decideResponse) {
979
+ // Convert v4 format to v3 format
980
+ const featureFlags = getFlagValuesFromFlags(decideResponse.flags);
981
+ const featureFlagPayloads = getPayloadsFromFlags(decideResponse.flags);
982
+ return {
983
+ ...decideResponse,
984
+ featureFlags,
985
+ featureFlagPayloads,
986
+ };
987
+ }
988
+ else {
989
+ // Convert v3 format to v4 format
990
+ const featureFlags = decideResponse.featureFlags ?? {};
991
+ const featureFlagPayloads = Object.fromEntries(Object.entries(decideResponse.featureFlagPayloads || {}).map(([k, v]) => [k, parsePayload(v)]));
992
+ const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
993
+ key,
994
+ getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key]),
995
+ ]));
996
+ return {
997
+ ...decideResponse,
998
+ featureFlags,
999
+ featureFlagPayloads,
1000
+ flags,
1001
+ };
1002
+ }
1003
+ };
1004
+ function getFlagDetailFromFlagAndPayload(key, value, payload) {
1005
+ return {
1006
+ key: key,
1007
+ enabled: typeof value === 'string' ? true : value,
1008
+ variant: typeof value === 'string' ? value : undefined,
1009
+ reason: undefined,
1010
+ metadata: {
1011
+ id: undefined,
1012
+ version: undefined,
1013
+ payload: payload ? JSON.stringify(payload) : undefined,
1014
+ description: undefined,
1015
+ },
1016
+ };
1017
+ }
1018
+ /**
1019
+ * Get the flag values from the flags v4 response.
1020
+ * @param flags - The flags
1021
+ * @returns The flag values
1022
+ */
1023
+ const getFlagValuesFromFlags = (flags) => {
1024
+ return Object.fromEntries(Object.entries(flags ?? {})
1025
+ .map(([key, detail]) => [key, getFeatureFlagValue(detail)])
1026
+ .filter(([, value]) => value !== undefined));
1027
+ };
1028
+ /**
1029
+ * Get the payloads from the flags v4 response.
1030
+ * @param flags - The flags
1031
+ * @returns The payloads
1032
+ */
1033
+ const getPayloadsFromFlags = (flags) => {
1034
+ const safeFlags = flags ?? {};
1035
+ return Object.fromEntries(Object.keys(safeFlags)
1036
+ .filter((flag) => {
1037
+ const details = safeFlags[flag];
1038
+ return details.enabled && details.metadata && details.metadata.payload !== undefined;
1039
+ })
1040
+ .map((flag) => {
1041
+ const payload = safeFlags[flag].metadata?.payload;
1042
+ return [flag, payload ? parsePayload(payload) : undefined];
1043
+ }));
1044
+ };
1045
+ const getFeatureFlagValue = (detail) => {
1046
+ return detail === undefined ? undefined : detail.variant ?? detail.enabled;
1047
+ };
1048
+ const parsePayload = (response) => {
1049
+ if (typeof response !== 'string') {
1050
+ return response;
1051
+ }
1052
+ try {
1053
+ return JSON.parse(response);
1054
+ }
1055
+ catch {
1056
+ return response;
1057
+ }
1058
+ };
1059
+
1060
+ // Rollout constants
1061
+ const NEW_FLAGS_ROLLOUT_PERCENTAGE = 1;
1062
+ // The fnv1a hashes of the tokens that are explicitly excluded from the rollout
1063
+ // see https://github.com/PostHog/posthog-js-lite/blob/main/posthog-core/src/utils.ts#L84
1064
+ // are hashed API tokens from our top 10 for each category supported by this SDK.
1065
+ const NEW_FLAGS_EXCLUDED_HASHES = new Set([
1066
+ // Node
1067
+ '61be3dd8',
1068
+ '96f6df5f',
1069
+ '8cfdba9b',
1070
+ 'bf027177',
1071
+ 'e59430a8',
1072
+ '7fa5500b',
1073
+ '569798e9',
1074
+ '04809ff7',
1075
+ '0ebc61a5',
1076
+ '32de7f98',
1077
+ '3beeb69a',
1078
+ '12d34ad9',
1079
+ '733853ec',
1080
+ '0645bb64',
1081
+ '5dcbee21',
1082
+ 'b1f95fa3',
1083
+ '2189e408',
1084
+ '82b460c2',
1085
+ '3a8cc979',
1086
+ '29ef8843',
1087
+ '2cdbf767',
1088
+ '38084b54',
1089
+ // React Native
1090
+ '50f9f8de',
1091
+ '41d0df91',
1092
+ '5c236689',
1093
+ 'c11aedd3',
1094
+ 'ada46672',
1095
+ 'f4331ee1',
1096
+ '42fed62a',
1097
+ 'c957462c',
1098
+ 'd62f705a',
1099
+ // Web (lots of teams per org, hence lots of API tokens)
1100
+ 'e0162666',
1101
+ '01b3e5cf',
1102
+ '441cef7f',
1103
+ 'bb9cafee',
1104
+ '8f348eb0',
1105
+ 'b2553f3a',
1106
+ '97469d7d',
1107
+ '39f21a76',
1108
+ '03706dcc',
1109
+ '27d50569',
1110
+ '307584a7',
1111
+ '6433e92e',
1112
+ '150c7fbb',
1113
+ '49f57f22',
1114
+ '3772f65b',
1115
+ '01eb8256',
1116
+ '3c9e9234',
1117
+ 'f853c7f7',
1118
+ 'c0ac4b67',
1119
+ 'cd609d40',
1120
+ '10ca9b1a',
1121
+ '8a87f11b',
1122
+ '8e8e5216',
1123
+ '1f6b63b3',
1124
+ 'db7943dd',
1125
+ '79b7164c',
1126
+ '07f78e33',
1127
+ '2d21b6fd',
1128
+ '952db5ee',
1129
+ 'a7d3b43f',
1130
+ '1924dd9c',
1131
+ '84e1b8f6',
1132
+ 'dff631b6',
1133
+ 'c5aa8a79',
1134
+ 'fa133a95',
1135
+ '498a4508',
1136
+ '24748755',
1137
+ '98f3d658',
1138
+ '21bbda67',
1139
+ '7dbfed69',
1140
+ 'be3ec24c',
1141
+ 'fc80b8e2',
1142
+ '75cc0998',
1143
+ ]);
1144
+ const STRING_FORMAT = 'utf8';
1145
+ function assert(truthyValue, message) {
1146
+ if (!truthyValue || typeof truthyValue !== 'string' || isEmpty(truthyValue)) {
1147
+ throw new Error(message);
1148
+ }
1149
+ }
1150
+ function isEmpty(truthyValue) {
1151
+ if (truthyValue.trim().length === 0) {
1152
+ return true;
1153
+ }
1154
+ return false;
1155
+ }
1156
+ function removeTrailingSlash(url) {
1157
+ return url?.replace(/\/+$/, '');
1158
+ }
1159
+ async function retriable(fn, props) {
1160
+ let lastError = null;
1161
+ for (let i = 0; i < props.retryCount + 1; i++) {
1162
+ if (i > 0) {
1163
+ // don't wait when it's the last try
1164
+ await new Promise((r) => setTimeout(r, props.retryDelay));
1165
+ }
1166
+ try {
1167
+ const res = await fn();
1168
+ return res;
1169
+ }
1170
+ catch (e) {
1171
+ lastError = e;
1172
+ if (!props.retryCheck(e)) {
1173
+ throw e;
1174
+ }
1175
+ }
1176
+ }
1177
+ throw lastError;
1178
+ }
1179
+ function currentTimestamp() {
1180
+ return new Date().getTime();
1181
+ }
1182
+ function currentISOTime() {
1183
+ return new Date().toISOString();
1184
+ }
1185
+ function safeSetTimeout(fn, timeout) {
1186
+ // NOTE: we use this so rarely that it is totally fine to do `safeSetTimeout(fn, 0)``
1187
+ // rather than setImmediate.
1188
+ const t = setTimeout(fn, timeout);
1189
+ // We unref if available to prevent Node.js hanging on exit
1190
+ t?.unref && t?.unref();
1191
+ return t;
1192
+ }
1193
+ function getFetch() {
1194
+ return typeof fetch !== 'undefined' ? fetch : typeof globalThis.fetch !== 'undefined' ? globalThis.fetch : undefined;
1195
+ }
1196
+ // FNV-1a hash function
1197
+ // https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
1198
+ // I know, I know, I'm rolling my own hash function, but I didn't want to take on
1199
+ // a crypto dependency and this is just temporary anyway
1200
+ function fnv1a(str) {
1201
+ let hash = 0x811c9dc5; // FNV offset basis
1202
+ for (let i = 0; i < str.length; i++) {
1203
+ hash ^= str.charCodeAt(i);
1204
+ hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
1205
+ }
1206
+ // Convert to hex string, padding to 8 chars
1207
+ return (hash >>> 0).toString(16).padStart(8, '0');
1208
+ }
1209
+ function isTokenInRollout(token, percentage = 0, excludedHashes) {
1210
+ const tokenHash = fnv1a(token);
1211
+ // Check excluded hashes (we're explicitly including these tokens from the rollout)
1212
+ if (excludedHashes?.has(tokenHash)) {
1213
+ return false;
1214
+ }
1215
+ // Convert hash to int and divide by max value to get number between 0-1
1216
+ const hashInt = parseInt(tokenHash, 16);
1217
+ const hashFloat = hashInt / 0xffffffff;
1218
+ return hashFloat < percentage;
1219
+ }
1220
+
1221
+ // Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>
1222
+ // This work is free. You can redistribute it and/or modify it
1223
+ // under the terms of the WTFPL, Version 2
1224
+ // For more information see LICENSE.txt or http://www.wtfpl.net/
1225
+ //
1226
+ // For more information, the home page:
1227
+ // http://pieroxy.net/blog/pages/lz-string/testing.html
1228
+ //
1229
+ // LZ-based compression algorithm, version 1.4.4
1230
+ // private property
1231
+ const f = String.fromCharCode;
1232
+ const keyStrBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
1233
+ const baseReverseDic = {};
1234
+ function getBaseValue(alphabet, character) {
1235
+ if (!baseReverseDic[alphabet]) {
1236
+ baseReverseDic[alphabet] = {};
1237
+ for (let i = 0; i < alphabet.length; i++) {
1238
+ baseReverseDic[alphabet][alphabet.charAt(i)] = i;
1239
+ }
1240
+ }
1241
+ return baseReverseDic[alphabet][character];
1242
+ }
1243
+ const LZString = {
1244
+ compressToBase64: function (input) {
1245
+ if (input == null) {
1246
+ return '';
1247
+ }
1248
+ const res = LZString._compress(input, 6, function (a) {
1249
+ return keyStrBase64.charAt(a);
1250
+ });
1251
+ switch (res.length % 4 // To produce valid Base64
1252
+ ) {
1253
+ default: // When could this happen ?
1254
+ case 0:
1255
+ return res;
1256
+ case 1:
1257
+ return res + '===';
1258
+ case 2:
1259
+ return res + '==';
1260
+ case 3:
1261
+ return res + '=';
1262
+ }
1263
+ },
1264
+ decompressFromBase64: function (input) {
1265
+ if (input == null) {
1266
+ return '';
1267
+ }
1268
+ if (input == '') {
1269
+ return null;
1270
+ }
1271
+ return LZString._decompress(input.length, 32, function (index) {
1272
+ return getBaseValue(keyStrBase64, input.charAt(index));
1273
+ });
1274
+ },
1275
+ compress: function (uncompressed) {
1276
+ return LZString._compress(uncompressed, 16, function (a) {
1277
+ return f(a);
1278
+ });
1279
+ },
1280
+ _compress: function (uncompressed, bitsPerChar, getCharFromInt) {
1281
+ if (uncompressed == null) {
1282
+ return '';
1283
+ }
1284
+ const context_dictionary = {}, context_dictionaryToCreate = {}, context_data = [];
1285
+ let i, value, context_c = '', context_wc = '', context_w = '', context_enlargeIn = 2, // Compensate for the first entry which should not count
1286
+ context_dictSize = 3, context_numBits = 2, context_data_val = 0, context_data_position = 0, ii;
1287
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
1288
+ context_c = uncompressed.charAt(ii);
1289
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
1290
+ context_dictionary[context_c] = context_dictSize++;
1291
+ context_dictionaryToCreate[context_c] = true;
1292
+ }
1293
+ context_wc = context_w + context_c;
1294
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) {
1295
+ context_w = context_wc;
1296
+ }
1297
+ else {
1298
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
1299
+ if (context_w.charCodeAt(0) < 256) {
1300
+ for (i = 0; i < context_numBits; i++) {
1301
+ context_data_val = context_data_val << 1;
1302
+ if (context_data_position == bitsPerChar - 1) {
1303
+ context_data_position = 0;
1304
+ context_data.push(getCharFromInt(context_data_val));
1305
+ context_data_val = 0;
1306
+ }
1307
+ else {
1308
+ context_data_position++;
1309
+ }
1310
+ }
1311
+ value = context_w.charCodeAt(0);
1312
+ for (i = 0; i < 8; i++) {
1313
+ context_data_val = (context_data_val << 1) | (value & 1);
1314
+ if (context_data_position == bitsPerChar - 1) {
1315
+ context_data_position = 0;
1316
+ context_data.push(getCharFromInt(context_data_val));
1317
+ context_data_val = 0;
1318
+ }
1319
+ else {
1320
+ context_data_position++;
1321
+ }
1322
+ value = value >> 1;
1323
+ }
1324
+ }
1325
+ else {
1326
+ value = 1;
1327
+ for (i = 0; i < context_numBits; i++) {
1328
+ context_data_val = (context_data_val << 1) | value;
1329
+ if (context_data_position == bitsPerChar - 1) {
1330
+ context_data_position = 0;
1331
+ context_data.push(getCharFromInt(context_data_val));
1332
+ context_data_val = 0;
1333
+ }
1334
+ else {
1335
+ context_data_position++;
1336
+ }
1337
+ value = 0;
1338
+ }
1339
+ value = context_w.charCodeAt(0);
1340
+ for (i = 0; i < 16; i++) {
1341
+ context_data_val = (context_data_val << 1) | (value & 1);
1342
+ if (context_data_position == bitsPerChar - 1) {
1343
+ context_data_position = 0;
1344
+ context_data.push(getCharFromInt(context_data_val));
1345
+ context_data_val = 0;
1346
+ }
1347
+ else {
1348
+ context_data_position++;
1349
+ }
1350
+ value = value >> 1;
1351
+ }
1352
+ }
1353
+ context_enlargeIn--;
1354
+ if (context_enlargeIn == 0) {
1355
+ context_enlargeIn = Math.pow(2, context_numBits);
1356
+ context_numBits++;
1357
+ }
1358
+ delete context_dictionaryToCreate[context_w];
1359
+ }
1360
+ else {
1361
+ value = context_dictionary[context_w];
1362
+ for (i = 0; i < context_numBits; i++) {
1363
+ context_data_val = (context_data_val << 1) | (value & 1);
1364
+ if (context_data_position == bitsPerChar - 1) {
1365
+ context_data_position = 0;
1366
+ context_data.push(getCharFromInt(context_data_val));
1367
+ context_data_val = 0;
1368
+ }
1369
+ else {
1370
+ context_data_position++;
1371
+ }
1372
+ value = value >> 1;
1373
+ }
1374
+ }
1375
+ context_enlargeIn--;
1376
+ if (context_enlargeIn == 0) {
1377
+ context_enlargeIn = Math.pow(2, context_numBits);
1378
+ context_numBits++;
1379
+ }
1380
+ // Add wc to the dictionary.
1381
+ context_dictionary[context_wc] = context_dictSize++;
1382
+ context_w = String(context_c);
1383
+ }
1384
+ }
1385
+ // Output the code for w.
1386
+ if (context_w !== '') {
1387
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
1388
+ if (context_w.charCodeAt(0) < 256) {
1389
+ for (i = 0; i < context_numBits; i++) {
1390
+ context_data_val = context_data_val << 1;
1391
+ if (context_data_position == bitsPerChar - 1) {
1392
+ context_data_position = 0;
1393
+ context_data.push(getCharFromInt(context_data_val));
1394
+ context_data_val = 0;
1395
+ }
1396
+ else {
1397
+ context_data_position++;
1398
+ }
1399
+ }
1400
+ value = context_w.charCodeAt(0);
1401
+ for (i = 0; i < 8; i++) {
1402
+ context_data_val = (context_data_val << 1) | (value & 1);
1403
+ if (context_data_position == bitsPerChar - 1) {
1404
+ context_data_position = 0;
1405
+ context_data.push(getCharFromInt(context_data_val));
1406
+ context_data_val = 0;
1407
+ }
1408
+ else {
1409
+ context_data_position++;
1410
+ }
1411
+ value = value >> 1;
1412
+ }
1413
+ }
1414
+ else {
1415
+ value = 1;
1416
+ for (i = 0; i < context_numBits; i++) {
1417
+ context_data_val = (context_data_val << 1) | value;
1418
+ if (context_data_position == bitsPerChar - 1) {
1419
+ context_data_position = 0;
1420
+ context_data.push(getCharFromInt(context_data_val));
1421
+ context_data_val = 0;
1422
+ }
1423
+ else {
1424
+ context_data_position++;
1425
+ }
1426
+ value = 0;
1427
+ }
1428
+ value = context_w.charCodeAt(0);
1429
+ for (i = 0; i < 16; i++) {
1430
+ context_data_val = (context_data_val << 1) | (value & 1);
1431
+ if (context_data_position == bitsPerChar - 1) {
1432
+ context_data_position = 0;
1433
+ context_data.push(getCharFromInt(context_data_val));
1434
+ context_data_val = 0;
1435
+ }
1436
+ else {
1437
+ context_data_position++;
1438
+ }
1439
+ value = value >> 1;
1440
+ }
1441
+ }
1442
+ context_enlargeIn--;
1443
+ if (context_enlargeIn == 0) {
1444
+ context_enlargeIn = Math.pow(2, context_numBits);
1445
+ context_numBits++;
1446
+ }
1447
+ delete context_dictionaryToCreate[context_w];
1448
+ }
1449
+ else {
1450
+ value = context_dictionary[context_w];
1451
+ for (i = 0; i < context_numBits; i++) {
1452
+ context_data_val = (context_data_val << 1) | (value & 1);
1453
+ if (context_data_position == bitsPerChar - 1) {
1454
+ context_data_position = 0;
1455
+ context_data.push(getCharFromInt(context_data_val));
1456
+ context_data_val = 0;
1457
+ }
1458
+ else {
1459
+ context_data_position++;
1460
+ }
1461
+ value = value >> 1;
1462
+ }
1463
+ }
1464
+ context_enlargeIn--;
1465
+ if (context_enlargeIn == 0) {
1466
+ context_enlargeIn = Math.pow(2, context_numBits);
1467
+ context_numBits++;
1468
+ }
1469
+ }
1470
+ // Mark the end of the stream
1471
+ value = 2;
1472
+ for (i = 0; i < context_numBits; i++) {
1473
+ context_data_val = (context_data_val << 1) | (value & 1);
1474
+ if (context_data_position == bitsPerChar - 1) {
1475
+ context_data_position = 0;
1476
+ context_data.push(getCharFromInt(context_data_val));
1477
+ context_data_val = 0;
1478
+ }
1479
+ else {
1480
+ context_data_position++;
1481
+ }
1482
+ value = value >> 1;
1483
+ }
1484
+ // Flush the last char
1485
+ while (true) {
1486
+ context_data_val = context_data_val << 1;
1487
+ if (context_data_position == bitsPerChar - 1) {
1488
+ context_data.push(getCharFromInt(context_data_val));
1489
+ break;
1490
+ }
1491
+ else {
1492
+ context_data_position++;
1493
+ }
1494
+ }
1495
+ return context_data.join('');
1496
+ },
1497
+ decompress: function (compressed) {
1498
+ if (compressed == null) {
1499
+ return '';
1500
+ }
1501
+ if (compressed == '') {
1502
+ return null;
1503
+ }
1504
+ return LZString._decompress(compressed.length, 32768, function (index) {
1505
+ return compressed.charCodeAt(index);
1506
+ });
1507
+ },
1508
+ _decompress: function (length, resetValue, getNextValue) {
1509
+ const dictionary = [], result = [], data = { val: getNextValue(0), position: resetValue, index: 1 };
1510
+ let enlargeIn = 4, dictSize = 4, numBits = 3, entry = '', i, w, bits, resb, maxpower, power, c;
1511
+ for (i = 0; i < 3; i += 1) {
1512
+ dictionary[i] = i;
1513
+ }
1514
+ bits = 0;
1515
+ maxpower = Math.pow(2, 2);
1516
+ power = 1;
1517
+ while (power != maxpower) {
1518
+ resb = data.val & data.position;
1519
+ data.position >>= 1;
1520
+ if (data.position == 0) {
1521
+ data.position = resetValue;
1522
+ data.val = getNextValue(data.index++);
1523
+ }
1524
+ bits |= (resb > 0 ? 1 : 0) * power;
1525
+ power <<= 1;
1526
+ }
1527
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1528
+ switch ((bits)) {
1529
+ case 0:
1530
+ bits = 0;
1531
+ maxpower = Math.pow(2, 8);
1532
+ power = 1;
1533
+ while (power != maxpower) {
1534
+ resb = data.val & data.position;
1535
+ data.position >>= 1;
1536
+ if (data.position == 0) {
1537
+ data.position = resetValue;
1538
+ data.val = getNextValue(data.index++);
1539
+ }
1540
+ bits |= (resb > 0 ? 1 : 0) * power;
1541
+ power <<= 1;
1542
+ }
1543
+ c = f(bits);
1544
+ break;
1545
+ case 1:
1546
+ bits = 0;
1547
+ maxpower = Math.pow(2, 16);
1548
+ power = 1;
1549
+ while (power != maxpower) {
1550
+ resb = data.val & data.position;
1551
+ data.position >>= 1;
1552
+ if (data.position == 0) {
1553
+ data.position = resetValue;
1554
+ data.val = getNextValue(data.index++);
1555
+ }
1556
+ bits |= (resb > 0 ? 1 : 0) * power;
1557
+ power <<= 1;
1558
+ }
1559
+ c = f(bits);
1560
+ break;
1561
+ case 2:
1562
+ return '';
1563
+ }
1564
+ dictionary[3] = c;
1565
+ w = c;
1566
+ result.push(c);
1567
+ while (true) {
1568
+ if (data.index > length) {
1569
+ return '';
1570
+ }
1571
+ bits = 0;
1572
+ maxpower = Math.pow(2, numBits);
1573
+ power = 1;
1574
+ while (power != maxpower) {
1575
+ resb = data.val & data.position;
1576
+ data.position >>= 1;
1577
+ if (data.position == 0) {
1578
+ data.position = resetValue;
1579
+ data.val = getNextValue(data.index++);
1580
+ }
1581
+ bits |= (resb > 0 ? 1 : 0) * power;
1582
+ power <<= 1;
1583
+ }
1584
+ switch ((c = bits)) {
1585
+ case 0:
1586
+ bits = 0;
1587
+ maxpower = Math.pow(2, 8);
1588
+ power = 1;
1589
+ while (power != maxpower) {
1590
+ resb = data.val & data.position;
1591
+ data.position >>= 1;
1592
+ if (data.position == 0) {
1593
+ data.position = resetValue;
1594
+ data.val = getNextValue(data.index++);
1595
+ }
1596
+ bits |= (resb > 0 ? 1 : 0) * power;
1597
+ power <<= 1;
1598
+ }
1599
+ dictionary[dictSize++] = f(bits);
1600
+ c = dictSize - 1;
1601
+ enlargeIn--;
1602
+ break;
1603
+ case 1:
1604
+ bits = 0;
1605
+ maxpower = Math.pow(2, 16);
1606
+ power = 1;
1607
+ while (power != maxpower) {
1608
+ resb = data.val & data.position;
1609
+ data.position >>= 1;
1610
+ if (data.position == 0) {
1611
+ data.position = resetValue;
1612
+ data.val = getNextValue(data.index++);
1613
+ }
1614
+ bits |= (resb > 0 ? 1 : 0) * power;
1615
+ power <<= 1;
1616
+ }
1617
+ dictionary[dictSize++] = f(bits);
1618
+ c = dictSize - 1;
1619
+ enlargeIn--;
1620
+ break;
1621
+ case 2:
1622
+ return result.join('');
1623
+ }
1624
+ if (enlargeIn == 0) {
1625
+ enlargeIn = Math.pow(2, numBits);
1626
+ numBits++;
1627
+ }
1628
+ if (dictionary[c]) {
1629
+ entry = dictionary[c];
1630
+ }
1631
+ else {
1632
+ if (c === dictSize) {
1633
+ entry = w + w.charAt(0);
1634
+ }
1635
+ else {
1636
+ return null;
1637
+ }
1638
+ }
1639
+ result.push(entry);
1640
+ // Add w+entry[0] to the dictionary.
1641
+ dictionary[dictSize++] = w + entry.charAt(0);
1642
+ enlargeIn--;
1643
+ w = entry;
1644
+ if (enlargeIn == 0) {
1645
+ enlargeIn = Math.pow(2, numBits);
1646
+ numBits++;
1647
+ }
1648
+ }
1649
+ },
1650
+ };
1651
+
1652
+ class SimpleEventEmitter {
1653
+ constructor() {
1654
+ this.events = {};
1655
+ this.events = {};
1656
+ }
1657
+ on(event, listener) {
1658
+ if (!this.events[event]) {
1659
+ this.events[event] = [];
1660
+ }
1661
+ this.events[event].push(listener);
1662
+ return () => {
1663
+ this.events[event] = this.events[event].filter((x) => x !== listener);
1664
+ };
1665
+ }
1666
+ emit(event, payload) {
1667
+ for (const listener of this.events[event] || []) {
1668
+ listener(payload);
1669
+ }
1670
+ for (const listener of this.events['*'] || []) {
1671
+ listener(event, payload);
1672
+ }
1673
+ }
1674
+ }
1675
+
1676
+ class PostHogFetchHttpError extends Error {
1677
+ constructor(response, reqByteLength) {
1678
+ super('HTTP error while fetching PostHog: status=' + response.status + ', reqByteLength=' + reqByteLength);
1679
+ this.response = response;
1680
+ this.reqByteLength = reqByteLength;
1681
+ this.name = 'PostHogFetchHttpError';
1682
+ }
1683
+ get status() {
1684
+ return this.response.status;
1685
+ }
1686
+ get text() {
1687
+ return this.response.text();
1688
+ }
1689
+ get json() {
1690
+ return this.response.json();
1691
+ }
1692
+ }
1693
+ class PostHogFetchNetworkError extends Error {
1694
+ constructor(error) {
1695
+ // TRICKY: "cause" is a newer property but is just ignored otherwise. Cast to any to ignore the type issue.
1696
+ // eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
1697
+ // @ts-ignore
1698
+ super('Network error while fetching PostHog', error instanceof Error ? { cause: error } : {});
1699
+ this.error = error;
1700
+ this.name = 'PostHogFetchNetworkError';
1701
+ }
1702
+ }
1703
+ async function logFlushError(err) {
1704
+ if (err instanceof PostHogFetchHttpError) {
1705
+ let text = '';
1706
+ try {
1707
+ text = await err.text;
1708
+ }
1709
+ catch { }
1710
+ console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
1711
+ }
1712
+ else {
1713
+ console.error('Error while flushing PostHog', err);
1714
+ }
1715
+ return Promise.resolve();
1716
+ }
1717
+ function isPostHogFetchError(err) {
1718
+ return typeof err === 'object' && (err instanceof PostHogFetchHttpError || err instanceof PostHogFetchNetworkError);
1719
+ }
1720
+ function isPostHogFetchContentTooLargeError(err) {
1721
+ return typeof err === 'object' && err instanceof PostHogFetchHttpError && err.status === 413;
1722
+ }
1723
+ var QuotaLimitedFeature;
1724
+ (function (QuotaLimitedFeature) {
1725
+ QuotaLimitedFeature["FeatureFlags"] = "feature_flags";
1726
+ QuotaLimitedFeature["Recordings"] = "recordings";
1727
+ })(QuotaLimitedFeature || (QuotaLimitedFeature = {}));
1728
+ class PostHogCoreStateless {
1729
+ constructor(apiKey, options) {
1730
+ this.flushPromise = null;
1731
+ this.shutdownPromise = null;
1732
+ this.pendingPromises = {};
1733
+ // internal
1734
+ this._events = new SimpleEventEmitter();
1735
+ this._isInitialized = false;
1736
+ assert(apiKey, "You must pass your PostHog project's api key.");
1737
+ this.apiKey = apiKey;
1738
+ this.host = removeTrailingSlash(options?.host || 'https://us.i.posthog.com');
1739
+ this.flushAt = options?.flushAt ? Math.max(options?.flushAt, 1) : 20;
1740
+ this.maxBatchSize = Math.max(this.flushAt, options?.maxBatchSize ?? 100);
1741
+ this.maxQueueSize = Math.max(this.flushAt, options?.maxQueueSize ?? 1000);
1742
+ this.flushInterval = options?.flushInterval ?? 10000;
1743
+ this.captureMode = options?.captureMode || 'json';
1744
+ this.preloadFeatureFlags = options?.preloadFeatureFlags ?? true;
1745
+ // If enable is explicitly set to false we override the optout
1746
+ this.defaultOptIn = options?.defaultOptIn ?? true;
1747
+ this.disableSurveys = options?.disableSurveys ?? false;
1748
+ this._retryOptions = {
1749
+ retryCount: options?.fetchRetryCount ?? 3,
1750
+ retryDelay: options?.fetchRetryDelay ?? 3000,
1751
+ retryCheck: isPostHogFetchError,
1752
+ };
1753
+ this.requestTimeout = options?.requestTimeout ?? 10000; // 10 seconds
1754
+ this.featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 3000; // 3 seconds
1755
+ this.remoteConfigRequestTimeoutMs = options?.remoteConfigRequestTimeoutMs ?? 3000; // 3 seconds
1756
+ this.disableGeoip = options?.disableGeoip ?? true;
1757
+ this.disabled = options?.disabled ?? false;
1758
+ this.historicalMigration = options?.historicalMigration ?? false;
1759
+ // Init promise allows the derived class to block calls until it is ready
1760
+ this._initPromise = Promise.resolve();
1761
+ this._isInitialized = true;
1762
+ }
1763
+ logMsgIfDebug(fn) {
1764
+ if (this.isDebug) {
1765
+ fn();
1766
+ }
1767
+ }
1768
+ wrap(fn) {
1769
+ if (this.disabled) {
1770
+ this.logMsgIfDebug(() => console.warn('[PostHog] The client is disabled'));
1771
+ return;
1772
+ }
1773
+ if (this._isInitialized) {
1774
+ // NOTE: We could also check for the "opt in" status here...
1775
+ return fn();
1776
+ }
1777
+ this._initPromise.then(() => fn());
1778
+ }
1779
+ getCommonEventProperties() {
1780
+ return {
1781
+ $lib: this.getLibraryId(),
1782
+ $lib_version: this.getLibraryVersion(),
1783
+ };
1784
+ }
1785
+ get optedOut() {
1786
+ return this.getPersistedProperty(PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
1787
+ }
1788
+ async optIn() {
1789
+ this.wrap(() => {
1790
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
1791
+ });
1792
+ }
1793
+ async optOut() {
1794
+ this.wrap(() => {
1795
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
1796
+ });
1797
+ }
1798
+ on(event, cb) {
1799
+ return this._events.on(event, cb);
1800
+ }
1801
+ debug(enabled = true) {
1802
+ this.removeDebugCallback?.();
1803
+ if (enabled) {
1804
+ const removeDebugCallback = this.on('*', (event, payload) => console.log('PostHog Debug', event, payload));
1805
+ this.removeDebugCallback = () => {
1806
+ removeDebugCallback();
1807
+ this.removeDebugCallback = undefined;
1808
+ };
1809
+ }
1810
+ }
1811
+ get isDebug() {
1812
+ return !!this.removeDebugCallback;
1813
+ }
1814
+ get isDisabled() {
1815
+ return this.disabled;
1816
+ }
1817
+ buildPayload(payload) {
1818
+ return {
1819
+ distinct_id: payload.distinct_id,
1820
+ event: payload.event,
1821
+ properties: {
1822
+ ...(payload.properties || {}),
1823
+ ...this.getCommonEventProperties(), // Common PH props
1824
+ },
1825
+ };
1826
+ }
1827
+ addPendingPromise(promise) {
1828
+ const promiseUUID = uuidv7();
1829
+ this.pendingPromises[promiseUUID] = promise;
1830
+ promise
1831
+ .catch(() => { })
1832
+ .finally(() => {
1833
+ delete this.pendingPromises[promiseUUID];
1834
+ });
1835
+ return promise;
1836
+ }
1837
+ /***
1838
+ *** TRACKING
1839
+ ***/
1840
+ identifyStateless(distinctId, properties, options) {
1841
+ this.wrap(() => {
1842
+ // The properties passed to identifyStateless are event properties.
1843
+ // To add person properties, pass in all person properties to the `$set` and `$set_once` keys.
1844
+ const payload = {
1845
+ ...this.buildPayload({
1846
+ distinct_id: distinctId,
1847
+ event: '$identify',
1848
+ properties,
1849
+ }),
1850
+ };
1851
+ this.enqueue('identify', payload, options);
1852
+ });
1853
+ }
1854
+ async identifyStatelessImmediate(distinctId, properties, options) {
1855
+ const payload = {
1856
+ ...this.buildPayload({
1857
+ distinct_id: distinctId,
1858
+ event: '$identify',
1859
+ properties,
1860
+ }),
1861
+ };
1862
+ await this.sendImmediate('identify', payload, options);
1863
+ }
1864
+ captureStateless(distinctId, event, properties, options) {
1865
+ this.wrap(() => {
1866
+ const payload = this.buildPayload({ distinct_id: distinctId, event, properties });
1867
+ this.enqueue('capture', payload, options);
1868
+ });
1869
+ }
1870
+ async captureStatelessImmediate(distinctId, event, properties, options) {
1871
+ const payload = this.buildPayload({ distinct_id: distinctId, event, properties });
1872
+ await this.sendImmediate('capture', payload, options);
1873
+ }
1874
+ aliasStateless(alias, distinctId, properties, options) {
1875
+ this.wrap(() => {
1876
+ const payload = this.buildPayload({
1877
+ event: '$create_alias',
1878
+ distinct_id: distinctId,
1879
+ properties: {
1880
+ ...(properties || {}),
1881
+ distinct_id: distinctId,
1882
+ alias,
1883
+ },
1884
+ });
1885
+ this.enqueue('alias', payload, options);
1886
+ });
1887
+ }
1888
+ async aliasStatelessImmediate(alias, distinctId, properties, options) {
1889
+ const payload = this.buildPayload({
1890
+ event: '$create_alias',
1891
+ distinct_id: distinctId,
1892
+ properties: {
1893
+ ...(properties || {}),
1894
+ distinct_id: distinctId,
1895
+ alias,
1896
+ },
1897
+ });
1898
+ await this.sendImmediate('alias', payload, options);
1899
+ }
1900
+ /***
1901
+ *** GROUPS
1902
+ ***/
1903
+ groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
1904
+ this.wrap(() => {
1905
+ const payload = this.buildPayload({
1906
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
1907
+ event: '$groupidentify',
1908
+ properties: {
1909
+ $group_type: groupType,
1910
+ $group_key: groupKey,
1911
+ $group_set: groupProperties || {},
1912
+ ...(eventProperties || {}),
1913
+ },
1914
+ });
1915
+ this.enqueue('capture', payload, options);
1916
+ });
1917
+ }
1918
+ async getRemoteConfig() {
1919
+ await this._initPromise;
1920
+ let host = this.host;
1921
+ if (host === 'https://us.i.posthog.com') {
1922
+ host = 'https://us-assets.i.posthog.com';
1923
+ }
1924
+ else if (host === 'https://eu.i.posthog.com') {
1925
+ host = 'https://eu-assets.i.posthog.com';
1926
+ }
1927
+ const url = `${host}/array/${this.apiKey}/config`;
1928
+ const fetchOptions = {
1929
+ method: 'GET',
1930
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
1931
+ };
1932
+ // Don't retry remote config API calls
1933
+ return this.fetchWithRetry(url, fetchOptions, { retryCount: 0 }, this.remoteConfigRequestTimeoutMs)
1934
+ .then((response) => response.json())
1935
+ .catch((error) => {
1936
+ this.logMsgIfDebug(() => console.error('Remote config could not be loaded', error));
1937
+ this._events.emit('error', error);
1938
+ return undefined;
1939
+ });
1940
+ }
1941
+ /***
1942
+ *** FEATURE FLAGS
1943
+ ***/
1944
+ async getDecide(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}) {
1945
+ await this._initPromise;
1946
+ // Check if the API token is in the new flags rollout
1947
+ // This is a temporary measure to ensure that we can still use the old flags API
1948
+ // while we migrate to the new flags API
1949
+ const useFlags = isTokenInRollout(this.apiKey, NEW_FLAGS_ROLLOUT_PERCENTAGE, NEW_FLAGS_EXCLUDED_HASHES);
1950
+ const url = useFlags ? `${this.host}/flags/?v=2` : `${this.host}/decide/?v=4`;
1951
+ const fetchOptions = {
1952
+ method: 'POST',
1953
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
1954
+ body: JSON.stringify({
1955
+ token: this.apiKey,
1956
+ distinct_id: distinctId,
1957
+ groups,
1958
+ person_properties: personProperties,
1959
+ group_properties: groupProperties,
1960
+ ...extraPayload,
1961
+ }),
1962
+ };
1963
+ // Don't retry /decide API calls
1964
+ return this.fetchWithRetry(url, fetchOptions, { retryCount: 0 }, this.featureFlagsRequestTimeoutMs)
1965
+ .then((response) => response.json())
1966
+ .then((response) => normalizeDecideResponse(response))
1967
+ .catch((error) => {
1968
+ this._events.emit('error', error);
1969
+ return undefined;
1970
+ });
1971
+ }
1972
+ async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1973
+ await this._initPromise;
1974
+ const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
1975
+ if (flagDetailResponse === undefined) {
1976
+ // If we haven't loaded flags yet, or errored out, we respond with undefined
1977
+ return {
1978
+ response: undefined,
1979
+ requestId: undefined,
1980
+ };
1981
+ }
1982
+ let response = getFeatureFlagValue(flagDetailResponse.response);
1983
+ if (response === undefined) {
1984
+ // For cases where the flag is unknown, return false
1985
+ response = false;
1986
+ }
1987
+ // If we have flags we either return the value (true or string) or false
1988
+ return {
1989
+ response,
1990
+ requestId: flagDetailResponse.requestId,
1991
+ };
1992
+ }
1993
+ async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1994
+ await this._initPromise;
1995
+ const decideResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [key]);
1996
+ if (decideResponse === undefined) {
1997
+ return undefined;
1998
+ }
1999
+ const featureFlags = decideResponse.flags;
2000
+ const flagDetail = featureFlags[key];
2001
+ return {
2002
+ response: flagDetail,
2003
+ requestId: decideResponse.requestId,
2004
+ };
2005
+ }
2006
+ async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
2007
+ await this._initPromise;
2008
+ const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [key]);
2009
+ if (!payloads) {
2010
+ return undefined;
2011
+ }
2012
+ const response = payloads[key];
2013
+ // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
2014
+ if (response === undefined) {
2015
+ return null;
2016
+ }
2017
+ return response;
2018
+ }
2019
+ async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
2020
+ await this._initPromise;
2021
+ const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
2022
+ return payloads;
2023
+ }
2024
+ async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
2025
+ await this._initPromise;
2026
+ return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
2027
+ }
2028
+ async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
2029
+ await this._initPromise;
2030
+ const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
2031
+ if (!featureFlagDetails) {
2032
+ return {
2033
+ flags: undefined,
2034
+ payloads: undefined,
2035
+ requestId: undefined,
2036
+ };
2037
+ }
2038
+ return {
2039
+ flags: featureFlagDetails.featureFlags,
2040
+ payloads: featureFlagDetails.featureFlagPayloads,
2041
+ requestId: featureFlagDetails.requestId,
2042
+ };
2043
+ }
2044
+ async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
2045
+ await this._initPromise;
2046
+ const extraPayload = {};
2047
+ if (disableGeoip ?? this.disableGeoip) {
2048
+ extraPayload['geoip_disable'] = true;
2049
+ }
2050
+ if (flagKeysToEvaluate) {
2051
+ extraPayload['flag_keys_to_evaluate'] = flagKeysToEvaluate;
2052
+ }
2053
+ const decideResponse = await this.getDecide(distinctId, groups, personProperties, groupProperties, extraPayload);
2054
+ if (decideResponse === undefined) {
2055
+ // We probably errored out, so return undefined
2056
+ return undefined;
2057
+ }
2058
+ // if there's an error on the decideResponse, log a console error, but don't throw an error
2059
+ if (decideResponse.errorsWhileComputingFlags) {
2060
+ console.error('[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices');
2061
+ }
2062
+ // Add check for quota limitation on feature flags
2063
+ if (decideResponse.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags)) {
2064
+ console.warn('[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');
2065
+ return {
2066
+ flags: {},
2067
+ featureFlags: {},
2068
+ featureFlagPayloads: {},
2069
+ requestId: decideResponse?.requestId,
2070
+ };
2071
+ }
2072
+ return decideResponse;
2073
+ }
2074
+ /***
2075
+ *** SURVEYS
2076
+ ***/
2077
+ async getSurveysStateless() {
2078
+ await this._initPromise;
2079
+ if (this.disableSurveys === true) {
2080
+ this.logMsgIfDebug(() => console.log('Loading surveys is disabled.'));
2081
+ return [];
2082
+ }
2083
+ const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
2084
+ const fetchOptions = {
2085
+ method: 'GET',
2086
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
2087
+ };
2088
+ const response = await this.fetchWithRetry(url, fetchOptions)
2089
+ .then((response) => {
2090
+ if (response.status !== 200 || !response.json) {
2091
+ const msg = `Surveys API could not be loaded: ${response.status}`;
2092
+ const error = new Error(msg);
2093
+ this.logMsgIfDebug(() => console.error(error));
2094
+ this._events.emit('error', new Error(msg));
2095
+ return undefined;
2096
+ }
2097
+ return response.json();
2098
+ })
2099
+ .catch((error) => {
2100
+ this.logMsgIfDebug(() => console.error('Surveys API could not be loaded', error));
2101
+ this._events.emit('error', error);
2102
+ return undefined;
2103
+ });
2104
+ const newSurveys = response?.surveys;
2105
+ if (newSurveys) {
2106
+ this.logMsgIfDebug(() => console.log('PostHog Debug', 'Surveys fetched from API: ', JSON.stringify(newSurveys)));
2107
+ }
2108
+ return newSurveys ?? [];
2109
+ }
2110
+ get props() {
2111
+ if (!this._props) {
2112
+ this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
2113
+ }
2114
+ return this._props || {};
2115
+ }
2116
+ set props(val) {
2117
+ this._props = val;
2118
+ }
2119
+ async register(properties) {
2120
+ this.wrap(() => {
2121
+ this.props = {
2122
+ ...this.props,
2123
+ ...properties,
2124
+ };
2125
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
2126
+ });
2127
+ }
2128
+ async unregister(property) {
2129
+ this.wrap(() => {
2130
+ delete this.props[property];
2131
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
2132
+ });
2133
+ }
2134
+ /***
2135
+ *** QUEUEING AND FLUSHING
2136
+ ***/
2137
+ enqueue(type, _message, options) {
2138
+ this.wrap(() => {
2139
+ if (this.optedOut) {
2140
+ this._events.emit(type, `Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);
2141
+ return;
2142
+ }
2143
+ const message = this.prepareMessage(type, _message, options);
2144
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
2145
+ if (queue.length >= this.maxQueueSize) {
2146
+ queue.shift();
2147
+ this.logMsgIfDebug(() => console.info('Queue is full, the oldest event is dropped.'));
2148
+ }
2149
+ queue.push({ message });
2150
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
2151
+ this._events.emit(type, message);
2152
+ // Flush queued events if we meet the flushAt length
2153
+ if (queue.length >= this.flushAt) {
2154
+ this.flushBackground();
2155
+ }
2156
+ if (this.flushInterval && !this._flushTimer) {
2157
+ this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
2158
+ }
2159
+ });
2160
+ }
2161
+ async sendImmediate(type, _message, options) {
2162
+ if (this.disabled) {
2163
+ this.logMsgIfDebug(() => console.warn('[PostHog] The client is disabled'));
2164
+ return;
2165
+ }
2166
+ if (!this._isInitialized) {
2167
+ await this._initPromise;
2168
+ }
2169
+ if (this.optedOut) {
2170
+ this._events.emit(type, `Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);
2171
+ return;
2172
+ }
2173
+ const data = {
2174
+ api_key: this.apiKey,
2175
+ batch: [this.prepareMessage(type, _message, options)],
2176
+ sent_at: currentISOTime(),
2177
+ };
2178
+ if (this.historicalMigration) {
2179
+ data.historical_migration = true;
2180
+ }
2181
+ const payload = JSON.stringify(data);
2182
+ const url = this.captureMode === 'form'
2183
+ ? `${this.host}/e/?ip=1&_=${currentTimestamp()}&v=${this.getLibraryVersion()}`
2184
+ : `${this.host}/batch/`;
2185
+ const fetchOptions = this.captureMode === 'form'
2186
+ ? {
2187
+ method: 'POST',
2188
+ mode: 'no-cors',
2189
+ credentials: 'omit',
2190
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/x-www-form-urlencoded' },
2191
+ body: `data=${encodeURIComponent(LZString.compressToBase64(payload))}&compression=lz64`,
2192
+ }
2193
+ : {
2194
+ method: 'POST',
2195
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
2196
+ body: payload,
2197
+ };
2198
+ try {
2199
+ await this.fetchWithRetry(url, fetchOptions);
2200
+ }
2201
+ catch (err) {
2202
+ this._events.emit('error', err);
2203
+ throw err;
2204
+ }
2205
+ }
2206
+ prepareMessage(type, _message, options) {
2207
+ const message = {
2208
+ ..._message,
2209
+ type: type,
2210
+ library: this.getLibraryId(),
2211
+ library_version: this.getLibraryVersion(),
2212
+ timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
2213
+ uuid: options?.uuid ? options.uuid : uuidv7(),
2214
+ };
2215
+ const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
2216
+ if (addGeoipDisableProperty) {
2217
+ if (!message.properties) {
2218
+ message.properties = {};
2219
+ }
2220
+ message['properties']['$geoip_disable'] = true;
2221
+ }
2222
+ if (message.distinctId) {
2223
+ message.distinct_id = message.distinctId;
2224
+ delete message.distinctId;
2225
+ }
2226
+ return message;
2227
+ }
2228
+ clearFlushTimer() {
2229
+ if (this._flushTimer) {
2230
+ clearTimeout(this._flushTimer);
2231
+ this._flushTimer = undefined;
2232
+ }
2233
+ }
2234
+ /**
2235
+ * Helper for flushing the queue in the background
2236
+ * Avoids unnecessary promise errors
2237
+ */
2238
+ flushBackground() {
2239
+ void this.flush().catch(async (err) => {
2240
+ await logFlushError(err);
2241
+ });
2242
+ }
2243
+ async flush() {
2244
+ // Wait for the current flush operation to finish (regardless of success or failure), then try to flush again.
2245
+ // Use allSettled instead of finally to be defensive around flush throwing errors immediately rather than rejecting.
2246
+ const nextFlushPromise = Promise.allSettled([this.flushPromise]).then(() => {
2247
+ return this._flush();
2248
+ });
2249
+ this.flushPromise = nextFlushPromise;
2250
+ void this.addPendingPromise(nextFlushPromise);
2251
+ Promise.allSettled([nextFlushPromise]).then(() => {
2252
+ // If there are no others waiting to flush, clear the promise.
2253
+ // We don't strictly need to do this, but it could make debugging easier
2254
+ if (this.flushPromise === nextFlushPromise) {
2255
+ this.flushPromise = null;
2256
+ }
2257
+ });
2258
+ return nextFlushPromise;
2259
+ }
2260
+ getCustomHeaders() {
2261
+ // Don't set the user agent if we're not on a browser. The latest spec allows
2262
+ // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
2263
+ // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
2264
+ // but browsers such as Chrome and Safari have not caught up.
2265
+ const customUserAgent = this.getCustomUserAgent();
2266
+ const headers = {};
2267
+ if (customUserAgent && customUserAgent !== '') {
2268
+ headers['User-Agent'] = customUserAgent;
2269
+ }
2270
+ return headers;
2271
+ }
2272
+ async _flush() {
2273
+ this.clearFlushTimer();
2274
+ await this._initPromise;
2275
+ let queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
2276
+ if (!queue.length) {
2277
+ return [];
2278
+ }
2279
+ const sentMessages = [];
2280
+ const originalQueueLength = queue.length;
2281
+ while (queue.length > 0 && sentMessages.length < originalQueueLength) {
2282
+ const batchItems = queue.slice(0, this.maxBatchSize);
2283
+ const batchMessages = batchItems.map((item) => item.message);
2284
+ const persistQueueChange = () => {
2285
+ const refreshedQueue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
2286
+ const newQueue = refreshedQueue.slice(batchItems.length);
2287
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, newQueue);
2288
+ queue = newQueue;
2289
+ };
2290
+ const data = {
2291
+ api_key: this.apiKey,
2292
+ batch: batchMessages,
2293
+ sent_at: currentISOTime(),
2294
+ };
2295
+ if (this.historicalMigration) {
2296
+ data.historical_migration = true;
2297
+ }
2298
+ const payload = JSON.stringify(data);
2299
+ const url = this.captureMode === 'form'
2300
+ ? `${this.host}/e/?ip=1&_=${currentTimestamp()}&v=${this.getLibraryVersion()}`
2301
+ : `${this.host}/batch/`;
2302
+ const fetchOptions = this.captureMode === 'form'
2303
+ ? {
2304
+ method: 'POST',
2305
+ mode: 'no-cors',
2306
+ credentials: 'omit',
2307
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/x-www-form-urlencoded' },
2308
+ body: `data=${encodeURIComponent(LZString.compressToBase64(payload))}&compression=lz64`,
2309
+ }
2310
+ : {
2311
+ method: 'POST',
2312
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
2313
+ body: payload,
2314
+ };
2315
+ const retryOptions = {
2316
+ retryCheck: (err) => {
2317
+ // don't automatically retry on 413 errors, we want to reduce the batch size first
2318
+ if (isPostHogFetchContentTooLargeError(err)) {
2319
+ return false;
2320
+ }
2321
+ // otherwise, retry on network errors
2322
+ return isPostHogFetchError(err);
2323
+ },
2324
+ };
2325
+ try {
2326
+ await this.fetchWithRetry(url, fetchOptions, retryOptions);
2327
+ }
2328
+ catch (err) {
2329
+ if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
2330
+ // if we get a 413 error, we want to reduce the batch size and try again
2331
+ this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
2332
+ this.logMsgIfDebug(() => console.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`));
2333
+ // do not persist the queue change, we want to retry the same batch
2334
+ continue;
2335
+ }
2336
+ // depending on the error type, eg a malformed JSON or broken queue, it'll always return an error
2337
+ // and this will be an endless loop, in this case, if the error isn't a network issue, we always remove the items from the queue
2338
+ if (!(err instanceof PostHogFetchNetworkError)) {
2339
+ persistQueueChange();
2340
+ }
2341
+ this._events.emit('error', err);
2342
+ throw err;
2343
+ }
2344
+ persistQueueChange();
2345
+ sentMessages.push(...batchMessages);
2346
+ }
2347
+ this._events.emit('flush', sentMessages);
2348
+ return sentMessages;
2349
+ }
2350
+ async fetchWithRetry(url, options, retryOptions, requestTimeout) {
2351
+ var _a;
2352
+ (_a = AbortSignal).timeout ?? (_a.timeout = function timeout(ms) {
2353
+ const ctrl = new AbortController();
2354
+ setTimeout(() => ctrl.abort(), ms);
2355
+ return ctrl.signal;
2356
+ });
2357
+ const body = options.body ? options.body : '';
2358
+ const reqByteLength = Buffer.byteLength(body, STRING_FORMAT);
2359
+ return await retriable(async () => {
2360
+ let res = null;
2361
+ try {
2362
+ res = await this.fetch(url, {
2363
+ signal: AbortSignal.timeout(requestTimeout ?? this.requestTimeout),
2364
+ ...options,
2365
+ });
2366
+ }
2367
+ catch (e) {
2368
+ // fetch will only throw on network errors or on timeouts
2369
+ throw new PostHogFetchNetworkError(e);
2370
+ }
2371
+ // If we're in no-cors mode, we can't access the response status
2372
+ // We only throw on HTTP errors if we're not in no-cors mode
2373
+ // https://developer.mozilla.org/en-US/docs/Web/API/Request/mode#no-cors
2374
+ const isNoCors = options.mode === 'no-cors';
2375
+ if (!isNoCors && (res.status < 200 || res.status >= 400)) {
2376
+ throw new PostHogFetchHttpError(res, reqByteLength);
2377
+ }
2378
+ return res;
2379
+ }, { ...this._retryOptions, ...retryOptions });
2380
+ }
2381
+ async _shutdown(shutdownTimeoutMs = 30000) {
2382
+ // A little tricky - we want to have a max shutdown time and enforce it, even if that means we have some
2383
+ // dangling promises. We'll keep track of the timeout and resolve/reject based on that.
2384
+ await this._initPromise;
2385
+ let hasTimedOut = false;
2386
+ this.clearFlushTimer();
2387
+ const doShutdown = async () => {
2388
+ try {
2389
+ await Promise.all(Object.values(this.pendingPromises));
2390
+ while (true) {
2391
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
2392
+ if (queue.length === 0) {
2393
+ break;
2394
+ }
2395
+ // flush again to make sure we send all events, some of which might've been added
2396
+ // while we were waiting for the pending promises to resolve
2397
+ // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
2398
+ await this.flush();
2399
+ if (hasTimedOut) {
2400
+ break;
2401
+ }
2402
+ }
2403
+ }
2404
+ catch (e) {
2405
+ if (!isPostHogFetchError(e)) {
2406
+ throw e;
2407
+ }
2408
+ await logFlushError(e);
2409
+ }
2410
+ };
2411
+ return Promise.race([
2412
+ new Promise((_, reject) => {
2413
+ safeSetTimeout(() => {
2414
+ this.logMsgIfDebug(() => console.error('Timed out while shutting down PostHog'));
2415
+ hasTimedOut = true;
2416
+ reject('Timeout while shutting down PostHog. Some events may not have been sent.');
2417
+ }, shutdownTimeoutMs);
2418
+ }),
2419
+ doShutdown(),
2420
+ ]);
2421
+ }
2422
+ /**
2423
+ * Call shutdown() once before the node process exits, so ensure that all events have been sent and all promises
2424
+ * have resolved. Do not use this function if you intend to keep using this PostHog instance after calling it.
2425
+ * @param shutdownTimeoutMs
2426
+ */
2427
+ async shutdown(shutdownTimeoutMs = 30000) {
2428
+ if (this.shutdownPromise) {
2429
+ this.logMsgIfDebug(() => console.warn('shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup'));
2430
+ }
2431
+ else {
2432
+ this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
2433
+ this.shutdownPromise = null;
2434
+ });
2435
+ }
2436
+ return this.shutdownPromise;
2437
+ }
2438
+ }
2439
+
2440
+ /**
2441
+ * Fetch wrapper
2442
+ *
2443
+ * We want to polyfill fetch when not available with axios but use it when it is.
2444
+ * NOTE: The current version of Axios has an issue when in non-node environments like Clouflare Workers.
2445
+ * This is currently solved by using the global fetch if available instead.
2446
+ * See https://github.com/PostHog/posthog-js-lite/issues/127 for more info
2447
+ */
2448
+ let _fetch = getFetch();
2449
+ if (!_fetch) {
2450
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
2451
+ const axios = require('axios');
2452
+ _fetch = async (url, options) => {
2453
+ const res = await axios.request({
2454
+ url,
2455
+ headers: options.headers,
2456
+ method: options.method.toLowerCase(),
2457
+ data: options.body,
2458
+ signal: options.signal,
2459
+ // fetch only throws on network errors, not on HTTP errors
2460
+ validateStatus: () => true
2461
+ });
2462
+ return {
2463
+ status: res.status,
2464
+ text: async () => res.data,
2465
+ json: async () => res.data
2466
+ };
2467
+ };
2468
+ }
2469
+ // NOTE: We have to export this as default, even though we prefer named exports as we are relying on detecting "fetch" in the global scope
2470
+ var fetch$1 = _fetch;
2471
+
2472
+ /**
2473
+ * A lazy value that is only computed when needed. Inspired by C#'s Lazy<T> class.
2474
+ */
2475
+ class Lazy {
2476
+ constructor(factory) {
2477
+ this.factory = factory;
2478
+ }
2479
+ /**
2480
+ * Gets the value, initializing it if necessary.
2481
+ * Multiple concurrent calls will share the same initialization promise.
2482
+ */
2483
+ async getValue() {
2484
+ if (this.value !== undefined) {
2485
+ return this.value;
2486
+ }
2487
+ if (this.initializationPromise === undefined) {
2488
+ this.initializationPromise = (async () => {
2489
+ try {
2490
+ const result = await this.factory();
2491
+ this.value = result;
2492
+ return result;
2493
+ } finally {
2494
+ // Clear the promise so we can retry if needed
2495
+ this.initializationPromise = undefined;
2496
+ }
2497
+ })();
2498
+ }
2499
+ return this.initializationPromise;
2500
+ }
2501
+ /**
2502
+ * Returns true if the value has been initialized.
2503
+ */
2504
+ isInitialized() {
2505
+ return this.value !== undefined;
2506
+ }
2507
+ /**
2508
+ * Returns a promise that resolves when the value is initialized.
2509
+ * If already initialized, resolves immediately.
2510
+ */
2511
+ async waitForInitialization() {
2512
+ if (this.isInitialized()) {
2513
+ return;
2514
+ }
2515
+ await this.getValue();
2516
+ }
2517
+ }
2518
+
2519
+ /// <reference lib="dom" />
2520
+ const nodeCrypto = new Lazy(async () => {
2521
+ try {
2522
+ return await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('crypto')); });
2523
+ } catch {
2524
+ return undefined;
2525
+ }
2526
+ });
2527
+ async function getNodeCrypto() {
2528
+ return await nodeCrypto.getValue();
2529
+ }
2530
+ const webCrypto = new Lazy(async () => {
2531
+ if (typeof globalThis.crypto?.subtle !== 'undefined') {
2532
+ return globalThis.crypto.subtle;
2533
+ }
2534
+ try {
2535
+ // Node.js: use built-in webcrypto and assign it if needed
2536
+ const crypto = await nodeCrypto.getValue();
2537
+ if (crypto?.webcrypto?.subtle) {
2538
+ return crypto.webcrypto.subtle;
2539
+ }
2540
+ } catch {
2541
+ // Ignore if not available
2542
+ }
2543
+ return undefined;
2544
+ });
2545
+ async function getWebCrypto() {
2546
+ return await webCrypto.getValue();
2547
+ }
2548
+
2549
+ /// <reference lib="dom" />
2550
+ async function hashSHA1(text) {
2551
+ // Try Node.js crypto first
2552
+ const nodeCrypto = await getNodeCrypto();
2553
+ if (nodeCrypto) {
2554
+ return nodeCrypto.createHash('sha1').update(text).digest('hex');
2555
+ }
2556
+ const webCrypto = await getWebCrypto();
2557
+ // Fall back to Web Crypto API
2558
+ if (webCrypto) {
2559
+ const hashBuffer = await webCrypto.digest('SHA-1', new TextEncoder().encode(text));
2560
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
2561
+ return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
2562
+ }
2563
+ throw new Error('No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API');
2564
+ }
2565
+
2566
+ const SIXTY_SECONDS = 60 * 1000;
2567
+ // eslint-disable-next-line
2568
+ const LONG_SCALE = 0xfffffffffffffff;
2569
+ const NULL_VALUES_ALLOWED_OPERATORS = ['is_not'];
2570
+ class ClientError extends Error {
2571
+ constructor(message) {
2572
+ super();
2573
+ Error.captureStackTrace(this, this.constructor);
2574
+ this.name = 'ClientError';
2575
+ this.message = message;
2576
+ Object.setPrototypeOf(this, ClientError.prototype);
2577
+ }
2578
+ }
2579
+ class InconclusiveMatchError extends Error {
2580
+ constructor(message) {
2581
+ super(message);
2582
+ this.name = this.constructor.name;
2583
+ Error.captureStackTrace(this, this.constructor);
2584
+ // instanceof doesn't work in ES3 or ES5
2585
+ // https://www.dannyguo.com/blog/how-to-fix-instanceof-not-working-for-custom-errors-in-typescript/
2586
+ // this is the workaround
2587
+ Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
2588
+ }
2589
+ }
2590
+ class FeatureFlagsPoller {
2591
+ constructor({
2592
+ pollingInterval,
2593
+ personalApiKey,
2594
+ projectApiKey,
2595
+ timeout,
2596
+ host,
2597
+ customHeaders,
2598
+ ...options
2599
+ }) {
2600
+ this.debugMode = false;
2601
+ this.shouldBeginExponentialBackoff = false;
2602
+ this.backOffCount = 0;
2603
+ this.pollingInterval = pollingInterval;
2604
+ this.personalApiKey = personalApiKey;
2605
+ this.featureFlags = [];
2606
+ this.featureFlagsByKey = {};
2607
+ this.groupTypeMapping = {};
2608
+ this.cohorts = {};
2609
+ this.loadedSuccessfullyOnce = false;
2610
+ this.timeout = timeout;
2611
+ this.projectApiKey = projectApiKey;
2612
+ this.host = host;
2613
+ this.poller = undefined;
2614
+ this.fetch = options.fetch || fetch$1;
2615
+ this.onError = options.onError;
2616
+ this.customHeaders = customHeaders;
2617
+ this.onLoad = options.onLoad;
2618
+ void this.loadFeatureFlags();
2619
+ }
2620
+ debug(enabled = true) {
2621
+ this.debugMode = enabled;
2622
+ }
2623
+ logMsgIfDebug(fn) {
2624
+ if (this.debugMode) {
2625
+ fn();
2626
+ }
2627
+ }
2628
+ async getFeatureFlag(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {
2629
+ await this.loadFeatureFlags();
2630
+ let response = undefined;
2631
+ let featureFlag = undefined;
2632
+ if (!this.loadedSuccessfullyOnce) {
2633
+ return response;
2634
+ }
2635
+ for (const flag of this.featureFlags) {
2636
+ if (key === flag.key) {
2637
+ featureFlag = flag;
2638
+ break;
2639
+ }
2640
+ }
2641
+ if (featureFlag !== undefined) {
2642
+ try {
2643
+ response = await this.computeFlagLocally(featureFlag, distinctId, groups, personProperties, groupProperties);
2644
+ this.logMsgIfDebug(() => console.debug(`Successfully computed flag locally: ${key} -> ${response}`));
2645
+ } catch (e) {
2646
+ if (e instanceof InconclusiveMatchError) {
2647
+ this.logMsgIfDebug(() => console.debug(`InconclusiveMatchError when computing flag locally: ${key}: ${e}`));
2648
+ } else if (e instanceof Error) {
2649
+ this.onError?.(new Error(`Error computing flag locally: ${key}: ${e}`));
2650
+ }
2651
+ }
2652
+ }
2653
+ return response;
2654
+ }
2655
+ async computeFeatureFlagPayloadLocally(key, matchValue) {
2656
+ await this.loadFeatureFlags();
2657
+ let response = undefined;
2658
+ if (!this.loadedSuccessfullyOnce) {
2659
+ return undefined;
2660
+ }
2661
+ if (typeof matchValue == 'boolean') {
2662
+ response = this.featureFlagsByKey?.[key]?.filters?.payloads?.[matchValue.toString()];
2663
+ } else if (typeof matchValue == 'string') {
2664
+ response = this.featureFlagsByKey?.[key]?.filters?.payloads?.[matchValue];
2665
+ }
2666
+ // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
2667
+ if (response === undefined || response === null) {
2668
+ return null;
2669
+ }
2670
+ try {
2671
+ return JSON.parse(response);
2672
+ } catch {
2673
+ return response;
2674
+ }
2675
+ }
2676
+ async getAllFlagsAndPayloads(distinctId, groups = {}, personProperties = {}, groupProperties = {}) {
2677
+ await this.loadFeatureFlags();
2678
+ const response = {};
2679
+ const payloads = {};
2680
+ let fallbackToDecide = this.featureFlags.length == 0;
2681
+ await Promise.all(this.featureFlags.map(async flag => {
2682
+ try {
2683
+ const matchValue = await this.computeFlagLocally(flag, distinctId, groups, personProperties, groupProperties);
2684
+ response[flag.key] = matchValue;
2685
+ const matchPayload = await this.computeFeatureFlagPayloadLocally(flag.key, matchValue);
2686
+ if (matchPayload) {
2687
+ payloads[flag.key] = matchPayload;
2688
+ }
2689
+ } catch (e) {
2690
+ if (e instanceof InconclusiveMatchError) ; else if (e instanceof Error) {
2691
+ this.onError?.(new Error(`Error computing flag locally: ${flag.key}: ${e}`));
2692
+ }
2693
+ fallbackToDecide = true;
2694
+ }
2695
+ }));
2696
+ return {
2697
+ response,
2698
+ payloads,
2699
+ fallbackToDecide
2700
+ };
2701
+ }
2702
+ async computeFlagLocally(flag, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {
2703
+ if (flag.ensure_experience_continuity) {
2704
+ throw new InconclusiveMatchError('Flag has experience continuity enabled');
2705
+ }
2706
+ if (!flag.active) {
2707
+ return false;
2708
+ }
2709
+ const flagFilters = flag.filters || {};
2710
+ const aggregation_group_type_index = flagFilters.aggregation_group_type_index;
2711
+ if (aggregation_group_type_index != undefined) {
2712
+ const groupName = this.groupTypeMapping[String(aggregation_group_type_index)];
2713
+ if (!groupName) {
2714
+ this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Unknown group type index ${aggregation_group_type_index} for feature flag ${flag.key}`));
2715
+ throw new InconclusiveMatchError('Flag has unknown group type index');
2716
+ }
2717
+ if (!(groupName in groups)) {
2718
+ this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${flag.key} without group names passed in`));
2719
+ return false;
2720
+ }
2721
+ const focusedGroupProperties = groupProperties[groupName];
2722
+ return await this.matchFeatureFlagProperties(flag, groups[groupName], focusedGroupProperties);
2723
+ } else {
2724
+ return await this.matchFeatureFlagProperties(flag, distinctId, personProperties);
2725
+ }
2726
+ }
2727
+ async matchFeatureFlagProperties(flag, distinctId, properties) {
2728
+ const flagFilters = flag.filters || {};
2729
+ const flagConditions = flagFilters.groups || [];
2730
+ let isInconclusive = false;
2731
+ let result = undefined;
2732
+ // # Stable sort conditions with variant overrides to the top. This ensures that if overrides are present, they are
2733
+ // # evaluated first, and the variant override is applied to the first matching condition.
2734
+ const sortedFlagConditions = [...flagConditions].sort((conditionA, conditionB) => {
2735
+ const AHasVariantOverride = !!conditionA.variant;
2736
+ const BHasVariantOverride = !!conditionB.variant;
2737
+ if (AHasVariantOverride && BHasVariantOverride) {
2738
+ return 0;
2739
+ } else if (AHasVariantOverride) {
2740
+ return -1;
2741
+ } else if (BHasVariantOverride) {
2742
+ return 1;
2743
+ } else {
2744
+ return 0;
2745
+ }
2746
+ });
2747
+ for (const condition of sortedFlagConditions) {
2748
+ try {
2749
+ if (await this.isConditionMatch(flag, distinctId, condition, properties)) {
2750
+ const variantOverride = condition.variant;
2751
+ const flagVariants = flagFilters.multivariate?.variants || [];
2752
+ if (variantOverride && flagVariants.some(variant => variant.key === variantOverride)) {
2753
+ result = variantOverride;
2754
+ } else {
2755
+ result = (await this.getMatchingVariant(flag, distinctId)) || true;
2756
+ }
2757
+ break;
2758
+ }
2759
+ } catch (e) {
2760
+ if (e instanceof InconclusiveMatchError) {
2761
+ isInconclusive = true;
2762
+ } else {
2763
+ throw e;
2764
+ }
2765
+ }
2766
+ }
2767
+ if (result !== undefined) {
2768
+ return result;
2769
+ } else if (isInconclusive) {
2770
+ throw new InconclusiveMatchError("Can't determine if feature flag is enabled or not with given properties");
2771
+ }
2772
+ // We can only return False when all conditions are False
2773
+ return false;
2774
+ }
2775
+ async isConditionMatch(flag, distinctId, condition, properties) {
2776
+ const rolloutPercentage = condition.rollout_percentage;
2777
+ const warnFunction = msg => {
2778
+ this.logMsgIfDebug(() => console.warn(msg));
2779
+ };
2780
+ if ((condition.properties || []).length > 0) {
2781
+ for (const prop of condition.properties) {
2782
+ const propertyType = prop.type;
2783
+ let matches = false;
2784
+ if (propertyType === 'cohort') {
2785
+ matches = matchCohort(prop, properties, this.cohorts, this.debugMode);
2786
+ } else {
2787
+ matches = matchProperty(prop, properties, warnFunction);
2788
+ }
2789
+ if (!matches) {
2790
+ return false;
2791
+ }
2792
+ }
2793
+ if (rolloutPercentage == undefined) {
2794
+ return true;
2795
+ }
2796
+ }
2797
+ if (rolloutPercentage != undefined && (await _hash(flag.key, distinctId)) > rolloutPercentage / 100.0) {
2798
+ return false;
2799
+ }
2800
+ return true;
2801
+ }
2802
+ async getMatchingVariant(flag, distinctId) {
2803
+ const hashValue = await _hash(flag.key, distinctId, 'variant');
2804
+ const matchingVariant = this.variantLookupTable(flag).find(variant => {
2805
+ return hashValue >= variant.valueMin && hashValue < variant.valueMax;
2806
+ });
2807
+ if (matchingVariant) {
2808
+ return matchingVariant.key;
2809
+ }
2810
+ return undefined;
2811
+ }
2812
+ variantLookupTable(flag) {
2813
+ const lookupTable = [];
2814
+ let valueMin = 0;
2815
+ let valueMax = 0;
2816
+ const flagFilters = flag.filters || {};
2817
+ const multivariates = flagFilters.multivariate?.variants || [];
2818
+ multivariates.forEach(variant => {
2819
+ valueMax = valueMin + variant.rollout_percentage / 100.0;
2820
+ lookupTable.push({
2821
+ valueMin,
2822
+ valueMax,
2823
+ key: variant.key
2824
+ });
2825
+ valueMin = valueMax;
2826
+ });
2827
+ return lookupTable;
2828
+ }
2829
+ async loadFeatureFlags(forceReload = false) {
2830
+ if (!this.loadedSuccessfullyOnce || forceReload) {
2831
+ await this._loadFeatureFlags();
2832
+ }
2833
+ }
2834
+ /**
2835
+ * Returns true if the feature flags poller has loaded successfully at least once and has more than 0 feature flags.
2836
+ * This is useful to check if local evaluation is ready before calling getFeatureFlag.
2837
+ */
2838
+ isLocalEvaluationReady() {
2839
+ return (this.loadedSuccessfullyOnce ?? false) && (this.featureFlags?.length ?? 0) > 0;
2840
+ }
2841
+ /**
2842
+ * If a client is misconfigured with an invalid or improper API key, the polling interval is doubled each time
2843
+ * until a successful request is made, up to a maximum of 60 seconds.
2844
+ *
2845
+ * @returns The polling interval to use for the next request.
2846
+ */
2847
+ getPollingInterval() {
2848
+ if (!this.shouldBeginExponentialBackoff) {
2849
+ return this.pollingInterval;
2850
+ }
2851
+ return Math.min(SIXTY_SECONDS, this.pollingInterval * 2 ** this.backOffCount);
2852
+ }
2853
+ async _loadFeatureFlags() {
2854
+ if (this.poller) {
2855
+ clearTimeout(this.poller);
2856
+ this.poller = undefined;
2857
+ }
2858
+ this.poller = setTimeout(() => this._loadFeatureFlags(), this.getPollingInterval());
2859
+ try {
2860
+ const res = await this._requestFeatureFlagDefinitions();
2861
+ // Handle undefined res case, this shouldn't happen, but it doesn't hurt to handle it anyway
2862
+ if (!res) {
2863
+ // Don't override existing flags when something goes wrong
2864
+ return;
2865
+ }
2866
+ // NB ON ERROR HANDLING & `loadedSuccessfullyOnce`:
2867
+ //
2868
+ // `loadedSuccessfullyOnce` indicates we've successfully loaded a valid set of flags at least once.
2869
+ // If we set it to `true` in an error scenario (e.g. 402 Over Quota, 401 Invalid Key, etc.),
2870
+ // any manual call to `loadFeatureFlags()` (without forceReload) will skip refetching entirely,
2871
+ // leaving us stuck with zero or outdated flags. The poller does keep running, but we also want
2872
+ // manual reloads to be possible as soon as the error condition is resolved.
2873
+ //
2874
+ // Therefore, on error statuses, we do *not* set `loadedSuccessfullyOnce = true`, ensuring that
2875
+ // both the background poller and any subsequent manual calls can keep trying to load flags
2876
+ // once the issue (quota, permission, rate limit, etc.) is resolved.
2877
+ switch (res.status) {
2878
+ case 401:
2879
+ // Invalid API key
2880
+ this.shouldBeginExponentialBackoff = true;
2881
+ this.backOffCount += 1;
2882
+ throw new ClientError(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);
2883
+ case 402:
2884
+ // Quota exceeded - clear all flags
2885
+ console.warn('[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');
2886
+ this.featureFlags = [];
2887
+ this.featureFlagsByKey = {};
2888
+ this.groupTypeMapping = {};
2889
+ this.cohorts = {};
2890
+ return;
2891
+ case 403:
2892
+ // Permissions issue
2893
+ this.shouldBeginExponentialBackoff = true;
2894
+ this.backOffCount += 1;
2895
+ throw new ClientError(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);
2896
+ case 429:
2897
+ // Rate limited
2898
+ this.shouldBeginExponentialBackoff = true;
2899
+ this.backOffCount += 1;
2900
+ throw new ClientError(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);
2901
+ case 200:
2902
+ {
2903
+ // Process successful response
2904
+ const responseJson = await res.json();
2905
+ if (!('flags' in responseJson)) {
2906
+ this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(responseJson)}`));
2907
+ return;
2908
+ }
2909
+ this.featureFlags = responseJson.flags || [];
2910
+ this.featureFlagsByKey = this.featureFlags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
2911
+ this.groupTypeMapping = responseJson.group_type_mapping || {};
2912
+ this.cohorts = responseJson.cohorts || {};
2913
+ this.loadedSuccessfullyOnce = true;
2914
+ this.shouldBeginExponentialBackoff = false;
2915
+ this.backOffCount = 0;
2916
+ this.onLoad?.(this.featureFlags.length);
2917
+ break;
2918
+ }
2919
+ default:
2920
+ // Something else went wrong, or the server is down.
2921
+ // In this case, don't override existing flags
2922
+ return;
2923
+ }
2924
+ } catch (err) {
2925
+ if (err instanceof ClientError) {
2926
+ this.onError?.(err);
2927
+ }
2928
+ }
2929
+ }
2930
+ getPersonalApiKeyRequestOptions(method = 'GET') {
2931
+ return {
2932
+ method,
2933
+ headers: {
2934
+ ...this.customHeaders,
2935
+ 'Content-Type': 'application/json',
2936
+ Authorization: `Bearer ${this.personalApiKey}`
2937
+ }
2938
+ };
2939
+ }
2940
+ async _requestFeatureFlagDefinitions() {
2941
+ const url = `${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`;
2942
+ const options = this.getPersonalApiKeyRequestOptions();
2943
+ let abortTimeout = null;
2944
+ if (this.timeout && typeof this.timeout === 'number') {
2945
+ const controller = new AbortController();
2946
+ abortTimeout = safeSetTimeout(() => {
2947
+ controller.abort();
2948
+ }, this.timeout);
2949
+ options.signal = controller.signal;
2950
+ }
2951
+ try {
2952
+ return await this.fetch(url, options);
2953
+ } finally {
2954
+ clearTimeout(abortTimeout);
2955
+ }
2956
+ }
2957
+ stopPoller() {
2958
+ clearTimeout(this.poller);
2959
+ }
2960
+ _requestRemoteConfigPayload(flagKey) {
2961
+ const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config/`;
2962
+ const options = this.getPersonalApiKeyRequestOptions();
2963
+ let abortTimeout = null;
2964
+ if (this.timeout && typeof this.timeout === 'number') {
2965
+ const controller = new AbortController();
2966
+ abortTimeout = safeSetTimeout(() => {
2967
+ controller.abort();
2968
+ }, this.timeout);
2969
+ options.signal = controller.signal;
2970
+ }
2971
+ try {
2972
+ return this.fetch(url, options);
2973
+ } finally {
2974
+ clearTimeout(abortTimeout);
2975
+ }
2976
+ }
2977
+ }
2978
+ // # This function takes a distinct_id and a feature flag key and returns a float between 0 and 1.
2979
+ // # Given the same distinct_id and key, it'll always return the same float. These floats are
2980
+ // # uniformly distributed between 0 and 1, so if we want to show this feature to 20% of traffic
2981
+ // # we can do _hash(key, distinct_id) < 0.2
2982
+ async function _hash(key, distinctId, salt = '') {
2983
+ const hashString = await hashSHA1(`${key}.${distinctId}${salt}`);
2984
+ return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
2985
+ }
2986
+ function matchProperty(property, propertyValues, warnFunction) {
2987
+ const key = property.key;
2988
+ const value = property.value;
2989
+ const operator = property.operator || 'exact';
2990
+ if (!(key in propertyValues)) {
2991
+ throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
2992
+ } else if (operator === 'is_not_set') {
2993
+ throw new InconclusiveMatchError(`Operator is_not_set is not supported`);
2994
+ }
2995
+ const overrideValue = propertyValues[key];
2996
+ if (overrideValue == null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {
2997
+ // if the value is null, just fail the feature flag comparison
2998
+ // this isn't an InconclusiveMatchError because the property value was provided.
2999
+ if (warnFunction) {
3000
+ warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);
3001
+ }
3002
+ return false;
3003
+ }
3004
+ function computeExactMatch(value, overrideValue) {
3005
+ if (Array.isArray(value)) {
3006
+ return value.map(val => String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());
3007
+ }
3008
+ return String(value).toLowerCase() === String(overrideValue).toLowerCase();
3009
+ }
3010
+ function compare(lhs, rhs, operator) {
3011
+ if (operator === 'gt') {
3012
+ return lhs > rhs;
3013
+ } else if (operator === 'gte') {
3014
+ return lhs >= rhs;
3015
+ } else if (operator === 'lt') {
3016
+ return lhs < rhs;
3017
+ } else if (operator === 'lte') {
3018
+ return lhs <= rhs;
3019
+ } else {
3020
+ throw new Error(`Invalid operator: ${operator}`);
3021
+ }
3022
+ }
3023
+ switch (operator) {
3024
+ case 'exact':
3025
+ return computeExactMatch(value, overrideValue);
3026
+ case 'is_not':
3027
+ return !computeExactMatch(value, overrideValue);
3028
+ case 'is_set':
3029
+ return key in propertyValues;
3030
+ case 'icontains':
3031
+ return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
3032
+ case 'not_icontains':
3033
+ return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
3034
+ case 'regex':
3035
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
3036
+ case 'not_regex':
3037
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null;
3038
+ case 'gt':
3039
+ case 'gte':
3040
+ case 'lt':
3041
+ case 'lte':
3042
+ {
3043
+ // :TRICKY: We adjust comparison based on the override value passed in,
3044
+ // to make sure we handle both numeric and string comparisons appropriately.
3045
+ let parsedValue = typeof value === 'number' ? value : null;
3046
+ if (typeof value === 'string') {
3047
+ try {
3048
+ parsedValue = parseFloat(value);
3049
+ } catch (err) {
3050
+ // pass
3051
+ }
3052
+ }
3053
+ if (parsedValue != null && overrideValue != null) {
3054
+ // check both null and undefined
3055
+ if (typeof overrideValue === 'string') {
3056
+ return compare(overrideValue, String(value), operator);
3057
+ } else {
3058
+ return compare(overrideValue, parsedValue, operator);
3059
+ }
3060
+ } else {
3061
+ return compare(String(overrideValue), String(value), operator);
3062
+ }
3063
+ }
3064
+ case 'is_date_after':
3065
+ case 'is_date_before':
3066
+ {
3067
+ let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
3068
+ if (parsedDate == null) {
3069
+ parsedDate = convertToDateTime(value);
3070
+ }
3071
+ if (parsedDate == null) {
3072
+ throw new InconclusiveMatchError(`Invalid date: ${value}`);
3073
+ }
3074
+ const overrideDate = convertToDateTime(overrideValue);
3075
+ if (['is_date_before'].includes(operator)) {
3076
+ return overrideDate < parsedDate;
3077
+ }
3078
+ return overrideDate > parsedDate;
3079
+ }
3080
+ default:
3081
+ throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
3082
+ }
3083
+ }
3084
+ function matchCohort(property, propertyValues, cohortProperties, debugMode = false) {
3085
+ const cohortId = String(property.value);
3086
+ if (!(cohortId in cohortProperties)) {
3087
+ throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
3088
+ }
3089
+ const propertyGroup = cohortProperties[cohortId];
3090
+ return matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode);
3091
+ }
3092
+ function matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode = false) {
3093
+ if (!propertyGroup) {
3094
+ return true;
3095
+ }
3096
+ const propertyGroupType = propertyGroup.type;
3097
+ const properties = propertyGroup.values;
3098
+ if (!properties || properties.length === 0) {
3099
+ // empty groups are no-ops, always match
3100
+ return true;
3101
+ }
3102
+ let errorMatchingLocally = false;
3103
+ if ('values' in properties[0]) {
3104
+ // a nested property group
3105
+ for (const prop of properties) {
3106
+ try {
3107
+ const matches = matchPropertyGroup(prop, propertyValues, cohortProperties, debugMode);
3108
+ if (propertyGroupType === 'AND') {
3109
+ if (!matches) {
3110
+ return false;
3111
+ }
3112
+ } else {
3113
+ // OR group
3114
+ if (matches) {
3115
+ return true;
3116
+ }
3117
+ }
3118
+ } catch (err) {
3119
+ if (err instanceof InconclusiveMatchError) {
3120
+ if (debugMode) {
3121
+ console.debug(`Failed to compute property ${prop} locally: ${err}`);
3122
+ }
3123
+ errorMatchingLocally = true;
3124
+ } else {
3125
+ throw err;
3126
+ }
3127
+ }
3128
+ }
3129
+ if (errorMatchingLocally) {
3130
+ throw new InconclusiveMatchError("Can't match cohort without a given cohort property value");
3131
+ }
3132
+ // if we get here, all matched in AND case, or none matched in OR case
3133
+ return propertyGroupType === 'AND';
3134
+ } else {
3135
+ for (const prop of properties) {
3136
+ try {
3137
+ let matches;
3138
+ if (prop.type === 'cohort') {
3139
+ matches = matchCohort(prop, propertyValues, cohortProperties, debugMode);
3140
+ } else {
3141
+ matches = matchProperty(prop, propertyValues);
3142
+ }
3143
+ const negation = prop.negation || false;
3144
+ if (propertyGroupType === 'AND') {
3145
+ // if negated property, do the inverse
3146
+ if (!matches && !negation) {
3147
+ return false;
3148
+ }
3149
+ if (matches && negation) {
3150
+ return false;
3151
+ }
3152
+ } else {
3153
+ // OR group
3154
+ if (matches && !negation) {
3155
+ return true;
3156
+ }
3157
+ if (!matches && negation) {
3158
+ return true;
3159
+ }
3160
+ }
3161
+ } catch (err) {
3162
+ if (err instanceof InconclusiveMatchError) {
3163
+ if (debugMode) {
3164
+ console.debug(`Failed to compute property ${prop} locally: ${err}`);
3165
+ }
3166
+ errorMatchingLocally = true;
3167
+ } else {
3168
+ throw err;
3169
+ }
3170
+ }
3171
+ }
3172
+ if (errorMatchingLocally) {
3173
+ throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
3174
+ }
3175
+ // if we get here, all matched in AND case, or none matched in OR case
3176
+ return propertyGroupType === 'AND';
3177
+ }
3178
+ }
3179
+ function isValidRegex(regex) {
3180
+ try {
3181
+ new RegExp(regex);
3182
+ return true;
3183
+ } catch (err) {
3184
+ return false;
3185
+ }
3186
+ }
3187
+ function convertToDateTime(value) {
3188
+ if (value instanceof Date) {
3189
+ return value;
3190
+ } else if (typeof value === 'string' || typeof value === 'number') {
3191
+ const date = new Date(value);
3192
+ if (!isNaN(date.valueOf())) {
3193
+ return date;
3194
+ }
3195
+ throw new InconclusiveMatchError(`${value} is in an invalid date format`);
3196
+ } else {
3197
+ throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
3198
+ }
3199
+ }
3200
+ function relativeDateParseForFeatureFlagMatching(value) {
3201
+ const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
3202
+ const match = value.match(regex);
3203
+ const parsedDt = new Date(new Date().toISOString());
3204
+ if (match) {
3205
+ if (!match.groups) {
3206
+ return null;
3207
+ }
3208
+ const number = parseInt(match.groups['number']);
3209
+ if (number >= 10000) {
3210
+ // Guard against overflow, disallow numbers greater than 10_000
3211
+ return null;
3212
+ }
3213
+ const interval = match.groups['interval'];
3214
+ if (interval == 'h') {
3215
+ parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
3216
+ } else if (interval == 'd') {
3217
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
3218
+ } else if (interval == 'w') {
3219
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - number * 7);
3220
+ } else if (interval == 'm') {
3221
+ parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
3222
+ } else if (interval == 'y') {
3223
+ parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
3224
+ } else {
3225
+ return null;
3226
+ }
3227
+ return parsedDt;
3228
+ } else {
3229
+ return null;
3230
+ }
3231
+ }
3232
+
3233
+ class PostHogMemoryStorage {
3234
+ constructor() {
3235
+ this._memoryStorage = {};
3236
+ }
3237
+ getProperty(key) {
3238
+ return this._memoryStorage[key];
3239
+ }
3240
+ setProperty(key, value) {
3241
+ this._memoryStorage[key] = value !== null ? value : undefined;
3242
+ }
3243
+ }
3244
+
3245
+ // Standard local evaluation rate limit is 600 per minute (10 per second),
3246
+ // so the fastest a poller should ever be set is 100ms.
3247
+ const MINIMUM_POLLING_INTERVAL = 100;
3248
+ const THIRTY_SECONDS = 30 * 1000;
3249
+ const MAX_CACHE_SIZE = 50 * 1000;
3250
+ // The actual exported Nodejs API.
3251
+ class PostHogBackendClient extends PostHogCoreStateless {
3252
+ constructor(apiKey, options = {}) {
3253
+ super(apiKey, options);
3254
+ this._memoryStorage = new PostHogMemoryStorage();
3255
+ this.options = options;
3256
+ this.options.featureFlagsPollingInterval = typeof options.featureFlagsPollingInterval === 'number' ? Math.max(options.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;
3257
+ if (options.personalApiKey) {
3258
+ if (options.personalApiKey.includes('phc_')) {
3259
+ throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');
3260
+ }
3261
+ this.featureFlagsPoller = new FeatureFlagsPoller({
3262
+ pollingInterval: this.options.featureFlagsPollingInterval,
3263
+ personalApiKey: options.personalApiKey,
3264
+ projectApiKey: apiKey,
3265
+ timeout: options.requestTimeout ?? 10000,
3266
+ host: this.host,
3267
+ fetch: options.fetch,
3268
+ onError: err => {
3269
+ this._events.emit('error', err);
3270
+ },
3271
+ onLoad: count => {
3272
+ this._events.emit('localEvaluationFlagsLoaded', count);
3273
+ },
3274
+ customHeaders: this.getCustomHeaders()
3275
+ });
3276
+ }
3277
+ this.errorTracking = new ErrorTracking(this, options);
3278
+ this.distinctIdHasSentFlagCalls = {};
3279
+ this.maxCacheSize = options.maxCacheSize || MAX_CACHE_SIZE;
3280
+ }
3281
+ getPersistedProperty(key) {
3282
+ return this._memoryStorage.getProperty(key);
3283
+ }
3284
+ setPersistedProperty(key, value) {
3285
+ return this._memoryStorage.setProperty(key, value);
3286
+ }
3287
+ fetch(url, options) {
3288
+ return this.options.fetch ? this.options.fetch(url, options) : fetch$1(url, options);
3289
+ }
3290
+ getLibraryVersion() {
3291
+ return version;
3292
+ }
3293
+ getCustomUserAgent() {
3294
+ return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
3295
+ }
3296
+ enable() {
3297
+ return super.optIn();
3298
+ }
3299
+ disable() {
3300
+ return super.optOut();
3301
+ }
3302
+ debug(enabled = true) {
3303
+ super.debug(enabled);
3304
+ this.featureFlagsPoller?.debug(enabled);
3305
+ }
3306
+ capture(props) {
3307
+ if (typeof props === 'string') {
3308
+ this.logMsgIfDebug(() => console.warn('Called capture() with a string as the first argument when an object was expected.'));
3309
+ }
3310
+ const {
3311
+ distinctId,
3312
+ event,
3313
+ properties,
3314
+ groups,
3315
+ sendFeatureFlags,
3316
+ timestamp,
3317
+ disableGeoip,
3318
+ uuid
3319
+ } = props;
3320
+ const _capture = props => {
3321
+ super.captureStateless(distinctId, event, props, {
3322
+ timestamp,
3323
+ disableGeoip,
3324
+ uuid
3325
+ });
3326
+ };
3327
+ const _getFlags = async (distinctId, groups, disableGeoip) => {
3328
+ return (await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)).flags;
3329
+ };
3330
+ // :TRICKY: If we flush, or need to shut down, to not lose events we want this promise to resolve before we flush
3331
+ const capturePromise = Promise.resolve().then(async () => {
3332
+ if (sendFeatureFlags) {
3333
+ // If we are sending feature flags, we need to make sure we have the latest flags
3334
+ // return await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)
3335
+ return await _getFlags(distinctId, groups, disableGeoip);
3336
+ }
3337
+ if (event === '$feature_flag_called') {
3338
+ // If we're capturing a $feature_flag_called event, we don't want to enrich the event with cached flags that may be out of date.
3339
+ return {};
3340
+ }
3341
+ if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
3342
+ // Otherwise we may as well check for the flags locally and include them if they are already loaded
3343
+ const groupsWithStringValues = {};
3344
+ for (const [key, value] of Object.entries(groups || {})) {
3345
+ groupsWithStringValues[key] = String(value);
3346
+ }
3347
+ return await this.getAllFlags(distinctId, {
3348
+ groups: groupsWithStringValues,
3349
+ disableGeoip,
3350
+ onlyEvaluateLocally: true
3351
+ });
3352
+ }
3353
+ return {};
3354
+ }).then(flags => {
3355
+ // Derive the relevant flag properties to add
3356
+ const additionalProperties = {};
3357
+ if (flags) {
3358
+ for (const [feature, variant] of Object.entries(flags)) {
3359
+ additionalProperties[`$feature/${feature}`] = variant;
3360
+ }
3361
+ }
3362
+ const activeFlags = Object.keys(flags || {}).filter(flag => flags?.[flag] !== false).sort();
3363
+ if (activeFlags.length > 0) {
3364
+ additionalProperties['$active_feature_flags'] = activeFlags;
3365
+ }
3366
+ return additionalProperties;
3367
+ }).catch(() => {
3368
+ // Something went wrong getting the flag info - we should capture the event anyways
3369
+ return {};
3370
+ }).then(additionalProperties => {
3371
+ // No matter what - capture the event
3372
+ _capture({
3373
+ ...additionalProperties,
3374
+ ...properties,
3375
+ $groups: groups
3376
+ });
3377
+ });
3378
+ this.addPendingPromise(capturePromise);
3379
+ }
3380
+ async captureImmediate(props) {
3381
+ if (typeof props === 'string') {
3382
+ this.logMsgIfDebug(() => console.warn('Called capture() with a string as the first argument when an object was expected.'));
3383
+ }
3384
+ const {
3385
+ distinctId,
3386
+ event,
3387
+ properties,
3388
+ groups,
3389
+ sendFeatureFlags,
3390
+ timestamp,
3391
+ disableGeoip,
3392
+ uuid
3393
+ } = props;
3394
+ const _capture = props => {
3395
+ return super.captureStatelessImmediate(distinctId, event, props, {
3396
+ timestamp,
3397
+ disableGeoip,
3398
+ uuid
3399
+ });
3400
+ };
3401
+ const _getFlags = async (distinctId, groups, disableGeoip) => {
3402
+ return (await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)).flags;
3403
+ };
3404
+ const capturePromise = Promise.resolve().then(async () => {
3405
+ if (sendFeatureFlags) {
3406
+ // If we are sending feature flags, we need to make sure we have the latest flags
3407
+ // return await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)
3408
+ return await _getFlags(distinctId, groups, disableGeoip);
3409
+ }
3410
+ if (event === '$feature_flag_called') {
3411
+ // If we're capturing a $feature_flag_called event, we don't want to enrich the event with cached flags that may be out of date.
3412
+ return {};
3413
+ }
3414
+ if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
3415
+ // Otherwise we may as well check for the flags locally and include them if they are already loaded
3416
+ const groupsWithStringValues = {};
3417
+ for (const [key, value] of Object.entries(groups || {})) {
3418
+ groupsWithStringValues[key] = String(value);
3419
+ }
3420
+ return await this.getAllFlags(distinctId, {
3421
+ groups: groupsWithStringValues,
3422
+ disableGeoip,
3423
+ onlyEvaluateLocally: true
3424
+ });
3425
+ }
3426
+ return {};
3427
+ }).then(flags => {
3428
+ // Derive the relevant flag properties to add
3429
+ const additionalProperties = {};
3430
+ if (flags) {
3431
+ for (const [feature, variant] of Object.entries(flags)) {
3432
+ additionalProperties[`$feature/${feature}`] = variant;
3433
+ }
3434
+ }
3435
+ const activeFlags = Object.keys(flags || {}).filter(flag => flags?.[flag] !== false).sort();
3436
+ if (activeFlags.length > 0) {
3437
+ additionalProperties['$active_feature_flags'] = activeFlags;
3438
+ }
3439
+ return additionalProperties;
3440
+ }).catch(() => {
3441
+ // Something went wrong getting the flag info - we should capture the event anyways
3442
+ return {};
3443
+ }).then(additionalProperties => {
3444
+ // No matter what - capture the event
3445
+ _capture({
3446
+ ...additionalProperties,
3447
+ ...properties,
3448
+ $groups: groups
3449
+ });
3450
+ });
3451
+ await capturePromise;
3452
+ }
3453
+ identify({
3454
+ distinctId,
3455
+ properties,
3456
+ disableGeoip
3457
+ }) {
3458
+ // Catch properties passed as $set and move them to the top level
3459
+ // promote $set and $set_once to top level
3460
+ const userPropsOnce = properties?.$set_once;
3461
+ delete properties?.$set_once;
3462
+ // if no $set is provided we assume all properties are $set
3463
+ const userProps = properties?.$set || properties;
3464
+ super.identifyStateless(distinctId, {
3465
+ $set: userProps,
3466
+ $set_once: userPropsOnce
3467
+ }, {
3468
+ disableGeoip
3469
+ });
3470
+ }
3471
+ async identifyImmediate({
3472
+ distinctId,
3473
+ properties,
3474
+ disableGeoip
3475
+ }) {
3476
+ // promote $set and $set_once to top level
3477
+ const userPropsOnce = properties?.$set_once;
3478
+ delete properties?.$set_once;
3479
+ // if no $set is provided we assume all properties are $set
3480
+ const userProps = properties?.$set || properties;
3481
+ await super.identifyStatelessImmediate(distinctId, {
3482
+ $set: userProps,
3483
+ $set_once: userPropsOnce
3484
+ }, {
3485
+ disableGeoip
3486
+ });
3487
+ }
3488
+ alias(data) {
3489
+ super.aliasStateless(data.alias, data.distinctId, undefined, {
3490
+ disableGeoip: data.disableGeoip
3491
+ });
3492
+ }
3493
+ async aliasImmediate(data) {
3494
+ await super.aliasStatelessImmediate(data.alias, data.distinctId, undefined, {
3495
+ disableGeoip: data.disableGeoip
3496
+ });
3497
+ }
3498
+ isLocalEvaluationReady() {
3499
+ return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;
3500
+ }
3501
+ async waitForLocalEvaluationReady(timeoutMs = THIRTY_SECONDS) {
3502
+ if (this.isLocalEvaluationReady()) {
3503
+ return true;
3504
+ }
3505
+ if (this.featureFlagsPoller === undefined) {
3506
+ return false;
3507
+ }
3508
+ return new Promise(resolve => {
3509
+ const timeout = setTimeout(() => {
3510
+ cleanup();
3511
+ resolve(false);
3512
+ }, timeoutMs);
3513
+ const cleanup = this._events.on('localEvaluationFlagsLoaded', count => {
3514
+ clearTimeout(timeout);
3515
+ cleanup();
3516
+ resolve(count > 0);
3517
+ });
3518
+ });
3519
+ }
3520
+ async getFeatureFlag(key, distinctId, options) {
3521
+ const {
3522
+ groups,
3523
+ disableGeoip
3524
+ } = options || {};
3525
+ let {
3526
+ onlyEvaluateLocally,
3527
+ sendFeatureFlagEvents,
3528
+ personProperties,
3529
+ groupProperties
3530
+ } = options || {};
3531
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3532
+ personProperties = adjustedProperties.allPersonProperties;
3533
+ groupProperties = adjustedProperties.allGroupProperties;
3534
+ // set defaults
3535
+ if (onlyEvaluateLocally == undefined) {
3536
+ onlyEvaluateLocally = false;
3537
+ }
3538
+ if (sendFeatureFlagEvents == undefined) {
3539
+ sendFeatureFlagEvents = true;
3540
+ }
3541
+ let response = await this.featureFlagsPoller?.getFeatureFlag(key, distinctId, groups, personProperties, groupProperties);
3542
+ const flagWasLocallyEvaluated = response !== undefined;
3543
+ let requestId = undefined;
3544
+ let flagDetail = undefined;
3545
+ if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {
3546
+ const remoteResponse = await super.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
3547
+ if (remoteResponse === undefined) {
3548
+ return undefined;
3549
+ }
3550
+ flagDetail = remoteResponse.response;
3551
+ response = getFeatureFlagValue(flagDetail);
3552
+ requestId = remoteResponse?.requestId;
3553
+ }
3554
+ const featureFlagReportedKey = `${key}_${response}`;
3555
+ if (sendFeatureFlagEvents && (!(distinctId in this.distinctIdHasSentFlagCalls) || !this.distinctIdHasSentFlagCalls[distinctId].includes(featureFlagReportedKey))) {
3556
+ if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize) {
3557
+ this.distinctIdHasSentFlagCalls = {};
3558
+ }
3559
+ if (Array.isArray(this.distinctIdHasSentFlagCalls[distinctId])) {
3560
+ this.distinctIdHasSentFlagCalls[distinctId].push(featureFlagReportedKey);
3561
+ } else {
3562
+ this.distinctIdHasSentFlagCalls[distinctId] = [featureFlagReportedKey];
3563
+ }
3564
+ this.capture({
3565
+ distinctId,
3566
+ event: '$feature_flag_called',
3567
+ properties: {
3568
+ $feature_flag: key,
3569
+ $feature_flag_response: response,
3570
+ $feature_flag_id: flagDetail?.metadata?.id,
3571
+ $feature_flag_version: flagDetail?.metadata?.version,
3572
+ $feature_flag_reason: flagDetail?.reason?.description ?? flagDetail?.reason?.code,
3573
+ locally_evaluated: flagWasLocallyEvaluated,
3574
+ [`$feature/${key}`]: response,
3575
+ $feature_flag_request_id: requestId
3576
+ },
3577
+ groups,
3578
+ disableGeoip
3579
+ });
3580
+ }
3581
+ return response;
3582
+ }
3583
+ async getFeatureFlagPayload(key, distinctId, matchValue, options) {
3584
+ const {
3585
+ groups,
3586
+ disableGeoip
3587
+ } = options || {};
3588
+ let {
3589
+ onlyEvaluateLocally,
3590
+ sendFeatureFlagEvents,
3591
+ personProperties,
3592
+ groupProperties
3593
+ } = options || {};
3594
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3595
+ personProperties = adjustedProperties.allPersonProperties;
3596
+ groupProperties = adjustedProperties.allGroupProperties;
3597
+ let response = undefined;
3598
+ const localEvaluationEnabled = this.featureFlagsPoller !== undefined;
3599
+ if (localEvaluationEnabled) {
3600
+ // Try to get match value locally if not provided
3601
+ if (!matchValue) {
3602
+ matchValue = await this.getFeatureFlag(key, distinctId, {
3603
+ ...options,
3604
+ onlyEvaluateLocally: true,
3605
+ sendFeatureFlagEvents: false
3606
+ });
3607
+ }
3608
+ if (matchValue) {
3609
+ response = await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(key, matchValue);
3610
+ }
3611
+ }
3612
+ //}
3613
+ // set defaults
3614
+ if (onlyEvaluateLocally == undefined) {
3615
+ onlyEvaluateLocally = false;
3616
+ }
3617
+ if (sendFeatureFlagEvents == undefined) {
3618
+ sendFeatureFlagEvents = true;
3619
+ }
3620
+ // set defaults
3621
+ if (onlyEvaluateLocally == undefined) {
3622
+ onlyEvaluateLocally = false;
3623
+ }
3624
+ const payloadWasLocallyEvaluated = response !== undefined;
3625
+ if (!payloadWasLocallyEvaluated && !onlyEvaluateLocally) {
3626
+ response = await super.getFeatureFlagPayloadStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
3627
+ }
3628
+ return response;
3629
+ }
3630
+ async getRemoteConfigPayload(flagKey) {
3631
+ return (await this.featureFlagsPoller?._requestRemoteConfigPayload(flagKey))?.json();
3632
+ }
3633
+ async isFeatureEnabled(key, distinctId, options) {
3634
+ const feat = await this.getFeatureFlag(key, distinctId, options);
3635
+ if (feat === undefined) {
3636
+ return undefined;
3637
+ }
3638
+ return !!feat || false;
3639
+ }
3640
+ async getAllFlags(distinctId, options) {
3641
+ const response = await this.getAllFlagsAndPayloads(distinctId, options);
3642
+ return response.featureFlags || {};
3643
+ }
3644
+ async getAllFlagsAndPayloads(distinctId, options) {
3645
+ const {
3646
+ groups,
3647
+ disableGeoip
3648
+ } = options || {};
3649
+ let {
3650
+ onlyEvaluateLocally,
3651
+ personProperties,
3652
+ groupProperties
3653
+ } = options || {};
3654
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3655
+ personProperties = adjustedProperties.allPersonProperties;
3656
+ groupProperties = adjustedProperties.allGroupProperties;
3657
+ // set defaults
3658
+ if (onlyEvaluateLocally == undefined) {
3659
+ onlyEvaluateLocally = false;
3660
+ }
3661
+ const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(distinctId, groups, personProperties, groupProperties);
3662
+ let featureFlags = {};
3663
+ let featureFlagPayloads = {};
3664
+ let fallbackToDecide = true;
3665
+ if (localEvaluationResult) {
3666
+ featureFlags = localEvaluationResult.response;
3667
+ featureFlagPayloads = localEvaluationResult.payloads;
3668
+ fallbackToDecide = localEvaluationResult.fallbackToDecide;
3669
+ }
3670
+ if (fallbackToDecide && !onlyEvaluateLocally) {
3671
+ const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip);
3672
+ featureFlags = {
3673
+ ...featureFlags,
3674
+ ...(remoteEvaluationResult.flags || {})
3675
+ };
3676
+ featureFlagPayloads = {
3677
+ ...featureFlagPayloads,
3678
+ ...(remoteEvaluationResult.payloads || {})
3679
+ };
3680
+ }
3681
+ return {
3682
+ featureFlags,
3683
+ featureFlagPayloads
3684
+ };
3685
+ }
3686
+ groupIdentify({
3687
+ groupType,
3688
+ groupKey,
3689
+ properties,
3690
+ distinctId,
3691
+ disableGeoip
3692
+ }) {
3693
+ super.groupIdentifyStateless(groupType, groupKey, properties, {
3694
+ disableGeoip
3695
+ }, distinctId);
3696
+ }
3697
+ /**
3698
+ * Reloads the feature flag definitions from the server for local evaluation.
3699
+ * This is useful to call if you want to ensure that the feature flags are up to date before calling getFeatureFlag.
3700
+ */
3701
+ async reloadFeatureFlags() {
3702
+ await this.featureFlagsPoller?.loadFeatureFlags(true);
3703
+ }
3704
+ async _shutdown(shutdownTimeoutMs) {
3705
+ this.featureFlagsPoller?.stopPoller();
3706
+ return super._shutdown(shutdownTimeoutMs);
3707
+ }
3708
+ addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {
3709
+ const allPersonProperties = {
3710
+ distinct_id: distinctId,
3711
+ ...(personProperties || {})
3712
+ };
3713
+ const allGroupProperties = {};
3714
+ if (groups) {
3715
+ for (const groupName of Object.keys(groups)) {
3716
+ allGroupProperties[groupName] = {
3717
+ $group_key: groups[groupName],
3718
+ ...(groupProperties?.[groupName] || {})
3719
+ };
3720
+ }
3721
+ }
3722
+ return {
3723
+ allPersonProperties,
3724
+ allGroupProperties
3725
+ };
3726
+ }
3727
+ captureException(error, distinctId, additionalProperties) {
3728
+ const syntheticException = new Error('PostHog syntheticException');
3729
+ ErrorTracking.captureException(this, error, {
3730
+ syntheticException
3731
+ }, distinctId, additionalProperties);
3732
+ }
3733
+ }
3734
+
3735
+ // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
3736
+ // Licensed under the MIT License
3737
+ // This was originally forked from https://github.com/csnover/TraceKit, and was largely
3738
+ // re-written as part of raven - js.
3739
+ //
3740
+ // This code was later copied to the JavaScript mono - repo and further modified and
3741
+ // refactored over the years.
3742
+ // Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.
3743
+ //
3744
+ // Permission is hereby granted, free of charge, to any person obtaining a copy of this
3745
+ // software and associated documentation files(the 'Software'), to deal in the Software
3746
+ // without restriction, including without limitation the rights to use, copy, modify,
3747
+ // merge, publish, distribute, sublicense, and / or sell copies of the Software, and to
3748
+ // permit persons to whom the Software is furnished to do so, subject to the following
3749
+ // conditions:
3750
+ //
3751
+ // The above copyright notice and this permission notice shall be included in all copies
3752
+ // or substantial portions of the Software.
3753
+ //
3754
+ // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
3755
+ // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
3756
+ // PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
3757
+ // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
3758
+ // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
3759
+ // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
3760
+ const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
3761
+ const STACKTRACE_FRAME_LIMIT = 50;
3762
+ const UNKNOWN_FUNCTION = '?';
3763
+ /** Node Stack line parser */
3764
+ function node(getModule) {
3765
+ const FILENAME_MATCH = /^\s*[-]{4,}$/;
3766
+ const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
3767
+ return line => {
3768
+ const lineMatch = line.match(FULL_MATCH);
3769
+ if (lineMatch) {
3770
+ let object;
3771
+ let method;
3772
+ let functionName;
3773
+ let typeName;
3774
+ let methodName;
3775
+ if (lineMatch[1]) {
3776
+ functionName = lineMatch[1];
3777
+ let methodStart = functionName.lastIndexOf('.');
3778
+ if (functionName[methodStart - 1] === '.') {
3779
+ methodStart--;
3780
+ }
3781
+ if (methodStart > 0) {
3782
+ object = functionName.slice(0, methodStart);
3783
+ method = functionName.slice(methodStart + 1);
3784
+ const objectEnd = object.indexOf('.Module');
3785
+ if (objectEnd > 0) {
3786
+ functionName = functionName.slice(objectEnd + 1);
3787
+ object = object.slice(0, objectEnd);
3788
+ }
3789
+ }
3790
+ typeName = undefined;
3791
+ }
3792
+ if (method) {
3793
+ typeName = object;
3794
+ methodName = method;
3795
+ }
3796
+ if (method === '<anonymous>') {
3797
+ methodName = undefined;
3798
+ functionName = undefined;
3799
+ }
3800
+ if (functionName === undefined) {
3801
+ methodName = methodName || UNKNOWN_FUNCTION;
3802
+ functionName = typeName ? `${typeName}.${methodName}` : methodName;
3803
+ }
3804
+ let filename = lineMatch[2]?.startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];
3805
+ const isNative = lineMatch[5] === 'native';
3806
+ // If it's a Windows path, trim the leading slash so that `/C:/foo` becomes `C:/foo`
3807
+ if (filename?.match(/\/[A-Z]:/)) {
3808
+ filename = filename.slice(1);
3809
+ }
3810
+ if (!filename && lineMatch[5] && !isNative) {
3811
+ filename = lineMatch[5];
3812
+ }
3813
+ return {
3814
+ filename: filename ? decodeURI(filename) : undefined,
3815
+ module: getModule ? getModule(filename) : undefined,
3816
+ function: functionName,
3817
+ lineno: _parseIntOrUndefined(lineMatch[3]),
3818
+ colno: _parseIntOrUndefined(lineMatch[4]),
3819
+ in_app: filenameIsInApp(filename || '', isNative),
3820
+ platform: 'node:javascript'
3821
+ };
3822
+ }
3823
+ if (line.match(FILENAME_MATCH)) {
3824
+ return {
3825
+ filename: line,
3826
+ platform: 'node:javascript'
3827
+ };
3828
+ }
3829
+ return undefined;
3830
+ };
3831
+ }
3832
+ /**
3833
+ * Does this filename look like it's part of the app code?
3834
+ */
3835
+ function filenameIsInApp(filename, isNative = false) {
3836
+ const isInternal = isNative || filename &&
3837
+ // It's not internal if it's an absolute linux path
3838
+ !filename.startsWith('/') &&
3839
+ // It's not internal if it's an absolute windows path
3840
+ !filename.match(/^[A-Z]:/) &&
3841
+ // It's not internal if the path is starting with a dot
3842
+ !filename.startsWith('.') &&
3843
+ // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack
3844
+ !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//); // Schema from: https://stackoverflow.com/a/3641782
3845
+ // in_app is all that's not an internal Node function or a module within node_modules
3846
+ // note that isNative appears to return true even for node core libraries
3847
+ // see https://github.com/getsentry/raven-node/issues/176
3848
+ return !isInternal && filename !== undefined && !filename.includes('node_modules/');
3849
+ }
3850
+ function _parseIntOrUndefined(input) {
3851
+ return parseInt(input || '', 10) || undefined;
3852
+ }
3853
+ function nodeStackLineParser(getModule) {
3854
+ return [90, node(getModule)];
3855
+ }
3856
+ function createStackParser(getModule) {
3857
+ const parsers = [nodeStackLineParser(getModule)];
3858
+ const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);
3859
+ return (stack, skipFirstLines = 0) => {
3860
+ const frames = [];
3861
+ const lines = stack.split('\n');
3862
+ for (let i = skipFirstLines; i < lines.length; i++) {
3863
+ const line = lines[i];
3864
+ // Ignore lines over 1kb as they are unlikely to be stack frames.
3865
+ if (line.length > 1024) {
3866
+ continue;
3867
+ }
3868
+ // https://github.com/getsentry/sentry-javascript/issues/5459
3869
+ // Remove webpack (error: *) wrappers
3870
+ const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;
3871
+ // https://github.com/getsentry/sentry-javascript/issues/7813
3872
+ // Skip Error: lines
3873
+ if (cleanedLine.match(/\S*Error: /)) {
3874
+ continue;
3875
+ }
3876
+ for (const parser of sortedParsers) {
3877
+ const frame = parser(cleanedLine);
3878
+ if (frame) {
3879
+ frames.push(frame);
3880
+ break;
3881
+ }
3882
+ }
3883
+ if (frames.length >= STACKTRACE_FRAME_LIMIT) {
3884
+ break;
3885
+ }
3886
+ }
3887
+ return reverseAndStripFrames(frames);
3888
+ };
3889
+ }
3890
+ function reverseAndStripFrames(stack) {
3891
+ if (!stack.length) {
3892
+ return [];
3893
+ }
3894
+ const localStack = Array.from(stack);
3895
+ localStack.reverse();
3896
+ return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({
3897
+ ...frame,
3898
+ filename: frame.filename || getLastStackFrame(localStack).filename,
3899
+ function: frame.function || UNKNOWN_FUNCTION
3900
+ }));
3901
+ }
3902
+ function getLastStackFrame(arr) {
3903
+ return arr[arr.length - 1] || {};
3904
+ }
3905
+
3906
+ ErrorTracking.stackParser = createStackParser();
3907
+ ErrorTracking.frameModifiers = [];
3908
+ class PostHog extends PostHogBackendClient {
3909
+ getLibraryId() {
3910
+ return 'posthog-edge';
3911
+ }
3912
+ }
3913
+
3914
+ exports.PostHog = PostHog;
3915
+ exports.PostHogSentryIntegration = PostHogSentryIntegration;
3916
+ exports.createEventProcessor = createEventProcessor;
3917
+ exports.sentryIntegration = sentryIntegration;
3918
+ exports.setupExpressErrorHandler = setupExpressErrorHandler;
3919
+ //# sourceMappingURL=index.cjs.js.map