posthog-js-lite 0.0.5 → 2.0.0-alpha1

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