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