@layers/react-native 0.2.0-alpha.9 → 1.0.1

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.
package/dist/index.js CHANGED
@@ -1,961 +1,5 @@
1
- import { __require } from "./chunk-BLXvPPr8.js";
2
- import { LayersClient } from "@layers/client";
3
- import { NativeModules, Platform } from "react-native";
4
- import { useEffect } from "react";
1
+ import { a as requestTrackingAuthorization, i as isATTAvailable, n as getAdvertisingId, r as getVendorId, t as getATTStatus } from "./att-C5tL1hKX.js";
2
+ import { t as SKANManager } from "./skan-_aDXcXWQ.js";
3
+ import { a as setupDeepLinkListener, i as parseDeepLink, n as LayersReactNative, o as useLayersExpoRouterTracking, r as getOrSetInstallId, t as LayersError } from "./src-CkG9jg57.js";
5
4
 
6
- export * from "@layers/client"
7
-
8
- //#region src/native/SKANModule.ts
9
- /**
10
- * Mock SKAN implementation
11
- */
12
- var MockSKANModule = class {
13
- conversionValue = 0;
14
- isRegistered = false;
15
- attributionData = null;
16
- async isAvailable() {
17
- return Platform.OS === "ios";
18
- }
19
- async getVersion() {
20
- return "4.0";
21
- }
22
- async registerAppForAdNetworkAttribution() {
23
- this.isRegistered = true;
24
- this.attributionData = {
25
- adNetworkId: "mock.network.com",
26
- campaignId: "12345",
27
- sourceAppId: "123456789",
28
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
29
- };
30
- console.log("[Mock SKAN] App registered for attribution");
31
- }
32
- async updateConversionValue(value) {
33
- if (value >= 0 && value <= 63) {
34
- this.conversionValue = Math.max(this.conversionValue, value);
35
- console.log(`[Mock SKAN] Conversion value updated to: ${value}`);
36
- } else console.warn(`[Mock SKAN] Invalid conversion value: ${value}. Must be 0-63.`);
37
- }
38
- async updatePostbackConversionValue(value, coarseValue, lockWindow) {
39
- this.conversionValue = Math.max(this.conversionValue, value);
40
- console.log(`[Mock SKAN] Postback value updated: ${value}, coarse: ${coarseValue}, lock: ${lockWindow}`);
41
- }
42
- async startImpression(signature) {
43
- console.log(`[Mock SKAN] Started impression: ${signature}`);
44
- }
45
- async endImpression(signature) {
46
- console.log(`[Mock SKAN] Ended impression: ${signature}`);
47
- }
48
- async getCurrentConversionValue() {
49
- return this.conversionValue;
50
- }
51
- async getAttributionData() {
52
- return this.attributionData;
53
- }
54
- };
55
- /**
56
- * Get SKAN module instance
57
- */
58
- function getSKANModule() {
59
- if (Platform.OS === "ios") {
60
- const nativeModule = NativeModules.LayersSKAN;
61
- if (nativeModule) return nativeModule;
62
- }
63
- return new MockSKANModule();
64
- }
65
- /**
66
- * SKAN Manager - High-level wrapper for SKAdNetwork functionality with rule engine
67
- */
68
- var SKANManager = class {
69
- module;
70
- onConversionUpdate;
71
- currentPreset;
72
- rules = [];
73
- ruleEvaluationHistory = [];
74
- constructor(onConversionUpdate) {
75
- this.module = getSKANModule();
76
- if (onConversionUpdate) this.onConversionUpdate = onConversionUpdate;
77
- }
78
- /**
79
- * Initialize SKAN
80
- */
81
- async initialize() {
82
- if (await this.module.isAvailable()) await this.module.registerAppForAdNetworkAttribution();
83
- }
84
- /**
85
- * Check if SKAN is supported
86
- */
87
- async isSupported() {
88
- return this.module.isAvailable();
89
- }
90
- /**
91
- * Get SKAN version
92
- */
93
- async getVersion() {
94
- return this.module.getVersion();
95
- }
96
- /**
97
- * Set conversion rules preset
98
- */
99
- setPreset(preset) {
100
- this.rules = this.getPresetConfig(preset).rules.sort((a, b) => (b.priority || 0) - (a.priority || 0));
101
- this.currentPreset = preset;
102
- console.log(`SKAN preset set to: ${preset} (${this.rules.length} rules)`);
103
- }
104
- /**
105
- * Set custom conversion rules
106
- */
107
- setCustomRules(rules) {
108
- this.rules = rules.sort((a, b) => (b.priority || 0) - (a.priority || 0));
109
- this.currentPreset = "custom";
110
- console.log(`SKAN custom rules set: ${rules.length} rules`);
111
- }
112
- /**
113
- * Process an event against conversion rules
114
- */
115
- async processEvent(eventName, properties) {
116
- if (!await this.isSupported()) return;
117
- const ruleEvaluations = [];
118
- let matchedRule;
119
- for (const rule of this.rules) {
120
- const evaluation = this.evaluateRule(rule, eventName, properties);
121
- const ruleEvaluation = {
122
- rule: rule.description || `${rule.eventName} (${rule.conversionValue})`,
123
- matched: evaluation.matched
124
- };
125
- if (evaluation.reason) ruleEvaluation.reason = evaluation.reason;
126
- ruleEvaluations.push(ruleEvaluation);
127
- if (evaluation.matched && !matchedRule) {
128
- matchedRule = rule;
129
- break;
130
- }
131
- }
132
- const historyEntry = {
133
- event: eventName,
134
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
135
- };
136
- if (matchedRule?.description || matchedRule?.eventName) historyEntry.rule = matchedRule.description || matchedRule.eventName;
137
- this.ruleEvaluationHistory.push(historyEntry);
138
- if (this.ruleEvaluationHistory.length > 100) this.ruleEvaluationHistory = this.ruleEvaluationHistory.slice(-100);
139
- if (matchedRule) try {
140
- const previousValue = await this.module.getCurrentConversionValue() || 0;
141
- if (matchedRule.conversionValue > previousValue) {
142
- if (await this.getVersion() === "4.0" && matchedRule.coarseValue) await this.module.updatePostbackConversionValue(matchedRule.conversionValue, matchedRule.coarseValue, matchedRule.lockWindow);
143
- else await this.module.updateConversionValue(matchedRule.conversionValue);
144
- if (this.onConversionUpdate) this.onConversionUpdate({
145
- event: eventName,
146
- properties,
147
- matchedRule,
148
- previousValue,
149
- newValue: matchedRule.conversionValue,
150
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
151
- ruleEvaluations
152
- });
153
- console.log(`SKAN: Event ${eventName} matched rule '${matchedRule.description || matchedRule.eventName}', value: ${previousValue} → ${matchedRule.conversionValue}`);
154
- } else console.log(`SKAN: Event ${eventName} matched rule but value ${matchedRule.conversionValue} not higher than current ${previousValue}`);
155
- } catch (error) {
156
- console.error("SKAN conversion value update failed:", error);
157
- }
158
- }
159
- /**
160
- * Evaluate if a rule matches an event
161
- */
162
- evaluateRule(rule, eventName, properties) {
163
- if (rule.eventName !== eventName) return {
164
- matched: false,
165
- reason: `Event name '${eventName}' != '${rule.eventName}'`
166
- };
167
- if (rule.conditions) for (const [key, expectedValue] of Object.entries(rule.conditions)) {
168
- const actualValue = properties[key];
169
- if (typeof expectedValue === "object" && expectedValue !== null) {
170
- for (const [operator, comparisonValue] of Object.entries(expectedValue)) if (!this.evaluateCondition(actualValue, operator, comparisonValue).matched) return {
171
- matched: false,
172
- reason: `Condition ${key} ${operator} ${comparisonValue} failed (actual: ${actualValue})`
173
- };
174
- } else if (actualValue !== expectedValue) return {
175
- matched: false,
176
- reason: `Property ${key}: expected ${expectedValue}, got ${actualValue}`
177
- };
178
- }
179
- return { matched: true };
180
- }
181
- /**
182
- * Evaluate a single condition with operator
183
- */
184
- evaluateCondition(actualValue, operator, expectedValue) {
185
- const numericActual = Number(actualValue);
186
- const numericExpected = Number(expectedValue);
187
- switch (operator) {
188
- case ">": return { matched: numericActual > numericExpected };
189
- case ">=": return { matched: numericActual >= numericExpected };
190
- case "<": return { matched: numericActual < numericExpected };
191
- case "<=": return { matched: numericActual <= numericExpected };
192
- case "==":
193
- case "=": return { matched: actualValue === expectedValue };
194
- case "!=": return { matched: actualValue !== expectedValue };
195
- default:
196
- console.warn(`Unknown condition operator: ${operator}`);
197
- return { matched: false };
198
- }
199
- }
200
- /**
201
- * Get current conversion value
202
- */
203
- async getCurrentValue() {
204
- return this.module.getCurrentConversionValue();
205
- }
206
- /**
207
- * Get attribution data
208
- */
209
- async getAttributionData() {
210
- return this.module.getAttributionData();
211
- }
212
- /**
213
- * Get preset configuration
214
- */
215
- getPresetConfig(preset) {
216
- switch (preset) {
217
- case "subscriptions": return {
218
- name: "subscriptions",
219
- description: "Optimized for subscription apps with trial-to-paid conversion tracking",
220
- maxValue: 63,
221
- rules: [
222
- {
223
- eventName: "app_open",
224
- conversionValue: 1,
225
- priority: 1,
226
- description: "App opened"
227
- },
228
- {
229
- eventName: "screen_view",
230
- conditions: { screen_name: "onboarding_complete" },
231
- conversionValue: 8,
232
- priority: 3,
233
- description: "Onboarding completed"
234
- },
235
- {
236
- eventName: "trial_start",
237
- conversionValue: 20,
238
- priority: 5,
239
- description: "Free trial started"
240
- },
241
- {
242
- eventName: "purchase_success",
243
- conditions: { revenue: { "<": 5 } },
244
- conversionValue: 35,
245
- priority: 7,
246
- description: "Small purchase (<$5)"
247
- },
248
- {
249
- eventName: "subscription_start",
250
- conversionValue: 50,
251
- priority: 10,
252
- description: "Subscription started"
253
- },
254
- {
255
- eventName: "subscription_renew",
256
- conversionValue: 63,
257
- priority: 15,
258
- description: "Subscription renewed"
259
- }
260
- ]
261
- };
262
- case "engagement": return {
263
- name: "engagement",
264
- description: "Optimized for engagement-driven apps focusing on user activity",
265
- maxValue: 63,
266
- rules: [
267
- {
268
- eventName: "app_open",
269
- conversionValue: 1,
270
- priority: 1,
271
- description: "App opened"
272
- },
273
- {
274
- eventName: "content_open",
275
- conversionValue: 5,
276
- priority: 2,
277
- description: "Content viewed"
278
- },
279
- {
280
- eventName: "search",
281
- conversionValue: 12,
282
- priority: 4,
283
- description: "Search performed"
284
- },
285
- {
286
- eventName: "bookmark_add",
287
- conversionValue: 25,
288
- priority: 6,
289
- description: "Content bookmarked"
290
- },
291
- {
292
- eventName: "app_open",
293
- conditions: { session_count: { ">": 3 } },
294
- conversionValue: 40,
295
- priority: 8,
296
- description: "Regular user (3+ sessions)"
297
- },
298
- {
299
- eventName: "app_open",
300
- conditions: { session_count: { ">": 10 } },
301
- conversionValue: 63,
302
- priority: 12,
303
- description: "Power user (10+ sessions)"
304
- }
305
- ]
306
- };
307
- case "iap": return {
308
- name: "iap",
309
- description: "Optimized for in-app purchase revenue tracking",
310
- maxValue: 63,
311
- rules: [
312
- {
313
- eventName: "app_open",
314
- conversionValue: 1,
315
- priority: 1,
316
- description: "App opened"
317
- },
318
- {
319
- eventName: "paywall_show",
320
- conversionValue: 8,
321
- priority: 2,
322
- description: "Paywall shown"
323
- },
324
- {
325
- eventName: "purchase_attempt",
326
- conversionValue: 15,
327
- priority: 3,
328
- description: "Purchase attempted"
329
- },
330
- {
331
- eventName: "purchase_success",
332
- conditions: { revenue: { "<": 1 } },
333
- conversionValue: 25,
334
- priority: 5,
335
- description: "Small purchase (<$1)"
336
- },
337
- {
338
- eventName: "purchase_success",
339
- conditions: { revenue: {
340
- ">=": 1,
341
- "<": 10
342
- } },
343
- conversionValue: 40,
344
- priority: 7,
345
- description: "Medium purchase ($1-$10)"
346
- },
347
- {
348
- eventName: "purchase_success",
349
- conditions: { revenue: { ">=": 10 } },
350
- conversionValue: 63,
351
- priority: 10,
352
- description: "Large purchase ($10+)"
353
- }
354
- ]
355
- };
356
- default: throw new Error(`Unknown preset: ${preset}`);
357
- }
358
- }
359
- /**
360
- * Get current preset name
361
- */
362
- getCurrentPreset() {
363
- return this.currentPreset || null;
364
- }
365
- /**
366
- * Get current rules
367
- */
368
- getCurrentRules() {
369
- return [...this.rules];
370
- }
371
- /**
372
- * Get rule evaluation history
373
- */
374
- getEvaluationHistory() {
375
- return [...this.ruleEvaluationHistory];
376
- }
377
- /**
378
- * Check if SKAN 4.0 features are available
379
- */
380
- async supportsSKAN4() {
381
- return await this.getVersion() === "4.0";
382
- }
383
- /**
384
- * Get SKAN metrics for debugging
385
- */
386
- async getSKANMetrics() {
387
- const isSupported = await this.isSupported();
388
- const version = await this.getVersion();
389
- const currentValue = await this.getCurrentValue();
390
- const attributionData = await this.getAttributionData();
391
- return {
392
- isSupported,
393
- version,
394
- currentValue,
395
- currentPreset: this.currentPreset || null,
396
- ruleCount: this.rules.length,
397
- evaluationCount: this.ruleEvaluationHistory.length,
398
- attributionData,
399
- lastEvaluations: this.ruleEvaluationHistory.slice(-5)
400
- };
401
- }
402
- };
403
- const SKAN = new SKANManager();
404
-
405
- //#endregion
406
- //#region src/storage/identity.ts
407
- const INSTALL_ID_KEY = "layers_install_id";
408
- let AsyncStorage$1;
409
- try {
410
- AsyncStorage$1 = __require("@react-native-async-storage/async-storage").default;
411
- } catch (_e) {}
412
- let _pendingPromise = null;
413
- function getOrSetInstallId() {
414
- if (_pendingPromise) return _pendingPromise;
415
- _pendingPromise = (async () => {
416
- try {
417
- if (!AsyncStorage$1) {
418
- console.warn("[Layers] AsyncStorage not found. Using temporary install_id. Identity will not persist across restarts.");
419
- return generateUUID();
420
- }
421
- const existingId = await AsyncStorage$1.getItem(INSTALL_ID_KEY);
422
- if (existingId) return existingId;
423
- const newId = generateUUID();
424
- await AsyncStorage$1.setItem(INSTALL_ID_KEY, newId);
425
- return newId;
426
- } catch (error) {
427
- console.warn("[Layers] Failed to access storage for install_id", error);
428
- return generateUUID();
429
- }
430
- })();
431
- return _pendingPromise;
432
- }
433
- function generateUUID() {
434
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
435
- const r = Math.random() * 16 | 0;
436
- return (c === "x" ? r : r & 3 | 8).toString(16);
437
- });
438
- }
439
-
440
- //#endregion
441
- //#region src/storage/nativeQueueStorage.ts
442
- const STORAGE_KEY_PREFIX = "layers_queue_";
443
- let AsyncStorage;
444
- try {
445
- AsyncStorage = __require("@react-native-async-storage/async-storage").default;
446
- } catch (_e) {}
447
- const createMemoryQueueStorage = () => {
448
- let snapshot = null;
449
- return {
450
- async load() {
451
- return snapshot;
452
- },
453
- async save(nextSnapshot) {
454
- snapshot = nextSnapshot;
455
- },
456
- async clear() {
457
- snapshot = null;
458
- }
459
- };
460
- };
461
- function createReactNativeQueueStorage(appId) {
462
- if (!AsyncStorage) {
463
- console.warn("[Layers] AsyncStorage not found. Falling back to in-memory storage. Events will not persist across restarts.");
464
- return createMemoryQueueStorage();
465
- }
466
- const storageKey = `${STORAGE_KEY_PREFIX}${appId}`;
467
- return {
468
- async load() {
469
- try {
470
- const value = await AsyncStorage.getItem(storageKey);
471
- if (!value) return null;
472
- return JSON.parse(value);
473
- } catch (error) {
474
- console.warn("[Layers] Failed to load queue from AsyncStorage", error);
475
- return null;
476
- }
477
- },
478
- async save(snapshot) {
479
- try {
480
- await AsyncStorage.setItem(storageKey, JSON.stringify(snapshot));
481
- } catch (error) {
482
- console.warn("[Layers] Failed to persist queue to AsyncStorage", error);
483
- }
484
- },
485
- async clear() {
486
- try {
487
- await AsyncStorage.removeItem(storageKey);
488
- } catch (error) {
489
- console.warn("[Layers] Failed to clear queue storage", error);
490
- }
491
- }
492
- };
493
- }
494
-
495
- //#endregion
496
- //#region src/ExpoRouterIntegration.ts
497
- /**
498
- * Hook for tracking screen views with Expo Router.
499
- *
500
- * @param usePathname - The `usePathname` hook from `expo-router`.
501
- * @param useGlobalSearchParams - The `useGlobalSearchParams` hook from `expo-router`.
502
- */
503
- function useLayersExpoRouterTracking(usePathname, useGlobalSearchParams) {
504
- const pathname = usePathname();
505
- const params = useGlobalSearchParams();
506
- const paramsString = JSON.stringify(params);
507
- useEffect(() => {
508
- if (pathname) {
509
- const properties = {};
510
- Object.entries(params).forEach(([key, value]) => {
511
- if (Array.isArray(value)) properties[key] = value.join(",");
512
- else properties[key] = value;
513
- });
514
- Layers.screen(pathname, properties).catch((err) => {
515
- console.warn("[Layers] Failed to track screen view:", err);
516
- });
517
- }
518
- }, [pathname, paramsString]);
519
- }
520
- /**
521
- * Component for tracking screen views with Expo Router.
522
- * Render this in your root `_layout.tsx`.
523
- */
524
- function LayersExpoRouter({ usePathname, useGlobalSearchParams }) {
525
- useLayersExpoRouterTracking(usePathname, useGlobalSearchParams);
526
- return null;
527
- }
528
-
529
- //#endregion
530
- //#region src/integrations/Commerce.ts
531
- const Commerce = { trackPurchase: async (transaction) => {
532
- try {
533
- await Layers.track("purchase_success", {
534
- product_id: transaction.products.map((p) => p.productId).join(","),
535
- transaction_id: transaction.transactionId,
536
- store: transaction.store,
537
- revenue: transaction.revenue,
538
- currency: transaction.currency,
539
- quantity: transaction.products.reduce((acc, p) => acc + (p.quantity ?? 1), 0),
540
- items: transaction.products
541
- });
542
- } catch (e) {
543
- console.warn("[Layers] Failed to track purchase:", e);
544
- }
545
- } };
546
-
547
- //#endregion
548
- //#region src/integrations/RevenueCat.ts
549
- /**
550
- * Safe wrapper for RevenueCat integration.
551
- * Does not import 'react-native-purchases' to avoid runtime crashes.
552
- */
553
- const RevenueCat = {
554
- connect: (purchasesInstance) => {
555
- if (_isConnected) return;
556
- try {
557
- if (!purchasesInstance || typeof purchasesInstance.addCustomerInfoUpdateListener !== "function" || typeof purchasesInstance.getCustomerInfo !== "function") {
558
- console.warn("[Layers] RevenueCat.connect() was passed an invalid object. Expected the default export from \"react-native-purchases\".");
559
- return;
560
- }
561
- const purchases = purchasesInstance;
562
- purchases.addCustomerInfoUpdateListener((info) => {
563
- handleCustomerInfoUpdate(info, false);
564
- });
565
- purchases.getCustomerInfo().then((info) => handleCustomerInfoUpdate(info, true)).catch(() => {});
566
- _isConnected = true;
567
- console.log("[Layers] RevenueCat integration connected.");
568
- } catch (e) {
569
- console.warn("[Layers] Failed to connect RevenueCat:", e);
570
- }
571
- },
572
- trackPurchase: async (rcPackage) => {
573
- try {
574
- if (!rcPackage || !rcPackage.product) return;
575
- const { product } = rcPackage;
576
- const store = Platform.OS === "ios" ? "app_store" : Platform.OS === "android" ? "play_store" : "custom";
577
- await Layers.track("purchase_success", {
578
- product_id: product.identifier,
579
- price: product.price,
580
- currency: product.currencyCode,
581
- store,
582
- transaction_id: "",
583
- source: "revenuecat"
584
- });
585
- } catch (e) {}
586
- }
587
- };
588
- let _activeSubscriptionsSet = /* @__PURE__ */ new Set();
589
- let _isInitialized = false;
590
- let _isConnected = false;
591
- function handleCustomerInfoUpdate(info, isInitialLoad) {
592
- try {
593
- const currentSubscriptions = new Set(info.activeSubscriptions || []);
594
- if (isInitialLoad && _isInitialized) return;
595
- if (!isInitialLoad && _isInitialized) {
596
- for (const subId of currentSubscriptions) if (!_activeSubscriptionsSet.has(subId)) Layers.track("subscription_start", {
597
- product_id: subId,
598
- platform: "revenuecat"
599
- }).catch((err) => {
600
- console.warn("[Layers] Failed to track subscription start:", err);
601
- });
602
- }
603
- _activeSubscriptionsSet = currentSubscriptions;
604
- _isInitialized = true;
605
- const userProps = { is_subscriber: currentSubscriptions.size > 0 };
606
- if (info.originalAppUserId) userProps.revenuecat_original_app_user_id = info.originalAppUserId;
607
- Layers.setUserProperties(userProps).catch((err) => {
608
- console.warn("[Layers] Failed to sync user properties:", err);
609
- });
610
- } catch (e) {
611
- console.warn("[Layers] Error processing RevenueCat update:", e);
612
- }
613
- }
614
-
615
- //#endregion
616
- //#region src/integrations/Superwall.ts
617
- const Superwall = {
618
- trackPresentation: async (paywallInfo) => {
619
- try {
620
- if (!paywallInfo) return;
621
- await Layers.track("paywall_show", {
622
- paywall_id: paywallInfo.identifier,
623
- placement: paywallInfo.name || "unknown",
624
- ab_test: paywallInfo.experiment ? {
625
- id: paywallInfo.experiment.id,
626
- variant: paywallInfo.experiment.variantId
627
- } : void 0,
628
- url: paywallInfo.url
629
- });
630
- } catch (e) {}
631
- },
632
- trackDismiss: async (paywallInfo) => {
633
- try {
634
- if (!paywallInfo) return;
635
- await Layers.track("paywall_dismiss", {
636
- paywall_id: paywallInfo.identifier,
637
- reason: "user_close"
638
- });
639
- } catch (e) {}
640
- }
641
- };
642
-
643
- //#endregion
644
- //#region src/index.ts
645
- const SUPPORTED_NETWORKS = [
646
- "meta",
647
- "tiktok",
648
- "snap",
649
- "google"
650
- ];
651
- const DEFAULT_DEEP_LINK_CONFIG = {
652
- urlSchemes: [],
653
- universalLinkDomains: [],
654
- deferredDeepLinkTimeout: 0,
655
- attributionWindowDays: 0,
656
- trackOrganicLinks: false
657
- };
658
- const EMPTY_CONNECTOR_STATUS = {
659
- network: "meta",
660
- enabled: false,
661
- initialized: false,
662
- hasSDK: false,
663
- eventsSent: 0,
664
- errors: 0
665
- };
666
- const EMPTY_CONNECTOR_METRICS = {
667
- network: "meta",
668
- totalEvents: 0,
669
- successfulEvents: 0,
670
- failedEvents: 0
671
- };
672
- const EMPTY_DEEP_LINK_METRICS = {
673
- totalLinks: 0,
674
- uniqueLinks: 0,
675
- attributedInstalls: 0,
676
- attributedSessions: 0,
677
- deferredLinks: 0,
678
- sourceBreakdown: {},
679
- conversionRate: 0
680
- };
681
- const NOT_SUPPORTED_ATT_STATUS = "not_determined";
682
- const NOT_SUPPORTED_SKAN_METRICS = {
683
- isSupported: false,
684
- version: "4.0",
685
- currentValue: null,
686
- currentPreset: null,
687
- ruleCount: 0,
688
- evaluationCount: 0,
689
- attributionData: null,
690
- lastEvaluations: []
691
- };
692
- var LayersRN = class {
693
- client = null;
694
- isInitialized = false;
695
- deepLinkConfig = null;
696
- skanManager = null;
697
- async init(config) {
698
- const installId = await getOrSetInstallId();
699
- this.client = new LayersClient({
700
- ...config,
701
- queueStorage: createReactNativeQueueStorage(config.appId),
702
- queueOptions: {
703
- flushIntervalMs: 1e3,
704
- maxQueueSize: 50,
705
- maxItemAgeMs: 6e4,
706
- requestTimeoutMs: 1e4,
707
- maxRetries: 1,
708
- baseRetryDelayMs: 500,
709
- maxRetryDelayMs: 1e3,
710
- ...config.queueOptions ?? {}
711
- }
712
- });
713
- this.client.setDeviceInfo({
714
- platform: Platform.OS === "ios" ? "ios" : Platform.OS === "android" ? "android" : "react-native",
715
- os_version: typeof Platform.Version === "string" ? Platform.Version : String(Platform.Version),
716
- install_id: installId
717
- });
718
- await this.client.init();
719
- if (Platform.OS === "ios") await this.initializeSKAN();
720
- this.isInitialized = true;
721
- if (config.enableDebug) console.log("Layers initialized with SKAN support.");
722
- }
723
- /**
724
- * Initialize SKAN and apply config from server
725
- */
726
- async initializeSKAN() {
727
- try {
728
- this.skanManager = new SKANManager((data) => {
729
- if (this.client?.getConfig().enableDebug) console.log("[Layers SKAN] Conversion updated:", {
730
- event: data.event,
731
- previousValue: data.previousValue,
732
- newValue: data.newValue,
733
- rule: data.matchedRule?.description
734
- });
735
- });
736
- await this.skanManager.initialize();
737
- const remoteConfig = await this.getRemoteConfig();
738
- if (remoteConfig?.skan) await this.applySKANConfig(remoteConfig.skan);
739
- } catch (error) {
740
- console.warn("[Layers] SKAN initialization failed:", error);
741
- }
742
- }
743
- /**
744
- * Get remote config from client
745
- */
746
- async getRemoteConfig() {
747
- if (!this.client) return null;
748
- try {
749
- return this.client.remoteConfig ?? null;
750
- } catch {
751
- return null;
752
- }
753
- }
754
- /**
755
- * Apply SKAN configuration from server
756
- */
757
- async applySKANConfig(skanConfig) {
758
- if (!this.skanManager || !skanConfig.enabled) return;
759
- try {
760
- if (skanConfig.preset && [
761
- "subscriptions",
762
- "engagement",
763
- "iap"
764
- ].includes(skanConfig.preset)) {
765
- this.skanManager.setPreset(skanConfig.preset);
766
- console.log(`[Layers SKAN] Preset applied: ${skanConfig.preset}`);
767
- } else if (Array.isArray(skanConfig.customRules) && skanConfig.customRules.length > 0) {
768
- this.skanManager.setCustomRules(skanConfig.customRules);
769
- console.log(`[Layers SKAN] Custom rules applied: ${skanConfig.customRules.length} rules`);
770
- }
771
- } catch (error) {
772
- console.warn("[Layers] Failed to apply SKAN config:", error);
773
- }
774
- }
775
- getClient() {
776
- return this.client;
777
- }
778
- isReady() {
779
- return this.isInitialized;
780
- }
781
- async destroy() {
782
- if (this.client) {
783
- await this.client.flush();
784
- this.client = null;
785
- }
786
- this.isInitialized = false;
787
- }
788
- async track(eventName, properties = {}) {
789
- if (!this.client) throw new Error("Layers must be initialized before tracking events");
790
- const eventProperties = {
791
- platform: Platform.OS,
792
- ...properties
793
- };
794
- await this.client.track(eventName, eventProperties);
795
- if (Platform.OS === "ios" && this.skanManager) this.skanManager.processEvent(eventName, eventProperties).catch((error) => {
796
- if (this.client?.getConfig().enableDebug) console.warn("[Layers SKAN] Event processing failed:", error);
797
- });
798
- }
799
- async screen(screenName, properties = {}) {
800
- await this.track("screen_view", {
801
- screen_name: screenName,
802
- ...properties
803
- });
804
- }
805
- async setUserProperties(properties) {
806
- if (!this.client) throw new Error("Layers must be initialized before setting user properties");
807
- await this.client.setUserProperties(properties);
808
- }
809
- setAppUserId(appUserId) {
810
- if (!this.client) throw new Error("Layers must be initialized before setting app user ID");
811
- this.client.setAppUserId(appUserId);
812
- }
813
- clearAppUserId() {
814
- if (!this.client) throw new Error("Layers must be initialized before clearing app user ID");
815
- this.client.setAppUserId(void 0);
816
- }
817
- async setConsent(consent) {
818
- if (!this.client) throw new Error("Layers must be initialized before setting consent");
819
- await this.client.setConsent(consent);
820
- }
821
- async requestTracking(_options) {
822
- console.warn("Layers ATT support is disabled in simplified mode.");
823
- }
824
- debug = {
825
- showOverlay: (_options) => {
826
- console.warn("Debug overlay is not available in simplified mode.");
827
- },
828
- hideOverlay: () => {},
829
- isOverlayVisible: () => false,
830
- getATTStatus: async () => NOT_SUPPORTED_ATT_STATUS,
831
- getSKANMetrics: async () => {
832
- if (Platform.OS !== "ios" || !this.skanManager) return NOT_SUPPORTED_SKAN_METRICS;
833
- return this.skanManager.getSKANMetrics();
834
- },
835
- getDeepLinkMetrics: async () => EMPTY_DEEP_LINK_METRICS,
836
- getConnectorStatuses: async () => this.createConnectorStatusMap(),
837
- testConnectorConnection: async (_network) => false,
838
- flushAllEvents: async () => {
839
- if (this.client) await this.client.flush();
840
- return this.createZeroCountMap();
841
- }
842
- };
843
- connectors = {
844
- configure: async (_network, _config) => false,
845
- enable: async (_network) => false,
846
- disable: async (_network) => false,
847
- getStatus: async (network) => ({
848
- ...EMPTY_CONNECTOR_STATUS,
849
- network
850
- }),
851
- getAllStatuses: async () => this.createConnectorStatusMap(),
852
- getMetrics: async (network) => ({
853
- ...EMPTY_CONNECTOR_METRICS,
854
- network
855
- }),
856
- testConnection: async (_network) => false,
857
- flush: async () => this.createZeroCountMap()
858
- };
859
- deepLinks = {
860
- configure: async (config) => {
861
- this.deepLinkConfig = {
862
- ...DEFAULT_DEEP_LINK_CONFIG,
863
- ...this.deepLinkConfig ?? {},
864
- ...config
865
- };
866
- },
867
- addListener: (_listener) => {
868
- console.warn("Deep link listeners are not available in simplified mode.");
869
- return () => void 0;
870
- },
871
- getMetrics: async () => EMPTY_DEEP_LINK_METRICS,
872
- parseUrl: (url) => {
873
- try {
874
- const parsed = new URL(url);
875
- const params = {};
876
- parsed.searchParams.forEach((value, key) => {
877
- params[key] = value;
878
- });
879
- const data = {
880
- url,
881
- scheme: parsed.protocol.replace(":", ""),
882
- host: parsed.hostname,
883
- path: parsed.pathname,
884
- queryParams: params,
885
- timestamp: Date.now()
886
- };
887
- if (parsed.hash) data.fragment = parsed.hash.slice(1);
888
- return data;
889
- } catch {
890
- throw new Error(`Invalid deep link URL: ${url}`);
891
- }
892
- },
893
- clearAttribution: async () => {}
894
- };
895
- att = {
896
- request: async (_strategy) => {
897
- console.warn("ATT request is not supported in simplified mode.");
898
- return NOT_SUPPORTED_ATT_STATUS;
899
- },
900
- getStatus: async () => NOT_SUPPORTED_ATT_STATUS,
901
- isSupported: async () => false,
902
- setCustomPrompt: (_title, _message) => {
903
- console.warn("ATT custom prompts are not supported in simplified mode.");
904
- }
905
- };
906
- skan = {
907
- setPreset: async (preset) => {
908
- if (Platform.OS !== "ios") {
909
- console.warn("[Layers SKAN] Only supported on iOS");
910
- return;
911
- }
912
- if (!this.skanManager) {
913
- console.warn("[Layers SKAN] Not initialized");
914
- return;
915
- }
916
- this.skanManager.setPreset(preset);
917
- },
918
- setRules: async (rules) => {
919
- if (Platform.OS !== "ios") {
920
- console.warn("[Layers SKAN] Only supported on iOS");
921
- return;
922
- }
923
- if (!this.skanManager) {
924
- console.warn("[Layers SKAN] Not initialized");
925
- return;
926
- }
927
- this.skanManager.setCustomRules(rules);
928
- },
929
- getCurrentConversionValue: async () => {
930
- if (Platform.OS !== "ios" || !this.skanManager) return null;
931
- return this.skanManager.getCurrentValue();
932
- },
933
- getMetrics: async () => {
934
- if (Platform.OS !== "ios" || !this.skanManager) return NOT_SUPPORTED_SKAN_METRICS;
935
- return this.skanManager.getSKANMetrics();
936
- }
937
- };
938
- createConnectorStatusMap() {
939
- const statuses = {};
940
- for (const network of SUPPORTED_NETWORKS) statuses[network] = {
941
- ...EMPTY_CONNECTOR_STATUS,
942
- network
943
- };
944
- return statuses;
945
- }
946
- createZeroCountMap() {
947
- return {
948
- meta: 0,
949
- tiktok: 0,
950
- snap: 0,
951
- google: 0
952
- };
953
- }
954
- };
955
- const Layers = new LayersRN();
956
- var src_default = Layers;
957
- const DebugOverlay = (_props) => null;
958
-
959
- //#endregion
960
- export { Commerce, DebugOverlay, Layers, LayersExpoRouter, RevenueCat, Superwall, src_default as default, useLayersExpoRouterTracking };
961
- //# sourceMappingURL=index.js.map
5
+ export { LayersError, LayersReactNative, SKANManager, getATTStatus, getAdvertisingId, getOrSetInstallId, getVendorId, isATTAvailable, parseDeepLink, requestTrackingAuthorization, setupDeepLinkListener, useLayersExpoRouterTracking };