posthog-react-native 2.1.4 → 2.2.0-alpha2

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