@layers/react-native 3.3.2 → 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.
@@ -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. */
@@ -711,8 +711,9 @@ function connectRevenueCat(config, purchases) {
711
711
  purchases.addCustomerInfoUpdateListener((info) => {
712
712
  handleCustomerInfoUpdate(config, info, false);
713
713
  });
714
- purchases.getCustomerInfo().then(({ customerInfo }) => {
715
- handleCustomerInfoUpdate(config, customerInfo, true);
714
+ purchases.getCustomerInfo().then((result) => {
715
+ const customerInfo = unwrapCustomerInfo(result);
716
+ if (customerInfo) handleCustomerInfoUpdate(config, customerInfo, true);
716
717
  }).catch(() => {});
717
718
  _isConnected = true;
718
719
  } catch {}
@@ -772,6 +773,18 @@ function resetRevenueCatForTesting() {
772
773
  function isRevenueCatConnected() {
773
774
  return _isConnected;
774
775
  }
776
+ /**
777
+ * Accept both shapes `getCustomerInfo()` can resolve to: the `CustomerInfo`
778
+ * object `react-native-purchases` actually returns, and a `{ customerInfo }`
779
+ * wrapper. Destructuring `{ customerInfo }` from the real return read
780
+ * `undefined`, so the first subscriber sync never ran.
781
+ */
782
+ function unwrapCustomerInfo(result) {
783
+ if (!result || typeof result !== "object") return null;
784
+ const wrapped = result.customerInfo;
785
+ if (wrapped && typeof wrapped === "object") return wrapped;
786
+ return result;
787
+ }
775
788
  function handleCustomerInfoUpdate(config, info, isInitialLoad) {
776
789
  try {
777
790
  const currentSubs = new Set(Array.isArray(info.activeSubscriptions) ? info.activeSubscriptions : []);
@@ -1109,16 +1122,21 @@ function hostAppIsRegisteredOn(rn) {
1109
1122
  }
1110
1123
  }
1111
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'.";
1112
- const SDK_VERSION = "3.3.2";
1125
+ const SDK_VERSION = "3.3.4";
1113
1126
  var LayersReactNative = class LayersReactNative {
1114
1127
  core;
1115
- eagerPersistence;
1128
+ eager;
1129
+ get eagerPersistence() {
1130
+ return this.eager.backend;
1131
+ }
1116
1132
  appUserId;
1117
1133
  isOnline = true;
1118
1134
  enableDebug;
1119
1135
  appStateSubscription = null;
1120
1136
  exceptionUninstall = null;
1121
1137
  persistenceSettle = null;
1138
+ _persistTimer = null;
1139
+ _wrapperFlushes = /* @__PURE__ */ new Set();
1122
1140
  _lifecycleCheckTimer = null;
1123
1141
  netInfoUnsubscribe = null;
1124
1142
  config;
@@ -1135,10 +1153,13 @@ var LayersReactNative = class LayersReactNative {
1135
1153
  _runtimeGeneration = 0;
1136
1154
  _configPollTimer = null;
1137
1155
  static CONFIG_POLL_INTERVAL_MS = 3e5;
1156
+ static PERSIST_THROTTLE_MS = 1e3;
1138
1157
  _adServicesToken = null;
1139
1158
  _installReferrer = null;
1159
+ _gaid = null;
1140
1160
  _installReferrerParams = null;
1141
1161
  _hadPriorSdkState = false;
1162
+ _hadPriorAppIdentity = false;
1142
1163
  _attributionDeeplinkId = null;
1143
1164
  _attributionGclid = null;
1144
1165
  _attributionFbclid = null;
@@ -1157,7 +1178,7 @@ var LayersReactNative = class LayersReactNative {
1157
1178
  this.appUserId = config.appUserId;
1158
1179
  this.config = config;
1159
1180
  const httpClient = new FetchHttpClient();
1160
- this.eagerPersistence = new MemoryPersistence();
1181
+ this.eager = createEagerPersistence(config.appId);
1161
1182
  this.core = LayersCore.init({
1162
1183
  config: {
1163
1184
  appId: config.appId,
@@ -1301,12 +1322,20 @@ var LayersReactNative = class LayersReactNative {
1301
1322
  const initStartTime = Date.now();
1302
1323
  if (typeof WebAssembly !== "undefined") await initWasm();
1303
1324
  if (this.initAborted(generation)) return;
1325
+ this._hadPriorAppIdentity = false;
1304
1326
  try {
1305
- const { backend: persistence, settle: persistenceSettle } = await createAsyncStoragePersistence(this.config.appId);
1327
+ const { backend: persistence, settle: persistenceSettle, forget: forgetPreloaded } = await createAsyncStoragePersistence(this.config.appId);
1328
+ try {
1329
+ const record = persistence.read("identity_state");
1330
+ this._hadPriorAppIdentity = record != null && record.length > 0;
1331
+ } catch {
1332
+ this._hadPriorAppIdentity = false;
1333
+ }
1306
1334
  if (this.initAborted(generation)) return;
1307
1335
  this.persistenceSettle = persistenceSettle;
1308
1336
  const httpClient = new FetchHttpClient();
1309
1337
  const migrationState = this.core.exportMigrationState();
1338
+ this.eager.stopMirroring();
1310
1339
  this.core.shutdown();
1311
1340
  try {
1312
1341
  let migrated = 0;
@@ -1319,6 +1348,7 @@ var LayersReactNative = class LayersReactNative {
1319
1348
  this.eagerPersistence.delete(key);
1320
1349
  }
1321
1350
  } catch {}
1351
+ forgetPreloaded(this.eager.mirrorKeyPrefix);
1322
1352
  this.core = LayersCore.init({
1323
1353
  config: {
1324
1354
  appId: this.config.appId,
@@ -1339,6 +1369,10 @@ var LayersReactNative = class LayersReactNative {
1339
1369
  this._runtimeGeneration = generation;
1340
1370
  setSkanCore(this.core);
1341
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);
1342
1376
  } catch {}
1343
1377
  await this.restoreAttributionData();
1344
1378
  await this.initializeDeviceInfo();
@@ -1372,6 +1406,7 @@ var LayersReactNative = class LayersReactNative {
1372
1406
  if (this.config.autoTrackAppOpen !== false) {
1373
1407
  const appOpenProps = {};
1374
1408
  let isFirstLaunchByFlag = true;
1409
+ let priorLaunchDecided = false;
1375
1410
  try {
1376
1411
  const AsyncStorage = await loadAsyncStorage();
1377
1412
  if (AsyncStorage) {
@@ -1386,14 +1421,16 @@ var LayersReactNative = class LayersReactNative {
1386
1421
  }
1387
1422
  }
1388
1423
  if (flag === "true") isFirstLaunchByFlag = false;
1424
+ if (isFirstLaunchByFlag && this._hadPriorAppIdentity) priorLaunchDecided = await AsyncStorage.getItem(LAST_APP_VERSION_KEY) !== null;
1389
1425
  if (adoptLegacy) try {
1390
1426
  await AsyncStorage.setItem(scopedKey, "true");
1391
1427
  await AsyncStorage.removeItem(FIRST_LAUNCH_TRACKED_KEY_LEGACY);
1392
1428
  } catch {}
1393
1429
  }
1394
1430
  } catch {}
1395
- const isFirstLaunch = await shouldTreatAsNewInstall(isFirstLaunchByFlag, this._hadPriorSdkState, this.enableDebug);
1431
+ const isFirstLaunch = await shouldTreatAsNewInstall(isFirstLaunchByFlag, this._hadPriorSdkState, this.enableDebug, () => this.readFirstInstallTime(), priorLaunchDecided);
1396
1432
  appOpenProps.is_first_launch = isFirstLaunch;
1433
+ if (isFirstLaunchByFlag && !isFirstLaunch) await this.persistFirstLaunchHandled();
1397
1434
  let hasAttribution = this._attributionFbclid != null || this._attributionGclid != null || this._attributionTtclid != null || this._attributionMsclkid != null;
1398
1435
  if (fingerprintResolveEnabled && isFirstLaunch && !hasAttribution) try {
1399
1436
  await this.resolveClickFromFingerprint();
@@ -1414,10 +1451,7 @@ var LayersReactNative = class LayersReactNative {
1414
1451
  if (this.initAborted(generation)) return;
1415
1452
  if (isFirstLaunch) this.track("app_install", appOpenProps);
1416
1453
  this.track("app_open", appOpenProps);
1417
- if (isFirstLaunch) try {
1418
- const AsyncStorage = await loadAsyncStorage();
1419
- if (AsyncStorage) await AsyncStorage.setItem(firstLaunchTrackedKey(this.config.appId), "true");
1420
- } catch {}
1454
+ if (isFirstLaunch) await this.persistFirstLaunchHandled();
1421
1455
  if (this.config.autoTrackAppUpdate !== false) try {
1422
1456
  const currentVersion = this.core.getDeviceContext().appVersion ?? appOpenProps.app_version;
1423
1457
  if (currentVersion && typeof currentVersion === "string") {
@@ -1444,6 +1478,7 @@ var LayersReactNative = class LayersReactNative {
1444
1478
  ...typeof __DEV__ !== "undefined" && __DEV__ === true ? {} : { onFatal: () => this.persistForCrash() }
1445
1479
  });
1446
1480
  this._isInitialized = true;
1481
+ this.persistThenSend();
1447
1482
  const totalDurationMs = Date.now() - initStartTime;
1448
1483
  if (this.enableDebug) console.log(`[Layers] Init timing: mainThread=${String(mainThreadDurationMs)}ms, total=${String(totalDurationMs)}ms`);
1449
1484
  if (this._initListener) try {
@@ -1459,6 +1494,7 @@ var LayersReactNative = class LayersReactNative {
1459
1494
  const depthBefore = this.core.queueDepth();
1460
1495
  this.core.track(eventName, merged, this.appUserId);
1461
1496
  const depthAfter = this.core.queueDepth();
1497
+ this.schedulePersist();
1462
1498
  if (depthAfter <= depthBefore && this.enableDebug) console.warn(`[Layers] track("${eventName}") — event may not have been queued (depth before=${String(depthBefore)}, after=${String(depthAfter)})`);
1463
1499
  this.recordRecentEvent(eventName, properties);
1464
1500
  if (this._skanManager) this._skanManager.processEvent(eventName, merged ?? {}).catch(() => {});
@@ -1487,6 +1523,7 @@ var LayersReactNative = class LayersReactNative {
1487
1523
  const depthBefore = this.core.queueDepth();
1488
1524
  this.core.screen(screenName, merged, this.appUserId);
1489
1525
  const depthAfter = this.core.queueDepth();
1526
+ this.schedulePersist();
1490
1527
  if (depthAfter <= depthBefore && this.enableDebug) console.warn(`[Layers] screen("${screenName}") — event may not have been queued (depth before=${String(depthBefore)}, after=${String(depthAfter)})`);
1491
1528
  this.recordRecentEvent(`screen:${screenName}`, properties);
1492
1529
  if (forwardToSkan && this._skanManager) {
@@ -1508,6 +1545,47 @@ var LayersReactNative = class LayersReactNative {
1508
1545
  }
1509
1546
  async setConsent(consent) {
1510
1547
  this.core.setConsent(consent);
1548
+ this.applyGaidConsent();
1549
+ }
1550
+ /**
1551
+ * Whether the app has explicitly denied advertising consent
1552
+ * (`adStorage: false`, or the legacy `advertising: false`). Unset means
1553
+ * allowed, the same default as the engine's ad gate and the Kotlin SDK.
1554
+ */
1555
+ advertisingConsentDenied() {
1556
+ try {
1557
+ const consent = this.core.getConsentState();
1558
+ return (consent.adStorage ?? consent.advertising) === false;
1559
+ } catch {
1560
+ return false;
1561
+ }
1562
+ }
1563
+ /**
1564
+ * Keep the Google Advertising ID on the device context unless the app has
1565
+ * explicitly denied advertising consent, and take it off when it has.
1566
+ *
1567
+ * The GAID is sent by default, as mobile measurement partners and the
1568
+ * Kotlin SDK do. It honours two opt-outs: the user's Limit Ad Tracking
1569
+ * setting (applied where the GAID is read) and the app's consent API.
1570
+ * Revoking removes it from later events and re-granting restores it. No
1571
+ * `att_status` is set on Android: that field carries Apple's ATT answer.
1572
+ */
1573
+ applyGaidConsent() {
1574
+ const gaid = this._gaid;
1575
+ if (!gaid) return;
1576
+ try {
1577
+ const context = this.core.getDeviceContext();
1578
+ const granted = !this.advertisingConsentDenied();
1579
+ if (granted && context.idfa !== gaid) this.core.setDeviceContext({
1580
+ ...context,
1581
+ idfa: gaid
1582
+ });
1583
+ else if (!granted && context.idfa === gaid) {
1584
+ const next = { ...context };
1585
+ delete next.idfa;
1586
+ this.core.setDeviceContext(next);
1587
+ }
1588
+ } catch {}
1511
1589
  }
1512
1590
  /** Evaluate a feature flag. Emits `$feature_flag_called` (deduped per session). */
1513
1591
  getFeatureFlag(flagKey) {
@@ -1807,6 +1885,7 @@ var LayersReactNative = class LayersReactNative {
1807
1885
  this.core.setDeviceContext(next);
1808
1886
  }
1809
1887
  async flush() {
1888
+ await this.waitForWrapperFlush();
1810
1889
  try {
1811
1890
  await this.core.flushAsync();
1812
1891
  } catch (e) {
@@ -2079,10 +2158,90 @@ var LayersReactNative = class LayersReactNative {
2079
2158
  * held open only for the write.
2080
2159
  */
2081
2160
  async persistForCrash() {
2161
+ this.cancelPersist();
2082
2162
  try {
2083
2163
  this.core.flush();
2084
2164
  } catch {}
2085
- 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());
2086
2245
  }
2087
2246
  /**
2088
2247
  * Remove every listener and timer this instance installed, then shut the
@@ -2092,6 +2251,7 @@ var LayersReactNative = class LayersReactNative {
2092
2251
  */
2093
2252
  teardownRuntime() {
2094
2253
  this.stopConfigPolling();
2254
+ this.cancelPersist();
2095
2255
  this.cancelLifecycleReachabilityCheck();
2096
2256
  if (this.appStateSubscription) {
2097
2257
  this.appStateSubscription.remove();
@@ -2276,7 +2436,31 @@ var LayersReactNative = class LayersReactNative {
2276
2436
  }
2277
2437
  });
2278
2438
  }
2439
+ /**
2440
+ * Record that this install's first launch has been decided, whichever way.
2441
+ * Best-effort: without AsyncStorage nothing persists anyway.
2442
+ */
2443
+ async persistFirstLaunchHandled() {
2444
+ try {
2445
+ const AsyncStorage = await loadAsyncStorage();
2446
+ if (AsyncStorage) await AsyncStorage.setItem(firstLaunchTrackedKey(this.config.appId), "true");
2447
+ } catch {}
2448
+ }
2449
+ /**
2450
+ * The package's first install time, for the 24-hour install gate. A method
2451
+ * so tests can drive the gate: the native module sits behind a real CJS
2452
+ * `require('react-native')` (same seam as `collectInstallReferrer`).
2453
+ */
2454
+ readFirstInstallTime() {
2455
+ return getFirstInstallTime();
2456
+ }
2279
2457
  async initializeDeviceInfo() {
2458
+ try {
2459
+ const gaid = await this.collectGoogleAdvertisingId();
2460
+ this._gaid = gaid && !gaid.isLimitAdTrackingEnabled ? gaid.id : null;
2461
+ } catch {
2462
+ this._gaid = null;
2463
+ }
2280
2464
  try {
2281
2465
  const { Platform, Dimensions, NativeModules } = __require("react-native");
2282
2466
  const window = Dimensions.get("window");
@@ -2310,11 +2494,7 @@ var LayersReactNative = class LayersReactNative {
2310
2494
  const idfv = await getVendorId();
2311
2495
  if (idfv) context.idfv = idfv;
2312
2496
  } catch {}
2313
- if (Platform.OS === "android") try {
2314
- const gaid = await getGoogleAdvertisingId();
2315
- if (gaid) context.idfa = gaid.id;
2316
- if (gaid && gaid.isLimitAdTrackingEnabled != null) context.attStatus = gaid.isLimitAdTrackingEnabled ? "denied" : "authorized";
2317
- } catch {}
2497
+ if (this._gaid && !this.advertisingConsentDenied()) context.idfa = this._gaid;
2318
2498
  try {
2319
2499
  const AsyncStorage = await loadAsyncStorage();
2320
2500
  if (AsyncStorage) this._hadPriorSdkState = await AsyncStorage.getItem(INSTALL_ID_KEY) != null;
@@ -2339,6 +2519,7 @@ var LayersReactNative = class LayersReactNative {
2339
2519
  const installId = await getOrSetInstallId();
2340
2520
  if (installId) context.installId = installId;
2341
2521
  } catch {}
2522
+ if (this._gaid && !this.advertisingConsentDenied()) context.idfa = this._gaid;
2342
2523
  this.core.setDeviceContext(context);
2343
2524
  }
2344
2525
  this._installReferrerParams = null;
@@ -2373,6 +2554,10 @@ var LayersReactNative = class LayersReactNative {
2373
2554
  collectInstallReferrer() {
2374
2555
  return getInstallReferrer();
2375
2556
  }
2557
+ /** Read the Google Advertising ID. A method for the same test seam. */
2558
+ collectGoogleAdvertisingId() {
2559
+ return getGoogleAdvertisingId();
2560
+ }
2376
2561
  /**
2377
2562
  * Emit the canonical `install_referrer` event (Android only).
2378
2563
  *
@@ -2433,7 +2618,7 @@ var LayersReactNative = class LayersReactNative {
2433
2618
  this.track("$app_background");
2434
2619
  lastEmittedState = "background";
2435
2620
  } catch {}
2436
- this.core.flush();
2621
+ this.persistThenSend();
2437
2622
  }
2438
2623
  if (nextAppState === "active") {
2439
2624
  if (this.config.autoTrackAppLifecycle !== false && lastEmittedState !== null && lastEmittedState !== "active") try {
@@ -2535,18 +2720,26 @@ var LayersReactNative = class LayersReactNative {
2535
2720
  } catch {}
2536
2721
  }
2537
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
+ }
2538
2739
  async function createAsyncStoragePersistence(appId) {
2539
2740
  const prefix = `layers_sdk_${appId}_`;
2540
2741
  const memoryStore = /* @__PURE__ */ new Map();
2541
- const inFlight = /* @__PURE__ */ new Set();
2542
- const trackInFlight = (operation) => {
2543
- const entry = operation.then(() => {
2544
- inFlight.delete(entry);
2545
- }, () => {
2546
- inFlight.delete(entry);
2547
- });
2548
- inFlight.add(entry);
2549
- };
2742
+ const queue = createKeyedStorageQueue();
2550
2743
  try {
2551
2744
  const AsyncStorage = await loadAsyncStorage();
2552
2745
  if (AsyncStorage) {
@@ -2565,15 +2758,16 @@ async function createAsyncStoragePersistence(appId) {
2565
2758
  return {
2566
2759
  backend: {
2567
2760
  write(key, data) {
2568
- memoryStore.set(key, new Uint8Array(data));
2569
- 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));
2570
2764
  },
2571
2765
  read(key) {
2572
2766
  return memoryStore.get(key) ?? null;
2573
2767
  },
2574
2768
  delete(key) {
2575
2769
  memoryStore.delete(key);
2576
- trackInFlight(deleteFromAsyncStorage(prefix + key));
2770
+ queue.run(prefix + key, () => deleteFromAsyncStorage(prefix + key));
2577
2771
  },
2578
2772
  listKeys(keyPrefix) {
2579
2773
  const keys = [];
@@ -2582,7 +2776,57 @@ async function createAsyncStoragePersistence(appId) {
2582
2776
  return keys;
2583
2777
  }
2584
2778
  },
2585
- 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
+ }
2586
2830
  };
2587
2831
  }
2588
2832
  const B64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -2807,8 +3051,11 @@ async function getFirstInstallTime() {
2807
3051
  * 1. If `isFirstLaunchByFlag` is `false` (flag already tracked), return `false`.
2808
3052
  * 2. If the SDK had prior state (`install_id` already existed in
2809
3053
  * AsyncStorage), trust the flag — this is a returning user whose
2810
- * first-launch flag was not yet written (e.g. upgrade from an older
2811
- * SDK version). Return `true`.
3054
+ * first-launch flag was not yet written (e.g. a first launch that died
3055
+ * before the flag write). Return `true` — UNLESS `priorLaunchDecided`
3056
+ * says an earlier launch already reached the decision and did not record
3057
+ * it (a launch on 3.3.2 or earlier that suppressed `app_install`, see the
3058
+ * caller). Then return `false`.
2812
3059
  * 3. If the SDK had NO prior state AND the app was installed more than
2813
3060
  * 24 hours ago, this is an existing app getting the SDK for the first
2814
3061
  * time — suppress `is_first_launch`. Return `false`.
@@ -2819,10 +3066,12 @@ async function getFirstInstallTime() {
2819
3066
  * @param isFirstLaunchByFlag Whether the first_launch flag has NOT been set yet (true = not yet tracked).
2820
3067
  * @param hadPriorSdkState Whether `install_id` already existed before init.
2821
3068
  * @param enableDebug Whether to log debug info.
3069
+ * @param priorLaunchDecided Whether an earlier launch already made the
3070
+ * install decision without writing the flag.
2822
3071
  */
2823
- async function shouldTreatAsNewInstall(isFirstLaunchByFlag, hadPriorSdkState, enableDebug = false, _getInstallTime = getFirstInstallTime) {
3072
+ async function shouldTreatAsNewInstall(isFirstLaunchByFlag, hadPriorSdkState, enableDebug = false, _getInstallTime = getFirstInstallTime, priorLaunchDecided = false) {
2824
3073
  if (!isFirstLaunchByFlag) return false;
2825
- if (hadPriorSdkState) return true;
3074
+ if (hadPriorSdkState) return !priorLaunchDecided;
2826
3075
  try {
2827
3076
  const firstInstallTime = await _getInstallTime();
2828
3077
  if (firstInstallTime != null) {
@@ -3155,4 +3404,4 @@ function useLayersExpoRouterTracking(sdkInstance, usePathname, useGlobalSearchPa
3155
3404
 
3156
3405
  //#endregion
3157
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 };
3158
- //# sourceMappingURL=src-HL7K6lv5.mjs.map
3407
+ //# sourceMappingURL=src-DnutJ2iZ.mjs.map