posthog-react-native 1.1.4 → 2.0.0-alpha11

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