@layers/react-native 3.2.6 → 3.2.8

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.
@@ -910,7 +910,34 @@ var SurveysModule = class {
910
910
 
911
911
  //#endregion
912
912
  //#region src/index.ts
913
- const SDK_VERSION = "3.2.6";
913
+ /**
914
+ * The surface `AppRegistry.js` registers at module scope in EVERY copy of
915
+ * react-native, duplicate or not, so it proves nothing on its own.
916
+ */
917
+ const LOGBOX_SURFACE_KEY = "LogBox";
918
+ /**
919
+ * Is this the copy of react-native the host app actually runs?
920
+ *
921
+ * `AppRegistry.registerComponent` is called by the app's entry file, so the
922
+ * live copy carries the app's own surface key alongside LogBox. A copy that
923
+ * only the SDK imported was never handed an application and carries LogBox
924
+ * alone.
925
+ *
926
+ * Returns `null` when the question cannot be answered (no AppRegistry, a
927
+ * shape we don't recognise). Callers must stay silent on `null` — inventing a
928
+ * diagnosis from missing evidence is worse than the silence this replaces.
929
+ */
930
+ function hostAppIsRegisteredOn(rn) {
931
+ try {
932
+ const keys = rn?.AppRegistry?.getAppKeys?.();
933
+ if (!Array.isArray(keys)) return null;
934
+ return keys.some((key) => typeof key === "string" && key !== LOGBOX_SURFACE_KEY);
935
+ } catch {
936
+ return null;
937
+ }
938
+ }
939
+ 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.2.8";
914
941
  var LayersReactNative = class LayersReactNative {
915
942
  core;
916
943
  eagerPersistence;
@@ -918,6 +945,7 @@ var LayersReactNative = class LayersReactNative {
918
945
  isOnline = true;
919
946
  enableDebug;
920
947
  appStateSubscription = null;
948
+ _lifecycleCheckTimer = null;
921
949
  netInfoUnsubscribe = null;
922
950
  config;
923
951
  userIdLocked = false;
@@ -1832,6 +1860,7 @@ var LayersReactNative = class LayersReactNative {
1832
1860
  */
1833
1861
  teardownRuntime() {
1834
1862
  this.stopConfigPolling();
1863
+ this.cancelLifecycleReachabilityCheck();
1835
1864
  if (this.appStateSubscription) {
1836
1865
  this.appStateSubscription.remove();
1837
1866
  this.appStateSubscription = null;
@@ -2094,13 +2123,27 @@ var LayersReactNative = class LayersReactNative {
2094
2123
  } catch {}
2095
2124
  } catch {}
2096
2125
  }
2126
+ /**
2127
+ * The `react-native` module as this package resolves it.
2128
+ *
2129
+ * A method rather than 16 scattered `require` calls at the lifecycle sites,
2130
+ * so the module the listener binds to and the module the reachability check
2131
+ * inspects are provably the same one.
2132
+ */
2133
+ requireReactNative() {
2134
+ return require("react-native");
2135
+ }
2097
2136
  setupAppStateListener() {
2098
2137
  if (this.appStateSubscription) {
2099
2138
  this.appStateSubscription.remove();
2100
2139
  this.appStateSubscription = null;
2101
2140
  }
2141
+ this.cancelLifecycleReachabilityCheck();
2102
2142
  try {
2103
- const { AppState } = require("react-native");
2143
+ const injected = this.config.appState;
2144
+ const rn = injected ? null : this.requireReactNative();
2145
+ const AppState = injected ?? rn?.AppState;
2146
+ if (!AppState) throw new Error("react-native AppState is unavailable");
2104
2147
  let lastEmittedState = null;
2105
2148
  this.appStateSubscription = AppState.addEventListener("change", (nextAppState) => {
2106
2149
  if (nextAppState === "background" || nextAppState === "inactive") {
@@ -2119,11 +2162,46 @@ var LayersReactNative = class LayersReactNative {
2119
2162
  if (this.isOnline) this.core.flushAsync().catch(() => {});
2120
2163
  }
2121
2164
  });
2165
+ if (rn) this.scheduleLifecycleReachabilityCheck(rn);
2122
2166
  } catch (e) {
2123
2167
  this.emitError(e);
2124
2168
  console.warn("[Layers] AppState listener failed to register — $app_background and the background crash-safety snapshot are disabled for this session:", e);
2125
2169
  }
2126
2170
  }
2171
+ /**
2172
+ * Ask, one tick later, whether the listener just registered can ever fire.
2173
+ *
2174
+ * `AppState.addEventListener` hands back a subscription object no matter
2175
+ * which copy of react-native you call it on, and a duplicate copy's
2176
+ * `RCTDeviceEventEmitter` is never fed by the native side — so the
2177
+ * subscription is real, well-formed, and permanently silent. That is the
2178
+ * exact state a release build of examples/expo was in: registration logged
2179
+ * success on every launch while `$app_background`, `$app_foreground` and
2180
+ * the crash-safety snapshot had not run once. Nothing in the SDK could see
2181
+ * it, and nothing in the app could either.
2182
+ *
2183
+ * The check is DEFERRED by a tick because it reads `AppRegistry`, which the
2184
+ * host populates from its entry file. An SDK constructed at module scope
2185
+ * ahead of `AppRegistry.registerComponent` would otherwise look like a
2186
+ * duplicate to itself — a false alarm about a healthy integration, which is
2187
+ * a worse failure than the one being fixed.
2188
+ */
2189
+ scheduleLifecycleReachabilityCheck(rn) {
2190
+ this.cancelLifecycleReachabilityCheck();
2191
+ this._lifecycleCheckTimer = setTimeout(() => {
2192
+ this._lifecycleCheckTimer = null;
2193
+ if (hostAppIsRegisteredOn(rn) !== false) return;
2194
+ const error = new Error(DUPLICATE_REACT_NATIVE_MESSAGE);
2195
+ this.emitError(error);
2196
+ console.warn(DUPLICATE_REACT_NATIVE_MESSAGE);
2197
+ }, 0);
2198
+ }
2199
+ cancelLifecycleReachabilityCheck() {
2200
+ if (this._lifecycleCheckTimer !== null) {
2201
+ clearTimeout(this._lifecycleCheckTimer);
2202
+ this._lifecycleCheckTimer = null;
2203
+ }
2204
+ }
2127
2205
  async configureSkanFromRemoteConfig() {
2128
2206
  try {
2129
2207
  const { Platform } = require("react-native");
@@ -2183,14 +2261,16 @@ async function createAsyncStoragePersistence(appId) {
2183
2261
  if (AsyncStorage) {
2184
2262
  const sdkKeys = (await AsyncStorage.getAllKeys()).filter((k) => k.startsWith(prefix));
2185
2263
  if (sdkKeys.length > 0) {
2186
- const pairs = await AsyncStorage.multiGet(sdkKeys);
2264
+ const pairs = await readManyFromAsyncStorage(AsyncStorage, sdkKeys);
2187
2265
  for (const [key, value] of pairs) if (value) {
2188
2266
  const shortKey = key.slice(prefix.length);
2189
2267
  memoryStore.set(shortKey, base64Decode(value));
2190
2268
  }
2191
2269
  }
2192
2270
  }
2193
- } catch {}
2271
+ } catch (error) {
2272
+ warnPersistencePreloadFailed(error);
2273
+ }
2194
2274
  return {
2195
2275
  write(key, data) {
2196
2276
  memoryStore.set(key, new Uint8Array(data));
@@ -2268,6 +2348,38 @@ async function deleteFromAsyncStorage(key) {
2268
2348
  await AsyncStorage.removeItem(key);
2269
2349
  } catch {}
2270
2350
  }
2351
+ let _warnedAsyncStorageBatchShape = false;
2352
+ let _warnedPersistencePreloadFailed = false;
2353
+ /**
2354
+ * Batch-read `keys` through whichever multi-key API the installed AsyncStorage
2355
+ * exposes.
2356
+ *
2357
+ * v3.0.0 removed `multiGet` in favour of `getMany`, and changed the return
2358
+ * type with it: `multiGet` answers `[key, value][]`, `getMany` answers
2359
+ * `Record<key, value | null>`. Calling the v1/v2 name unconditionally threw
2360
+ * `TypeError: AsyncStorage.multiGet is not a function` on v3 — and because
2361
+ * `>=1.21.0` admits v3, and npm's `latest` has been v3 since v3.0.0, that was
2362
+ * the default install.
2363
+ */
2364
+ async function readManyFromAsyncStorage(storage, keys) {
2365
+ if (typeof storage.multiGet === "function") return (await storage.multiGet(keys)).map(([key, value]) => [key, value ?? null]);
2366
+ if (typeof storage.getMany === "function") {
2367
+ const record = await storage.getMany([...keys]);
2368
+ return keys.map((key) => [key, record?.[key] ?? null]);
2369
+ }
2370
+ warnAsyncStorageBatchShape();
2371
+ return Promise.all(keys.map(async (key) => [key, await storage.getItem(key)]));
2372
+ }
2373
+ function warnAsyncStorageBatchShape() {
2374
+ if (_warnedAsyncStorageBatchShape) return;
2375
+ _warnedAsyncStorageBatchShape = true;
2376
+ console.warn("[Layers] @react-native-async-storage/async-storage exposes neither multiGet (v1/v2) nor getMany (v3) — falling back to one read per key to restore persisted identity and queued events. If launches start reporting as new installs, pin async-storage to a version this SDK recognises (>=1.21.0).");
2377
+ }
2378
+ function warnPersistencePreloadFailed(error) {
2379
+ if (_warnedPersistencePreloadFailed) return;
2380
+ _warnedPersistencePreloadFailed = true;
2381
+ console.warn("[Layers] could not read persisted SDK state back from AsyncStorage — this launch starts with a fresh identity and an empty event queue, and will report itself as a new install. Check @react-native-async-storage/async-storage compatibility; the SDK supports v1.21+, v2 and v3.", error);
2382
+ }
2271
2383
  let _asyncStorage = void 0;
2272
2384
  let _asyncStoragePromise = null;
2273
2385
  async function loadAsyncStorage() {
@@ -2530,6 +2642,32 @@ const INSTALL_REFERRER_ATTRIBUTION_PARAMS = new Set([
2530
2642
  "click_id"
2531
2643
  ]);
2532
2644
  /**
2645
+ * Decode one `application/x-www-form-urlencoded` token from a URL query
2646
+ * component. This is the single decoding rule every Layers SDK implements
2647
+ * (Kotlin, Swift, Dart, C#, and here):
2648
+ *
2649
+ * - `+` -> space (ad platforms emit `running+shoes` for "running shoes")
2650
+ * - `%XX` -> the byte 0xXX (then UTF-8)
2651
+ * - one pass: neither output feeds the other, so `%2B` yields a literal `+`
2652
+ *
2653
+ * The order below is load-bearing. Percent-decoding FIRST and then swapping
2654
+ * `+` for a space turns `%2B` into a space — a double decode that silently
2655
+ * corrupts any campaign name containing a real plus sign. Swapping `+` for
2656
+ * its own escape on the still-encoded token makes that impossible.
2657
+ *
2658
+ * Applies to the QUERY component only. Path and fragment are RFC 3986, where
2659
+ * `+` is an ordinary character.
2660
+ *
2661
+ * Never throws: a malformed escape (e.g. `%ZZ`) yields the raw token.
2662
+ */
2663
+ function decodeFormUrlComponent(encoded) {
2664
+ try {
2665
+ return decodeURIComponent(encoded.replace(/\+/g, "%20"));
2666
+ } catch {
2667
+ return encoded;
2668
+ }
2669
+ }
2670
+ /**
2533
2671
  * Parse a raw Play Install Referrer string into a map of recognized attribution
2534
2672
  * params. Accepts either a bare query string (`a=1&b=2`) or a full URL.
2535
2673
  * Returns an empty object on parse failure.
@@ -2544,11 +2682,11 @@ function parseInstallReferrerUrl(referrer) {
2544
2682
  if (!qs.includes("=") && qs.includes("%3D")) qs = decodeURIComponent(qs);
2545
2683
  for (const pair of qs.split("&")) {
2546
2684
  const eq = pair.indexOf("=");
2547
- if (eq >= 0) try {
2548
- const key = decodeURIComponent(pair.slice(0, eq));
2549
- const value = decodeURIComponent(pair.slice(eq + 1));
2685
+ if (eq >= 0) {
2686
+ const key = decodeFormUrlComponent(pair.slice(0, eq));
2687
+ const value = decodeFormUrlComponent(pair.slice(eq + 1));
2550
2688
  if (value && INSTALL_REFERRER_ATTRIBUTION_PARAMS.has(key)) out[key] = value;
2551
- } catch {}
2689
+ }
2552
2690
  }
2553
2691
  } catch {}
2554
2692
  return out;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@layers/react-native",
3
- "version": "3.2.6",
3
+ "version": "3.2.8",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -67,7 +67,7 @@
67
67
  "mobile"
68
68
  ],
69
69
  "dependencies": {
70
- "@layers/core-wasm": "3.2.6"
70
+ "@layers/core-wasm": "3.2.8"
71
71
  },
72
72
  "peerDependencies": {
73
73
  "@react-native-async-storage/async-storage": ">=1.21.0",