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