@layers/react-native 3.3.0 → 3.3.1

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.
@@ -1,9 +1,149 @@
1
1
  const require_chunk = require('./chunk-nOFOJqeH.js');
2
2
  const require_att = require('./att-CauvkIKr.js');
3
- const require_skan = require('./skan-BRhw9sPC.js');
3
+ const require_skan = require('./skan-qcOYJKzP.js');
4
4
  let __layers_core_wasm = require("@layers/core-wasm");
5
5
  __layers_core_wasm = require_chunk.__toESM(__layers_core_wasm);
6
6
 
7
+ //#region src/exceptions.ts
8
+ /** Cap on the serialized stack length to keep payloads sane. */
9
+ const MAX_STACK_CHARS = 1e4;
10
+ /** Cap on the serialized message length. */
11
+ const MAX_MESSAGE_CHARS = 4e3;
12
+ /** How long a fatal error waits for `onFatal` before the crash proceeds. */
13
+ const DEFAULT_FATAL_TIMEOUT_MS = 1e3;
14
+ /**
15
+ * Process-wide: `true` while a fatal error is waiting on `onFatal`. Module
16
+ * level on purpose, so two SDK instances cannot each hold the crash open.
17
+ */
18
+ let fatalInFlight = false;
19
+ function findErrorUtils() {
20
+ const candidate = globalThis.ErrorUtils;
21
+ if (typeof candidate === "object" && candidate !== null && typeof candidate.getGlobalHandler === "function" && typeof candidate.setGlobalHandler === "function") return candidate;
22
+ return null;
23
+ }
24
+ function truncate(s, max) {
25
+ return s.length > max ? `${s.slice(0, max)}…` : s;
26
+ }
27
+ /**
28
+ * Describe whatever React Native handed the global handler. Errors carry a
29
+ * name, message and stack; anything else thrown (strings, plain objects) is
30
+ * serialized best-effort. Every field is coerced to a string, since Error
31
+ * subclasses in the wild override `message` with numbers and getters.
32
+ */
33
+ function buildExceptionProperties(error, isFatal) {
34
+ const props = {
35
+ $exception_type: "Error",
36
+ $exception_message: "",
37
+ $exception_promise_rejection: false
38
+ };
39
+ if (error instanceof Error) {
40
+ props.$exception_type = String(error.name || "Error");
41
+ props.$exception_message = truncate(String(error.message ?? String(error)), MAX_MESSAGE_CHARS);
42
+ if (error.stack) props.$exception_stack = truncate(String(error.stack), MAX_STACK_CHARS);
43
+ } else if (typeof error === "string") props.$exception_message = truncate(error, MAX_MESSAGE_CHARS);
44
+ else {
45
+ let serialized;
46
+ try {
47
+ serialized = JSON.stringify(error);
48
+ } catch {
49
+ serialized = void 0;
50
+ }
51
+ props.$exception_message = truncate(typeof serialized === "string" ? serialized : String(error), MAX_MESSAGE_CHARS);
52
+ }
53
+ if (typeof isFatal === "boolean") props.$exception_fatal = isFatal;
54
+ return props;
55
+ }
56
+ /**
57
+ * Invoke the consumer-supplied `onInternalError` defensively. A throwing
58
+ * callback must never escape the global handler, where it would be reported
59
+ * as a second uncaught error.
60
+ */
61
+ function reportInternalError(options, message, error) {
62
+ if (!options.onInternalError) return;
63
+ try {
64
+ options.onInternalError(message, error);
65
+ } catch {}
66
+ }
67
+ /**
68
+ * Run `onFatal`, then `chain` exactly once: when `onFatal` settles, when it
69
+ * throws or returns nothing, or when `fatalTimeoutMs` passes. The timer is
70
+ * the guarantee that a crashed app is never kept alive by a hung write.
71
+ */
72
+ function chainAfterFatalWork(options, chain) {
73
+ let chained = false;
74
+ const chainOnce = () => {
75
+ if (chained) return;
76
+ chained = true;
77
+ fatalInFlight = false;
78
+ try {
79
+ chain();
80
+ } catch (e) {
81
+ reportInternalError(options, "previous global error handler threw", e);
82
+ }
83
+ };
84
+ const timer = setTimeout(chainOnce, options.fatalTimeoutMs ?? DEFAULT_FATAL_TIMEOUT_MS);
85
+ const finish = () => {
86
+ clearTimeout(timer);
87
+ chainOnce();
88
+ };
89
+ fatalInFlight = true;
90
+ let pending;
91
+ try {
92
+ pending = options.onFatal?.();
93
+ } catch (e) {
94
+ reportInternalError(options, "onFatal threw", e);
95
+ finish();
96
+ return;
97
+ }
98
+ if (!pending || typeof pending.then !== "function") {
99
+ finish();
100
+ return;
101
+ }
102
+ pending.then(finish, (e) => {
103
+ reportInternalError(options, "onFatal rejected", e);
104
+ finish();
105
+ });
106
+ }
107
+ /**
108
+ * Install the React Native global error handler.
109
+ *
110
+ * Returns an idempotent uninstall function that restores the previous
111
+ * handler when ours is still the current one. Returns a no-op uninstall when
112
+ * `ErrorUtils` is absent (Node, Jest without the RN preset, web).
113
+ */
114
+ function installExceptionAutoCapture(sink, options = {}) {
115
+ const errorUtils = findErrorUtils();
116
+ if (!errorUtils) return () => {};
117
+ const previous = errorUtils.getGlobalHandler();
118
+ let uninstalled = false;
119
+ const handler = (error, isFatal) => {
120
+ if (!uninstalled) try {
121
+ sink("$exception", buildExceptionProperties(error, isFatal));
122
+ } catch (e) {
123
+ reportInternalError(options, "exception auto-capture failed", e);
124
+ }
125
+ const chain = () => {
126
+ if (typeof previous === "function") previous(error, isFatal);
127
+ };
128
+ if (isFatal === true && !uninstalled && options.onFatal && !fatalInFlight) {
129
+ chainAfterFatalWork(options, chain);
130
+ return;
131
+ }
132
+ chain();
133
+ };
134
+ errorUtils.setGlobalHandler(handler);
135
+ return () => {
136
+ if (uninstalled) return;
137
+ uninstalled = true;
138
+ if (errorUtils.getGlobalHandler() !== handler) return;
139
+ if (typeof previous === "function") errorUtils.setGlobalHandler(previous);
140
+ else errorUtils.setGlobalHandler((error) => {
141
+ throw error;
142
+ });
143
+ };
144
+ }
145
+
146
+ //#endregion
7
147
  //#region src/standard-events.ts
8
148
  /**
9
149
  * Predefined standard event name constants.
@@ -35,7 +175,10 @@ const StandardEvents = {
35
175
  VIEW_CONTENT: "view_content",
36
176
  SHARE: "share",
37
177
  DEEP_LINK: "deep_link_opened",
38
- SCREEN_VIEW: "screen_view"
178
+ SCREEN_VIEW: "screen_view",
179
+ ONBOARDING_START: "onboarding_start",
180
+ ONBOARDING_COMPLETE: "onboarding_complete",
181
+ PAYWALL_SHOW: "paywall_show"
39
182
  };
40
183
  /** Build a login event. */
41
184
  function loginEvent(method) {
@@ -203,6 +346,36 @@ function screenViewEvent(name, screenClass) {
203
346
  properties
204
347
  };
205
348
  }
349
+ /** Build an onboarding-start event. `screenName` is the first onboarding screen shown. */
350
+ function onboardingStartEvent(screenName) {
351
+ const properties = {};
352
+ if (screenName !== void 0) properties.screen_name = screenName;
353
+ return {
354
+ event: StandardEvents.ONBOARDING_START,
355
+ properties
356
+ };
357
+ }
358
+ /** Build an onboarding-complete event. `screenName` is the screen the user finished on. */
359
+ function onboardingCompleteEvent(screenName) {
360
+ const properties = {};
361
+ if (screenName !== void 0) properties.screen_name = screenName;
362
+ return {
363
+ event: StandardEvents.ONBOARDING_COMPLETE,
364
+ properties
365
+ };
366
+ }
367
+ /**
368
+ * Build a paywall-show event. `placement` names where the paywall appeared
369
+ * (e.g. `onboarding`, `settings`); `productIds` lists the products offered.
370
+ */
371
+ function paywallShowEvent(placement, productIds) {
372
+ const properties = { placement };
373
+ if (productIds !== void 0) properties.product_ids = productIds;
374
+ return {
375
+ event: StandardEvents.PAYWALL_SHOW,
376
+ properties
377
+ };
378
+ }
206
379
 
207
380
  //#endregion
208
381
  //#region src/superwall.ts
@@ -937,7 +1110,7 @@ function hostAppIsRegisteredOn(rn) {
937
1110
  }
938
1111
  }
939
1112
  const DUPLICATE_REACT_NATIVE_MESSAGE = "[Layers] The SDK resolved a SECOND copy of react-native, not the one your app runs. React Native delivers native lifecycle events to a single copy, so this listener can never fire: $app_background and $app_foreground will not be emitted and the background crash-safety snapshot will not run, which loses every event queued since the last flush on any launch that ends in a kill. Fix the duplicate in your bundler — in a Metro monorepo set `resolver.disableHierarchicalLookup = true` and list every workspace node_modules in `resolver.nodeModulesPaths` — or hand the SDK your app's module: `new LayersReactNative({ ..., appState: AppState })` with AppState imported from 'react-native'.";
940
- const SDK_VERSION = "3.3.0";
1113
+ const SDK_VERSION = "3.3.1";
941
1114
  var LayersReactNative = class LayersReactNative {
942
1115
  core;
943
1116
  eagerPersistence;
@@ -945,6 +1118,8 @@ var LayersReactNative = class LayersReactNative {
945
1118
  isOnline = true;
946
1119
  enableDebug;
947
1120
  appStateSubscription = null;
1121
+ exceptionUninstall = null;
1122
+ persistenceSettle = null;
948
1123
  _lifecycleCheckTimer = null;
949
1124
  netInfoUnsubscribe = null;
950
1125
  config;
@@ -1128,8 +1303,9 @@ var LayersReactNative = class LayersReactNative {
1128
1303
  if (typeof WebAssembly !== "undefined") await (0, __layers_core_wasm.initWasm)();
1129
1304
  if (this.initAborted(generation)) return;
1130
1305
  try {
1131
- const persistence = await createAsyncStoragePersistence(this.config.appId);
1306
+ const { backend: persistence, settle: persistenceSettle } = await createAsyncStoragePersistence(this.config.appId);
1132
1307
  if (this.initAborted(generation)) return;
1308
+ this.persistenceSettle = persistenceSettle;
1133
1309
  const httpClient = new __layers_core_wasm.FetchHttpClient();
1134
1310
  const migrationState = this.core.exportMigrationState();
1135
1311
  this.core.shutdown();
@@ -1260,6 +1436,14 @@ var LayersReactNative = class LayersReactNative {
1260
1436
  }
1261
1437
  if (this.initAborted(generation)) return;
1262
1438
  if (this.config.autoTrackDeepLinks !== false) this.setupDeepLinkAutoTracking();
1439
+ if (this.config.autoTrackExceptions !== false) this.exceptionUninstall = installExceptionAutoCapture((eventName, properties) => {
1440
+ this.track(eventName, properties);
1441
+ }, {
1442
+ onInternalError: (message, error) => {
1443
+ if (this.enableDebug) console.warn("[Layers]", message, error);
1444
+ },
1445
+ ...typeof __DEV__ !== "undefined" && __DEV__ === true ? {} : { onFatal: () => this.persistForCrash() }
1446
+ });
1263
1447
  this._isInitialized = true;
1264
1448
  const totalDurationMs = Date.now() - initStartTime;
1265
1449
  if (this.enableDebug) console.log(`[Layers] Init timing: mainThread=${String(mainThreadDurationMs)}ms, total=${String(totalDurationMs)}ms`);
@@ -1284,6 +1468,20 @@ var LayersReactNative = class LayersReactNative {
1284
1468
  }
1285
1469
  }
1286
1470
  screen(screenName, properties) {
1471
+ this.screenImpl(screenName, properties, true);
1472
+ }
1473
+ /**
1474
+ * @internal Entry point for auto-capture integrations (the Expo provider's
1475
+ * router tracker). Identical to `screen()` except the view is kept out of
1476
+ * the SKAN engine: SKAN preset rules key off `screen_name`, and an
1477
+ * auto-captured stream of route views would otherwise change an app's iOS
1478
+ * conversion values the moment auto-capture turned on. Manual `screen()`
1479
+ * calls keep feeding SKAN exactly as before.
1480
+ */
1481
+ _screenAutoCaptured(screenName, properties) {
1482
+ this.screenImpl(screenName, properties, false);
1483
+ }
1484
+ screenImpl(screenName, properties, forwardToSkan) {
1287
1485
  if (this.enableDebug) console.log(`[Layers] screen("${screenName}", ${Object.keys(properties ?? {}).length} properties)`);
1288
1486
  try {
1289
1487
  const merged = this.mergeAttributionProperties(properties);
@@ -1292,7 +1490,7 @@ var LayersReactNative = class LayersReactNative {
1292
1490
  const depthAfter = this.core.queueDepth();
1293
1491
  if (depthAfter <= depthBefore && this.enableDebug) console.warn(`[Layers] screen("${screenName}") — event may not have been queued (depth before=${String(depthBefore)}, after=${String(depthAfter)})`);
1294
1492
  this.recordRecentEvent(`screen:${screenName}`, properties);
1295
- if (this._skanManager) {
1493
+ if (forwardToSkan && this._skanManager) {
1296
1494
  const skanProps = { ...merged };
1297
1495
  if (skanProps.screen_name === void 0) skanProps.screen_name = screenName;
1298
1496
  this._skanManager.processEvent("screen_view", skanProps).catch(() => {});
@@ -1874,6 +2072,20 @@ var LayersReactNative = class LayersReactNative {
1874
2072
  require_skan.setSkanCore(null);
1875
2073
  }
1876
2074
  /**
2075
+ * Make a fatal error's `$exception` durable before React Native's crash
2076
+ * path ends the process. The core's `flush()` snapshots the queue to the
2077
+ * persistence backend, whose AsyncStorage write is otherwise fire-and-
2078
+ * forget; this waits for that write to land. Delivery is left to the next
2079
+ * launch, which re-hydrates the snapshot and sends it, so the crashed app is
2080
+ * held open only for the write.
2081
+ */
2082
+ async persistForCrash() {
2083
+ try {
2084
+ this.core.flush();
2085
+ } catch {}
2086
+ if (this.persistenceSettle) await this.persistenceSettle();
2087
+ }
2088
+ /**
1877
2089
  * Remove every listener and timer this instance installed, then shut the
1878
2090
  * core down. Shared by shutdown() and the mid-init abort path, so it must be
1879
2091
  * safe to call twice — every handle is nulled and the core's own shutdown()
@@ -1894,6 +2106,12 @@ var LayersReactNative = class LayersReactNative {
1894
2106
  this.deepLinkUnsubscribe();
1895
2107
  this.deepLinkUnsubscribe = null;
1896
2108
  }
2109
+ if (this.exceptionUninstall) {
2110
+ try {
2111
+ this.exceptionUninstall();
2112
+ } catch {}
2113
+ this.exceptionUninstall = null;
2114
+ }
1897
2115
  try {
1898
2116
  this.core.shutdown();
1899
2117
  } catch {}
@@ -2321,6 +2539,15 @@ var LayersReactNative = class LayersReactNative {
2321
2539
  async function createAsyncStoragePersistence(appId) {
2322
2540
  const prefix = `layers_sdk_${appId}_`;
2323
2541
  const memoryStore = /* @__PURE__ */ new Map();
2542
+ const inFlight = /* @__PURE__ */ new Set();
2543
+ const trackInFlight = (operation) => {
2544
+ const entry = operation.then(() => {
2545
+ inFlight.delete(entry);
2546
+ }, () => {
2547
+ inFlight.delete(entry);
2548
+ });
2549
+ inFlight.add(entry);
2550
+ };
2324
2551
  try {
2325
2552
  const AsyncStorage = await loadAsyncStorage();
2326
2553
  if (AsyncStorage) {
@@ -2337,23 +2564,26 @@ async function createAsyncStoragePersistence(appId) {
2337
2564
  warnPersistencePreloadFailed(error);
2338
2565
  }
2339
2566
  return {
2340
- write(key, data) {
2341
- memoryStore.set(key, new Uint8Array(data));
2342
- writeToAsyncStorage(prefix + key, data);
2343
- },
2344
- read(key) {
2345
- return memoryStore.get(key) ?? null;
2346
- },
2347
- delete(key) {
2348
- memoryStore.delete(key);
2349
- deleteFromAsyncStorage(prefix + key);
2567
+ backend: {
2568
+ write(key, data) {
2569
+ memoryStore.set(key, new Uint8Array(data));
2570
+ trackInFlight(writeToAsyncStorage(prefix + key, data));
2571
+ },
2572
+ read(key) {
2573
+ return memoryStore.get(key) ?? null;
2574
+ },
2575
+ delete(key) {
2576
+ memoryStore.delete(key);
2577
+ trackInFlight(deleteFromAsyncStorage(prefix + key));
2578
+ },
2579
+ listKeys(keyPrefix) {
2580
+ const keys = [];
2581
+ for (const k of memoryStore.keys()) if (k.startsWith(keyPrefix)) keys.push(k);
2582
+ keys.sort();
2583
+ return keys;
2584
+ }
2350
2585
  },
2351
- listKeys(keyPrefix) {
2352
- const keys = [];
2353
- for (const k of memoryStore.keys()) if (k.startsWith(keyPrefix)) keys.push(k);
2354
- keys.sort();
2355
- return keys;
2356
- }
2586
+ settle: () => Promise.all(Array.from(inFlight)).then(() => void 0)
2357
2587
  };
2358
2588
  }
2359
2589
  const B64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -2876,39 +3106,51 @@ function parseDeepLink(url) {
2876
3106
  const _expoRouterPreviousPath = /* @__PURE__ */ new WeakMap();
2877
3107
  const _expoRouterLastTracked = /* @__PURE__ */ new WeakMap();
2878
3108
  /**
2879
- * Hook that emits `$screen_view` for every Expo Router pathname change.
3109
+ * Hook that emits `screen_view` for every Expo Router pathname change.
3110
+ *
3111
+ * One view per route per SDK instance: the deduplication key is the resolved
3112
+ * pathname alone. A param-only change on the same route (a search box or
3113
+ * filter chips mirrored into the URL) is the same screen and is not
3114
+ * re-tracked, and the Expo provider's auto-captured view and a manual call on
3115
+ * the same route count once, whichever effect runs first.
2880
3116
  *
2881
- * The hook also tracks the previous pathname so the emitted event carries
3117
+ * The hook also tracks the previous screen name so the emitted event carries
2882
3118
  * `previous_screen_name`, matching the React Navigation observer in
2883
3119
  * `useLayersNavigationTracking`. This makes funnel analysis trivial
2884
3120
  * server-side: every screen event has a self-contained pair `(from, to)`
2885
3121
  * — no need to join adjacent rows.
2886
3122
  */
2887
- function useLayersExpoRouterTracking(sdkInstance, usePathname, useGlobalSearchParams) {
3123
+ function useLayersExpoRouterTracking(sdkInstance, usePathname, useGlobalSearchParams, options = {}) {
3124
+ const autoCaptured = options.source === "auto";
2888
3125
  if (sdkInstance != null && typeof sdkInstance.screen !== "function") throw new TypeError("useLayersExpoRouterTracking: expected a LayersReactNative instance (or null before init).");
2889
3126
  const { useEffect } = require("react");
2890
3127
  const pathname = usePathname();
2891
3128
  const params = useGlobalSearchParams();
2892
- const paramsString = JSON.stringify(params);
3129
+ const routeKey = options.resolvedPath ?? pathname;
2893
3130
  useEffect(() => {
2894
3131
  if (sdkInstance == null) return;
2895
3132
  if (pathname) {
2896
- const routeKey = `${pathname}${paramsString}`;
2897
- if (_expoRouterLastTracked.get(sdkInstance) === routeKey) return;
3133
+ const last = _expoRouterLastTracked.get(sdkInstance);
3134
+ if (last && last.resolvedPath === routeKey && (!autoCaptured || last.name === pathname)) return;
2898
3135
  const properties = {};
2899
3136
  Object.entries(params).forEach(([key, value]) => {
2900
3137
  properties[key] = Array.isArray(value) ? value.join(",") : value;
2901
3138
  });
2902
3139
  const previous = _expoRouterPreviousPath.get(sdkInstance);
2903
3140
  if (previous && previous !== pathname) properties.previous_screen_name = previous;
2904
- sdkInstance.screen(pathname, properties);
3141
+ if (autoCaptured && typeof sdkInstance._screenAutoCaptured === "function") sdkInstance._screenAutoCaptured(pathname, properties);
3142
+ else sdkInstance.screen(pathname, properties);
2905
3143
  _expoRouterPreviousPath.set(sdkInstance, pathname);
2906
- _expoRouterLastTracked.set(sdkInstance, routeKey);
3144
+ _expoRouterLastTracked.set(sdkInstance, {
3145
+ resolvedPath: routeKey,
3146
+ name: pathname
3147
+ });
2907
3148
  }
2908
3149
  }, [
2909
3150
  sdkInstance,
2910
3151
  pathname,
2911
- paramsString
3152
+ routeKey,
3153
+ autoCaptured
2912
3154
  ]);
2913
3155
  }
2914
3156
 
@@ -2955,6 +3197,12 @@ Object.defineProperty(exports, 'addToWishlistEvent', {
2955
3197
  return addToWishlistEvent;
2956
3198
  }
2957
3199
  });
3200
+ Object.defineProperty(exports, 'buildExceptionProperties', {
3201
+ enumerable: true,
3202
+ get: function () {
3203
+ return buildExceptionProperties;
3204
+ }
3205
+ });
2958
3206
  Object.defineProperty(exports, 'buildInstallReferrerProperties', {
2959
3207
  enumerable: true,
2960
3208
  get: function () {
@@ -3021,6 +3269,12 @@ Object.defineProperty(exports, 'initiateCheckoutEvent', {
3021
3269
  return initiateCheckoutEvent;
3022
3270
  }
3023
3271
  });
3272
+ Object.defineProperty(exports, 'installExceptionAutoCapture', {
3273
+ enumerable: true,
3274
+ get: function () {
3275
+ return installExceptionAutoCapture;
3276
+ }
3277
+ });
3024
3278
  Object.defineProperty(exports, 'isRevenueCatConnected', {
3025
3279
  enumerable: true,
3026
3280
  get: function () {
@@ -3045,6 +3299,18 @@ Object.defineProperty(exports, 'loginEvent', {
3045
3299
  return loginEvent;
3046
3300
  }
3047
3301
  });
3302
+ Object.defineProperty(exports, 'onboardingCompleteEvent', {
3303
+ enumerable: true,
3304
+ get: function () {
3305
+ return onboardingCompleteEvent;
3306
+ }
3307
+ });
3308
+ Object.defineProperty(exports, 'onboardingStartEvent', {
3309
+ enumerable: true,
3310
+ get: function () {
3311
+ return onboardingStartEvent;
3312
+ }
3313
+ });
3048
3314
  Object.defineProperty(exports, 'parseDeepLink', {
3049
3315
  enumerable: true,
3050
3316
  get: function () {
@@ -3057,6 +3323,12 @@ Object.defineProperty(exports, 'parseInstallReferrerUrl', {
3057
3323
  return parseInstallReferrerUrl;
3058
3324
  }
3059
3325
  });
3326
+ Object.defineProperty(exports, 'paywallShowEvent', {
3327
+ enumerable: true,
3328
+ get: function () {
3329
+ return paywallShowEvent;
3330
+ }
3331
+ });
3060
3332
  Object.defineProperty(exports, 'purchaseEvent', {
3061
3333
  enumerable: true,
3062
3334
  get: function () {