@attribra/react-native 0.0.0-stage → 2.9.7

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.
@@ -0,0 +1,2109 @@
1
+ // Metro provides these at runtime; declared so the SDK type-checks without @types/node or RN globals.
2
+ declare const require: (moduleId: string) => unknown
3
+ declare const __DEV__: boolean | undefined
4
+
5
+ export type AurionPlatform = 'android' | 'ios' | 'web' | 'unknown'
6
+
7
+ export type AurionAttribution = {
8
+ campaign?: string
9
+ channel?: string
10
+ provider?: string
11
+ provider_account_id?: string
12
+ campaign_id?: string
13
+ ad_group_id?: string
14
+ ad_group_name?: string
15
+ ad_id?: string
16
+ ad_name?: string
17
+ creative_id?: string
18
+ click_id?: string
19
+ /** Google's iPhone click ids (used instead of gclid when the user did not allow tracking). */
20
+ gbraid?: string
21
+ wbraid?: string
22
+ }
23
+
24
+ export type AurionConfig = {
25
+ apiKey: string
26
+ /** e.g. http://localhost:8000/api or https://signal.example.com/api */
27
+ baseUrl?: string
28
+ /** Default true */
29
+ consent?: boolean
30
+ /** Overrides default source "react_native" */
31
+ source?: string
32
+ /**
33
+ * Device OS. Auto-detected from React Native Platform when omitted.
34
+ * android | ios | web | unknown
35
+ */
36
+ platform?: AurionPlatform
37
+ /** First-touch campaign (install / click). Stored and attached automatically. */
38
+ campaign?: string
39
+ channel?: string
40
+ /**
41
+ * Default true. Sends app_install once per device after deep-link attribution
42
+ * is captured. Set false only if you call flushInstall() yourself.
43
+ */
44
+ autoInstall?: boolean
45
+ /**
46
+ * Default true. Automatically reads Linking.getInitialURL() and listens for
47
+ * future deep links so campaign_id / utm_* are applied without app code.
48
+ */
49
+ autoCaptureDeepLinks?: boolean
50
+ /**
51
+ * Milliseconds to wait for a late Android/iOS deep-link url event before
52
+ * sending app_install. Default 3000. Set 0 to skip the wait.
53
+ */
54
+ deepLinkGraceMs?: number
55
+ /**
56
+ * Days to keep a stored campaign for later track() calls. Default 30.
57
+ * Set 0 to keep forever.
58
+ */
59
+ attributionWindowDays?: number
60
+ /**
61
+ * When true, reads the clipboard for a campaign URL if no deep link was captured.
62
+ * On iOS this defaults to on (short links copy an install payload before the App Store);
63
+ * iOS may show a paste permission banner. Android defaults off (Play referrer is used instead).
64
+ */
65
+ readClipboard?: boolean
66
+ /**
67
+ * Called whenever a campaign deep link is captured (launch or warm start).
68
+ * Use for a toast or analytics UI — optional.
69
+ */
70
+ onAttribution?: (attribution: AurionAttribution) => void
71
+ /**
72
+ * Called when an installed device opens a different paid campaign link and
73
+ * the SDK sends a reattributed event. Optional.
74
+ */
75
+ onReattributed?: (next: AurionAttribution, previous: AurionAttribution) => void
76
+ /**
77
+ * Default true. Requests location permission once and attaches the last GPS
78
+ * fix (latitude / longitude / accuracy) to every event when available.
79
+ */
80
+ collectLocation?: boolean
81
+ /**
82
+ * Default true. Sends open_app when the app launches (after install) or
83
+ * returns to the foreground from background.
84
+ */
85
+ autoOpenApp?: boolean
86
+ appVersion?: string
87
+ }
88
+
89
+ export type TrackProperties = {
90
+ channel?: string
91
+ campaign?: string
92
+ value?: string
93
+ city?: string
94
+ latitude?: number
95
+ longitude?: number
96
+ location_accuracy?: number
97
+ consent?: boolean
98
+ timestamp?: string
99
+ platform?: AurionPlatform
100
+ properties?: Record<string, unknown>
101
+ attribution?: AurionAttribution
102
+ provider?: string
103
+ provider_account_id?: string
104
+ campaign_id?: string
105
+ ad_group_id?: string
106
+ ad_group_name?: string
107
+ ad_id?: string
108
+ ad_name?: string
109
+ creative_id?: string
110
+ click_id?: string
111
+ [key: string]: unknown
112
+ }
113
+
114
+ export type TrackEventInput = {
115
+ event: string
116
+ source?: string
117
+ platform?: AurionPlatform
118
+ channel?: string
119
+ campaign?: string
120
+ value?: string
121
+ city?: string
122
+ latitude?: number
123
+ longitude?: number
124
+ location_accuracy?: number
125
+ user_id?: string
126
+ consent?: boolean
127
+ timestamp?: string
128
+ properties?: Record<string, unknown>
129
+ event_id?: string
130
+ installation_id?: string
131
+ session_id?: string
132
+ sdk_name?: string
133
+ sdk_version?: string
134
+ app_version?: string
135
+ provider?: string
136
+ provider_account_id?: string
137
+ campaign_id?: string
138
+ ad_group_id?: string
139
+ ad_group_name?: string
140
+ ad_id?: string
141
+ ad_name?: string
142
+ creative_id?: string
143
+ click_id?: string
144
+ }
145
+
146
+ const EVENT_RE = /^[a-z][a-z0-9_]*$/
147
+ const STORE_CAMPAIGN = 'asg_campaign'
148
+ const STORE_CHANNEL = 'asg_channel'
149
+ const STORE_INSTALL = 'asg_install_sent'
150
+ const STORE_MATCHED = 'asg_install_matched'
151
+ const STORE_INSTALLATION_ID = 'asg_installation_id'
152
+ const STORE_ATTRIBUTION = 'asg_attribution'
153
+ const STORE_PENDING_URL = 'asg_pending_attribution_url'
154
+ const STORE_ATTRIBUTION_AT = 'asg_attribution_at'
155
+ const STORE_LOCATION = 'asg_location'
156
+ const STORE_EVENT_QUEUE = 'asg_event_queue'
157
+ const SDK_VERSION = '2.9.7'
158
+ let cachedGaid: string | null = null
159
+ const DEFAULT_DEEP_LINK_GRACE_MS = 3000
160
+ const DEFAULT_ATTRIBUTION_WINDOW_DAYS = 30
161
+ const DEEP_LINK_POLL_MS = 250
162
+ const OPEN_APP_DEBOUNCE_MS = 2000
163
+ const MAX_EVENT_QUEUE = 100
164
+ const STORAGE_KEYS = [
165
+ STORE_CAMPAIGN,
166
+ STORE_CHANNEL,
167
+ STORE_INSTALL,
168
+ STORE_INSTALLATION_ID,
169
+ STORE_ATTRIBUTION,
170
+ STORE_PENDING_URL,
171
+ STORE_ATTRIBUTION_AT,
172
+ STORE_LOCATION,
173
+ STORE_EVENT_QUEUE,
174
+ ] as const
175
+
176
+ type QueuedEvent = {
177
+ id: string
178
+ path: '/v1/events' | '/v1/events/batch'
179
+ body: unknown
180
+ queued_at: string
181
+ }
182
+
183
+ type LocationFix = {
184
+ latitude: number
185
+ longitude: number
186
+ accuracy?: number
187
+ }
188
+
189
+ type InternalConfig = {
190
+ apiKey: string
191
+ baseUrl: string
192
+ consent: boolean
193
+ source: string
194
+ platform: AurionPlatform
195
+ campaign?: string
196
+ channel?: string
197
+ attribution: AurionAttribution
198
+ installationId: string
199
+ sessionId: string
200
+ appVersion?: string
201
+ attributionWindowDays: number
202
+ readClipboard: boolean
203
+ collectLocation: boolean
204
+ autoOpenApp: boolean
205
+ onAttribution?: (attribution: AurionAttribution) => void
206
+ onReattributed?: (next: AurionAttribution, previous: AurionAttribution) => void
207
+ }
208
+
209
+ type AppStateLike = {
210
+ currentState: string
211
+ addEventListener: (
212
+ type: 'change',
213
+ handler: (nextAppState: string) => void,
214
+ ) => { remove: () => void } | void
215
+ }
216
+
217
+ type AsyncStorageLike = {
218
+ multiGet: (keys: readonly string[]) => Promise<readonly [string, string | null][]>
219
+ getItem: (key: string) => Promise<string | null>
220
+ setItem: (key: string, value: string) => Promise<void>
221
+ removeItem: (key: string) => Promise<void>
222
+ }
223
+
224
+ type LinkingLike = {
225
+ getInitialURL: () => Promise<string | null>
226
+ addEventListener: (
227
+ event: 'url',
228
+ handler: (event: { url: string }) => void,
229
+ ) => { remove: () => void } | void
230
+ }
231
+
232
+ let config: InternalConfig | null = null
233
+ let installSent = false
234
+ let readyPromise: Promise<void> = Promise.resolve()
235
+ let installPromise: Promise<void> = Promise.resolve()
236
+ let reattributedPromise: Promise<void> = Promise.resolve()
237
+ /** In-flight deep-link / short-link attribution work. open_app waits on this so it does not beat resolve. */
238
+ let attributionApplyPromise: Promise<void> = Promise.resolve()
239
+ /** Android returns the first launch URL from getInitialURL() forever — apply that URL only once per process. */
240
+ let consumedInitialUrl: string | null = null
241
+ let openAppPromise: Promise<void> = Promise.resolve()
242
+ let linkingSubscription: { remove: () => void } | null = null
243
+ let appStateSubscription: { remove: () => void } | null = null
244
+ let lastAppState = 'active'
245
+ let lastOpenAppAt = 0
246
+ const memoryStore: Record<string, string> = {}
247
+ const pendingUrls: string[] = []
248
+ let lastNotifiedAttributionKey = ''
249
+ let cachedLocation: LocationFix | null = null
250
+ let eventQueueFlushPromise: Promise<{ flushed: number; remaining: number }> | null = null
251
+ let networkUnsubscribe: (() => void) | null = null
252
+
253
+ /** Detect android / ios / web without requiring Platform import at module load. */
254
+ export function detectPlatform(): AurionPlatform {
255
+ try {
256
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
257
+ const { Platform } = require('react-native') as { Platform: { OS: string } }
258
+ if (Platform.OS === 'android') return 'android'
259
+ if (Platform.OS === 'ios') return 'ios'
260
+ if (Platform.OS === 'web') return 'web'
261
+ } catch {
262
+ /* not running in RN */
263
+ }
264
+ const browser = globalThis as {
265
+ navigator?: { userAgent?: string }
266
+ window?: unknown
267
+ }
268
+ const userAgent = browser.navigator?.userAgent ?? ''
269
+ if (/android/i.test(userAgent)) return 'android'
270
+ if (/iPhone|iPad|iPod/i.test(userAgent)) return 'ios'
271
+ if (browser.window !== undefined) return 'web'
272
+ return 'unknown'
273
+ }
274
+
275
+ function getAsyncStorage(): AsyncStorageLike | null {
276
+ try {
277
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
278
+ const mod = require('@react-native-async-storage/async-storage') as {
279
+ default?: AsyncStorageLike
280
+ } & AsyncStorageLike
281
+ return mod.default ?? mod
282
+ } catch {
283
+ return null
284
+ }
285
+ }
286
+
287
+ type GeolocationLike = {
288
+ requestAuthorization?: (level?: string) => void | Promise<void>
289
+ getCurrentPosition: (
290
+ success: (position: {
291
+ coords: { latitude: number; longitude: number; accuracy?: number }
292
+ }) => void,
293
+ error?: (error: unknown) => void,
294
+ options?: {
295
+ enableHighAccuracy?: boolean
296
+ timeout?: number
297
+ maximumAge?: number
298
+ },
299
+ ) => void
300
+ }
301
+
302
+ function getGeolocation(): GeolocationLike | null {
303
+ try {
304
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
305
+ const mod = require('@react-native-community/geolocation') as {
306
+ default?: GeolocationLike
307
+ } & GeolocationLike
308
+ return mod.default ?? mod
309
+ } catch {
310
+ return null
311
+ }
312
+ }
313
+
314
+ async function requestLocationPermission(): Promise<boolean> {
315
+ try {
316
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
317
+ const rn = require('react-native') as {
318
+ Platform?: { OS: string }
319
+ PermissionsAndroid?: {
320
+ PERMISSIONS: { ACCESS_FINE_LOCATION: string; ACCESS_COARSE_LOCATION: string }
321
+ RESULTS: { GRANTED: string }
322
+ request: (permission: string) => Promise<string>
323
+ }
324
+ }
325
+ if (rn.Platform?.OS === 'android' && rn.PermissionsAndroid) {
326
+ const fine = await rn.PermissionsAndroid.request(
327
+ rn.PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
328
+ )
329
+ if (fine === rn.PermissionsAndroid.RESULTS.GRANTED) {
330
+ return true
331
+ }
332
+ const coarse = await rn.PermissionsAndroid.request(
333
+ rn.PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
334
+ )
335
+ return coarse === rn.PermissionsAndroid.RESULTS.GRANTED
336
+ }
337
+ const geo = getGeolocation()
338
+ if (geo?.requestAuthorization) {
339
+ await geo.requestAuthorization('whenInUse')
340
+ }
341
+ return true
342
+ } catch {
343
+ return false
344
+ }
345
+ }
346
+
347
+ function readStoredLocation(): LocationFix | null {
348
+ const raw = storageGet(STORE_LOCATION)
349
+ if (!raw) return null
350
+ try {
351
+ const parsed = JSON.parse(raw) as LocationFix
352
+ if (
353
+ typeof parsed.latitude === 'number' &&
354
+ typeof parsed.longitude === 'number' &&
355
+ Number.isFinite(parsed.latitude) &&
356
+ Number.isFinite(parsed.longitude)
357
+ ) {
358
+ return parsed
359
+ }
360
+ } catch {
361
+ /* ignore */
362
+ }
363
+ return null
364
+ }
365
+
366
+ function rememberLocation(fix: LocationFix) {
367
+ cachedLocation = fix
368
+ storageSet(STORE_LOCATION, JSON.stringify(fix))
369
+ }
370
+
371
+ /** Non-blocking: request permission once and refresh the last known GPS fix. */
372
+ async function refreshLocationIfNeeded(): Promise<void> {
373
+ if (!config?.collectLocation) return
374
+ cachedLocation = cachedLocation ?? readStoredLocation()
375
+ const granted = await requestLocationPermission()
376
+ if (!granted) return
377
+ const geo = getGeolocation()
378
+ if (!geo) return
379
+ await new Promise<void>((resolve) => {
380
+ geo.getCurrentPosition(
381
+ (position) => {
382
+ rememberLocation({
383
+ latitude: position.coords.latitude,
384
+ longitude: position.coords.longitude,
385
+ accuracy:
386
+ typeof position.coords.accuracy === 'number'
387
+ ? position.coords.accuracy
388
+ : undefined,
389
+ })
390
+ resolve()
391
+ },
392
+ () => resolve(),
393
+ { enableHighAccuracy: false, timeout: 4000, maximumAge: 60_000 },
394
+ )
395
+ })
396
+ }
397
+
398
+ function getLinking(): LinkingLike | null {
399
+ try {
400
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
401
+ const { Linking } = require('react-native') as { Linking: LinkingLike }
402
+ return Linking
403
+ } catch {
404
+ return null
405
+ }
406
+ }
407
+
408
+ function storageGet(key: string): string | undefined {
409
+ if (Object.prototype.hasOwnProperty.call(memoryStore, key)) {
410
+ return memoryStore[key]
411
+ }
412
+ try {
413
+ if (typeof localStorage !== 'undefined') {
414
+ return localStorage.getItem(key) ?? undefined
415
+ }
416
+ } catch {
417
+ /* ignore */
418
+ }
419
+ return undefined
420
+ }
421
+
422
+ function storageSet(key: string, value: string) {
423
+ memoryStore[key] = value
424
+ try {
425
+ if (typeof localStorage !== 'undefined') {
426
+ localStorage.setItem(key, value)
427
+ }
428
+ } catch {
429
+ /* ignore */
430
+ }
431
+ const asyncStorage = getAsyncStorage()
432
+ if (asyncStorage) {
433
+ void asyncStorage.setItem(key, value).catch(() => {
434
+ /* persistence best-effort */
435
+ })
436
+ }
437
+ }
438
+
439
+ async function storageSetAsync(key: string, value: string): Promise<void> {
440
+ memoryStore[key] = value
441
+ try {
442
+ if (typeof localStorage !== 'undefined') {
443
+ localStorage.setItem(key, value)
444
+ }
445
+ } catch {
446
+ /* ignore */
447
+ }
448
+ const asyncStorage = getAsyncStorage()
449
+ if (!asyncStorage) {
450
+ return
451
+ }
452
+ try {
453
+ await asyncStorage.setItem(key, value)
454
+ } catch {
455
+ /* persistence best-effort */
456
+ }
457
+ }
458
+
459
+ async function hydrateStorage(): Promise<void> {
460
+ const asyncStorage = getAsyncStorage()
461
+ if (asyncStorage) {
462
+ try {
463
+ const rows = await asyncStorage.multiGet(STORAGE_KEYS)
464
+ for (const [key, value] of rows) {
465
+ if (value != null) {
466
+ memoryStore[key] = value
467
+ }
468
+ }
469
+ return
470
+ } catch {
471
+ /* fall through to localStorage */
472
+ }
473
+ }
474
+ try {
475
+ if (typeof localStorage === 'undefined') return
476
+ for (const key of STORAGE_KEYS) {
477
+ const value = localStorage.getItem(key)
478
+ if (value != null) {
479
+ memoryStore[key] = value
480
+ }
481
+ }
482
+ } catch {
483
+ /* memory-only */
484
+ }
485
+ }
486
+
487
+ function uuid(): string {
488
+ const cryptoApi = globalThis.crypto as { randomUUID?: () => string } | undefined
489
+ if (cryptoApi?.randomUUID) return cryptoApi.randomUUID()
490
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (char) => {
491
+ const random = Math.floor(Math.random() * 16)
492
+ const value = char === 'x' ? random : (random & 0x3) | 0x8
493
+ return value.toString(16)
494
+ })
495
+ }
496
+
497
+ function storedAttribution(): AurionAttribution {
498
+ try {
499
+ return JSON.parse(storageGet(STORE_ATTRIBUTION) ?? '{}') as AurionAttribution
500
+ } catch {
501
+ return {}
502
+ }
503
+ }
504
+
505
+ function requireConfig(): InternalConfig {
506
+ if (!config) {
507
+ throw new Error('AurionSignal.configure() must be called before tracking events')
508
+ }
509
+ return config
510
+ }
511
+
512
+ function assertEventName(event: string) {
513
+ if (!EVENT_RE.test(event)) {
514
+ throw new Error(
515
+ `Invalid event "${event}". Use snake_case like sign_up (^[a-z][a-z0-9_]*$)`,
516
+ )
517
+ }
518
+ }
519
+
520
+ function hasAttributionValues(attribution: AurionAttribution): boolean {
521
+ return Object.values(attribution).some((value) => value != null && value !== '')
522
+ }
523
+
524
+ function isPaidAttribution(attribution: AurionAttribution): boolean {
525
+ return Boolean(
526
+ attribution.campaign_id ||
527
+ attribution.click_id ||
528
+ attribution.gbraid ||
529
+ attribution.wbraid ||
530
+ (attribution.campaign && attribution.campaign.toLowerCase() !== 'organic') ||
531
+ (attribution.channel && attribution.channel.toLowerCase() !== 'organic'),
532
+ )
533
+ }
534
+
535
+ function attributionKey(attribution: AurionAttribution): string {
536
+ return [
537
+ attribution.campaign_id ?? '',
538
+ attribution.campaign ?? '',
539
+ attribution.channel ?? '',
540
+ attribution.click_id ?? '',
541
+ attribution.gbraid ?? '',
542
+ attribution.wbraid ?? '',
543
+ ].join('|')
544
+ }
545
+
546
+ function sleep(ms: number): Promise<void> {
547
+ return new Promise((resolve) => setTimeout(resolve, ms))
548
+ }
549
+
550
+ function compactAttribution(attribution: AurionAttribution): AurionAttribution {
551
+ const next: AurionAttribution = {}
552
+ for (const [key, value] of Object.entries(attribution) as [keyof AurionAttribution, string | undefined][]) {
553
+ if (value != null && String(value).trim() !== '') {
554
+ next[key] = String(value).trim()
555
+ }
556
+ }
557
+ return next
558
+ }
559
+
560
+ function rememberAttribution(attribution: AurionAttribution, options?: { replace?: boolean }) {
561
+ const c = requireConfig()
562
+ const compact = compactAttribution(attribution)
563
+ const campaign = compact.campaign
564
+ const channel = compact.channel
565
+ if (campaign) {
566
+ c.campaign = campaign
567
+ storageSet(STORE_CAMPAIGN, campaign)
568
+ }
569
+ if (channel) {
570
+ c.channel = channel
571
+ storageSet(STORE_CHANNEL, channel)
572
+ }
573
+ // New paid links must replace the previous campaign wholesale. A shallow merge kept the old
574
+ // campaign_id when a deep link only carried utm_* briefly, so reattributed stayed on the old id.
575
+ c.attribution = options?.replace ? { ...compact } : { ...c.attribution, ...compact }
576
+ storageSet(STORE_ATTRIBUTION, JSON.stringify(c.attribution))
577
+ storageSet(STORE_ATTRIBUTION_AT, String(Date.now()))
578
+ }
579
+
580
+ function clearStoredAttribution() {
581
+ delete memoryStore[STORE_CAMPAIGN]
582
+ delete memoryStore[STORE_CHANNEL]
583
+ delete memoryStore[STORE_ATTRIBUTION]
584
+ delete memoryStore[STORE_ATTRIBUTION_AT]
585
+ delete memoryStore[STORE_PENDING_URL]
586
+ if (config) {
587
+ config.campaign = undefined
588
+ config.channel = undefined
589
+ config.attribution = {}
590
+ }
591
+ const asyncStorage = getAsyncStorage()
592
+ if (asyncStorage) {
593
+ for (const key of [
594
+ STORE_CAMPAIGN,
595
+ STORE_CHANNEL,
596
+ STORE_ATTRIBUTION,
597
+ STORE_ATTRIBUTION_AT,
598
+ STORE_PENDING_URL,
599
+ ]) {
600
+ void asyncStorage.removeItem(key).catch(() => undefined)
601
+ }
602
+ }
603
+ }
604
+
605
+ function expireAttributionIfNeeded() {
606
+ const c = config
607
+ if (!c || c.attributionWindowDays <= 0) {
608
+ return
609
+ }
610
+ const raw = storageGet(STORE_ATTRIBUTION_AT)
611
+ if (!raw) {
612
+ return
613
+ }
614
+ const at = Number(raw)
615
+ if (!Number.isFinite(at)) {
616
+ return
617
+ }
618
+ const maxAgeMs = c.attributionWindowDays * 24 * 60 * 60 * 1000
619
+ if (Date.now() - at > maxAgeMs) {
620
+ clearStoredAttribution()
621
+ }
622
+ }
623
+
624
+ function notifyAttribution(attribution: AurionAttribution) {
625
+ if (!config?.onAttribution || !isPaidAttribution(attribution)) {
626
+ return
627
+ }
628
+ const key = attributionKey(attribution)
629
+ if (key === lastNotifiedAttributionKey) {
630
+ return
631
+ }
632
+ lastNotifiedAttributionKey = key
633
+ try {
634
+ config.onAttribution({ ...attribution })
635
+ } catch (error) {
636
+ console.warn('AurionSignal onAttribution callback failed', error)
637
+ }
638
+ }
639
+
640
+
641
+ // --- SKAdNetwork (iOS) -------------------------------------------------------------------------------------------
642
+ type AurionSkanModule = {
643
+ start?: () => Promise<void>
644
+ report?: (value: number, medium: number, high: number) => Promise<void>
645
+ getBundleId?: () => Promise<string | null>
646
+ }
647
+ type SkanSchema = { events: Array<{ event: string; value: number }>; coarse: { medium: number; high: number } }
648
+
649
+ const DEFAULT_SKAN_SCHEMA: SkanSchema = {
650
+ events: [
651
+ { event: 'app_install', value: 1 }, { event: 'sign_up', value: 8 }, { event: 'kyc_started', value: 14 },
652
+ { event: 'kyc_completed', value: 20 }, { event: 'account_opened', value: 28 }, { event: 'first_deposit', value: 40 },
653
+ { event: 'repeat_deposit', value: 52 },
654
+ ],
655
+ coarse: { medium: 8, high: 28 },
656
+ }
657
+ let skanSchemaPromise: Promise<SkanSchema> | null = null
658
+
659
+ function skanModule(): AurionSkanModule | null {
660
+ try {
661
+ const rn = require('react-native') as { NativeModules?: Record<string, AurionSkanModule | undefined> }
662
+ return rn.NativeModules?.AurionSkan ?? null
663
+ } catch {
664
+ return null
665
+ }
666
+ }
667
+
668
+ /** The server decides which event is worth which number (Dashboard: SKAN). Falls back to the defaults offline. */
669
+ function loadSkanSchema(mod: AurionSkanModule): Promise<SkanSchema> {
670
+ if (!skanSchemaPromise) {
671
+ skanSchemaPromise = (async () => {
672
+ try {
673
+ const c = requireConfig()
674
+ const bundle = (await mod.getBundleId?.()) ?? ''
675
+ const res = await fetch(`${c.baseUrl.replace(/\/$/, '')}/v1/skan/schema?bundle_id=${encodeURIComponent(bundle)}`, { headers: { 'X-API-Key': c.apiKey } })
676
+ if (!res.ok) return DEFAULT_SKAN_SCHEMA
677
+ const json = (await res.json()) as Partial<SkanSchema>
678
+ return Array.isArray(json.events) && json.events.length && json.coarse ? { events: json.events, coarse: json.coarse } : DEFAULT_SKAN_SCHEMA
679
+ } catch {
680
+ skanSchemaPromise = null
681
+ return DEFAULT_SKAN_SCHEMA
682
+ }
683
+ })()
684
+ }
685
+ return skanSchemaPromise
686
+ }
687
+
688
+ async function skanStart(): Promise<void> {
689
+ const mod = skanModule()
690
+ if (!mod?.start || config?.platform !== 'ios') return
691
+ try {
692
+ await mod.start()
693
+ await loadSkanSchema(mod)
694
+ } catch {
695
+ /* SKAN is best effort and never blocks tracking */
696
+ }
697
+ }
698
+
699
+ /** Raise the conversion value when an event worth more than anything reported so far happens (the native side keeps the maximum). */
700
+ async function skanReport(event: string): Promise<void> {
701
+ const mod = skanModule()
702
+ if (!mod?.report || config?.platform !== 'ios') return
703
+ try {
704
+ const schema = await loadSkanSchema(mod)
705
+ const entry = schema.events.find((e) => e.event === event)
706
+ if (entry) await mod.report(entry.value, schema.coarse.medium, schema.coarse.high)
707
+ } catch {
708
+ /* best effort */
709
+ }
710
+ }
711
+
712
+ // --- Android uninstall (Aurion secondary Firebase) --------------------------------------------------------------
713
+ type AurionPushModule = {
714
+ start?: (options: Record<string, string>) => Promise<string | null>
715
+ getAdvertisingId?: () => Promise<string | null>
716
+ }
717
+
718
+ function pushModule(): AurionPushModule | null {
719
+ try {
720
+ const rn = require('react-native') as { NativeModules?: Record<string, AurionPushModule | undefined> }
721
+ return rn.NativeModules?.AurionPush ?? null
722
+ } catch {
723
+ return null
724
+ }
725
+ }
726
+
727
+ /** Resolve Android GAID once (null when LAT / Play Services unavailable). iOS skipped. */
728
+ async function resolveAndroidGaid(): Promise<string | null> {
729
+ if (config?.platform !== 'android') return null
730
+ if (cachedGaid) return cachedGaid
731
+ const mod = pushModule()
732
+ try {
733
+ const gaid = (await mod?.getAdvertisingId?.()) ?? null
734
+ cachedGaid = gaid
735
+ return gaid
736
+ } catch {
737
+ return null
738
+ }
739
+ }
740
+
741
+ /** Single in-flight Android register so install waits for GAID without double POSTs. */
742
+ let androidDeviceReady: Promise<void> | null = null
743
+
744
+ /**
745
+ * Fetch Attribra Firebase options, start secondary app, register FCM token + GAID.
746
+ * GAID is resolved first so reinstall stitch can run even if FCM config is unavailable.
747
+ */
748
+ async function registerAndroidDevice(): Promise<void> {
749
+ if (config?.platform !== 'android') return
750
+ const mod = pushModule()
751
+ try {
752
+ const c = requireConfig()
753
+ const headers = { 'X-API-Key': c.apiKey }
754
+ const gaid = await resolveAndroidGaid()
755
+ const attribution = { ...c.attribution }
756
+ let pushToken: string | null = null
757
+
758
+ if (mod?.start) {
759
+ const cfgRes = await fetch(`${c.baseUrl.replace(/\/$/, '')}/v1/apps/firebase-config`, { headers })
760
+ if (cfgRes.ok) {
761
+ const cfg = (await cfgRes.json()) as {
762
+ ok?: boolean
763
+ uninstallTrackingEnabled?: boolean
764
+ options?: Record<string, string> | null
765
+ }
766
+ if (cfg.ok && cfg.uninstallTrackingEnabled && cfg.options) {
767
+ pushToken = (await mod.start(cfg.options)) ?? null
768
+ }
769
+ }
770
+ }
771
+
772
+ // Always register when we have GAID and/or a push token so reinstall can stitch.
773
+ if (!gaid && !pushToken) return
774
+
775
+ await fetch(`${c.baseUrl.replace(/\/$/, '')}/v1/devices/register`, {
776
+ method: 'POST',
777
+ headers: { ...headers, 'Content-Type': 'application/json' },
778
+ body: JSON.stringify({
779
+ installation_id: c.installationId,
780
+ platform: 'android',
781
+ push_token: pushToken ?? undefined,
782
+ push_provider: pushToken ? 'fcm' : undefined,
783
+ gaid: gaid ?? undefined,
784
+ campaign: attribution.campaign,
785
+ channel: attribution.channel,
786
+ campaign_id: attribution.campaign_id,
787
+ provider: attribution.provider,
788
+ provider_account_id: attribution.provider_account_id,
789
+ ad_group_id: attribution.ad_group_id,
790
+ ad_group_name: attribution.ad_group_name,
791
+ ad_id: attribution.ad_id,
792
+ ad_name: attribution.ad_name,
793
+ creative_id: attribution.creative_id,
794
+ click_id: attribution.click_id,
795
+ }),
796
+ })
797
+ } catch {
798
+ /* uninstall / reinstall tracking is best effort */
799
+ }
800
+ }
801
+
802
+ function ensureAndroidDeviceRegistered(): Promise<void> {
803
+ if (config?.platform !== 'android') return Promise.resolve()
804
+ if (!androidDeviceReady) {
805
+ androidDeviceReady = registerAndroidDevice().catch(() => {
806
+ /* best effort */
807
+ })
808
+ }
809
+ return androidDeviceReady
810
+ }
811
+
812
+ async function postJson(path: string, body: unknown): Promise<unknown> {
813
+ const c = requireConfig()
814
+ const url = `${c.baseUrl.replace(/\/$/, '')}${path}`
815
+ const controller = new AbortController()
816
+ const timer = setTimeout(() => controller.abort(), 15000)
817
+
818
+ let res: Response
819
+ try {
820
+ res = await fetch(url, {
821
+ method: 'POST',
822
+ headers: {
823
+ 'Content-Type': 'application/json',
824
+ 'X-API-Key': c.apiKey,
825
+ },
826
+ body: JSON.stringify(body),
827
+ signal: controller.signal,
828
+ })
829
+ } catch (err) {
830
+ const msg = err instanceof Error ? err.message : String(err)
831
+ if (msg.includes('AbortError') || controller.signal.aborted) {
832
+ throw new Error(
833
+ `Request timed out after 15s → ${url}. Check baseUrl / API key / network.`,
834
+ )
835
+ }
836
+ throw new Error(`Network error → ${url}: ${msg}`)
837
+ } finally {
838
+ clearTimeout(timer)
839
+ }
840
+
841
+ const text = await res.text()
842
+ let data: unknown = null
843
+ try {
844
+ data = text ? JSON.parse(text) : null
845
+ } catch {
846
+ data = { raw: text }
847
+ }
848
+
849
+ if (!res.ok) {
850
+ throw new Error(`AurionSignal HTTP ${res.status}: ${text || res.statusText}`)
851
+ }
852
+ if (path === '/v1/events') {
853
+ const name = (body as { event?: unknown } | null)?.event
854
+ if (typeof name === 'string') void skanReport(name)
855
+ }
856
+ return data
857
+ }
858
+
859
+ function readEventQueue(): QueuedEvent[] {
860
+ const raw = storageGet(STORE_EVENT_QUEUE)
861
+ if (!raw) {
862
+ return []
863
+ }
864
+ try {
865
+ const parsed = JSON.parse(raw) as unknown
866
+ return Array.isArray(parsed) ? (parsed as QueuedEvent[]) : []
867
+ } catch {
868
+ return []
869
+ }
870
+ }
871
+
872
+ async function writeEventQueue(queue: QueuedEvent[]): Promise<void> {
873
+ await storageSetAsync(STORE_EVENT_QUEUE, JSON.stringify(queue))
874
+ }
875
+
876
+ function isRetriableDeliveryError(error: unknown): boolean {
877
+ const msg = error instanceof Error ? error.message : String(error)
878
+ if (/Network error|timed out|Failed to fetch|Network request failed|ECONN|ENOTFOUND|ETIMEDOUT/i.test(msg)) {
879
+ return true
880
+ }
881
+ const status = msg.match(/AurionSignal HTTP (\d+)/)?.[1]
882
+ if (!status) {
883
+ return false
884
+ }
885
+ const code = Number(status)
886
+ return code === 408 || code === 429 || code >= 500
887
+ }
888
+
889
+ async function enqueueEvent(
890
+ path: '/v1/events' | '/v1/events/batch',
891
+ body: unknown,
892
+ ): Promise<{ ok: true; queued: true; queueSize: number }> {
893
+ const queue = readEventQueue()
894
+ while (queue.length >= MAX_EVENT_QUEUE) {
895
+ queue.shift()
896
+ }
897
+ queue.push({
898
+ id: uuid(),
899
+ path,
900
+ body,
901
+ queued_at: new Date().toISOString(),
902
+ })
903
+ await writeEventQueue(queue)
904
+ return { ok: true, queued: true, queueSize: queue.length }
905
+ }
906
+
907
+ function markInstallPersistedIfNeeded(path: string, body: unknown): void {
908
+ if (path !== '/v1/events') {
909
+ return
910
+ }
911
+ const eventName = (body as { event?: unknown } | null)?.event
912
+ if (eventName === 'app_install') {
913
+ installSent = true
914
+ void storageSetAsync(STORE_INSTALL, '1')
915
+ }
916
+ }
917
+
918
+ /**
919
+ * POST an event now; on offline / timeout / 5xx, persist locally and resolve.
920
+ * Queued events are flushed when the network returns or the app foregrounds.
921
+ */
922
+ async function deliverEvent(
923
+ path: '/v1/events' | '/v1/events/batch',
924
+ body: unknown,
925
+ ): Promise<unknown> {
926
+ try {
927
+ const result = await postJson(path, body)
928
+ markInstallPersistedIfNeeded(path, body)
929
+ void flushEventQueue()
930
+ return result
931
+ } catch (error) {
932
+ if (!isRetriableDeliveryError(error)) {
933
+ throw error
934
+ }
935
+ const queued = await enqueueEvent(path, body)
936
+ if (path === '/v1/events' && (body as { event?: unknown } | null)?.event === 'app_install') {
937
+ // Avoid duplicate install scheduling while the payload sits in the offline queue.
938
+ installSent = true
939
+ }
940
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
941
+ console.warn('AurionSignal queued event offline', queued.queueSize, error)
942
+ }
943
+ return queued
944
+ }
945
+ }
946
+
947
+ async function flushEventQueue(): Promise<{ flushed: number; remaining: number }> {
948
+ if (eventQueueFlushPromise) {
949
+ return eventQueueFlushPromise
950
+ }
951
+ eventQueueFlushPromise = (async () => {
952
+ let flushed = 0
953
+ while (true) {
954
+ const queue = readEventQueue()
955
+ if (queue.length === 0) {
956
+ return { flushed, remaining: 0 }
957
+ }
958
+ const next = queue[0]
959
+ try {
960
+ await postJson(next.path, next.body)
961
+ markInstallPersistedIfNeeded(next.path, next.body)
962
+ queue.shift()
963
+ await writeEventQueue(queue)
964
+ flushed += 1
965
+ } catch (error) {
966
+ if (isRetriableDeliveryError(error)) {
967
+ return { flushed, remaining: queue.length }
968
+ }
969
+ // Drop permanent failures so one bad payload cannot block the queue.
970
+ queue.shift()
971
+ await writeEventQueue(queue)
972
+ console.warn('AurionSignal dropped queued event', error)
973
+ }
974
+ }
975
+ })()
976
+ try {
977
+ return await eventQueueFlushPromise
978
+ } finally {
979
+ eventQueueFlushPromise = null
980
+ }
981
+ }
982
+
983
+ function isConnectivityOnline(state: {
984
+ isConnected?: boolean | null
985
+ isInternetReachable?: boolean | null
986
+ }): boolean {
987
+ if (state.isConnected === false) {
988
+ return false
989
+ }
990
+ // null means "not checked yet" — treat as online so we still attempt a flush.
991
+ if (state.isInternetReachable === false) {
992
+ return false
993
+ }
994
+ return true
995
+ }
996
+
997
+ type NetworkState = {
998
+ isConnected?: boolean | null
999
+ isInternetReachable?: boolean | null
1000
+ }
1001
+
1002
+ /**
1003
+ * SDK-only connectivity via the packaged AurionNetwork native module
1004
+ * (Android ConnectivityManager / iOS NWPathMonitor). No NetInfo peer.
1005
+ * AppState foreground flush still runs as a safety net.
1006
+ */
1007
+ function startNetworkListener() {
1008
+ try {
1009
+ networkUnsubscribe?.()
1010
+ } catch {
1011
+ /* ignore */
1012
+ }
1013
+ networkUnsubscribe = null
1014
+
1015
+ let wasOnline: boolean | null = null
1016
+ const onNetChange = (state: NetworkState) => {
1017
+ const online = isConnectivityOnline(state)
1018
+ if (online && wasOnline !== true) {
1019
+ void flushEventQueue()
1020
+ }
1021
+ wasOnline = online
1022
+ }
1023
+
1024
+ try {
1025
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
1026
+ const rn = require('react-native') as {
1027
+ NativeModules?: {
1028
+ AurionNetwork?: {
1029
+ start?: () => Promise<boolean>
1030
+ isOnline?: () => Promise<boolean>
1031
+ addListener?: (event: string) => void
1032
+ removeListeners?: (count: number) => void
1033
+ }
1034
+ }
1035
+ NativeEventEmitter?: new (nativeModule?: unknown) => {
1036
+ addListener: (
1037
+ event: string,
1038
+ listener: (state: NetworkState) => void,
1039
+ ) => { remove: () => void }
1040
+ }
1041
+ }
1042
+ const native = rn.NativeModules?.AurionNetwork
1043
+ if (!native?.start || !rn.NativeEventEmitter) {
1044
+ return
1045
+ }
1046
+ const emitter = new rn.NativeEventEmitter(native)
1047
+ const sub = emitter.addListener('aurionNetworkChange', onNetChange)
1048
+ networkUnsubscribe = () => {
1049
+ try {
1050
+ sub.remove()
1051
+ } catch {
1052
+ /* ignore */
1053
+ }
1054
+ }
1055
+ void native
1056
+ .start()
1057
+ .then((online) => {
1058
+ onNetChange({ isConnected: online, isInternetReachable: online })
1059
+ })
1060
+ .catch(() => undefined)
1061
+ } catch {
1062
+ /* rebuild the app so AurionNetwork autolinks; AppState flush still works */
1063
+ }
1064
+ }
1065
+
1066
+ function buildPayload(event: string, props: TrackProperties = {}): TrackEventInput {
1067
+ const c = requireConfig()
1068
+ assertEventName(event)
1069
+ expireAttributionIfNeeded()
1070
+
1071
+ const {
1072
+ channel,
1073
+ campaign,
1074
+ value,
1075
+ city,
1076
+ latitude,
1077
+ longitude,
1078
+ location_accuracy,
1079
+ consent,
1080
+ timestamp,
1081
+ platform,
1082
+ properties,
1083
+ attribution,
1084
+ provider,
1085
+ provider_account_id,
1086
+ campaign_id,
1087
+ ad_group_id,
1088
+ ad_group_name,
1089
+ ad_id,
1090
+ ad_name,
1091
+ creative_id,
1092
+ click_id,
1093
+ ...rest
1094
+ } = props
1095
+
1096
+ const incomingAttribution: AurionAttribution = { ...attribution }
1097
+ if (campaign) incomingAttribution.campaign = campaign
1098
+ if (channel) incomingAttribution.channel = channel
1099
+ if (provider) incomingAttribution.provider = provider
1100
+ if (provider_account_id) incomingAttribution.provider_account_id = provider_account_id
1101
+ if (campaign_id) incomingAttribution.campaign_id = campaign_id
1102
+ if (ad_group_id) incomingAttribution.ad_group_id = ad_group_id
1103
+ if (ad_group_name) incomingAttribution.ad_group_name = ad_group_name
1104
+ if (ad_id) incomingAttribution.ad_id = ad_id
1105
+ if (ad_name) incomingAttribution.ad_name = ad_name
1106
+ if (creative_id) incomingAttribution.creative_id = creative_id
1107
+ if (click_id) incomingAttribution.click_id = click_id
1108
+ if (hasAttributionValues(incomingAttribution)) {
1109
+ rememberAttribution(incomingAttribution)
1110
+ }
1111
+
1112
+ const extra = { ...(properties ?? {}), ...rest }
1113
+ delete extra.event
1114
+ delete extra.source
1115
+ delete extra.user_id
1116
+ if (cachedGaid && extra.gaid == null) {
1117
+ extra.gaid = cachedGaid
1118
+ }
1119
+ // Google's iPhone click ids ride along as properties so the server can report the conversion to Google Ads.
1120
+ if (c.attribution.gbraid && extra.gbraid == null) extra.gbraid = c.attribution.gbraid
1121
+ if (c.attribution.wbraid && extra.wbraid == null) extra.wbraid = c.attribution.wbraid
1122
+
1123
+ const location = cachedLocation ?? readStoredLocation()
1124
+ cachedLocation = location
1125
+
1126
+ return {
1127
+ event,
1128
+ source: c.source,
1129
+ platform: platform ?? c.platform,
1130
+ channel: channel ?? c.channel ?? c.attribution.channel,
1131
+ campaign: campaign ?? c.campaign ?? c.attribution.campaign,
1132
+ value,
1133
+ city,
1134
+ latitude: latitude ?? location?.latitude,
1135
+ longitude: longitude ?? location?.longitude,
1136
+ location_accuracy: location_accuracy ?? location?.accuracy,
1137
+ // Device identity: always the persistent installation UUID.
1138
+ user_id: c.installationId,
1139
+ consent: consent ?? c.consent,
1140
+ timestamp: timestamp ?? new Date().toISOString(),
1141
+ properties: Object.keys(extra).length ? extra : undefined,
1142
+ event_id: uuid(),
1143
+ installation_id: c.installationId,
1144
+ session_id: c.sessionId,
1145
+ sdk_name: 'react_native',
1146
+ sdk_version: SDK_VERSION,
1147
+ app_version: c.appVersion,
1148
+ provider: provider ?? c.attribution.provider,
1149
+ provider_account_id: provider_account_id ?? c.attribution.provider_account_id,
1150
+ campaign_id: campaign_id ?? c.attribution.campaign_id,
1151
+ ad_group_id: ad_group_id ?? c.attribution.ad_group_id,
1152
+ ad_group_name: ad_group_name ?? c.attribution.ad_group_name,
1153
+ ad_id: ad_id ?? c.attribution.ad_id,
1154
+ ad_name: ad_name ?? c.attribution.ad_name,
1155
+ creative_id: creative_id ?? c.attribution.creative_id,
1156
+ click_id: click_id ?? c.attribution.click_id,
1157
+ }
1158
+ }
1159
+
1160
+ async function sendInstallIfNeeded(): Promise<void> {
1161
+ if (installSent || storageGet(STORE_INSTALL) === '1') {
1162
+ installSent = true
1163
+ return
1164
+ }
1165
+ installSent = true
1166
+ try {
1167
+ // Android: wait for GAID + devices/register before app_install so reinstall can stitch.
1168
+ await ensureAndroidDeviceRegistered()
1169
+ const payload = buildPayload('app_install')
1170
+ const result = await deliverEvent('/v1/events', payload)
1171
+ const queued = (result as { queued?: boolean } | null)?.queued === true
1172
+ if (!queued) {
1173
+ await storageSetAsync(STORE_INSTALL, '1')
1174
+ }
1175
+ } catch (err) {
1176
+ installSent = false
1177
+ console.warn('AurionSignal app_install failed', err)
1178
+ }
1179
+ }
1180
+
1181
+ async function sendReattributed(
1182
+ next: AurionAttribution,
1183
+ previous: AurionAttribution,
1184
+ ): Promise<void> {
1185
+ try {
1186
+ const compact = compactAttribution(next)
1187
+ await deliverEvent(
1188
+ '/v1/events',
1189
+ buildPayload('reattributed', {
1190
+ ...compact,
1191
+ campaign: compact.campaign,
1192
+ channel: compact.channel,
1193
+ campaign_id: compact.campaign_id,
1194
+ attribution: compact,
1195
+ properties: {
1196
+ deep_link: true,
1197
+ previous_campaign: previous.campaign ?? null,
1198
+ previous_campaign_id: previous.campaign_id ?? null,
1199
+ },
1200
+ }),
1201
+ )
1202
+ if (config?.onReattributed) {
1203
+ try {
1204
+ config.onReattributed({ ...next }, { ...previous })
1205
+ } catch (error) {
1206
+ console.warn('AurionSignal onReattributed callback failed', error)
1207
+ }
1208
+ }
1209
+ } catch (error) {
1210
+ console.warn('AurionSignal reattributed failed', error)
1211
+ }
1212
+ }
1213
+
1214
+ async function sendOpenApp(): Promise<void> {
1215
+ if (!config?.autoOpenApp || !installSent) {
1216
+ return
1217
+ }
1218
+ const now = Date.now()
1219
+ if (now - lastOpenAppAt < OPEN_APP_DEBOUNCE_MS) {
1220
+ return
1221
+ }
1222
+ lastOpenAppAt = now
1223
+ try {
1224
+ await deliverEvent('/v1/events', buildPayload('open_app'))
1225
+ } catch (error) {
1226
+ console.warn('AurionSignal open_app failed', error)
1227
+ }
1228
+ }
1229
+
1230
+ function getAppState(): AppStateLike | null {
1231
+ try {
1232
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
1233
+ const { AppState } = require('react-native') as { AppState: AppStateLike }
1234
+ return AppState
1235
+ } catch {
1236
+ return null
1237
+ }
1238
+ }
1239
+
1240
+ function startAppStateListener() {
1241
+ const appState = getAppState()
1242
+ if (!appState) return
1243
+ try {
1244
+ appStateSubscription?.remove()
1245
+ } catch {
1246
+ /* ignore */
1247
+ }
1248
+ lastAppState = appState.currentState || 'active'
1249
+ const subscription = appState.addEventListener('change', (nextAppState) => {
1250
+ const wasBackground =
1251
+ lastAppState === 'background' || lastAppState === 'inactive'
1252
+ lastAppState = nextAppState
1253
+ if (wasBackground && nextAppState === 'active') {
1254
+ void flushEventQueue()
1255
+ openAppPromise = (async () => {
1256
+ // Do not re-read getInitialURL()/pending here: Android keeps returning the first
1257
+ // launch URL forever, which re-applied the old campaign over a fresh deep link.
1258
+ try {
1259
+ await attributionApplyPromise
1260
+ } catch {
1261
+ /* still open */
1262
+ }
1263
+ await reattributedPromise
1264
+ await sendOpenApp()
1265
+ })()
1266
+ void openAppPromise
1267
+ }
1268
+ })
1269
+ appStateSubscription =
1270
+ subscription && typeof subscription.remove === 'function' ? subscription : null
1271
+ }
1272
+
1273
+ /** Read query params without depending on Hermes URLSearchParams quirks. */
1274
+ function queryParamsFromUrl(url: string): Record<string, string> {
1275
+ const raw = String(url ?? '').trim()
1276
+ if (!raw) {
1277
+ return {}
1278
+ }
1279
+
1280
+ let query = raw
1281
+ const schemeIdx = raw.indexOf('://')
1282
+ const pathStart = schemeIdx >= 0 ? schemeIdx + 3 : 0
1283
+ const qIdx = raw.indexOf('?', pathStart)
1284
+ if (qIdx >= 0) {
1285
+ query = raw.slice(qIdx + 1)
1286
+ } else if (raw.includes('://') || raw.startsWith('/') || raw.startsWith('http')) {
1287
+ return {}
1288
+ }
1289
+
1290
+ const hashIdx = query.indexOf('#')
1291
+ if (hashIdx >= 0) {
1292
+ query = query.slice(0, hashIdx)
1293
+ }
1294
+
1295
+ const out: Record<string, string> = {}
1296
+ for (const part of query.split('&')) {
1297
+ if (!part) {
1298
+ continue
1299
+ }
1300
+ const eq = part.indexOf('=')
1301
+ const rawKey = eq >= 0 ? part.slice(0, eq) : part
1302
+ const rawVal = eq >= 0 ? part.slice(eq + 1) : ''
1303
+ if (!rawKey) {
1304
+ continue
1305
+ }
1306
+ let key = rawKey
1307
+ let value = rawVal
1308
+ try {
1309
+ key = decodeURIComponent(rawKey.replace(/\+/g, ' '))
1310
+ value = decodeURIComponent(rawVal.replace(/\+/g, ' '))
1311
+ } catch {
1312
+ /* keep raw */
1313
+ }
1314
+ if (!(key in out)) {
1315
+ out[key] = value
1316
+ }
1317
+ }
1318
+ return out
1319
+ }
1320
+
1321
+ /**
1322
+ * Map ad network / deep-link query params → campaign + channel.
1323
+ * Supports Google (utm_*), Meta (campaign_name / utm_source=facebook|instagram), TikTok.
1324
+ */
1325
+ export function parseAttributionFromUrl(url: string): {
1326
+ campaign: string | null
1327
+ channel: string | null
1328
+ attribution: AurionAttribution
1329
+ } {
1330
+ try {
1331
+ const params = queryParamsFromUrl(url)
1332
+ const get = (...keys: string[]) => {
1333
+ for (const key of keys) {
1334
+ const value = params[key]
1335
+ if (value != null && String(value).trim() !== '') {
1336
+ return String(value).trim()
1337
+ }
1338
+ }
1339
+ return null
1340
+ }
1341
+
1342
+ const campaign = get(
1343
+ 'utm_campaign',
1344
+ 'campaign',
1345
+ 'campaign_name',
1346
+ 'c',
1347
+ 'utm_content',
1348
+ )
1349
+
1350
+ let channel = get('utm_source', 'channel', 'utm_medium', 'media_source')
1351
+
1352
+ if (channel) {
1353
+ const lower = channel.toLowerCase()
1354
+ if (
1355
+ lower.includes('facebook') ||
1356
+ lower.includes('instagram') ||
1357
+ lower === 'fb' ||
1358
+ lower === 'ig'
1359
+ ) {
1360
+ channel = 'Meta'
1361
+ } else if (lower.includes('google') || lower === 'gclid' || lower === 'adwords') {
1362
+ channel = 'Google'
1363
+ } else if (lower.includes('tiktok') || lower === 'tt') {
1364
+ channel = 'TikTok'
1365
+ }
1366
+ }
1367
+
1368
+ const clickId = get('click_id', 'gclid', 'fbclid', 'ttclid') ?? undefined
1369
+ const attribution: AurionAttribution = {
1370
+ campaign: campaign ?? undefined,
1371
+ channel: channel ?? undefined,
1372
+ provider: get('provider') ?? undefined,
1373
+ provider_account_id: get('account_id') ?? undefined,
1374
+ campaign_id: get('campaign_id') ?? undefined,
1375
+ ad_group_id: get('adgroup_id', 'ad_group_id') ?? undefined,
1376
+ ad_group_name: get('adgroup', 'ad_group', 'adset_name') ?? undefined,
1377
+ ad_id: get('ad_id') ?? undefined,
1378
+ ad_name: get('ad_name', 'ad', 'creative_name') ?? undefined,
1379
+ creative_id: get('creative_id') ?? undefined,
1380
+ click_id: clickId,
1381
+ gbraid: get('gbraid') ?? undefined,
1382
+ wbraid: get('wbraid') ?? undefined,
1383
+ }
1384
+ return { campaign, channel, attribution }
1385
+ } catch {
1386
+ return { campaign: null, channel: null, attribution: {} }
1387
+ }
1388
+ }
1389
+
1390
+ function looksLikeAttributionUrl(value: string): boolean {
1391
+ const lower = value.toLowerCase()
1392
+ return (
1393
+ lower.includes('aurion_clip=1') ||
1394
+ lower.includes('campaign_id=') ||
1395
+ lower.includes('utm_campaign=') ||
1396
+ lower.includes('utm_source=') ||
1397
+ lower.includes('click_id=') ||
1398
+ lower.includes('tl=') ||
1399
+ lower.includes('gclid=') ||
1400
+ lower.includes('gbraid=') ||
1401
+ lower.includes('wbraid=') ||
1402
+ lower.includes('fbclid=')
1403
+ )
1404
+ }
1405
+
1406
+ function persistParsedAttribution(parsed: {
1407
+ campaign: string | null
1408
+ channel: string | null
1409
+ attribution: AurionAttribution
1410
+ }) {
1411
+ if (!hasAttributionValues(parsed.attribution)) {
1412
+ return
1413
+ }
1414
+ if (parsed.campaign) {
1415
+ storageSet(STORE_CAMPAIGN, parsed.campaign)
1416
+ }
1417
+ if (parsed.channel) {
1418
+ storageSet(STORE_CHANNEL, parsed.channel)
1419
+ }
1420
+ const replaced = compactAttribution({
1421
+ ...parsed.attribution,
1422
+ campaign: parsed.campaign ?? parsed.attribution.campaign,
1423
+ channel: parsed.channel ?? parsed.attribution.channel,
1424
+ })
1425
+ storageSet(STORE_ATTRIBUTION, JSON.stringify(replaced))
1426
+ storageSet(STORE_ATTRIBUTION_AT, String(Date.now()))
1427
+ if (config) {
1428
+ rememberAttribution(replaced, { replace: true })
1429
+ }
1430
+ }
1431
+
1432
+ /**
1433
+ * Attribra short links look like https://<host>/l/<app>/<token>. When an installed app is opened through one
1434
+ * (Universal Link / App Link) the browser redirect never runs, so the campaign details are fetched from the API.
1435
+ */
1436
+ const TRACKING_LINK_PATH = /^\/l\/(?:[a-z0-9-]{2,60}\/)?[A-Za-z0-9]{4,16}\/?$/
1437
+ const resolvingLinks = new Map<string, Promise<string>>()
1438
+
1439
+ function hostAndPath(url: string): { host: string; path: string } | null {
1440
+ const m = /^https?:\/\/([^/?#]+)(\/[^?#]*)?/i.exec(String(url ?? '').trim())
1441
+ return m ? { host: m[1].toLowerCase(), path: m[2] ?? '/' } : null
1442
+ }
1443
+
1444
+ function isTrackingLinkUrl(url: string): boolean {
1445
+ if (!config) return false
1446
+ const link = hostAndPath(url)
1447
+ const base = hostAndPath(config.baseUrl)
1448
+ return !!link && !!base && link.host === base.host && TRACKING_LINK_PATH.test(link.path)
1449
+ }
1450
+
1451
+ /** Turn a short link into a URL carrying its campaign parameters. Falls back to the original URL on any error. */
1452
+ function expandTrackingLink(url: string): Promise<string> {
1453
+ const pending = resolvingLinks.get(url)
1454
+ if (pending) return pending
1455
+ const work = (async () => {
1456
+ try {
1457
+ const platform = config?.platform
1458
+ const res = (await postJson('/v1/tracking-links/resolve', {
1459
+ url,
1460
+ ...(platform === 'android' || platform === 'ios' ? { platform } : {}),
1461
+ })) as { query?: string } | null
1462
+ const link = hostAndPath(url)
1463
+ if (res?.query && link) return `https://${link.host}/?${res.query}`
1464
+ } catch {
1465
+ /* offline or unknown link: leave the URL as it is */
1466
+ }
1467
+ return url
1468
+ })()
1469
+ resolvingLinks.set(url, work)
1470
+ return work
1471
+ }
1472
+
1473
+ function applyResolvedAttribution(
1474
+ url: string,
1475
+ options?: { announce?: boolean; sendAppOpenIfInstalled?: boolean },
1476
+ ): ReturnType<typeof parseAttributionFromUrl> {
1477
+ if (!looksLikeAttributionUrl(url)) {
1478
+ return { campaign: null, channel: null, attribution: {} }
1479
+ }
1480
+
1481
+ storageSet(STORE_PENDING_URL, url)
1482
+ const parsed = parseAttributionFromUrl(url)
1483
+ if (!hasAttributionValues(parsed.attribution)) {
1484
+ return parsed
1485
+ }
1486
+ // The link was created with "credit the previous ad": keep the earlier paid campaign.
1487
+ if (config && isPaidAttribution(config.attribution) && queryParamsFromUrl(url).attr_mode === 'previous_ad') {
1488
+ return parsed
1489
+ }
1490
+
1491
+ const previousAttribution = config ? { ...config.attribution } : {}
1492
+ const previousPaid = config ? isPaidAttribution(previousAttribution) : false
1493
+ const nextKey = attributionKey(parsed.attribution)
1494
+ const previousKey = attributionKey(previousAttribution)
1495
+ persistParsedAttribution(parsed)
1496
+
1497
+ if (!config) {
1498
+ pendingUrls.push(url)
1499
+ return parsed
1500
+ }
1501
+
1502
+ if (options?.announce !== false) {
1503
+ notifyAttribution(parsed.attribution)
1504
+ }
1505
+
1506
+ // First launch: install still pending — campaign is attached to app_install.
1507
+ // Later opens: installed device + different paid campaign → reattributed.
1508
+ if (
1509
+ options?.sendAppOpenIfInstalled !== false &&
1510
+ installSent &&
1511
+ isPaidAttribution(parsed.attribution) &&
1512
+ (!previousPaid || nextKey !== previousKey)
1513
+ ) {
1514
+ const send = sendReattributed(compactAttribution(parsed.attribution), previousAttribution)
1515
+ reattributedPromise = reattributedPromise.then(() => send, () => send)
1516
+ void reattributedPromise
1517
+ }
1518
+
1519
+ return parsed
1520
+ }
1521
+
1522
+ async function applyAttributionFromUrlAsync(
1523
+ url: string,
1524
+ options?: { announce?: boolean; sendAppOpenIfInstalled?: boolean },
1525
+ ): Promise<ReturnType<typeof parseAttributionFromUrl>> {
1526
+ let target = url
1527
+ if (isTrackingLinkUrl(url)) {
1528
+ target = await expandTrackingLink(url)
1529
+ if (target === url) {
1530
+ return { campaign: null, channel: null, attribution: {} }
1531
+ }
1532
+ }
1533
+ return applyResolvedAttribution(target, options)
1534
+ }
1535
+
1536
+ function queueAttributionApply(
1537
+ url: string,
1538
+ options?: { announce?: boolean; sendAppOpenIfInstalled?: boolean },
1539
+ ): void {
1540
+ const work = applyAttributionFromUrlAsync(url, options).then(() => undefined)
1541
+ attributionApplyPromise = attributionApplyPromise.then(() => work, () => work)
1542
+ void attributionApplyPromise
1543
+ }
1544
+
1545
+ function applyAttributionFromUrlInternal(
1546
+ url: string,
1547
+ options?: { announce?: boolean; sendAppOpenIfInstalled?: boolean },
1548
+ ): ReturnType<typeof parseAttributionFromUrl> {
1549
+ if (isTrackingLinkUrl(url)) {
1550
+ queueAttributionApply(url, options)
1551
+ return { campaign: null, channel: null, attribution: {} }
1552
+ }
1553
+ return applyResolvedAttribution(url, options)
1554
+ }
1555
+
1556
+ /** Packaged iOS native module — UIPasteboard only (no JS clipboard dependency). */
1557
+ function clipboardModule(): { getString?: () => Promise<string | null> } | null {
1558
+ if (config?.platform !== 'ios') return null
1559
+ try {
1560
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
1561
+ const rn = require('react-native') as {
1562
+ NativeModules?: Record<string, { getString?: () => Promise<string | null> } | undefined>
1563
+ }
1564
+ return rn.NativeModules?.AurionClipboard ?? null
1565
+ } catch {
1566
+ return null
1567
+ }
1568
+ }
1569
+
1570
+ async function readClipboardCandidate(): Promise<string | null> {
1571
+ // iOS defaults readClipboard on in configure(); Android stays opt-in (Play referrer).
1572
+ if (!config?.readClipboard) {
1573
+ return null
1574
+ }
1575
+ try {
1576
+ const mod = clipboardModule()
1577
+ if (!mod?.getString) return null
1578
+ const raw = await mod.getString()
1579
+ const value = typeof raw === 'string' ? raw.trim() : ''
1580
+ if (value && looksLikeAttributionUrl(value)) {
1581
+ return value.includes('://')
1582
+ ? value
1583
+ : `https://aurion.signal/open?${value.replace(/^\?/, '')}`
1584
+ }
1585
+ } catch {
1586
+ /* paste denied / native module missing until rebuild */
1587
+ }
1588
+ return null
1589
+ }
1590
+
1591
+ /**
1592
+ * During the first-install grace window, suppress reattributed so the campaign
1593
+ * attaches to app_install instead. After install is sent, cold-start / refresh
1594
+ * deep links must fire reattributed when the campaign changes.
1595
+ */
1596
+ function attributionSendOptions(): { sendAppOpenIfInstalled: boolean } {
1597
+ return { sendAppOpenIfInstalled: installSent }
1598
+ }
1599
+
1600
+ function flushPendingUrls() {
1601
+ while (pendingUrls.length > 0) {
1602
+ const url = pendingUrls.shift()
1603
+ if (url) {
1604
+ applyAttributionFromUrlInternal(url, attributionSendOptions())
1605
+ }
1606
+ }
1607
+ }
1608
+
1609
+ /**
1610
+ * Reads the Google Play install referrer (Android) that the short-link redirect attached to the store URL.
1611
+ * Returns the referrer text (empty for an organic install) or null when Play could not answer.
1612
+ */
1613
+ async function readNativeInstallReferrer(): Promise<string | null> {
1614
+ try {
1615
+ const rn = require('react-native') as { NativeModules?: Record<string, { getInstallReferrer?: () => Promise<string | null> } | undefined> }
1616
+ const module = rn.NativeModules?.AurionInstallReferrer
1617
+ if (!module?.getInstallReferrer) return null
1618
+ const value = await module.getInstallReferrer()
1619
+ return typeof value === 'string' ? value : null
1620
+ } catch {
1621
+ return null
1622
+ }
1623
+ }
1624
+
1625
+ /** true when the Play referrer answered (even if organic); false when it is unavailable and matching should be tried. */
1626
+ async function captureInstallReferrer(): Promise<boolean> {
1627
+ if (!config || config.platform !== 'android') return false
1628
+ if (isPaidAttribution(config.attribution)) return true
1629
+ const referrer = await readNativeInstallReferrer()
1630
+ if (referrer === null) return false
1631
+ // Organic installs carry a generic google-play referrer; only act on one our links produced.
1632
+ if (/(^|&)(tl|campaign_id|click_id|gclid|gbraid|wbraid|fbclid)=/.test(referrer)) {
1633
+ applyAttributionFromUrlInternal(referrer, { sendAppOpenIfInstalled: false })
1634
+ }
1635
+ return true
1636
+ }
1637
+
1638
+ /**
1639
+ * Fresh install that carries no link data (every iPhone install, Android without a Play referrer):
1640
+ * ask Attribra for the recent click from this network and OS version. The answer is a best guess.
1641
+ */
1642
+ async function matchInstallIfNeeded(): Promise<void> {
1643
+ if (!config || installSent || isPaidAttribution(config.attribution)) return
1644
+ if (config.platform !== 'ios' && config.platform !== 'android') return
1645
+ if (storageGet(STORE_MATCHED) === '1') return
1646
+ storageSet(STORE_MATCHED, '1')
1647
+ try {
1648
+ let osVersion: string | undefined
1649
+ if (config.platform === 'ios') {
1650
+ const rn = require('react-native') as { Platform?: { Version?: string | number } }
1651
+ osVersion = rn.Platform?.Version != null ? String(rn.Platform.Version) : undefined
1652
+ }
1653
+ const res = (await postJson('/v1/tracking-links/match', {
1654
+ platform: config.platform,
1655
+ installation_id: config.installationId,
1656
+ ...(osVersion ? { os_version: osVersion } : {}),
1657
+ })) as { matched?: boolean; query?: string } | null
1658
+ if (res?.matched && res.query) {
1659
+ applyAttributionFromUrlInternal(`https://match.invalid/?${res.query}`, { sendAppOpenIfInstalled: false })
1660
+ }
1661
+ } catch {
1662
+ /* offline: the install is sent without a campaign */
1663
+ }
1664
+ }
1665
+
1666
+ async function captureLaunchUrl(): Promise<boolean> {
1667
+ const linking = getLinking()
1668
+ if (!linking) return false
1669
+ try {
1670
+ const url = await linking.getInitialURL()
1671
+ if (url) {
1672
+ consumedInitialUrl = url
1673
+ await applyAttributionFromUrlAsync(url, attributionSendOptions())
1674
+ return config ? isPaidAttribution(config.attribution) : false
1675
+ }
1676
+ } catch {
1677
+ /* linking unavailable */
1678
+ }
1679
+ return false
1680
+ }
1681
+
1682
+ function startDeepLinkListener() {
1683
+ const linking = getLinking()
1684
+ if (!linking) return
1685
+ try {
1686
+ linkingSubscription?.remove()
1687
+ } catch {
1688
+ /* ignore */
1689
+ }
1690
+ const subscription = linking.addEventListener('url', ({ url }) => {
1691
+ queueAttributionApply(url)
1692
+ })
1693
+ linkingSubscription =
1694
+ subscription && typeof subscription.remove === 'function' ? subscription : null
1695
+ }
1696
+
1697
+ /**
1698
+ * Android cold-starts often return null from getInitialURL() on the first call,
1699
+ * then the same API returns the App Link a moment later — without firing a url
1700
+ * event. Poll + listen during the grace window so app_install is not Organic.
1701
+ */
1702
+ async function waitForLateDeepLink(graceMs: number): Promise<void> {
1703
+ if (graceMs <= 0) return
1704
+ if (config && isPaidAttribution(config.attribution)) return
1705
+
1706
+ const linking = getLinking()
1707
+ if (!linking) {
1708
+ await sleep(graceMs)
1709
+ return
1710
+ }
1711
+
1712
+ await new Promise<void>((resolve) => {
1713
+ let settled = false
1714
+ let pollTimer: ReturnType<typeof setInterval> | null = null
1715
+ let graceTimer: ReturnType<typeof setTimeout> | null = null
1716
+
1717
+ const finish = () => {
1718
+ if (settled) return
1719
+ settled = true
1720
+ if (pollTimer) clearInterval(pollTimer)
1721
+ if (graceTimer) clearTimeout(graceTimer)
1722
+ try {
1723
+ subscription?.remove?.()
1724
+ } catch {
1725
+ /* ignore */
1726
+ }
1727
+ resolve()
1728
+ }
1729
+
1730
+ const tryCapture = async () => {
1731
+ if (settled) return
1732
+ if (config && isPaidAttribution(config.attribution)) {
1733
+ finish()
1734
+ return
1735
+ }
1736
+ try {
1737
+ const url = await linking.getInitialURL()
1738
+ if (url) {
1739
+ consumedInitialUrl = url
1740
+ await applyAttributionFromUrlAsync(url, { sendAppOpenIfInstalled: false })
1741
+ if (config && isPaidAttribution(config.attribution)) {
1742
+ finish()
1743
+ }
1744
+ }
1745
+ } catch {
1746
+ /* ignore */
1747
+ }
1748
+ }
1749
+
1750
+ const subscription = linking.addEventListener('url', ({ url }) => {
1751
+ void applyAttributionFromUrlAsync(url, { sendAppOpenIfInstalled: false }).finally(() => {
1752
+ finish()
1753
+ })
1754
+ })
1755
+
1756
+ pollTimer = setInterval(() => {
1757
+ void tryCapture()
1758
+ }, DEEP_LINK_POLL_MS)
1759
+ graceTimer = setTimeout(finish, graceMs)
1760
+ void tryCapture()
1761
+ })
1762
+ }
1763
+
1764
+ async function refreshAttributionFromDevice(options?: {
1765
+ includeInitialUrl?: boolean
1766
+ includePending?: boolean
1767
+ }): Promise<AurionAttribution> {
1768
+ requireConfig()
1769
+ const includeInitialUrl = options?.includeInitialUrl !== false
1770
+ const includePending = options?.includePending !== false
1771
+ const linking = getLinking()
1772
+ const asyncStorage = getAsyncStorage()
1773
+ const candidates: string[] = []
1774
+
1775
+ if (includeInitialUrl && linking) {
1776
+ try {
1777
+ const initial = await linking.getInitialURL()
1778
+ // Android keeps returning the first launch URL; applying it again would
1779
+ // overwrite a newer campaign opened through a later App Link.
1780
+ if (initial && initial !== consumedInitialUrl) {
1781
+ consumedInitialUrl = initial
1782
+ candidates.push(initial)
1783
+ }
1784
+ } catch {
1785
+ /* ignore */
1786
+ }
1787
+ }
1788
+
1789
+ const liveAttributionUrl = candidates.some(
1790
+ (url) => isTrackingLinkUrl(url) || looksLikeAttributionUrl(url),
1791
+ )
1792
+
1793
+ // Pending is a bootstrap fallback only — never let a stale stored URL beat a live link.
1794
+ if (includePending && !liveAttributionUrl) {
1795
+ if (asyncStorage) {
1796
+ try {
1797
+ const stored = await asyncStorage.getItem(STORE_PENDING_URL)
1798
+ if (stored) candidates.push(stored)
1799
+ } catch {
1800
+ /* ignore */
1801
+ }
1802
+ }
1803
+
1804
+ const memoryPending = storageGet(STORE_PENDING_URL)
1805
+ if (memoryPending) candidates.push(memoryPending)
1806
+ }
1807
+
1808
+ const clip = await readClipboardCandidate()
1809
+ if (clip) candidates.push(clip)
1810
+
1811
+ for (const url of candidates) {
1812
+ await applyAttributionFromUrlAsync(url, attributionSendOptions())
1813
+ }
1814
+
1815
+ await attributionApplyPromise
1816
+ return { ...requireConfig().attribution }
1817
+ }
1818
+
1819
+ /** Background: capture late App Links / iOS clipboard, then send first install once. */
1820
+ function scheduleInstallCapture(graceMs: number) {
1821
+ installPromise = (async () => {
1822
+ try {
1823
+ await waitForLateDeepLink(graceMs)
1824
+ // Deep link, pending URL, then iOS clipboard (aurion_clip) before probabilistic match.
1825
+ await refreshAttributionFromDevice()
1826
+ const referrerAnswered = await captureInstallReferrer()
1827
+ // iOS: captureInstallReferrer is always false; match runs only if clipboard/link did not attribute.
1828
+ if (!referrerAnswered) await matchInstallIfNeeded()
1829
+ if (config && isPaidAttribution(config.attribution)) {
1830
+ notifyAttribution(config.attribution)
1831
+ }
1832
+ await sendInstallIfNeeded()
1833
+ } catch (error) {
1834
+ console.warn('AurionSignal background install failed', error)
1835
+ }
1836
+ })()
1837
+ }
1838
+
1839
+ async function bootstrap(options: AurionConfig): Promise<void> {
1840
+ await hydrateStorage()
1841
+ expireAttributionIfNeeded()
1842
+
1843
+ installSent = storageGet(STORE_INSTALL) === '1'
1844
+ const installationId = storageGet(STORE_INSTALLATION_ID) ?? uuid()
1845
+ storageSet(STORE_INSTALLATION_ID, installationId)
1846
+ const attribution = storedAttribution()
1847
+
1848
+ config = {
1849
+ apiKey: options.apiKey,
1850
+ baseUrl: options.baseUrl ?? 'http://localhost:8000/api',
1851
+ consent: options.consent ?? true,
1852
+ source: options.source ?? 'react_native',
1853
+ platform: options.platform ?? detectPlatform(),
1854
+ campaign: options.campaign ?? attribution.campaign ?? storageGet(STORE_CAMPAIGN),
1855
+ channel: options.channel ?? attribution.channel ?? storageGet(STORE_CHANNEL),
1856
+ attribution,
1857
+ installationId,
1858
+ sessionId: uuid(),
1859
+ appVersion: options.appVersion,
1860
+ attributionWindowDays: options.attributionWindowDays ?? DEFAULT_ATTRIBUTION_WINDOW_DAYS,
1861
+ // iOS: default on for App Store clipboard fallback; Android stays opt-in.
1862
+ readClipboard:
1863
+ options.readClipboard === true ||
1864
+ (options.readClipboard !== false && (options.platform ?? detectPlatform()) === 'ios'),
1865
+ collectLocation: options.collectLocation !== false,
1866
+ autoOpenApp: options.autoOpenApp !== false,
1867
+ onAttribution: options.onAttribution,
1868
+ onReattributed: options.onReattributed,
1869
+ }
1870
+ cachedLocation = readStoredLocation()
1871
+ flushPendingUrls()
1872
+
1873
+ if (options.campaign || options.channel) {
1874
+ rememberAttribution({ campaign: options.campaign, channel: options.channel })
1875
+ }
1876
+
1877
+ const graceMs = options.deepLinkGraceMs ?? DEFAULT_DEEP_LINK_GRACE_MS
1878
+
1879
+ if (options.autoCaptureDeepLinks !== false) {
1880
+ startDeepLinkListener()
1881
+ }
1882
+
1883
+ if (config.collectLocation) {
1884
+ void refreshLocationIfNeeded().catch(() => undefined)
1885
+ }
1886
+
1887
+ startAppStateListener()
1888
+ startNetworkListener()
1889
+ void flushEventQueue()
1890
+
1891
+ if (options.autoInstall !== false && !installSent) {
1892
+ if (options.autoCaptureDeepLinks !== false) {
1893
+ void captureLaunchUrl().catch(() => undefined)
1894
+ }
1895
+ scheduleInstallCapture(graceMs)
1896
+ } else {
1897
+ if (isPaidAttribution(config.attribution)) {
1898
+ notifyAttribution(config.attribution)
1899
+ }
1900
+ // Cold start of an already-installed device → open_app
1901
+ openAppPromise = (async () => {
1902
+ if (options.autoCaptureDeepLinks !== false) {
1903
+ try {
1904
+ await captureLaunchUrl()
1905
+ await refreshAttributionFromDevice({ includeInitialUrl: false, includePending: true })
1906
+ } catch {
1907
+ /* still open */
1908
+ }
1909
+ }
1910
+ await attributionApplyPromise
1911
+ await reattributedPromise
1912
+ await sendOpenApp()
1913
+ })()
1914
+ void openAppPromise
1915
+ }
1916
+ }
1917
+
1918
+ async function awaitReady(): Promise<void> {
1919
+ await readyPromise
1920
+ await installPromise
1921
+ await attributionApplyPromise
1922
+ await reattributedPromise
1923
+ await openAppPromise
1924
+ }
1925
+
1926
+ /** Test helper: reset module state between Jest cases. */
1927
+ export function __resetAurionSignalForTests() {
1928
+ config = null
1929
+ installSent = false
1930
+ readyPromise = Promise.resolve()
1931
+ installPromise = Promise.resolve()
1932
+ reattributedPromise = Promise.resolve()
1933
+ attributionApplyPromise = Promise.resolve()
1934
+ openAppPromise = Promise.resolve()
1935
+ consumedInitialUrl = null
1936
+ linkingSubscription = null
1937
+ try {
1938
+ appStateSubscription?.remove()
1939
+ } catch {
1940
+ /* ignore */
1941
+ }
1942
+ appStateSubscription = null
1943
+ lastAppState = 'active'
1944
+ lastOpenAppAt = 0
1945
+ lastNotifiedAttributionKey = ''
1946
+ cachedLocation = null
1947
+ cachedGaid = null
1948
+ androidDeviceReady = null
1949
+ eventQueueFlushPromise = null
1950
+ try {
1951
+ networkUnsubscribe?.()
1952
+ } catch {
1953
+ /* ignore */
1954
+ }
1955
+ networkUnsubscribe = null
1956
+ pendingUrls.length = 0
1957
+ resolvingLinks.clear()
1958
+ for (const key of Object.keys(memoryStore)) {
1959
+ delete memoryStore[key]
1960
+ }
1961
+ }
1962
+
1963
+ export const AurionSignal = {
1964
+ /**
1965
+ * Call once at app start. Deep links with campaign_id / utm_* are captured
1966
+ * automatically; app_install is sent once per device after that.
1967
+ */
1968
+ configure(options: AurionConfig) {
1969
+ if (!options.apiKey?.startsWith('asg_')) {
1970
+ console.warn('AurionSignal: apiKey usually starts with asg_')
1971
+ }
1972
+ readyPromise = bootstrap(options).catch((error) => {
1973
+ console.warn('AurionSignal bootstrap failed', error)
1974
+ })
1975
+ void readyPromise.then(() => skanStart())
1976
+ // Android: GAID + register start immediately; app_install awaits the same promise.
1977
+ void readyPromise.then(() => ensureAndroidDeviceRegistered())
1978
+ },
1979
+
1980
+ /** Resolves when storage + launch deep link + optional install are finished. */
1981
+ ready() {
1982
+ return awaitReady()
1983
+ },
1984
+
1985
+ getPlatform(): AurionPlatform {
1986
+ return config?.platform ?? detectPlatform()
1987
+ },
1988
+
1989
+ getAttribution(): AurionAttribution {
1990
+ expireAttributionIfNeeded()
1991
+ return { ...(config?.attribution ?? storedAttribution()) }
1992
+ },
1993
+
1994
+ setConsent(consent: boolean) {
1995
+ requireConfig().consent = consent
1996
+ },
1997
+
1998
+ /** Persistent device id used as user_id on every event. */
1999
+ getDeviceId(): string {
2000
+ return requireConfig().installationId
2001
+ },
2002
+
2003
+ setCampaign(campaign: string, channel?: string) {
2004
+ rememberAttribution({ campaign, channel })
2005
+ },
2006
+
2007
+ /** Optional escape hatch — deep links are captured automatically. */
2008
+ applyAttributionFromUrl(url: string) {
2009
+ return applyAttributionFromUrlInternal(url)
2010
+ },
2011
+
2012
+ /** Optional: parse a Play Install Referrer string the app already obtained. */
2013
+ applyInstallReferrer(referrer: string) {
2014
+ let query = referrer.trim()
2015
+ try {
2016
+ query = decodeURIComponent(query)
2017
+ } catch {
2018
+ /* keep raw referrer */
2019
+ }
2020
+ if (query.startsWith('referrer=')) {
2021
+ query = query.slice('referrer='.length)
2022
+ try {
2023
+ query = decodeURIComponent(query)
2024
+ } catch {
2025
+ /* keep unwrapped query */
2026
+ }
2027
+ }
2028
+ return this.applyAttributionFromUrl(query)
2029
+ },
2030
+
2031
+ /** Send app_install now if it has not been sent yet for this device. */
2032
+ async flushInstall() {
2033
+ await awaitReady()
2034
+ await refreshAttributionFromDevice()
2035
+ return sendInstallIfNeeded()
2036
+ },
2037
+
2038
+ /** Track a single event — campaign / user_id / platform are filled in automatically. */
2039
+ async track(event: string, props?: TrackProperties) {
2040
+ await awaitReady()
2041
+ try {
2042
+ await refreshAttributionFromDevice()
2043
+ } catch {
2044
+ /* still send the event */
2045
+ }
2046
+ // Cold-start deep links may start reattributed inside refresh — wait for it.
2047
+ await reattributedPromise
2048
+ await openAppPromise
2049
+ if (!installSent) {
2050
+ await sendInstallIfNeeded()
2051
+ }
2052
+ const attribution = { ...requireConfig().attribution }
2053
+ const merged: TrackProperties = {
2054
+ ...attribution,
2055
+ ...props,
2056
+ campaign: props?.campaign ?? attribution.campaign,
2057
+ channel: props?.channel ?? attribution.channel,
2058
+ campaign_id: props?.campaign_id ?? attribution.campaign_id,
2059
+ provider_account_id: props?.provider_account_id ?? attribution.provider_account_id,
2060
+ attribution: { ...attribution, ...(props?.attribution ?? {}) },
2061
+ }
2062
+ if (typeof __DEV__ !== 'undefined' && __DEV__) {
2063
+ console.log('AurionSignal.track', event, {
2064
+ campaign: merged.campaign,
2065
+ channel: merged.channel,
2066
+ campaign_id: merged.campaign_id,
2067
+ baseUrl: requireConfig().baseUrl,
2068
+ })
2069
+ }
2070
+ return deliverEvent('/v1/events', buildPayload(event, merged))
2071
+ },
2072
+
2073
+ /** Track up to 100 events */
2074
+ async trackBatch(events: Array<{ event: string; props?: TrackProperties }>) {
2075
+ await awaitReady()
2076
+ try {
2077
+ await refreshAttributionFromDevice()
2078
+ } catch {
2079
+ /* still send */
2080
+ }
2081
+ await reattributedPromise
2082
+ await openAppPromise
2083
+ if (!installSent) {
2084
+ await sendInstallIfNeeded()
2085
+ }
2086
+ if (events.length === 0) return { ok: true, count: 0 }
2087
+ if (events.length > 100) {
2088
+ throw new Error('AurionSignal.trackBatch supports at most 100 events')
2089
+ }
2090
+ const payload = {
2091
+ events: events.map(({ event, props }) => buildPayload(event, props)),
2092
+ }
2093
+ return deliverEvent('/v1/events/batch', payload)
2094
+ },
2095
+
2096
+ /**
2097
+ * Push any events stored while offline. Called automatically on launch,
2098
+ * foreground, reconnect (if NetInfo is installed), and after a successful send.
2099
+ */
2100
+ async flushQueue() {
2101
+ await awaitReady()
2102
+ return flushEventQueue()
2103
+ },
2104
+
2105
+ /** Number of events waiting for network (in-memory snapshot after hydrate). */
2106
+ pendingQueueSize() {
2107
+ return readEventQueue().length
2108
+ },
2109
+ }