@layers/react-native 1.4.11 → 2.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.
@@ -1,772 +0,0 @@
1
- import { t as __require } from "./chunk-DmmLNhcN.mjs";
2
- import { a as requestTrackingAuthorization, n as getAdvertisingId, r as getVendorId } from "./att-B6KTrEU7.mjs";
3
- import { t as SKANManager } from "./skan-CBE6_mjp.mjs";
4
- import { FetchHttpClient, LayersCore, LayersError as LayersError$1, MemoryPersistence } from "@layers/core-wasm";
5
-
6
- //#region src/index.ts
7
- const SDK_VERSION = typeof __LAYERS_RN_VERSION__ !== "undefined" ? __LAYERS_RN_VERSION__ : "0.1.0";
8
- var LayersReactNative = class LayersReactNative {
9
- core;
10
- appUserId;
11
- isOnline = true;
12
- enableDebug;
13
- appStateSubscription = null;
14
- netInfoUnsubscribe = null;
15
- config;
16
- userIdLocked = false;
17
- errorListeners = /* @__PURE__ */ new Set();
18
- _skanManager = null;
19
- _lastSkanConfigStr = null;
20
- deepLinkUnsubscribe = null;
21
- _configPollTimer = null;
22
- static CONFIG_POLL_INTERVAL_MS = 3e5;
23
- _adServicesToken = null;
24
- _installReferrer = null;
25
- constructor(config) {
26
- this.enableDebug = config.enableDebug ?? false;
27
- this.appUserId = config.appUserId;
28
- this.config = config;
29
- const httpClient = new FetchHttpClient();
30
- this.core = LayersCore.init({
31
- config: {
32
- appId: config.appId,
33
- environment: config.environment,
34
- ...config.baseUrl != null && { baseUrl: config.baseUrl },
35
- ...config.enableDebug != null && { enableDebug: config.enableDebug },
36
- ...config.flushIntervalMs != null && { flushIntervalMs: config.flushIntervalMs },
37
- ...config.flushThreshold != null && { flushThreshold: config.flushThreshold },
38
- ...config.maxQueueSize != null && { maxQueueSize: config.maxQueueSize },
39
- sdkVersion: `react-native/${SDK_VERSION}`
40
- },
41
- httpClient,
42
- persistence: new MemoryPersistence()
43
- });
44
- if (this.appUserId) {
45
- this.core.identify(this.appUserId);
46
- this.userIdLocked = true;
47
- }
48
- }
49
- async init() {
50
- try {
51
- const persistence = await createAsyncStoragePersistence(this.config.appId);
52
- const httpClient = new FetchHttpClient();
53
- this.core.shutdown();
54
- this.core = LayersCore.init({
55
- config: {
56
- appId: this.config.appId,
57
- environment: this.config.environment,
58
- ...this.config.baseUrl != null && { baseUrl: this.config.baseUrl },
59
- ...this.config.enableDebug != null && { enableDebug: this.config.enableDebug },
60
- ...this.config.flushIntervalMs != null && { flushIntervalMs: this.config.flushIntervalMs },
61
- ...this.config.flushThreshold != null && { flushThreshold: this.config.flushThreshold },
62
- ...this.config.maxQueueSize != null && { maxQueueSize: this.config.maxQueueSize },
63
- sdkVersion: `react-native/${SDK_VERSION}`
64
- },
65
- httpClient,
66
- persistence
67
- });
68
- if (this.appUserId) this.core.identify(this.appUserId);
69
- } catch {}
70
- await this.initializeDeviceInfo();
71
- this.setupAppStateListener();
72
- this.setupNetInfoListener();
73
- await this.core.fetchRemoteConfig().catch(() => {});
74
- await this.configureSkanFromRemoteConfig();
75
- this.startConfigPolling();
76
- let clipboardData = null;
77
- try {
78
- const { Platform } = __require("react-native");
79
- if (Platform.OS === "ios") {
80
- let clipboardEnabled = false;
81
- try {
82
- const configJson = this.core.getRemoteConfigJson?.();
83
- if (configJson) clipboardEnabled = JSON.parse(configJson)?.clipboard_attribution_enabled === true;
84
- } catch {}
85
- if (clipboardEnabled) clipboardData = await readClipboardAttribution();
86
- }
87
- } catch {}
88
- if (this.config.autoTrackAppOpen !== false) {
89
- const appOpenProps = {};
90
- if (clipboardData) {
91
- appOpenProps.clipboard_attribution_url = clipboardData.clickUrl;
92
- appOpenProps.clipboard_click_id = clipboardData.clickId;
93
- }
94
- if (this._adServicesToken) appOpenProps.adservices_token = this._adServicesToken;
95
- if (this._installReferrer) {
96
- appOpenProps.install_referrer_url = this._installReferrer.referrerUrl;
97
- if (this._installReferrer.referrerClickTimestamp) appOpenProps.install_referrer_click_timestamp = this._installReferrer.referrerClickTimestamp;
98
- if (this._installReferrer.installBeginTimestamp) appOpenProps.install_referrer_install_timestamp = this._installReferrer.installBeginTimestamp;
99
- }
100
- this.track("app_open", appOpenProps);
101
- }
102
- if (this.config.autoTrackDeepLinks !== false) this.setupDeepLinkAutoTracking();
103
- }
104
- track(eventName, properties) {
105
- if (this.enableDebug) console.log(`[Layers] track("${eventName}", ${Object.keys(properties ?? {}).length} properties)`);
106
- try {
107
- this.core.track(eventName, properties, this.appUserId);
108
- if (this._skanManager) this._skanManager.processEvent(eventName, properties ?? {}).catch(() => {});
109
- } catch (e) {
110
- this.emitError(e);
111
- }
112
- }
113
- screen(screenName, properties) {
114
- if (this.enableDebug) console.log(`[Layers] screen("${screenName}", ${Object.keys(properties ?? {}).length} properties)`);
115
- try {
116
- this.core.screen(screenName, properties, this.appUserId);
117
- } catch (e) {
118
- this.emitError(e);
119
- }
120
- }
121
- async setUserProperties(properties) {
122
- this.core.setUserProperties(properties);
123
- }
124
- async setUserPropertiesOnce(properties) {
125
- this.core.setUserPropertiesOnce(properties);
126
- }
127
- async setConsent(consent) {
128
- this.core.setConsent(consent);
129
- }
130
- /**
131
- * Request App Tracking Transparency authorization (iOS only).
132
- * After the user responds, this method automatically:
133
- * - Collects IDFA if authorized
134
- * - Updates device info with IDFA and ATT status
135
- * - Sets advertising consent based on ATT result
136
- *
137
- * Returns the ATT status string.
138
- */
139
- async requestTrackingPermission() {
140
- let status;
141
- try {
142
- const ExpoTT = await import("./TrackingTransparency-DunpgkgS.mjs").catch(() => null);
143
- if (ExpoTT) {
144
- const { status: expoStatus } = await ExpoTT.requestTrackingPermissionsAsync();
145
- status = {
146
- granted: "authorized",
147
- denied: "denied",
148
- restricted: "restricted",
149
- undetermined: "not_determined"
150
- }[expoStatus] ?? "not_determined";
151
- } else status = await requestTrackingAuthorization();
152
- } catch {
153
- status = await requestTrackingAuthorization();
154
- }
155
- const updates = {
156
- ...this.core.getDeviceContext(),
157
- attStatus: status
158
- };
159
- if (status === "authorized") try {
160
- const idfa = await getAdvertisingId();
161
- if (idfa) updates.idfa = idfa;
162
- } catch {}
163
- this.core.setDeviceContext(updates);
164
- const advertisingAllowed = status === "authorized";
165
- this.core.setConsent({ advertising: advertisingAllowed });
166
- if (this.enableDebug) console.log(`[Layers] ATT status: ${status}, advertising consent: ${String(advertisingAllowed)}`);
167
- return status;
168
- }
169
- /**
170
- * Set the app user ID. Uses set-user-once semantics:
171
- * once set, subsequent calls are ignored until clearAppUserId() is called.
172
- */
173
- setAppUserId(appUserId) {
174
- if (this.enableDebug) console.log(`[Layers] setAppUserId("${appUserId}")`);
175
- if (this.userIdLocked && this.appUserId) {
176
- if (this.enableDebug) console.warn("[Layers] appUserId already set. Call clearAppUserId() first to change it.");
177
- return;
178
- }
179
- this.appUserId = appUserId;
180
- this.userIdLocked = true;
181
- this.core.identify(appUserId);
182
- }
183
- clearAppUserId() {
184
- this.appUserId = void 0;
185
- this.userIdLocked = false;
186
- }
187
- /**
188
- * Reset the SDK state: clears the user ID, unlocks set-user-once,
189
- * clears user properties, and starts a new session.
190
- *
191
- * After reset(), the SDK behaves as if no user has been identified.
192
- * A new anonymous session is started. Events tracked after reset()
193
- * will not carry the previous user's identity.
194
- */
195
- reset() {
196
- if (this.enableDebug) console.log("[Layers] reset()");
197
- this.appUserId = void 0;
198
- this.userIdLocked = false;
199
- try {
200
- this.core.setUserProperties({});
201
- } catch (e) {
202
- this.emitError(e);
203
- }
204
- try {
205
- this.core.startNewSession();
206
- } catch (e) {
207
- this.emitError(e);
208
- }
209
- }
210
- getAppUserId() {
211
- return this.appUserId;
212
- }
213
- getSessionId() {
214
- return this.core.getSessionId();
215
- }
216
- getConsentState() {
217
- return this.core.getConsentState();
218
- }
219
- setDeviceInfo(deviceInfo) {
220
- this.core.setDeviceContext(deviceInfo);
221
- }
222
- async flush() {
223
- try {
224
- await this.core.flushAsync();
225
- } catch (e) {
226
- this.emitError(e);
227
- this.core.flush();
228
- }
229
- }
230
- /**
231
- * Flush all queued events synchronously (blocking).
232
- *
233
- * Drains all batches from the queue and sends them via HTTP, awaiting
234
- * each batch before proceeding. Does not return until all batches have
235
- * been sent or failed.
236
- *
237
- * This is useful for AppState background transitions where the app may
238
- * be suspended shortly after the call returns.
239
- */
240
- async flushBlocking() {
241
- try {
242
- let depth = this.core.queueDepth();
243
- while (depth > 0) {
244
- await this.core.flushAsync();
245
- const newDepth = this.core.queueDepth();
246
- if (newDepth >= depth) break;
247
- depth = newDepth;
248
- }
249
- } catch (e) {
250
- this.emitError(e);
251
- }
252
- }
253
- /**
254
- * Register an error listener. Errors from track/screen/flush
255
- * that would otherwise be silently dropped are forwarded here.
256
- */
257
- on(event, listener) {
258
- if (event === "error") this.errorListeners.add(listener);
259
- return this;
260
- }
261
- /**
262
- * Remove a previously registered error listener.
263
- */
264
- off(event, listener) {
265
- if (event === "error") this.errorListeners.delete(listener);
266
- return this;
267
- }
268
- /**
269
- * Returns the AdServices attribution token (iOS only), or null if not
270
- * available. Collected automatically during init() on iOS 14.3+.
271
- * Does NOT require ATT consent.
272
- */
273
- getAdServicesToken() {
274
- return this._adServicesToken;
275
- }
276
- /**
277
- * Returns the Google Play install referrer data (Android only), or null
278
- * if not available. Collected automatically during init() on Android.
279
- */
280
- getInstallReferrer() {
281
- return this._installReferrer;
282
- }
283
- /**
284
- * Returns the auto-configured SKANManager instance, or null if SKAN was not
285
- * configured by the server's remote config.
286
- * On iOS, when remote config contains a `skan` section with `preset` or
287
- * `customRules`, the SDK automatically creates and configures a SKANManager.
288
- * Every `track()` call is automatically forwarded to SKAN rule evaluation.
289
- */
290
- getSkanManager() {
291
- return this._skanManager;
292
- }
293
- emitError(error) {
294
- const err = error instanceof Error ? error : new Error(String(error));
295
- for (const listener of this.errorListeners) try {
296
- listener(err);
297
- } catch {}
298
- if (this.enableDebug && this.errorListeners.size === 0) console.warn("[Layers]", err.message);
299
- }
300
- shutdown() {
301
- this.stopConfigPolling();
302
- if (this.appStateSubscription) {
303
- this.appStateSubscription.remove();
304
- this.appStateSubscription = null;
305
- }
306
- if (this.netInfoUnsubscribe) {
307
- this.netInfoUnsubscribe();
308
- this.netInfoUnsubscribe = null;
309
- }
310
- if (this.deepLinkUnsubscribe) {
311
- this.deepLinkUnsubscribe();
312
- this.deepLinkUnsubscribe = null;
313
- }
314
- this.core.shutdown();
315
- }
316
- _trackedDeepLinkUrls = /* @__PURE__ */ new Set();
317
- setupDeepLinkAutoTracking() {
318
- this.deepLinkUnsubscribe = setupDeepLinkListener((data) => {
319
- if (this._trackedDeepLinkUrls.has(data.url)) return;
320
- this._trackedDeepLinkUrls.add(data.url);
321
- setTimeout(() => this._trackedDeepLinkUrls.delete(data.url), 2e3);
322
- try {
323
- const properties = {
324
- ...data.queryParams,
325
- url: data.url,
326
- scheme: data.scheme,
327
- host: data.host,
328
- path: data.path
329
- };
330
- this.track("deep_link_opened", properties);
331
- if (this.enableDebug) console.log(`[Layers] auto-tracked deep_link_opened: ${data.url}`);
332
- } catch (e) {
333
- this.emitError(e);
334
- }
335
- });
336
- }
337
- async initializeDeviceInfo() {
338
- try {
339
- const { Platform, Dimensions, NativeModules } = __require("react-native");
340
- const window = Dimensions.get("window");
341
- const platform = Platform.OS === "ios" ? "ios" : Platform.OS === "android" ? "android" : "react-native";
342
- const osVersion = typeof Platform.Version === "string" ? Platform.Version : String(Platform.Version);
343
- let deviceModel;
344
- if (Platform.OS === "android") {
345
- const brand = Platform.constants?.Brand ?? "";
346
- const model = Platform.constants?.Model ?? "";
347
- deviceModel = brand && model ? `${brand} ${model}` : model || brand || "Android";
348
- } else if (Platform.OS === "ios") try {
349
- deviceModel = await NativeModules.LayersDeviceInfo?.getModelIdentifier() || "iPhone";
350
- } catch {
351
- deviceModel = "iPhone";
352
- }
353
- else deviceModel = "unknown";
354
- let appVersion;
355
- try {
356
- appVersion = await getAppVersion(Platform, NativeModules);
357
- } catch {}
358
- const context = {
359
- platform,
360
- osVersion,
361
- deviceModel,
362
- locale: getLocale(),
363
- screenSize: `${Math.round(window.width)}x${Math.round(window.height)}`,
364
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
365
- ...appVersion != null && { appVersion }
366
- };
367
- if (Platform.OS === "ios") try {
368
- const idfv = await getVendorId();
369
- if (idfv) context.idfv = idfv;
370
- } catch {}
371
- if (Platform.OS === "android") try {
372
- const gaid = await getGoogleAdvertisingId();
373
- if (gaid) context.idfa = gaid.id;
374
- if (gaid && gaid.isLimitAdTrackingEnabled != null) context.attStatus = gaid.isLimitAdTrackingEnabled ? "denied" : "authorized";
375
- } catch {}
376
- try {
377
- const installId = await getOrSetInstallId();
378
- if (installId) context.installId = installId;
379
- } catch {}
380
- this.core.setDeviceContext(context);
381
- } catch {
382
- const context = {
383
- platform: "react-native",
384
- osVersion: "unknown",
385
- deviceModel: "unknown",
386
- locale: "en-US"
387
- };
388
- try {
389
- const installId = await getOrSetInstallId();
390
- if (installId) context.installId = installId;
391
- } catch {}
392
- this.core.setDeviceContext(context);
393
- }
394
- try {
395
- const { Platform } = __require("react-native");
396
- if (Platform.OS === "ios") try {
397
- const token = await getAdServicesToken();
398
- if (token) this._adServicesToken = token;
399
- } catch {}
400
- if (Platform.OS === "android") try {
401
- const referrer = await getInstallReferrer();
402
- if (referrer) this._installReferrer = referrer;
403
- } catch {}
404
- } catch {}
405
- }
406
- setupAppStateListener() {
407
- try {
408
- const { AppState } = __require("react-native");
409
- this.appStateSubscription = AppState.addEventListener("change", (nextAppState) => {
410
- if (nextAppState === "background" || nextAppState === "inactive") this.core.flush();
411
- if (nextAppState === "active" && this.isOnline) this.core.flushAsync().catch(() => {});
412
- });
413
- } catch {}
414
- }
415
- async configureSkanFromRemoteConfig() {
416
- try {
417
- const { Platform } = __require("react-native");
418
- if (Platform.OS !== "ios") return;
419
- } catch {}
420
- try {
421
- const configJson = this.core.getRemoteConfigJson?.();
422
- if (!configJson) return;
423
- const skanConfig = JSON.parse(configJson)?.skan;
424
- if (!skanConfig || skanConfig.enabled === false) {
425
- this._skanManager = null;
426
- this._lastSkanConfigStr = null;
427
- return;
428
- }
429
- const skanConfigStr = JSON.stringify(skanConfig);
430
- if (this._skanManager && this._lastSkanConfigStr === skanConfigStr) return;
431
- const manager = new SKANManager();
432
- if (skanConfig.preset) manager.setPreset(skanConfig.preset);
433
- else if (skanConfig.customRules && Array.isArray(skanConfig.customRules)) manager.setCustomRules(skanConfig.customRules);
434
- else return;
435
- await manager.initialize();
436
- this._skanManager = manager;
437
- this._lastSkanConfigStr = skanConfigStr;
438
- if (this.enableDebug) {
439
- const metrics = manager.getMetrics();
440
- console.log(`[Layers] SKAN auto-configured from remote config: preset=${metrics.currentPreset}, rules=${String(metrics.ruleCount)}`);
441
- }
442
- } catch {}
443
- }
444
- startConfigPolling() {
445
- this.stopConfigPolling();
446
- this._configPollTimer = setInterval(() => {
447
- this.pollRemoteConfig();
448
- }, LayersReactNative.CONFIG_POLL_INTERVAL_MS);
449
- }
450
- stopConfigPolling() {
451
- if (this._configPollTimer) {
452
- clearInterval(this._configPollTimer);
453
- this._configPollTimer = null;
454
- }
455
- }
456
- async pollRemoteConfig() {
457
- try {
458
- await this.core.fetchRemoteConfig();
459
- await this.configureSkanFromRemoteConfig();
460
- if (this.enableDebug) console.log("[Layers] Remote config updated (poll)");
461
- } catch {}
462
- }
463
- setupNetInfoListener() {
464
- try {
465
- this.netInfoUnsubscribe = __require("@react-native-community/netinfo").addEventListener((state) => {
466
- const wasOffline = !this.isOnline;
467
- this.isOnline = state.isConnected !== false;
468
- if (wasOffline && this.isOnline) this.core.flushAsync().catch(() => {});
469
- });
470
- } catch {}
471
- }
472
- };
473
- async function createAsyncStoragePersistence(appId) {
474
- const prefix = `layers_sdk_${appId}_`;
475
- const memoryStore = /* @__PURE__ */ new Map();
476
- try {
477
- const AsyncStorage = await loadAsyncStorage();
478
- if (AsyncStorage) {
479
- const layersKeys = (await AsyncStorage.getAllKeys()).filter((k) => k.startsWith(prefix));
480
- if (layersKeys.length > 0) {
481
- const pairs = await AsyncStorage.multiGet(layersKeys);
482
- for (const [key, value] of pairs) if (value) {
483
- const shortKey = key.slice(prefix.length);
484
- memoryStore.set(shortKey, base64Decode(value));
485
- }
486
- }
487
- }
488
- } catch {}
489
- return {
490
- write(key, data) {
491
- memoryStore.set(key, new Uint8Array(data));
492
- writeToAsyncStorage(prefix + key, data);
493
- },
494
- read(key) {
495
- return memoryStore.get(key) ?? null;
496
- },
497
- delete(key) {
498
- memoryStore.delete(key);
499
- deleteFromAsyncStorage(prefix + key);
500
- },
501
- listKeys(keyPrefix) {
502
- const keys = [];
503
- for (const k of memoryStore.keys()) if (k.startsWith(keyPrefix)) keys.push(k);
504
- keys.sort();
505
- return keys;
506
- }
507
- };
508
- }
509
- const B64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
510
- const B64_LOOKUP = new Uint8Array(128);
511
- for (let _i = 0; _i < 64; _i += 1) B64_LOOKUP[B64_CHARS.charCodeAt(_i)] = _i;
512
- function base64Decode(str) {
513
- const lookup = B64_LOOKUP;
514
- let len = str.length;
515
- if (str[len - 1] === "=") len -= 1;
516
- if (str[len - 1] === "=") len -= 1;
517
- const bytes = new Uint8Array(Math.floor(len * 3 / 4));
518
- let p = 0;
519
- for (let i = 0; i < len; i += 4) {
520
- const b0 = lookup[str.charCodeAt(i)];
521
- const b1 = lookup[str.charCodeAt(i + 1)];
522
- const b2 = i + 2 < len ? lookup[str.charCodeAt(i + 2)] : 0;
523
- const b3 = i + 3 < len ? lookup[str.charCodeAt(i + 3)] : 0;
524
- bytes[p] = b0 << 2 | b1 >> 4;
525
- p += 1;
526
- if (i + 2 < len) {
527
- bytes[p] = (b1 & 15) << 4 | b2 >> 2;
528
- p += 1;
529
- }
530
- if (i + 3 < len) {
531
- bytes[p] = (b2 & 3) << 6 | b3;
532
- p += 1;
533
- }
534
- }
535
- return bytes;
536
- }
537
- function base64Encode(bytes) {
538
- let result = "";
539
- const len = bytes.length;
540
- for (let i = 0; i < len; i += 3) {
541
- const b0 = bytes[i];
542
- const b1 = i + 1 < len ? bytes[i + 1] : 0;
543
- const b2 = i + 2 < len ? bytes[i + 2] : 0;
544
- result += B64_CHARS[b0 >> 2];
545
- result += B64_CHARS[(b0 & 3) << 4 | b1 >> 4];
546
- result += i + 1 < len ? B64_CHARS[(b1 & 15) << 2 | b2 >> 6] : "=";
547
- result += i + 2 < len ? B64_CHARS[b2 & 63] : "=";
548
- }
549
- return result;
550
- }
551
- async function writeToAsyncStorage(key, data) {
552
- try {
553
- const AsyncStorage = await loadAsyncStorage();
554
- if (!AsyncStorage) return;
555
- const encoded = base64Encode(data);
556
- await AsyncStorage.setItem(key, encoded);
557
- } catch {}
558
- }
559
- async function deleteFromAsyncStorage(key) {
560
- try {
561
- const AsyncStorage = await loadAsyncStorage();
562
- if (!AsyncStorage) return;
563
- await AsyncStorage.removeItem(key);
564
- } catch {}
565
- }
566
- let _asyncStorage = void 0;
567
- let _asyncStoragePromise = null;
568
- async function loadAsyncStorage() {
569
- if (_asyncStorage) return _asyncStorage;
570
- if (!_asyncStoragePromise) _asyncStoragePromise = import("@react-native-async-storage/async-storage").then((mod) => {
571
- _asyncStorage = mod.default ?? mod;
572
- return _asyncStorage;
573
- }).catch(() => null);
574
- return _asyncStoragePromise;
575
- }
576
- function getLocale() {
577
- try {
578
- const { Platform, NativeModules } = __require("react-native");
579
- if (Platform.OS === "ios") return NativeModules.SettingsManager?.settings?.AppleLocale ?? NativeModules.SettingsManager?.settings?.AppleLanguages?.[0] ?? "en-US";
580
- if (Platform.OS === "android") return NativeModules.I18nManager?.localeIdentifier ?? "en-US";
581
- } catch {}
582
- return "en-US";
583
- }
584
- const INSTALL_ID_KEY = "layers_install_id";
585
- async function getOrSetInstallId() {
586
- try {
587
- const AsyncStorage = await loadAsyncStorage();
588
- if (!AsyncStorage) return generateUUID();
589
- const existing = await AsyncStorage.getItem(INSTALL_ID_KEY);
590
- if (existing) return existing;
591
- const newId = generateUUID();
592
- await AsyncStorage.setItem(INSTALL_ID_KEY, newId);
593
- return newId;
594
- } catch {
595
- return generateUUID();
596
- }
597
- }
598
- function generateUUID() {
599
- if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID();
600
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
601
- const r = Math.random() * 16 | 0;
602
- return (c === "x" ? r : r & 3 | 8).toString(16);
603
- });
604
- }
605
- const CLIPBOARD_CHECKED_KEY = "@layers/clipboard_checked";
606
- async function readClipboardAttribution() {
607
- try {
608
- const { Platform } = __require("react-native");
609
- if (Platform.OS !== "ios") return null;
610
- } catch {
611
- return null;
612
- }
613
- try {
614
- const AS = await loadAsyncStorage();
615
- if (AS) {
616
- if (await AS.getItem(CLIPBOARD_CHECKED_KEY) === "true") return null;
617
- }
618
- } catch {}
619
- let text = null;
620
- try {
621
- const Clipboard = await import("@react-native-clipboard/clipboard").then((m) => m.default).catch(() => null);
622
- if (Clipboard) text = await Clipboard.getString();
623
- else {
624
- const { Clipboard: RNClipboard } = __require("react-native");
625
- if (RNClipboard) text = await RNClipboard.getString();
626
- }
627
- } catch {}
628
- try {
629
- const AS = await loadAsyncStorage();
630
- if (AS) await AS.setItem(CLIPBOARD_CHECKED_KEY, "true");
631
- } catch {}
632
- if (!text) return null;
633
- const match = text.match(/https?:\/\/(in\.layers\.com|link\.layers\.com)\/c\/([^?\s]+)/);
634
- if (!match) return null;
635
- return {
636
- clickUrl: text,
637
- clickId: match[2]
638
- };
639
- }
640
- /**
641
- * Attempt to read the host app version from platform-specific APIs.
642
- * On Android, reads from PackageInfo via Platform.constants or a native module.
643
- * On iOS, reads from the LayersDeviceInfo native module which can access the Info.plist.
644
- */
645
- async function getAppVersion(Platform, NativeModules) {
646
- try {
647
- if (Platform.OS === "android") {
648
- const mod = NativeModules.LayersDeviceInfo;
649
- if (mod?.getAppVersion) {
650
- const version = await mod.getAppVersion();
651
- if (version) return version;
652
- }
653
- }
654
- if (Platform.OS === "ios") {
655
- const mod = NativeModules.LayersDeviceInfo;
656
- if (mod?.getAppVersion) {
657
- const version = await mod.getAppVersion();
658
- if (version) return version;
659
- }
660
- }
661
- } catch {}
662
- }
663
- /**
664
- * Fetch the Google Advertising ID (GAID) on Android via NativeModules.
665
- * Returns null on iOS or when the native module is not available.
666
- */
667
- async function getGoogleAdvertisingId() {
668
- try {
669
- const { NativeModules, Platform } = __require("react-native");
670
- if (Platform.OS !== "android") return null;
671
- const mod = NativeModules.LayersAdvertisingId;
672
- if (!mod?.getAdvertisingInfo) return null;
673
- const info = await mod.getAdvertisingInfo();
674
- if (!info || !info.id || info.id === "00000000-0000-0000-0000-000000000000") return null;
675
- return info;
676
- } catch {
677
- return null;
678
- }
679
- }
680
- /**
681
- * Request the AdServices attribution token on iOS 14.3+.
682
- * Uses the LayersAdServices native module which calls AAAttribution.attributionToken().
683
- * Does NOT require ATT consent.
684
- * Returns null on Android or when the native module is not available.
685
- */
686
- async function getAdServicesToken() {
687
- try {
688
- const { NativeModules, Platform } = __require("react-native");
689
- if (Platform.OS !== "ios") return null;
690
- const mod = NativeModules.LayersAdServices;
691
- if (!mod?.getAttributionToken) return null;
692
- return await mod.getAttributionToken();
693
- } catch {
694
- return null;
695
- }
696
- }
697
- /**
698
- * Fetch the Google Play install referrer on Android via NativeModules.
699
- * Requires the `com.android.installreferrer` library on the native side.
700
- * Returns null on iOS or when the native module is not available.
701
- */
702
- async function getInstallReferrer() {
703
- try {
704
- const { NativeModules, Platform } = __require("react-native");
705
- if (Platform.OS !== "android") return null;
706
- const mod = NativeModules.LayersInstallReferrer;
707
- if (!mod?.getInstallReferrer) return null;
708
- const data = await mod.getInstallReferrer();
709
- if (!data || !data.referrerUrl) return null;
710
- return data;
711
- } catch {
712
- return null;
713
- }
714
- }
715
- function setupDeepLinkListener(onDeepLink) {
716
- try {
717
- const { Linking } = __require("react-native");
718
- const handler = (event) => {
719
- const parsed = parseDeepLink(event.url);
720
- if (parsed) onDeepLink(parsed);
721
- };
722
- const subscription = Linking.addEventListener("url", handler);
723
- Linking.getInitialURL().then((url) => {
724
- if (url) {
725
- const parsed = parseDeepLink(url);
726
- if (parsed) onDeepLink(parsed);
727
- }
728
- });
729
- return () => {
730
- if (subscription?.remove) subscription.remove();
731
- };
732
- } catch {
733
- return () => {};
734
- }
735
- }
736
- function parseDeepLink(url) {
737
- try {
738
- const parsed = new URL(url);
739
- const params = {};
740
- parsed.searchParams.forEach((value, key) => {
741
- params[key] = value;
742
- });
743
- return {
744
- url,
745
- scheme: parsed.protocol.replace(":", ""),
746
- host: parsed.hostname,
747
- path: parsed.pathname,
748
- queryParams: params,
749
- timestamp: Date.now()
750
- };
751
- } catch {
752
- return null;
753
- }
754
- }
755
- function useLayersExpoRouterTracking(layersInstance, usePathname, useGlobalSearchParams) {
756
- const { useEffect } = __require("react");
757
- const pathname = usePathname();
758
- const params = useGlobalSearchParams();
759
- useEffect(() => {
760
- if (pathname) {
761
- const properties = {};
762
- Object.entries(params).forEach(([key, value]) => {
763
- properties[key] = Array.isArray(value) ? value.join(",") : value;
764
- });
765
- layersInstance.screen(pathname, properties);
766
- }
767
- }, [pathname, JSON.stringify(params)]);
768
- }
769
-
770
- //#endregion
771
- export { getInstallReferrer as a, readClipboardAttribution as c, getGoogleAdvertisingId as i, setupDeepLinkListener as l, LayersReactNative as n, getOrSetInstallId as o, getAdServicesToken as r, parseDeepLink as s, LayersError$1 as t, useLayersExpoRouterTracking as u };
772
- //# sourceMappingURL=src-DFnL34cK.mjs.map