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