posthog-react-native 1.1.5 → 2.0.0-alpha12

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 (146) hide show
  1. package/README.md +9 -0
  2. package/lib/index.cjs.js +1804 -0
  3. package/lib/index.cjs.js.map +1 -0
  4. package/lib/index.d.ts +220 -0
  5. package/lib/index.esm.js +1767 -0
  6. package/lib/index.esm.js.map +1 -0
  7. package/lib/node_modules/tslib/tslib.es6.d.ts +35 -0
  8. package/lib/posthog-core/src/eventemitter.d.ts +8 -0
  9. package/lib/posthog-core/src/index.d.ts +87 -0
  10. package/lib/posthog-core/src/lz-string.d.ts +8 -0
  11. package/lib/posthog-core/src/storage-memory.d.ts +6 -0
  12. package/lib/posthog-core/src/types.d.ts +69 -0
  13. package/lib/posthog-core/src/utils.d.ts +12 -0
  14. package/lib/posthog-react-native/index.d.ts +10 -0
  15. package/lib/posthog-react-native/src/PostHogProvider.d.ts +13 -0
  16. package/lib/posthog-react-native/src/PosthogContext.d.ts +5 -0
  17. package/lib/posthog-react-native/src/autocapture.d.ts +3 -0
  18. package/lib/posthog-react-native/src/hooks/useFeatureFlag.d.ts +1 -0
  19. package/lib/posthog-react-native/src/hooks/useFeatureFlags.d.ts +3 -0
  20. package/lib/posthog-react-native/src/hooks/useLifecycleTracker.d.ts +2 -0
  21. package/lib/posthog-react-native/src/hooks/useNavigationTracker.d.ts +5 -0
  22. package/lib/posthog-react-native/src/hooks/usePostHog.d.ts +2 -0
  23. package/lib/posthog-react-native/src/legacy.d.ts +4 -0
  24. package/lib/posthog-react-native/src/optional-imports.d.ts +2 -0
  25. package/lib/posthog-react-native/src/posthog-rn.d.ts +18 -0
  26. package/lib/posthog-react-native/src/storage.d.ts +8 -0
  27. package/lib/posthog-react-native/src/types.d.ts +13 -0
  28. package/package.json +28 -52
  29. package/RNPostHog.podspec +0 -21
  30. package/android/build.gradle +0 -46
  31. package/android/src/main/AndroidManifest.xml +0 -1
  32. package/android/src/main/java/com/posthog/reactnative/core/RNPostHogModule.kt +0 -250
  33. package/android/src/main/java/com/posthog/reactnative/core/RNPostHogPackage.kt +0 -44
  34. package/build/cjs/__mocks__/bridge.d.ts +0 -14
  35. package/build/cjs/__mocks__/bridge.js +0 -15
  36. package/build/cjs/__mocks__/bridge.js.map +0 -1
  37. package/build/cjs/__tests__/bridge.spec.d.ts +0 -1
  38. package/build/cjs/__tests__/bridge.spec.js +0 -19
  39. package/build/cjs/__tests__/bridge.spec.js.map +0 -1
  40. package/build/cjs/__tests__/configuration.spec.d.ts +0 -1
  41. package/build/cjs/__tests__/configuration.spec.js +0 -131
  42. package/build/cjs/__tests__/configuration.spec.js.map +0 -1
  43. package/build/cjs/__tests__/index.spec.d.ts +0 -1
  44. package/build/cjs/__tests__/index.spec.js +0 -9
  45. package/build/cjs/__tests__/index.spec.js.map +0 -1
  46. package/build/cjs/__tests__/posthog.spec.d.ts +0 -1
  47. package/build/cjs/__tests__/posthog.spec.js +0 -193
  48. package/build/cjs/__tests__/posthog.spec.js.map +0 -1
  49. package/build/cjs/bridge.d.ts +0 -50
  50. package/build/cjs/bridge.js +0 -9
  51. package/build/cjs/bridge.js.map +0 -1
  52. package/build/cjs/configuration.d.ts +0 -3
  53. package/build/cjs/configuration.js +0 -94
  54. package/build/cjs/configuration.js.map +0 -1
  55. package/build/cjs/index.d.ts +0 -5
  56. package/build/cjs/index.js +0 -6
  57. package/build/cjs/index.js.map +0 -1
  58. package/build/cjs/make-pkg.d.ts +0 -1
  59. package/build/cjs/make-pkg.js +0 -5
  60. package/build/cjs/make-pkg.js.map +0 -1
  61. package/build/cjs/middleware.d.ts +0 -41
  62. package/build/cjs/middleware.js +0 -114
  63. package/build/cjs/middleware.js.map +0 -1
  64. package/build/cjs/posthog.d.ts +0 -228
  65. package/build/cjs/posthog.js +0 -309
  66. package/build/cjs/posthog.js.map +0 -1
  67. package/build/cjs/utils.d.ts +0 -1
  68. package/build/cjs/utils.js +0 -7
  69. package/build/cjs/utils.js.map +0 -1
  70. package/build/cjs/wrapper.d.ts +0 -22
  71. package/build/cjs/wrapper.js +0 -114
  72. package/build/cjs/wrapper.js.map +0 -1
  73. package/build/coverage/clover.xml +0 -169
  74. package/build/coverage/coverage-final.json +0 -8
  75. package/build/coverage/lcov-report/base.css +0 -212
  76. package/build/coverage/lcov-report/bridge.ts.html +0 -228
  77. package/build/coverage/lcov-report/configuration.ts.html +0 -228
  78. package/build/coverage/lcov-report/index.html +0 -151
  79. package/build/coverage/lcov-report/index.ts.html +0 -60
  80. package/build/coverage/lcov-report/middleware.ts.html +0 -429
  81. package/build/coverage/lcov-report/posthog.ts.html +0 -960
  82. package/build/coverage/lcov-report/prettify.css +0 -1
  83. package/build/coverage/lcov-report/prettify.js +0 -1
  84. package/build/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  85. package/build/coverage/lcov-report/sorter.js +0 -158
  86. package/build/coverage/lcov-report/utils.ts.html +0 -54
  87. package/build/coverage/lcov-report/wrapper.ts.html +0 -228
  88. package/build/coverage/lcov.info +0 -365
  89. package/build/esm/__mocks__/bridge.d.ts +0 -14
  90. package/build/esm/__mocks__/bridge.js +0 -13
  91. package/build/esm/__mocks__/bridge.js.map +0 -1
  92. package/build/esm/__tests__/bridge.spec.d.ts +0 -1
  93. package/build/esm/__tests__/bridge.spec.js +0 -19
  94. package/build/esm/__tests__/bridge.spec.js.map +0 -1
  95. package/build/esm/__tests__/configuration.spec.d.ts +0 -1
  96. package/build/esm/__tests__/configuration.spec.js +0 -129
  97. package/build/esm/__tests__/configuration.spec.js.map +0 -1
  98. package/build/esm/__tests__/index.spec.d.ts +0 -1
  99. package/build/esm/__tests__/index.spec.js +0 -7
  100. package/build/esm/__tests__/index.spec.js.map +0 -1
  101. package/build/esm/__tests__/posthog.spec.d.ts +0 -1
  102. package/build/esm/__tests__/posthog.spec.js +0 -191
  103. package/build/esm/__tests__/posthog.spec.js.map +0 -1
  104. package/build/esm/bridge.d.ts +0 -50
  105. package/build/esm/bridge.js +0 -7
  106. package/build/esm/bridge.js.map +0 -1
  107. package/build/esm/configuration.d.ts +0 -3
  108. package/build/esm/configuration.js +0 -92
  109. package/build/esm/configuration.js.map +0 -1
  110. package/build/esm/index.d.ts +0 -5
  111. package/build/esm/index.js +0 -4
  112. package/build/esm/index.js.map +0 -1
  113. package/build/esm/make-pkg.d.ts +0 -1
  114. package/build/esm/make-pkg.js +0 -3
  115. package/build/esm/make-pkg.js.map +0 -1
  116. package/build/esm/middleware.d.ts +0 -41
  117. package/build/esm/middleware.js +0 -112
  118. package/build/esm/middleware.js.map +0 -1
  119. package/build/esm/posthog.d.ts +0 -228
  120. package/build/esm/posthog.js +0 -307
  121. package/build/esm/posthog.js.map +0 -1
  122. package/build/esm/utils.d.ts +0 -1
  123. package/build/esm/utils.js +0 -4
  124. package/build/esm/utils.js.map +0 -1
  125. package/build/esm/wrapper.d.ts +0 -22
  126. package/build/esm/wrapper.js +0 -112
  127. package/build/esm/wrapper.js.map +0 -1
  128. package/build/package.json +0 -3
  129. package/ios/RNPostHog/RNPostHog.h +0 -9
  130. package/ios/RNPostHog/RNPostHog.m +0 -128
  131. package/ios/RNPostHog.xcodeproj/project.pbxproj +0 -336
  132. package/ios/RNPostHog.xcodeproj/project.xcworkspace/contents.xcworkspacedata +0 -7
  133. package/src/__mocks__/bridge.ts +0 -12
  134. package/src/__tests__/bridge.spec.ts +0 -23
  135. package/src/__tests__/configuration.spec.ts +0 -79
  136. package/src/__tests__/index.spec.ts +0 -7
  137. package/src/__tests__/posthog.spec.ts +0 -108
  138. package/src/bridge.ts +0 -61
  139. package/src/configuration.ts +0 -61
  140. package/src/index.ts +0 -5
  141. package/src/make-pkg.ts +0 -3
  142. package/src/middleware.ts +0 -128
  143. package/src/modules.d.ts +0 -2
  144. package/src/posthog.ts +0 -305
  145. package/src/utils.ts +0 -3
  146. package/src/wrapper.ts +0 -61
@@ -0,0 +1,1804 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var reactNative = require('react-native');
6
+ var ExpoApplication = require('expo-application');
7
+ var ExpoDevice = require('expo-device');
8
+ var ExpoLocalization = require('expo-localization');
9
+ var FileSystem = require('expo-file-system');
10
+ var React = require('react');
11
+
12
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
13
+
14
+ function _interopNamespace(e) {
15
+ if (e && e.__esModule) return e;
16
+ var n = Object.create(null);
17
+ if (e) {
18
+ Object.keys(e).forEach(function (k) {
19
+ if (k !== 'default') {
20
+ var d = Object.getOwnPropertyDescriptor(e, k);
21
+ Object.defineProperty(n, k, d.get ? d : {
22
+ enumerable: true,
23
+ get: function () { return e[k]; }
24
+ });
25
+ }
26
+ });
27
+ }
28
+ n["default"] = e;
29
+ return Object.freeze(n);
30
+ }
31
+
32
+ var ExpoApplication__namespace = /*#__PURE__*/_interopNamespace(ExpoApplication);
33
+ var ExpoDevice__namespace = /*#__PURE__*/_interopNamespace(ExpoDevice);
34
+ var ExpoLocalization__namespace = /*#__PURE__*/_interopNamespace(ExpoLocalization);
35
+ var FileSystem__namespace = /*#__PURE__*/_interopNamespace(FileSystem);
36
+ var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
37
+
38
+ /******************************************************************************
39
+ Copyright (c) Microsoft Corporation.
40
+
41
+ Permission to use, copy, modify, and/or distribute this software for any
42
+ purpose with or without fee is hereby granted.
43
+
44
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
45
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
46
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
47
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
48
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
49
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
50
+ PERFORMANCE OF THIS SOFTWARE.
51
+ ***************************************************************************** */
52
+ /* global Reflect, Promise */
53
+ var extendStatics = function (d, b) {
54
+ extendStatics = Object.setPrototypeOf ||
55
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
56
+ function (d, b) { for (var p in b)
57
+ if (Object.prototype.hasOwnProperty.call(b, p))
58
+ d[p] = b[p]; };
59
+ return extendStatics(d, b);
60
+ };
61
+ function __extends(d, b) {
62
+ if (typeof b !== "function" && b !== null)
63
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
64
+ extendStatics(d, b);
65
+ function __() { this.constructor = d; }
66
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
67
+ }
68
+ var __assign = function () {
69
+ __assign = Object.assign || function __assign(t) {
70
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
71
+ s = arguments[i];
72
+ for (var p in s)
73
+ if (Object.prototype.hasOwnProperty.call(s, p))
74
+ t[p] = s[p];
75
+ }
76
+ return t;
77
+ };
78
+ return __assign.apply(this, arguments);
79
+ };
80
+ function __awaiter(thisArg, _arguments, P, generator) {
81
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
82
+ return new (P || (P = Promise))(function (resolve, reject) {
83
+ function fulfilled(value) { try {
84
+ step(generator.next(value));
85
+ }
86
+ catch (e) {
87
+ reject(e);
88
+ } }
89
+ function rejected(value) { try {
90
+ step(generator["throw"](value));
91
+ }
92
+ catch (e) {
93
+ reject(e);
94
+ } }
95
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
96
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
97
+ });
98
+ }
99
+ function __generator(thisArg, body) {
100
+ var _ = { label: 0, sent: function () { if (t[0] & 1)
101
+ throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
102
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
103
+ function verb(n) { return function (v) { return step([n, v]); }; }
104
+ function step(op) {
105
+ if (f)
106
+ throw new TypeError("Generator is already executing.");
107
+ while (_)
108
+ try {
109
+ 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)
110
+ return t;
111
+ if (y = 0, t)
112
+ op = [op[0] & 2, t.value];
113
+ switch (op[0]) {
114
+ case 0:
115
+ case 1:
116
+ t = op;
117
+ break;
118
+ case 4:
119
+ _.label++;
120
+ return { value: op[1], done: false };
121
+ case 5:
122
+ _.label++;
123
+ y = op[1];
124
+ op = [0];
125
+ continue;
126
+ case 7:
127
+ op = _.ops.pop();
128
+ _.trys.pop();
129
+ continue;
130
+ default:
131
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
132
+ _ = 0;
133
+ continue;
134
+ }
135
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
136
+ _.label = op[1];
137
+ break;
138
+ }
139
+ if (op[0] === 6 && _.label < t[1]) {
140
+ _.label = t[1];
141
+ t = op;
142
+ break;
143
+ }
144
+ if (t && _.label < t[2]) {
145
+ _.label = t[2];
146
+ _.ops.push(op);
147
+ break;
148
+ }
149
+ if (t[2])
150
+ _.ops.pop();
151
+ _.trys.pop();
152
+ continue;
153
+ }
154
+ op = body.call(thisArg, _);
155
+ }
156
+ catch (e) {
157
+ op = [6, e];
158
+ y = 0;
159
+ }
160
+ finally {
161
+ f = t = 0;
162
+ }
163
+ if (op[0] & 5)
164
+ throw op[1];
165
+ return { value: op[0] ? op[1] : void 0, done: true };
166
+ }
167
+ }
168
+
169
+ var PostHogPersistedProperty;
170
+ (function (PostHogPersistedProperty) {
171
+ PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
172
+ PostHogPersistedProperty["DistinctId"] = "distinct_id";
173
+ PostHogPersistedProperty["Props"] = "props";
174
+ PostHogPersistedProperty["FeatureFlags"] = "feature_flags";
175
+ PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
176
+ PostHogPersistedProperty["Queue"] = "queue";
177
+ PostHogPersistedProperty["OptedOut"] = "opted_out";
178
+ PostHogPersistedProperty["SessionId"] = "session_id";
179
+ PostHogPersistedProperty["SessionLastTimestamp"] = "session_timestamp";
180
+ })(PostHogPersistedProperty || (PostHogPersistedProperty = {}));
181
+
182
+ function assert(truthyValue, message) {
183
+ if (!truthyValue) {
184
+ throw new Error(message);
185
+ }
186
+ }
187
+ function removeTrailingSlash(url) {
188
+ return url === null || url === void 0 ? void 0 : url.replace(/\/+$/, '');
189
+ }
190
+ function retriable(fn, props) {
191
+ if (props === void 0) { props = {}; }
192
+ return __awaiter(this, void 0, void 0, function () {
193
+ var _a, retryCount, _b, retryDelay, _c, retryCheck, lastError, i, res, e_1;
194
+ return __generator(this, function (_d) {
195
+ switch (_d.label) {
196
+ case 0:
197
+ _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;
198
+ lastError = null;
199
+ i = 0;
200
+ _d.label = 1;
201
+ case 1:
202
+ if (!(i < retryCount + 1)) return [3 /*break*/, 8];
203
+ _d.label = 2;
204
+ case 2:
205
+ _d.trys.push([2, 4, , 5]);
206
+ return [4 /*yield*/, fn()];
207
+ case 3:
208
+ res = _d.sent();
209
+ return [2 /*return*/, res];
210
+ case 4:
211
+ e_1 = _d.sent();
212
+ lastError = e_1;
213
+ if (!retryCheck(e_1)) {
214
+ throw e_1;
215
+ }
216
+ return [3 /*break*/, 5];
217
+ case 5: return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, retryDelay); })];
218
+ case 6:
219
+ _d.sent();
220
+ _d.label = 7;
221
+ case 7:
222
+ i++;
223
+ return [3 /*break*/, 1];
224
+ case 8: throw lastError;
225
+ }
226
+ });
227
+ });
228
+ }
229
+ // https://stackoverflow.com/a/8809472
230
+ function generateUUID(globalThis) {
231
+ // Public Domain/MIT
232
+ var d = new Date().getTime(); //Timestamp
233
+ var d2 = (globalThis && globalThis.performance && globalThis.performance.now && globalThis.performance.now() * 1000) || 0; //Time in microseconds since page-load or 0 if unsupported
234
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
235
+ var r = Math.random() * 16; //random number between 0 and 16
236
+ if (d > 0) {
237
+ //Use timestamp until depleted
238
+ r = (d + r) % 16 | 0;
239
+ d = Math.floor(d / 16);
240
+ }
241
+ else {
242
+ //Use microseconds since page-load if supported
243
+ r = (d2 + r) % 16 | 0;
244
+ d2 = Math.floor(d2 / 16);
245
+ }
246
+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
247
+ });
248
+ }
249
+ function currentTimestamp() {
250
+ return new Date().getTime();
251
+ }
252
+ function currentISOTime() {
253
+ return new Date().toISOString();
254
+ }
255
+ function safeSetTimeout(fn, timeout) {
256
+ // NOTE: we use this so rarely that it is totally fine to do `safeSetTimeout(fn, 0)``
257
+ // rather than setImmediate.
258
+ var t = setTimeout(fn, timeout);
259
+ // We unref if available to prevent Node.js hanging on exit
260
+ (t === null || t === void 0 ? void 0 : t.unref) && (t === null || t === void 0 ? void 0 : t.unref());
261
+ return t;
262
+ }
263
+
264
+ // Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>
265
+ // This work is free. You can redistribute it and/or modify it
266
+ // under the terms of the WTFPL, Version 2
267
+ // For more information see LICENSE.txt or http://www.wtfpl.net/
268
+ //
269
+ // For more information, the home page:
270
+ // http://pieroxy.net/blog/pages/lz-string/testing.html
271
+ //
272
+ // LZ-based compression algorithm, version 1.4.4
273
+ // private property
274
+ var f = String.fromCharCode;
275
+ var keyStrBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
276
+ var baseReverseDic = {};
277
+ function getBaseValue(alphabet, character) {
278
+ if (!baseReverseDic[alphabet]) {
279
+ baseReverseDic[alphabet] = {};
280
+ for (var i = 0; i < alphabet.length; i++) {
281
+ baseReverseDic[alphabet][alphabet.charAt(i)] = i;
282
+ }
283
+ }
284
+ return baseReverseDic[alphabet][character];
285
+ }
286
+ var LZString = {
287
+ compressToBase64: function (input) {
288
+ if (input == null) {
289
+ return '';
290
+ }
291
+ var res = LZString._compress(input, 6, function (a) {
292
+ return keyStrBase64.charAt(a);
293
+ });
294
+ switch (res.length % 4 // To produce valid Base64
295
+ ) {
296
+ default: // When could this happen ?
297
+ case 0:
298
+ return res;
299
+ case 1:
300
+ return res + '===';
301
+ case 2:
302
+ return res + '==';
303
+ case 3:
304
+ return res + '=';
305
+ }
306
+ },
307
+ decompressFromBase64: function (input) {
308
+ if (input == null) {
309
+ return '';
310
+ }
311
+ if (input == '') {
312
+ return null;
313
+ }
314
+ return LZString._decompress(input.length, 32, function (index) {
315
+ return getBaseValue(keyStrBase64, input.charAt(index));
316
+ });
317
+ },
318
+ compress: function (uncompressed) {
319
+ return LZString._compress(uncompressed, 16, function (a) {
320
+ return f(a);
321
+ });
322
+ },
323
+ _compress: function (uncompressed, bitsPerChar, getCharFromInt) {
324
+ if (uncompressed == null) {
325
+ return '';
326
+ }
327
+ var context_dictionary = {}, context_dictionaryToCreate = {}, context_data = [];
328
+ var i, value, context_c = '', context_wc = '', context_w = '', context_enlargeIn = 2, // Compensate for the first entry which should not count
329
+ context_dictSize = 3, context_numBits = 2, context_data_val = 0, context_data_position = 0, ii;
330
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
331
+ context_c = uncompressed.charAt(ii);
332
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
333
+ context_dictionary[context_c] = context_dictSize++;
334
+ context_dictionaryToCreate[context_c] = true;
335
+ }
336
+ context_wc = context_w + context_c;
337
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) {
338
+ context_w = context_wc;
339
+ }
340
+ else {
341
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
342
+ if (context_w.charCodeAt(0) < 256) {
343
+ for (i = 0; i < context_numBits; i++) {
344
+ context_data_val = context_data_val << 1;
345
+ if (context_data_position == bitsPerChar - 1) {
346
+ context_data_position = 0;
347
+ context_data.push(getCharFromInt(context_data_val));
348
+ context_data_val = 0;
349
+ }
350
+ else {
351
+ context_data_position++;
352
+ }
353
+ }
354
+ value = context_w.charCodeAt(0);
355
+ for (i = 0; i < 8; i++) {
356
+ context_data_val = (context_data_val << 1) | (value & 1);
357
+ if (context_data_position == bitsPerChar - 1) {
358
+ context_data_position = 0;
359
+ context_data.push(getCharFromInt(context_data_val));
360
+ context_data_val = 0;
361
+ }
362
+ else {
363
+ context_data_position++;
364
+ }
365
+ value = value >> 1;
366
+ }
367
+ }
368
+ else {
369
+ value = 1;
370
+ for (i = 0; i < context_numBits; i++) {
371
+ context_data_val = (context_data_val << 1) | value;
372
+ if (context_data_position == bitsPerChar - 1) {
373
+ context_data_position = 0;
374
+ context_data.push(getCharFromInt(context_data_val));
375
+ context_data_val = 0;
376
+ }
377
+ else {
378
+ context_data_position++;
379
+ }
380
+ value = 0;
381
+ }
382
+ value = context_w.charCodeAt(0);
383
+ for (i = 0; i < 16; i++) {
384
+ context_data_val = (context_data_val << 1) | (value & 1);
385
+ if (context_data_position == bitsPerChar - 1) {
386
+ context_data_position = 0;
387
+ context_data.push(getCharFromInt(context_data_val));
388
+ context_data_val = 0;
389
+ }
390
+ else {
391
+ context_data_position++;
392
+ }
393
+ value = value >> 1;
394
+ }
395
+ }
396
+ context_enlargeIn--;
397
+ if (context_enlargeIn == 0) {
398
+ context_enlargeIn = Math.pow(2, context_numBits);
399
+ context_numBits++;
400
+ }
401
+ delete context_dictionaryToCreate[context_w];
402
+ }
403
+ else {
404
+ value = context_dictionary[context_w];
405
+ for (i = 0; i < context_numBits; i++) {
406
+ context_data_val = (context_data_val << 1) | (value & 1);
407
+ if (context_data_position == bitsPerChar - 1) {
408
+ context_data_position = 0;
409
+ context_data.push(getCharFromInt(context_data_val));
410
+ context_data_val = 0;
411
+ }
412
+ else {
413
+ context_data_position++;
414
+ }
415
+ value = value >> 1;
416
+ }
417
+ }
418
+ context_enlargeIn--;
419
+ if (context_enlargeIn == 0) {
420
+ context_enlargeIn = Math.pow(2, context_numBits);
421
+ context_numBits++;
422
+ }
423
+ // Add wc to the dictionary.
424
+ context_dictionary[context_wc] = context_dictSize++;
425
+ context_w = String(context_c);
426
+ }
427
+ }
428
+ // Output the code for w.
429
+ if (context_w !== '') {
430
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
431
+ if (context_w.charCodeAt(0) < 256) {
432
+ for (i = 0; i < context_numBits; i++) {
433
+ context_data_val = context_data_val << 1;
434
+ if (context_data_position == bitsPerChar - 1) {
435
+ context_data_position = 0;
436
+ context_data.push(getCharFromInt(context_data_val));
437
+ context_data_val = 0;
438
+ }
439
+ else {
440
+ context_data_position++;
441
+ }
442
+ }
443
+ value = context_w.charCodeAt(0);
444
+ for (i = 0; i < 8; i++) {
445
+ context_data_val = (context_data_val << 1) | (value & 1);
446
+ if (context_data_position == bitsPerChar - 1) {
447
+ context_data_position = 0;
448
+ context_data.push(getCharFromInt(context_data_val));
449
+ context_data_val = 0;
450
+ }
451
+ else {
452
+ context_data_position++;
453
+ }
454
+ value = value >> 1;
455
+ }
456
+ }
457
+ else {
458
+ value = 1;
459
+ for (i = 0; i < context_numBits; i++) {
460
+ context_data_val = (context_data_val << 1) | value;
461
+ if (context_data_position == bitsPerChar - 1) {
462
+ context_data_position = 0;
463
+ context_data.push(getCharFromInt(context_data_val));
464
+ context_data_val = 0;
465
+ }
466
+ else {
467
+ context_data_position++;
468
+ }
469
+ value = 0;
470
+ }
471
+ value = context_w.charCodeAt(0);
472
+ for (i = 0; i < 16; i++) {
473
+ context_data_val = (context_data_val << 1) | (value & 1);
474
+ if (context_data_position == bitsPerChar - 1) {
475
+ context_data_position = 0;
476
+ context_data.push(getCharFromInt(context_data_val));
477
+ context_data_val = 0;
478
+ }
479
+ else {
480
+ context_data_position++;
481
+ }
482
+ value = value >> 1;
483
+ }
484
+ }
485
+ context_enlargeIn--;
486
+ if (context_enlargeIn == 0) {
487
+ context_enlargeIn = Math.pow(2, context_numBits);
488
+ context_numBits++;
489
+ }
490
+ delete context_dictionaryToCreate[context_w];
491
+ }
492
+ else {
493
+ value = context_dictionary[context_w];
494
+ for (i = 0; i < context_numBits; i++) {
495
+ context_data_val = (context_data_val << 1) | (value & 1);
496
+ if (context_data_position == bitsPerChar - 1) {
497
+ context_data_position = 0;
498
+ context_data.push(getCharFromInt(context_data_val));
499
+ context_data_val = 0;
500
+ }
501
+ else {
502
+ context_data_position++;
503
+ }
504
+ value = value >> 1;
505
+ }
506
+ }
507
+ context_enlargeIn--;
508
+ if (context_enlargeIn == 0) {
509
+ context_enlargeIn = Math.pow(2, context_numBits);
510
+ context_numBits++;
511
+ }
512
+ }
513
+ // Mark the end of the stream
514
+ value = 2;
515
+ for (i = 0; i < context_numBits; i++) {
516
+ context_data_val = (context_data_val << 1) | (value & 1);
517
+ if (context_data_position == bitsPerChar - 1) {
518
+ context_data_position = 0;
519
+ context_data.push(getCharFromInt(context_data_val));
520
+ context_data_val = 0;
521
+ }
522
+ else {
523
+ context_data_position++;
524
+ }
525
+ value = value >> 1;
526
+ }
527
+ // Flush the last char
528
+ while (true) {
529
+ context_data_val = context_data_val << 1;
530
+ if (context_data_position == bitsPerChar - 1) {
531
+ context_data.push(getCharFromInt(context_data_val));
532
+ break;
533
+ }
534
+ else {
535
+ context_data_position++;
536
+ }
537
+ }
538
+ return context_data.join('');
539
+ },
540
+ decompress: function (compressed) {
541
+ if (compressed == null) {
542
+ return '';
543
+ }
544
+ if (compressed == '') {
545
+ return null;
546
+ }
547
+ return LZString._decompress(compressed.length, 32768, function (index) {
548
+ return compressed.charCodeAt(index);
549
+ });
550
+ },
551
+ _decompress: function (length, resetValue, getNextValue) {
552
+ var dictionary = [], result = [], data = { val: getNextValue(0), position: resetValue, index: 1 };
553
+ var enlargeIn = 4, dictSize = 4, numBits = 3, entry = '', i, w, bits, resb, maxpower, power, c;
554
+ for (i = 0; i < 3; i += 1) {
555
+ dictionary[i] = i;
556
+ }
557
+ bits = 0;
558
+ maxpower = Math.pow(2, 2);
559
+ power = 1;
560
+ while (power != maxpower) {
561
+ resb = data.val & data.position;
562
+ data.position >>= 1;
563
+ if (data.position == 0) {
564
+ data.position = resetValue;
565
+ data.val = getNextValue(data.index++);
566
+ }
567
+ bits |= (resb > 0 ? 1 : 0) * power;
568
+ power <<= 1;
569
+ }
570
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
571
+ switch ((bits)) {
572
+ case 0:
573
+ bits = 0;
574
+ maxpower = Math.pow(2, 8);
575
+ power = 1;
576
+ while (power != maxpower) {
577
+ resb = data.val & data.position;
578
+ data.position >>= 1;
579
+ if (data.position == 0) {
580
+ data.position = resetValue;
581
+ data.val = getNextValue(data.index++);
582
+ }
583
+ bits |= (resb > 0 ? 1 : 0) * power;
584
+ power <<= 1;
585
+ }
586
+ c = f(bits);
587
+ break;
588
+ case 1:
589
+ bits = 0;
590
+ maxpower = Math.pow(2, 16);
591
+ power = 1;
592
+ while (power != maxpower) {
593
+ resb = data.val & data.position;
594
+ data.position >>= 1;
595
+ if (data.position == 0) {
596
+ data.position = resetValue;
597
+ data.val = getNextValue(data.index++);
598
+ }
599
+ bits |= (resb > 0 ? 1 : 0) * power;
600
+ power <<= 1;
601
+ }
602
+ c = f(bits);
603
+ break;
604
+ case 2:
605
+ return '';
606
+ }
607
+ dictionary[3] = c;
608
+ w = c;
609
+ result.push(c);
610
+ while (true) {
611
+ if (data.index > length) {
612
+ return '';
613
+ }
614
+ bits = 0;
615
+ maxpower = Math.pow(2, numBits);
616
+ power = 1;
617
+ while (power != maxpower) {
618
+ resb = data.val & data.position;
619
+ data.position >>= 1;
620
+ if (data.position == 0) {
621
+ data.position = resetValue;
622
+ data.val = getNextValue(data.index++);
623
+ }
624
+ bits |= (resb > 0 ? 1 : 0) * power;
625
+ power <<= 1;
626
+ }
627
+ switch ((c = bits)) {
628
+ case 0:
629
+ bits = 0;
630
+ maxpower = Math.pow(2, 8);
631
+ power = 1;
632
+ while (power != maxpower) {
633
+ resb = data.val & data.position;
634
+ data.position >>= 1;
635
+ if (data.position == 0) {
636
+ data.position = resetValue;
637
+ data.val = getNextValue(data.index++);
638
+ }
639
+ bits |= (resb > 0 ? 1 : 0) * power;
640
+ power <<= 1;
641
+ }
642
+ dictionary[dictSize++] = f(bits);
643
+ c = dictSize - 1;
644
+ enlargeIn--;
645
+ break;
646
+ case 1:
647
+ bits = 0;
648
+ maxpower = Math.pow(2, 16);
649
+ power = 1;
650
+ while (power != maxpower) {
651
+ resb = data.val & data.position;
652
+ data.position >>= 1;
653
+ if (data.position == 0) {
654
+ data.position = resetValue;
655
+ data.val = getNextValue(data.index++);
656
+ }
657
+ bits |= (resb > 0 ? 1 : 0) * power;
658
+ power <<= 1;
659
+ }
660
+ dictionary[dictSize++] = f(bits);
661
+ c = dictSize - 1;
662
+ enlargeIn--;
663
+ break;
664
+ case 2:
665
+ return result.join('');
666
+ }
667
+ if (enlargeIn == 0) {
668
+ enlargeIn = Math.pow(2, numBits);
669
+ numBits++;
670
+ }
671
+ if (dictionary[c]) {
672
+ entry = dictionary[c];
673
+ }
674
+ else {
675
+ if (c === dictSize) {
676
+ entry = w + w.charAt(0);
677
+ }
678
+ else {
679
+ return null;
680
+ }
681
+ }
682
+ result.push(entry);
683
+ // Add w+entry[0] to the dictionary.
684
+ dictionary[dictSize++] = w + entry.charAt(0);
685
+ enlargeIn--;
686
+ w = entry;
687
+ if (enlargeIn == 0) {
688
+ enlargeIn = Math.pow(2, numBits);
689
+ numBits++;
690
+ }
691
+ }
692
+ },
693
+ };
694
+
695
+ var SimpleEventEmitter = /** @class */ (function () {
696
+ function SimpleEventEmitter() {
697
+ this.events = {};
698
+ this.events = {};
699
+ }
700
+ SimpleEventEmitter.prototype.on = function (event, listener) {
701
+ var _this = this;
702
+ if (!this.events[event]) {
703
+ this.events[event] = [];
704
+ }
705
+ this.events[event].push(listener);
706
+ return function () {
707
+ _this.events[event] = _this.events[event].filter(function (x) { return x !== listener; });
708
+ };
709
+ };
710
+ SimpleEventEmitter.prototype.emit = function (event, payload) {
711
+ for (var _i = 0, _a = this.events[event] || []; _i < _a.length; _i++) {
712
+ var listener = _a[_i];
713
+ listener(payload);
714
+ }
715
+ for (var _b = 0, _c = this.events['*'] || []; _b < _c.length; _b++) {
716
+ var listener = _c[_b];
717
+ listener(event, payload);
718
+ }
719
+ };
720
+ return SimpleEventEmitter;
721
+ }());
722
+
723
+ var PostHogCore = /** @class */ (function () {
724
+ function PostHogCore(apiKey, options) {
725
+ var _this = this;
726
+ var _a, _b, _c, _d, _e;
727
+ this.flagCallReported = {};
728
+ // internal
729
+ this._events = new SimpleEventEmitter();
730
+ assert(apiKey, "You must pass your PostHog project's api key.");
731
+ this.apiKey = apiKey;
732
+ this.host = removeTrailingSlash((options === null || options === void 0 ? void 0 : options.host) || 'https://app.posthog.com');
733
+ this.flushAt = (options === null || options === void 0 ? void 0 : options.flushAt) ? Math.max(options === null || options === void 0 ? void 0 : options.flushAt, 1) : 20;
734
+ this.flushInterval = (_a = options === null || options === void 0 ? void 0 : options.flushInterval) !== null && _a !== void 0 ? _a : 10000;
735
+ this.captureMode = (options === null || options === void 0 ? void 0 : options.captureMode) || 'form';
736
+ this.sendFeatureFlagEvent = (_b = options === null || options === void 0 ? void 0 : options.sendFeatureFlagEvent) !== null && _b !== void 0 ? _b : true;
737
+ // If enable is explicitly set to false we override the optout
738
+ this._optoutOverride = (options === null || options === void 0 ? void 0 : options.enable) === false;
739
+ this._retryOptions = {
740
+ retryCount: (_c = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _c !== void 0 ? _c : 3,
741
+ retryDelay: (_d = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _d !== void 0 ? _d : 3000,
742
+ };
743
+ this._sessionExpirationTimeSeconds = (_e = options === null || options === void 0 ? void 0 : options.sessionExpirationTimeSeconds) !== null && _e !== void 0 ? _e : 1800; // 30 minutes
744
+ // NOTE: It is important we don't initiate anything in the constructor as some async IO may still be underway on the parent
745
+ if ((options === null || options === void 0 ? void 0 : options.preloadFeatureFlags) !== false) {
746
+ safeSetTimeout(function () {
747
+ void _this.reloadFeatureFlagsAsync();
748
+ }, 1);
749
+ }
750
+ }
751
+ PostHogCore.prototype.getCommonEventProperties = function () {
752
+ var featureFlags = this.getFeatureFlags();
753
+ return {
754
+ $lib: this.getLibraryId(),
755
+ $lib_version: this.getLibraryVersion(),
756
+ $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined,
757
+ $enabled_feature_flags: featureFlags,
758
+ };
759
+ };
760
+ Object.defineProperty(PostHogCore.prototype, "props", {
761
+ // NOTE: Props are lazy loaded from localstorage hence the complex getter setter logic
762
+ get: function () {
763
+ if (!this._props) {
764
+ this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
765
+ }
766
+ return this._props || {};
767
+ },
768
+ set: function (val) {
769
+ this._props = val;
770
+ },
771
+ enumerable: false,
772
+ configurable: true
773
+ });
774
+ Object.defineProperty(PostHogCore.prototype, "optedOut", {
775
+ get: function () {
776
+ var _a, _b;
777
+ return (_b = (_a = this.getPersistedProperty(PostHogPersistedProperty.OptedOut)) !== null && _a !== void 0 ? _a : this._optoutOverride) !== null && _b !== void 0 ? _b : false;
778
+ },
779
+ enumerable: false,
780
+ configurable: true
781
+ });
782
+ PostHogCore.prototype.optIn = function () {
783
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
784
+ };
785
+ PostHogCore.prototype.optOut = function () {
786
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
787
+ };
788
+ PostHogCore.prototype.on = function (event, cb) {
789
+ return this._events.on(event, cb);
790
+ };
791
+ PostHogCore.prototype.reset = function () {
792
+ for (var key in PostHogPersistedProperty) {
793
+ this.setPersistedProperty(PostHogPersistedProperty[key], null);
794
+ }
795
+ };
796
+ PostHogCore.prototype.debug = function (enabled) {
797
+ var _a;
798
+ if (enabled === void 0) { enabled = true; }
799
+ (_a = this.removeDebugCallback) === null || _a === void 0 ? void 0 : _a.call(this);
800
+ if (enabled) {
801
+ this.removeDebugCallback = this.on('*', function (event, payload) { return console.log('PostHog Debug', event, payload); });
802
+ }
803
+ };
804
+ PostHogCore.prototype.buildPayload = function (payload) {
805
+ return {
806
+ distinct_id: payload.distinct_id || this.getDistinctId(),
807
+ event: payload.event,
808
+ properties: __assign(__assign(__assign(__assign({}, this.props), (payload.properties || {})), this.getCommonEventProperties()), { $session_id: this.getSessionId() }),
809
+ };
810
+ };
811
+ PostHogCore.prototype.getSessionId = function () {
812
+ var sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
813
+ var sessionTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
814
+ if (!sessionId || Date.now() - sessionTimestamp > this._sessionExpirationTimeSeconds * 1000) {
815
+ sessionId = generateUUID(globalThis);
816
+ this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);
817
+ }
818
+ this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, Date.now());
819
+ return sessionId;
820
+ };
821
+ PostHogCore.prototype.resetSessionId = function () {
822
+ this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);
823
+ };
824
+ PostHogCore.prototype.getAnonymousId = function () {
825
+ var anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
826
+ if (!anonId) {
827
+ anonId = generateUUID(globalThis);
828
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId);
829
+ }
830
+ return anonId;
831
+ };
832
+ PostHogCore.prototype.getDistinctId = function () {
833
+ return this.getPersistedProperty(PostHogPersistedProperty.DistinctId) || this.getAnonymousId();
834
+ };
835
+ PostHogCore.prototype.register = function (properties) {
836
+ this.props = __assign(__assign({}, this.props), properties);
837
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
838
+ };
839
+ PostHogCore.prototype.unregister = function (property) {
840
+ delete this.props[property];
841
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
842
+ };
843
+ /***
844
+ *** TRACKING
845
+ ***/
846
+ PostHogCore.prototype.identify = function (distinctId, properties) {
847
+ var previousDistinctId = this.getDistinctId();
848
+ distinctId = distinctId || previousDistinctId;
849
+ if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
850
+ this.groups(properties.$groups);
851
+ }
852
+ var payload = __assign(__assign({}, this.buildPayload({
853
+ distinct_id: distinctId,
854
+ event: '$identify',
855
+ properties: __assign(__assign({}, (properties || {})), { $anon_distinct_id: this.getAnonymousId() }),
856
+ })), { $set: properties });
857
+ if (distinctId !== previousDistinctId) {
858
+ // We keep the AnonymousId to be used by decide calls and identify to link the previousId
859
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);
860
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
861
+ if (this.getFeatureFlags()) {
862
+ void this.reloadFeatureFlagsAsync();
863
+ }
864
+ }
865
+ this.enqueue('identify', payload);
866
+ return this;
867
+ };
868
+ PostHogCore.prototype.capture = function (event, properties) {
869
+ if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
870
+ this.groups(properties.$groups);
871
+ }
872
+ var payload = this.buildPayload({ event: event, properties: properties });
873
+ this.enqueue('capture', payload);
874
+ return this;
875
+ };
876
+ PostHogCore.prototype.alias = function (alias) {
877
+ var distinctId = this.getDistinctId();
878
+ var payload = this.buildPayload({
879
+ event: '$create_alias',
880
+ properties: {
881
+ distinct_id: distinctId,
882
+ alias: alias,
883
+ },
884
+ });
885
+ this.enqueue('alias', payload);
886
+ return this;
887
+ };
888
+ PostHogCore.prototype.autocapture = function (eventType, elements, properties) {
889
+ if (properties === void 0) { properties = {}; }
890
+ var payload = this.buildPayload({
891
+ event: '$autocapture',
892
+ properties: __assign(__assign({}, properties), { $event_type: eventType, $elements: elements }),
893
+ });
894
+ this.enqueue('autocapture', payload);
895
+ return this;
896
+ };
897
+ /***
898
+ *** GROUPS
899
+ ***/
900
+ PostHogCore.prototype.groups = function (groups) {
901
+ // Get persisted groups
902
+ var existingGroups = this.props.$groups || {};
903
+ // NOTE: Should we do the same for groups listed in identify / capture?
904
+ this.register({
905
+ $groups: __assign(__assign({}, existingGroups), groups),
906
+ });
907
+ if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; }) && this.getFeatureFlags()) {
908
+ void this.reloadFeatureFlagsAsync();
909
+ }
910
+ return this;
911
+ };
912
+ PostHogCore.prototype.group = function (groupType, groupKey, groupProperties) {
913
+ var _a;
914
+ this.groups((_a = {},
915
+ _a[groupType] = groupKey,
916
+ _a));
917
+ if (groupProperties) {
918
+ this.groupIdentify(groupType, groupKey, groupProperties);
919
+ }
920
+ return this;
921
+ };
922
+ PostHogCore.prototype.groupIdentify = function (groupType, groupKey, groupProperties) {
923
+ var payload = {
924
+ event: '$groupidentify',
925
+ distinctId: "$".concat(groupType, "_").concat(groupKey),
926
+ properties: __assign({ $group_type: groupType, $group_key: groupKey, $group_set: groupProperties || {} }, this.getCommonEventProperties()),
927
+ };
928
+ this.enqueue('capture', payload);
929
+ return this;
930
+ };
931
+ /***
932
+ *** FEATURE FLAGS
933
+ ***/
934
+ PostHogCore.prototype.decideAsync = function () {
935
+ if (this._decideResponsePromise) {
936
+ return this._decideResponsePromise;
937
+ }
938
+ return this._decideAsync();
939
+ };
940
+ PostHogCore.prototype._decideAsync = function () {
941
+ return __awaiter(this, void 0, void 0, function () {
942
+ var url, distinctId, groups, fetchOptions;
943
+ var _this = this;
944
+ return __generator(this, function (_a) {
945
+ url = "".concat(this.host, "/decide/?v=2");
946
+ distinctId = this.getDistinctId();
947
+ groups = this.props.$groups || {};
948
+ fetchOptions = {
949
+ method: 'POST',
950
+ headers: { 'Content-Type': 'application/json' },
951
+ body: JSON.stringify({
952
+ token: this.apiKey,
953
+ distinct_id: distinctId,
954
+ $anon_distinct_id: this.getAnonymousId(),
955
+ groups: groups,
956
+ }),
957
+ };
958
+ this._decideResponsePromise = this.fetchWithRetry(url, fetchOptions)
959
+ .then(function (r) { return r.json(); })
960
+ .then(function (res) {
961
+ if (res.featureFlags) {
962
+ _this.setPersistedProperty(PostHogPersistedProperty.FeatureFlags, res.featureFlags);
963
+ _this._events.emit('featureflags', res.featureFlags);
964
+ }
965
+ return res;
966
+ })
967
+ .finally(function () {
968
+ _this._decideResponsePromise = undefined;
969
+ });
970
+ return [2 /*return*/, this._decideResponsePromise];
971
+ });
972
+ });
973
+ };
974
+ PostHogCore.prototype.getFeatureFlag = function (key, defaultResult) {
975
+ var _a;
976
+ if (defaultResult === void 0) { defaultResult = false; }
977
+ var featureFlags = this.getFeatureFlags();
978
+ if (!featureFlags) {
979
+ // If we haven't loaded flags yet we respond undefined to indicate this
980
+ return undefined;
981
+ }
982
+ if (this.sendFeatureFlagEvent && !this.flagCallReported[key]) {
983
+ this.flagCallReported[key] = true;
984
+ this.capture('$feature_flag_called', {
985
+ $feature_flag: key,
986
+ $feature_flag_response: featureFlags[key],
987
+ });
988
+ }
989
+ // If we have flags we either return the value (true or string) or the defaultResult
990
+ return (_a = featureFlags[key]) !== null && _a !== void 0 ? _a : defaultResult;
991
+ };
992
+ PostHogCore.prototype.getFeatureFlags = function () {
993
+ var flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
994
+ var overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
995
+ if (!overriddenFlags) {
996
+ return flags;
997
+ }
998
+ flags = flags || {};
999
+ for (var key in overriddenFlags) {
1000
+ if (!overriddenFlags[key]) {
1001
+ delete flags[key];
1002
+ }
1003
+ else {
1004
+ flags[key] = overriddenFlags[key];
1005
+ }
1006
+ }
1007
+ return flags;
1008
+ };
1009
+ PostHogCore.prototype.isFeatureEnabled = function (key, defaultResult) {
1010
+ var _a;
1011
+ if (defaultResult === void 0) { defaultResult = false; }
1012
+ var flag = (_a = this.getFeatureFlag(key, defaultResult)) !== null && _a !== void 0 ? _a : defaultResult;
1013
+ return !!flag;
1014
+ };
1015
+ PostHogCore.prototype.reloadFeatureFlagsAsync = function () {
1016
+ return __awaiter(this, void 0, void 0, function () {
1017
+ return __generator(this, function (_a) {
1018
+ switch (_a.label) {
1019
+ case 0: return [4 /*yield*/, this.decideAsync()];
1020
+ case 1: return [2 /*return*/, (_a.sent()).featureFlags];
1021
+ }
1022
+ });
1023
+ });
1024
+ };
1025
+ PostHogCore.prototype.onFeatureFlags = function (cb) {
1026
+ var _this = this;
1027
+ return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
1028
+ var flags;
1029
+ return __generator(this, function (_a) {
1030
+ flags = this.getFeatureFlags();
1031
+ if (flags) {
1032
+ cb(flags);
1033
+ }
1034
+ return [2 /*return*/];
1035
+ });
1036
+ }); });
1037
+ };
1038
+ PostHogCore.prototype.onFeatureFlag = function (key, cb) {
1039
+ var _this = this;
1040
+ return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
1041
+ var flagResponse;
1042
+ return __generator(this, function (_a) {
1043
+ flagResponse = this.getFeatureFlag(key);
1044
+ if (flagResponse !== undefined) {
1045
+ cb(flagResponse);
1046
+ }
1047
+ return [2 /*return*/];
1048
+ });
1049
+ }); });
1050
+ };
1051
+ PostHogCore.prototype.overrideFeatureFlag = function (flags) {
1052
+ if (flags === null) {
1053
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);
1054
+ }
1055
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1056
+ };
1057
+ /***
1058
+ *** QUEUEING AND FLUSHING
1059
+ ***/
1060
+ PostHogCore.prototype.enqueue = function (type, _message) {
1061
+ var _this = this;
1062
+ if (this.optedOut) {
1063
+ return;
1064
+ }
1065
+ var message = __assign(__assign({}, _message), { type: type, library: this.getLibraryId(), library_version: this.getLibraryVersion(), timestamp: _message.timestamp ? _message.timestamp : currentISOTime() });
1066
+ if (message.distinctId) {
1067
+ message.distinct_id = message.distinctId;
1068
+ delete message.distinctId;
1069
+ }
1070
+ var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1071
+ queue.push({ message: message });
1072
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1073
+ this._events.emit(type, message);
1074
+ // Flush queued events if we meet the flushAt length
1075
+ if (queue.length >= this.flushAt) {
1076
+ this.flush();
1077
+ }
1078
+ if (this.flushInterval && !this._flushTimer) {
1079
+ this._flushTimer = safeSetTimeout(function () { return _this.flush(); }, this.flushInterval);
1080
+ }
1081
+ };
1082
+ PostHogCore.prototype.flushAsync = function () {
1083
+ var _this = this;
1084
+ return new Promise(function (resolve, reject) {
1085
+ _this.flush(function (err, data) { return (err ? reject(err) : resolve(data)); });
1086
+ });
1087
+ };
1088
+ PostHogCore.prototype.flush = function (callback) {
1089
+ var _this = this;
1090
+ if (this.optedOut) {
1091
+ return callback && safeSetTimeout(callback, 0);
1092
+ }
1093
+ if (this._flushTimer) {
1094
+ clearTimeout(this._flushTimer);
1095
+ this._flushTimer = null;
1096
+ }
1097
+ var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1098
+ if (!queue.length) {
1099
+ return callback && safeSetTimeout(callback, 0);
1100
+ }
1101
+ var items = queue.splice(0, this.flushAt);
1102
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1103
+ var messages = items.map(function (item) { return item.message; });
1104
+ var data = {
1105
+ api_key: this.apiKey,
1106
+ batch: messages,
1107
+ sent_at: currentISOTime(),
1108
+ };
1109
+ var done = function (err) {
1110
+ callback === null || callback === void 0 ? void 0 : callback(err, messages);
1111
+ _this._events.emit('flush', messages);
1112
+ };
1113
+ // Don't set the user agent if we're not on a browser. The latest spec allows
1114
+ // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1115
+ // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1116
+ // but browsers such as Chrome and Safari have not caught up.
1117
+ this.getCustomUserAgent();
1118
+ var payload = JSON.stringify(data);
1119
+ var url = this.captureMode === 'form'
1120
+ ? "".concat(this.host, "/e/?ip=1&_=").concat(currentTimestamp(), "&v=").concat(this.getLibraryVersion())
1121
+ : "".concat(this.host, "/batch/");
1122
+ var fetchOptions = this.captureMode === 'form'
1123
+ ? {
1124
+ method: 'POST',
1125
+ mode: 'no-cors',
1126
+ credentials: 'omit',
1127
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1128
+ body: "data=".concat(encodeURIComponent(LZString.compressToBase64(payload)), "&compression=lz64"),
1129
+ }
1130
+ : {
1131
+ method: 'POST',
1132
+ headers: { 'Content-Type': 'application/json' },
1133
+ body: payload,
1134
+ };
1135
+ this.fetchWithRetry(url, fetchOptions)
1136
+ .then(function () { return done(); })
1137
+ .catch(function (err) {
1138
+ if (err.response) {
1139
+ var error = new Error(err.response.statusText);
1140
+ return done(error);
1141
+ }
1142
+ done(err);
1143
+ });
1144
+ };
1145
+ PostHogCore.prototype.fetchWithRetry = function (url, options, retryOptions) {
1146
+ return __awaiter(this, void 0, void 0, function () {
1147
+ var _this = this;
1148
+ return __generator(this, function (_a) {
1149
+ return [2 /*return*/, retriable(function () { return _this.fetch(url, options); }, retryOptions || this._retryOptions)];
1150
+ });
1151
+ });
1152
+ };
1153
+ PostHogCore.prototype.shutdownAsync = function () {
1154
+ return __awaiter(this, void 0, void 0, function () {
1155
+ return __generator(this, function (_a) {
1156
+ switch (_a.label) {
1157
+ case 0:
1158
+ clearTimeout(this._flushTimer);
1159
+ return [4 /*yield*/, this.flushAsync()];
1160
+ case 1:
1161
+ _a.sent();
1162
+ return [2 /*return*/];
1163
+ }
1164
+ });
1165
+ });
1166
+ };
1167
+ PostHogCore.prototype.shutdown = function () {
1168
+ void this.shutdownAsync();
1169
+ };
1170
+ return PostHogCore;
1171
+ }());
1172
+
1173
+ var PostHogMemoryStorage = /** @class */ (function () {
1174
+ function PostHogMemoryStorage() {
1175
+ this._memoryStorage = {};
1176
+ }
1177
+ PostHogMemoryStorage.prototype.getProperty = function (key) {
1178
+ return this._memoryStorage[key];
1179
+ };
1180
+ PostHogMemoryStorage.prototype.setProperty = function (key, value) {
1181
+ this._memoryStorage[key] = value !== null ? value : undefined;
1182
+ };
1183
+ return PostHogMemoryStorage;
1184
+ }());
1185
+
1186
+ var getLegacyValues = function () {
1187
+ return __awaiter(void 0, void 0, void 0, function () {
1188
+ var posthogFileDirectory, posthogDistinctIdFile, posthogAnonymousIdFile, res, _a, _b, _c, _d, _e, _f;
1189
+
1190
+ return __generator(this, function (_g) {
1191
+ switch (_g.label) {
1192
+ case 0:
1193
+ if (!(reactNative.Platform.OS === 'ios')) return [3
1194
+ /*break*/
1195
+ , 8];
1196
+ posthogFileDirectory = "".concat(FileSystem__namespace.documentDirectory, "../Library/Application%20Support/").concat(ExpoApplication__namespace.applicationId, "/");
1197
+ posthogDistinctIdFile = posthogFileDirectory + 'posthog.distinctId';
1198
+ posthogAnonymousIdFile = posthogFileDirectory + 'posthog.anonymousId';
1199
+ res = {
1200
+ distinctId: undefined,
1201
+ anonymousId: undefined
1202
+ };
1203
+ _g.label = 1;
1204
+
1205
+ case 1:
1206
+ _g.trys.push([1, 3,, 4]);
1207
+
1208
+ _a = res;
1209
+ _c = (_b = JSON).parse;
1210
+ return [4
1211
+ /*yield*/
1212
+ , FileSystem__namespace.readAsStringAsync(posthogDistinctIdFile)];
1213
+
1214
+ case 2:
1215
+ _a.distinctId = _c.apply(_b, [_g.sent()])['posthog.distinctId'];
1216
+ return [3
1217
+ /*break*/
1218
+ , 4];
1219
+
1220
+ case 3:
1221
+ _g.sent();
1222
+ return [3
1223
+ /*break*/
1224
+ , 4];
1225
+
1226
+ case 4:
1227
+ _g.trys.push([4, 6,, 7]);
1228
+
1229
+ _d = res;
1230
+ _f = (_e = JSON).parse;
1231
+ return [4
1232
+ /*yield*/
1233
+ , FileSystem__namespace.readAsStringAsync(posthogAnonymousIdFile)];
1234
+
1235
+ case 5:
1236
+ _d.anonymousId = _f.apply(_e, [_g.sent()])['posthog.anonymousId'];
1237
+ return [3
1238
+ /*break*/
1239
+ , 7];
1240
+
1241
+ case 6:
1242
+ _g.sent();
1243
+ return [3
1244
+ /*break*/
1245
+ , 7];
1246
+
1247
+ case 7:
1248
+ return [2
1249
+ /*return*/
1250
+ , res];
1251
+
1252
+ case 8:
1253
+ return [2
1254
+ /*return*/
1255
+ ];
1256
+ }
1257
+ });
1258
+ });
1259
+ };
1260
+
1261
+ var POSTHOG_STORAGE_KEY = '.posthog-rn.json';
1262
+ var POSTHOG_STORAGE_VERSION = 'v1';
1263
+
1264
+ var loadStorageAsync = function () {
1265
+ return __awaiter(void 0, void 0, void 0, function () {
1266
+ var uri, stringContent;
1267
+ return __generator(this, function (_a) {
1268
+ switch (_a.label) {
1269
+ case 0:
1270
+ uri = FileSystem__namespace.documentDirectory + POSTHOG_STORAGE_KEY;
1271
+ _a.label = 1;
1272
+
1273
+ case 1:
1274
+ _a.trys.push([1, 3,, 4]);
1275
+
1276
+ return [4
1277
+ /*yield*/
1278
+ , FileSystem__namespace.readAsStringAsync(uri)];
1279
+
1280
+ case 2:
1281
+ stringContent = _a.sent();
1282
+ return [2
1283
+ /*return*/
1284
+ , JSON.parse(stringContent).content];
1285
+
1286
+ case 3:
1287
+ _a.sent();
1288
+ return [2
1289
+ /*return*/
1290
+ , {}];
1291
+
1292
+ case 4:
1293
+ return [2
1294
+ /*return*/
1295
+ ];
1296
+ }
1297
+ });
1298
+ });
1299
+ };
1300
+
1301
+ var persitStorageAsync = function (content) {
1302
+ return __awaiter(void 0, void 0, void 0, function () {
1303
+ var uri, data;
1304
+ return __generator(this, function (_a) {
1305
+ switch (_a.label) {
1306
+ case 0:
1307
+ uri = FileSystem__namespace.documentDirectory + POSTHOG_STORAGE_KEY;
1308
+ data = {
1309
+ version: POSTHOG_STORAGE_VERSION,
1310
+ content: content
1311
+ };
1312
+ return [4
1313
+ /*yield*/
1314
+ , FileSystem__namespace.writeAsStringAsync(uri, JSON.stringify(data)).catch(function (e) {
1315
+ console.error('PostHog failed to persist data to storage', e);
1316
+ })];
1317
+
1318
+ case 1:
1319
+ _a.sent();
1320
+
1321
+ return [2
1322
+ /*return*/
1323
+ ];
1324
+ }
1325
+ });
1326
+ });
1327
+ }; // NOTE: The core prefers a synchronous storage so we mimic this by pre-loading all keys
1328
+
1329
+
1330
+ var _memoryCache = {};
1331
+ var SemiAsyncStorage = {
1332
+ getItem: function (key) {
1333
+ return _memoryCache[key];
1334
+ },
1335
+ setItem: function (key, value) {
1336
+ _memoryCache[key] = value;
1337
+ void persitStorageAsync(_memoryCache);
1338
+ },
1339
+ removeItem: function (key) {
1340
+ delete _memoryCache[key];
1341
+ void persitStorageAsync(_memoryCache);
1342
+ },
1343
+ clear: function () {
1344
+ for (var key in _memoryCache) {
1345
+ delete _memoryCache[key];
1346
+ }
1347
+
1348
+ void persitStorageAsync(_memoryCache);
1349
+ },
1350
+ getAllKeys: function () {
1351
+ return Object.keys(_memoryCache);
1352
+ }
1353
+ };
1354
+
1355
+ var _preloadSemiAsyncStoragePromise;
1356
+
1357
+ var preloadSemiAsyncStorage = function () {
1358
+ if (_preloadSemiAsyncStoragePromise) {
1359
+ return _preloadSemiAsyncStoragePromise;
1360
+ }
1361
+
1362
+ _preloadSemiAsyncStoragePromise = loadStorageAsync().then(function (res) {
1363
+ for (var key in res) {
1364
+ _memoryCache[key] = res[key];
1365
+ }
1366
+ });
1367
+ return _preloadSemiAsyncStoragePromise;
1368
+ };
1369
+
1370
+ var version = "2.0.0-alpha12";
1371
+
1372
+ var PostHog =
1373
+ /** @class */
1374
+ function (_super) {
1375
+ __extends(PostHog, _super);
1376
+
1377
+ function PostHog(apiKey, options) {
1378
+ var _this = _super.call(this, apiKey, options) || this;
1379
+
1380
+ _this._memoryStorage = new PostHogMemoryStorage();
1381
+ _this._persistence = options === null || options === void 0 ? void 0 : options.persistence;
1382
+ reactNative.AppState.addEventListener('change', function () {
1383
+ _this.flush();
1384
+ }); // Ensure the async storage has been preloaded (this call is cached)
1385
+ // It is possible that the old library was used so we try to get the legacy distinctID
1386
+
1387
+ void preloadSemiAsyncStorage().then(function () {
1388
+ if (!SemiAsyncStorage.getItem(PostHogPersistedProperty.AnonymousId)) {
1389
+ getLegacyValues().then(function (legacyValues) {
1390
+ if (legacyValues === null || legacyValues === void 0 ? void 0 : legacyValues.distinctId) {
1391
+ SemiAsyncStorage.setItem(PostHogPersistedProperty.DistinctId, legacyValues.distinctId);
1392
+ SemiAsyncStorage.setItem(PostHogPersistedProperty.AnonymousId, legacyValues.anonymousId);
1393
+ }
1394
+ });
1395
+ }
1396
+ });
1397
+ return _this;
1398
+ }
1399
+
1400
+ PostHog.initAsync = function () {
1401
+ return preloadSemiAsyncStorage();
1402
+ };
1403
+
1404
+ PostHog.prototype.getPersistedProperty = function (key) {
1405
+ if (this._persistence === 'memory') {
1406
+ return this._memoryStorage.getProperty(key);
1407
+ }
1408
+
1409
+ return SemiAsyncStorage.getItem(key) || undefined;
1410
+ };
1411
+
1412
+ PostHog.prototype.setPersistedProperty = function (key, value) {
1413
+ if (this._persistence === 'memory') {
1414
+ return this._memoryStorage.getProperty(key);
1415
+ }
1416
+
1417
+ return value !== null ? SemiAsyncStorage.setItem(key, value) : SemiAsyncStorage.removeItem(key);
1418
+ };
1419
+
1420
+ PostHog.prototype.fetch = function (url, options) {
1421
+ return fetch(url, options);
1422
+ };
1423
+
1424
+ PostHog.prototype.getLibraryId = function () {
1425
+ return 'posthog-react-native';
1426
+ };
1427
+
1428
+ PostHog.prototype.getLibraryVersion = function () {
1429
+ return version;
1430
+ };
1431
+
1432
+ PostHog.prototype.getCustomUserAgent = function () {
1433
+ // TODO
1434
+ return;
1435
+ };
1436
+
1437
+ PostHog.prototype.getCommonEventProperties = function () {
1438
+ console.log('DeviceInfo', ExpoDevice__namespace);
1439
+ return __assign(__assign({}, _super.prototype.getCommonEventProperties.call(this)), {
1440
+ $app_build: '1',
1441
+ $app_name: ExpoApplication__namespace.applicationName,
1442
+ $app_namespace: ExpoApplication__namespace.applicationId,
1443
+ $app_version: ExpoApplication__namespace.nativeApplicationVersion,
1444
+ // "$device_id": "F31C35E8-5B28-4626-8AFC-213D1C655FF9",
1445
+ $device_manufacturer: ExpoDevice__namespace.manufacturer,
1446
+ // "$device_model": "x86_64",
1447
+ $device_name: ExpoDevice__namespace.modelName,
1448
+ // "$device_type": "ios",
1449
+ $locale: ExpoLocalization__namespace.locale,
1450
+ // "$network_cellular": false,
1451
+ // "$network_wifi": true,
1452
+ $os_name: ExpoDevice__namespace.osName,
1453
+ $os_version: ExpoDevice__namespace.osVersion,
1454
+ $screen_height: reactNative.Dimensions.get('screen').height,
1455
+ $screen_width: reactNative.Dimensions.get('screen').width,
1456
+ $timezone: ExpoLocalization__namespace.timezone
1457
+ });
1458
+ }; // Custom methods
1459
+
1460
+
1461
+ PostHog.prototype.screen = function (name, properties) {
1462
+ return this.capture('$screen', __assign(__assign({}, properties), {
1463
+ $screen_name: name
1464
+ }));
1465
+ };
1466
+
1467
+ return PostHog;
1468
+ }(PostHogCore);
1469
+ // is used
1470
+
1471
+ void PostHog.initAsync();
1472
+
1473
+ var PostHogContext = /*#__PURE__*/React__default["default"].createContext({
1474
+ client: undefined
1475
+ });
1476
+
1477
+ var usePostHog = function () {
1478
+ var client = React__default["default"].useContext(PostHogContext).client;
1479
+ return client;
1480
+ };
1481
+
1482
+ function useLifecycleTracker(client) {
1483
+ var openTrackedRef = React.useRef(false);
1484
+ var contextClient = usePostHog();
1485
+ var posthog = client || contextClient;
1486
+ return React.useEffect(function () {
1487
+ if (!posthog) {
1488
+ return;
1489
+ }
1490
+
1491
+ if (!openTrackedRef.current) {
1492
+ openTrackedRef.current = true;
1493
+ posthog.capture('Application Opened');
1494
+ }
1495
+
1496
+ var subscription = reactNative.AppState.addEventListener('change', function (nextAppState) {
1497
+ switch (nextAppState) {
1498
+ case 'active':
1499
+ return posthog.capture('Application Became Active');
1500
+
1501
+ case 'background':
1502
+ return posthog.capture('Application Backgrounded');
1503
+
1504
+ default:
1505
+ return;
1506
+ }
1507
+ });
1508
+ return function () {
1509
+ return subscription.remove();
1510
+ };
1511
+ }, [posthog]);
1512
+ }
1513
+
1514
+ var _OptionalReactNativeNavigation = undefined;
1515
+
1516
+ var warn = function (name) {
1517
+ console.warn("PostHog: Missing ".concat(name, " optional dependency. Some functions may not work as expected..."));
1518
+ };
1519
+
1520
+ try {
1521
+ _OptionalReactNativeNavigation = require('@react-navigation/native');
1522
+ } catch (e) {
1523
+ warn('@react-navigation/native');
1524
+ }
1525
+
1526
+ var OptionalReactNativeNavigation = _OptionalReactNativeNavigation;
1527
+
1528
+ function _useNavigationTrackerDisabled() {
1529
+ return;
1530
+ }
1531
+
1532
+ function _useNavigationTracker(options, client) {
1533
+ var contextClient = usePostHog();
1534
+ var posthog = client || contextClient;
1535
+
1536
+ if (!OptionalReactNativeNavigation) {
1537
+ // NOTE: This is taken care of by the export but we keep this here for TS
1538
+ return;
1539
+ }
1540
+
1541
+ var routes = OptionalReactNativeNavigation.useNavigationState(function (state) {
1542
+ return state === null || state === void 0 ? void 0 : state.routes;
1543
+ });
1544
+ var navigation = OptionalReactNativeNavigation.useNavigation();
1545
+
1546
+ var trackRoute = function () {
1547
+ var _a, _b, _c;
1548
+
1549
+ if (!posthog) {
1550
+ return;
1551
+ } // NOTE: This method is not typed correctly but is available and takes care of parsing the router state correctly
1552
+
1553
+
1554
+ var currentRoute = navigation.getCurrentRoute();
1555
+
1556
+ if (!currentRoute) {
1557
+ return;
1558
+ }
1559
+
1560
+ var state = currentRoute.state;
1561
+ var name = currentRoute.name,
1562
+ params = currentRoute.params;
1563
+
1564
+ if ((_a = state === null || state === void 0 ? void 0 : state.routes) === null || _a === void 0 ? void 0 : _a.length) {
1565
+ var route = state.routes[state.routes.length - 1];
1566
+ name = route.name;
1567
+ params = route.params;
1568
+ }
1569
+
1570
+ var currentRouteName = ((_b = options === null || options === void 0 ? void 0 : options.routeToName) === null || _b === void 0 ? void 0 : _b.call(options, name, params)) || name || 'Unknown';
1571
+
1572
+ if (currentRouteName) {
1573
+ var properties = (_c = options === null || options === void 0 ? void 0 : options.routeToProperties) === null || _c === void 0 ? void 0 : _c.call(options, currentRouteName, params);
1574
+ posthog.screen(currentRouteName, properties);
1575
+ }
1576
+ };
1577
+
1578
+ React.useEffect(function () {
1579
+ // NOTE: The navigation stacks may not be fully rendered initially. This means the first route can be missed (it doesn't update useNavigationState)
1580
+ // If missing we simply wait a tick and call it again.
1581
+ if (!routes) {
1582
+ setTimeout(trackRoute, 1);
1583
+ return;
1584
+ }
1585
+
1586
+ trackRoute();
1587
+ }, [routes]);
1588
+ }
1589
+
1590
+ var useNavigationTracker = OptionalReactNativeNavigation ? _useNavigationTracker : _useNavigationTrackerDisabled;
1591
+
1592
+ function useFeatureFlags(client) {
1593
+ var contextClient = usePostHog();
1594
+ var posthog = client || contextClient;
1595
+
1596
+ var _a = React.useState(posthog === null || posthog === void 0 ? void 0 : posthog.getFeatureFlags()),
1597
+ featureFlags = _a[0],
1598
+ setFeatureFlags = _a[1];
1599
+
1600
+ if (!posthog) {
1601
+ return featureFlags;
1602
+ }
1603
+
1604
+ React.useEffect(function () {
1605
+ setFeatureFlags(posthog.getFeatureFlags());
1606
+ return posthog.onFeatureFlags(function (flags) {
1607
+ setFeatureFlags(flags);
1608
+ });
1609
+ }, [posthog]);
1610
+ return featureFlags;
1611
+ }
1612
+
1613
+ function useFeatureFlag(flag, defaultValue) {
1614
+ var posthog = usePostHog();
1615
+
1616
+ var _a = React.useState(posthog === null || posthog === void 0 ? void 0 : posthog.getFeatureFlag(flag, defaultValue)),
1617
+ featureFlag = _a[0],
1618
+ setFeatureFlag = _a[1];
1619
+
1620
+ if (!posthog) {
1621
+ return featureFlag;
1622
+ }
1623
+
1624
+ React.useEffect(function () {
1625
+ setFeatureFlag(posthog.getFeatureFlag(flag, defaultValue));
1626
+ return posthog.onFeatureFlags(function () {
1627
+ setFeatureFlag(posthog.getFeatureFlag(flag, defaultValue));
1628
+ });
1629
+ }, [posthog, flag, defaultValue]);
1630
+ return featureFlag;
1631
+ }
1632
+
1633
+ var flattenStyles = function (styles) {
1634
+ var flattened = {};
1635
+
1636
+ if (Array.isArray(styles)) {
1637
+ for (var _i = 0, styles_1 = styles; _i < styles_1.length; _i++) {
1638
+ var style = styles_1[_i];
1639
+ Object.assign(flattened, flattenStyles(style));
1640
+ }
1641
+ } else {
1642
+ Object.assign(flattened, styles);
1643
+ }
1644
+
1645
+ return flattened;
1646
+ };
1647
+
1648
+ var stringifyStyle = function (styles) {
1649
+ var flattened = flattenStyles(styles);
1650
+ var str = Object.keys(flattened).map(function (x) {
1651
+ return "".concat(x, ":").concat(flattened[x]);
1652
+ }).join(';');
1653
+ return str;
1654
+ };
1655
+
1656
+ var sanitiseLabel = function (label) {
1657
+ return label.replace(/[^a-z0-9]+/gi, '-');
1658
+ };
1659
+
1660
+ var autocaptureFromTouchEvent = function (e, posthog, options) {
1661
+ var _a, _b;
1662
+
1663
+ if (options === void 0) {
1664
+ options = {};
1665
+ }
1666
+
1667
+ var _c = options.noCaptureProp,
1668
+ noCaptureProp = _c === void 0 ? 'ph-no-capture' : _c,
1669
+ _d = options.customLabelProp,
1670
+ customLabelProp = _d === void 0 ? 'ph-label' : _d,
1671
+ _e = options.maxElementsCaptured,
1672
+ maxElementsCaptured = _e === void 0 ? 20 : _e,
1673
+ _f = options.ignoreLabels,
1674
+ ignoreLabels = _f === void 0 ? [] : _f,
1675
+ _g = options.propsToCapture,
1676
+ propsToCapture = _g === void 0 ? ['style', 'testID', 'accessibilityLabel', 'ph-label'] : _g;
1677
+
1678
+ if (!e._targetInst) {
1679
+ return;
1680
+ }
1681
+
1682
+ var elements = [];
1683
+ var currentInst = e._targetInst;
1684
+
1685
+ var _loop_1 = function () {
1686
+ var el = {
1687
+ tag_name: ''
1688
+ };
1689
+ var props = currentInst.memoizedProps;
1690
+
1691
+ if (props === null || props === void 0 ? void 0 : props[noCaptureProp]) {
1692
+ return {
1693
+ value: void 0
1694
+ };
1695
+ }
1696
+
1697
+ if (props) {
1698
+ // Capture only props we have said to capture. By default this is only "safe" props
1699
+ Object.keys(props).forEach(function (key) {
1700
+ if (!propsToCapture.includes(key)) {
1701
+ return;
1702
+ }
1703
+
1704
+ var value = props[key];
1705
+
1706
+ if (key === 'style') {
1707
+ el.attr__style = stringifyStyle(value);
1708
+ } else if (['string', 'number', 'boolean'].includes(typeof value)) {
1709
+ if (key === 'children') {
1710
+ el.$el_text = typeof value === 'string' ? value : JSON.stringify(value);
1711
+ } else {
1712
+ el["attr__".concat(key)] = value;
1713
+ }
1714
+ }
1715
+ });
1716
+ } // Try and find a sensible label
1717
+
1718
+
1719
+ var label = typeof (props === null || props === void 0 ? void 0 : props[customLabelProp]) !== 'undefined' ? "".concat(props[customLabelProp]) : ((_a = currentInst.elementType) === null || _a === void 0 ? void 0 : _a.displayName) || ((_b = currentInst.elementType) === null || _b === void 0 ? void 0 : _b.name);
1720
+
1721
+ if (label && !ignoreLabels.includes(label)) {
1722
+ el.tag_name = sanitiseLabel(label);
1723
+ elements.push(el);
1724
+ }
1725
+
1726
+ currentInst = currentInst.return;
1727
+ };
1728
+
1729
+ while (currentInst && // maxComponentTreeSize will always be defined as we have a defaultProps. But ts needs a check so this is here.
1730
+ elements.length < maxElementsCaptured) {
1731
+ var state_1 = _loop_1();
1732
+
1733
+ if (typeof state_1 === "object") return state_1.value;
1734
+ }
1735
+
1736
+ if (elements.length) {
1737
+ posthog.autocapture('touch', elements, {
1738
+ $touch_x: e.nativeEvent.pageX,
1739
+ $touch_y: e.nativeEvent.pageY
1740
+ });
1741
+ }
1742
+ };
1743
+
1744
+ function PostHogHooks(_a) {
1745
+ var options = _a.options;
1746
+ useNavigationTracker(options === null || options === void 0 ? void 0 : options.navigation);
1747
+ useLifecycleTracker();
1748
+ return null;
1749
+ }
1750
+
1751
+ var PostHogProvider = function (_a) {
1752
+ var children = _a.children,
1753
+ client = _a.client,
1754
+ options = _a.options,
1755
+ apiKey = _a.apiKey,
1756
+ autocapture = _a.autocapture,
1757
+ style = _a.style;
1758
+ var posthogRef = React.useRef();
1759
+
1760
+ if (!posthogRef.current) {
1761
+ posthogRef.current = client ? client : apiKey ? new PostHog(apiKey, options) : undefined;
1762
+ }
1763
+
1764
+ var autocaptureEnabled = !!autocapture;
1765
+ var autocaptureOptions = autocapture && typeof autocapture !== 'boolean' ? autocapture : {};
1766
+ var posthog = posthogRef.current;
1767
+ var captureTouches = posthog && (autocapture === true || (autocaptureOptions === null || autocaptureOptions === void 0 ? void 0 : autocaptureOptions.captureTouches));
1768
+ var onTouch = React.useCallback(function (type, e) {
1769
+ // TODO: Improve this to ensure we only capture presses and not just ends of a drag for example
1770
+ if (!captureTouches) {
1771
+ return;
1772
+ }
1773
+
1774
+ if (type === 'end') {
1775
+ autocaptureFromTouchEvent(e, posthog, autocaptureOptions);
1776
+ }
1777
+ }, [posthog, autocapture]); // TODO: Improve this to ensure we only capture presses and not just ends of a drag for example
1778
+
1779
+ return /*#__PURE__*/React__default["default"].createElement(reactNative.View, {
1780
+ "ph-label": "PostHogProvider",
1781
+ style: style || {
1782
+ flex: 1
1783
+ },
1784
+ onTouchEndCapture: captureTouches ? function (e) {
1785
+ return onTouch('end', e);
1786
+ } : undefined
1787
+ }, /*#__PURE__*/React__default["default"].createElement(PostHogContext.Provider, {
1788
+ value: {
1789
+ client: posthogRef.current
1790
+ }
1791
+ }, autocaptureEnabled ? /*#__PURE__*/React__default["default"].createElement(PostHogHooks, {
1792
+ options: autocaptureOptions
1793
+ }) : null, children));
1794
+ };
1795
+
1796
+ exports.PostHog = PostHog;
1797
+ exports.PostHogProvider = PostHogProvider;
1798
+ exports["default"] = PostHog;
1799
+ exports.useFeatureFlag = useFeatureFlag;
1800
+ exports.useFeatureFlags = useFeatureFlags;
1801
+ exports.useLifecycleTracker = useLifecycleTracker;
1802
+ exports.useNavigationTracker = useNavigationTracker;
1803
+ exports.usePostHog = usePostHog;
1804
+ //# sourceMappingURL=index.cjs.js.map