@layers/react-native 2.1.6 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/android/build.gradle +62 -0
  2. package/android/src/main/AndroidManifest.xml +2 -0
  3. package/android/src/main/java/io/layers/sdk/reactnative/LayersAdvertisingIdModule.java +70 -0
  4. package/android/src/main/java/io/layers/sdk/reactnative/LayersDeviceInfoModule.java +54 -0
  5. package/android/src/main/java/io/layers/sdk/reactnative/LayersInstallReferrerModule.java +116 -0
  6. package/android/src/main/java/io/layers/sdk/reactnative/LayersReactNativePackage.java +36 -0
  7. package/dist/att-BDPyE-Gs.d.mts.map +1 -1
  8. package/dist/debug-overlay.d.mts +3 -3
  9. package/dist/debug-overlay.d.mts.map +1 -1
  10. package/dist/debug-overlay.d.ts +3 -3
  11. package/dist/debug-overlay.d.ts.map +1 -1
  12. package/dist/debug-overlay.js +18 -18
  13. package/dist/debug-overlay.mjs +18 -18
  14. package/dist/debug-overlay.mjs.map +1 -1
  15. package/dist/{index-CHZdzlpP.d.mts → index-BqcbQZEP.d.mts} +324 -47
  16. package/dist/index-BqcbQZEP.d.mts.map +1 -0
  17. package/dist/{index-DKnTFmDn.d.ts → index-fU6euPnq.d.ts} +324 -47
  18. package/dist/index-fU6euPnq.d.ts.map +1 -0
  19. package/dist/index.d.mts +2 -2
  20. package/dist/index.d.ts +2 -2
  21. package/dist/index.js +54 -1
  22. package/dist/index.mjs +2 -2
  23. package/dist/react.d.mts +1 -1
  24. package/dist/react.d.ts +1 -1
  25. package/dist/react.js +1 -1
  26. package/dist/react.mjs +1 -1
  27. package/dist/{src-B4Ri1LeO.mjs → src-BNoj1E-e.mjs} +679 -90
  28. package/dist/src-BNoj1E-e.mjs.map +1 -0
  29. package/dist/{src-CTABFR5u.js → src-ym3bM4JE.js} +706 -87
  30. package/ios/LayersAdServices.m +8 -0
  31. package/ios/LayersAdServices.swift +41 -0
  32. package/ios/LayersDeviceInfo.m +14 -0
  33. package/ios/LayersDeviceInfo.swift +53 -0
  34. package/ios/LayersSKAN.m +45 -0
  35. package/ios/LayersSKAN.swift +188 -0
  36. package/ios/LayersSKANCompat.h +22 -0
  37. package/ios/LayersSKANCompat.m +118 -0
  38. package/layers-react-native.podspec +34 -0
  39. package/package.json +6 -3
  40. package/dist/index-CHZdzlpP.d.mts.map +0 -1
  41. package/dist/index-DKnTFmDn.d.ts.map +0 -1
  42. package/dist/src-B4Ri1LeO.mjs.map +0 -1
@@ -15,6 +15,7 @@ __layers_core_wasm = require_chunk.__toESM(__layers_core_wasm);
15
15
  * ```
16
16
  */
17
17
  const StandardEvents = {
18
+ APP_INSTALL: "app_install",
18
19
  APP_OPEN: "app_open",
19
20
  LOGIN: "login",
20
21
  SIGN_UP: "sign_up",
@@ -215,27 +216,27 @@ function screenViewEvent(name, screenClass) {
215
216
  *
216
217
  * Superwall.instance.setDelegate({
217
218
  * handleSuperwallEvent(eventInfo) {
218
- * superwallOnEvent(layers, eventInfo);
219
+ * superwallOnEvent(sdk, eventInfo);
219
220
  * }
220
221
  * });
221
222
  * ```
222
223
  */
223
- function superwallOnEvent(layers, eventInfo) {
224
+ function superwallOnEvent(sdk, eventInfo) {
224
225
  try {
225
226
  const eventName = eventInfo.event.rawName ?? eventInfo.event.type ?? "unknown";
226
227
  const properties = { source: "superwall" };
227
228
  if (eventInfo.params) Object.assign(properties, eventInfo.params);
228
- layers.track(`superwall_${eventName}`, properties);
229
+ sdk.track(`superwall_${eventName}`, properties);
229
230
  } catch {}
230
231
  }
231
232
  /**
232
233
  * Track that a paywall was presented to the user.
233
234
  *
234
235
  * ```ts
235
- * superwallTrackPresentation(layers, paywallInfo);
236
+ * superwallTrackPresentation(sdk, paywallInfo);
236
237
  * ```
237
238
  */
238
- function superwallTrackPresentation(layers, paywallInfo) {
239
+ function superwallTrackPresentation(sdk, paywallInfo) {
239
240
  try {
240
241
  if (!paywallInfo) return;
241
242
  const properties = {
@@ -248,20 +249,20 @@ function superwallTrackPresentation(layers, paywallInfo) {
248
249
  id: paywallInfo.experiment.id,
249
250
  variant: paywallInfo.experiment.variantId
250
251
  };
251
- layers.track("paywall_show", properties);
252
+ sdk.track("paywall_show", properties);
252
253
  } catch {}
253
254
  }
254
255
  /**
255
256
  * Track that a paywall was dismissed.
256
257
  *
257
258
  * ```ts
258
- * superwallTrackDismiss(layers, paywallInfo);
259
+ * superwallTrackDismiss(sdk, paywallInfo);
259
260
  * ```
260
261
  */
261
- function superwallTrackDismiss(layers, paywallInfo) {
262
+ function superwallTrackDismiss(sdk, paywallInfo) {
262
263
  try {
263
264
  if (!paywallInfo) return;
264
- layers.track("paywall_dismiss", {
265
+ sdk.track("paywall_dismiss", {
265
266
  paywall_id: paywallInfo.identifier,
266
267
  source: "superwall"
267
268
  });
@@ -271,10 +272,10 @@ function superwallTrackDismiss(layers, paywallInfo) {
271
272
  * Track a purchase initiated from a Superwall paywall.
272
273
  *
273
274
  * ```ts
274
- * superwallTrackPurchase(layers, paywallInfo, product);
275
+ * superwallTrackPurchase(sdk, paywallInfo, product);
275
276
  * ```
276
277
  */
277
- function superwallTrackPurchase(layers, paywallInfo, product) {
278
+ function superwallTrackPurchase(sdk, paywallInfo, product) {
278
279
  try {
279
280
  const properties = {
280
281
  paywall_id: paywallInfo?.identifier ?? "unknown",
@@ -287,19 +288,19 @@ function superwallTrackPurchase(layers, paywallInfo, product) {
287
288
  const currency = product.currencyCode ?? product.currency;
288
289
  if (currency) properties.currency = currency;
289
290
  }
290
- layers.track("paywall_purchase", properties);
291
+ sdk.track("paywall_purchase", properties);
291
292
  } catch {}
292
293
  }
293
294
  /**
294
295
  * Track that a paywall was skipped (e.g. holdout, no rule match).
295
296
  *
296
297
  * ```ts
297
- * superwallTrackSkip(layers, paywallInfo, 'holdout');
298
+ * superwallTrackSkip(sdk, paywallInfo, 'holdout');
298
299
  * ```
299
300
  */
300
- function superwallTrackSkip(layers, paywallInfo, reason) {
301
+ function superwallTrackSkip(sdk, paywallInfo, reason) {
301
302
  try {
302
- layers.track("paywall_skip", {
303
+ sdk.track("paywall_skip", {
303
304
  paywall_id: paywallInfo?.identifier ?? "unknown",
304
305
  reason,
305
306
  source: "superwall"
@@ -311,16 +312,16 @@ function superwallTrackSkip(layers, paywallInfo, reason) {
311
312
  *
312
313
  * Pass the returned object to `Superwall.instance.setUserAttributes()`:
313
314
  * ```ts
314
- * const attrs = superwallUserAttributes(layers);
315
+ * const attrs = superwallUserAttributes(sdk);
315
316
  * Superwall.instance.setUserAttributes(attrs);
316
317
  * ```
317
318
  */
318
- function superwallUserAttributes(layers) {
319
+ function superwallUserAttributes(sdk) {
319
320
  const attrs = {};
320
321
  try {
321
- const sessionId = layers.getSessionId();
322
+ const sessionId = sdk.getSessionId();
322
323
  if (sessionId) attrs.layers_session_id = sessionId;
323
- const userId = layers.getAppUserId();
324
+ const userId = sdk.getAppUserId();
324
325
  if (userId) attrs.layers_user_id = userId;
325
326
  } catch {}
326
327
  return attrs;
@@ -334,7 +335,7 @@ function superwallUserAttributes(layers) {
334
335
  * ```ts
335
336
  * import { trackPurchase } from '@layers/react-native';
336
337
  *
337
- * trackPurchase(layers, {
338
+ * trackPurchase(sdk, {
338
339
  * productId: 'premium_monthly',
339
340
  * price: 9.99,
340
341
  * currency: 'USD',
@@ -342,7 +343,7 @@ function superwallUserAttributes(layers) {
342
343
  * });
343
344
  * ```
344
345
  */
345
- function trackPurchase(layers, params) {
346
+ function trackPurchase(sdk, params) {
346
347
  const quantity = params.quantity ?? 1;
347
348
  const props = {
348
349
  product_id: params.productId,
@@ -355,12 +356,12 @@ function trackPurchase(layers, params) {
355
356
  if (params.transactionId !== void 0) props.transaction_id = params.transactionId;
356
357
  if (params.isRestored !== void 0) props.is_restored = params.isRestored;
357
358
  if (params.store !== void 0) props.store = params.store;
358
- layers.track("purchase_success", props);
359
+ sdk.track("purchase_success", props);
359
360
  }
360
361
  /**
361
362
  * Track a failed purchase attempt.
362
363
  */
363
- function trackPurchaseFailed(layers, params) {
364
+ function trackPurchaseFailed(sdk, params) {
364
365
  const props = {
365
366
  product_id: params.productId,
366
367
  currency: params.currency,
@@ -368,7 +369,7 @@ function trackPurchaseFailed(layers, params) {
368
369
  ...params.properties
369
370
  };
370
371
  if (params.errorMessage !== void 0) props.error_message = params.errorMessage;
371
- layers.track("purchase_failed", props);
372
+ sdk.track("purchase_failed", props);
372
373
  }
373
374
  /**
374
375
  * Track a subscription purchase or renewal.
@@ -376,7 +377,7 @@ function trackPurchaseFailed(layers, params) {
376
377
  * ```ts
377
378
  * import { trackSubscription } from '@layers/react-native';
378
379
  *
379
- * trackSubscription(layers, {
380
+ * trackSubscription(sdk, {
380
381
  * productId: 'pro_annual',
381
382
  * price: 49.99,
382
383
  * currency: 'USD',
@@ -384,7 +385,7 @@ function trackPurchaseFailed(layers, params) {
384
385
  * });
385
386
  * ```
386
387
  */
387
- function trackSubscription(layers, params) {
388
+ function trackSubscription(sdk, params) {
388
389
  const props = {
389
390
  product_id: params.productId,
390
391
  price: params.price,
@@ -399,12 +400,12 @@ function trackSubscription(layers, params) {
399
400
  if (params.isTrial !== void 0) props.is_trial = params.isTrial;
400
401
  if (params.subscriptionGroupId !== void 0) props.subscription_group_id = params.subscriptionGroupId;
401
402
  if (params.originalTransactionId !== void 0) props.original_transaction_id = params.originalTransactionId;
402
- layers.track("subscribe", props);
403
+ sdk.track("subscribe", props);
403
404
  }
404
405
  /**
405
406
  * Track a completed order with multiple line items.
406
407
  */
407
- function trackOrder(layers, params) {
408
+ function trackOrder(sdk, params) {
408
409
  const currency = params.currency ?? "USD";
409
410
  let total = params.subtotal;
410
411
  if (params.tax !== void 0) total += params.tax;
@@ -424,12 +425,12 @@ function trackOrder(layers, params) {
424
425
  if (params.shipping !== void 0) props.shipping = params.shipping;
425
426
  if (params.discount !== void 0) props.discount = params.discount;
426
427
  if (params.couponCode !== void 0) props.coupon_code = params.couponCode;
427
- layers.track("purchase_success", props);
428
+ sdk.track("purchase_success", props);
428
429
  }
429
430
  /**
430
431
  * Track an item being added to the cart.
431
432
  */
432
- function trackAddToCart(layers, item, properties) {
433
+ function trackAddToCart(sdk, item, properties) {
433
434
  const quantity = item.quantity ?? 1;
434
435
  const props = {
435
436
  product_id: item.productId,
@@ -440,12 +441,12 @@ function trackAddToCart(layers, item, properties) {
440
441
  ...properties
441
442
  };
442
443
  if (item.category !== void 0) props.category = item.category;
443
- layers.track("add_to_cart", props);
444
+ sdk.track("add_to_cart", props);
444
445
  }
445
446
  /**
446
447
  * Track an item being removed from the cart.
447
448
  */
448
- function trackRemoveFromCart(layers, item, properties) {
449
+ function trackRemoveFromCart(sdk, item, properties) {
449
450
  const quantity = item.quantity ?? 1;
450
451
  const props = {
451
452
  product_id: item.productId,
@@ -455,12 +456,12 @@ function trackRemoveFromCart(layers, item, properties) {
455
456
  ...properties
456
457
  };
457
458
  if (item.category !== void 0) props.category = item.category;
458
- layers.track("remove_from_cart", props);
459
+ sdk.track("remove_from_cart", props);
459
460
  }
460
461
  /**
461
462
  * Track beginning the checkout flow.
462
463
  */
463
- function trackBeginCheckout(layers, items, currency = "USD", properties) {
464
+ function trackBeginCheckout(sdk, items, currency = "USD", properties) {
464
465
  const total = items.reduce((sum, item) => sum + item.price * (item.quantity ?? 1), 0);
465
466
  const props = {
466
467
  item_count: items.length,
@@ -469,12 +470,12 @@ function trackBeginCheckout(layers, items, currency = "USD", properties) {
469
470
  product_ids: items.map((i) => i.productId).join(","),
470
471
  ...properties
471
472
  };
472
- layers.track("begin_checkout", props);
473
+ sdk.track("begin_checkout", props);
473
474
  }
474
475
  /**
475
476
  * Track viewing a product detail page.
476
477
  */
477
- function trackViewProduct(layers, productId, name, price, currency = "USD", category, properties) {
478
+ function trackViewProduct(sdk, productId, name, price, currency = "USD", category, properties) {
478
479
  const props = {
479
480
  product_id: productId,
480
481
  product_name: name,
@@ -483,12 +484,12 @@ function trackViewProduct(layers, productId, name, price, currency = "USD", cate
483
484
  ...properties
484
485
  };
485
486
  if (category !== void 0) props.category = category;
486
- layers.track("view_item", props);
487
+ sdk.track("view_item", props);
487
488
  }
488
489
  /**
489
490
  * Track a refund.
490
491
  */
491
- function trackRefund(layers, params) {
492
+ function trackRefund(sdk, params) {
492
493
  const props = {
493
494
  transaction_id: params.transactionId,
494
495
  amount: params.amount,
@@ -496,7 +497,7 @@ function trackRefund(layers, params) {
496
497
  ...params.properties
497
498
  };
498
499
  if (params.reason !== void 0) props.reason = params.reason;
499
- layers.track("refund", props);
500
+ sdk.track("refund", props);
500
501
  }
501
502
 
502
503
  //#endregion
@@ -504,7 +505,7 @@ function trackRefund(layers, params) {
504
505
  let _isConnected = false;
505
506
  let _activeSubscriptions = /* @__PURE__ */ new Set();
506
507
  let _isInitialLoadDone = false;
507
- let _connectedLayers = null;
508
+ let _connectedSDK = null;
508
509
  /**
509
510
  * Connect Layers to your existing RevenueCat Purchases instance.
510
511
  *
@@ -516,16 +517,16 @@ let _connectedLayers = null;
516
517
  * import Purchases from 'react-native-purchases';
517
518
  * import { LayersReactNative, connectRevenueCat } from '@layers/react-native';
518
519
  *
519
- * const layers = new LayersReactNative();
520
+ * const sdk = new LayersReactNative();
520
521
  * await layers.init({ appId: 'your-app-id', environment: 'production' });
521
522
  *
522
523
  * connectRevenueCat({
523
- * layers,
524
+ * sdk,
524
525
  * purchases: Purchases,
525
526
  * });
526
527
  * ```
527
528
  *
528
- * @param config - Configuration including the Layers instance.
529
+ * @param config - Configuration including the SDK instance.
529
530
  * @param purchases - The RevenueCat Purchases instance (duck-typed to avoid hard dependency).
530
531
  */
531
532
  function connectRevenueCat(config, purchases) {
@@ -534,7 +535,7 @@ function connectRevenueCat(config, purchases) {
534
535
  if (!purchases) return;
535
536
  if (typeof purchases.addCustomerInfoUpdateListener !== "function") return;
536
537
  if (typeof purchases.getCustomerInfo !== "function") return;
537
- _connectedLayers = config.layers;
538
+ _connectedSDK = config.sdk;
538
539
  purchases.addCustomerInfoUpdateListener((info) => {
539
540
  handleCustomerInfoUpdate(config, info, false);
540
541
  });
@@ -551,10 +552,10 @@ function connectRevenueCat(config, purchases) {
551
552
  * ```ts
552
553
  * const offerings = await Purchases.getOfferings();
553
554
  * const pkg = offerings.current?.availablePackages[0];
554
- * if (pkg) trackRevenueCatPurchase(layers, pkg);
555
+ * if (pkg) trackRevenueCatPurchase(sdk, pkg);
555
556
  * ```
556
557
  */
557
- function trackRevenueCatPurchase(layers, rcPackage, store) {
558
+ function trackRevenueCatPurchase(sdk, rcPackage, store) {
558
559
  try {
559
560
  if (!rcPackage?.product) return;
560
561
  let resolvedStore = store ?? "app_store";
@@ -562,7 +563,7 @@ function trackRevenueCatPurchase(layers, rcPackage, store) {
562
563
  const { Platform } = require("react-native");
563
564
  resolvedStore = Platform.OS === "ios" ? "app_store" : "play_store";
564
565
  } catch {}
565
- layers.track("purchase_success", {
566
+ sdk.track("purchase_success", {
566
567
  product_id: rcPackage.product.identifier ?? "",
567
568
  price: rcPackage.product.price ?? 0,
568
569
  currency: rcPackage.product.currencyCode ?? "USD",
@@ -577,11 +578,11 @@ function trackRevenueCatPurchase(layers, rcPackage, store) {
577
578
  * This is called automatically when using `connectRevenueCat()`, but can also
578
579
  * be called manually if needed.
579
580
  */
580
- function syncRevenueCatAttributes(layers, customerInfo) {
581
+ function syncRevenueCatAttributes(sdk, customerInfo) {
581
582
  try {
582
583
  const userProps = { is_subscriber: Array.isArray(customerInfo.activeSubscriptions) && customerInfo.activeSubscriptions.length > 0 };
583
584
  if (customerInfo.originalAppUserId) userProps.revenuecat_original_app_user_id = customerInfo.originalAppUserId;
584
- layers.setUserProperties(userProps);
585
+ sdk.setUserProperties(userProps);
585
586
  } catch {}
586
587
  }
587
588
  /**
@@ -591,7 +592,7 @@ function resetRevenueCatForTesting() {
591
592
  _isConnected = false;
592
593
  _activeSubscriptions = /* @__PURE__ */ new Set();
593
594
  _isInitialLoadDone = false;
594
- _connectedLayers = null;
595
+ _connectedSDK = null;
595
596
  }
596
597
  /**
597
598
  * Whether the RevenueCat integration is currently connected.
@@ -603,10 +604,10 @@ function handleCustomerInfoUpdate(config, info, isInitialLoad) {
603
604
  try {
604
605
  const currentSubs = new Set(Array.isArray(info.activeSubscriptions) ? info.activeSubscriptions : []);
605
606
  if (isInitialLoad && _isInitialLoadDone) return;
606
- if (!isInitialLoad && _isInitialLoadDone && _connectedLayers) {
607
+ if (!isInitialLoad && _isInitialLoadDone && _connectedSDK) {
607
608
  for (const subId of currentSubs) if (!_activeSubscriptions.has(subId)) {
608
609
  if (config.onSubscriptionStart !== null) if (config.onSubscriptionStart) config.onSubscriptionStart(subId);
609
- else _connectedLayers.track("subscription_start", {
610
+ else _connectedSDK.track("subscription_start", {
610
611
  product_id: subId,
611
612
  source: "revenuecat"
612
613
  });
@@ -614,7 +615,7 @@ function handleCustomerInfoUpdate(config, info, isInitialLoad) {
614
615
  }
615
616
  _activeSubscriptions = currentSubs;
616
617
  _isInitialLoadDone = true;
617
- if (_connectedLayers) syncRevenueCatAttributes(_connectedLayers, info);
618
+ if (_connectedSDK) syncRevenueCatAttributes(_connectedSDK, info);
618
619
  } catch {}
619
620
  }
620
621
 
@@ -641,21 +642,21 @@ const BACKGROUND_FLUSH_MIN_INTERVAL_MINUTES = 15;
641
642
  * will flush any queued events via the Layers SDK. It is safe to call even
642
643
  * if the SDK is not initialized (it will silently no-op).
643
644
  *
644
- * @param getLayers - A getter that returns the current LayersReactNative
645
+ * @param getSDK - A getter that returns the current LayersReactNative
645
646
  * instance, or `null` if the SDK is not yet initialized.
646
647
  * @returns An async handler suitable for use with background task libraries.
647
648
  *
648
649
  * @example
649
650
  * ```typescript
650
- * const handler = createBackgroundFlushHandler(() => myLayersInstance);
651
+ * const handler = createBackgroundFlushHandler(() => mySDKInstance);
651
652
  * ```
652
653
  */
653
- function createBackgroundFlushHandler(getLayers) {
654
+ function createBackgroundFlushHandler(getSDK) {
654
655
  return async () => {
655
- const layers = getLayers();
656
- if (!layers) return { success: false };
656
+ const sdk = getSDK();
657
+ if (!sdk) return { success: false };
657
658
  try {
658
- await layers.flush();
659
+ await sdk.flush();
659
660
  return { success: true };
660
661
  } catch {
661
662
  return { success: false };
@@ -669,7 +670,7 @@ function createBackgroundFlushHandler(getLayers) {
669
670
  * `expo-task-manager` requires tasks to be defined before the app mounts.
670
671
  *
671
672
  * @param taskManager - The `expo-task-manager` module (import * as TaskManager from 'expo-task-manager').
672
- * @param getLayers - A getter that returns the current LayersReactNative
673
+ * @param getSDK - A getter that returns the current LayersReactNative
673
674
  * instance, or `null` if the SDK is not yet initialized.
674
675
  *
675
676
  * @example
@@ -677,21 +678,236 @@ function createBackgroundFlushHandler(getLayers) {
677
678
  * import * as TaskManager from 'expo-task-manager';
678
679
  * import { registerExpoBackgroundFlush } from '@layers/expo';
679
680
  *
680
- * let layers: LayersReactNative | null = null;
681
- * registerExpoBackgroundFlush(TaskManager, () => layers);
681
+ * let sdk: LayersReactNative | null = null;
682
+ * registerExpoBackgroundFlush(TaskManager, () => sdk);
682
683
  *
683
684
  * // Later, in your app initialization:
684
- * layers = new LayersReactNative({ appId: '...', environment: 'production' });
685
+ * sdk = new LayersReactNative({ appId: '...', environment: 'production' });
685
686
  * await layers.init();
686
687
  * ```
687
688
  */
688
- function registerExpoBackgroundFlush(taskManager, getLayers) {
689
- const handler = createBackgroundFlushHandler(getLayers);
689
+ function registerExpoBackgroundFlush(taskManager, getSDK) {
690
+ const handler = createBackgroundFlushHandler(getSDK);
690
691
  taskManager.defineTask(BACKGROUND_FLUSH_TASK_NAME, async () => {
691
692
  await handler();
692
693
  });
693
694
  }
694
695
 
696
+ //#endregion
697
+ //#region src/navigation-tracking.ts
698
+ /**
699
+ * Build a stateful listener that emits `$screen_view` whenever the active
700
+ * route changes. The returned function should be passed to React
701
+ * Navigation's `onStateChange` prop or `navigationRef.addListener('state',
702
+ * cb)`. It returns nothing — the SDK records the event side-effecting.
703
+ *
704
+ * The listener:
705
+ * - resolves the deepest active route via `getActiveRouteName()`
706
+ * semantics so nested stack/tab navigators correctly report the
707
+ * leaf screen
708
+ * - de-dupes consecutive identical names (some RN versions emit the
709
+ * same state twice on re-renders)
710
+ * - attaches route params + previous screen on the screen event
711
+ */
712
+ function createNavigationListener(sdk) {
713
+ let previousScreen = null;
714
+ return function onStateChange(state) {
715
+ if (!state) return;
716
+ const currentRoute = resolveActiveRoute(state);
717
+ if (!currentRoute) return;
718
+ if (currentRoute.name === previousScreen) return;
719
+ const properties = {
720
+ ...currentRoute.params ?? {},
721
+ screen_name: currentRoute.name
722
+ };
723
+ if (previousScreen) properties.previous_screen_name = previousScreen;
724
+ try {
725
+ sdk.screen(currentRoute.name, properties);
726
+ if (sdk.enableDebug) console.log(`[Layers] $screen_view: ${currentRoute.name}`);
727
+ } catch {}
728
+ previousScreen = currentRoute.name;
729
+ };
730
+ }
731
+ /**
732
+ * React hook that subscribes to a React Navigation NavigationContainerRef
733
+ * and emits a `$screen_view` for each route change. Pass the SDK instance
734
+ * and the same `navigationRef` you give to `<NavigationContainer ref={...}>`.
735
+ *
736
+ * ```tsx
737
+ * import { createNavigationContainerRef } from '@react-navigation/native';
738
+ * const navigationRef = createNavigationContainerRef();
739
+ *
740
+ * function Root() {
741
+ * useLayersNavigationTracking(layers, navigationRef);
742
+ * return <NavigationContainer ref={navigationRef}>...</NavigationContainer>;
743
+ * }
744
+ * ```
745
+ *
746
+ * The hook is implemented via a lazy `require('react')` so it only fails
747
+ * if React itself is unavailable — consumers without React Navigation can
748
+ * still call it and it will silently no-op.
749
+ */
750
+ function useLayersNavigationTracking(sdk, navigationRef) {
751
+ let useEffect = null;
752
+ try {
753
+ useEffect = require("react").useEffect;
754
+ } catch {
755
+ return;
756
+ }
757
+ if (!useEffect) return;
758
+ useEffect(() => {
759
+ if (!navigationRef?.addListener) return void 0;
760
+ const listener = createNavigationListener(sdk);
761
+ const unsubscribe = navigationRef.addListener("state", (event) => {
762
+ listener((event?.data)?.state ?? event);
763
+ });
764
+ return () => {
765
+ try {
766
+ if (typeof unsubscribe === "function") unsubscribe();
767
+ } catch {}
768
+ };
769
+ }, [sdk, navigationRef]);
770
+ }
771
+ /**
772
+ * Walk a NavigationState tree and return the active leaf route. Mirrors
773
+ * React Navigation's own `getActiveRouteName()` helper without taking a
774
+ * peer-dep on `@react-navigation/native`.
775
+ *
776
+ * Exported for testing.
777
+ * @internal
778
+ */
779
+ function resolveActiveRoute(state) {
780
+ if (!state || !Array.isArray(state.routes) || state.routes.length === 0) return null;
781
+ const idx = typeof state.index === "number" ? state.index : state.routes.length - 1;
782
+ const route = state.routes[idx];
783
+ if (!route) return null;
784
+ if (route.state) {
785
+ const inner = resolveActiveRoute(route.state);
786
+ if (inner) return inner;
787
+ }
788
+ return {
789
+ name: route.name,
790
+ ...route.params != null && { params: route.params }
791
+ };
792
+ }
793
+
794
+ //#endregion
795
+ //#region src/surveys.ts
796
+ const SHOW_HISTORY_STORAGE_KEY = "layers:surveys:show-history";
797
+ /**
798
+ * Public surveys API exposed via `LayersReactNative.surveys`.
799
+ *
800
+ * Render the actual chrome by mounting `<LayersSurveyModal />` from
801
+ * `@layers/react-native/surveys-component` somewhere in your app tree
802
+ * and binding it to the eligible survey via `surveys.getActive()`.
803
+ */
804
+ var SurveysModule = class {
805
+ hydrated = false;
806
+ listeners = /* @__PURE__ */ new Set();
807
+ constructor(core, options = {}) {
808
+ this.core = core;
809
+ this.options = options;
810
+ if (this.options.persistence) this.hydrate();
811
+ else this.hydrated = true;
812
+ }
813
+ get enabled() {
814
+ return this.options.enabled !== false;
815
+ }
816
+ knownIds() {
817
+ return this.core.knownSurveyIds();
818
+ }
819
+ /**
820
+ * Return surveys currently eligible to show. Builds the targeting context
821
+ * from caller-supplied person properties + feature flag values. URL
822
+ * targeting is web-only so it's omitted.
823
+ */
824
+ getActive() {
825
+ if (!this.enabled) return [];
826
+ return this.core.getActiveSurveys(this.buildContext());
827
+ }
828
+ /** Mark a survey as shown — emits `survey shown` auto-event. */
829
+ markShown(surveyId) {
830
+ this.core.markSurveyShown(surveyId);
831
+ this.persistShowHistory();
832
+ this.notify();
833
+ }
834
+ /** Mark a survey as dismissed — emits `survey dismissed` auto-event. */
835
+ markDismissed(surveyId) {
836
+ this.core.markSurveyDismissed(surveyId);
837
+ this.notify();
838
+ }
839
+ /** Submit a survey response — emits `survey sent` auto-event. */
840
+ submit(surveyId, response) {
841
+ this.core.submitSurveyResponse(surveyId, response);
842
+ this.notify();
843
+ }
844
+ /**
845
+ * Subscribe to changes in the eligible-surveys list. The callback fires
846
+ * after every show/dismiss/submit and after the show-history is hydrated
847
+ * from persistence on init.
848
+ */
849
+ subscribe(listener) {
850
+ this.listeners.add(listener);
851
+ try {
852
+ listener(this.getActive());
853
+ } catch {}
854
+ return () => {
855
+ this.listeners.delete(listener);
856
+ };
857
+ }
858
+ configure(patch) {
859
+ Object.assign(this.options, patch);
860
+ this.notify();
861
+ }
862
+ buildContext() {
863
+ const featureFlagValues = {};
864
+ const resolver = this.options.resolveFeatureFlag;
865
+ if (resolver) for (const def of this.allDefinitions()) {
866
+ const flag = def?.targeting?.feature_flag;
867
+ if (flag) {
868
+ const v = resolver(flag);
869
+ if (typeof v === "boolean") featureFlagValues[flag] = v;
870
+ else if (typeof v === "string") featureFlagValues[flag] = v.length > 0 && v !== "false";
871
+ }
872
+ }
873
+ return {
874
+ person_properties: this.options.personProperties ?? {},
875
+ feature_flag_values: featureFlagValues
876
+ };
877
+ }
878
+ allDefinitions() {
879
+ try {
880
+ return JSON.parse(this.core.surveyDefinitionsJson());
881
+ } catch {
882
+ return [];
883
+ }
884
+ }
885
+ async hydrate() {
886
+ if (this.hydrated) return;
887
+ try {
888
+ const raw = await this.options.persistence?.read(SHOW_HISTORY_STORAGE_KEY);
889
+ if (raw) this.core.seedSurveyShowHistory(raw);
890
+ } catch {} finally {
891
+ this.hydrated = true;
892
+ this.notify();
893
+ }
894
+ }
895
+ async persistShowHistory() {
896
+ if (!this.options.persistence) return;
897
+ try {
898
+ const json = this.core.surveyShowHistoryJson();
899
+ await this.options.persistence.write(SHOW_HISTORY_STORAGE_KEY, json);
900
+ } catch {}
901
+ }
902
+ notify() {
903
+ if (this.listeners.size === 0) return;
904
+ const actives = this.getActive();
905
+ for (const l of this.listeners) try {
906
+ l(actives);
907
+ } catch {}
908
+ }
909
+ };
910
+
695
911
  //#endregion
696
912
  //#region src/index.ts
697
913
  const SDK_VERSION = typeof __LAYERS_RN_VERSION__ !== "undefined" ? __LAYERS_RN_VERSION__ : "0.1.0";
@@ -715,6 +931,7 @@ var LayersReactNative = class LayersReactNative {
715
931
  static CONFIG_POLL_INTERVAL_MS = 3e5;
716
932
  _adServicesToken = null;
717
933
  _installReferrer = null;
934
+ _installReferrerParams = null;
718
935
  _hadPriorSdkState = false;
719
936
  _attributionDeeplinkId = null;
720
937
  _attributionGclid = null;
@@ -743,7 +960,8 @@ var LayersReactNative = class LayersReactNative {
743
960
  ...config.flushIntervalMs != null && { flushIntervalMs: config.flushIntervalMs },
744
961
  ...config.flushThreshold != null && { flushThreshold: config.flushThreshold },
745
962
  ...config.maxQueueSize != null && { maxQueueSize: config.maxQueueSize },
746
- sdkVersion: `react-native/${SDK_VERSION}`
963
+ sdkVersion: `react-native/${SDK_VERSION}`,
964
+ ...config.bootstrap != null && { bootstrap: config.bootstrap }
747
965
  },
748
966
  httpClient,
749
967
  persistence: new __layers_core_wasm.MemoryPersistence()
@@ -765,21 +983,23 @@ var LayersReactNative = class LayersReactNative {
765
983
  environment: this.config.environment,
766
984
  ...this.config.baseUrl != null && { baseUrl: this.config.baseUrl },
767
985
  ...this.config.enableDebug != null && { enableDebug: this.config.enableDebug },
986
+ ...this.config.debug != null && { debug: this.config.debug },
768
987
  ...this.config.flushIntervalMs != null && { flushIntervalMs: this.config.flushIntervalMs },
769
988
  ...this.config.flushThreshold != null && { flushThreshold: this.config.flushThreshold },
770
989
  ...this.config.maxQueueSize != null && { maxQueueSize: this.config.maxQueueSize },
771
- sdkVersion: `react-native/${SDK_VERSION}`
990
+ sdkVersion: `react-native/${SDK_VERSION}`,
991
+ ...this.config.bootstrap != null && { bootstrap: this.config.bootstrap }
772
992
  },
773
993
  httpClient,
774
994
  persistence
775
995
  });
776
996
  if (this.appUserId) this.core.identify(this.appUserId);
777
997
  } catch {}
998
+ await this.restoreAttributionData();
778
999
  await this.initializeDeviceInfo();
779
1000
  this.setupAppStateListener();
780
1001
  this.setupNetInfoListener();
781
1002
  const mainThreadDurationMs = Date.now() - initStartTime;
782
- await this.restoreAttributionData();
783
1003
  await this.core.fetchRemoteConfig().catch(() => {});
784
1004
  await this.configureSkanFromRemoteConfig();
785
1005
  this.startConfigPolling();
@@ -806,6 +1026,10 @@ var LayersReactNative = class LayersReactNative {
806
1026
  } catch {}
807
1027
  const isFirstLaunch = await shouldTreatAsNewInstall(isFirstLaunchByFlag, this._hadPriorSdkState, this.enableDebug);
808
1028
  appOpenProps.is_first_launch = isFirstLaunch;
1029
+ let hasAttribution = this._attributionFbclid != null || this._attributionGclid != null || this._attributionTtclid != null || this._attributionMsclkid != null;
1030
+ if (isFirstLaunch && !hasAttribution) try {
1031
+ await this.resolveClickFromFingerprint();
1032
+ } catch {}
809
1033
  if (isFirstLaunch) try {
810
1034
  const AsyncStorage = await loadAsyncStorage();
811
1035
  if (AsyncStorage) await AsyncStorage.setItem(FIRST_LAUNCH_TRACKED_KEY, "true");
@@ -820,7 +1044,25 @@ var LayersReactNative = class LayersReactNative {
820
1044
  if (this._installReferrer.referrerClickTimestamp) appOpenProps.install_referrer_click_timestamp = this._installReferrer.referrerClickTimestamp;
821
1045
  if (this._installReferrer.installBeginTimestamp) appOpenProps.install_referrer_install_timestamp = this._installReferrer.installBeginTimestamp;
822
1046
  }
1047
+ if (this._installReferrerParams) {
1048
+ for (const [key, value] of Object.entries(this._installReferrerParams)) if (appOpenProps[key] === void 0) appOpenProps[key] = value;
1049
+ }
1050
+ if (isFirstLaunch) this.track("app_install", appOpenProps);
823
1051
  this.track("app_open", appOpenProps);
1052
+ if (this.config.autoTrackAppUpdate !== false) try {
1053
+ const currentVersion = this.core.getDeviceContext().appVersion ?? appOpenProps.app_version;
1054
+ if (currentVersion && typeof currentVersion === "string") {
1055
+ const AsyncStorage = await loadAsyncStorage();
1056
+ if (AsyncStorage) {
1057
+ const previousVersion = await AsyncStorage.getItem(LAST_APP_VERSION_KEY);
1058
+ if (previousVersion && previousVersion !== currentVersion) this.track("$app_update", {
1059
+ previous_version: previousVersion,
1060
+ current_version: currentVersion
1061
+ });
1062
+ await AsyncStorage.setItem(LAST_APP_VERSION_KEY, currentVersion);
1063
+ }
1064
+ }
1065
+ } catch {}
824
1066
  }
825
1067
  if (this.config.autoTrackDeepLinks !== false) this.setupDeepLinkAutoTracking();
826
1068
  this._isInitialized = true;
@@ -870,6 +1112,193 @@ var LayersReactNative = class LayersReactNative {
870
1112
  async setConsent(consent) {
871
1113
  this.core.setConsent(consent);
872
1114
  }
1115
+ /** Evaluate a feature flag. Emits `$feature_flag_called` (deduped per session). */
1116
+ getFeatureFlag(flagKey) {
1117
+ return this.core.getFeatureFlag(flagKey);
1118
+ }
1119
+ /** Convenience: returns true iff `getFeatureFlag(flagKey)` is truthy. */
1120
+ isFeatureEnabled(flagKey) {
1121
+ return this.core.isFeatureEnabled(flagKey);
1122
+ }
1123
+ /** Look up the JSON payload attached to a flag. Does NOT emit exposure events. */
1124
+ getFeatureFlagPayload(flagKey) {
1125
+ return this.core.getFeatureFlagPayload(flagKey);
1126
+ }
1127
+ /** Snapshot every accessible flag's current value. */
1128
+ getAllFlags() {
1129
+ return this.core.getAllFlags();
1130
+ }
1131
+ /** Force a /config refresh and re-fire any registered listeners. */
1132
+ async reloadFeatureFlags() {
1133
+ return this.core.reloadFeatureFlags();
1134
+ }
1135
+ /** Override person properties used for flag evaluation only. */
1136
+ setPersonPropertiesForFlags(properties) {
1137
+ try {
1138
+ this.core.setPersonPropertiesForFlags(properties);
1139
+ } catch (e) {
1140
+ this.emitError(e);
1141
+ }
1142
+ }
1143
+ /** Merge additional person properties into the flag-evaluation map. */
1144
+ mergePersonPropertiesForFlags(properties) {
1145
+ try {
1146
+ this.core.mergePersonPropertiesForFlags(properties);
1147
+ } catch (e) {
1148
+ this.emitError(e);
1149
+ }
1150
+ }
1151
+ /** Subscribe to feature-flag refreshes. Returns an unsubscribe function. */
1152
+ onFeatureFlags(callback) {
1153
+ return this.core.onFeatureFlags(callback);
1154
+ }
1155
+ /** Seed bootstrap flag values + payloads after init. */
1156
+ setFeatureFlagBootstrap(bootstrap) {
1157
+ this.core.setFeatureFlagBootstrap(bootstrap);
1158
+ }
1159
+ /**
1160
+ * Register one or more super-properties — auto-merged into every track /
1161
+ * screen call until cleared. Super-properties carry app-wide context
1162
+ * (plan tier, region, experiment bucket).
1163
+ */
1164
+ setSuperProperties(properties) {
1165
+ try {
1166
+ this.core.setSuperProperties(properties);
1167
+ } catch (e) {
1168
+ this.emitError(e);
1169
+ }
1170
+ }
1171
+ /** Register super-properties only if their keys have not been set before. */
1172
+ setSuperPropertiesOnce(properties) {
1173
+ try {
1174
+ this.core.setSuperPropertiesOnce(properties);
1175
+ } catch (e) {
1176
+ this.emitError(e);
1177
+ }
1178
+ }
1179
+ /** Remove a single super-property by key. */
1180
+ unregisterSuperProperty(key) {
1181
+ try {
1182
+ this.core.unregisterSuperProperty(key);
1183
+ } catch (e) {
1184
+ this.emitError(e);
1185
+ }
1186
+ }
1187
+ /** Clear all registered super-properties. */
1188
+ clearSuperProperties() {
1189
+ try {
1190
+ this.core.clearSuperProperties();
1191
+ } catch (e) {
1192
+ this.emitError(e);
1193
+ }
1194
+ }
1195
+ /** Snapshot the currently-registered super-properties. */
1196
+ getSuperProperties() {
1197
+ return this.core.getSuperProperties();
1198
+ }
1199
+ /** Start a duration timer for the next `track(name)` call. */
1200
+ timeEvent(eventName) {
1201
+ try {
1202
+ this.core.timeEvent(eventName);
1203
+ } catch (e) {
1204
+ this.emitError(e);
1205
+ }
1206
+ }
1207
+ /** Cancel a timed event without emitting it. Returns elapsed ms (0 if none). */
1208
+ cancelTimedEvent(eventName) {
1209
+ try {
1210
+ return this.core.cancelTimedEvent(eventName);
1211
+ } catch (e) {
1212
+ this.emitError(e);
1213
+ return 0;
1214
+ }
1215
+ }
1216
+ /** Set membership for a single group_type. Empty `groupId` removes the type. */
1217
+ setGroup(groupType, groupId) {
1218
+ try {
1219
+ this.core.setGroup(groupType, groupId);
1220
+ } catch (e) {
1221
+ this.emitError(e);
1222
+ }
1223
+ }
1224
+ /** Add a group membership without overwriting other types (alias for setGroup). */
1225
+ addGroup(groupType, groupId) {
1226
+ try {
1227
+ this.core.addGroup(groupType, groupId);
1228
+ } catch (e) {
1229
+ this.emitError(e);
1230
+ }
1231
+ }
1232
+ /** Remove a group_type from the membership map. */
1233
+ removeGroup(groupType) {
1234
+ try {
1235
+ this.core.removeGroup(groupType);
1236
+ } catch (e) {
1237
+ this.emitError(e);
1238
+ }
1239
+ }
1240
+ /** Snapshot the current $groups membership map. */
1241
+ getGroups() {
1242
+ return this.core.getGroups();
1243
+ }
1244
+ /** Increment a numeric user property by `delta`. */
1245
+ increment(key, delta = 1) {
1246
+ try {
1247
+ this.core.increment(key, delta);
1248
+ } catch (e) {
1249
+ this.emitError(e);
1250
+ }
1251
+ }
1252
+ /** Append a single value to a list-typed user property. */
1253
+ append(key, value) {
1254
+ try {
1255
+ this.core.append(key, value);
1256
+ } catch (e) {
1257
+ this.emitError(e);
1258
+ }
1259
+ }
1260
+ /** Union (set-add) values into a list-typed user property. */
1261
+ union(key, values) {
1262
+ try {
1263
+ this.core.union(key, values);
1264
+ } catch (e) {
1265
+ this.emitError(e);
1266
+ }
1267
+ }
1268
+ /** Remove a user property by key. */
1269
+ unset(key) {
1270
+ try {
1271
+ this.core.unset(key);
1272
+ } catch (e) {
1273
+ this.emitError(e);
1274
+ }
1275
+ }
1276
+ /** Returns the current anonymous ID, rotated on `reset()`. */
1277
+ getAnonymousId() {
1278
+ return this.core.getAnonymousId();
1279
+ }
1280
+ /** Returns the current device ID (stable per install, rotated on `reset()`). */
1281
+ getDeviceId() {
1282
+ return this.core.getDeviceId();
1283
+ }
1284
+ /** Returns the monotonically-increasing session number. */
1285
+ getSessionNumber() {
1286
+ return this.core.getSessionNumber();
1287
+ }
1288
+ /** Returns the SDK first-open RFC3339 timestamp, or null. */
1289
+ getFirstOpenTime() {
1290
+ return this.core.getFirstOpenTime();
1291
+ }
1292
+ /**
1293
+ * Register a synchronous filter callback called for every track / screen
1294
+ * before the event reaches the queue. Return `null` to drop, or a modified
1295
+ * `BeforeSendEvent` to forward.
1296
+ *
1297
+ * Pass `null` to clear the hook.
1298
+ */
1299
+ setBeforeSend(hook) {
1300
+ this.core.setBeforeSend(hook);
1301
+ }
873
1302
  /**
874
1303
  * Request App Tracking Transparency authorization (iOS only).
875
1304
  * After the user responds, this method automatically:
@@ -928,24 +1357,19 @@ var LayersReactNative = class LayersReactNative {
928
1357
  this.userIdLocked = false;
929
1358
  }
930
1359
  /**
931
- * Reset the SDK state: clears the user ID, unlocks set-user-once,
932
- * clears user properties, and starts a new session.
1360
+ * Reset the SDK state: clears the user ID, unlocks set-user-once, drops
1361
+ * super-properties + multi-group memberships, rotates device / anonymous
1362
+ * IDs, and starts a new session.
933
1363
  *
934
- * After reset(), the SDK behaves as if no user has been identified.
935
- * A new anonymous session is started. Events tracked after reset()
936
- * will not carry the previous user's identity.
1364
+ * After reset(), the SDK behaves as if no user has been identified. Events
1365
+ * tracked after reset() will not carry the previous user's identity.
937
1366
  */
938
1367
  reset() {
939
1368
  if (this.enableDebug) console.log("[Layers] reset()");
940
1369
  this.appUserId = void 0;
941
1370
  this.userIdLocked = false;
942
1371
  try {
943
- this.core.setUserProperties({});
944
- } catch (e) {
945
- this.emitError(e);
946
- }
947
- try {
948
- this.core.startNewSession();
1372
+ this.core.reset();
949
1373
  } catch (e) {
950
1374
  this.emitError(e);
951
1375
  }
@@ -1073,6 +1497,17 @@ var LayersReactNative = class LayersReactNative {
1073
1497
  getQueueDepth() {
1074
1498
  return this.core.queueDepth();
1075
1499
  }
1500
+ /**
1501
+ * Return the per-device DebugView token, or null if `debug` was not enabled
1502
+ * in the constructor config.
1503
+ *
1504
+ * When debug mode is on the SDK persists a stable UUID via AsyncStorage
1505
+ * and sends it in the `X-Debug-Token` header on every event upload. This
1506
+ * lets dashboard UIs filter the live tail to events from this device only.
1507
+ */
1508
+ getDebugToken() {
1509
+ return this.core.getDebugToken();
1510
+ }
1076
1511
  /** Current device context from the core. */
1077
1512
  getDeviceContext() {
1078
1513
  return this.core.getDeviceContext();
@@ -1093,6 +1528,72 @@ var LayersReactNative = class LayersReactNative {
1093
1528
  return this._recentEvents;
1094
1529
  }
1095
1530
  /**
1531
+ * POST a device fingerprint to /clicks/resolve so the server can match this
1532
+ * first-launch install to a recent /c/:appId click captured in the browser
1533
+ * before the App Store / Play Store redirect. On a successful match, persist
1534
+ * the returned click IDs via setAttributionData so every subsequent event
1535
+ * (app_open, purchase_success, etc.) carries fbclid / gclid / ttclid / etc.
1536
+ *
1537
+ * This is the primary iOS web-to-app attribution path, since iOS has no
1538
+ * equivalent of Android's Play Install Referrer. Also serves as a fallback
1539
+ * for Android installs where the Install Referrer API returned nothing
1540
+ * (sideload, Amazon Appstore, testing).
1541
+ *
1542
+ * Best-effort: all errors are swallowed — this must never block app_open.
1543
+ */
1544
+ async resolveClickFromFingerprint() {
1545
+ const baseUrl = (this.config.baseUrl ?? "https://in.layers.com").replace(/\/$/, "");
1546
+ const deviceContext = this.core.getDeviceContext();
1547
+ let platform;
1548
+ try {
1549
+ const { Platform } = require("react-native");
1550
+ platform = Platform.OS;
1551
+ } catch {
1552
+ platform = void 0;
1553
+ }
1554
+ const fingerprint = {
1555
+ app_id: this.config.appId,
1556
+ platform,
1557
+ device_model: deviceContext.deviceModel ?? null,
1558
+ os_version: deviceContext.osVersion ?? null,
1559
+ locale: deviceContext.locale ?? null,
1560
+ timezone: deviceContext.timezone ?? null,
1561
+ screen_size: deviceContext.screenSize ?? null
1562
+ };
1563
+ const controller = new AbortController();
1564
+ const timeoutId = setTimeout(() => controller.abort(), 3e3);
1565
+ let response;
1566
+ try {
1567
+ response = await fetch(`${baseUrl}/clicks/resolve`, {
1568
+ method: "POST",
1569
+ headers: {
1570
+ "Content-Type": "application/json",
1571
+ "X-App-Id": this.config.appId,
1572
+ "X-SDK-Version": `react-native/${SDK_VERSION}`
1573
+ },
1574
+ body: JSON.stringify(fingerprint),
1575
+ signal: controller.signal
1576
+ });
1577
+ } finally {
1578
+ clearTimeout(timeoutId);
1579
+ }
1580
+ if (!response.ok) {
1581
+ if (this.enableDebug) console.log(`[Layers] /clicks/resolve status=${response.status}`);
1582
+ return;
1583
+ }
1584
+ const body = await response.json();
1585
+ if (!body?.success || !body.data?.matched) {
1586
+ if (this.enableDebug) console.log("[Layers] /clicks/resolve no-match");
1587
+ return;
1588
+ }
1589
+ const { fbclid, gclid, ttclid, msclkid, method, confidence } = body.data;
1590
+ if (!fbclid && !gclid && !ttclid && !msclkid) return;
1591
+ try {
1592
+ await this.setAttributionData(this._attributionDeeplinkId, gclid ?? this._attributionGclid, fbclid ?? this._attributionFbclid, ttclid ?? this._attributionTtclid, msclkid ?? this._attributionMsclkid);
1593
+ if (this.enableDebug) console.log(`[Layers] /clicks/resolve matched method=${String(method)} confidence=${String(confidence)} fbclid=${String(fbclid)}`);
1594
+ } catch {}
1595
+ }
1596
+ /**
1096
1597
  * Fire-and-forget POST to /users/properties.
1097
1598
  * Best-effort: errors are silently swallowed.
1098
1599
  */
@@ -1376,6 +1877,7 @@ var LayersReactNative = class LayersReactNative {
1376
1877
  } catch {}
1377
1878
  this.core.setDeviceContext(context);
1378
1879
  }
1880
+ this._installReferrerParams = null;
1379
1881
  try {
1380
1882
  const { Platform } = require("react-native");
1381
1883
  if (Platform.OS === "ios") try {
@@ -1384,16 +1886,37 @@ var LayersReactNative = class LayersReactNative {
1384
1886
  } catch {}
1385
1887
  if (Platform.OS === "android") try {
1386
1888
  const referrer = await getInstallReferrer();
1387
- if (referrer) this._installReferrer = referrer;
1889
+ if (referrer) {
1890
+ this._installReferrer = referrer;
1891
+ const parsed = parseInstallReferrerUrl(referrer.referrerUrl);
1892
+ this._installReferrerParams = Object.keys(parsed).length > 0 ? parsed : null;
1893
+ if (parsed.fbclid || parsed.gclid || parsed.ttclid || parsed.msclkid) try {
1894
+ await this.setAttributionData(this._attributionDeeplinkId, parsed.gclid ?? this._attributionGclid, parsed.fbclid ?? this._attributionFbclid, parsed.ttclid ?? this._attributionTtclid, parsed.msclkid ?? this._attributionMsclkid);
1895
+ } catch {}
1896
+ }
1388
1897
  } catch {}
1389
1898
  } catch {}
1390
1899
  }
1391
1900
  setupAppStateListener() {
1392
1901
  try {
1393
1902
  const { AppState } = require("react-native");
1903
+ let lastEmittedState = null;
1394
1904
  this.appStateSubscription = AppState.addEventListener("change", (nextAppState) => {
1395
- if (nextAppState === "background" || nextAppState === "inactive") this.core.flush();
1396
- if (nextAppState === "active" && this.isOnline) this.core.flushAsync().catch(() => {});
1905
+ if (nextAppState === "background" || nextAppState === "inactive") {
1906
+ if (this.config.autoTrackAppLifecycle !== false && lastEmittedState !== "background") try {
1907
+ this.track("$app_background");
1908
+ lastEmittedState = "background";
1909
+ } catch {}
1910
+ this.core.flush();
1911
+ }
1912
+ if (nextAppState === "active") {
1913
+ if (this.config.autoTrackAppLifecycle !== false && lastEmittedState !== null && lastEmittedState !== "active") try {
1914
+ this.track("$app_foreground");
1915
+ lastEmittedState = "active";
1916
+ } catch {}
1917
+ else if (lastEmittedState === null) lastEmittedState = "active";
1918
+ if (this.isOnline) this.core.flushAsync().catch(() => {});
1919
+ }
1397
1920
  });
1398
1921
  } catch {}
1399
1922
  }
@@ -1461,9 +1984,9 @@ async function createAsyncStoragePersistence(appId) {
1461
1984
  try {
1462
1985
  const AsyncStorage = await loadAsyncStorage();
1463
1986
  if (AsyncStorage) {
1464
- const layersKeys = (await AsyncStorage.getAllKeys()).filter((k) => k.startsWith(prefix));
1465
- if (layersKeys.length > 0) {
1466
- const pairs = await AsyncStorage.multiGet(layersKeys);
1987
+ const sdkKeys = (await AsyncStorage.getAllKeys()).filter((k) => k.startsWith(prefix));
1988
+ if (sdkKeys.length > 0) {
1989
+ const pairs = await AsyncStorage.multiGet(sdkKeys);
1467
1990
  for (const [key, value] of pairs) if (value) {
1468
1991
  const shortKey = key.slice(prefix.length);
1469
1992
  memoryStore.set(shortKey, base64Decode(value));
@@ -1570,6 +2093,11 @@ function getLocale() {
1570
2093
  const INSTALL_ID_KEY = "layers_install_id";
1571
2094
  const FIRST_LAUNCH_TRACKED_KEY = "@layers/first_launch_tracked";
1572
2095
  /**
2096
+ * Last-known app_version persisted across launches. Used to detect
2097
+ * `$app_update` (version increment) vs. `$first_open` (no prior value).
2098
+ */
2099
+ const LAST_APP_VERSION_KEY = "@layers/last_app_version";
2100
+ /**
1573
2101
  * Maximum age of an app installation (in milliseconds) for which the SDK
1574
2102
  * will consider the first launch as a genuine new install. If the app was
1575
2103
  * installed more than 24 hours ago AND no prior Layers SDK state exists,
@@ -1748,6 +2276,54 @@ async function getAdServicesToken() {
1748
2276
  }
1749
2277
  }
1750
2278
  /**
2279
+ * Known attribution params extracted from the Play Install Referrer string.
2280
+ * Keep in sync with layers sdk-ingest routes/click.ts::buildAndroidReferrerUrl
2281
+ * and the parallel allowlists in kotlin / unity / flutter SDKs.
2282
+ */
2283
+ const INSTALL_REFERRER_ATTRIBUTION_PARAMS = new Set([
2284
+ "utm_source",
2285
+ "utm_medium",
2286
+ "utm_campaign",
2287
+ "utm_content",
2288
+ "utm_term",
2289
+ "gclid",
2290
+ "gbraid",
2291
+ "wbraid",
2292
+ "fbclid",
2293
+ "ttclid",
2294
+ "twclid",
2295
+ "msclkid",
2296
+ "li_fat_id",
2297
+ "sclid",
2298
+ "rclid",
2299
+ "irclickid",
2300
+ "click_id"
2301
+ ]);
2302
+ /**
2303
+ * Parse a raw Play Install Referrer string into a map of recognized attribution
2304
+ * params. Accepts either a bare query string (`a=1&b=2`) or a full URL.
2305
+ * Returns an empty object on parse failure.
2306
+ */
2307
+ function parseInstallReferrerUrl(referrer) {
2308
+ const out = {};
2309
+ if (!referrer) return out;
2310
+ try {
2311
+ let qs = referrer;
2312
+ const qIdx = qs.indexOf("?");
2313
+ if (qIdx >= 0) qs = qs.slice(qIdx + 1);
2314
+ if (!qs.includes("=") && qs.includes("%3D")) qs = decodeURIComponent(qs);
2315
+ for (const pair of qs.split("&")) {
2316
+ const eq = pair.indexOf("=");
2317
+ if (eq >= 0) try {
2318
+ const key = decodeURIComponent(pair.slice(0, eq));
2319
+ const value = decodeURIComponent(pair.slice(eq + 1));
2320
+ if (value && INSTALL_REFERRER_ATTRIBUTION_PARAMS.has(key)) out[key] = value;
2321
+ } catch {}
2322
+ }
2323
+ } catch {}
2324
+ return out;
2325
+ }
2326
+ /**
1751
2327
  * Fetch the Google Play install referrer on Android via NativeModules.
1752
2328
  * Requires the `com.android.installreferrer` library on the native side.
1753
2329
  * Returns null on iOS or when the native module is not available.
@@ -1821,7 +2397,17 @@ function parseDeepLink(url) {
1821
2397
  return null;
1822
2398
  }
1823
2399
  }
1824
- function useLayersExpoRouterTracking(layersInstance, usePathname, useGlobalSearchParams) {
2400
+ const _expoRouterPreviousPath = /* @__PURE__ */ new WeakMap();
2401
+ /**
2402
+ * Hook that emits `$screen_view` for every Expo Router pathname change.
2403
+ *
2404
+ * The hook also tracks the previous pathname so the emitted event carries
2405
+ * `previous_screen_name`, matching the React Navigation observer in
2406
+ * `useLayersNavigationTracking`. This makes funnel analysis trivial
2407
+ * server-side: every screen event has a self-contained pair `(from, to)`
2408
+ * — no need to join adjacent rows.
2409
+ */
2410
+ function useLayersExpoRouterTracking(sdkInstance, usePathname, useGlobalSearchParams) {
1825
2411
  const { useEffect } = require("react");
1826
2412
  const pathname = usePathname();
1827
2413
  const params = useGlobalSearchParams();
@@ -1831,7 +2417,10 @@ function useLayersExpoRouterTracking(layersInstance, usePathname, useGlobalSearc
1831
2417
  Object.entries(params).forEach(([key, value]) => {
1832
2418
  properties[key] = Array.isArray(value) ? value.join(",") : value;
1833
2419
  });
1834
- layersInstance.screen(pathname, properties);
2420
+ const previous = _expoRouterPreviousPath.get(sdkInstance);
2421
+ if (previous && previous !== pathname) properties.previous_screen_name = previous;
2422
+ sdkInstance.screen(pathname, properties);
2423
+ _expoRouterPreviousPath.set(sdkInstance, pathname);
1835
2424
  }
1836
2425
  }, [pathname, JSON.stringify(params)]);
1837
2426
  }
@@ -1861,6 +2450,12 @@ Object.defineProperty(exports, 'StandardEvents', {
1861
2450
  return StandardEvents;
1862
2451
  }
1863
2452
  });
2453
+ Object.defineProperty(exports, 'SurveysModule', {
2454
+ enumerable: true,
2455
+ get: function () {
2456
+ return SurveysModule;
2457
+ }
2458
+ });
1864
2459
  Object.defineProperty(exports, 'addToCartEvent', {
1865
2460
  enumerable: true,
1866
2461
  get: function () {
@@ -1885,6 +2480,12 @@ Object.defineProperty(exports, 'createBackgroundFlushHandler', {
1885
2480
  return createBackgroundFlushHandler;
1886
2481
  }
1887
2482
  });
2483
+ Object.defineProperty(exports, 'createNavigationListener', {
2484
+ enumerable: true,
2485
+ get: function () {
2486
+ return createNavigationListener;
2487
+ }
2488
+ });
1888
2489
  Object.defineProperty(exports, 'formatFbc', {
1889
2490
  enumerable: true,
1890
2491
  get: function () {
@@ -1957,6 +2558,12 @@ Object.defineProperty(exports, 'parseDeepLink', {
1957
2558
  return parseDeepLink;
1958
2559
  }
1959
2560
  });
2561
+ Object.defineProperty(exports, 'parseInstallReferrerUrl', {
2562
+ enumerable: true,
2563
+ get: function () {
2564
+ return parseInstallReferrerUrl;
2565
+ }
2566
+ });
1960
2567
  Object.defineProperty(exports, 'purchaseEvent', {
1961
2568
  enumerable: true,
1962
2569
  get: function () {
@@ -1987,6 +2594,12 @@ Object.defineProperty(exports, 'resetRevenueCatForTesting', {
1987
2594
  return resetRevenueCatForTesting;
1988
2595
  }
1989
2596
  });
2597
+ Object.defineProperty(exports, 'resolveActiveRoute', {
2598
+ enumerable: true,
2599
+ get: function () {
2600
+ return resolveActiveRoute;
2601
+ }
2602
+ });
1990
2603
  Object.defineProperty(exports, 'screenViewEvent', {
1991
2604
  enumerable: true,
1992
2605
  get: function () {
@@ -2149,6 +2762,12 @@ Object.defineProperty(exports, 'useLayersExpoRouterTracking', {
2149
2762
  return useLayersExpoRouterTracking;
2150
2763
  }
2151
2764
  });
2765
+ Object.defineProperty(exports, 'useLayersNavigationTracking', {
2766
+ enumerable: true,
2767
+ get: function () {
2768
+ return useLayersNavigationTracking;
2769
+ }
2770
+ });
2152
2771
  Object.defineProperty(exports, 'viewContentEvent', {
2153
2772
  enumerable: true,
2154
2773
  get: function () {