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