@layers/react-native 3.3.3 → 3.3.4

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.
@@ -1123,16 +1123,21 @@ function hostAppIsRegisteredOn(rn) {
1123
1123
  }
1124
1124
  }
1125
1125
  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'.";
1126
- const SDK_VERSION = "3.3.3";
1126
+ const SDK_VERSION = "3.3.4";
1127
1127
  var LayersReactNative = class LayersReactNative {
1128
1128
  core;
1129
- eagerPersistence;
1129
+ eager;
1130
+ get eagerPersistence() {
1131
+ return this.eager.backend;
1132
+ }
1130
1133
  appUserId;
1131
1134
  isOnline = true;
1132
1135
  enableDebug;
1133
1136
  appStateSubscription = null;
1134
1137
  exceptionUninstall = null;
1135
1138
  persistenceSettle = null;
1139
+ _persistTimer = null;
1140
+ _wrapperFlushes = /* @__PURE__ */ new Set();
1136
1141
  _lifecycleCheckTimer = null;
1137
1142
  netInfoUnsubscribe = null;
1138
1143
  config;
@@ -1149,6 +1154,7 @@ var LayersReactNative = class LayersReactNative {
1149
1154
  _runtimeGeneration = 0;
1150
1155
  _configPollTimer = null;
1151
1156
  static CONFIG_POLL_INTERVAL_MS = 3e5;
1157
+ static PERSIST_THROTTLE_MS = 1e3;
1152
1158
  _adServicesToken = null;
1153
1159
  _installReferrer = null;
1154
1160
  _gaid = null;
@@ -1173,7 +1179,7 @@ var LayersReactNative = class LayersReactNative {
1173
1179
  this.appUserId = config.appUserId;
1174
1180
  this.config = config;
1175
1181
  const httpClient = new __layers_core_wasm.FetchHttpClient();
1176
- this.eagerPersistence = new __layers_core_wasm.MemoryPersistence();
1182
+ this.eager = createEagerPersistence(config.appId);
1177
1183
  this.core = __layers_core_wasm.LayersCore.init({
1178
1184
  config: {
1179
1185
  appId: config.appId,
@@ -1319,7 +1325,7 @@ var LayersReactNative = class LayersReactNative {
1319
1325
  if (this.initAborted(generation)) return;
1320
1326
  this._hadPriorAppIdentity = false;
1321
1327
  try {
1322
- const { backend: persistence, settle: persistenceSettle } = await createAsyncStoragePersistence(this.config.appId);
1328
+ const { backend: persistence, settle: persistenceSettle, forget: forgetPreloaded } = await createAsyncStoragePersistence(this.config.appId);
1323
1329
  try {
1324
1330
  const record = persistence.read("identity_state");
1325
1331
  this._hadPriorAppIdentity = record != null && record.length > 0;
@@ -1330,6 +1336,7 @@ var LayersReactNative = class LayersReactNative {
1330
1336
  this.persistenceSettle = persistenceSettle;
1331
1337
  const httpClient = new __layers_core_wasm.FetchHttpClient();
1332
1338
  const migrationState = this.core.exportMigrationState();
1339
+ this.eager.stopMirroring();
1333
1340
  this.core.shutdown();
1334
1341
  try {
1335
1342
  let migrated = 0;
@@ -1342,6 +1349,7 @@ var LayersReactNative = class LayersReactNative {
1342
1349
  this.eagerPersistence.delete(key);
1343
1350
  }
1344
1351
  } catch {}
1352
+ forgetPreloaded(this.eager.mirrorKeyPrefix);
1345
1353
  this.core = __layers_core_wasm.LayersCore.init({
1346
1354
  config: {
1347
1355
  appId: this.config.appId,
@@ -1362,6 +1370,10 @@ var LayersReactNative = class LayersReactNative {
1362
1370
  this._runtimeGeneration = generation;
1363
1371
  require_skan.setSkanCore(this.core);
1364
1372
  if (this.appUserId) this.core.identify(this.appUserId);
1373
+ try {
1374
+ this.core.flush();
1375
+ } catch {}
1376
+ persistenceSettle().then(() => this.eager.discardMirror()).catch(() => void 0);
1365
1377
  } catch {}
1366
1378
  await this.restoreAttributionData();
1367
1379
  await this.initializeDeviceInfo();
@@ -1467,6 +1479,7 @@ var LayersReactNative = class LayersReactNative {
1467
1479
  ...typeof __DEV__ !== "undefined" && __DEV__ === true ? {} : { onFatal: () => this.persistForCrash() }
1468
1480
  });
1469
1481
  this._isInitialized = true;
1482
+ this.persistThenSend();
1470
1483
  const totalDurationMs = Date.now() - initStartTime;
1471
1484
  if (this.enableDebug) console.log(`[Layers] Init timing: mainThread=${String(mainThreadDurationMs)}ms, total=${String(totalDurationMs)}ms`);
1472
1485
  if (this._initListener) try {
@@ -1482,6 +1495,7 @@ var LayersReactNative = class LayersReactNative {
1482
1495
  const depthBefore = this.core.queueDepth();
1483
1496
  this.core.track(eventName, merged, this.appUserId);
1484
1497
  const depthAfter = this.core.queueDepth();
1498
+ this.schedulePersist();
1485
1499
  if (depthAfter <= depthBefore && this.enableDebug) console.warn(`[Layers] track("${eventName}") — event may not have been queued (depth before=${String(depthBefore)}, after=${String(depthAfter)})`);
1486
1500
  this.recordRecentEvent(eventName, properties);
1487
1501
  if (this._skanManager) this._skanManager.processEvent(eventName, merged ?? {}).catch(() => {});
@@ -1510,6 +1524,7 @@ var LayersReactNative = class LayersReactNative {
1510
1524
  const depthBefore = this.core.queueDepth();
1511
1525
  this.core.screen(screenName, merged, this.appUserId);
1512
1526
  const depthAfter = this.core.queueDepth();
1527
+ this.schedulePersist();
1513
1528
  if (depthAfter <= depthBefore && this.enableDebug) console.warn(`[Layers] screen("${screenName}") — event may not have been queued (depth before=${String(depthBefore)}, after=${String(depthAfter)})`);
1514
1529
  this.recordRecentEvent(`screen:${screenName}`, properties);
1515
1530
  if (forwardToSkan && this._skanManager) {
@@ -1871,6 +1886,7 @@ var LayersReactNative = class LayersReactNative {
1871
1886
  this.core.setDeviceContext(next);
1872
1887
  }
1873
1888
  async flush() {
1889
+ await this.waitForWrapperFlush();
1874
1890
  try {
1875
1891
  await this.core.flushAsync();
1876
1892
  } catch (e) {
@@ -2143,10 +2159,90 @@ var LayersReactNative = class LayersReactNative {
2143
2159
  * held open only for the write.
2144
2160
  */
2145
2161
  async persistForCrash() {
2162
+ this.cancelPersist();
2146
2163
  try {
2147
2164
  this.core.flush();
2148
2165
  } catch {}
2149
- if (this.persistenceSettle) await this.persistenceSettle();
2166
+ await this.settleWrites();
2167
+ }
2168
+ /**
2169
+ * Resolves once every AsyncStorage write started so far has landed: the
2170
+ * durable backend's, and the eager store's mirror (the only durable copy of
2171
+ * pre-init events until the core swap).
2172
+ */
2173
+ async settleWrites() {
2174
+ await Promise.all([this.eager.settle(), this.persistenceSettle?.()]);
2175
+ }
2176
+ /**
2177
+ * Snapshot the queue to disk within {@link PERSIST_THROTTLE_MS} of an
2178
+ * accepted event.
2179
+ *
2180
+ * The engine writes its crash-safety snapshot only at the flush threshold,
2181
+ * on a delivery verdict, on background and at shutdown. A short session
2182
+ * (the typical lost Android install: 13 events in 13 seconds) reached none
2183
+ * of those before the process died, so its events never left memory.
2184
+ * Throttled rather than per event: each snapshot serializes the whole
2185
+ * queue, and one write per burst also keeps same-key writes apart on
2186
+ * AsyncStorage v3, which does not order them.
2187
+ */
2188
+ schedulePersist() {
2189
+ if (this._persistTimer !== null) return;
2190
+ this._persistTimer = setTimeout(() => {
2191
+ this._persistTimer = null;
2192
+ try {
2193
+ this.core.flush();
2194
+ } catch {}
2195
+ }, LayersReactNative.PERSIST_THROTTLE_MS);
2196
+ }
2197
+ cancelPersist() {
2198
+ if (this._persistTimer !== null) {
2199
+ clearTimeout(this._persistTimer);
2200
+ this._persistTimer = null;
2201
+ }
2202
+ }
2203
+ /**
2204
+ * Start a send owned by the wrapper: optionally wait on `before` (the
2205
+ * background path waits for its snapshot to land), then deliver if online.
2206
+ * Failures are reported through the error listeners and never thrown into
2207
+ * the AppState callback that started it.
2208
+ */
2209
+ startWrapperFlush(before) {
2210
+ const tracked = (async () => {
2211
+ if (before) await before();
2212
+ if (!this.isOnline) return;
2213
+ await this.core.flushAsync();
2214
+ })().catch((e) => {
2215
+ if (e?.code === "SHUT_DOWN") return;
2216
+ this.emitError(e);
2217
+ }).finally(() => {
2218
+ this._wrapperFlushes.delete(tracked);
2219
+ });
2220
+ this._wrapperFlushes.add(tracked);
2221
+ }
2222
+ async waitForWrapperFlush() {
2223
+ if (this._wrapperFlushes.size === 0) return;
2224
+ await Promise.all(Array.from(this._wrapperFlushes));
2225
+ }
2226
+ /**
2227
+ * Make the queue durable, then try to send it. Used at the end of init()
2228
+ * and on the background transition.
2229
+ *
2230
+ * The snapshot is taken synchronously, and the send starts only once that
2231
+ * write has landed. The order matters: the send drains the batch out of the
2232
+ * queue, and a process killed mid-request must still find it on disk next
2233
+ * launch. Before this the background path took the snapshot and stopped,
2234
+ * so nothing was delivered until the app came back to the foreground, and
2235
+ * an Android app is usually killed rather than resumed.
2236
+ */
2237
+ persistThenSend() {
2238
+ this.cancelPersist();
2239
+ try {
2240
+ this.core.flush();
2241
+ } catch (e) {
2242
+ this.emitError(e);
2243
+ return;
2244
+ }
2245
+ this.startWrapperFlush(() => this.settleWrites());
2150
2246
  }
2151
2247
  /**
2152
2248
  * Remove every listener and timer this instance installed, then shut the
@@ -2156,6 +2252,7 @@ var LayersReactNative = class LayersReactNative {
2156
2252
  */
2157
2253
  teardownRuntime() {
2158
2254
  this.stopConfigPolling();
2255
+ this.cancelPersist();
2159
2256
  this.cancelLifecycleReachabilityCheck();
2160
2257
  if (this.appStateSubscription) {
2161
2258
  this.appStateSubscription.remove();
@@ -2522,7 +2619,7 @@ var LayersReactNative = class LayersReactNative {
2522
2619
  this.track("$app_background");
2523
2620
  lastEmittedState = "background";
2524
2621
  } catch {}
2525
- this.core.flush();
2622
+ this.persistThenSend();
2526
2623
  }
2527
2624
  if (nextAppState === "active") {
2528
2625
  if (this.config.autoTrackAppLifecycle !== false && lastEmittedState !== null && lastEmittedState !== "active") try {
@@ -2624,18 +2721,26 @@ var LayersReactNative = class LayersReactNative {
2624
2721
  } catch {}
2625
2722
  }
2626
2723
  };
2724
+ function createKeyedStorageQueue() {
2725
+ const tails = /* @__PURE__ */ new Map();
2726
+ const inFlight = /* @__PURE__ */ new Set();
2727
+ return {
2728
+ run(fullKey, operation) {
2729
+ const entry = (tails.get(fullKey) ?? Promise.resolve()).then(operation, operation).then(() => void 0, () => void 0);
2730
+ tails.set(fullKey, entry);
2731
+ inFlight.add(entry);
2732
+ entry.then(() => {
2733
+ inFlight.delete(entry);
2734
+ if (tails.get(fullKey) === entry) tails.delete(fullKey);
2735
+ });
2736
+ },
2737
+ settle: () => Promise.all(Array.from(inFlight)).then(() => void 0)
2738
+ };
2739
+ }
2627
2740
  async function createAsyncStoragePersistence(appId) {
2628
2741
  const prefix = `layers_sdk_${appId}_`;
2629
2742
  const memoryStore = /* @__PURE__ */ new Map();
2630
- const inFlight = /* @__PURE__ */ new Set();
2631
- const trackInFlight = (operation) => {
2632
- const entry = operation.then(() => {
2633
- inFlight.delete(entry);
2634
- }, () => {
2635
- inFlight.delete(entry);
2636
- });
2637
- inFlight.add(entry);
2638
- };
2743
+ const queue = createKeyedStorageQueue();
2639
2744
  try {
2640
2745
  const AsyncStorage = await loadAsyncStorage();
2641
2746
  if (AsyncStorage) {
@@ -2654,15 +2759,16 @@ async function createAsyncStoragePersistence(appId) {
2654
2759
  return {
2655
2760
  backend: {
2656
2761
  write(key, data) {
2657
- memoryStore.set(key, new Uint8Array(data));
2658
- trackInFlight(writeToAsyncStorage(prefix + key, data));
2762
+ const copy = new Uint8Array(data);
2763
+ memoryStore.set(key, copy);
2764
+ queue.run(prefix + key, () => writeToAsyncStorage(prefix + key, copy));
2659
2765
  },
2660
2766
  read(key) {
2661
2767
  return memoryStore.get(key) ?? null;
2662
2768
  },
2663
2769
  delete(key) {
2664
2770
  memoryStore.delete(key);
2665
- trackInFlight(deleteFromAsyncStorage(prefix + key));
2771
+ queue.run(prefix + key, () => deleteFromAsyncStorage(prefix + key));
2666
2772
  },
2667
2773
  listKeys(keyPrefix) {
2668
2774
  const keys = [];
@@ -2671,7 +2777,57 @@ async function createAsyncStoragePersistence(appId) {
2671
2777
  return keys;
2672
2778
  }
2673
2779
  },
2674
- settle: () => Promise.all(Array.from(inFlight)).then(() => void 0)
2780
+ settle: queue.settle,
2781
+ forget: (keyPrefix) => {
2782
+ for (const key of [...memoryStore.keys()]) if (key.startsWith(keyPrefix)) memoryStore.delete(key);
2783
+ }
2784
+ };
2785
+ }
2786
+ function createEagerPersistence(appId) {
2787
+ const prefix = `layers_sdk_${appId}_`;
2788
+ const mirrorKeyPrefix = `events_eager_${`${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`}_`;
2789
+ const memoryStore = /* @__PURE__ */ new Map();
2790
+ const mirrored = /* @__PURE__ */ new Set();
2791
+ const queue = createKeyedStorageQueue();
2792
+ let mirroring = true;
2793
+ return {
2794
+ backend: {
2795
+ write(key, data) {
2796
+ const copy = new Uint8Array(data);
2797
+ memoryStore.set(key, copy);
2798
+ if (mirroring && key.startsWith("events_")) {
2799
+ const fullKey = prefix + mirrorKeyPrefix + key;
2800
+ mirrored.add(fullKey);
2801
+ queue.run(fullKey, () => writeToAsyncStorage(fullKey, copy));
2802
+ }
2803
+ },
2804
+ read(key) {
2805
+ return memoryStore.get(key) ?? null;
2806
+ },
2807
+ delete(key) {
2808
+ memoryStore.delete(key);
2809
+ if (mirroring && key.startsWith("events_")) {
2810
+ const fullKey = prefix + mirrorKeyPrefix + key;
2811
+ queue.run(fullKey, () => deleteFromAsyncStorage(fullKey));
2812
+ }
2813
+ },
2814
+ listKeys(keyPrefix) {
2815
+ const keys = [];
2816
+ for (const k of memoryStore.keys()) if (k.startsWith(keyPrefix)) keys.push(k);
2817
+ keys.sort();
2818
+ return keys;
2819
+ }
2820
+ },
2821
+ mirrorKeyPrefix,
2822
+ stopMirroring: () => {
2823
+ mirroring = false;
2824
+ },
2825
+ settle: queue.settle,
2826
+ discardMirror: async () => {
2827
+ for (const key of mirrored) queue.run(key, () => deleteFromAsyncStorage(key));
2828
+ mirrored.clear();
2829
+ await queue.settle();
2830
+ }
2675
2831
  };
2676
2832
  }
2677
2833
  const B64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -1,7 +1,7 @@
1
1
  import { t as __require } from "./chunk-COTuXS2J.mjs";
2
2
  import { a as requestTrackingAuthorization, n as getAdvertisingId, r as getVendorId } from "./att-CnlG_CuV.mjs";
3
3
  import { r as setSkanCore, t as SKANManager } from "./skan-DO7MLv2w.mjs";
4
- import { FetchHttpClient, LayersCore, LayersError as LayersError$1, LayersEvent, MemoryPersistence, addToCartEvent as buildAddToCartEvent, beginCheckoutEvent as buildBeginCheckoutEvent, initWasm, onboardingCompleteEvent as buildOnboardingCompleteEvent, onboardingStartEvent as buildOnboardingStartEvent, paywallShowEvent as buildPaywallShowEvent, purchaseEvent as buildPurchaseEvent, refundEvent as buildRefundEvent, startTrialEvent as buildStartTrialEvent, subscribeEvent as buildSubscribeEvent, viewItemEvent as buildViewItemEvent } from "@layers/core-wasm";
4
+ import { FetchHttpClient, LayersCore, LayersError as LayersError$1, LayersEvent, addToCartEvent as buildAddToCartEvent, beginCheckoutEvent as buildBeginCheckoutEvent, initWasm, onboardingCompleteEvent as buildOnboardingCompleteEvent, onboardingStartEvent as buildOnboardingStartEvent, paywallShowEvent as buildPaywallShowEvent, purchaseEvent as buildPurchaseEvent, refundEvent as buildRefundEvent, startTrialEvent as buildStartTrialEvent, subscribeEvent as buildSubscribeEvent, viewItemEvent as buildViewItemEvent } from "@layers/core-wasm";
5
5
 
6
6
  //#region src/exceptions.ts
7
7
  /** Cap on the serialized stack length to keep payloads sane. */
@@ -1122,16 +1122,21 @@ function hostAppIsRegisteredOn(rn) {
1122
1122
  }
1123
1123
  }
1124
1124
  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'.";
1125
- const SDK_VERSION = "3.3.3";
1125
+ const SDK_VERSION = "3.3.4";
1126
1126
  var LayersReactNative = class LayersReactNative {
1127
1127
  core;
1128
- eagerPersistence;
1128
+ eager;
1129
+ get eagerPersistence() {
1130
+ return this.eager.backend;
1131
+ }
1129
1132
  appUserId;
1130
1133
  isOnline = true;
1131
1134
  enableDebug;
1132
1135
  appStateSubscription = null;
1133
1136
  exceptionUninstall = null;
1134
1137
  persistenceSettle = null;
1138
+ _persistTimer = null;
1139
+ _wrapperFlushes = /* @__PURE__ */ new Set();
1135
1140
  _lifecycleCheckTimer = null;
1136
1141
  netInfoUnsubscribe = null;
1137
1142
  config;
@@ -1148,6 +1153,7 @@ var LayersReactNative = class LayersReactNative {
1148
1153
  _runtimeGeneration = 0;
1149
1154
  _configPollTimer = null;
1150
1155
  static CONFIG_POLL_INTERVAL_MS = 3e5;
1156
+ static PERSIST_THROTTLE_MS = 1e3;
1151
1157
  _adServicesToken = null;
1152
1158
  _installReferrer = null;
1153
1159
  _gaid = null;
@@ -1172,7 +1178,7 @@ var LayersReactNative = class LayersReactNative {
1172
1178
  this.appUserId = config.appUserId;
1173
1179
  this.config = config;
1174
1180
  const httpClient = new FetchHttpClient();
1175
- this.eagerPersistence = new MemoryPersistence();
1181
+ this.eager = createEagerPersistence(config.appId);
1176
1182
  this.core = LayersCore.init({
1177
1183
  config: {
1178
1184
  appId: config.appId,
@@ -1318,7 +1324,7 @@ var LayersReactNative = class LayersReactNative {
1318
1324
  if (this.initAborted(generation)) return;
1319
1325
  this._hadPriorAppIdentity = false;
1320
1326
  try {
1321
- const { backend: persistence, settle: persistenceSettle } = await createAsyncStoragePersistence(this.config.appId);
1327
+ const { backend: persistence, settle: persistenceSettle, forget: forgetPreloaded } = await createAsyncStoragePersistence(this.config.appId);
1322
1328
  try {
1323
1329
  const record = persistence.read("identity_state");
1324
1330
  this._hadPriorAppIdentity = record != null && record.length > 0;
@@ -1329,6 +1335,7 @@ var LayersReactNative = class LayersReactNative {
1329
1335
  this.persistenceSettle = persistenceSettle;
1330
1336
  const httpClient = new FetchHttpClient();
1331
1337
  const migrationState = this.core.exportMigrationState();
1338
+ this.eager.stopMirroring();
1332
1339
  this.core.shutdown();
1333
1340
  try {
1334
1341
  let migrated = 0;
@@ -1341,6 +1348,7 @@ var LayersReactNative = class LayersReactNative {
1341
1348
  this.eagerPersistence.delete(key);
1342
1349
  }
1343
1350
  } catch {}
1351
+ forgetPreloaded(this.eager.mirrorKeyPrefix);
1344
1352
  this.core = LayersCore.init({
1345
1353
  config: {
1346
1354
  appId: this.config.appId,
@@ -1361,6 +1369,10 @@ var LayersReactNative = class LayersReactNative {
1361
1369
  this._runtimeGeneration = generation;
1362
1370
  setSkanCore(this.core);
1363
1371
  if (this.appUserId) this.core.identify(this.appUserId);
1372
+ try {
1373
+ this.core.flush();
1374
+ } catch {}
1375
+ persistenceSettle().then(() => this.eager.discardMirror()).catch(() => void 0);
1364
1376
  } catch {}
1365
1377
  await this.restoreAttributionData();
1366
1378
  await this.initializeDeviceInfo();
@@ -1466,6 +1478,7 @@ var LayersReactNative = class LayersReactNative {
1466
1478
  ...typeof __DEV__ !== "undefined" && __DEV__ === true ? {} : { onFatal: () => this.persistForCrash() }
1467
1479
  });
1468
1480
  this._isInitialized = true;
1481
+ this.persistThenSend();
1469
1482
  const totalDurationMs = Date.now() - initStartTime;
1470
1483
  if (this.enableDebug) console.log(`[Layers] Init timing: mainThread=${String(mainThreadDurationMs)}ms, total=${String(totalDurationMs)}ms`);
1471
1484
  if (this._initListener) try {
@@ -1481,6 +1494,7 @@ var LayersReactNative = class LayersReactNative {
1481
1494
  const depthBefore = this.core.queueDepth();
1482
1495
  this.core.track(eventName, merged, this.appUserId);
1483
1496
  const depthAfter = this.core.queueDepth();
1497
+ this.schedulePersist();
1484
1498
  if (depthAfter <= depthBefore && this.enableDebug) console.warn(`[Layers] track("${eventName}") — event may not have been queued (depth before=${String(depthBefore)}, after=${String(depthAfter)})`);
1485
1499
  this.recordRecentEvent(eventName, properties);
1486
1500
  if (this._skanManager) this._skanManager.processEvent(eventName, merged ?? {}).catch(() => {});
@@ -1509,6 +1523,7 @@ var LayersReactNative = class LayersReactNative {
1509
1523
  const depthBefore = this.core.queueDepth();
1510
1524
  this.core.screen(screenName, merged, this.appUserId);
1511
1525
  const depthAfter = this.core.queueDepth();
1526
+ this.schedulePersist();
1512
1527
  if (depthAfter <= depthBefore && this.enableDebug) console.warn(`[Layers] screen("${screenName}") — event may not have been queued (depth before=${String(depthBefore)}, after=${String(depthAfter)})`);
1513
1528
  this.recordRecentEvent(`screen:${screenName}`, properties);
1514
1529
  if (forwardToSkan && this._skanManager) {
@@ -1870,6 +1885,7 @@ var LayersReactNative = class LayersReactNative {
1870
1885
  this.core.setDeviceContext(next);
1871
1886
  }
1872
1887
  async flush() {
1888
+ await this.waitForWrapperFlush();
1873
1889
  try {
1874
1890
  await this.core.flushAsync();
1875
1891
  } catch (e) {
@@ -2142,10 +2158,90 @@ var LayersReactNative = class LayersReactNative {
2142
2158
  * held open only for the write.
2143
2159
  */
2144
2160
  async persistForCrash() {
2161
+ this.cancelPersist();
2145
2162
  try {
2146
2163
  this.core.flush();
2147
2164
  } catch {}
2148
- if (this.persistenceSettle) await this.persistenceSettle();
2165
+ await this.settleWrites();
2166
+ }
2167
+ /**
2168
+ * Resolves once every AsyncStorage write started so far has landed: the
2169
+ * durable backend's, and the eager store's mirror (the only durable copy of
2170
+ * pre-init events until the core swap).
2171
+ */
2172
+ async settleWrites() {
2173
+ await Promise.all([this.eager.settle(), this.persistenceSettle?.()]);
2174
+ }
2175
+ /**
2176
+ * Snapshot the queue to disk within {@link PERSIST_THROTTLE_MS} of an
2177
+ * accepted event.
2178
+ *
2179
+ * The engine writes its crash-safety snapshot only at the flush threshold,
2180
+ * on a delivery verdict, on background and at shutdown. A short session
2181
+ * (the typical lost Android install: 13 events in 13 seconds) reached none
2182
+ * of those before the process died, so its events never left memory.
2183
+ * Throttled rather than per event: each snapshot serializes the whole
2184
+ * queue, and one write per burst also keeps same-key writes apart on
2185
+ * AsyncStorage v3, which does not order them.
2186
+ */
2187
+ schedulePersist() {
2188
+ if (this._persistTimer !== null) return;
2189
+ this._persistTimer = setTimeout(() => {
2190
+ this._persistTimer = null;
2191
+ try {
2192
+ this.core.flush();
2193
+ } catch {}
2194
+ }, LayersReactNative.PERSIST_THROTTLE_MS);
2195
+ }
2196
+ cancelPersist() {
2197
+ if (this._persistTimer !== null) {
2198
+ clearTimeout(this._persistTimer);
2199
+ this._persistTimer = null;
2200
+ }
2201
+ }
2202
+ /**
2203
+ * Start a send owned by the wrapper: optionally wait on `before` (the
2204
+ * background path waits for its snapshot to land), then deliver if online.
2205
+ * Failures are reported through the error listeners and never thrown into
2206
+ * the AppState callback that started it.
2207
+ */
2208
+ startWrapperFlush(before) {
2209
+ const tracked = (async () => {
2210
+ if (before) await before();
2211
+ if (!this.isOnline) return;
2212
+ await this.core.flushAsync();
2213
+ })().catch((e) => {
2214
+ if (e?.code === "SHUT_DOWN") return;
2215
+ this.emitError(e);
2216
+ }).finally(() => {
2217
+ this._wrapperFlushes.delete(tracked);
2218
+ });
2219
+ this._wrapperFlushes.add(tracked);
2220
+ }
2221
+ async waitForWrapperFlush() {
2222
+ if (this._wrapperFlushes.size === 0) return;
2223
+ await Promise.all(Array.from(this._wrapperFlushes));
2224
+ }
2225
+ /**
2226
+ * Make the queue durable, then try to send it. Used at the end of init()
2227
+ * and on the background transition.
2228
+ *
2229
+ * The snapshot is taken synchronously, and the send starts only once that
2230
+ * write has landed. The order matters: the send drains the batch out of the
2231
+ * queue, and a process killed mid-request must still find it on disk next
2232
+ * launch. Before this the background path took the snapshot and stopped,
2233
+ * so nothing was delivered until the app came back to the foreground, and
2234
+ * an Android app is usually killed rather than resumed.
2235
+ */
2236
+ persistThenSend() {
2237
+ this.cancelPersist();
2238
+ try {
2239
+ this.core.flush();
2240
+ } catch (e) {
2241
+ this.emitError(e);
2242
+ return;
2243
+ }
2244
+ this.startWrapperFlush(() => this.settleWrites());
2149
2245
  }
2150
2246
  /**
2151
2247
  * Remove every listener and timer this instance installed, then shut the
@@ -2155,6 +2251,7 @@ var LayersReactNative = class LayersReactNative {
2155
2251
  */
2156
2252
  teardownRuntime() {
2157
2253
  this.stopConfigPolling();
2254
+ this.cancelPersist();
2158
2255
  this.cancelLifecycleReachabilityCheck();
2159
2256
  if (this.appStateSubscription) {
2160
2257
  this.appStateSubscription.remove();
@@ -2521,7 +2618,7 @@ var LayersReactNative = class LayersReactNative {
2521
2618
  this.track("$app_background");
2522
2619
  lastEmittedState = "background";
2523
2620
  } catch {}
2524
- this.core.flush();
2621
+ this.persistThenSend();
2525
2622
  }
2526
2623
  if (nextAppState === "active") {
2527
2624
  if (this.config.autoTrackAppLifecycle !== false && lastEmittedState !== null && lastEmittedState !== "active") try {
@@ -2623,18 +2720,26 @@ var LayersReactNative = class LayersReactNative {
2623
2720
  } catch {}
2624
2721
  }
2625
2722
  };
2723
+ function createKeyedStorageQueue() {
2724
+ const tails = /* @__PURE__ */ new Map();
2725
+ const inFlight = /* @__PURE__ */ new Set();
2726
+ return {
2727
+ run(fullKey, operation) {
2728
+ const entry = (tails.get(fullKey) ?? Promise.resolve()).then(operation, operation).then(() => void 0, () => void 0);
2729
+ tails.set(fullKey, entry);
2730
+ inFlight.add(entry);
2731
+ entry.then(() => {
2732
+ inFlight.delete(entry);
2733
+ if (tails.get(fullKey) === entry) tails.delete(fullKey);
2734
+ });
2735
+ },
2736
+ settle: () => Promise.all(Array.from(inFlight)).then(() => void 0)
2737
+ };
2738
+ }
2626
2739
  async function createAsyncStoragePersistence(appId) {
2627
2740
  const prefix = `layers_sdk_${appId}_`;
2628
2741
  const memoryStore = /* @__PURE__ */ new Map();
2629
- const inFlight = /* @__PURE__ */ new Set();
2630
- const trackInFlight = (operation) => {
2631
- const entry = operation.then(() => {
2632
- inFlight.delete(entry);
2633
- }, () => {
2634
- inFlight.delete(entry);
2635
- });
2636
- inFlight.add(entry);
2637
- };
2742
+ const queue = createKeyedStorageQueue();
2638
2743
  try {
2639
2744
  const AsyncStorage = await loadAsyncStorage();
2640
2745
  if (AsyncStorage) {
@@ -2653,15 +2758,16 @@ async function createAsyncStoragePersistence(appId) {
2653
2758
  return {
2654
2759
  backend: {
2655
2760
  write(key, data) {
2656
- memoryStore.set(key, new Uint8Array(data));
2657
- trackInFlight(writeToAsyncStorage(prefix + key, data));
2761
+ const copy = new Uint8Array(data);
2762
+ memoryStore.set(key, copy);
2763
+ queue.run(prefix + key, () => writeToAsyncStorage(prefix + key, copy));
2658
2764
  },
2659
2765
  read(key) {
2660
2766
  return memoryStore.get(key) ?? null;
2661
2767
  },
2662
2768
  delete(key) {
2663
2769
  memoryStore.delete(key);
2664
- trackInFlight(deleteFromAsyncStorage(prefix + key));
2770
+ queue.run(prefix + key, () => deleteFromAsyncStorage(prefix + key));
2665
2771
  },
2666
2772
  listKeys(keyPrefix) {
2667
2773
  const keys = [];
@@ -2670,7 +2776,57 @@ async function createAsyncStoragePersistence(appId) {
2670
2776
  return keys;
2671
2777
  }
2672
2778
  },
2673
- settle: () => Promise.all(Array.from(inFlight)).then(() => void 0)
2779
+ settle: queue.settle,
2780
+ forget: (keyPrefix) => {
2781
+ for (const key of [...memoryStore.keys()]) if (key.startsWith(keyPrefix)) memoryStore.delete(key);
2782
+ }
2783
+ };
2784
+ }
2785
+ function createEagerPersistence(appId) {
2786
+ const prefix = `layers_sdk_${appId}_`;
2787
+ const mirrorKeyPrefix = `events_eager_${`${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`}_`;
2788
+ const memoryStore = /* @__PURE__ */ new Map();
2789
+ const mirrored = /* @__PURE__ */ new Set();
2790
+ const queue = createKeyedStorageQueue();
2791
+ let mirroring = true;
2792
+ return {
2793
+ backend: {
2794
+ write(key, data) {
2795
+ const copy = new Uint8Array(data);
2796
+ memoryStore.set(key, copy);
2797
+ if (mirroring && key.startsWith("events_")) {
2798
+ const fullKey = prefix + mirrorKeyPrefix + key;
2799
+ mirrored.add(fullKey);
2800
+ queue.run(fullKey, () => writeToAsyncStorage(fullKey, copy));
2801
+ }
2802
+ },
2803
+ read(key) {
2804
+ return memoryStore.get(key) ?? null;
2805
+ },
2806
+ delete(key) {
2807
+ memoryStore.delete(key);
2808
+ if (mirroring && key.startsWith("events_")) {
2809
+ const fullKey = prefix + mirrorKeyPrefix + key;
2810
+ queue.run(fullKey, () => deleteFromAsyncStorage(fullKey));
2811
+ }
2812
+ },
2813
+ listKeys(keyPrefix) {
2814
+ const keys = [];
2815
+ for (const k of memoryStore.keys()) if (k.startsWith(keyPrefix)) keys.push(k);
2816
+ keys.sort();
2817
+ return keys;
2818
+ }
2819
+ },
2820
+ mirrorKeyPrefix,
2821
+ stopMirroring: () => {
2822
+ mirroring = false;
2823
+ },
2824
+ settle: queue.settle,
2825
+ discardMirror: async () => {
2826
+ for (const key of mirrored) queue.run(key, () => deleteFromAsyncStorage(key));
2827
+ mirrored.clear();
2828
+ await queue.settle();
2829
+ }
2674
2830
  };
2675
2831
  }
2676
2832
  const B64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -3248,4 +3404,4 @@ function useLayersExpoRouterTracking(sdkInstance, usePathname, useGlobalSearchPa
3248
3404
 
3249
3405
  //#endregion
3250
3406
  export { superwallTrackSkip as $, useLayersNavigationTracking as A, trackAddToCart as B, readClipboardAttribution as C, installExceptionAutoCapture as Ct, SurveysModule as D, useLayersExpoRouterTracking as E, connectRevenueCat as F, trackRefund as G, trackOrder as H, isRevenueCatConnected as I, trackViewProduct as J, trackRemoveFromCart as K, resetRevenueCatForTesting as L, BACKGROUND_FLUSH_TASK_NAME as M, createBackgroundFlushHandler as N, createNavigationListener as O, registerExpoBackgroundFlush as P, superwallTrackPurchase as Q, syncRevenueCatAttributes as R, parseInstallReferrerUrl as S, buildExceptionProperties as St, shouldTreatAsNewInstall as T, trackPurchase as U, trackBeginCheckout as V, trackPurchaseFailed as W, superwallTrackDismiss as X, superwallOnEvent as Y, superwallTrackPresentation as Z, getFirstInstallTime as _, startTrialEvent as _t, buildBeginCheckoutEvent as a, levelCompleteEvent as at, getOrSetInstallId as b, viewContentEvent as bt, buildOnboardingStartEvent as c, onboardingCompleteEvent as ct, buildRefundEvent as d, purchaseEvent as dt, superwallUserAttributes as et, buildStartTrialEvent as f, registerEvent as ft, getAdServicesToken as g, signUpEvent as gt, formatFbc as h, shareEvent as ht, buildAddToCartEvent as i, initiateCheckoutEvent as it, BACKGROUND_FLUSH_MIN_INTERVAL_MINUTES as j, resolveActiveRoute as k, buildPaywallShowEvent as l, onboardingStartEvent as lt, buildViewItemEvent as m, searchEvent as mt, LayersEvent as n, addToCartEvent as nt, buildInstallReferrerProperties as o, levelStartEvent as ot, buildSubscribeEvent as p, screenViewEvent as pt, trackSubscription as q, LayersReactNative as r, addToWishlistEvent as rt, buildOnboardingCompleteEvent as s, loginEvent as st, LayersError$1 as t, StandardEvents as tt, buildPurchaseEvent as u, paywallShowEvent as ut, getGoogleAdvertisingId as v, subscribeEvent as vt, setupDeepLinkListener as w, parseDeepLink as x, viewItemEvent as xt, getInstallReferrer as y, tutorialCompleteEvent as yt, trackRevenueCatPurchase as z };
3251
- //# sourceMappingURL=src-BhzpYUDb.mjs.map
3407
+ //# sourceMappingURL=src-DnutJ2iZ.mjs.map