posthog-node 1.3.0 → 2.0.0-alpha3

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.
@@ -0,0 +1,1300 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var undici = require('undici');
6
+
7
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
+
9
+ var undici__default = /*#__PURE__*/_interopDefaultLegacy(undici);
10
+
11
+ /******************************************************************************
12
+ Copyright (c) Microsoft Corporation.
13
+
14
+ Permission to use, copy, modify, and/or distribute this software for any
15
+ purpose with or without fee is hereby granted.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
18
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
19
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
20
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
22
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23
+ PERFORMANCE OF THIS SOFTWARE.
24
+ ***************************************************************************** */
25
+ /* global Reflect, Promise */
26
+ var extendStatics = function (d, b) {
27
+ extendStatics = Object.setPrototypeOf ||
28
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
29
+ function (d, b) { for (var p in b)
30
+ if (Object.prototype.hasOwnProperty.call(b, p))
31
+ d[p] = b[p]; };
32
+ return extendStatics(d, b);
33
+ };
34
+ function __extends(d, b) {
35
+ if (typeof b !== "function" && b !== null)
36
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
37
+ extendStatics(d, b);
38
+ function __() { this.constructor = d; }
39
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40
+ }
41
+ var __assign = function () {
42
+ __assign = Object.assign || function __assign(t) {
43
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
44
+ s = arguments[i];
45
+ for (var p in s)
46
+ if (Object.prototype.hasOwnProperty.call(s, p))
47
+ t[p] = s[p];
48
+ }
49
+ return t;
50
+ };
51
+ return __assign.apply(this, arguments);
52
+ };
53
+ function __awaiter(thisArg, _arguments, P, generator) {
54
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
55
+ return new (P || (P = Promise))(function (resolve, reject) {
56
+ function fulfilled(value) { try {
57
+ step(generator.next(value));
58
+ }
59
+ catch (e) {
60
+ reject(e);
61
+ } }
62
+ function rejected(value) { try {
63
+ step(generator["throw"](value));
64
+ }
65
+ catch (e) {
66
+ reject(e);
67
+ } }
68
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
69
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
70
+ });
71
+ }
72
+ function __generator(thisArg, body) {
73
+ var _ = { label: 0, sent: function () { if (t[0] & 1)
74
+ throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
75
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
76
+ function verb(n) { return function (v) { return step([n, v]); }; }
77
+ function step(op) {
78
+ if (f)
79
+ throw new TypeError("Generator is already executing.");
80
+ while (_)
81
+ try {
82
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
83
+ return t;
84
+ if (y = 0, t)
85
+ op = [op[0] & 2, t.value];
86
+ switch (op[0]) {
87
+ case 0:
88
+ case 1:
89
+ t = op;
90
+ break;
91
+ case 4:
92
+ _.label++;
93
+ return { value: op[1], done: false };
94
+ case 5:
95
+ _.label++;
96
+ y = op[1];
97
+ op = [0];
98
+ continue;
99
+ case 7:
100
+ op = _.ops.pop();
101
+ _.trys.pop();
102
+ continue;
103
+ default:
104
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
105
+ _ = 0;
106
+ continue;
107
+ }
108
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
109
+ _.label = op[1];
110
+ break;
111
+ }
112
+ if (op[0] === 6 && _.label < t[1]) {
113
+ _.label = t[1];
114
+ t = op;
115
+ break;
116
+ }
117
+ if (t && _.label < t[2]) {
118
+ _.label = t[2];
119
+ _.ops.push(op);
120
+ break;
121
+ }
122
+ if (t[2])
123
+ _.ops.pop();
124
+ _.trys.pop();
125
+ continue;
126
+ }
127
+ op = body.call(thisArg, _);
128
+ }
129
+ catch (e) {
130
+ op = [6, e];
131
+ y = 0;
132
+ }
133
+ finally {
134
+ f = t = 0;
135
+ }
136
+ if (op[0] & 5)
137
+ throw op[1];
138
+ return { value: op[0] ? op[1] : void 0, done: true };
139
+ }
140
+ }
141
+
142
+ var version = "2.0.0-alpha3";
143
+
144
+ var PostHogPersistedProperty;
145
+ (function (PostHogPersistedProperty) {
146
+ PostHogPersistedProperty["DistinctId"] = "distinct_id";
147
+ PostHogPersistedProperty["Props"] = "props";
148
+ PostHogPersistedProperty["FeatureFlags"] = "feature_flags";
149
+ PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
150
+ PostHogPersistedProperty["Queue"] = "queue";
151
+ PostHogPersistedProperty["OptedOut"] = "opted_out";
152
+ PostHogPersistedProperty["SessionId"] = "session_id";
153
+ PostHogPersistedProperty["SessionLastTimestamp"] = "session_timestamp";
154
+ })(PostHogPersistedProperty || (PostHogPersistedProperty = {}));
155
+
156
+ function assert(truthyValue, message) {
157
+ if (!truthyValue) {
158
+ throw new Error(message);
159
+ }
160
+ }
161
+ function removeTrailingSlash(url) {
162
+ return url === null || url === void 0 ? void 0 : url.replace(/\/+$/, '');
163
+ }
164
+ function retriable(fn, props) {
165
+ if (props === void 0) { props = {}; }
166
+ return __awaiter(this, void 0, void 0, function () {
167
+ var _a, retryCount, _b, retryDelay, _c, retryCheck, lastError, i, res, e_1;
168
+ return __generator(this, function (_d) {
169
+ switch (_d.label) {
170
+ case 0:
171
+ _a = props.retryCount, retryCount = _a === void 0 ? 3 : _a, _b = props.retryDelay, retryDelay = _b === void 0 ? 5000 : _b, _c = props.retryCheck, retryCheck = _c === void 0 ? function () { return true; } : _c;
172
+ lastError = null;
173
+ i = 0;
174
+ _d.label = 1;
175
+ case 1:
176
+ if (!(i < retryCount + 1)) return [3 /*break*/, 8];
177
+ _d.label = 2;
178
+ case 2:
179
+ _d.trys.push([2, 4, , 5]);
180
+ return [4 /*yield*/, fn()];
181
+ case 3:
182
+ res = _d.sent();
183
+ return [2 /*return*/, res];
184
+ case 4:
185
+ e_1 = _d.sent();
186
+ lastError = e_1;
187
+ if (!retryCheck(e_1)) {
188
+ throw e_1;
189
+ }
190
+ return [3 /*break*/, 5];
191
+ case 5: return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, retryDelay); })];
192
+ case 6:
193
+ _d.sent();
194
+ _d.label = 7;
195
+ case 7:
196
+ i++;
197
+ return [3 /*break*/, 1];
198
+ case 8: throw lastError;
199
+ }
200
+ });
201
+ });
202
+ }
203
+ // https://stackoverflow.com/a/8809472
204
+ function generateUUID(globalThis) {
205
+ // Public Domain/MIT
206
+ var d = new Date().getTime(); //Timestamp
207
+ var d2 = (globalThis && globalThis.performance && globalThis.performance.now && globalThis.performance.now() * 1000) || 0; //Time in microseconds since page-load or 0 if unsupported
208
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
209
+ var r = Math.random() * 16; //random number between 0 and 16
210
+ if (d > 0) {
211
+ //Use timestamp until depleted
212
+ r = (d + r) % 16 | 0;
213
+ d = Math.floor(d / 16);
214
+ }
215
+ else {
216
+ //Use microseconds since page-load if supported
217
+ r = (d2 + r) % 16 | 0;
218
+ d2 = Math.floor(d2 / 16);
219
+ }
220
+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
221
+ });
222
+ }
223
+ function currentTimestamp() {
224
+ return new Date().getTime();
225
+ }
226
+ function currentISOTime() {
227
+ return new Date().toISOString();
228
+ }
229
+ function safeSetTimeout(fn, timeout) {
230
+ // NOTE: we use this so rarely that it is totally fine to do `safeSetTimeout(fn, 0)``
231
+ // rather than setImmediate.
232
+ var t = setTimeout(fn, timeout);
233
+ // We unref if available to prevent Node.js hanging on exit
234
+ (t === null || t === void 0 ? void 0 : t.unref) && (t === null || t === void 0 ? void 0 : t.unref());
235
+ return t;
236
+ }
237
+
238
+ // Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>
239
+ // This work is free. You can redistribute it and/or modify it
240
+ // under the terms of the WTFPL, Version 2
241
+ // For more information see LICENSE.txt or http://www.wtfpl.net/
242
+ //
243
+ // For more information, the home page:
244
+ // http://pieroxy.net/blog/pages/lz-string/testing.html
245
+ //
246
+ // LZ-based compression algorithm, version 1.4.4
247
+ // private property
248
+ var f = String.fromCharCode;
249
+ var keyStrBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
250
+ var baseReverseDic = {};
251
+ function getBaseValue(alphabet, character) {
252
+ if (!baseReverseDic[alphabet]) {
253
+ baseReverseDic[alphabet] = {};
254
+ for (var i = 0; i < alphabet.length; i++) {
255
+ baseReverseDic[alphabet][alphabet.charAt(i)] = i;
256
+ }
257
+ }
258
+ return baseReverseDic[alphabet][character];
259
+ }
260
+ var LZString = {
261
+ compressToBase64: function (input) {
262
+ if (input == null) {
263
+ return '';
264
+ }
265
+ var res = LZString._compress(input, 6, function (a) {
266
+ return keyStrBase64.charAt(a);
267
+ });
268
+ switch (res.length % 4 // To produce valid Base64
269
+ ) {
270
+ default: // When could this happen ?
271
+ case 0:
272
+ return res;
273
+ case 1:
274
+ return res + '===';
275
+ case 2:
276
+ return res + '==';
277
+ case 3:
278
+ return res + '=';
279
+ }
280
+ },
281
+ decompressFromBase64: function (input) {
282
+ if (input == null) {
283
+ return '';
284
+ }
285
+ if (input == '') {
286
+ return null;
287
+ }
288
+ return LZString._decompress(input.length, 32, function (index) {
289
+ return getBaseValue(keyStrBase64, input.charAt(index));
290
+ });
291
+ },
292
+ compress: function (uncompressed) {
293
+ return LZString._compress(uncompressed, 16, function (a) {
294
+ return f(a);
295
+ });
296
+ },
297
+ _compress: function (uncompressed, bitsPerChar, getCharFromInt) {
298
+ if (uncompressed == null) {
299
+ return '';
300
+ }
301
+ var context_dictionary = {}, context_dictionaryToCreate = {}, context_data = [];
302
+ var i, value, context_c = '', context_wc = '', context_w = '', context_enlargeIn = 2, // Compensate for the first entry which should not count
303
+ context_dictSize = 3, context_numBits = 2, context_data_val = 0, context_data_position = 0, ii;
304
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
305
+ context_c = uncompressed.charAt(ii);
306
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
307
+ context_dictionary[context_c] = context_dictSize++;
308
+ context_dictionaryToCreate[context_c] = true;
309
+ }
310
+ context_wc = context_w + context_c;
311
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) {
312
+ context_w = context_wc;
313
+ }
314
+ else {
315
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
316
+ if (context_w.charCodeAt(0) < 256) {
317
+ for (i = 0; i < context_numBits; i++) {
318
+ context_data_val = context_data_val << 1;
319
+ if (context_data_position == bitsPerChar - 1) {
320
+ context_data_position = 0;
321
+ context_data.push(getCharFromInt(context_data_val));
322
+ context_data_val = 0;
323
+ }
324
+ else {
325
+ context_data_position++;
326
+ }
327
+ }
328
+ value = context_w.charCodeAt(0);
329
+ for (i = 0; i < 8; i++) {
330
+ context_data_val = (context_data_val << 1) | (value & 1);
331
+ if (context_data_position == bitsPerChar - 1) {
332
+ context_data_position = 0;
333
+ context_data.push(getCharFromInt(context_data_val));
334
+ context_data_val = 0;
335
+ }
336
+ else {
337
+ context_data_position++;
338
+ }
339
+ value = value >> 1;
340
+ }
341
+ }
342
+ else {
343
+ value = 1;
344
+ for (i = 0; i < context_numBits; i++) {
345
+ context_data_val = (context_data_val << 1) | value;
346
+ if (context_data_position == bitsPerChar - 1) {
347
+ context_data_position = 0;
348
+ context_data.push(getCharFromInt(context_data_val));
349
+ context_data_val = 0;
350
+ }
351
+ else {
352
+ context_data_position++;
353
+ }
354
+ value = 0;
355
+ }
356
+ value = context_w.charCodeAt(0);
357
+ for (i = 0; i < 16; i++) {
358
+ context_data_val = (context_data_val << 1) | (value & 1);
359
+ if (context_data_position == bitsPerChar - 1) {
360
+ context_data_position = 0;
361
+ context_data.push(getCharFromInt(context_data_val));
362
+ context_data_val = 0;
363
+ }
364
+ else {
365
+ context_data_position++;
366
+ }
367
+ value = value >> 1;
368
+ }
369
+ }
370
+ context_enlargeIn--;
371
+ if (context_enlargeIn == 0) {
372
+ context_enlargeIn = Math.pow(2, context_numBits);
373
+ context_numBits++;
374
+ }
375
+ delete context_dictionaryToCreate[context_w];
376
+ }
377
+ else {
378
+ value = context_dictionary[context_w];
379
+ for (i = 0; i < context_numBits; i++) {
380
+ context_data_val = (context_data_val << 1) | (value & 1);
381
+ if (context_data_position == bitsPerChar - 1) {
382
+ context_data_position = 0;
383
+ context_data.push(getCharFromInt(context_data_val));
384
+ context_data_val = 0;
385
+ }
386
+ else {
387
+ context_data_position++;
388
+ }
389
+ value = value >> 1;
390
+ }
391
+ }
392
+ context_enlargeIn--;
393
+ if (context_enlargeIn == 0) {
394
+ context_enlargeIn = Math.pow(2, context_numBits);
395
+ context_numBits++;
396
+ }
397
+ // Add wc to the dictionary.
398
+ context_dictionary[context_wc] = context_dictSize++;
399
+ context_w = String(context_c);
400
+ }
401
+ }
402
+ // Output the code for w.
403
+ if (context_w !== '') {
404
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
405
+ if (context_w.charCodeAt(0) < 256) {
406
+ for (i = 0; i < context_numBits; i++) {
407
+ context_data_val = context_data_val << 1;
408
+ if (context_data_position == bitsPerChar - 1) {
409
+ context_data_position = 0;
410
+ context_data.push(getCharFromInt(context_data_val));
411
+ context_data_val = 0;
412
+ }
413
+ else {
414
+ context_data_position++;
415
+ }
416
+ }
417
+ value = context_w.charCodeAt(0);
418
+ for (i = 0; i < 8; i++) {
419
+ context_data_val = (context_data_val << 1) | (value & 1);
420
+ if (context_data_position == bitsPerChar - 1) {
421
+ context_data_position = 0;
422
+ context_data.push(getCharFromInt(context_data_val));
423
+ context_data_val = 0;
424
+ }
425
+ else {
426
+ context_data_position++;
427
+ }
428
+ value = value >> 1;
429
+ }
430
+ }
431
+ else {
432
+ value = 1;
433
+ for (i = 0; i < context_numBits; i++) {
434
+ context_data_val = (context_data_val << 1) | value;
435
+ if (context_data_position == bitsPerChar - 1) {
436
+ context_data_position = 0;
437
+ context_data.push(getCharFromInt(context_data_val));
438
+ context_data_val = 0;
439
+ }
440
+ else {
441
+ context_data_position++;
442
+ }
443
+ value = 0;
444
+ }
445
+ value = context_w.charCodeAt(0);
446
+ for (i = 0; i < 16; i++) {
447
+ context_data_val = (context_data_val << 1) | (value & 1);
448
+ if (context_data_position == bitsPerChar - 1) {
449
+ context_data_position = 0;
450
+ context_data.push(getCharFromInt(context_data_val));
451
+ context_data_val = 0;
452
+ }
453
+ else {
454
+ context_data_position++;
455
+ }
456
+ value = value >> 1;
457
+ }
458
+ }
459
+ context_enlargeIn--;
460
+ if (context_enlargeIn == 0) {
461
+ context_enlargeIn = Math.pow(2, context_numBits);
462
+ context_numBits++;
463
+ }
464
+ delete context_dictionaryToCreate[context_w];
465
+ }
466
+ else {
467
+ value = context_dictionary[context_w];
468
+ for (i = 0; i < context_numBits; i++) {
469
+ context_data_val = (context_data_val << 1) | (value & 1);
470
+ if (context_data_position == bitsPerChar - 1) {
471
+ context_data_position = 0;
472
+ context_data.push(getCharFromInt(context_data_val));
473
+ context_data_val = 0;
474
+ }
475
+ else {
476
+ context_data_position++;
477
+ }
478
+ value = value >> 1;
479
+ }
480
+ }
481
+ context_enlargeIn--;
482
+ if (context_enlargeIn == 0) {
483
+ context_enlargeIn = Math.pow(2, context_numBits);
484
+ context_numBits++;
485
+ }
486
+ }
487
+ // Mark the end of the stream
488
+ value = 2;
489
+ for (i = 0; i < context_numBits; i++) {
490
+ context_data_val = (context_data_val << 1) | (value & 1);
491
+ if (context_data_position == bitsPerChar - 1) {
492
+ context_data_position = 0;
493
+ context_data.push(getCharFromInt(context_data_val));
494
+ context_data_val = 0;
495
+ }
496
+ else {
497
+ context_data_position++;
498
+ }
499
+ value = value >> 1;
500
+ }
501
+ // Flush the last char
502
+ while (true) {
503
+ context_data_val = context_data_val << 1;
504
+ if (context_data_position == bitsPerChar - 1) {
505
+ context_data.push(getCharFromInt(context_data_val));
506
+ break;
507
+ }
508
+ else {
509
+ context_data_position++;
510
+ }
511
+ }
512
+ return context_data.join('');
513
+ },
514
+ decompress: function (compressed) {
515
+ if (compressed == null) {
516
+ return '';
517
+ }
518
+ if (compressed == '') {
519
+ return null;
520
+ }
521
+ return LZString._decompress(compressed.length, 32768, function (index) {
522
+ return compressed.charCodeAt(index);
523
+ });
524
+ },
525
+ _decompress: function (length, resetValue, getNextValue) {
526
+ var dictionary = [], result = [], data = { val: getNextValue(0), position: resetValue, index: 1 };
527
+ var enlargeIn = 4, dictSize = 4, numBits = 3, entry = '', i, w, bits, resb, maxpower, power, c;
528
+ for (i = 0; i < 3; i += 1) {
529
+ dictionary[i] = i;
530
+ }
531
+ bits = 0;
532
+ maxpower = Math.pow(2, 2);
533
+ power = 1;
534
+ while (power != maxpower) {
535
+ resb = data.val & data.position;
536
+ data.position >>= 1;
537
+ if (data.position == 0) {
538
+ data.position = resetValue;
539
+ data.val = getNextValue(data.index++);
540
+ }
541
+ bits |= (resb > 0 ? 1 : 0) * power;
542
+ power <<= 1;
543
+ }
544
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
545
+ switch ((bits)) {
546
+ case 0:
547
+ bits = 0;
548
+ maxpower = Math.pow(2, 8);
549
+ power = 1;
550
+ while (power != maxpower) {
551
+ resb = data.val & data.position;
552
+ data.position >>= 1;
553
+ if (data.position == 0) {
554
+ data.position = resetValue;
555
+ data.val = getNextValue(data.index++);
556
+ }
557
+ bits |= (resb > 0 ? 1 : 0) * power;
558
+ power <<= 1;
559
+ }
560
+ c = f(bits);
561
+ break;
562
+ case 1:
563
+ bits = 0;
564
+ maxpower = Math.pow(2, 16);
565
+ power = 1;
566
+ while (power != maxpower) {
567
+ resb = data.val & data.position;
568
+ data.position >>= 1;
569
+ if (data.position == 0) {
570
+ data.position = resetValue;
571
+ data.val = getNextValue(data.index++);
572
+ }
573
+ bits |= (resb > 0 ? 1 : 0) * power;
574
+ power <<= 1;
575
+ }
576
+ c = f(bits);
577
+ break;
578
+ case 2:
579
+ return '';
580
+ }
581
+ dictionary[3] = c;
582
+ w = c;
583
+ result.push(c);
584
+ while (true) {
585
+ if (data.index > length) {
586
+ return '';
587
+ }
588
+ bits = 0;
589
+ maxpower = Math.pow(2, numBits);
590
+ power = 1;
591
+ while (power != maxpower) {
592
+ resb = data.val & data.position;
593
+ data.position >>= 1;
594
+ if (data.position == 0) {
595
+ data.position = resetValue;
596
+ data.val = getNextValue(data.index++);
597
+ }
598
+ bits |= (resb > 0 ? 1 : 0) * power;
599
+ power <<= 1;
600
+ }
601
+ switch ((c = bits)) {
602
+ case 0:
603
+ bits = 0;
604
+ maxpower = Math.pow(2, 8);
605
+ power = 1;
606
+ while (power != maxpower) {
607
+ resb = data.val & data.position;
608
+ data.position >>= 1;
609
+ if (data.position == 0) {
610
+ data.position = resetValue;
611
+ data.val = getNextValue(data.index++);
612
+ }
613
+ bits |= (resb > 0 ? 1 : 0) * power;
614
+ power <<= 1;
615
+ }
616
+ dictionary[dictSize++] = f(bits);
617
+ c = dictSize - 1;
618
+ enlargeIn--;
619
+ break;
620
+ case 1:
621
+ bits = 0;
622
+ maxpower = Math.pow(2, 16);
623
+ power = 1;
624
+ while (power != maxpower) {
625
+ resb = data.val & data.position;
626
+ data.position >>= 1;
627
+ if (data.position == 0) {
628
+ data.position = resetValue;
629
+ data.val = getNextValue(data.index++);
630
+ }
631
+ bits |= (resb > 0 ? 1 : 0) * power;
632
+ power <<= 1;
633
+ }
634
+ dictionary[dictSize++] = f(bits);
635
+ c = dictSize - 1;
636
+ enlargeIn--;
637
+ break;
638
+ case 2:
639
+ return result.join('');
640
+ }
641
+ if (enlargeIn == 0) {
642
+ enlargeIn = Math.pow(2, numBits);
643
+ numBits++;
644
+ }
645
+ if (dictionary[c]) {
646
+ entry = dictionary[c];
647
+ }
648
+ else {
649
+ if (c === dictSize) {
650
+ entry = w + w.charAt(0);
651
+ }
652
+ else {
653
+ return null;
654
+ }
655
+ }
656
+ result.push(entry);
657
+ // Add w+entry[0] to the dictionary.
658
+ dictionary[dictSize++] = w + entry.charAt(0);
659
+ enlargeIn--;
660
+ w = entry;
661
+ if (enlargeIn == 0) {
662
+ enlargeIn = Math.pow(2, numBits);
663
+ numBits++;
664
+ }
665
+ }
666
+ },
667
+ };
668
+
669
+ var SimpleEventEmitter = /** @class */ (function () {
670
+ function SimpleEventEmitter() {
671
+ this.events = {};
672
+ this.events = {};
673
+ }
674
+ SimpleEventEmitter.prototype.on = function (event, listener) {
675
+ var _this = this;
676
+ if (!this.events[event]) {
677
+ this.events[event] = [];
678
+ }
679
+ this.events[event].push(listener);
680
+ return function () {
681
+ _this.events[event] = _this.events[event].filter(function (x) { return x !== listener; });
682
+ };
683
+ };
684
+ SimpleEventEmitter.prototype.emit = function (event, payload) {
685
+ if (!this.events[event]) {
686
+ return;
687
+ }
688
+ for (var _i = 0, _a = this.events[event]; _i < _a.length; _i++) {
689
+ var listener = _a[_i];
690
+ listener(payload);
691
+ }
692
+ };
693
+ return SimpleEventEmitter;
694
+ }());
695
+
696
+ var PostHogCore = /** @class */ (function () {
697
+ function PostHogCore(apiKey, options) {
698
+ var _this = this;
699
+ var _a, _b, _c, _d, _e, _f;
700
+ this.flagCallReported = {};
701
+ // internal
702
+ this._events = new SimpleEventEmitter();
703
+ assert(apiKey, "You must pass your PostHog project's api key.");
704
+ this.apiKey = apiKey;
705
+ this.host = removeTrailingSlash((options === null || options === void 0 ? void 0 : options.host) || 'https://app.posthog.com');
706
+ this.flushAt = (options === null || options === void 0 ? void 0 : options.flushAt) ? Math.max(options === null || options === void 0 ? void 0 : options.flushAt, 1) : 20;
707
+ this.flushInterval = (_a = options === null || options === void 0 ? void 0 : options.flushInterval) !== null && _a !== void 0 ? _a : 10000;
708
+ this.captureMode = (options === null || options === void 0 ? void 0 : options.captureMode) || 'form';
709
+ this.sendFeatureFlagEvent = (_b = options === null || options === void 0 ? void 0 : options.sendFeatureFlagEvent) !== null && _b !== void 0 ? _b : true;
710
+ this._decidePollInterval = Math.max(0, (_c = options === null || options === void 0 ? void 0 : options.decidePollInterval) !== null && _c !== void 0 ? _c : 30000);
711
+ // If enable is explicitly set to false we override the optout
712
+ this._optoutOverride = (options === null || options === void 0 ? void 0 : options.enable) === false;
713
+ this._retryOptions = {
714
+ retryCount: (_d = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _d !== void 0 ? _d : 3,
715
+ retryDelay: (_e = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _e !== void 0 ? _e : 3000,
716
+ };
717
+ this._sessionExpirationTimeSeconds = (_f = options === null || options === void 0 ? void 0 : options.sessionExpirationTimeSeconds) !== null && _f !== void 0 ? _f : 1800; // 30 minutes
718
+ // NOTE: It is important we don't initiate anything in the constructor as some async IO may still be underway on the parent
719
+ if ((options === null || options === void 0 ? void 0 : options.preloadFeatureFlags) !== false) {
720
+ safeSetTimeout(function () {
721
+ void _this.reloadFeatureFlagsAsync();
722
+ }, 1);
723
+ }
724
+ }
725
+ PostHogCore.prototype.getCommonEventProperties = function () {
726
+ var featureFlags = this.getFeatureFlags();
727
+ return {
728
+ $lib: this.getLibraryId(),
729
+ $lib_version: this.getLibraryVersion(),
730
+ $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined,
731
+ $enabled_feature_flags: featureFlags,
732
+ };
733
+ };
734
+ Object.defineProperty(PostHogCore.prototype, "props", {
735
+ // NOTE: Props are lazy loaded from localstorage hence the complex getter setter logic
736
+ get: function () {
737
+ if (!this._props) {
738
+ this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
739
+ }
740
+ return this._props || {};
741
+ },
742
+ set: function (val) {
743
+ this._props = val;
744
+ },
745
+ enumerable: false,
746
+ configurable: true
747
+ });
748
+ Object.defineProperty(PostHogCore.prototype, "optedOut", {
749
+ get: function () {
750
+ var _a, _b;
751
+ return (_b = (_a = this.getPersistedProperty(PostHogPersistedProperty.OptedOut)) !== null && _a !== void 0 ? _a : this._optoutOverride) !== null && _b !== void 0 ? _b : false;
752
+ },
753
+ enumerable: false,
754
+ configurable: true
755
+ });
756
+ PostHogCore.prototype.optIn = function () {
757
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
758
+ };
759
+ PostHogCore.prototype.optOut = function () {
760
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
761
+ };
762
+ PostHogCore.prototype.on = function (event, cb) {
763
+ return this._events.on(event, cb);
764
+ };
765
+ PostHogCore.prototype.reset = function () {
766
+ for (var key in PostHogPersistedProperty) {
767
+ this.setPersistedProperty(PostHogPersistedProperty[key], null);
768
+ }
769
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, generateUUID(globalThis));
770
+ };
771
+ PostHogCore.prototype.buildPayload = function (payload) {
772
+ return {
773
+ distinct_id: payload.distinct_id || this.getDistinctId(),
774
+ event: payload.event,
775
+ properties: __assign(__assign(__assign(__assign({}, this.props), (payload.properties || {})), this.getCommonEventProperties()), { $session_id: this.getSessionId() }),
776
+ };
777
+ };
778
+ PostHogCore.prototype.getSessionId = function () {
779
+ var sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
780
+ var sessionTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
781
+ if (!sessionId || Date.now() - sessionTimestamp > this._sessionExpirationTimeSeconds * 1000) {
782
+ sessionId = generateUUID(globalThis);
783
+ this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);
784
+ }
785
+ this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, Date.now());
786
+ return sessionId;
787
+ };
788
+ PostHogCore.prototype.getDistinctId = function () {
789
+ var distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);
790
+ if (!distinctId) {
791
+ distinctId = generateUUID(globalThis);
792
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
793
+ }
794
+ return distinctId;
795
+ };
796
+ PostHogCore.prototype.register = function (properties) {
797
+ this.props = __assign(__assign({}, this.props), properties);
798
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
799
+ };
800
+ PostHogCore.prototype.unregister = function (property) {
801
+ delete this.props[property];
802
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
803
+ };
804
+ /***
805
+ *** TRACKING
806
+ ***/
807
+ PostHogCore.prototype.identify = function (distinctId, properties) {
808
+ distinctId = distinctId || this.getDistinctId();
809
+ if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
810
+ this.groups(properties.$groups);
811
+ }
812
+ var payload = __assign(__assign({}, this.buildPayload({
813
+ distinct_id: distinctId,
814
+ event: '$identify',
815
+ properties: __assign(__assign({}, (properties || {})), { $anon_distinct_id: this.getDistinctId() }),
816
+ })), { $set: properties });
817
+ if (distinctId !== this.getDistinctId()) {
818
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
819
+ }
820
+ this.enqueue('identify', payload);
821
+ return this;
822
+ };
823
+ PostHogCore.prototype.capture = function (event, properties) {
824
+ // NOTE: Legacy nodejs implementation uses groups
825
+ if (properties && properties['groups']) {
826
+ properties.$groups = properties.groups;
827
+ delete properties.groups;
828
+ }
829
+ if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
830
+ this.groups(properties.$groups);
831
+ }
832
+ var payload = this.buildPayload({ event: event, properties: properties });
833
+ this.enqueue('capture', payload);
834
+ return this;
835
+ };
836
+ PostHogCore.prototype.alias = function (alias) {
837
+ var distinctId = this.getDistinctId();
838
+ var payload = this.buildPayload({
839
+ event: '$create_alias',
840
+ properties: {
841
+ distinct_id: distinctId,
842
+ alias: alias,
843
+ },
844
+ });
845
+ this.enqueue('alias', payload);
846
+ return this;
847
+ };
848
+ PostHogCore.prototype.autocapture = function (eventType, elements, properties) {
849
+ if (properties === void 0) { properties = {}; }
850
+ var payload = this.buildPayload({
851
+ event: '$autocapture',
852
+ properties: __assign(__assign({}, properties), { $event_type: eventType, $elements: elements }),
853
+ });
854
+ this.enqueue('autocapture', payload);
855
+ return this;
856
+ };
857
+ /***
858
+ *** GROUPS
859
+ ***/
860
+ PostHogCore.prototype.groups = function (groups) {
861
+ // Get persisted groups
862
+ var existingGroups = this.props.$groups || {};
863
+ // NOTE: Should we do the same for groups listed in identify / capture?
864
+ this.register({
865
+ $groups: __assign(__assign({}, existingGroups), groups),
866
+ });
867
+ if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; }) && this._decideResponsePromise) {
868
+ void this.reloadFeatureFlagsAsync();
869
+ }
870
+ return this;
871
+ };
872
+ PostHogCore.prototype.group = function (groupType, groupKey, groupProperties) {
873
+ var _a;
874
+ this.groups((_a = {},
875
+ _a[groupType] = groupKey,
876
+ _a));
877
+ if (groupProperties) {
878
+ this.groupIdentify(groupType, groupKey, groupProperties);
879
+ }
880
+ return this;
881
+ };
882
+ PostHogCore.prototype.groupIdentify = function (groupType, groupKey, groupProperties) {
883
+ var payload = {
884
+ event: '$groupidentify',
885
+ distinctId: "$".concat(groupType, "_").concat(groupKey),
886
+ properties: __assign({ $group_type: groupType, $group_key: groupKey, $group_set: groupProperties || {} }, this.getCommonEventProperties()),
887
+ };
888
+ this.enqueue('capture', payload);
889
+ return this;
890
+ };
891
+ /***
892
+ *** FEATURE FLAGS
893
+ ***/
894
+ PostHogCore.prototype.decideAsync = function () {
895
+ if (this._decideResponsePromise) {
896
+ return this._decideResponsePromise;
897
+ }
898
+ return this._decideAsync();
899
+ };
900
+ PostHogCore.prototype._decideAsync = function () {
901
+ return __awaiter(this, void 0, void 0, function () {
902
+ var url, distinctId, groups, fetchOptions;
903
+ var _this = this;
904
+ return __generator(this, function (_a) {
905
+ url = "".concat(this.host, "/decide/?v=2");
906
+ distinctId = this.getDistinctId();
907
+ groups = this.props.$groups || {};
908
+ fetchOptions = {
909
+ method: 'POST',
910
+ headers: { 'Content-Type': 'application/json' },
911
+ body: JSON.stringify({ groups: groups, distinct_id: distinctId, token: this.apiKey }),
912
+ };
913
+ this._decideResponsePromise = this.fetchWithRetry(url, fetchOptions)
914
+ .then(function (r) { return r.json(); })
915
+ .then(function (res) {
916
+ if (res.featureFlags) {
917
+ _this.setPersistedProperty(PostHogPersistedProperty.FeatureFlags, res.featureFlags);
918
+ }
919
+ _this._events.emit('featureflags', res.featureFlags);
920
+ return res;
921
+ });
922
+ return [2 /*return*/, this._decideResponsePromise];
923
+ });
924
+ });
925
+ };
926
+ PostHogCore.prototype.getFeatureFlag = function (key, defaultResult) {
927
+ var _a;
928
+ if (defaultResult === void 0) { defaultResult = false; }
929
+ var featureFlags = this.getFeatureFlags();
930
+ if (!featureFlags) {
931
+ // If we haven't loaded flags yet we respond undefined to indicate this
932
+ return undefined;
933
+ }
934
+ if (this.sendFeatureFlagEvent && !this.flagCallReported[key]) {
935
+ this.flagCallReported[key] = true;
936
+ this.capture('$feature_flag_called', {
937
+ $feature_flag: key,
938
+ $feature_flag_response: featureFlags[key],
939
+ });
940
+ }
941
+ // If we have flags we either return the value (true or string) or the defaultResult
942
+ return (_a = featureFlags[key]) !== null && _a !== void 0 ? _a : defaultResult;
943
+ };
944
+ PostHogCore.prototype.getFeatureFlags = function () {
945
+ var flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
946
+ var overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
947
+ if (!overriddenFlags) {
948
+ return flags;
949
+ }
950
+ flags = flags || {};
951
+ for (var key in overriddenFlags) {
952
+ if (!overriddenFlags[key]) {
953
+ delete flags[key];
954
+ }
955
+ else {
956
+ flags[key] = overriddenFlags[key];
957
+ }
958
+ }
959
+ return flags;
960
+ };
961
+ PostHogCore.prototype.isFeatureEnabled = function (key, defaultResult) {
962
+ var _a;
963
+ if (defaultResult === void 0) { defaultResult = false; }
964
+ var flag = (_a = this.getFeatureFlag(key, defaultResult)) !== null && _a !== void 0 ? _a : defaultResult;
965
+ return !!flag;
966
+ };
967
+ PostHogCore.prototype.reloadFeatureFlagsAsync = function () {
968
+ return __awaiter(this, void 0, void 0, function () {
969
+ var _this = this;
970
+ return __generator(this, function (_a) {
971
+ switch (_a.label) {
972
+ case 0:
973
+ clearTimeout(this._decideTimer);
974
+ if (this._decidePollInterval) {
975
+ this._decideTimer = safeSetTimeout(function () { return _this.reloadFeatureFlagsAsync(); }, this._decidePollInterval);
976
+ }
977
+ this._decideResponsePromise = undefined;
978
+ return [4 /*yield*/, this.decideAsync()];
979
+ case 1: return [2 /*return*/, (_a.sent()).featureFlags];
980
+ }
981
+ });
982
+ });
983
+ };
984
+ // When listening to feature flags polling is active
985
+ PostHogCore.prototype.onFeatureFlags = function (cb) {
986
+ var _this = this;
987
+ if (!this._decideTimer) {
988
+ void this.reloadFeatureFlagsAsync();
989
+ }
990
+ return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
991
+ var flags;
992
+ return __generator(this, function (_a) {
993
+ flags = this.getFeatureFlags();
994
+ if (flags) {
995
+ cb(flags);
996
+ }
997
+ return [2 /*return*/];
998
+ });
999
+ }); });
1000
+ };
1001
+ PostHogCore.prototype.overrideFeatureFlag = function (flags) {
1002
+ if (flags === null) {
1003
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);
1004
+ }
1005
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1006
+ };
1007
+ /***
1008
+ *** QUEUEING AND FLUSHING
1009
+ ***/
1010
+ PostHogCore.prototype.enqueue = function (type, _message) {
1011
+ var _this = this;
1012
+ if (this.optedOut) {
1013
+ return;
1014
+ }
1015
+ var message = __assign(__assign({}, _message), { type: type, library: this.getLibraryId(), library_version: this.getLibraryVersion(), timestamp: _message.timestamp ? _message.timestamp : currentISOTime() });
1016
+ if (message.distinctId) {
1017
+ message.distinct_id = message.distinctId;
1018
+ delete message.distinctId;
1019
+ }
1020
+ var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1021
+ queue.push({ message: message });
1022
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1023
+ this._events.emit(type, message);
1024
+ // Flush queued events if we meet the flushAt length
1025
+ if (queue.length >= this.flushAt) {
1026
+ this.flush();
1027
+ }
1028
+ if (this.flushInterval && !this._flushTimer) {
1029
+ this._flushTimer = safeSetTimeout(function () { return _this.flush(); }, this.flushInterval);
1030
+ }
1031
+ };
1032
+ PostHogCore.prototype.flushAsync = function () {
1033
+ var _this = this;
1034
+ return new Promise(function (resolve, reject) {
1035
+ _this.flush(function (err, data) { return (err ? reject(err) : resolve(data)); });
1036
+ });
1037
+ };
1038
+ PostHogCore.prototype.flush = function (callback) {
1039
+ var _this = this;
1040
+ if (this.optedOut) {
1041
+ return callback && safeSetTimeout(callback, 0);
1042
+ }
1043
+ if (this._flushTimer) {
1044
+ clearTimeout(this._flushTimer);
1045
+ this._flushTimer = null;
1046
+ }
1047
+ var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1048
+ if (!queue.length) {
1049
+ return callback && safeSetTimeout(callback, 0);
1050
+ }
1051
+ var items = queue.splice(0, this.flushAt);
1052
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1053
+ var messages = items.map(function (item) { return item.message; });
1054
+ var data = {
1055
+ api_key: this.apiKey,
1056
+ batch: messages,
1057
+ sent_at: currentISOTime(),
1058
+ };
1059
+ var done = function (err) {
1060
+ callback === null || callback === void 0 ? void 0 : callback(err, messages);
1061
+ _this._events.emit('flush', messages);
1062
+ };
1063
+ // Don't set the user agent if we're not on a browser. The latest spec allows
1064
+ // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1065
+ // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1066
+ // but browsers such as Chrome and Safari have not caught up.
1067
+ this.getCustomUserAgent();
1068
+ var payload = JSON.stringify(data);
1069
+ var url = this.captureMode === 'form'
1070
+ ? "".concat(this.host, "/e/?ip=1&_=").concat(currentTimestamp(), "&v=").concat(this.getLibraryVersion())
1071
+ : "".concat(this.host, "/batch/");
1072
+ var fetchOptions = this.captureMode === 'form'
1073
+ ? {
1074
+ method: 'POST',
1075
+ mode: 'no-cors',
1076
+ credentials: 'omit',
1077
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1078
+ body: "data=".concat(encodeURIComponent(LZString.compressToBase64(payload)), "&compression=lz64"),
1079
+ }
1080
+ : {
1081
+ method: 'POST',
1082
+ headers: { 'Content-Type': 'application/json' },
1083
+ body: payload,
1084
+ };
1085
+ this.fetchWithRetry(url, fetchOptions)
1086
+ .then(function () { return done(); })
1087
+ .catch(function (err) {
1088
+ if (err.response) {
1089
+ var error = new Error(err.response.statusText);
1090
+ return done(error);
1091
+ }
1092
+ done(err);
1093
+ });
1094
+ };
1095
+ PostHogCore.prototype.fetchWithRetry = function (url, options, retryOptions) {
1096
+ return __awaiter(this, void 0, void 0, function () {
1097
+ var _this = this;
1098
+ return __generator(this, function (_a) {
1099
+ return [2 /*return*/, retriable(function () { return _this.fetch(url, options); }, retryOptions || this._retryOptions)];
1100
+ });
1101
+ });
1102
+ };
1103
+ PostHogCore.prototype.shutdownAsync = function () {
1104
+ return __awaiter(this, void 0, void 0, function () {
1105
+ return __generator(this, function (_a) {
1106
+ switch (_a.label) {
1107
+ case 0:
1108
+ clearTimeout(this._decideTimer);
1109
+ clearTimeout(this._flushTimer);
1110
+ return [4 /*yield*/, this.flushAsync()];
1111
+ case 1:
1112
+ _a.sent();
1113
+ return [2 /*return*/];
1114
+ }
1115
+ });
1116
+ });
1117
+ };
1118
+ PostHogCore.prototype.shutdown = function () {
1119
+ void this.shutdownAsync();
1120
+ };
1121
+ return PostHogCore;
1122
+ }());
1123
+
1124
+ var PostHog =
1125
+ /** @class */
1126
+ function (_super) {
1127
+ __extends(PostHog, _super);
1128
+
1129
+ function PostHog(apiKey, options) {
1130
+ if (options === void 0) {
1131
+ options = {};
1132
+ }
1133
+
1134
+ var _this = this;
1135
+
1136
+ options.captureMode = (options === null || options === void 0 ? void 0 : options.captureMode) || 'json';
1137
+ options.preloadFeatureFlags = false; // Don't preload as this makes no sense without a distinctId
1138
+
1139
+ _this = _super.call(this, apiKey, options) || this;
1140
+ _this._memoryStorage = {};
1141
+ return _this;
1142
+ }
1143
+
1144
+ PostHog.prototype.getPersistedProperty = function (key) {
1145
+ return this._memoryStorage[key];
1146
+ };
1147
+
1148
+ PostHog.prototype.setPersistedProperty = function (key, value) {
1149
+ this._memoryStorage[key] = value !== null ? value : undefined;
1150
+ };
1151
+
1152
+ PostHog.prototype.getSessionId = function () {
1153
+ // Sessions don't make sense for Node
1154
+ return undefined;
1155
+ };
1156
+
1157
+ PostHog.prototype.fetch = function (url, options) {
1158
+ return undici__default["default"].fetch(url, options);
1159
+ };
1160
+
1161
+ PostHog.prototype.getLibraryId = function () {
1162
+ return 'posthog-node';
1163
+ };
1164
+
1165
+ PostHog.prototype.getLibraryVersion = function () {
1166
+ return version;
1167
+ };
1168
+
1169
+ PostHog.prototype.getCustomUserAgent = function () {
1170
+ return "posthog-node/".concat(version);
1171
+ };
1172
+
1173
+ return PostHog;
1174
+ }(PostHogCore); // The actual exported Nodejs API.
1175
+
1176
+
1177
+ var PostHogGlobal =
1178
+ /** @class */
1179
+ function () {
1180
+ function PostHogGlobal(apiKey, options) {
1181
+ if (options === void 0) {
1182
+ options = {};
1183
+ }
1184
+
1185
+ options.decidePollInterval = 0; // Forcefully set to 0 so we don't auto-reload
1186
+
1187
+ this._sharedClient = new PostHog(apiKey, options);
1188
+ }
1189
+
1190
+ PostHogGlobal.prototype.reInit = function (distinctId) {
1191
+ // Remove all state except the queue
1192
+ var queue = this._sharedClient.getPersistedProperty(PostHogPersistedProperty.Queue);
1193
+
1194
+ this._sharedClient.reset();
1195
+
1196
+ this._sharedClient.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1197
+
1198
+ this._sharedClient.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
1199
+ };
1200
+
1201
+ PostHogGlobal.prototype.enable = function () {
1202
+ return this._sharedClient.optIn();
1203
+ };
1204
+
1205
+ PostHogGlobal.prototype.disable = function () {
1206
+ return this._sharedClient.optOut();
1207
+ };
1208
+
1209
+ PostHogGlobal.prototype.capture = function (_a) {
1210
+ var distinctId = _a.distinctId,
1211
+ event = _a.event,
1212
+ properties = _a.properties,
1213
+ groups = _a.groups;
1214
+ this.reInit(distinctId);
1215
+
1216
+ if (groups) {
1217
+ this._sharedClient.groups(groups);
1218
+ }
1219
+
1220
+ this._sharedClient.capture(event, properties);
1221
+ };
1222
+
1223
+ PostHogGlobal.prototype.identify = function (_a) {
1224
+ var distinctId = _a.distinctId,
1225
+ properties = _a.properties;
1226
+ this.reInit(distinctId);
1227
+
1228
+ this._sharedClient.identify(distinctId, properties);
1229
+ };
1230
+
1231
+ PostHogGlobal.prototype.alias = function (data) {
1232
+ this.reInit(data.distinctId);
1233
+
1234
+ this._sharedClient.alias(data.alias);
1235
+ };
1236
+
1237
+ PostHogGlobal.prototype.getFeatureFlag = function (key, distinctId, groups) {
1238
+ return __awaiter(this, void 0, void 0, function () {
1239
+ return __generator(this, function (_a) {
1240
+ switch (_a.label) {
1241
+ case 0:
1242
+ this.reInit(distinctId);
1243
+
1244
+ if (groups) {
1245
+ this._sharedClient.groups(groups);
1246
+ }
1247
+
1248
+ return [4
1249
+ /*yield*/
1250
+ , this._sharedClient.reloadFeatureFlagsAsync()];
1251
+
1252
+ case 1:
1253
+ _a.sent();
1254
+
1255
+ return [2
1256
+ /*return*/
1257
+ , this._sharedClient.getFeatureFlag(key)];
1258
+ }
1259
+ });
1260
+ });
1261
+ };
1262
+
1263
+ PostHogGlobal.prototype.isFeatureEnabled = function (key, distinctId, defaultResult, groups) {
1264
+ return __awaiter(this, void 0, void 0, function () {
1265
+ var feat;
1266
+ return __generator(this, function (_a) {
1267
+ feat = this.getFeatureFlag(key, distinctId, groups);
1268
+ return [2
1269
+ /*return*/
1270
+ , !!feat || defaultResult || false];
1271
+ });
1272
+ });
1273
+ };
1274
+
1275
+ PostHogGlobal.prototype.groupIdentify = function (_a) {
1276
+ var groupType = _a.groupType,
1277
+ groupKey = _a.groupKey,
1278
+ properties = _a.properties;
1279
+
1280
+ this._sharedClient.groupIdentify(groupType, groupKey, properties);
1281
+ };
1282
+
1283
+ PostHogGlobal.prototype.reloadFeatureFlags = function () {
1284
+ throw new Error('Method not implemented.');
1285
+ };
1286
+
1287
+ PostHogGlobal.prototype.shutdown = function () {
1288
+ void this._sharedClient.shutdownAsync();
1289
+ };
1290
+
1291
+ PostHogGlobal.prototype.shutdownAsync = function () {
1292
+ return this._sharedClient.shutdownAsync();
1293
+ };
1294
+
1295
+ return PostHogGlobal;
1296
+ }();
1297
+
1298
+ exports.PostHogGlobal = PostHogGlobal;
1299
+ exports["default"] = PostHogGlobal;
1300
+ //# sourceMappingURL=index.cjs.js.map