posthog-js-lite 2.6.2 → 3.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs.js CHANGED
@@ -2,148 +2,6 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- /******************************************************************************
6
- Copyright (c) Microsoft Corporation.
7
-
8
- Permission to use, copy, modify, and/or distribute this software for any
9
- purpose with or without fee is hereby granted.
10
-
11
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
- PERFORMANCE OF THIS SOFTWARE.
18
- ***************************************************************************** */
19
- /* global Reflect, Promise */
20
- var extendStatics = function (d, b) {
21
- extendStatics = Object.setPrototypeOf ||
22
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23
- function (d, b) { for (var p in b)
24
- if (Object.prototype.hasOwnProperty.call(b, p))
25
- d[p] = b[p]; };
26
- return extendStatics(d, b);
27
- };
28
- function __extends(d, b) {
29
- if (typeof b !== "function" && b !== null)
30
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
31
- extendStatics(d, b);
32
- function __() { this.constructor = d; }
33
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34
- }
35
- var __assign = function () {
36
- __assign = Object.assign || function __assign(t) {
37
- for (var s, i = 1, n = arguments.length; i < n; i++) {
38
- s = arguments[i];
39
- for (var p in s)
40
- if (Object.prototype.hasOwnProperty.call(s, p))
41
- t[p] = s[p];
42
- }
43
- return t;
44
- };
45
- return __assign.apply(this, arguments);
46
- };
47
- function __awaiter(thisArg, _arguments, P, generator) {
48
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
49
- return new (P || (P = Promise))(function (resolve, reject) {
50
- function fulfilled(value) { try {
51
- step(generator.next(value));
52
- }
53
- catch (e) {
54
- reject(e);
55
- } }
56
- function rejected(value) { try {
57
- step(generator["throw"](value));
58
- }
59
- catch (e) {
60
- reject(e);
61
- } }
62
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
63
- step((generator = generator.apply(thisArg, _arguments || [])).next());
64
- });
65
- }
66
- function __generator(thisArg, body) {
67
- var _ = { label: 0, sent: function () { if (t[0] & 1)
68
- throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
69
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
70
- function verb(n) { return function (v) { return step([n, v]); }; }
71
- function step(op) {
72
- if (f)
73
- throw new TypeError("Generator is already executing.");
74
- while (_)
75
- try {
76
- 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)
77
- return t;
78
- if (y = 0, t)
79
- op = [op[0] & 2, t.value];
80
- switch (op[0]) {
81
- case 0:
82
- case 1:
83
- t = op;
84
- break;
85
- case 4:
86
- _.label++;
87
- return { value: op[1], done: false };
88
- case 5:
89
- _.label++;
90
- y = op[1];
91
- op = [0];
92
- continue;
93
- case 7:
94
- op = _.ops.pop();
95
- _.trys.pop();
96
- continue;
97
- default:
98
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
99
- _ = 0;
100
- continue;
101
- }
102
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
103
- _.label = op[1];
104
- break;
105
- }
106
- if (op[0] === 6 && _.label < t[1]) {
107
- _.label = t[1];
108
- t = op;
109
- break;
110
- }
111
- if (t && _.label < t[2]) {
112
- _.label = t[2];
113
- _.ops.push(op);
114
- break;
115
- }
116
- if (t[2])
117
- _.ops.pop();
118
- _.trys.pop();
119
- continue;
120
- }
121
- op = body.call(thisArg, _);
122
- }
123
- catch (e) {
124
- op = [6, e];
125
- y = 0;
126
- }
127
- finally {
128
- f = t = 0;
129
- }
130
- if (op[0] & 5)
131
- throw op[1];
132
- return { value: op[0] ? op[1] : void 0, done: true };
133
- }
134
- }
135
- function __spreadArray(to, from, pack) {
136
- if (pack || arguments.length === 2)
137
- for (var i = 0, l = from.length, ar; i < l; i++) {
138
- if (ar || !(i in from)) {
139
- if (!ar)
140
- ar = Array.prototype.slice.call(from, 0, i);
141
- ar[i] = from[i];
142
- }
143
- }
144
- return to.concat(ar || Array.prototype.slice.call(from));
145
- }
146
-
147
5
  var PostHogPersistedProperty;
148
6
  (function (PostHogPersistedProperty) {
149
7
  PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
@@ -168,48 +26,27 @@ function assert(truthyValue, message) {
168
26
  }
169
27
  }
170
28
  function removeTrailingSlash(url) {
171
- return url === null || url === void 0 ? void 0 : url.replace(/\/+$/, '');
29
+ return url?.replace(/\/+$/, '');
172
30
  }
173
- function retriable(fn, props) {
174
- if (props === void 0) { props = {}; }
175
- return __awaiter(this, void 0, void 0, function () {
176
- var _a, retryCount, _b, retryDelay, _c, retryCheck, lastError, i, res, e_1;
177
- return __generator(this, function (_d) {
178
- switch (_d.label) {
179
- case 0:
180
- _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;
181
- lastError = null;
182
- i = 0;
183
- _d.label = 1;
184
- case 1:
185
- if (!(i < retryCount + 1)) return [3 /*break*/, 7];
186
- if (!(i > 0)) return [3 /*break*/, 3];
187
- // don't wait when it's the last try
188
- return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, retryDelay); })];
189
- case 2:
190
- // don't wait when it's the last try
191
- _d.sent();
192
- _d.label = 3;
193
- case 3:
194
- _d.trys.push([3, 5, , 6]);
195
- return [4 /*yield*/, fn()];
196
- case 4:
197
- res = _d.sent();
198
- return [2 /*return*/, res];
199
- case 5:
200
- e_1 = _d.sent();
201
- lastError = e_1;
202
- if (!retryCheck(e_1)) {
203
- throw e_1;
204
- }
205
- return [3 /*break*/, 6];
206
- case 6:
207
- i++;
208
- return [3 /*break*/, 1];
209
- case 7: throw lastError;
31
+ async function retriable(fn, props) {
32
+ let lastError = null;
33
+ for (let i = 0; i < props.retryCount + 1; i++) {
34
+ if (i > 0) {
35
+ // don't wait when it's the last try
36
+ await new Promise((r) => setTimeout(r, props.retryDelay));
37
+ }
38
+ try {
39
+ const res = await fn();
40
+ return res;
41
+ }
42
+ catch (e) {
43
+ lastError = e;
44
+ if (!props.retryCheck(e)) {
45
+ throw e;
210
46
  }
211
- });
212
- });
47
+ }
48
+ }
49
+ throw lastError;
213
50
  }
214
51
  function currentTimestamp() {
215
52
  return new Date().getTime();
@@ -220,9 +57,9 @@ function currentISOTime() {
220
57
  function safeSetTimeout(fn, timeout) {
221
58
  // NOTE: we use this so rarely that it is totally fine to do `safeSetTimeout(fn, 0)``
222
59
  // rather than setImmediate.
223
- var t = setTimeout(fn, timeout);
60
+ const t = setTimeout(fn, timeout);
224
61
  // We unref if available to prevent Node.js hanging on exit
225
- (t === null || t === void 0 ? void 0 : t.unref) && (t === null || t === void 0 ? void 0 : t.unref());
62
+ t?.unref && t?.unref();
226
63
  return t;
227
64
  }
228
65
 
@@ -236,24 +73,24 @@ function safeSetTimeout(fn, timeout) {
236
73
  //
237
74
  // LZ-based compression algorithm, version 1.4.4
238
75
  // private property
239
- var f = String.fromCharCode;
240
- var keyStrBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
241
- var baseReverseDic = {};
76
+ const f = String.fromCharCode;
77
+ const keyStrBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
78
+ const baseReverseDic = {};
242
79
  function getBaseValue(alphabet, character) {
243
80
  if (!baseReverseDic[alphabet]) {
244
81
  baseReverseDic[alphabet] = {};
245
- for (var i = 0; i < alphabet.length; i++) {
82
+ for (let i = 0; i < alphabet.length; i++) {
246
83
  baseReverseDic[alphabet][alphabet.charAt(i)] = i;
247
84
  }
248
85
  }
249
86
  return baseReverseDic[alphabet][character];
250
87
  }
251
- var LZString = {
88
+ const LZString = {
252
89
  compressToBase64: function (input) {
253
90
  if (input == null) {
254
91
  return '';
255
92
  }
256
- var res = LZString._compress(input, 6, function (a) {
93
+ const res = LZString._compress(input, 6, function (a) {
257
94
  return keyStrBase64.charAt(a);
258
95
  });
259
96
  switch (res.length % 4 // To produce valid Base64
@@ -289,8 +126,8 @@ var LZString = {
289
126
  if (uncompressed == null) {
290
127
  return '';
291
128
  }
292
- var context_dictionary = {}, context_dictionaryToCreate = {}, context_data = [];
293
- var i, value, context_c = '', context_wc = '', context_w = '', context_enlargeIn = 2, // Compensate for the first entry which should not count
129
+ const context_dictionary = {}, context_dictionaryToCreate = {}, context_data = [];
130
+ let i, value, context_c = '', context_wc = '', context_w = '', context_enlargeIn = 2, // Compensate for the first entry which should not count
294
131
  context_dictSize = 3, context_numBits = 2, context_data_val = 0, context_data_position = 0, ii;
295
132
  for (ii = 0; ii < uncompressed.length; ii += 1) {
296
133
  context_c = uncompressed.charAt(ii);
@@ -514,8 +351,8 @@ var LZString = {
514
351
  });
515
352
  },
516
353
  _decompress: function (length, resetValue, getNextValue) {
517
- var dictionary = [], result = [], data = { val: getNextValue(0), position: resetValue, index: 1 };
518
- var enlargeIn = 4, dictSize = 4, numBits = 3, entry = '', i, w, bits, resb, maxpower, power, c;
354
+ const dictionary = [], result = [], data = { val: getNextValue(0), position: resetValue, index: 1 };
355
+ let enlargeIn = 4, dictSize = 4, numBits = 3, entry = '', i, w, bits, resb, maxpower, power, c;
519
356
  for (i = 0; i < 3; i += 1) {
520
357
  dictionary[i] = i;
521
358
  }
@@ -657,33 +494,29 @@ var LZString = {
657
494
  },
658
495
  };
659
496
 
660
- var SimpleEventEmitter = /** @class */ (function () {
661
- function SimpleEventEmitter() {
497
+ class SimpleEventEmitter {
498
+ constructor() {
662
499
  this.events = {};
663
500
  this.events = {};
664
501
  }
665
- SimpleEventEmitter.prototype.on = function (event, listener) {
666
- var _this = this;
502
+ on(event, listener) {
667
503
  if (!this.events[event]) {
668
504
  this.events[event] = [];
669
505
  }
670
506
  this.events[event].push(listener);
671
- return function () {
672
- _this.events[event] = _this.events[event].filter(function (x) { return x !== listener; });
507
+ return () => {
508
+ this.events[event] = this.events[event].filter((x) => x !== listener);
673
509
  };
674
- };
675
- SimpleEventEmitter.prototype.emit = function (event, payload) {
676
- for (var _i = 0, _a = this.events[event] || []; _i < _a.length; _i++) {
677
- var listener = _a[_i];
510
+ }
511
+ emit(event, payload) {
512
+ for (const listener of this.events[event] || []) {
678
513
  listener(payload);
679
514
  }
680
- for (var _b = 0, _c = this.events['*'] || []; _b < _c.length; _b++) {
681
- var listener = _c[_b];
515
+ for (const listener of this.events['*'] || []) {
682
516
  listener(event, payload);
683
517
  }
684
- };
685
- return SimpleEventEmitter;
686
- }());
518
+ }
519
+ }
687
520
 
688
521
  // vendor from: https://github.com/LiosK/uuidv7/blob/f30b7a7faff73afbce0b27a46c638310f96912ba/src/index.ts
689
522
  // https://github.com/LiosK/uuidv7#license
@@ -694,11 +527,11 @@ var SimpleEventEmitter = /** @class */ (function () {
694
527
  * @copyright 2021-2023 LiosK
695
528
  * @packageDocumentation
696
529
  */
697
- var DIGITS = "0123456789abcdef";
530
+ const DIGITS = "0123456789abcdef";
698
531
  /** Represents a UUID as a 16-byte byte array. */
699
- var UUID = /** @class */ (function () {
532
+ class UUID {
700
533
  /** @param bytes - The 16-byte byte array representation. */
701
- function UUID(bytes) {
534
+ constructor(bytes) {
702
535
  this.bytes = bytes;
703
536
  }
704
537
  /**
@@ -710,14 +543,14 @@ var UUID = /** @class */ (function () {
710
543
  *
711
544
  * @throws TypeError if the length of the argument is not 16.
712
545
  */
713
- UUID.ofInner = function (bytes) {
546
+ static ofInner(bytes) {
714
547
  if (bytes.length !== 16) {
715
548
  throw new TypeError("not 128-bit length");
716
549
  }
717
550
  else {
718
551
  return new UUID(bytes);
719
552
  }
720
- };
553
+ }
721
554
  /**
722
555
  * Builds a byte array from UUIDv7 field values.
723
556
  *
@@ -727,7 +560,7 @@ var UUID = /** @class */ (function () {
727
560
  * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
728
561
  * @throws RangeError if any field value is out of the specified range.
729
562
  */
730
- UUID.fromFieldsV7 = function (unixTsMs, randA, randBHi, randBLo) {
563
+ static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
731
564
  if (!Number.isInteger(unixTsMs) ||
732
565
  !Number.isInteger(randA) ||
733
566
  !Number.isInteger(randBHi) ||
@@ -742,12 +575,12 @@ var UUID = /** @class */ (function () {
742
575
  randBLo > 4294967295) {
743
576
  throw new RangeError("invalid field value");
744
577
  }
745
- var bytes = new Uint8Array(16);
746
- bytes[0] = unixTsMs / Math.pow(2, 40);
747
- bytes[1] = unixTsMs / Math.pow(2, 32);
748
- bytes[2] = unixTsMs / Math.pow(2, 24);
749
- bytes[3] = unixTsMs / Math.pow(2, 16);
750
- bytes[4] = unixTsMs / Math.pow(2, 8);
578
+ const bytes = new Uint8Array(16);
579
+ bytes[0] = unixTsMs / 2 ** 40;
580
+ bytes[1] = unixTsMs / 2 ** 32;
581
+ bytes[2] = unixTsMs / 2 ** 24;
582
+ bytes[3] = unixTsMs / 2 ** 16;
583
+ bytes[4] = unixTsMs / 2 ** 8;
751
584
  bytes[5] = unixTsMs;
752
585
  bytes[6] = 0x70 | (randA >>> 8);
753
586
  bytes[7] = randA;
@@ -760,7 +593,7 @@ var UUID = /** @class */ (function () {
760
593
  bytes[14] = randBLo >>> 8;
761
594
  bytes[15] = randBLo;
762
595
  return new UUID(bytes);
763
- };
596
+ }
764
597
  /**
765
598
  * Builds a byte array from a string representation.
766
599
  *
@@ -775,33 +608,38 @@ var UUID = /** @class */ (function () {
775
608
  *
776
609
  * @throws SyntaxError if the argument could not parse as a valid UUID string.
777
610
  */
778
- UUID.parse = function (uuid) {
779
- var _a, _b, _c, _d;
780
- var hex = undefined;
611
+ static parse(uuid) {
612
+ let hex = undefined;
781
613
  switch (uuid.length) {
782
614
  case 32:
783
- hex = (_a = /^[0-9a-f]{32}$/i.exec(uuid)) === null || _a === void 0 ? void 0 : _a[0];
615
+ hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];
784
616
  break;
785
617
  case 36:
786
618
  hex =
787
- (_b = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
788
- .exec(uuid)) === null || _b === void 0 ? void 0 : _b.slice(1, 6).join("");
619
+ /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
620
+ .exec(uuid)
621
+ ?.slice(1, 6)
622
+ .join("");
789
623
  break;
790
624
  case 38:
791
625
  hex =
792
- (_c = /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i
793
- .exec(uuid)) === null || _c === void 0 ? void 0 : _c.slice(1, 6).join("");
626
+ /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i
627
+ .exec(uuid)
628
+ ?.slice(1, 6)
629
+ .join("");
794
630
  break;
795
631
  case 45:
796
632
  hex =
797
- (_d = /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
798
- .exec(uuid)) === null || _d === void 0 ? void 0 : _d.slice(1, 6).join("");
633
+ /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
634
+ .exec(uuid)
635
+ ?.slice(1, 6)
636
+ .join("");
799
637
  break;
800
638
  }
801
639
  if (hex) {
802
- var inner = new Uint8Array(16);
803
- for (var i = 0; i < 16; i += 4) {
804
- var n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
640
+ const inner = new Uint8Array(16);
641
+ for (let i = 0; i < 16; i += 4) {
642
+ const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
805
643
  inner[i + 0] = n >>> 24;
806
644
  inner[i + 1] = n >>> 16;
807
645
  inner[i + 2] = n >>> 8;
@@ -812,14 +650,14 @@ var UUID = /** @class */ (function () {
812
650
  else {
813
651
  throw new SyntaxError("could not parse UUID string");
814
652
  }
815
- };
653
+ }
816
654
  /**
817
655
  * @returns The 8-4-4-4-12 canonical hexadecimal string representation
818
656
  * (`0189dcd5-5311-7d40-8db0-9496a2eef37b`).
819
657
  */
820
- UUID.prototype.toString = function () {
821
- var text = "";
822
- for (var i = 0; i < this.bytes.length; i++) {
658
+ toString() {
659
+ let text = "";
660
+ for (let i = 0; i < this.bytes.length; i++) {
823
661
  text += DIGITS.charAt(this.bytes[i] >>> 4);
824
662
  text += DIGITS.charAt(this.bytes[i] & 0xf);
825
663
  if (i === 3 || i === 5 || i === 7 || i === 9) {
@@ -827,23 +665,23 @@ var UUID = /** @class */ (function () {
827
665
  }
828
666
  }
829
667
  return text;
830
- };
668
+ }
831
669
  /**
832
670
  * @returns The 32-digit hexadecimal representation without hyphens
833
671
  * (`0189dcd553117d408db09496a2eef37b`).
834
672
  */
835
- UUID.prototype.toHex = function () {
836
- var text = "";
837
- for (var i = 0; i < this.bytes.length; i++) {
673
+ toHex() {
674
+ let text = "";
675
+ for (let i = 0; i < this.bytes.length; i++) {
838
676
  text += DIGITS.charAt(this.bytes[i] >>> 4);
839
677
  text += DIGITS.charAt(this.bytes[i] & 0xf);
840
678
  }
841
679
  return text;
842
- };
680
+ }
843
681
  /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
844
- UUID.prototype.toJSON = function () {
682
+ toJSON() {
845
683
  return this.toString();
846
- };
684
+ }
847
685
  /**
848
686
  * Reports the variant field value of the UUID or, if appropriate, "NIL" or
849
687
  * "MAX".
@@ -852,57 +690,56 @@ var UUID = /** @class */ (function () {
852
690
  * the Nil or Max UUID, although the Nil and Max UUIDs are technically
853
691
  * subsumed under the variants `0b0` and `0b111`, respectively.
854
692
  */
855
- UUID.prototype.getVariant = function () {
856
- var n = this.bytes[8] >>> 4;
693
+ getVariant() {
694
+ const n = this.bytes[8] >>> 4;
857
695
  if (n < 0) {
858
696
  throw new Error("unreachable");
859
697
  }
860
- else if (n <= 7) {
861
- return this.bytes.every(function (e) { return e === 0; }) ? "NIL" : "VAR_0";
698
+ else if (n <= 0b0111) {
699
+ return this.bytes.every((e) => e === 0) ? "NIL" : "VAR_0";
862
700
  }
863
- else if (n <= 11) {
701
+ else if (n <= 0b1011) {
864
702
  return "VAR_10";
865
703
  }
866
- else if (n <= 13) {
704
+ else if (n <= 0b1101) {
867
705
  return "VAR_110";
868
706
  }
869
- else if (n <= 15) {
870
- return this.bytes.every(function (e) { return e === 0xff; }) ? "MAX" : "VAR_RESERVED";
707
+ else if (n <= 0b1111) {
708
+ return this.bytes.every((e) => e === 0xff) ? "MAX" : "VAR_RESERVED";
871
709
  }
872
710
  else {
873
711
  throw new Error("unreachable");
874
712
  }
875
- };
713
+ }
876
714
  /**
877
715
  * Returns the version field value of the UUID or `undefined` if the UUID does
878
716
  * not have the variant field value of `0b10`.
879
717
  */
880
- UUID.prototype.getVersion = function () {
718
+ getVersion() {
881
719
  return this.getVariant() === "VAR_10" ? this.bytes[6] >>> 4 : undefined;
882
- };
720
+ }
883
721
  /** Creates an object from `this`. */
884
- UUID.prototype.clone = function () {
722
+ clone() {
885
723
  return new UUID(this.bytes.slice(0));
886
- };
724
+ }
887
725
  /** Returns true if `this` is equivalent to `other`. */
888
- UUID.prototype.equals = function (other) {
726
+ equals(other) {
889
727
  return this.compareTo(other) === 0;
890
- };
728
+ }
891
729
  /**
892
730
  * Returns a negative integer, zero, or positive integer if `this` is less
893
731
  * than, equal to, or greater than `other`, respectively.
894
732
  */
895
- UUID.prototype.compareTo = function (other) {
896
- for (var i = 0; i < 16; i++) {
897
- var diff = this.bytes[i] - other.bytes[i];
733
+ compareTo(other) {
734
+ for (let i = 0; i < 16; i++) {
735
+ const diff = this.bytes[i] - other.bytes[i];
898
736
  if (diff !== 0) {
899
737
  return Math.sign(diff);
900
738
  }
901
739
  }
902
740
  return 0;
903
- };
904
- return UUID;
905
- }());
741
+ }
742
+ }
906
743
  /**
907
744
  * Encapsulates the monotonic counter state.
908
745
  *
@@ -912,16 +749,16 @@ var UUID = /** @class */ (function () {
912
749
  * that is useful to absolutely guarantee the monotonically increasing order of
913
750
  * generated UUIDs. See their respective documentation for details.
914
751
  */
915
- var V7Generator = /** @class */ (function () {
752
+ class V7Generator {
916
753
  /**
917
754
  * Creates a generator object with the default random number generator, or
918
755
  * with the specified one if passed as an argument. The specified random
919
756
  * number generator should be cryptographically strong and securely seeded.
920
757
  */
921
- function V7Generator(randomNumberGenerator) {
758
+ constructor(randomNumberGenerator) {
922
759
  this.timestamp = 0;
923
760
  this.counter = 0;
924
- this.random = randomNumberGenerator !== null && randomNumberGenerator !== void 0 ? randomNumberGenerator : getDefaultRandom();
761
+ this.random = randomNumberGenerator ?? getDefaultRandom();
925
762
  }
926
763
  /**
927
764
  * Generates a new UUIDv7 object from the current timestamp, or resets the
@@ -937,9 +774,9 @@ var V7Generator = /** @class */ (function () {
937
774
  * See {@link generateOrAbort} for the other mode of generation and
938
775
  * {@link generateOrResetCore} for the low-level primitive.
939
776
  */
940
- V7Generator.prototype.generate = function () {
777
+ generate() {
941
778
  return this.generateOrResetCore(Date.now(), 10000);
942
- };
779
+ }
943
780
  /**
944
781
  * Generates a new UUIDv7 object from the current timestamp, or returns
945
782
  * `undefined` upon significant timestamp rollback.
@@ -953,9 +790,9 @@ var V7Generator = /** @class */ (function () {
953
790
  * See {@link generate} for the other mode of generation and
954
791
  * {@link generateOrAbortCore} for the low-level primitive.
955
792
  */
956
- V7Generator.prototype.generateOrAbort = function () {
793
+ generateOrAbort() {
957
794
  return this.generateOrAbortCore(Date.now(), 10000);
958
- };
795
+ }
959
796
  /**
960
797
  * Generates a new UUIDv7 object from the `unixTsMs` passed, or resets the
961
798
  * generator upon significant timestamp rollback.
@@ -967,15 +804,15 @@ var V7Generator = /** @class */ (function () {
967
804
  * considered significant. A suggested value is `10_000` (milliseconds).
968
805
  * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
969
806
  */
970
- V7Generator.prototype.generateOrResetCore = function (unixTsMs, rollbackAllowance) {
971
- var value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
807
+ generateOrResetCore(unixTsMs, rollbackAllowance) {
808
+ let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
972
809
  if (value === undefined) {
973
810
  // reset state and resume
974
811
  this.timestamp = 0;
975
812
  value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
976
813
  }
977
814
  return value;
978
- };
815
+ }
979
816
  /**
980
817
  * Generates a new UUIDv7 object from the `unixTsMs` passed, or returns
981
818
  * `undefined` upon significant timestamp rollback.
@@ -987,8 +824,8 @@ var V7Generator = /** @class */ (function () {
987
824
  * considered significant. A suggested value is `10_000` (milliseconds).
988
825
  * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
989
826
  */
990
- V7Generator.prototype.generateOrAbortCore = function (unixTsMs, rollbackAllowance) {
991
- var MAX_COUNTER = 4398046511103;
827
+ generateOrAbortCore(unixTsMs, rollbackAllowance) {
828
+ const MAX_COUNTER = 4398046511103;
992
829
  if (!Number.isInteger(unixTsMs) ||
993
830
  unixTsMs < 1 ||
994
831
  unixTsMs > 281474976710655) {
@@ -1014,30 +851,29 @@ var V7Generator = /** @class */ (function () {
1014
851
  // abort if clock went backwards to unbearable extent
1015
852
  return undefined;
1016
853
  }
1017
- return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / Math.pow(2, 30)), this.counter & (Math.pow(2, 30) - 1), this.random.nextUint32());
1018
- };
854
+ return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & (2 ** 30 - 1), this.random.nextUint32());
855
+ }
1019
856
  /** Initializes the counter at a 42-bit random integer. */
1020
- V7Generator.prototype.resetCounter = function () {
857
+ resetCounter() {
1021
858
  this.counter =
1022
859
  this.random.nextUint32() * 0x400 + (this.random.nextUint32() & 0x3ff);
1023
- };
860
+ }
1024
861
  /**
1025
862
  * Generates a new UUIDv4 object utilizing the random number generator inside.
1026
863
  *
1027
864
  * @internal
1028
865
  */
1029
- V7Generator.prototype.generateV4 = function () {
1030
- var bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
866
+ generateV4() {
867
+ const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
1031
868
  bytes[6] = 0x40 | (bytes[6] >>> 4);
1032
869
  bytes[8] = 0x80 | (bytes[8] >>> 2);
1033
870
  return UUID.ofInner(bytes);
1034
- };
1035
- return V7Generator;
1036
- }());
871
+ }
872
+ }
1037
873
  /** A global flag to force use of cryptographically strong RNG. */
1038
874
  // declare const UUIDV7_DENY_WEAK_RNG: boolean;
1039
875
  /** Returns the default random number generator available in the environment. */
1040
- var getDefaultRandom = function () {
876
+ const getDefaultRandom = () => {
1041
877
  // fix: crypto isn't available in react-native, always use Math.random
1042
878
  // // detect Web Crypto API
1043
879
  // if (
@@ -1057,10 +893,8 @@ var getDefaultRandom = function () {
1057
893
  // };
1058
894
  // }
1059
895
  return {
1060
- nextUint32: function () {
1061
- return Math.trunc(Math.random() * 65536) * 65536 +
1062
- Math.trunc(Math.random() * 65536);
1063
- },
896
+ nextUint32: () => Math.trunc(Math.random() * 65536) * 65536 +
897
+ Math.trunc(Math.random() * 65536),
1064
898
  };
1065
899
  };
1066
900
  // /**
@@ -1079,785 +913,799 @@ var getDefaultRandom = function () {
1079
913
  // return this.buffer[this.cursor++];
1080
914
  // }
1081
915
  // }
1082
- var defaultGenerator;
916
+ let defaultGenerator;
1083
917
  /**
1084
918
  * Generates a UUIDv7 string.
1085
919
  *
1086
920
  * @returns The 8-4-4-4-12 canonical hexadecimal string representation
1087
921
  * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
1088
922
  */
1089
- var uuidv7 = function () { return uuidv7obj().toString(); };
923
+ const uuidv7 = () => uuidv7obj().toString();
1090
924
  /** Generates a UUIDv7 object. */
1091
- var uuidv7obj = function () {
1092
- return (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
1093
- };
925
+ const uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
1094
926
 
1095
- var PostHogFetchHttpError = /** @class */ (function (_super) {
1096
- __extends(PostHogFetchHttpError, _super);
1097
- function PostHogFetchHttpError(response) {
1098
- var _this = _super.call(this, 'HTTP error while fetching PostHog: ' + response.status) || this;
1099
- _this.response = response;
1100
- _this.name = 'PostHogFetchHttpError';
1101
- return _this;
1102
- }
1103
- return PostHogFetchHttpError;
1104
- }(Error));
1105
- var PostHogFetchNetworkError = /** @class */ (function (_super) {
1106
- __extends(PostHogFetchNetworkError, _super);
1107
- function PostHogFetchNetworkError(error) {
1108
- var _this =
927
+ class PostHogFetchHttpError extends Error {
928
+ constructor(response) {
929
+ super('HTTP error while fetching PostHog: ' + response.status);
930
+ this.response = response;
931
+ this.name = 'PostHogFetchHttpError';
932
+ }
933
+ }
934
+ class PostHogFetchNetworkError extends Error {
935
+ constructor(error) {
1109
936
  // TRICKY: "cause" is a newer property but is just ignored otherwise. Cast to any to ignore the type issue.
937
+ // eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
1110
938
  // @ts-ignore
1111
- _super.call(this, 'Network error while fetching PostHog', error instanceof Error ? { cause: error } : {}) || this;
1112
- _this.error = error;
1113
- _this.name = 'PostHogFetchNetworkError';
1114
- return _this;
939
+ super('Network error while fetching PostHog', error instanceof Error ? { cause: error } : {});
940
+ this.error = error;
941
+ this.name = 'PostHogFetchNetworkError';
1115
942
  }
1116
- return PostHogFetchNetworkError;
1117
- }(Error));
943
+ }
1118
944
  function isPostHogFetchError(err) {
1119
- return typeof err === 'object' && (err.name === 'PostHogFetchHttpError' || err.name === 'PostHogFetchNetworkError');
945
+ return typeof err === 'object' && (err instanceof PostHogFetchHttpError || err instanceof PostHogFetchNetworkError);
1120
946
  }
1121
- var PostHogCoreStateless = /** @class */ (function () {
1122
- function PostHogCoreStateless(apiKey, options) {
1123
- var _a, _b, _c, _d, _e;
1124
- this.debugMode = false;
947
+ class PostHogCoreStateless {
948
+ constructor(apiKey, options) {
1125
949
  this.disableGeoip = true;
950
+ this.disabled = false;
951
+ this.defaultOptIn = true;
1126
952
  this.pendingPromises = {};
1127
953
  // internal
1128
954
  this._events = new SimpleEventEmitter();
955
+ this._isInitialized = false;
1129
956
  assert(apiKey, "You must pass your PostHog project's api key.");
1130
957
  this.apiKey = apiKey;
1131
- this.host = removeTrailingSlash((options === null || options === void 0 ? void 0 : options.host) || 'https://app.posthog.com');
1132
- this.flushAt = (options === null || options === void 0 ? void 0 : options.flushAt) ? Math.max(options === null || options === void 0 ? void 0 : options.flushAt, 1) : 20;
1133
- this.flushInterval = (_a = options === null || options === void 0 ? void 0 : options.flushInterval) !== null && _a !== void 0 ? _a : 10000;
1134
- this.captureMode = (options === null || options === void 0 ? void 0 : options.captureMode) || 'form';
958
+ this.host = removeTrailingSlash(options?.host || 'https://app.posthog.com');
959
+ this.flushAt = options?.flushAt ? Math.max(options?.flushAt, 1) : 20;
960
+ this.flushInterval = options?.flushInterval ?? 10000;
961
+ this.captureMode = options?.captureMode || 'form';
1135
962
  // If enable is explicitly set to false we override the optout
1136
- this._optoutOverride = (options === null || options === void 0 ? void 0 : options.enable) === false;
963
+ this.defaultOptIn = options?.defaultOptIn ?? true;
1137
964
  this._retryOptions = {
1138
- retryCount: (_b = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _b !== void 0 ? _b : 3,
1139
- retryDelay: (_c = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _c !== void 0 ? _c : 3000,
965
+ retryCount: options?.fetchRetryCount ?? 3,
966
+ retryDelay: options?.fetchRetryDelay ?? 3000,
1140
967
  retryCheck: isPostHogFetchError,
1141
968
  };
1142
- this.requestTimeout = (_d = options === null || options === void 0 ? void 0 : options.requestTimeout) !== null && _d !== void 0 ? _d : 10000; // 10 seconds
1143
- this.disableGeoip = (_e = options === null || options === void 0 ? void 0 : options.disableGeoip) !== null && _e !== void 0 ? _e : true;
969
+ this.requestTimeout = options?.requestTimeout ?? 10000; // 10 seconds
970
+ this.featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 3000; // 3 seconds
971
+ this.disableGeoip = options?.disableGeoip ?? true;
972
+ this.disabled = options?.disabled ?? false;
973
+ // Init promise allows the derived class to block calls until it is ready
974
+ this._initPromise = Promise.resolve();
975
+ this._isInitialized = true;
976
+ }
977
+ wrap(fn) {
978
+ if (this.disabled) {
979
+ if (this.isDebug) {
980
+ console.warn('[PostHog] The client is disabled');
981
+ }
982
+ return;
983
+ }
984
+ if (this._isInitialized) {
985
+ // NOTE: We could also check for the "opt in" status here...
986
+ return fn();
987
+ }
988
+ this._initPromise.then(() => fn());
1144
989
  }
1145
- PostHogCoreStateless.prototype.getCommonEventProperties = function () {
990
+ getCommonEventProperties() {
1146
991
  return {
1147
992
  $lib: this.getLibraryId(),
1148
993
  $lib_version: this.getLibraryVersion(),
1149
994
  };
1150
- };
1151
- Object.defineProperty(PostHogCoreStateless.prototype, "optedOut", {
1152
- get: function () {
1153
- var _a, _b;
1154
- return (_b = (_a = this.getPersistedProperty(PostHogPersistedProperty.OptedOut)) !== null && _a !== void 0 ? _a : this._optoutOverride) !== null && _b !== void 0 ? _b : false;
1155
- },
1156
- enumerable: false,
1157
- configurable: true
1158
- });
1159
- PostHogCoreStateless.prototype.optIn = function () {
1160
- this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
1161
- };
1162
- PostHogCoreStateless.prototype.optOut = function () {
1163
- this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
1164
- };
1165
- PostHogCoreStateless.prototype.on = function (event, cb) {
995
+ }
996
+ get optedOut() {
997
+ return this.getPersistedProperty(PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
998
+ }
999
+ async optIn() {
1000
+ this.wrap(() => {
1001
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
1002
+ });
1003
+ }
1004
+ async optOut() {
1005
+ this.wrap(() => {
1006
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
1007
+ });
1008
+ }
1009
+ on(event, cb) {
1166
1010
  return this._events.on(event, cb);
1167
- };
1168
- PostHogCoreStateless.prototype.debug = function (enabled) {
1169
- var _a;
1170
- if (enabled === void 0) { enabled = true; }
1171
- (_a = this.removeDebugCallback) === null || _a === void 0 ? void 0 : _a.call(this);
1172
- this.debugMode = enabled;
1011
+ }
1012
+ debug(enabled = true) {
1013
+ this.removeDebugCallback?.();
1173
1014
  if (enabled) {
1174
- this.removeDebugCallback = this.on('*', function (event, payload) { return console.log('PostHog Debug', event, payload); });
1015
+ const removeDebugCallback = this.on('*', (event, payload) => console.log('PostHog Debug', event, payload));
1016
+ this.removeDebugCallback = () => {
1017
+ removeDebugCallback();
1018
+ this.removeDebugCallback = undefined;
1019
+ };
1175
1020
  }
1176
- };
1177
- PostHogCoreStateless.prototype.buildPayload = function (payload) {
1021
+ }
1022
+ get isDebug() {
1023
+ return !!this.removeDebugCallback;
1024
+ }
1025
+ buildPayload(payload) {
1178
1026
  return {
1179
1027
  distinct_id: payload.distinct_id,
1180
1028
  event: payload.event,
1181
- properties: __assign(__assign({}, (payload.properties || {})), this.getCommonEventProperties()),
1029
+ properties: {
1030
+ ...(payload.properties || {}),
1031
+ ...this.getCommonEventProperties(), // Common PH props
1032
+ },
1182
1033
  };
1183
- };
1184
- PostHogCoreStateless.prototype.addPendingPromise = function (promise) {
1185
- var _this = this;
1186
- var promiseUUID = uuidv7();
1034
+ }
1035
+ addPendingPromise(promise) {
1036
+ const promiseUUID = uuidv7();
1187
1037
  this.pendingPromises[promiseUUID] = promise;
1188
- promise.finally(function () {
1189
- delete _this.pendingPromises[promiseUUID];
1038
+ promise.finally(() => {
1039
+ delete this.pendingPromises[promiseUUID];
1190
1040
  });
1191
- };
1041
+ }
1192
1042
  /***
1193
1043
  *** TRACKING
1194
1044
  ***/
1195
- PostHogCoreStateless.prototype.identifyStateless = function (distinctId, properties, options) {
1196
- // The properties passed to identifyStateless are event properties.
1197
- // To add person properties, pass in all person properties to the `$set` key.
1198
- var payload = __assign({}, this.buildPayload({
1199
- distinct_id: distinctId,
1200
- event: '$identify',
1201
- properties: properties,
1202
- }));
1203
- this.enqueue('identify', payload, options);
1204
- return this;
1205
- };
1206
- PostHogCoreStateless.prototype.captureStateless = function (distinctId, event, properties, options) {
1207
- var payload = this.buildPayload({ distinct_id: distinctId, event: event, properties: properties });
1208
- this.enqueue('capture', payload, options);
1209
- return this;
1210
- };
1211
- PostHogCoreStateless.prototype.aliasStateless = function (alias, distinctId, properties, options) {
1212
- var payload = this.buildPayload({
1213
- event: '$create_alias',
1214
- distinct_id: distinctId,
1215
- properties: __assign(__assign({}, (properties || {})), { distinct_id: distinctId, alias: alias }),
1045
+ identifyStateless(distinctId, properties, options) {
1046
+ this.wrap(() => {
1047
+ // The properties passed to identifyStateless are event properties.
1048
+ // To add person properties, pass in all person properties to the `$set` key.
1049
+ const payload = {
1050
+ ...this.buildPayload({
1051
+ distinct_id: distinctId,
1052
+ event: '$identify',
1053
+ properties,
1054
+ }),
1055
+ };
1056
+ this.enqueue('identify', payload, options);
1216
1057
  });
1217
- this.enqueue('alias', payload, options);
1218
- return this;
1219
- };
1058
+ }
1059
+ captureStateless(distinctId, event, properties, options) {
1060
+ this.wrap(() => {
1061
+ const payload = this.buildPayload({ distinct_id: distinctId, event, properties });
1062
+ this.enqueue('capture', payload, options);
1063
+ });
1064
+ }
1065
+ aliasStateless(alias, distinctId, properties, options) {
1066
+ this.wrap(() => {
1067
+ const payload = this.buildPayload({
1068
+ event: '$create_alias',
1069
+ distinct_id: distinctId,
1070
+ properties: {
1071
+ ...(properties || {}),
1072
+ distinct_id: distinctId,
1073
+ alias,
1074
+ },
1075
+ });
1076
+ this.enqueue('alias', payload, options);
1077
+ });
1078
+ }
1220
1079
  /***
1221
1080
  *** GROUPS
1222
1081
  ***/
1223
- PostHogCoreStateless.prototype.groupIdentifyStateless = function (groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
1224
- var payload = this.buildPayload({
1225
- distinct_id: distinctId || "$".concat(groupType, "_").concat(groupKey),
1226
- event: '$groupidentify',
1227
- properties: __assign({ $group_type: groupType, $group_key: groupKey, $group_set: groupProperties || {} }, (eventProperties || {})),
1082
+ groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
1083
+ this.wrap(() => {
1084
+ const payload = this.buildPayload({
1085
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
1086
+ event: '$groupidentify',
1087
+ properties: {
1088
+ $group_type: groupType,
1089
+ $group_key: groupKey,
1090
+ $group_set: groupProperties || {},
1091
+ ...(eventProperties || {}),
1092
+ },
1093
+ });
1094
+ this.enqueue('capture', payload, options);
1228
1095
  });
1229
- this.enqueue('capture', payload, options);
1230
- return this;
1231
- };
1096
+ }
1232
1097
  /***
1233
1098
  *** FEATURE FLAGS
1234
1099
  ***/
1235
- PostHogCoreStateless.prototype.getDecide = function (distinctId, groups, personProperties, groupProperties, extraPayload) {
1236
- if (groups === void 0) { groups = {}; }
1237
- if (personProperties === void 0) { personProperties = {}; }
1238
- if (groupProperties === void 0) { groupProperties = {}; }
1239
- if (extraPayload === void 0) { extraPayload = {}; }
1240
- return __awaiter(this, void 0, void 0, function () {
1241
- var url, fetchOptions;
1242
- var _this = this;
1243
- return __generator(this, function (_a) {
1244
- url = "".concat(this.host, "/decide/?v=3");
1245
- fetchOptions = {
1246
- method: 'POST',
1247
- headers: { 'Content-Type': 'application/json' },
1248
- body: JSON.stringify(__assign({ token: this.apiKey, distinct_id: distinctId, groups: groups, person_properties: personProperties, group_properties: groupProperties }, extraPayload)),
1249
- };
1250
- return [2 /*return*/, this.fetchWithRetry(url, fetchOptions)
1251
- .then(function (response) { return response.json(); })
1252
- .catch(function (error) {
1253
- _this._events.emit('error', error);
1254
- return undefined;
1255
- })];
1256
- });
1257
- });
1258
- };
1259
- PostHogCoreStateless.prototype.getFeatureFlagStateless = function (key, distinctId, groups, personProperties, groupProperties, disableGeoip) {
1260
- if (groups === void 0) { groups = {}; }
1261
- if (personProperties === void 0) { personProperties = {}; }
1262
- if (groupProperties === void 0) { groupProperties = {}; }
1263
- return __awaiter(this, void 0, void 0, function () {
1264
- var featureFlags, response;
1265
- return __generator(this, function (_a) {
1266
- switch (_a.label) {
1267
- case 0: return [4 /*yield*/, this.getFeatureFlagsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)];
1268
- case 1:
1269
- featureFlags = _a.sent();
1270
- if (!featureFlags) {
1271
- // If we haven't loaded flags yet, or errored out, we respond with undefined
1272
- return [2 /*return*/, undefined];
1273
- }
1274
- response = featureFlags[key];
1275
- // `/decide` v3 returns all flags
1276
- if (response === undefined) {
1277
- // For cases where the flag is unknown, return false
1278
- response = false;
1279
- }
1280
- // If we have flags we either return the value (true or string) or false
1281
- return [2 /*return*/, response];
1282
- }
1283
- });
1284
- });
1285
- };
1286
- PostHogCoreStateless.prototype.getFeatureFlagPayloadStateless = function (key, distinctId, groups, personProperties, groupProperties, disableGeoip) {
1287
- if (groups === void 0) { groups = {}; }
1288
- if (personProperties === void 0) { personProperties = {}; }
1289
- if (groupProperties === void 0) { groupProperties = {}; }
1290
- return __awaiter(this, void 0, void 0, function () {
1291
- var payloads, response;
1292
- return __generator(this, function (_a) {
1293
- switch (_a.label) {
1294
- case 0: return [4 /*yield*/, this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)];
1295
- case 1:
1296
- payloads = _a.sent();
1297
- if (!payloads) {
1298
- return [2 /*return*/, undefined];
1299
- }
1300
- response = payloads[key];
1301
- // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
1302
- if (response === undefined) {
1303
- return [2 /*return*/, null];
1304
- }
1305
- return [2 /*return*/, this._parsePayload(response)];
1306
- }
1307
- });
1308
- });
1309
- };
1310
- PostHogCoreStateless.prototype.getFeatureFlagPayloadsStateless = function (distinctId, groups, personProperties, groupProperties, disableGeoip) {
1311
- if (groups === void 0) { groups = {}; }
1312
- if (personProperties === void 0) { personProperties = {}; }
1313
- if (groupProperties === void 0) { groupProperties = {}; }
1314
- return __awaiter(this, void 0, void 0, function () {
1315
- var payloads;
1316
- var _this = this;
1317
- return __generator(this, function (_a) {
1318
- switch (_a.label) {
1319
- case 0: return [4 /*yield*/, this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)];
1320
- case 1:
1321
- payloads = (_a.sent()).payloads;
1322
- if (payloads) {
1323
- return [2 /*return*/, Object.fromEntries(Object.entries(payloads).map(function (_a) {
1324
- var k = _a[0], v = _a[1];
1325
- return [k, _this._parsePayload(v)];
1326
- }))];
1327
- }
1328
- return [2 /*return*/, payloads];
1329
- }
1330
- });
1100
+ async getDecide(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}) {
1101
+ await this._initPromise;
1102
+ const url = `${this.host}/decide/?v=3`;
1103
+ const fetchOptions = {
1104
+ method: 'POST',
1105
+ headers: { 'Content-Type': 'application/json' },
1106
+ body: JSON.stringify({
1107
+ token: this.apiKey,
1108
+ distinct_id: distinctId,
1109
+ groups,
1110
+ person_properties: personProperties,
1111
+ group_properties: groupProperties,
1112
+ ...extraPayload,
1113
+ }),
1114
+ };
1115
+ // Don't retry /decide API calls
1116
+ return this.fetchWithRetry(url, fetchOptions, { retryCount: 0 }, this.featureFlagsRequestTimeoutMs)
1117
+ .then((response) => response.json())
1118
+ .catch((error) => {
1119
+ this._events.emit('error', error);
1120
+ return undefined;
1331
1121
  });
1332
- };
1333
- PostHogCoreStateless.prototype._parsePayload = function (response) {
1122
+ }
1123
+ async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1124
+ await this._initPromise;
1125
+ const featureFlags = await this.getFeatureFlagsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip);
1126
+ if (!featureFlags) {
1127
+ // If we haven't loaded flags yet, or errored out, we respond with undefined
1128
+ return undefined;
1129
+ }
1130
+ let response = featureFlags[key];
1131
+ // `/decide` v3 returns all flags
1132
+ if (response === undefined) {
1133
+ // For cases where the flag is unknown, return false
1134
+ response = false;
1135
+ }
1136
+ // If we have flags we either return the value (true or string) or false
1137
+ return response;
1138
+ }
1139
+ async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1140
+ await this._initPromise;
1141
+ const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip);
1142
+ if (!payloads) {
1143
+ return undefined;
1144
+ }
1145
+ const response = payloads[key];
1146
+ // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
1147
+ if (response === undefined) {
1148
+ return null;
1149
+ }
1150
+ return this._parsePayload(response);
1151
+ }
1152
+ async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1153
+ await this._initPromise;
1154
+ const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)).payloads;
1155
+ if (payloads) {
1156
+ return Object.fromEntries(Object.entries(payloads).map(([k, v]) => [k, this._parsePayload(v)]));
1157
+ }
1158
+ return payloads;
1159
+ }
1160
+ _parsePayload(response) {
1334
1161
  try {
1335
1162
  return JSON.parse(response);
1336
1163
  }
1337
- catch (_a) {
1164
+ catch {
1338
1165
  return response;
1339
1166
  }
1340
- };
1341
- PostHogCoreStateless.prototype.getFeatureFlagsStateless = function (distinctId, groups, personProperties, groupProperties, disableGeoip) {
1342
- if (groups === void 0) { groups = {}; }
1343
- if (personProperties === void 0) { personProperties = {}; }
1344
- if (groupProperties === void 0) { groupProperties = {}; }
1345
- return __awaiter(this, void 0, void 0, function () {
1346
- return __generator(this, function (_a) {
1347
- switch (_a.label) {
1348
- case 0: return [4 /*yield*/, this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)];
1349
- case 1: return [2 /*return*/, (_a.sent()).flags];
1350
- }
1351
- });
1352
- });
1353
- };
1354
- PostHogCoreStateless.prototype.getFeatureFlagsAndPayloadsStateless = function (distinctId, groups, personProperties, groupProperties, disableGeoip) {
1355
- if (groups === void 0) { groups = {}; }
1356
- if (personProperties === void 0) { personProperties = {}; }
1357
- if (groupProperties === void 0) { groupProperties = {}; }
1358
- return __awaiter(this, void 0, void 0, function () {
1359
- var extraPayload, decideResponse, flags, payloads;
1360
- return __generator(this, function (_a) {
1361
- switch (_a.label) {
1362
- case 0:
1363
- extraPayload = {};
1364
- if (disableGeoip !== null && disableGeoip !== void 0 ? disableGeoip : this.disableGeoip) {
1365
- extraPayload['geoip_disable'] = true;
1366
- }
1367
- return [4 /*yield*/, this.getDecide(distinctId, groups, personProperties, groupProperties, extraPayload)];
1368
- case 1:
1369
- decideResponse = _a.sent();
1370
- flags = decideResponse === null || decideResponse === void 0 ? void 0 : decideResponse.featureFlags;
1371
- payloads = decideResponse === null || decideResponse === void 0 ? void 0 : decideResponse.featureFlagPayloads;
1372
- return [2 /*return*/, {
1373
- flags: flags,
1374
- payloads: payloads,
1375
- }];
1376
- }
1377
- });
1378
- });
1379
- };
1167
+ }
1168
+ async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1169
+ await this._initPromise;
1170
+ return (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)).flags;
1171
+ }
1172
+ async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1173
+ await this._initPromise;
1174
+ const extraPayload = {};
1175
+ if (disableGeoip ?? this.disableGeoip) {
1176
+ extraPayload['geoip_disable'] = true;
1177
+ }
1178
+ const decideResponse = await this.getDecide(distinctId, groups, personProperties, groupProperties, extraPayload);
1179
+ const flags = decideResponse?.featureFlags;
1180
+ const payloads = decideResponse?.featureFlagPayloads;
1181
+ return {
1182
+ flags,
1183
+ payloads,
1184
+ };
1185
+ }
1380
1186
  /***
1381
1187
  *** QUEUEING AND FLUSHING
1382
1188
  ***/
1383
- PostHogCoreStateless.prototype.enqueue = function (type, _message, options) {
1384
- var _this = this;
1385
- var _a;
1386
- if (this.optedOut) {
1387
- this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
1388
- return;
1389
- }
1390
- var message = __assign(__assign({}, _message), { type: type, library: this.getLibraryId(), library_version: this.getLibraryVersion(), timestamp: (options === null || options === void 0 ? void 0 : options.timestamp) ? options === null || options === void 0 ? void 0 : options.timestamp : currentISOTime(), uuid: (options === null || options === void 0 ? void 0 : options.uuid) ? options.uuid : uuidv7() });
1391
- var addGeoipDisableProperty = (_a = options === null || options === void 0 ? void 0 : options.disableGeoip) !== null && _a !== void 0 ? _a : this.disableGeoip;
1392
- if (addGeoipDisableProperty) {
1393
- if (!message.properties) {
1394
- message.properties = {};
1189
+ enqueue(type, _message, options) {
1190
+ this.wrap(() => {
1191
+ if (this.optedOut) {
1192
+ this._events.emit(type, `Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);
1193
+ return;
1395
1194
  }
1396
- message['properties']['$geoip_disable'] = true;
1397
- }
1398
- if (message.distinctId) {
1399
- message.distinct_id = message.distinctId;
1400
- delete message.distinctId;
1401
- }
1402
- var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1403
- queue.push({ message: message });
1404
- this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1405
- this._events.emit(type, message);
1406
- // Flush queued events if we meet the flushAt length
1407
- if (queue.length >= this.flushAt) {
1408
- this.flush();
1409
- }
1410
- if (this.flushInterval && !this._flushTimer) {
1411
- this._flushTimer = safeSetTimeout(function () { return _this.flush(); }, this.flushInterval);
1412
- }
1413
- };
1414
- PostHogCoreStateless.prototype.flushAsync = function () {
1415
- var _this = this;
1416
- return new Promise(function (resolve, reject) {
1417
- _this.flush(function (err, data) {
1195
+ const message = {
1196
+ ..._message,
1197
+ type: type,
1198
+ library: this.getLibraryId(),
1199
+ library_version: this.getLibraryVersion(),
1200
+ timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
1201
+ uuid: options?.uuid ? options.uuid : uuidv7(),
1202
+ };
1203
+ const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
1204
+ if (addGeoipDisableProperty) {
1205
+ if (!message.properties) {
1206
+ message.properties = {};
1207
+ }
1208
+ message['properties']['$geoip_disable'] = true;
1209
+ }
1210
+ if (message.distinctId) {
1211
+ message.distinct_id = message.distinctId;
1212
+ delete message.distinctId;
1213
+ }
1214
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1215
+ queue.push({ message });
1216
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1217
+ this._events.emit(type, message);
1218
+ // Flush queued events if we meet the flushAt length
1219
+ if (queue.length >= this.flushAt) {
1220
+ this.flush();
1221
+ }
1222
+ if (this.flushInterval && !this._flushTimer) {
1223
+ this._flushTimer = safeSetTimeout(() => this.flush(), this.flushInterval);
1224
+ }
1225
+ });
1226
+ }
1227
+ async flushAsync() {
1228
+ await this._initPromise;
1229
+ return new Promise((resolve, reject) => {
1230
+ this.flush((err, data) => {
1418
1231
  return err ? reject(err) : resolve(data);
1419
1232
  });
1420
1233
  });
1421
- };
1422
- PostHogCoreStateless.prototype.flush = function (callback) {
1423
- var _this = this;
1424
- if (this._flushTimer) {
1425
- clearTimeout(this._flushTimer);
1426
- this._flushTimer = null;
1427
- }
1428
- var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1429
- if (!queue.length) {
1430
- return callback === null || callback === void 0 ? void 0 : callback();
1431
- }
1432
- var items = queue.splice(0, this.flushAt);
1433
- this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1434
- var messages = items.map(function (item) { return item.message; });
1435
- var data = {
1436
- api_key: this.apiKey,
1437
- batch: messages,
1438
- sent_at: currentISOTime(),
1439
- };
1440
- var done = function (err) {
1441
- if (err) {
1442
- _this._events.emit('error', err);
1234
+ }
1235
+ flush(callback) {
1236
+ this.wrap(() => {
1237
+ if (this._flushTimer) {
1238
+ clearTimeout(this._flushTimer);
1239
+ this._flushTimer = null;
1443
1240
  }
1444
- callback === null || callback === void 0 ? void 0 : callback(err, messages);
1445
- _this._events.emit('flush', messages);
1446
- };
1447
- // Don't set the user agent if we're not on a browser. The latest spec allows
1448
- // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1449
- // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1450
- // but browsers such as Chrome and Safari have not caught up.
1451
- this.getCustomUserAgent();
1452
- var payload = JSON.stringify(data);
1453
- var url = this.captureMode === 'form'
1454
- ? "".concat(this.host, "/e/?ip=1&_=").concat(currentTimestamp(), "&v=").concat(this.getLibraryVersion())
1455
- : "".concat(this.host, "/batch/");
1456
- var fetchOptions = this.captureMode === 'form'
1457
- ? {
1458
- method: 'POST',
1459
- mode: 'no-cors',
1460
- credentials: 'omit',
1461
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1462
- body: "data=".concat(encodeURIComponent(LZString.compressToBase64(payload)), "&compression=lz64"),
1241
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1242
+ if (!queue.length) {
1243
+ return callback?.();
1463
1244
  }
1464
- : {
1465
- method: 'POST',
1466
- headers: { 'Content-Type': 'application/json' },
1467
- body: payload,
1245
+ const items = queue.splice(0, this.flushAt);
1246
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1247
+ const messages = items.map((item) => item.message);
1248
+ const data = {
1249
+ api_key: this.apiKey,
1250
+ batch: messages,
1251
+ sent_at: currentISOTime(),
1468
1252
  };
1469
- var requestPromise = this.fetchWithRetry(url, fetchOptions);
1470
- this.addPendingPromise(requestPromise
1471
- .then(function () { return done(); })
1472
- .catch(function (err) {
1473
- done(err);
1474
- }));
1475
- };
1476
- PostHogCoreStateless.prototype.fetchWithRetry = function (url, options, retryOptions) {
1477
- var _a;
1478
- var _b;
1479
- return __awaiter(this, void 0, void 0, function () {
1480
- var _this = this;
1481
- return __generator(this, function (_c) {
1482
- switch (_c.label) {
1483
- case 0:
1484
- (_a = (_b = AbortSignal).timeout) !== null && _a !== void 0 ? _a : (_b.timeout = function timeout(ms) {
1485
- var ctrl = new AbortController();
1486
- setTimeout(function () { return ctrl.abort(); }, ms);
1487
- return ctrl.signal;
1488
- });
1489
- return [4 /*yield*/, retriable(function () { return __awaiter(_this, void 0, void 0, function () {
1490
- var res, e_1, isNoCors;
1491
- return __generator(this, function (_a) {
1492
- switch (_a.label) {
1493
- case 0:
1494
- res = null;
1495
- _a.label = 1;
1496
- case 1:
1497
- _a.trys.push([1, 3, , 4]);
1498
- return [4 /*yield*/, this.fetch(url, __assign({ signal: AbortSignal.timeout(this.requestTimeout) }, options))];
1499
- case 2:
1500
- res = _a.sent();
1501
- return [3 /*break*/, 4];
1502
- case 3:
1503
- e_1 = _a.sent();
1504
- // fetch will only throw on network errors or on timeouts
1505
- throw new PostHogFetchNetworkError(e_1);
1506
- case 4:
1507
- isNoCors = options.mode === 'no-cors';
1508
- if (!isNoCors && (res.status < 200 || res.status >= 400)) {
1509
- throw new PostHogFetchHttpError(res);
1510
- }
1511
- return [2 /*return*/, res];
1512
- }
1513
- });
1514
- }); }, __assign(__assign({}, this._retryOptions), retryOptions))];
1515
- case 1: return [2 /*return*/, _c.sent()];
1253
+ const done = (err) => {
1254
+ if (err) {
1255
+ this._events.emit('error', err);
1516
1256
  }
1517
- });
1518
- });
1519
- };
1520
- PostHogCoreStateless.prototype.shutdownAsync = function () {
1521
- return __awaiter(this, void 0, void 0, function () {
1522
- var e_2;
1523
- return __generator(this, function (_a) {
1524
- switch (_a.label) {
1525
- case 0:
1526
- clearTimeout(this._flushTimer);
1527
- _a.label = 1;
1528
- case 1:
1529
- _a.trys.push([1, 5, , 6]);
1530
- return [4 /*yield*/, this.flushAsync()];
1531
- case 2:
1532
- _a.sent();
1533
- return [4 /*yield*/, Promise.all(Object.values(this.pendingPromises).map(function (x) {
1534
- return x.catch(function () {
1535
- // ignore errors as we are shutting down and can't deal with them anyways.
1536
- });
1537
- }))
1538
- // flush again to make sure we send all events, some of which might've been added
1539
- // while we were waiting for the pending promises to resolve
1540
- // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1541
- ];
1542
- case 3:
1543
- _a.sent();
1544
- // flush again to make sure we send all events, some of which might've been added
1545
- // while we were waiting for the pending promises to resolve
1546
- // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1547
- return [4 /*yield*/, this.flushAsync()];
1548
- case 4:
1549
- // flush again to make sure we send all events, some of which might've been added
1550
- // while we were waiting for the pending promises to resolve
1551
- // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1552
- _a.sent();
1553
- return [3 /*break*/, 6];
1554
- case 5:
1555
- e_2 = _a.sent();
1556
- if (!isPostHogFetchError(e_2)) {
1557
- throw e_2;
1558
- }
1559
- console.error('Error while shutting down PostHog', e_2);
1560
- return [3 /*break*/, 6];
1561
- case 6: return [2 /*return*/];
1257
+ callback?.(err, messages);
1258
+ this._events.emit('flush', messages);
1259
+ };
1260
+ // Don't set the user agent if we're not on a browser. The latest spec allows
1261
+ // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1262
+ // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1263
+ // but browsers such as Chrome and Safari have not caught up.
1264
+ this.getCustomUserAgent();
1265
+ const payload = JSON.stringify(data);
1266
+ const url = this.captureMode === 'form'
1267
+ ? `${this.host}/e/?ip=1&_=${currentTimestamp()}&v=${this.getLibraryVersion()}`
1268
+ : `${this.host}/batch/`;
1269
+ const fetchOptions = this.captureMode === 'form'
1270
+ ? {
1271
+ method: 'POST',
1272
+ mode: 'no-cors',
1273
+ credentials: 'omit',
1274
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1275
+ body: `data=${encodeURIComponent(LZString.compressToBase64(payload))}&compression=lz64`,
1562
1276
  }
1563
- });
1277
+ : {
1278
+ method: 'POST',
1279
+ headers: { 'Content-Type': 'application/json' },
1280
+ body: payload,
1281
+ };
1282
+ const requestPromise = this.fetchWithRetry(url, fetchOptions);
1283
+ this.addPendingPromise(requestPromise
1284
+ .then(() => done())
1285
+ .catch((err) => {
1286
+ done(err);
1287
+ }));
1564
1288
  });
1565
- };
1566
- PostHogCoreStateless.prototype.shutdown = function () {
1567
- void this.shutdownAsync();
1568
- };
1569
- return PostHogCoreStateless;
1570
- }());
1571
- var PostHogCore = /** @class */ (function (_super) {
1572
- __extends(PostHogCore, _super);
1573
- function PostHogCore(apiKey, options) {
1574
- var _this = this;
1575
- var _a, _b, _c;
1289
+ }
1290
+ async fetchWithRetry(url, options, retryOptions, requestTimeout) {
1291
+ var _a;
1292
+ (_a = AbortSignal).timeout ?? (_a.timeout = function timeout(ms) {
1293
+ const ctrl = new AbortController();
1294
+ setTimeout(() => ctrl.abort(), ms);
1295
+ return ctrl.signal;
1296
+ });
1297
+ return await retriable(async () => {
1298
+ let res = null;
1299
+ try {
1300
+ res = await this.fetch(url, {
1301
+ signal: AbortSignal.timeout(requestTimeout ?? this.requestTimeout),
1302
+ ...options,
1303
+ });
1304
+ }
1305
+ catch (e) {
1306
+ // fetch will only throw on network errors or on timeouts
1307
+ throw new PostHogFetchNetworkError(e);
1308
+ }
1309
+ // If we're in no-cors mode, we can't access the response status
1310
+ // We only throw on HTTP errors if we're not in no-cors mode
1311
+ // https://developer.mozilla.org/en-US/docs/Web/API/Request/mode#no-cors
1312
+ const isNoCors = options.mode === 'no-cors';
1313
+ if (!isNoCors && (res.status < 200 || res.status >= 400)) {
1314
+ throw new PostHogFetchHttpError(res);
1315
+ }
1316
+ return res;
1317
+ }, { ...this._retryOptions, ...retryOptions });
1318
+ }
1319
+ async shutdownAsync(shutdownTimeoutMs) {
1320
+ await this._initPromise;
1321
+ clearTimeout(this._flushTimer);
1322
+ try {
1323
+ await Promise.all(Object.values(this.pendingPromises).map((x) => x.catch(() => {
1324
+ // ignore errors as we are shutting down and can't deal with them anyways.
1325
+ })));
1326
+ const timeout = shutdownTimeoutMs ?? 30000;
1327
+ const startTimeWithDelay = Date.now() + timeout;
1328
+ while (true) {
1329
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1330
+ if (queue.length === 0) {
1331
+ break;
1332
+ }
1333
+ // flush again to make sure we send all events, some of which might've been added
1334
+ // while we were waiting for the pending promises to resolve
1335
+ // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1336
+ await this.flushAsync();
1337
+ // If we've been waiting for more than the shutdownTimeoutMs, stop it
1338
+ const now = Date.now();
1339
+ if (startTimeWithDelay < now) {
1340
+ break;
1341
+ }
1342
+ }
1343
+ }
1344
+ catch (e) {
1345
+ if (!isPostHogFetchError(e)) {
1346
+ throw e;
1347
+ }
1348
+ console.error('Error while shutting down PostHog', e);
1349
+ }
1350
+ }
1351
+ shutdown(shutdownTimeoutMs) {
1352
+ void this.shutdownAsync(shutdownTimeoutMs);
1353
+ }
1354
+ }
1355
+ class PostHogCore extends PostHogCoreStateless {
1356
+ constructor(apiKey, options) {
1576
1357
  // Default for stateful mode is to not disable geoip. Only override if explicitly set
1577
- var disableGeoipOption = (_a = options === null || options === void 0 ? void 0 : options.disableGeoip) !== null && _a !== void 0 ? _a : false;
1578
- _this = _super.call(this, apiKey, __assign(__assign({}, options), { disableGeoip: disableGeoipOption })) || this;
1579
- _this.flagCallReported = {};
1580
- _this.sessionProps = {};
1581
- _this.sendFeatureFlagEvent = (_b = options === null || options === void 0 ? void 0 : options.sendFeatureFlagEvent) !== null && _b !== void 0 ? _b : true;
1582
- _this._sessionExpirationTimeSeconds = (_c = options === null || options === void 0 ? void 0 : options.sessionExpirationTimeSeconds) !== null && _c !== void 0 ? _c : 1800; // 30 minutes
1583
- return _this;
1584
- }
1585
- PostHogCore.prototype.setupBootstrap = function (options) {
1586
- var _a, _b, _c, _d;
1587
- if ((_a = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _a === void 0 ? void 0 : _a.distinctId) {
1588
- if ((_b = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _b === void 0 ? void 0 : _b.isIdentifiedId) {
1358
+ const disableGeoipOption = options?.disableGeoip ?? false;
1359
+ // Default for stateful mode is to timeout at 10s. Only override if explicitly set
1360
+ const featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 10000; // 10 seconds
1361
+ super(apiKey, { ...options, disableGeoip: disableGeoipOption, featureFlagsRequestTimeoutMs });
1362
+ this.flagCallReported = {};
1363
+ this.sessionProps = {};
1364
+ this.sendFeatureFlagEvent = options?.sendFeatureFlagEvent ?? true;
1365
+ this._sessionExpirationTimeSeconds = options?.sessionExpirationTimeSeconds ?? 1800; // 30 minutes
1366
+ }
1367
+ setupBootstrap(options) {
1368
+ if (options?.bootstrap?.distinctId) {
1369
+ if (options?.bootstrap?.isIdentifiedId) {
1589
1370
  this.setPersistedProperty(PostHogPersistedProperty.DistinctId, options.bootstrap.distinctId);
1590
1371
  }
1591
1372
  else {
1592
1373
  this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, options.bootstrap.distinctId);
1593
1374
  }
1594
1375
  }
1595
- if ((_c = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _c === void 0 ? void 0 : _c.featureFlags) {
1596
- var activeFlags = Object.keys(((_d = options.bootstrap) === null || _d === void 0 ? void 0 : _d.featureFlags) || {})
1597
- .filter(function (flag) { var _a, _b; return !!((_b = (_a = options.bootstrap) === null || _a === void 0 ? void 0 : _a.featureFlags) === null || _b === void 0 ? void 0 : _b[flag]); })
1598
- .reduce(function (res, key) {
1599
- var _a, _b;
1600
- return ((res[key] = ((_b = (_a = options.bootstrap) === null || _a === void 0 ? void 0 : _a.featureFlags) === null || _b === void 0 ? void 0 : _b[key]) || false), res);
1601
- }, {});
1376
+ if (options?.bootstrap?.featureFlags) {
1377
+ const activeFlags = Object.keys(options.bootstrap?.featureFlags || {})
1378
+ .filter((flag) => !!options.bootstrap?.featureFlags?.[flag])
1379
+ .reduce((res, key) => ((res[key] = options.bootstrap?.featureFlags?.[key] || false), res), {});
1602
1380
  this.setKnownFeatureFlags(activeFlags);
1603
- (options === null || options === void 0 ? void 0 : options.bootstrap.featureFlagPayloads) && this.setKnownFeatureFlagPayloads(options === null || options === void 0 ? void 0 : options.bootstrap.featureFlagPayloads);
1381
+ options?.bootstrap.featureFlagPayloads && this.setKnownFeatureFlagPayloads(options?.bootstrap.featureFlagPayloads);
1604
1382
  }
1605
- };
1606
- Object.defineProperty(PostHogCore.prototype, "props", {
1607
- // NOTE: Props are lazy loaded from localstorage hence the complex getter setter logic
1608
- get: function () {
1609
- if (!this._props) {
1610
- this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
1611
- }
1612
- return this._props || {};
1613
- },
1614
- set: function (val) {
1615
- this._props = val;
1616
- },
1617
- enumerable: false,
1618
- configurable: true
1619
- });
1620
- PostHogCore.prototype.clearProps = function () {
1383
+ }
1384
+ // NOTE: Props are lazy loaded from localstorage hence the complex getter setter logic
1385
+ get props() {
1386
+ if (!this._props) {
1387
+ this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
1388
+ }
1389
+ return this._props || {};
1390
+ }
1391
+ set props(val) {
1392
+ this._props = val;
1393
+ }
1394
+ clearProps() {
1621
1395
  this.props = undefined;
1622
1396
  this.sessionProps = {};
1623
- };
1624
- PostHogCore.prototype.on = function (event, cb) {
1397
+ }
1398
+ on(event, cb) {
1625
1399
  return this._events.on(event, cb);
1626
- };
1627
- PostHogCore.prototype.reset = function (propertiesToKeep) {
1628
- var allPropertiesToKeep = __spreadArray([PostHogPersistedProperty.Queue], (propertiesToKeep || []), true);
1629
- // clean up props
1630
- this.clearProps();
1631
- for (var _i = 0, _a = Object.keys(PostHogPersistedProperty); _i < _a.length; _i++) {
1632
- var key = _a[_i];
1633
- if (!allPropertiesToKeep.includes(PostHogPersistedProperty[key])) {
1634
- this.setPersistedProperty(PostHogPersistedProperty[key], null);
1400
+ }
1401
+ reset(propertiesToKeep) {
1402
+ this.wrap(() => {
1403
+ const allPropertiesToKeep = [PostHogPersistedProperty.Queue, ...(propertiesToKeep || [])];
1404
+ // clean up props
1405
+ this.clearProps();
1406
+ for (const key of Object.keys(PostHogPersistedProperty)) {
1407
+ if (!allPropertiesToKeep.includes(PostHogPersistedProperty[key])) {
1408
+ this.setPersistedProperty(PostHogPersistedProperty[key], null);
1409
+ }
1635
1410
  }
1636
- }
1637
- };
1638
- PostHogCore.prototype.getCommonEventProperties = function () {
1639
- var featureFlags = this.getFeatureFlags();
1640
- var featureVariantProperties = {};
1411
+ });
1412
+ }
1413
+ getCommonEventProperties() {
1414
+ const featureFlags = this.getFeatureFlags();
1415
+ const featureVariantProperties = {};
1641
1416
  if (featureFlags) {
1642
- for (var _i = 0, _a = Object.entries(featureFlags); _i < _a.length; _i++) {
1643
- var _b = _a[_i], feature = _b[0], variant = _b[1];
1644
- featureVariantProperties["$feature/".concat(feature)] = variant;
1417
+ for (const [feature, variant] of Object.entries(featureFlags)) {
1418
+ featureVariantProperties[`$feature/${feature}`] = variant;
1645
1419
  }
1646
1420
  }
1647
- return __assign(__assign({ $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined }, featureVariantProperties), _super.prototype.getCommonEventProperties.call(this));
1648
- };
1649
- PostHogCore.prototype.enrichProperties = function (properties) {
1650
- return __assign(__assign(__assign(__assign(__assign({}, this.props), this.sessionProps), (properties || {})), this.getCommonEventProperties()), { $session_id: this.getSessionId() });
1651
- };
1652
- PostHogCore.prototype.getSessionId = function () {
1653
- var sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
1654
- var sessionTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
1421
+ return {
1422
+ $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined,
1423
+ ...featureVariantProperties,
1424
+ ...super.getCommonEventProperties(),
1425
+ };
1426
+ }
1427
+ enrichProperties(properties) {
1428
+ return {
1429
+ ...this.props,
1430
+ ...this.sessionProps,
1431
+ ...(properties || {}),
1432
+ ...this.getCommonEventProperties(),
1433
+ $session_id: this.getSessionId(),
1434
+ };
1435
+ }
1436
+ /**
1437
+ * * @returns {string} The stored session ID for the current session. This may be an empty string if the client is not yet fully initialized.
1438
+ */
1439
+ getSessionId() {
1440
+ if (!this._isInitialized) {
1441
+ return '';
1442
+ }
1443
+ let sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
1444
+ const sessionTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
1655
1445
  if (!sessionId || Date.now() - sessionTimestamp > this._sessionExpirationTimeSeconds * 1000) {
1656
1446
  sessionId = uuidv7();
1657
1447
  this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);
1658
1448
  }
1659
1449
  this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, Date.now());
1660
1450
  return sessionId;
1661
- };
1662
- PostHogCore.prototype.resetSessionId = function () {
1663
- this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);
1664
- };
1665
- PostHogCore.prototype.getAnonymousId = function () {
1666
- var anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
1451
+ }
1452
+ resetSessionId() {
1453
+ this.wrap(() => {
1454
+ this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);
1455
+ });
1456
+ }
1457
+ /**
1458
+ * * @returns {string} The stored anonymous ID. This may be an empty string if the client is not yet fully initialized.
1459
+ */
1460
+ getAnonymousId() {
1461
+ if (!this._isInitialized) {
1462
+ return '';
1463
+ }
1464
+ let anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
1667
1465
  if (!anonId) {
1668
1466
  anonId = uuidv7();
1669
1467
  this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId);
1670
1468
  }
1671
1469
  return anonId;
1672
- };
1673
- PostHogCore.prototype.getDistinctId = function () {
1470
+ }
1471
+ /**
1472
+ * * @returns {string} The stored distinct ID. This may be an empty string if the client is not yet fully initialized.
1473
+ */
1474
+ getDistinctId() {
1475
+ if (!this._isInitialized) {
1476
+ return '';
1477
+ }
1674
1478
  return this.getPersistedProperty(PostHogPersistedProperty.DistinctId) || this.getAnonymousId();
1675
- };
1676
- PostHogCore.prototype.unregister = function (property) {
1677
- delete this.props[property];
1678
- this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
1679
- };
1680
- PostHogCore.prototype.register = function (properties) {
1681
- this.props = __assign(__assign({}, this.props), properties);
1682
- this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
1683
- };
1684
- PostHogCore.prototype.registerForSession = function (properties) {
1685
- this.sessionProps = __assign(__assign({}, this.sessionProps), properties);
1686
- };
1687
- PostHogCore.prototype.unregisterForSession = function (property) {
1479
+ }
1480
+ async unregister(property) {
1481
+ this.wrap(() => {
1482
+ delete this.props[property];
1483
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
1484
+ });
1485
+ }
1486
+ async register(properties) {
1487
+ this.wrap(() => {
1488
+ this.props = {
1489
+ ...this.props,
1490
+ ...properties,
1491
+ };
1492
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
1493
+ });
1494
+ }
1495
+ registerForSession(properties) {
1496
+ this.sessionProps = {
1497
+ ...this.sessionProps,
1498
+ ...properties,
1499
+ };
1500
+ }
1501
+ unregisterForSession(property) {
1688
1502
  delete this.sessionProps[property];
1689
- };
1503
+ }
1690
1504
  /***
1691
1505
  *** TRACKING
1692
1506
  ***/
1693
- PostHogCore.prototype.identify = function (distinctId, properties, options) {
1694
- var previousDistinctId = this.getDistinctId();
1695
- distinctId = distinctId || previousDistinctId;
1696
- if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
1697
- this.groups(properties.$groups);
1698
- }
1699
- var allProperties = this.enrichProperties(__assign(__assign({}, properties), { $anon_distinct_id: this.getAnonymousId(), $set: properties }));
1700
- if (distinctId !== previousDistinctId) {
1701
- // We keep the AnonymousId to be used by decide calls and identify to link the previousId
1702
- this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);
1703
- this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
1704
- this.reloadFeatureFlags();
1705
- }
1706
- _super.prototype.identifyStateless.call(this, distinctId, allProperties, options);
1707
- return this;
1708
- };
1709
- PostHogCore.prototype.capture = function (event, properties, options) {
1710
- var distinctId = this.getDistinctId();
1711
- if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
1712
- this.groups(properties.$groups);
1713
- }
1714
- var allProperties = this.enrichProperties(properties);
1715
- _super.prototype.captureStateless.call(this, distinctId, event, allProperties, options);
1716
- return this;
1717
- };
1718
- PostHogCore.prototype.alias = function (alias) {
1719
- var distinctId = this.getDistinctId();
1720
- var allProperties = this.enrichProperties({});
1721
- _super.prototype.aliasStateless.call(this, alias, distinctId, allProperties);
1722
- return this;
1723
- };
1724
- PostHogCore.prototype.autocapture = function (eventType, elements, properties, options) {
1725
- if (properties === void 0) { properties = {}; }
1726
- var distinctId = this.getDistinctId();
1727
- var payload = {
1728
- distinct_id: distinctId,
1729
- event: '$autocapture',
1730
- properties: __assign(__assign({}, this.enrichProperties(properties)), { $event_type: eventType, $elements: elements }),
1731
- };
1732
- this.enqueue('autocapture', payload, options);
1733
- return this;
1734
- };
1507
+ identify(distinctId, properties, options) {
1508
+ this.wrap(() => {
1509
+ const previousDistinctId = this.getDistinctId();
1510
+ distinctId = distinctId || previousDistinctId;
1511
+ if (properties?.$groups) {
1512
+ this.groups(properties.$groups);
1513
+ }
1514
+ const allProperties = this.enrichProperties({
1515
+ ...properties,
1516
+ $anon_distinct_id: this.getAnonymousId(),
1517
+ $set: properties,
1518
+ });
1519
+ if (distinctId !== previousDistinctId) {
1520
+ // We keep the AnonymousId to be used by decide calls and identify to link the previousId
1521
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);
1522
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
1523
+ this.reloadFeatureFlags();
1524
+ }
1525
+ super.identifyStateless(distinctId, allProperties, options);
1526
+ });
1527
+ }
1528
+ capture(event, properties, options) {
1529
+ this.wrap(() => {
1530
+ const distinctId = this.getDistinctId();
1531
+ if (properties?.$groups) {
1532
+ this.groups(properties.$groups);
1533
+ }
1534
+ const allProperties = this.enrichProperties(properties);
1535
+ super.captureStateless(distinctId, event, allProperties, options);
1536
+ });
1537
+ }
1538
+ alias(alias) {
1539
+ this.wrap(() => {
1540
+ const distinctId = this.getDistinctId();
1541
+ const allProperties = this.enrichProperties({});
1542
+ super.aliasStateless(alias, distinctId, allProperties);
1543
+ });
1544
+ }
1545
+ autocapture(eventType, elements, properties = {}, options) {
1546
+ this.wrap(() => {
1547
+ const distinctId = this.getDistinctId();
1548
+ const payload = {
1549
+ distinct_id: distinctId,
1550
+ event: '$autocapture',
1551
+ properties: {
1552
+ ...this.enrichProperties(properties),
1553
+ $event_type: eventType,
1554
+ $elements: elements,
1555
+ },
1556
+ };
1557
+ this.enqueue('autocapture', payload, options);
1558
+ });
1559
+ }
1735
1560
  /***
1736
1561
  *** GROUPS
1737
1562
  ***/
1738
- PostHogCore.prototype.groups = function (groups) {
1739
- // Get persisted groups
1740
- var existingGroups = this.props.$groups || {};
1741
- this.register({
1742
- $groups: __assign(__assign({}, existingGroups), groups),
1563
+ groups(groups) {
1564
+ this.wrap(() => {
1565
+ // Get persisted groups
1566
+ const existingGroups = this.props.$groups || {};
1567
+ this.register({
1568
+ $groups: {
1569
+ ...existingGroups,
1570
+ ...groups,
1571
+ },
1572
+ });
1573
+ if (Object.keys(groups).find((type) => existingGroups[type] !== groups[type])) {
1574
+ this.reloadFeatureFlags();
1575
+ }
1743
1576
  });
1744
- if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; })) {
1745
- this.reloadFeatureFlags();
1746
- }
1747
- return this;
1748
- };
1749
- PostHogCore.prototype.group = function (groupType, groupKey, groupProperties, options) {
1750
- var _a;
1751
- this.groups((_a = {},
1752
- _a[groupType] = groupKey,
1753
- _a));
1754
- if (groupProperties) {
1755
- this.groupIdentify(groupType, groupKey, groupProperties, options);
1756
- }
1757
- return this;
1758
- };
1759
- PostHogCore.prototype.groupIdentify = function (groupType, groupKey, groupProperties, options) {
1760
- var distinctId = this.getDistinctId();
1761
- var eventProperties = this.enrichProperties({});
1762
- _super.prototype.groupIdentifyStateless.call(this, groupType, groupKey, groupProperties, options, distinctId, eventProperties);
1763
- return this;
1764
- };
1577
+ }
1578
+ group(groupType, groupKey, groupProperties, options) {
1579
+ this.wrap(() => {
1580
+ this.groups({
1581
+ [groupType]: groupKey,
1582
+ });
1583
+ if (groupProperties) {
1584
+ this.groupIdentify(groupType, groupKey, groupProperties, options);
1585
+ }
1586
+ });
1587
+ }
1588
+ groupIdentify(groupType, groupKey, groupProperties, options) {
1589
+ this.wrap(() => {
1590
+ const distinctId = this.getDistinctId();
1591
+ const eventProperties = this.enrichProperties({});
1592
+ super.groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties);
1593
+ });
1594
+ }
1765
1595
  /***
1766
1596
  * PROPERTIES
1767
1597
  ***/
1768
- PostHogCore.prototype.setPersonPropertiesForFlags = function (properties) {
1769
- // Get persisted person properties
1770
- var existingProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
1771
- this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, __assign(__assign({}, existingProperties), properties));
1772
- return this;
1773
- };
1774
- PostHogCore.prototype.resetPersonPropertiesForFlags = function () {
1775
- this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, {});
1776
- };
1598
+ setPersonPropertiesForFlags(properties) {
1599
+ this.wrap(() => {
1600
+ // Get persisted person properties
1601
+ const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
1602
+ this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, {
1603
+ ...existingProperties,
1604
+ ...properties,
1605
+ });
1606
+ });
1607
+ }
1608
+ resetPersonPropertiesForFlags() {
1609
+ this.wrap(() => {
1610
+ this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, {});
1611
+ });
1612
+ }
1777
1613
  /** @deprecated - Renamed to setPersonPropertiesForFlags */
1778
- PostHogCore.prototype.personProperties = function (properties) {
1614
+ personProperties(properties) {
1779
1615
  return this.setPersonPropertiesForFlags(properties);
1780
- };
1781
- PostHogCore.prototype.setGroupPropertiesForFlags = function (properties) {
1782
- // Get persisted group properties
1783
- var existingProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
1784
- if (Object.keys(existingProperties).length !== 0) {
1785
- Object.keys(existingProperties).forEach(function (groupType) {
1786
- existingProperties[groupType] = __assign(__assign({}, existingProperties[groupType]), properties[groupType]);
1787
- delete properties[groupType];
1616
+ }
1617
+ setGroupPropertiesForFlags(properties) {
1618
+ this.wrap(() => {
1619
+ // Get persisted group properties
1620
+ const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) ||
1621
+ {};
1622
+ if (Object.keys(existingProperties).length !== 0) {
1623
+ Object.keys(existingProperties).forEach((groupType) => {
1624
+ existingProperties[groupType] = {
1625
+ ...existingProperties[groupType],
1626
+ ...properties[groupType],
1627
+ };
1628
+ delete properties[groupType];
1629
+ });
1630
+ }
1631
+ this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, {
1632
+ ...existingProperties,
1633
+ ...properties,
1788
1634
  });
1789
- }
1790
- this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, __assign(__assign({}, existingProperties), properties));
1791
- return this;
1792
- };
1793
- PostHogCore.prototype.resetGroupPropertiesForFlags = function () {
1794
- this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, {});
1795
- };
1635
+ });
1636
+ }
1637
+ resetGroupPropertiesForFlags() {
1638
+ this.wrap(() => {
1639
+ this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, {});
1640
+ });
1641
+ }
1796
1642
  /** @deprecated - Renamed to setGroupPropertiesForFlags */
1797
- PostHogCore.prototype.groupProperties = function (properties) {
1798
- return this.setGroupPropertiesForFlags(properties);
1799
- };
1643
+ groupProperties(properties) {
1644
+ this.wrap(() => {
1645
+ this.setGroupPropertiesForFlags(properties);
1646
+ });
1647
+ }
1800
1648
  /***
1801
1649
  *** FEATURE FLAGS
1802
1650
  ***/
1803
- PostHogCore.prototype.decideAsync = function (sendAnonDistinctId) {
1804
- if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
1651
+ async decideAsync(sendAnonDistinctId = true) {
1652
+ await this._initPromise;
1805
1653
  if (this._decideResponsePromise) {
1806
1654
  return this._decideResponsePromise;
1807
1655
  }
1808
1656
  return this._decideAsync(sendAnonDistinctId);
1809
- };
1810
- PostHogCore.prototype._decideAsync = function (sendAnonDistinctId) {
1811
- if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
1812
- return __awaiter(this, void 0, void 0, function () {
1813
- var distinctId, groups, personProperties, groupProperties, extraProperties;
1814
- var _this = this;
1815
- return __generator(this, function (_a) {
1816
- distinctId = this.getDistinctId();
1817
- groups = this.props.$groups || {};
1818
- personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
1819
- groupProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
1820
- extraProperties = {
1821
- $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,
1822
- };
1823
- this._decideResponsePromise = _super.prototype.getDecide.call(this, distinctId, groups, personProperties, groupProperties, extraProperties)
1824
- .then(function (res) {
1825
- if (res === null || res === void 0 ? void 0 : res.featureFlags) {
1826
- var newFeatureFlags = res.featureFlags;
1827
- var newFeatureFlagPayloads = res.featureFlagPayloads;
1828
- if (res.errorsWhileComputingFlags) {
1829
- // if not all flags were computed, we upsert flags instead of replacing them
1830
- var currentFlags = _this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1831
- var currentFlagPayloads = _this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);
1832
- newFeatureFlags = __assign(__assign({}, currentFlags), res.featureFlags);
1833
- newFeatureFlagPayloads = __assign(__assign({}, currentFlagPayloads), res.featureFlagPayloads);
1834
- }
1835
- _this.setKnownFeatureFlags(newFeatureFlags);
1836
- _this.setKnownFeatureFlagPayloads(newFeatureFlagPayloads);
1657
+ }
1658
+ async _decideAsync(sendAnonDistinctId = true) {
1659
+ this._decideResponsePromise = this._initPromise
1660
+ .then(() => {
1661
+ const distinctId = this.getDistinctId();
1662
+ const groups = this.props.$groups || {};
1663
+ const personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
1664
+ const groupProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) ||
1665
+ {};
1666
+ const extraProperties = {
1667
+ $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,
1668
+ };
1669
+ return super.getDecide(distinctId, groups, personProperties, groupProperties, extraProperties).then((res) => {
1670
+ if (res?.featureFlags) {
1671
+ let newFeatureFlags = res.featureFlags;
1672
+ let newFeatureFlagPayloads = res.featureFlagPayloads;
1673
+ if (res.errorsWhileComputingFlags) {
1674
+ // if not all flags were computed, we upsert flags instead of replacing them
1675
+ const currentFlags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1676
+ const currentFlagPayloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);
1677
+ newFeatureFlags = { ...currentFlags, ...res.featureFlags };
1678
+ newFeatureFlagPayloads = { ...currentFlagPayloads, ...res.featureFlagPayloads };
1837
1679
  }
1838
- return res;
1839
- })
1840
- .finally(function () {
1841
- _this._decideResponsePromise = undefined;
1842
- });
1843
- return [2 /*return*/, this._decideResponsePromise];
1680
+ this.setKnownFeatureFlags(newFeatureFlags);
1681
+ this.setKnownFeatureFlagPayloads(newFeatureFlagPayloads);
1682
+ }
1683
+ return res;
1844
1684
  });
1685
+ })
1686
+ .finally(() => {
1687
+ this._decideResponsePromise = undefined;
1845
1688
  });
1846
- };
1847
- PostHogCore.prototype.setKnownFeatureFlags = function (featureFlags) {
1848
- this.setPersistedProperty(PostHogPersistedProperty.FeatureFlags, featureFlags);
1849
- this._events.emit('featureflags', featureFlags);
1850
- };
1851
- PostHogCore.prototype.setKnownFeatureFlagPayloads = function (featureFlagPayloads) {
1852
- this.setPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads, featureFlagPayloads);
1853
- };
1854
- PostHogCore.prototype.getFeatureFlag = function (key) {
1855
- var featureFlags = this.getFeatureFlags();
1689
+ return this._decideResponsePromise;
1690
+ }
1691
+ setKnownFeatureFlags(featureFlags) {
1692
+ this.wrap(() => {
1693
+ this.setPersistedProperty(PostHogPersistedProperty.FeatureFlags, featureFlags);
1694
+ this._events.emit('featureflags', featureFlags);
1695
+ });
1696
+ }
1697
+ setKnownFeatureFlagPayloads(featureFlagPayloads) {
1698
+ this.wrap(() => {
1699
+ this.setPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads, featureFlagPayloads);
1700
+ });
1701
+ }
1702
+ getFeatureFlag(key) {
1703
+ const featureFlags = this.getFeatureFlags();
1856
1704
  if (!featureFlags) {
1857
1705
  // If we haven't loaded flags yet, or errored out, we respond with undefined
1858
1706
  return undefined;
1859
1707
  }
1860
- var response = featureFlags[key];
1708
+ let response = featureFlags[key];
1861
1709
  // `/decide` v3 returns all flags
1862
1710
  if (response === undefined) {
1863
1711
  // For cases where the flag is unknown, return false
@@ -1872,38 +1720,36 @@ var PostHogCore = /** @class */ (function (_super) {
1872
1720
  }
1873
1721
  // If we have flags we either return the value (true or string) or false
1874
1722
  return response;
1875
- };
1876
- PostHogCore.prototype.getFeatureFlagPayload = function (key) {
1877
- var payloads = this.getFeatureFlagPayloads();
1723
+ }
1724
+ getFeatureFlagPayload(key) {
1725
+ const payloads = this.getFeatureFlagPayloads();
1878
1726
  if (!payloads) {
1879
1727
  return undefined;
1880
1728
  }
1881
- var response = payloads[key];
1729
+ const response = payloads[key];
1882
1730
  // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
1883
1731
  if (response === undefined) {
1884
1732
  return null;
1885
1733
  }
1886
1734
  return this._parsePayload(response);
1887
- };
1888
- PostHogCore.prototype.getFeatureFlagPayloads = function () {
1889
- var _this = this;
1890
- var payloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);
1735
+ }
1736
+ getFeatureFlagPayloads() {
1737
+ const payloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);
1891
1738
  if (payloads) {
1892
- return Object.fromEntries(Object.entries(payloads).map(function (_a) {
1893
- var k = _a[0], v = _a[1];
1894
- return [k, _this._parsePayload(v)];
1895
- }));
1739
+ return Object.fromEntries(Object.entries(payloads).map(([k, v]) => [k, this._parsePayload(v)]));
1896
1740
  }
1897
1741
  return payloads;
1898
- };
1899
- PostHogCore.prototype.getFeatureFlags = function () {
1900
- var flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1901
- var overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
1742
+ }
1743
+ getFeatureFlags() {
1744
+ // NOTE: We don't check for _initPromise here as the function is designed to be
1745
+ // callable before the state being loaded anyways
1746
+ let flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1747
+ const overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
1902
1748
  if (!overriddenFlags) {
1903
1749
  return flags;
1904
1750
  }
1905
1751
  flags = flags || {};
1906
- for (var key in overriddenFlags) {
1752
+ for (const key in overriddenFlags) {
1907
1753
  if (!overriddenFlags[key]) {
1908
1754
  delete flags[key];
1909
1755
  }
@@ -1912,90 +1758,72 @@ var PostHogCore = /** @class */ (function (_super) {
1912
1758
  }
1913
1759
  }
1914
1760
  return flags;
1915
- };
1916
- PostHogCore.prototype.getFeatureFlagsAndPayloads = function () {
1917
- var flags = this.getFeatureFlags();
1918
- var payloads = this.getFeatureFlagPayloads();
1761
+ }
1762
+ getFeatureFlagsAndPayloads() {
1763
+ const flags = this.getFeatureFlags();
1764
+ const payloads = this.getFeatureFlagPayloads();
1919
1765
  return {
1920
- flags: flags,
1921
- payloads: payloads,
1766
+ flags,
1767
+ payloads,
1922
1768
  };
1923
- };
1924
- PostHogCore.prototype.isFeatureEnabled = function (key) {
1925
- var response = this.getFeatureFlag(key);
1769
+ }
1770
+ isFeatureEnabled(key) {
1771
+ const response = this.getFeatureFlag(key);
1926
1772
  if (response === undefined) {
1927
1773
  return undefined;
1928
1774
  }
1929
1775
  return !!response;
1930
- };
1776
+ }
1931
1777
  // Used when we want to trigger the reload but we don't care about the result
1932
- PostHogCore.prototype.reloadFeatureFlags = function (cb) {
1778
+ reloadFeatureFlags(cb) {
1933
1779
  this.decideAsync()
1934
- .then(function (res) {
1935
- cb === null || cb === void 0 ? void 0 : cb(undefined, res === null || res === void 0 ? void 0 : res.featureFlags);
1780
+ .then((res) => {
1781
+ cb?.(undefined, res?.featureFlags);
1936
1782
  })
1937
- .catch(function (e) {
1938
- cb === null || cb === void 0 ? void 0 : cb(e, undefined);
1783
+ .catch((e) => {
1784
+ cb?.(e, undefined);
1939
1785
  if (!cb) {
1940
1786
  console.log('[PostHog] Error reloading feature flags', e);
1941
1787
  }
1942
1788
  });
1943
- };
1944
- PostHogCore.prototype.reloadFeatureFlagsAsync = function (sendAnonDistinctId) {
1945
- var _a;
1946
- if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
1947
- return __awaiter(this, void 0, void 0, function () {
1948
- return __generator(this, function (_b) {
1949
- switch (_b.label) {
1950
- case 0: return [4 /*yield*/, this.decideAsync(sendAnonDistinctId)];
1951
- case 1: return [2 /*return*/, (_a = (_b.sent())) === null || _a === void 0 ? void 0 : _a.featureFlags];
1952
- }
1953
- });
1789
+ }
1790
+ async reloadFeatureFlagsAsync(sendAnonDistinctId = true) {
1791
+ return (await this.decideAsync(sendAnonDistinctId))?.featureFlags;
1792
+ }
1793
+ onFeatureFlags(cb) {
1794
+ return this.on('featureflags', async () => {
1795
+ const flags = this.getFeatureFlags();
1796
+ if (flags) {
1797
+ cb(flags);
1798
+ }
1954
1799
  });
1955
- };
1956
- PostHogCore.prototype.onFeatureFlags = function (cb) {
1957
- var _this = this;
1958
- return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
1959
- var flags;
1960
- return __generator(this, function (_a) {
1961
- flags = this.getFeatureFlags();
1962
- if (flags) {
1963
- cb(flags);
1964
- }
1965
- return [2 /*return*/];
1966
- });
1967
- }); });
1968
- };
1969
- PostHogCore.prototype.onFeatureFlag = function (key, cb) {
1970
- var _this = this;
1971
- return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
1972
- var flagResponse;
1973
- return __generator(this, function (_a) {
1974
- flagResponse = this.getFeatureFlag(key);
1975
- if (flagResponse !== undefined) {
1976
- cb(flagResponse);
1977
- }
1978
- return [2 /*return*/];
1979
- });
1980
- }); });
1981
- };
1982
- PostHogCore.prototype.overrideFeatureFlag = function (flags) {
1983
- if (flags === null) {
1984
- return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);
1985
- }
1986
- return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1987
- };
1988
- return PostHogCore;
1989
- }(PostHogCoreStateless));
1800
+ }
1801
+ onFeatureFlag(key, cb) {
1802
+ return this.on('featureflags', async () => {
1803
+ const flagResponse = this.getFeatureFlag(key);
1804
+ if (flagResponse !== undefined) {
1805
+ cb(flagResponse);
1806
+ }
1807
+ });
1808
+ }
1809
+ async overrideFeatureFlag(flags) {
1810
+ this.wrap(() => {
1811
+ if (flags === null) {
1812
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);
1813
+ }
1814
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1815
+ });
1816
+ }
1817
+ }
1990
1818
 
1991
- var version = "2.6.2";
1819
+ var version = "3.0.0-beta.1";
1992
1820
 
1993
1821
  function getContext(window) {
1994
- var context = {};
1822
+ let context = {};
1995
1823
 
1996
1824
  if (window.navigator) {
1997
- var userAgent = window.navigator.userAgent;
1998
- context = __assign(__assign({}, context), {
1825
+ const userAgent = window.navigator.userAgent;
1826
+ context = { ...context,
1999
1827
  $os: os(window),
2000
1828
  $browser: browser(userAgent, window.navigator.vendor, !!window.opera),
2001
1829
  $referrer: window.document.referrer,
@@ -2008,15 +1836,16 @@ function getContext(window) {
2008
1836
  $screen_height: window.screen.height,
2009
1837
  $screen_width: window.screen.width,
2010
1838
  $screen_dpr: window.devicePixelRatio
2011
- });
1839
+ };
2012
1840
  }
2013
1841
 
2014
- context = __assign(__assign({}, context), {
1842
+ context = { ...context,
2015
1843
  $lib: 'js',
2016
1844
  $lib_version: version,
2017
1845
  $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),
2018
- $time: currentTimestamp() / 1000
2019
- });
1846
+ $time: currentTimestamp() / 1000 // epoch time in seconds
1847
+
1848
+ };
2020
1849
  return context; // TODO: strip empty props?
2021
1850
  }
2022
1851
 
@@ -2074,7 +1903,7 @@ function browser(userAgent, vendor, opera) {
2074
1903
  }
2075
1904
 
2076
1905
  function browserVersion(userAgent, vendor, opera) {
2077
- var regexList = {
1906
+ const regexList = {
2078
1907
  'Internet Explorer Mobile': /rv:(\d+(\.\d+)?)/,
2079
1908
  'Microsoft Edge': /Edge?\/(\d+(\.\d+)?)/,
2080
1909
  Chrome: /Chrome\/(\d+(\.\d+)?)/,
@@ -2092,14 +1921,14 @@ function browserVersion(userAgent, vendor, opera) {
2092
1921
  'Internet Explorer': /(rv:|MSIE )(\d+(\.\d+)?)/,
2093
1922
  Mozilla: /rv:(\d+(\.\d+)?)/
2094
1923
  };
2095
- var browserString = browser(userAgent, vendor, opera);
2096
- var regex = regexList[browserString] || undefined;
1924
+ const browserString = browser(userAgent, vendor, opera);
1925
+ const regex = regexList[browserString] || undefined;
2097
1926
 
2098
1927
  if (regex === undefined) {
2099
1928
  return null;
2100
1929
  }
2101
1930
 
2102
- var matches = userAgent.match(regex);
1931
+ const matches = userAgent.match(regex);
2103
1932
 
2104
1933
  if (!matches) {
2105
1934
  return null;
@@ -2109,7 +1938,7 @@ function browserVersion(userAgent, vendor, opera) {
2109
1938
  }
2110
1939
 
2111
1940
  function os(window) {
2112
- var a = window.navigator.userAgent;
1941
+ const a = window.navigator.userAgent;
2113
1942
 
2114
1943
  if (/Windows/i.test(a)) {
2115
1944
  if (/Phone/.test(a) || /WPDesktop/.test(a)) {
@@ -2153,7 +1982,7 @@ function device(userAgent) {
2153
1982
  }
2154
1983
 
2155
1984
  function referringDomain(referrer) {
2156
- var split = referrer.split('/');
1985
+ const split = referrer.split('/');
2157
1986
 
2158
1987
  if (split.length >= 3) {
2159
1988
  return split[2];
@@ -2163,14 +1992,14 @@ function referringDomain(referrer) {
2163
1992
  }
2164
1993
 
2165
1994
  // Methods partially borrowed from quirksmode.org/js/cookies.html
2166
- var cookieStore = {
2167
- getItem: function (key) {
1995
+ const cookieStore = {
1996
+ getItem(key) {
2168
1997
  try {
2169
- var nameEQ = key + '=';
2170
- var ca = document.cookie.split(';');
1998
+ const nameEQ = key + '=';
1999
+ const ca = document.cookie.split(';');
2171
2000
 
2172
- for (var i = 0; i < ca.length; i++) {
2173
- var c = ca[i];
2001
+ for (let i = 0; i < ca.length; i++) {
2002
+ let c = ca[i];
2174
2003
 
2175
2004
  while (c.charAt(0) == ' ') {
2176
2005
  c = c.substring(1, c.length);
@@ -2184,33 +2013,37 @@ var cookieStore = {
2184
2013
 
2185
2014
  return null;
2186
2015
  },
2187
- setItem: function (key, value) {
2016
+
2017
+ setItem(key, value) {
2188
2018
  try {
2189
- var cdomain = '',
2190
- expires = '',
2191
- secure = '';
2192
- var new_cookie_val = key + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
2019
+ const cdomain = '',
2020
+ expires = '',
2021
+ secure = '';
2022
+ const new_cookie_val = key + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
2193
2023
  document.cookie = new_cookie_val;
2194
2024
  } catch (err) {
2195
2025
  return;
2196
2026
  }
2197
2027
  },
2198
- removeItem: function (name) {
2028
+
2029
+ removeItem(name) {
2199
2030
  try {
2200
2031
  cookieStore.setItem(name, '');
2201
2032
  } catch (err) {
2202
2033
  return;
2203
2034
  }
2204
2035
  },
2205
- clear: function () {
2036
+
2037
+ clear() {
2206
2038
  document.cookie = '';
2207
2039
  },
2208
- getAllKeys: function () {
2209
- var ca = document.cookie.split(';');
2210
- var keys = [];
2211
2040
 
2212
- for (var i = 0; i < ca.length; i++) {
2213
- var c = ca[i];
2041
+ getAllKeys() {
2042
+ const ca = document.cookie.split(';');
2043
+ const keys = [];
2044
+
2045
+ for (let i = 0; i < ca.length; i++) {
2046
+ let c = ca[i];
2214
2047
 
2215
2048
  while (c.charAt(0) == ' ') {
2216
2049
  c = c.substring(1, c.length);
@@ -2221,45 +2054,47 @@ var cookieStore = {
2221
2054
 
2222
2055
  return keys;
2223
2056
  }
2057
+
2224
2058
  };
2225
2059
 
2226
- var createStorageLike = function (store) {
2060
+ const createStorageLike = store => {
2227
2061
  return {
2228
- getItem: function (key) {
2062
+ getItem(key) {
2229
2063
  return store.getItem(key);
2230
2064
  },
2231
- setItem: function (key, value) {
2065
+
2066
+ setItem(key, value) {
2232
2067
  store.setItem(key, value);
2233
2068
  },
2234
- removeItem: function (key) {
2069
+
2070
+ removeItem(key) {
2235
2071
  store.removeItem(key);
2236
2072
  },
2237
- clear: function () {
2073
+
2074
+ clear() {
2238
2075
  store.clear();
2239
2076
  },
2240
- getAllKeys: function () {
2241
- var keys = [];
2242
2077
 
2243
- for (var key in localStorage) {
2078
+ getAllKeys() {
2079
+ const keys = [];
2080
+
2081
+ for (const key in localStorage) {
2244
2082
  keys.push(key);
2245
2083
  }
2246
2084
 
2247
2085
  return keys;
2248
2086
  }
2087
+
2249
2088
  };
2250
2089
  };
2251
2090
 
2252
- var checkStoreIsSupported = function (storage, key) {
2253
- if (key === void 0) {
2254
- key = '__mplssupport__';
2255
- }
2256
-
2091
+ const checkStoreIsSupported = (storage, key = '__mplssupport__') => {
2257
2092
  if (!window) {
2258
2093
  return false;
2259
2094
  }
2260
2095
 
2261
2096
  try {
2262
- var val = 'xyz';
2097
+ const val = 'xyz';
2263
2098
  storage.setItem(key, val);
2264
2099
 
2265
2100
  if (storage.getItem(key) !== val) {
@@ -2273,49 +2108,54 @@ var checkStoreIsSupported = function (storage, key) {
2273
2108
  }
2274
2109
  };
2275
2110
 
2276
- var localStore = undefined;
2277
- var sessionStore = undefined;
2111
+ let localStore = undefined;
2112
+ let sessionStore = undefined;
2278
2113
 
2279
- var createMemoryStorage = function () {
2280
- var _cache = {};
2281
- var store = {
2282
- getItem: function (key) {
2114
+ const createMemoryStorage = () => {
2115
+ const _cache = {};
2116
+ const store = {
2117
+ getItem(key) {
2283
2118
  return _cache[key];
2284
2119
  },
2285
- setItem: function (key, value) {
2120
+
2121
+ setItem(key, value) {
2286
2122
  _cache[key] = value !== null ? value : undefined;
2287
2123
  },
2288
- removeItem: function (key) {
2124
+
2125
+ removeItem(key) {
2289
2126
  delete _cache[key];
2290
2127
  },
2291
- clear: function () {
2292
- for (var key in _cache) {
2128
+
2129
+ clear() {
2130
+ for (const key in _cache) {
2293
2131
  delete _cache[key];
2294
2132
  }
2295
2133
  },
2296
- getAllKeys: function () {
2297
- var keys = [];
2298
2134
 
2299
- for (var key in _cache) {
2135
+ getAllKeys() {
2136
+ const keys = [];
2137
+
2138
+ for (const key in _cache) {
2300
2139
  keys.push(key);
2301
2140
  }
2302
2141
 
2303
2142
  return keys;
2304
2143
  }
2144
+
2305
2145
  };
2306
2146
  return store;
2307
2147
  };
2308
2148
 
2309
- var getStorage = function (type, window) {
2149
+ const getStorage = (type, window) => {
2310
2150
  if (window) {
2311
2151
  if (!localStorage) {
2312
- var _localStore = createStorageLike(window.localStorage);
2152
+ const _localStore = createStorageLike(window.localStorage);
2313
2153
 
2314
2154
  localStore = checkStoreIsSupported(_localStore) ? _localStore : undefined;
2315
2155
  }
2316
2156
 
2317
2157
  if (!sessionStore) {
2318
- var _sessionStore = createStorageLike(window.sessionStorage);
2158
+ const _sessionStore = createStorageLike(window.sessionStorage);
2319
2159
 
2320
2160
  sessionStore = checkStoreIsSupported(_sessionStore) ? _sessionStore : undefined;
2321
2161
  }
@@ -2339,36 +2179,28 @@ var getStorage = function (type, window) {
2339
2179
  }
2340
2180
  };
2341
2181
 
2342
- var PostHog =
2343
- /** @class */
2344
- function (_super) {
2345
- __extends(PostHog, _super);
2346
-
2347
- function PostHog(apiKey, options) {
2348
- var _this = _super.call(this, apiKey, options) || this; // posthog-js stores options in one object on
2349
-
2350
-
2351
- _this._storageKey = (options === null || options === void 0 ? void 0 : options.persistence_name) ? "ph_".concat(options.persistence_name) : "ph_".concat(apiKey, "_posthog");
2352
- _this._storage = getStorage((options === null || options === void 0 ? void 0 : options.persistence) || 'localStorage', window);
2182
+ class PostHog extends PostHogCore {
2183
+ constructor(apiKey, options) {
2184
+ super(apiKey, options); // posthog-js stores options in one object on
2353
2185
 
2354
- _this.setupBootstrap(options);
2186
+ this._storageKey = options?.persistence_name ? `ph_${options.persistence_name}` : `ph_${apiKey}_posthog`;
2187
+ this._storage = getStorage(options?.persistence || 'localStorage', window);
2188
+ this.setupBootstrap(options);
2355
2189
 
2356
- if ((options === null || options === void 0 ? void 0 : options.preloadFeatureFlags) !== false) {
2357
- _this.reloadFeatureFlags();
2190
+ if (options?.preloadFeatureFlags !== false) {
2191
+ this.reloadFeatureFlags();
2358
2192
  }
2359
-
2360
- return _this;
2361
2193
  }
2362
2194
 
2363
- PostHog.prototype.getPersistedProperty = function (key) {
2195
+ getPersistedProperty(key) {
2364
2196
  if (!this._storageCache) {
2365
2197
  this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || '{}') || {};
2366
2198
  }
2367
2199
 
2368
2200
  return this._storageCache[key];
2369
- };
2201
+ }
2370
2202
 
2371
- PostHog.prototype.setPersistedProperty = function (key, value) {
2203
+ setPersistedProperty(key, value) {
2372
2204
  if (!this._storageCache) {
2373
2205
  this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || '{}') || {};
2374
2206
  }
@@ -2380,30 +2212,31 @@ function (_super) {
2380
2212
  }
2381
2213
 
2382
2214
  this._storage.setItem(this._storageKey, JSON.stringify(this._storageCache));
2383
- };
2215
+ }
2384
2216
 
2385
- PostHog.prototype.fetch = function (url, options) {
2217
+ fetch(url, options) {
2386
2218
  return window.fetch(url, options);
2387
- };
2219
+ }
2388
2220
 
2389
- PostHog.prototype.getLibraryId = function () {
2221
+ getLibraryId() {
2390
2222
  return 'posthog-js-lite';
2391
- };
2223
+ }
2392
2224
 
2393
- PostHog.prototype.getLibraryVersion = function () {
2225
+ getLibraryVersion() {
2394
2226
  return version;
2395
- };
2227
+ }
2396
2228
 
2397
- PostHog.prototype.getCustomUserAgent = function () {
2229
+ getCustomUserAgent() {
2398
2230
  return;
2399
- };
2231
+ }
2400
2232
 
2401
- PostHog.prototype.getCommonEventProperties = function () {
2402
- return __assign(__assign({}, _super.prototype.getCommonEventProperties.call(this)), getContext(window));
2403
- };
2233
+ getCommonEventProperties() {
2234
+ return { ...super.getCommonEventProperties(),
2235
+ ...getContext(window)
2236
+ };
2237
+ }
2404
2238
 
2405
- return PostHog;
2406
- }(PostHogCore);
2239
+ }
2407
2240
 
2408
2241
  exports.PostHog = PostHog;
2409
2242
  exports["default"] = PostHog;