@traqio/web 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../sdk-core/src/skan.ts", "../../sdk-core/src/adservices.ts", "../../sdk-core/src/deeplink.ts", "../src/shims/empty.ts", "../../sdk-core/src/index.ts", "../src/index.ts", "../src/cookies.ts", "../src/storage.ts", "../src/trackId.ts"],
4
+ "sourcesContent": ["// iOS SKAdNetwork conversion values \u2014 the JS half.\n//\n// Be clear about what this buys you: SKAN gives Apple SIX BITS about an install,\n// delivered to the ad network (and to Traqio's postback endpoint) at least 24h\n// after the conversion window closes, and withheld entirely when the campaign is\n// too small for Apple's crowd-anonymity threshold. It is aggregated, coarse and\n// late by construction \u2014 never per-user, never real-time. This file encodes a\n// number; it does not make iOS deterministic.\n//\n// The mapping is fetched from the API rather than hardcoded in the app: the\n// server decodes postbacks with the mapping it published, so a hardcoded copy in\n// the app drifts silently and you only find out 24h later when the values come\n// back meaning the wrong thing.\n\nexport type CoarseValue = \"low\" | \"medium\" | \"high\";\n\nexport type PostbackWindowIndex = 0 | 1 | 2;\n\n/**\n * When a conversion window is closed early. Mirrors `PostbackWindow` in the API\n * (apps/api/src/skan/conversion-value.ts).\n *\n * This used to be a parameter the HOST APP passed to `updateSkanConversionValue`,\n * which meant changing when a campaign reports required shipping an app release. It\n * is configuration now: the mapping carries it, the device obeys it.\n */\nexport interface PostbackWindow {\n window: PostbackWindowIndex;\n lock: boolean;\n /** Hours since install at which to lock. null = lock on the next value update. */\n lockAfterHours?: number | null;\n}\n\n/**\n * Apple's three conversion windows, in hours since install. Mirrors\n * CONVERSION_WINDOWS in the API \u2014 the device and the console must not disagree about\n * when a window closes.\n *\n * 0 \u2014 day 0-2 (0 \u2192 48 h), the only window carrying a FINE value\n * 1 \u2014 day 3-7 (48 \u2192 168 h), coarse only\n * 2 \u2014 day 8-35 (168 \u2192 840 h), coarse only\n */\nexport const CONVERSION_WINDOWS: { window: PostbackWindowIndex; startHours: number; endHours: number }[] = [\n { window: 0, startHours: 0, endHours: 48 },\n { window: 1, startHours: 48, endHours: 168 },\n { window: 2, startHours: 168, endHours: 840 },\n];\n\n/** What `GET /skan/mapping/<sdkKey>` returns (null when the app configured none). */\nexport interface SkanMapping {\n version: number;\n mode: \"revenue\" | \"events\";\n currency: string;\n /** revenue mode: ascending lower bounds, index = fine conversion value. */\n revenueBuckets?: number[] | null;\n /** events mode: bit index \u2192 event name (max 6). */\n eventBits?: string[] | null;\n /** Optional SKAN 4 coarse tiers, as revenue thresholds. */\n coarseRevenue?: Partial<Record<CoarseValue, number>> | null;\n /** The postback schedule. Absent = Apple's own timing, nothing locked early. */\n postbackWindows?: PostbackWindow[] | null;\n}\n\n/** The window an install of this age is inside, or null past day 35. */\nexport function windowForAge(hoursSinceInstall: number): PostbackWindowIndex | null {\n const found = CONVERSION_WINDOWS.find(\n (w) => hoursSinceInstall >= w.startHours && hoursSinceInstall < w.endHours,\n );\n return found ? found.window : null;\n}\n\n/**\n * Should this update carry `lockWindow: true`? Mirrors `shouldLockWindow` in the API.\n *\n * Locking closes the current window immediately: the postback arrives sooner, at the\n * cost of every conversion the rest of the window would have seen. The console shows\n * that cost as a measurement gap before anyone turns it on.\n */\nexport function shouldLockWindow(\n windows: PostbackWindow[] | null | undefined,\n hoursSinceInstall: number,\n): boolean {\n const current = windowForAge(hoursSinceInstall);\n if (current == null || !windows || !windows.length) return false;\n const rule = windows.find((w) => w.window === current);\n if (!rule || !rule.lock) return false;\n if (rule.lockAfterHours == null) return true;\n return hoursSinceInstall >= rule.lockAfterHours;\n}\n\n/** The native surface the Expo module exposes (no-op on Android). */\nexport interface SkanNative {\n updateConversionValue(fineValue: number, coarse?: CoarseValue, lockWindow?: boolean): void;\n}\n\nconst MAX_FINE_VALUE = 63;\nconst MAX_EVENT_BITS = 6;\n\n/**\n * Highest bucket whose lower bound the revenue has reached. Mirrors\n * `fineValueForRevenue` in the API (apps/api/src/skan/conversion-value.ts) \u2014 the\n * encode and decode sides of one mapping must never disagree.\n */\nexport function fineValueForRevenue(revenue: number, buckets: number[]): number {\n let value = 0;\n for (let i = 0; i < Math.min(buckets.length, MAX_FINE_VALUE + 1); i++) {\n if (revenue >= buckets[i]) value = i;\n }\n return value;\n}\n\n/** Milestone names \u2192 the 6-bit mask, in the bit order the mapping declares. */\nexport function fineValueForEvents(events: Iterable<string>, bits: string[]): number {\n const reached = new Set(events);\n let value = 0;\n bits.slice(0, MAX_EVENT_BITS).forEach((name, i) => {\n if (reached.has(name)) value |= 1 << i;\n });\n return value;\n}\n\n/**\n * Highest configured coarse tier the revenue has reached. Returns undefined when\n * the mapping declares no tiers \u2014 the native side then derives one from the fine\n * value rather than sending nothing.\n */\nexport function coarseValueForRevenue(\n revenue: number,\n tiers: Partial<Record<CoarseValue, number>> | null | undefined,\n): CoarseValue | undefined {\n if (!tiers) return undefined;\n let best: CoarseValue | undefined;\n let bestThreshold = -Infinity;\n for (const tier of [\"low\", \"medium\", \"high\"] as const) {\n const threshold = tiers[tier];\n if (threshold != null && revenue >= threshold && threshold >= bestThreshold) {\n best = tier;\n bestThreshold = threshold;\n }\n }\n return best;\n}\n\ninterface SkanState {\n /** Lifetime revenue this install has produced, as SKAN needs a running total. */\n revenue: number;\n /** Milestone names already reached (events mode). */\n events: string[];\n /** Last fine value we asked the device to send. */\n lastFine: number | null;\n /**\n * Unix ms of the first launch we saw. The conversion-window schedule is expressed\n * in hours SINCE INSTALL, and nothing on the device tells us the install time \u2014 so\n * this is our own stand-in, written once and never moved. It is later than the true\n * install by however long the user took to open the app, which makes a lock fire\n * slightly LATE rather than early: the safe direction, since an early lock throws\n * measurement away and a late one only delays the postback.\n */\n firstSeenAt?: number;\n}\n\nconst EMPTY_STATE: SkanState = { revenue: 0, events: [], lastFine: null };\n\nexport interface SkanOptions {\n endpoint: string;\n sdkKey: string;\n native?: SkanNative;\n /** Same store the event queue uses, so the running total survives a restart. */\n storage?: { getItem(key: string): Promise<string | null>; setItem(key: string, value: string): Promise<void> };\n /** Injectable for tests; defaults to the global fetch. */\n fetchFn?: typeof fetch;\n /** Injectable clock, so the window schedule is testable without waiting 48 hours. */\n nowFn?: () => number;\n}\n\nexport const SKAN_STATE_KEY = \"traq_skan_state\";\n\n/**\n * Owns the app's SKAN conversion value: fetch the mapping, keep the running\n * total across launches, and push a new value to the device when \u2014 and only\n * when \u2014 it actually changed upward.\n *\n * Inert unless everything is in place (iOS + a native bridge + a published\n * mapping). On Android and off-device it does nothing at all, so callers never\n * have to branch on platform.\n */\nexport class Skan {\n private opts!: SkanOptions;\n private mapping: SkanMapping | null = null;\n private state: SkanState = { ...EMPTY_STATE };\n private enabled = false;\n\n async init(opts: SkanOptions): Promise<void> {\n this.opts = opts;\n this.enabled = Boolean(opts.native);\n if (!this.enabled) return;\n await this.restore();\n if (this.state.firstSeenAt == null) {\n this.state.firstSeenAt = this.now();\n await this.persist();\n }\n this.mapping = await this.fetchMapping();\n // A mapping published (or changed) after the install still applies from now\n // on: re-encode the totals we already have so the first window isn't lost.\n if (this.mapping) this.push();\n }\n\n /**\n * Add revenue this install produced. SKAN encodes a LIFETIME total, not one\n * purchase, so amounts accumulate \u2014 passing a single sale twice double-counts\n * it, same as anywhere else.\n */\n addRevenue(amount: number): void {\n if (!this.enabled || !(amount > 0) || !Number.isFinite(amount)) return;\n this.state.revenue += amount;\n void this.persist();\n this.push();\n }\n\n /** Mark a milestone reached (events mode). Repeats are idempotent. */\n markEvent(name: string): void {\n if (!this.enabled || this.state.events.includes(name)) return;\n this.state.events.push(name);\n void this.persist();\n this.push();\n }\n\n /** The mapping in force, for callers that want to show it. Null until fetched. */\n get activeMapping(): SkanMapping | null {\n return this.mapping;\n }\n\n // \u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n private push(): void {\n const m = this.mapping;\n if (!m || !this.opts.native) return;\n\n let fine: number;\n let coarse: CoarseValue | undefined;\n if (m.mode === \"events\") {\n if (!m.eventBits?.length) return;\n fine = fineValueForEvents(this.state.events, m.eventBits);\n } else {\n if (!m.revenueBuckets?.length) return;\n fine = fineValueForRevenue(this.state.revenue, m.revenueBuckets);\n coarse = coarseValueForRevenue(this.state.revenue, m.coarseRevenue);\n }\n\n // Value 0 is already on the device: the native module registers the install\n // with it on create. Re-sending it would burn the first, most valuable\n // conversion window on \"nothing happened yet\".\n if (this.state.lastFine == null && fine === 0) return;\n // The native side enforces the increase rule too, but not crossing the bridge\n // at all is what keeps a chatty app from waking SKAdNetwork on every purchase.\n if (this.state.lastFine != null && fine <= this.state.lastFine) return;\n this.state.lastFine = fine;\n void this.persist();\n this.opts.native.updateConversionValue(fine, coarse, this.lockWindowNow());\n }\n\n /**\n * Whether this update closes the current conversion window, per the schedule the\n * mapping published. Without a mapping, or with no rule for the window we are in,\n * the answer is false \u2014 Apple's own timing, which gives nothing up.\n */\n private lockWindowNow(): boolean {\n const since = this.state.firstSeenAt;\n if (since == null) return false;\n const hours = (this.now() - since) / 3_600_000;\n return shouldLockWindow(this.mapping?.postbackWindows, hours);\n }\n\n private now(): number {\n return this.opts.nowFn ? this.opts.nowFn() : Date.now();\n }\n\n private async fetchMapping(): Promise<SkanMapping | null> {\n const doFetch = this.opts.fetchFn ?? (typeof fetch === \"function\" ? fetch : undefined);\n if (!doFetch) return null;\n try {\n const res = await doFetch(`${this.opts.endpoint}/skan/mapping/${encodeURIComponent(this.opts.sdkKey)}`);\n if (!res.ok) return null;\n const body = (await res.json()) as SkanMapping | null;\n return body && typeof body === \"object\" ? body : null;\n } catch {\n // Offline at launch is normal. No mapping \u2192 we simply never set a value;\n // the install itself is still registered natively on module create.\n return null;\n }\n }\n\n private async restore(): Promise<void> {\n try {\n const raw = await this.opts.storage?.getItem(SKAN_STATE_KEY);\n if (raw) this.state = { ...EMPTY_STATE, ...(JSON.parse(raw) as SkanState) };\n } catch {\n /* corrupt/absent \u2014 start from zero */\n }\n }\n\n private async persist(): Promise<void> {\n try {\n await this.opts.storage?.setItem(SKAN_STATE_KEY, JSON.stringify(this.state));\n } catch {\n /* storage full/unavailable */\n }\n }\n}\n", "// Apple Ads (Search Ads) attribution \u2014 the JS half.\n//\n// What it buys: the one DETERMINISTIC attribution iOS still allows. Every other iOS\n// signal is SKAdNetwork, which is aggregated, six bits wide and 24h+ late. Apple\n// Search Ads self-attributes through the AdServices framework, and any developer may\n// resolve their own app's tokens \u2014 no partner programme, no allowlist.\n//\n// What it is NOT: an identifier. `AAAttribution.attributionToken()` returns an\n// opaque, single-purpose claim ticket valid for **24 hours**. No IDFA, no ATT prompt\n// of our own, no fingerprinting. Apple decides how much of the answer to return from\n// the ATT status the user already chose \u2014 detailed with consent, standard without.\n//\n// Why the SERVER resolves it: Apple answers 404 until the token is known on its side,\n// which right after an install is the normal first answer. That retry has to outlive\n// the app process, so the device's only job is to hand the token over before it\n// expires. See apps/api/src/apple-ads/.\n//\n// https://developer.apple.com/documentation/adservices\n\n/** Native surface the Expo module exposes. Absent on Android and pre-iOS 14.3. */\nexport interface AdServicesNative {\n /** The opaque 24h token, or null when the framework has none on this device. */\n getAttributionToken(): Promise<string | null>;\n}\n\nexport interface AdServicesOptions {\n endpoint: string;\n sdkKey: string;\n deviceId?: string;\n userId?: string;\n native?: AdServicesNative;\n /** Same store the event queue uses, so \"already sent\" survives a restart. */\n storage?: { getItem(key: string): Promise<string | null>; setItem(key: string, value: string): Promise<void> };\n /** Injectable for tests; defaults to the global fetch. */\n fetchFn?: typeof fetch;\n}\n\nexport const ADSERVICES_SENT_KEY = \"traq_adservices_sent\";\nexport const ADSERVICES_ATTEMPTS_KEY = \"traq_adservices_attempts\";\n\n/**\n * How many launches we keep asking before giving up on this install. The framework\n * can answer later in an install's life, but on a device where it never will \u2014\n * a simulator, an install with no attribution record at all, which is MOST installs \u2014\n * asking forever is work with no answer to it.\n */\nconst MAX_ATTEMPTS = 5;\n\n/**\n * Hand the token over, at most once per install.\n *\n * Returns what happened, so a host app can debug the integration without reading our\n * logs. Never throws: there is no user-visible consequence to any outcome here, and\n * an exception in `init()` would take the whole SDK down for a signal most installs\n * do not have.\n */\nexport async function reportAdServicesToken(\n opts: AdServicesOptions,\n): Promise<\"sent\" | \"already-sent\" | \"no-token\" | \"unsupported\" | \"post-failed\"> {\n if (!opts.native?.getAttributionToken) return \"unsupported\";\n\n if (await read(opts, ADSERVICES_SENT_KEY)) return \"already-sent\";\n\n let token: string | null = null;\n try {\n token = await opts.native.getAttributionToken();\n } catch {\n // The framework throws on a device with nothing to give. Treated as \"no token\".\n }\n\n if (!token || !token.trim()) {\n const attempts = Number(await read(opts, ADSERVICES_ATTEMPTS_KEY)) || 0;\n await write(opts, ADSERVICES_ATTEMPTS_KEY, String(attempts + 1));\n // Bounded: stop asking a device that will never answer.\n if (attempts + 1 >= MAX_ATTEMPTS) await write(opts, ADSERVICES_SENT_KEY, \"1\");\n return \"no-token\";\n }\n\n const doFetch = opts.fetchFn ?? (typeof fetch === \"function\" ? fetch : undefined);\n if (!doFetch) return \"post-failed\";\n\n try {\n const res = await doFetch(`${opts.endpoint}/ingest/adservices`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n sdkKey: opts.sdkKey,\n token: token.trim(),\n deviceId: opts.deviceId,\n appUserId: opts.userId,\n }),\n });\n if (!res.ok) return \"post-failed\";\n } catch {\n return \"post-failed\";\n }\n\n // Only mark sent on success, so a failed post retries on the next launch \u2014 inside\n // the 24h window, which is what makes the retry worth anything.\n await write(opts, ADSERVICES_SENT_KEY, \"1\");\n return \"sent\";\n}\n\nasync function read(opts: AdServicesOptions, key: string): Promise<string | null> {\n try {\n return (await opts.storage?.getItem(key)) ?? null;\n } catch {\n return null;\n }\n}\n\nasync function write(opts: AdServicesOptions, key: string, value: string): Promise<void> {\n try {\n await opts.storage?.setItem(key, value);\n } catch {\n /* storage full/unavailable */\n }\n}\n", "// Deep linking \u2014 the SDK half (docs/DEEP_LINKING.md).\n//\n// Two moments, one callback:\n// - DIRECT: a universal link / App Link (`https://<your host>/c/<code>`) opened\n// the installed app. The OS never hit our server, so the SDK resolves the\n// code \u2014 which also records the click the OS skipped.\n// - DEFERRED: the app was installed FROM a link. On the very first launch the\n// SDK asks where that link wanted the user to land. Android answers from the\n// Play Install Referrer (deterministic); iOS only when the app opted into the\n// IP match in the console (probabilistic, off by default).\n//\n// Privacy: nothing new leaves the device. The referrer is already sent with the\n// install; the URL is the one that opened the app. No pasteboard, no IDFA.\n\n/** Where a link wants the app to land. */\nexport interface DeepLink {\n /**\n * The destination set on the link in the console \u2014 an in-app path\n * (\"/product/42\") or an app URL (\"myapp://product/42\"). Null when the link\n * carries none: the app still learns WHICH link brought the user (`code`).\n */\n deepLink: string | null;\n /** The link's slug (the `<code>` of `/c/<code>`). */\n code: string | null;\n /** True when the link was tapped BEFORE the install; false when it opened the app. */\n deferred: boolean;\n /** How it was resolved. `ip_match` is a probabilistic guess \u2014 see the docs. */\n via: \"referrer\" | \"ip_match\" | \"link\";\n /** The URL that opened the app (direct opens only). */\n url?: string;\n}\n\n/** What `/deeplink/deferred` and `/deeplink/open` answer. */\nexport interface DeepLinkAnswer {\n matched: boolean;\n via: \"referrer\" | \"ip_match\" | \"link\" | null;\n code: string | null;\n deepLink: string | null;\n}\n\n// Mirrors `parseTrackingUrl` in apps/api/src/tracking/link-rules.ts. Checked on\n// the device so the app's OWN URLs (most of what opens an app) never leave it.\nconst TRACKING_PATH = /^\\/c\\/[A-Za-z0-9_-]{1,50}\\/?$/;\n\n/** True when `url` is one of our tracking links (`http(s)://<host>/c/<code>`). */\nexport function isTrackingUrl(url: string): boolean {\n const m = /^https?:\\/\\/[^/?#]+(\\/[^?#]*)?/i.exec(url);\n return Boolean(m && TRACKING_PATH.test(m[1] ?? \"\"));\n}\n\n/** An API answer \u2192 the callback's shape, or null when nothing matched. */\nexport function toDeepLink(answer: DeepLinkAnswer | null, deferred: boolean, url?: string): DeepLink | null {\n if (!answer?.matched || !answer.via) return null;\n return { deepLink: answer.deepLink, code: answer.code, deferred, via: answer.via, ...(url ? { url } : {}) };\n}\n", "// Stands in for `react-native` and `@react-native-async-storage/async-storage` in the\n// bundle. @traqio/core reaches for both inside try/catch (they are how it finds\n// AppState, Linking and AsyncStorage on React Native); in a browser they must resolve\n// to nothing, never to a bare `require` a consumer's bundler would try to follow.\nexport {};\n", "// @traqio/core \u2014 the platform-neutral engine. Android-first: reads the Play Install\n// Referrer from the native module, sends install + events to the ingestion API,\n// with a persisted offline queue, batching, and exponential-backoff retries.\n// On iOS: SKAdNetwork conversion values (./skan) plus Apple Ads self-attribution\n// through AdServices (./adservices) \u2014 the one deterministic iOS source.\n// Privacy: NO IDFA/GAID, no pasteboard, no fingerprinting. deviceId is a\n// first-party random id (persisted), not a cross-app identifier. Deep links\n// (./deeplink) send nothing new: the referrer already travels with the install,\n// and the iOS deferred IP match is the SERVER's, opt-in per app, routing only.\n\n// `require` is provided by the React Native / Metro runtime (used to lazily\n// wire AppState for lifecycle flush; absent off-device, hence the try/catch).\ndeclare const require: (module: string) => any;\n\nimport { Skan, type CoarseValue, type SkanMapping } from \"./skan\";\nimport { reportAdServicesToken } from \"./adservices\";\nimport { isTrackingUrl, toDeepLink, type DeepLink, type DeepLinkAnswer } from \"./deeplink\";\n\nexport const SDK_VERSION = \"0.1.1\";\nexport { Skan, type CoarseValue, type SkanMapping } from \"./skan\";\nexport { reportAdServicesToken, type AdServicesNative } from \"./adservices\";\nexport { isTrackingUrl, type DeepLink } from \"./deeplink\";\n\nconst INSTALL_SENT_KEY = \"traq_install_sent\";\nconst INSTALL_ATTEMPTS_KEY = \"traq_install_attempts\";\nconst REFERRER_KEY = \"traq_referrer\";\nconst QUEUE_KEY = \"traq_queue\";\nconst AD_QUEUE_KEY = \"traq_ad_queue\";\nconst DEVICE_ID_KEY = \"traq_device_id\";\nconst LAST_SESSION_KEY = \"traq_last_session\";\n// Set once `forgetMe()` has been honoured by the server. Persisted, because the\n// whole point is that the NEXT launch stays silent too \u2014 the deviceId is still in\n// storage and an un-persisted flag would re-report the install tomorrow.\nconst ERASED_KEY = \"traq_erased\";\n// The deferred deep link, once the server has answered for this install\n// (\"null\" when it answered \"no link\"). Persisted so it is asked exactly once.\nconst DEFERRED_KEY = \"traq_deferred_link\";\n// The user's answer to the app's consent prompt (\"granted\" | \"denied\"), once given.\nconst CONSENT_KEY = \"traq_consent\";\nconst MAX_BATCH = 20;\nconst MAX_QUEUE = 500;\n// Ad impressions are far more frequent than tracked events (a banner refreshes\n// every 30-60s), so they get their own, larger queue and batch.\nconst MAX_AD_BATCH = 100;\nconst MAX_AD_QUEUE = 1000;\nconst BASE_RETRY_MS = 1000;\nconst MAX_RETRY_MS = 5 * 60 * 1000;\nconst FLUSH_DELAY_MS = 3000;\n// How many launches we let the Play Install Referrer stay unavailable before\n// reporting the install anyway. See `sendInstallOnce`.\nconst MAX_INSTALL_ATTEMPTS = 3;\n\n// How long the app must have been away before coming back counts as a NEW session.\n// 30 minutes is the near-universal convention (GA4, Adjust, AppsFlyer all land\n// there) and the point of it is that a user switching to Maps and back has not\n// started a new session. It is also the debounce: without it, every\n// foreground/background flicker would post.\nconst SESSION_TIMEOUT_MS = 30 * 60 * 1000;\n\nexport interface KeyValueStore {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n}\n\nexport interface DeviceContext {\n deviceId?: string;\n deviceModel?: string;\n osVersion?: string;\n appVersion?: string;\n locale?: string;\n sdkVersion?: string;\n}\n\n/**\n * Why a Play Install Referrer read ended. Mirrors `ReferrerStatus` in the Kotlin\n * module, plus `unavailable` for \"the native module answered nothing\".\n */\nexport type InstallReferrerStatus =\n | \"ok\"\n | \"no_referrer\"\n | \"feature_not_supported\"\n | \"service_unavailable\"\n | \"service_disconnected\"\n | \"developer_error\"\n | \"permission_error\"\n | \"timeout\"\n | \"error\"\n | \"no_context\"\n | \"not_supported_platform\"\n | \"unavailable\";\n\nexport interface InstallReferrerResult {\n status: InstallReferrerStatus;\n /** True when a later launch could still produce a referrer (Play was busy/hung). */\n retryable: boolean;\n /** The raw referrer string, e.g. \"utm_source=meta&traq_click=abc123\". */\n referrer?: string;\n /** Unix seconds \u2014 when the ad click happened, per Play. */\n referrerClickTs?: number;\n /** Unix seconds \u2014 when the install began, per Play. */\n installBeginTs?: number;\n googlePlayInstant?: boolean;\n}\n\nexport interface NativeBridge {\n platform: \"ios\" | \"android\";\n /** Android: reads the Play Install Referrer. Never rejects \u2014 failure is a status. */\n getInstallReferrer(): Promise<InstallReferrerResult>;\n /** Optional native device context (model, OS version). */\n getContext?(): Promise<{ deviceModel?: string; osVersion?: string }>;\n /** iOS: hand a SKAdNetwork conversion value to the device. No-op on Android. */\n updateConversionValue?(fineValue: number, coarse?: CoarseValue, lockWindow?: boolean): void;\n /**\n * iOS 14.3+: the AdServices attribution token (Apple Ads self-attribution).\n * Resolves null when the framework has none on this device \u2014 which is the case for\n * most installs, since most installs are not Apple Search Ads. Absent on Android.\n */\n getAttributionToken?(): Promise<string | null>;\n /**\n * The device advertising id (IDFA / GAID), or null. Called ONLY when the host set\n * `collectAdvertisingId: true`. It NEVER prompts: on iOS it answers only when the\n * app itself already obtained ATT, on Android only when the app ships Google's\n * ads-identifier library and declares the AD_ID permission. Decision cmvjohk6.\n */\n getAdvertisingId?(): Promise<string | null>;\n}\n\n/** One AdMob paid event, as handed to the app by `OnPaidEventListener`. */\nexport interface AdRevenue {\n /** `AdValue.getValueMicros()` \u2014 millionths of `currency`. Never pre-round it. */\n valueMicros: number;\n /** `AdValue.getCurrencyCode()` \u2014 ISO 4217. */\n currency: string;\n /** `AdValue.getPrecisionType()`. ESTIMATED is the normal case, and still real money. */\n precision?: \"unknown\" | \"estimated\" | \"publisher_provided\" | \"precise\";\n adUnitId?: string;\n adFormat?: \"banner\" | \"interstitial\" | \"rewarded\" | \"rewarded_interstitial\" | \"native\" | \"app_open\";\n /** Mediation ad source that filled it (`ResponseInfo.getLoadedAdapterResponseInfo()`). */\n adSourceName?: string;\n /** Unix seconds. Defaults to now. */\n ts?: number;\n}\n\n/**\n * The store a purchase went through, spelled the way the server's revenue key\n * spells it (`apps/api/src/revenuecat/revenue-key.ts`). It is part of the key, so\n * the same transaction id from two stores can never collide.\n */\nexport type RevenueStore = \"app_store\" | \"play_store\" | \"mac_app_store\" | \"amazon\" | \"stripe\";\n\n/** What `track()` accepts beside the event name. */\nexport interface TrackProps {\n /** Revenue DECLARED by the app. The SDK does not verify it against any receipt. */\n value?: number;\n currency?: string;\n /**\n * The STORE's id for this purchase \u2014 StoreKit's `transactionId`, Play Billing's\n * `orderId` (GPA.\u2026). With it, the server keys the event on the SAME deterministic\n * id RevenueCat / App Store Server Notifications / Play RTDN produce for that\n * transaction, so the purchase is counted once however many of them report it.\n * Without it, a purchase also reported server-side is counted twice.\n */\n transactionId?: string;\n /** Defaults to the platform's store (`app_store` on iOS, `play_store` on Android). */\n store?: RevenueStore;\n}\n\nexport interface InitOptions {\n sdkKey: string;\n endpoint: string; // origin only, no path \u2014 the SDK posts to `${endpoint}/ingest`\n /** Host-provided persistence (e.g. AsyncStorage) so the queue + install flag survive restarts. */\n storage?: KeyValueStore;\n /** Native bridge; on Android this reads the Install Referrer. */\n native?: NativeBridge;\n /** Your user id \u2014 set the SAME value as RevenueCat's app_user_id for revenue matching. */\n userId?: string;\n /** Your app's version string (host provides it). */\n appVersion?: string;\n /** Collect basic, non-fingerprinting device context (default true). Never IDFA/GAID. */\n collectContext?: boolean;\n /**\n * Set true while the app serves AdMob TEST ad units. Ad revenue is then logged\n * by the API (so you can see the pipe working) but never counted as revenue \u2014\n * test impressions are not money.\n */\n testAds?: boolean;\n /**\n * iOS only. Drive the SKAdNetwork conversion value from tracked revenue and\n * events, using the mapping published for this app (fetched from the API).\n * Default true \u2014 on Android and without a native bridge it is inert.\n *\n * SKAN is aggregated, coarse (six bits) and delayed 24h+ by design; this makes\n * iOS measurable, not deterministic. See docs/IOS_ATTRIBUTION.md.\n */\n skan?: boolean;\n /**\n * iOS only. Report the AdServices attribution token so the server can resolve\n * Apple Ads (Search Ads) attribution. Default true \u2014 on Android, pre-iOS 14.3 and\n * without a native bridge it is inert.\n *\n * This is the ONE deterministic attribution iOS allows, and it needs no IDFA and no\n * ATT prompt of our own: the token is an opaque 24h claim ticket, and Apple decides\n * how detailed an answer to give from the ATT status the user already chose. See\n * adservices.ts.\n */\n appleAds?: boolean;\n /**\n * Send the device advertising id (IDFA / GAID) with the install. Default FALSE \u2014\n * Traqio collects nothing of the kind unless you turn this on (decision cmvjohk6).\n *\n * It improves attribution precision for the networks that attribute by that id\n * and nothing else \u2014 Unity Ads and AppLovin: their click carries it, and the install\n * postback Unity expects needs it. It is never used as the user's identity.\n *\n * The SDK never shows a permission prompt. iOS: ask for App Tracking Transparency\n * yourself BEFORE `init()` (as AppLovin MAX recommends); the IDFA is read only if\n * the user said yes. Android: add `com.google.android.gms:play-services-ads-identifier`\n * and the `com.google.android.gms.permission.AD_ID` permission to your app.\n */\n collectAdvertisingId?: boolean;\n /**\n * Deep linking (docs/DEEP_LINKING.md). Default true.\n *\n * On the first launch of a fresh install, asks once where the link that brought\n * the user wanted them to land, and hands it to `onDeepLink`. On React Native it\n * also listens to `Linking` for universal / App Links that open the app; every\n * other host passes those URLs to `handleUrl()`.\n */\n deepLinking?: boolean;\n /**\n * The user's consent to SHARING with ad networks, when the app already knows it\n * at launch \u2014 see `setConsent()`. Omitted = unchanged (never collected, or the\n * answer persisted by an earlier `setConsent`).\n */\n consent?: boolean;\n /**\n * `\"web\"` = a browser (used by `@traqio/web`). A browser is not an install: no\n * install is reported, no Install Referrer is read and no deferred deep link is\n * asked for. The first visit of the day is a session like any other (debounced,\n * since a multi-page site re-runs `init()` on every page), and requests are sent\n * with `keepalive` so a flush on `pagehide` survives the page being torn down.\n * Omitted = an app: everything above behaves exactly as before.\n */\n platform?: \"web\";\n /**\n * Host-provided app lifecycle. Called once from `init()` with the two handlers;\n * the host invokes `background()` when the app/tab is hidden (the queue is\n * flushed) and `foreground()` when it comes back (a session, debounced by the\n * 30-minute timeout). Omitted = React Native's `AppState`, when present.\n */\n lifecycle?: (events: LifecycleEvents) => void;\n}\n\n/** What `InitOptions.lifecycle` is handed. */\nexport interface LifecycleEvents {\n background(): void;\n foreground(): void;\n}\n\nexport type { DeepLinkAnswer };\n\ninterface QueuedEvent {\n name: string;\n /**\n * A random id: it only makes the SDK's own retries idempotent. When the event\n * carries `transactionId`, the server replaces it with the transaction's\n * deterministic key before anything is stored or forwarded.\n */\n eventId: string;\n value?: number;\n currency?: string;\n transactionId?: string;\n store?: RevenueStore;\n}\n\n/** The ad platform a queued impression came from \u2014 the server's `source`. */\ntype AdRevenueSource = \"admob\" | \"applovin_max\";\n\ninterface QueuedAdImpression extends AdRevenue {\n impressionId: string;\n /** Absent on impressions persisted before MAX support: those are AdMob's. */\n source?: AdRevenueSource;\n}\n\n/**\n * One AppLovin MAX impression, as `onAdRevenuePaid(MaxAd ad)` describes it.\n * Docs: https://support.applovin.com/en/max/android/overview/advanced-settings\n */\nexport interface MaxAdRevenue {\n /** `ad.getRevenue()` \u2014 in USD. MAX answers -1 when it has no value. */\n revenue: number;\n /** `ad.getRevenuePrecision()`: \"exact\" | \"publisher_defined\" | \"estimated\" | \"undefined\" | \"\". */\n revenuePrecision?: string;\n /** `ad.getAdUnitId()`. */\n adUnitId?: string;\n /** `ad.getFormat().getLabel()` \u2014 \"BANNER\", \"INTER\", \"REWARDED\", \"MREC\", \"NATIVE\", \"APPOPEN\"\u2026 */\n format?: string;\n /** `ad.getNetworkName()` \u2014 the mediated network that filled the impression. */\n networkName?: string;\n /** Unix seconds. Defaults to now. */\n ts?: number;\n}\n\nconst MAX_PRECISION: Record<string, AdRevenue[\"precision\"]> = {\n exact: \"precise\",\n publisher_defined: \"publisher_provided\",\n estimated: \"estimated\",\n};\n\nconst MAX_FORMAT: Record<string, AdRevenue[\"adFormat\"]> = {\n BANNER: \"banner\",\n LEADER: \"banner\",\n MREC: \"banner\",\n INTER: \"interstitial\",\n INTERSTITIAL: \"interstitial\",\n REWARDED: \"rewarded\",\n REWARDED_INTER: \"rewarded_interstitial\",\n NATIVE: \"native\",\n APPOPEN: \"app_open\",\n APP_OPEN: \"app_open\",\n};\n\n/**\n * MAX \u2192 the server's impression shape. Undefined for an impression with no\n * usable revenue (MAX's -1), which is skipped rather than recorded as zero.\n */\nconst ZERO_AD_ID = \"00000000-0000-0000-0000-000000000000\";\n\n/** A real IDFA / GAID, or undefined: the all-zeros id means the OS withheld it. */\nexport function normalizeAdvertisingId(raw: unknown): string | undefined {\n if (typeof raw !== \"string\") return undefined;\n const id = raw.trim();\n if (!/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(id)) return undefined;\n return id === ZERO_AD_ID ? undefined : id;\n}\n\nexport function fromMaxAd(ad: MaxAdRevenue): AdRevenue | undefined {\n if (!(typeof ad.revenue === \"number\" && Number.isFinite(ad.revenue) && ad.revenue >= 0)) return undefined;\n return {\n // Rounded to the micro, never earlier: a banner is worth ~0.00002 USD.\n valueMicros: Math.round(ad.revenue * 1_000_000),\n currency: \"USD\",\n precision: MAX_PRECISION[ad.revenuePrecision ?? \"\"] ?? \"unknown\",\n adUnitId: ad.adUnitId,\n adFormat: MAX_FORMAT[(ad.format ?? \"\").toUpperCase()],\n adSourceName: ad.networkName,\n ts: ad.ts,\n };\n}\n\n// The batch id travels WITH the queue: if the app is killed between \"request sent\"\n// and \"response received\", the retry must reuse the same id or the server counts\n// the revenue twice.\ninterface PersistedAdQueue {\n batchId: string | null;\n items: QueuedAdImpression[];\n}\n\nfunction uuid(): string {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\nfunction safeLocale(): string | undefined {\n try {\n return Intl.DateTimeFormat().resolvedOptions().locale;\n } catch {\n return undefined;\n }\n}\n\n// Persistence is what makes the install fire exactly once and keeps queued events\n// across a kill. A host that forgets to pass `storage` would silently re-send the\n// install at every launch, so we pick up AsyncStorage when the app has it.\nfunction defaultStorage(): KeyValueStore | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const mod = require(\"@react-native-async-storage/async-storage\");\n const store = mod?.default ?? mod;\n if (typeof store?.getItem === \"function\" && typeof store?.setItem === \"function\") {\n return {\n getItem: (key) => store.getItem(key),\n setItem: (key, value) => store.setItem(key, value),\n };\n }\n } catch {\n // Not installed (or not React Native) \u2014 caller must pass `storage`.\n }\n return undefined;\n}\n\nexport class Client {\n private opts!: Required<Pick<InitOptions, \"collectContext\">> & InitOptions;\n private queue: QueuedEvent[] = [];\n private adQueue: QueuedAdImpression[] = [];\n private adBatchId: string | null = null;\n private context: DeviceContext = { sdkVersion: SDK_VERSION };\n private referrer: InstallReferrerResult | null = null;\n private started = false;\n private flushing = false;\n private flushTimer: ReturnType<typeof setTimeout> | null = null;\n private retryMs = BASE_RETRY_MS;\n private skan = new Skan();\n private erased = false;\n private deepLinkListeners = new Set<(link: DeepLink) => void>();\n // Links resolved before anyone subscribed \u2014 a cold start resolves the opening\n // URL before the app has mounted the screen that registers `onDeepLink`.\n private undelivered: DeepLink[] = [];\n private deferred: Promise<DeepLink | null> | null = null;\n private consent: \"granted\" | \"denied\" | null = null;\n\n async init(opts: InitOptions): Promise<void> {\n if (this.started) return; // idempotent\n this.started = true;\n this.opts = { collectContext: true, ...opts, storage: opts.storage ?? defaultStorage() };\n if (!this.opts.storage) {\n // Loud on purpose: without it the install is re-sent at every launch.\n console.warn(\n \"[traqio] no storage available \u2014 pass `storage` to init() or install \" +\n \"@react-native-async-storage/async-storage, otherwise the install is re-sent at every launch.\",\n );\n }\n await this.restoreConsent(opts.consent);\n await this.restoreQueue();\n await this.restoreAdQueue();\n await this.buildContext();\n // A device that asked to be forgotten stays forgotten across launches. Checked\n // before anything is sent: the install, the SKAN mapping fetch and the\n // AdServices token all carry this device's identity to the server.\n if (await this.restoreErased()) return;\n // Read BEFORE the install is marked sent: only a fresh install may ask for a\n // deferred link. An existing user updating to this SDK version must not be\n // routed by somebody else's click from the same address.\n // A browser is not an install and has no store to defer a link through: the\n // whole install / Install Referrer / deferred-link path is for apps only.\n if (!this.isWeb) {\n const freshInstall = Boolean(this.opts.storage) && !(await this.opts.storage!.getItem(INSTALL_SENT_KEY).catch(() => \"1\"));\n await this.sendInstallOnce();\n if (this.opts.deepLinking !== false) {\n this.deferred = this.resolveDeferredOnce(freshInstall);\n this.wireDeepLinks();\n }\n }\n // App: always, not debounced \u2014 init() means the app was opened, and the first\n // open of a day is the one the whole retention number rests on. Web: debounced,\n // because a multi-page site calls init() on every page load. After the erasure\n // check above, because a forgotten device must not report opens either.\n await this.maybeStartSession(!this.isWeb);\n await this.initSkan();\n await this.initAppleAds();\n this.wireLifecycle();\n if (this.queue.length || this.adQueue.length) this.scheduleFlush(0);\n }\n\n track(name: string, props?: TrackProps): void {\n if (!this.started || this.erased) return; // call init() first\n const transactionId = props?.transactionId?.trim() || undefined;\n this.enqueue({\n name,\n eventId: uuid(),\n value: props?.value,\n currency: props?.currency,\n ...(transactionId ? { transactionId, store: props?.store ?? this.defaultStore() } : {}),\n });\n // Same event, second job: on iOS it also moves the SKAN conversion value. Kept\n // for EVERY valued event, keyed or not: the conversion value must be set before\n // Apple's window closes, and a server webhook arrives too late for that. What\n // the transaction id changes is the event's place in the revenue TOTAL, never\n // this on-device signal.\n this.skan.markEvent(name);\n if (props?.value) this.skan.addRevenue(props.value);\n }\n\n private defaultStore(): RevenueStore | undefined {\n const platform = this.opts.native?.platform;\n return platform === \"ios\" ? \"app_store\" : platform === \"android\" ? \"play_store\" : undefined;\n }\n\n /**\n * Report one AdMob impression's revenue. Call it from the paid-event callback:\n *\n * ad.setOnPaidEventListener(v => Traqio.trackAdRevenue({\n * valueMicros: v.valueMicros, currency: v.currencyCode, precision: \"estimated\",\n * adUnitId, adFormat: \"rewarded\", adSourceName,\n * }));\n *\n * Impressions are batched and sent to /ingest/ad-revenue, where they are matched\n * to this install and become the ad half of ROAS.\n */\n trackAdRevenue(ad: AdRevenue): void {\n this.queueAdRevenue(ad, \"admob\");\n }\n\n /**\n * Report one AppLovin MAX impression's revenue. Call it from MAX's callback:\n *\n * onAdRevenuePaid(ad) { Traqio.trackMaxAdRevenue({\n * revenue: ad.getRevenue(), revenuePrecision: ad.getRevenuePrecision(),\n * adUnitId: ad.getAdUnitId(), format: ad.getFormat().getLabel(),\n * networkName: ad.getNetworkName(),\n * }); }\n *\n * Same batching, same endpoint and same ROAS numerator as AdMob, filed under\n * the `applovin_max` source.\n */\n trackMaxAdRevenue(ad: MaxAdRevenue): void {\n const converted = fromMaxAd(ad);\n if (converted) this.queueAdRevenue(converted, \"applovin_max\");\n }\n\n private queueAdRevenue(ad: AdRevenue, source: AdRevenueSource): void {\n if (!this.started || this.erased) return; // call init() first\n if (!(ad.valueMicros >= 0) || !ad.currency) return; // nothing to bill\n this.adQueue.push({ ...ad, source, impressionId: uuid(), ts: ad.ts ?? Math.floor(Date.now() / 1000) });\n // Ad revenue is revenue: it feeds the iOS conversion value like a purchase\n // does. Assumed to be in the mapping's currency \u2014 SKAN carries none, so a\n // mixed-currency app should map its buckets in the currency it reports.\n this.skan.addRevenue(ad.valueMicros / 1_000_000);\n if (this.adQueue.length > MAX_AD_QUEUE) this.adQueue.splice(0, this.adQueue.length - MAX_AD_QUEUE);\n void this.persistAdQueue();\n this.scheduleFlush();\n }\n\n /**\n * The Play Install Referrer for this install \u2014 the raw string your tracking link\n * put there, so a host app can use it for deferred deep linking on top of the\n * attribution we already do server-side. Resolves from cache after the first read\n * (Play only serves it reliably once). On iOS it reports\n * `not_supported_platform`; attribution there is SKAN.\n */\n getInstallReferrer(): Promise<InstallReferrerResult> {\n if (!this.started) return Promise.resolve({ status: \"unavailable\", retryable: false });\n return this.readReferrer();\n }\n\n /**\n * Subscribe to deep links \u2014 direct opens AND the one deferred link of a fresh\n * install. Links resolved before the first subscriber are delivered to it on\n * subscription, so a cold start does not lose the link that opened the app.\n *\n * Traqio.onDeepLink(({ deepLink }) => { if (deepLink) router.push(deepLink); });\n *\n * Returns the unsubscribe function.\n */\n onDeepLink(listener: (link: DeepLink) => void): () => void {\n this.deepLinkListeners.add(listener);\n const pending = this.undelivered.splice(0);\n for (const link of pending) listener(link);\n return () => {\n this.deepLinkListeners.delete(listener);\n };\n }\n\n /**\n * A URL opened the app. React Native is wired automatically (`Linking`); every\n * other host (Capacitor's `appUrlOpen`, a native shell) calls this.\n *\n * Only our tracking URLs (`https://<host>/c/<code>`) leave the device; the\n * app's own URLs resolve to null without a request. Resolving also records\n * the click, which the OS skipped by opening the app directly.\n */\n async handleUrl(url: string): Promise<DeepLink | null> {\n if (!this.started || this.erased || this.opts.deepLinking === false || !isTrackingUrl(url)) return null;\n const answer = await this.postJson<DeepLinkAnswer>({ url }, \"/deeplink/open\");\n const link = toDeepLink(answer, false, url);\n if (link) this.emitDeepLink(link);\n return link;\n }\n\n /**\n * The deferred deep link of this install, if it came from one \u2014 resolved once,\n * on the first launch, and remembered. Null on every install that did not\n * come from a link (and on iOS unless the IP match is on for this app).\n */\n getDeferredDeepLink(): Promise<DeepLink | null> {\n return this.deferred ?? Promise.resolve(null);\n }\n\n /**\n * GDPR Art. 17, from inside the app: delete everything the server holds about this\n * device and this user, and stop sending.\n *\n * \u26A0\uFE0F IRREVERSIBLE, on both sides. The server deletes the installs, events, clicks\n * and delivery payloads that name this subject and tombstones their identifiers,\n * so nothing this device sends afterwards is accepted. Locally the queue is\n * dropped and the SDK goes quiet for good \u2014 persisted, so the next launch does not\n * re-report the install. There is no way back on: an app that needs measurement\n * again has to be reinstalled.\n *\n * Wire it to your own \"delete my data\" control. Returns false when the call did\n * not reach the server, and in that case NOTHING has changed on either side \u2014 show\n * the user an error and let them try again, rather than a confirmation of a\n * deletion that did not happen.\n */\n async forgetMe(): Promise<boolean> {\n if (!this.started) return false;\n if (this.erased) return true; // already honoured \u2014 saying \"yes\" twice is correct\n const ok = await this.post(\n { deviceId: this.context.deviceId, appUserId: this.opts.userId },\n \"/privacy/forget\",\n );\n if (!ok) return false;\n await this.markErased();\n return true;\n }\n\n /**\n * The user's consent to SHARING their data with ad networks, as collected by the\n * app's own prompt \u2014 Traqio is not a CMP. Persisted, and sent with every install,\n * event batch and session from now on, events already queued included.\n *\n * `false` keeps first-party measurement (installs, events, retention and ROAS in\n * your dashboard), but the server forwards nothing about this device to Meta,\n * TikTok or any outbound postback. Never calling it = not collected: the app's\n * policy in the console decides (docs/PRIVACY.md \u00A7Consent).\n *\n * Traqio.setConsent(userAgreed);\n */\n async setConsent(granted: boolean): Promise<void> {\n this.consent = granted ? \"granted\" : \"denied\";\n await this.opts?.storage?.setItem(CONSENT_KEY, this.consent).catch(() => undefined);\n }\n\n /** True once `forgetMe()` has been honoured \u2014 this install sends nothing any more. */\n get forgotten(): boolean {\n return this.erased;\n }\n\n /** Set/override the user id (== RevenueCat app_user_id). Call after login. */\n setUserId(id: string): void {\n if (this.opts) this.opts.userId = id;\n }\n\n /** Force a flush now (e.g. on app background). RN wires this automatically. */\n flush(): void {\n if (this.erased) return;\n // NOW, even when a batching or back-off timer is already pending, and in this\n // very call stack: a host calls this because the app or tab is going away. A\n // timer \u2014 even a 0 ms one \u2014 may never run inside a `pagehide` handler, whereas\n // drain() starts its first request before its first await.\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n void this.drain();\n }\n\n /**\n * Tell the SDK the app came back to the foreground. React Native is wired\n * automatically; every other host (a web view, a game loop, a custom shell) has\n * to call this or its users look like they never came back.\n *\n * Safe to call on every resume: it is debounced by the session timeout.\n */\n appOpened(): void {\n if (!this.started || this.erased) return;\n void this.maybeStartSession();\n }\n\n /** The conversion-value mapping in force on this device, once fetched. */\n get skanMapping(): SkanMapping | null {\n return this.skan.activeMapping;\n }\n\n /**\n * Apple Ads self-attribution. Awaited rather than fired off, so a host that awaits\n * `init()` can be sure the token left the device before the app does anything\n * else \u2014 the window is 24 hours, but a user who installs from a Search Ads tap and\n * never reopens the app still has to be attributed.\n */\n private async initAppleAds(): Promise<void> {\n if (this.opts.appleAds === false) return;\n const native = this.opts.native;\n if (native?.platform !== \"ios\" || !native.getAttributionToken) return;\n await reportAdServicesToken({\n endpoint: this.opts.endpoint,\n sdkKey: this.opts.sdkKey,\n deviceId: this.context.deviceId,\n userId: this.opts.userId,\n storage: this.opts.storage,\n native: { getAttributionToken: () => native.getAttributionToken!() },\n });\n }\n\n private async initSkan(): Promise<void> {\n if (this.opts.skan === false) return;\n const native = this.opts.native;\n // iOS-only, and only when the native module is actually there to call.\n if (native?.platform !== \"ios\" || !native.updateConversionValue) return;\n await this.skan.init({\n endpoint: this.opts.endpoint,\n sdkKey: this.opts.sdkKey,\n storage: this.opts.storage,\n native: {\n updateConversionValue: (fine, coarse, lockWindow) =>\n native.updateConversionValue?.(fine, coarse, lockWindow),\n },\n });\n }\n\n /**\n * Asks `/deeplink/deferred` once per install. A settled answer \u2014 link or no\n * link \u2014 is persisted; a failed request is not, so the next launch retries\n * (still counted as fresh, since the flag is only written on an answer).\n */\n private async resolveDeferredOnce(freshInstall: boolean): Promise<DeepLink | null> {\n const store = this.opts.storage;\n try {\n const cached = await store?.getItem(DEFERRED_KEY);\n if (cached) return JSON.parse(cached) as DeepLink | null;\n } catch {\n /* corrupt \u2014 ask again if still a fresh install */\n }\n if (!freshInstall && !(await store?.getItem(`${DEFERRED_KEY}_pending`).catch(() => null))) return null;\n\n const platform = this.opts.native?.platform ?? \"android\";\n const referrer = platform === \"android\" ? await this.readReferrer() : null;\n await store?.setItem(`${DEFERRED_KEY}_pending`, \"1\").catch(() => undefined);\n const answer = await this.postJson<DeepLinkAnswer>(\n { platform, installReferrer: referrer?.referrer },\n \"/deeplink/deferred\",\n );\n if (!answer) return null; // unreachable \u2014 the pending flag makes the next launch retry\n const link = toDeepLink(answer, true);\n try {\n await store?.setItem(DEFERRED_KEY, JSON.stringify(link));\n } catch {\n /* storage full \u2014 worst case the next launch asks again */\n }\n if (link) this.emitDeepLink(link);\n return link;\n }\n\n private emitDeepLink(link: DeepLink): void {\n if (!this.deepLinkListeners.size) {\n this.undelivered.push(link);\n return;\n }\n for (const listener of this.deepLinkListeners) {\n try {\n listener(link);\n } catch {\n /* a throwing listener must not stop the others */\n }\n }\n }\n\n private wireDeepLinks(): void {\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { Linking } = require(\"react-native\");\n if (!Linking) return;\n void Linking.getInitialURL().then((url: string | null) => url && this.handleUrl(url)).catch(() => undefined);\n Linking.addEventListener(\"url\", ({ url }: { url: string }) => void this.handleUrl(url));\n } catch {\n // Not React Native \u2014 the host calls Traqio.handleUrl(url).\n }\n }\n\n private get isWeb(): boolean {\n return this.opts?.platform === \"web\";\n }\n\n private wireLifecycle(): void {\n const events: LifecycleEvents = {\n background: () => this.flush(),\n // Debounced by SESSION_TIMEOUT_MS inside, so a flick to another app/tab and\n // straight back posts nothing.\n foreground: () => this.appOpened(),\n };\n if (this.opts.lifecycle) {\n this.opts.lifecycle(events);\n return;\n }\n try {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const { AppState } = require(\"react-native\");\n AppState.addEventListener(\"change\", (state: string) => {\n if (state !== \"active\") {\n this.scheduleFlush(0);\n return;\n }\n // Back in the foreground. Debounced by SESSION_TIMEOUT_MS inside, so a\n // flick to another app and straight back posts nothing.\n void this.maybeStartSession();\n });\n } catch {\n // Not React Native \u2014 host can call Traqio.flush() manually.\n }\n }\n\n // \u2500\u2500 internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Reads the persisted erasure flag. True \u21D2 this install must stay silent. */\n private async restoreErased(): Promise<boolean> {\n try {\n this.erased = (await this.opts.storage?.getItem(ERASED_KEY)) === \"1\";\n } catch {\n // Storage unreadable: assume not erased. The server's tombstone is the real\n // enforcement \u2014 this flag only saves the round trip.\n this.erased = false;\n }\n return this.erased;\n }\n\n /** Local half of forgetMe(): drop what is queued and never send again. */\n private async markErased(): Promise<void> {\n this.erased = true;\n if (this.flushTimer) {\n clearTimeout(this.flushTimer);\n this.flushTimer = null;\n }\n // The queue holds events about the person who just asked to be forgotten;\n // flushing it later would post them to a server that would drop them anyway.\n this.queue = [];\n this.adQueue = [];\n this.adBatchId = null;\n await this.persistQueue();\n await this.persistAdQueue();\n try {\n await this.opts.storage?.setItem(ERASED_KEY, \"1\");\n } catch {\n /* storage full/unavailable \u2014 the in-memory flag still holds for this run */\n }\n }\n\n private enqueue(e: QueuedEvent) {\n this.queue.push(e);\n if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE);\n void this.persistQueue();\n this.scheduleFlush();\n }\n\n private async restoreQueue() {\n try {\n const raw = await this.opts.storage?.getItem(QUEUE_KEY);\n if (raw) this.queue = JSON.parse(raw) as QueuedEvent[];\n } catch {\n /* corrupt/absent \u2014 start empty */\n }\n }\n\n private async persistQueue() {\n try {\n await this.opts.storage?.setItem(QUEUE_KEY, JSON.stringify(this.queue));\n } catch {\n /* storage full/unavailable */\n }\n }\n\n private async restoreAdQueue() {\n try {\n const raw = await this.opts.storage?.getItem(AD_QUEUE_KEY);\n if (!raw) return;\n const parsed = JSON.parse(raw) as PersistedAdQueue;\n this.adQueue = parsed.items ?? [];\n this.adBatchId = parsed.batchId ?? null;\n } catch {\n /* corrupt/absent \u2014 start empty */\n }\n }\n\n private async persistAdQueue() {\n try {\n const state: PersistedAdQueue = { batchId: this.adBatchId, items: this.adQueue };\n await this.opts.storage?.setItem(AD_QUEUE_KEY, JSON.stringify(state));\n } catch {\n /* storage full/unavailable */\n }\n }\n\n /**\n * Report one app open \u2014 the signal that makes \"did the user come back on day n\"\n * answerable at all (docs/SESSIONS.md).\n *\n * Called on `init()` (the app was opened) and on returning to the foreground\n * after `SESSION_TIMEOUT_MS`.\n *\n * NO QUEUE, deliberately. A failed post does NOT persist the marker, so the next\n * foreground retries it. The signal is only ever read at DAY granularity, so a\n * post lost at 09:00 is recovered by any open before midnight \u2014 a far smaller\n * failure than a persisted queue that can replay yesterday's sessions into today,\n * which would be a retention chart that invents its own history.\n */\n private async maybeStartSession(force = false): Promise<void> {\n if (this.erased) return;\n const now = Date.now();\n if (!force) {\n const last = Number(await this.opts.storage?.getItem(LAST_SESSION_KEY).catch(() => null)) || 0;\n if (last && now - last < SESSION_TIMEOUT_MS) return;\n }\n\n const deviceId = this.context.deviceId ?? (await this.getOrCreateDeviceId());\n const ok = await this.post(\n {\n deviceId,\n appUserId: this.opts.userId,\n sessionId: uuid(),\n ts: Math.floor(now / 1000),\n context: this.context,\n },\n \"/ingest/session\",\n );\n // Only on success: a marker written for a post that never landed would suppress\n // the retry and lose the day.\n if (ok) {\n try {\n await this.opts.storage?.setItem(LAST_SESSION_KEY, String(now));\n } catch {\n /* storage full/unavailable \u2014 worst case we post one extra session */\n }\n }\n }\n\n private async buildContext() {\n if (!this.opts.collectContext) {\n this.context = { sdkVersion: SDK_VERSION };\n return;\n }\n let native: { deviceModel?: string; osVersion?: string } = {};\n try {\n native = (await this.opts.native?.getContext?.()) ?? {};\n } catch {\n /* native context unavailable */\n }\n this.context = {\n deviceId: await this.getOrCreateDeviceId(),\n deviceModel: native.deviceModel,\n osVersion: native.osVersion,\n appVersion: this.opts.appVersion,\n locale: safeLocale(),\n sdkVersion: SDK_VERSION,\n };\n }\n\n private async getOrCreateDeviceId(): Promise<string> {\n try {\n const existing = await this.opts.storage?.getItem(DEVICE_ID_KEY);\n if (existing) return existing;\n } catch {\n /* ignore */\n }\n const id = uuid();\n try {\n await this.opts.storage?.setItem(DEVICE_ID_KEY, id);\n } catch {\n /* ignore */\n }\n return id;\n }\n\n /**\n * Reads the Play Install Referrer, once per install, and caches a settled answer.\n * A retryable failure is deliberately NOT cached \u2014 freezing it would make the\n * install look organic for good.\n */\n private async readReferrer(): Promise<InstallReferrerResult> {\n if (this.referrer) return this.referrer;\n try {\n const raw = await this.opts.storage?.getItem(REFERRER_KEY);\n if (raw) return (this.referrer = JSON.parse(raw) as InstallReferrerResult);\n } catch {\n /* corrupt/absent \u2014 read it again */\n }\n\n const native = this.opts.native;\n if (native?.platform !== \"android\") {\n return { status: native ? \"not_supported_platform\" : \"unavailable\", retryable: false };\n }\n const result = await native\n .getInstallReferrer()\n .catch((): InstallReferrerResult => ({ status: \"error\", retryable: true }));\n if (!result.retryable) {\n this.referrer = result;\n try {\n await this.opts.storage?.setItem(REFERRER_KEY, JSON.stringify(result));\n } catch {\n /* storage full/unavailable */\n }\n }\n return result;\n }\n\n /** Only with the host's opt-in; a zeroed or malformed id is never sent. */\n private async readAdvertisingId(): Promise<string | undefined> {\n if (!this.opts.collectAdvertisingId || !this.opts.native?.getAdvertisingId) return undefined;\n try {\n return normalizeAdvertisingId(await this.opts.native.getAdvertisingId());\n } catch {\n return undefined;\n }\n }\n\n private async sendInstallOnce() {\n const store = this.opts.storage;\n if (store && (await store.getItem(INSTALL_SENT_KEY))) return; // already sent\n\n const platform = this.opts.native?.platform ?? \"android\";\n const referrer = await this.readReferrer();\n\n // The referrer IS the Android attribution. When Play couldn't serve it yet\n // (store updating itself, service still starting), reporting now would brand\n // the install organic forever \u2014 so we wait for a later launch instead. Bounded:\n // a device where it never works still gets its install counted.\n if (referrer.retryable && store) {\n const attempts = Number(await store.getItem(INSTALL_ATTEMPTS_KEY)) || 0;\n if (attempts + 1 < MAX_INSTALL_ATTEMPTS) {\n await store.setItem(INSTALL_ATTEMPTS_KEY, String(attempts + 1));\n return;\n }\n }\n\n const ok = await this.post({\n install: {\n platform,\n installReferrer: referrer.referrer,\n appUserId: this.opts.userId,\n advertisingId: await this.readAdvertisingId(),\n context: this.context,\n },\n });\n // Only mark sent on success \u2014 otherwise it retries on the next init().\n if (ok) await store?.setItem(INSTALL_SENT_KEY, \"1\");\n }\n\n private scheduleFlush(delay = FLUSH_DELAY_MS) {\n if (this.flushTimer) return;\n this.flushTimer = setTimeout(() => {\n this.flushTimer = null;\n void this.drain();\n }, delay);\n }\n\n private async drain() {\n if (this.erased) return;\n if (this.flushing || (!this.queue.length && !this.adQueue.length)) return;\n this.flushing = true;\n try {\n while (this.queue.length) {\n const batch = this.queue.slice(0, MAX_BATCH);\n // Identity travels with every batch, not just the install: the API forwards\n // these events to Meta/TikTok, and both REJECT an event that carries no user\n // identifier. Still first-party only \u2014 deviceId is our own random id, and the\n // API hashes whatever it forwards. Never IDFA/GAID.\n const ok = await this.post({\n events: batch,\n appUserId: this.opts.userId,\n deviceId: this.context.deviceId,\n });\n if (!ok) return this.backOff();\n this.queue.splice(0, batch.length);\n await this.persistQueue();\n this.retryMs = BASE_RETRY_MS;\n }\n while (this.adQueue.length) {\n // One batch = one platform: the server files a whole batch under one source.\n const source = this.adQueue[0].source ?? \"admob\";\n const run = this.adQueue.findIndex((i) => (i.source ?? \"admob\") !== source);\n const batch = this.adQueue.slice(0, Math.min(MAX_AD_BATCH, run === -1 ? this.adQueue.length : run));\n // Mint the batch id BEFORE the request and persist it, so a crash mid-flight\n // retries under the same id and the server dedups instead of double-counting.\n if (!this.adBatchId) {\n this.adBatchId = uuid();\n await this.persistAdQueue();\n }\n const ok = await this.post(\n {\n batchId: this.adBatchId,\n source,\n environment: this.opts.testAds ? \"TEST\" : \"PRODUCTION\",\n deviceId: this.context.deviceId,\n appUserId: this.opts.userId,\n impressions: batch.map(({ source: _source, ...impression }) => impression),\n },\n \"/ingest/ad-revenue\",\n );\n if (!ok) return this.backOff();\n this.adQueue.splice(0, batch.length);\n this.adBatchId = null;\n await this.persistAdQueue();\n this.retryMs = BASE_RETRY_MS;\n }\n } finally {\n this.flushing = false;\n }\n }\n\n // network/server failure \u2192 keep the queue, back off, retry later.\n private backOff(): void {\n this.retryMs = Math.min(this.retryMs * 2, MAX_RETRY_MS);\n this.scheduleFlush(this.retryMs);\n }\n\n /** Like `post`, for the two calls whose ANSWER matters. Null on any failure. */\n private async postJson<T>(body: Record<string, unknown>, path: string): Promise<T | null> {\n try {\n const res = await fetch(`${this.opts.endpoint}${path}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body }),\n ...this.keepalive(),\n });\n return res.ok ? ((await res.json()) as T) : null;\n } catch {\n return null;\n }\n }\n\n /**\n * The init option wins over what is stored (it is the app's current answer); a\n * `setConsent()` made before `init()` survives too \u2014 it is only kept in memory\n * until there is a storage to write it to.\n */\n private async restoreConsent(fromInit: boolean | undefined): Promise<void> {\n if (fromInit !== undefined) return this.setConsent(fromInit);\n if (this.consent) return this.setConsent(this.consent === \"granted\");\n const stored = await this.opts.storage?.getItem(CONSENT_KEY).catch(() => null);\n if (stored === \"granted\" || stored === \"denied\") this.consent = stored;\n }\n\n /**\n * Web only: a request started on `pagehide` is otherwise cancelled with the page.\n * Not set for apps \u2014 their fetch is not torn down, and the request stays as it was.\n */\n private keepalive(): { keepalive?: boolean } {\n return this.isWeb ? { keepalive: true } : {};\n }\n\n private async post(body: Record<string, unknown>, path = \"/ingest\"): Promise<boolean> {\n // Read at SEND time, so a batch queued before a \"no\" goes out under the \"no\".\n const consent = this.consent && (path === \"/ingest\" || path === \"/ingest/session\") ? { consent: this.consent } : {};\n try {\n const res = await fetch(`${this.opts.endpoint}${path}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body, ...consent }),\n ...this.keepalive(),\n });\n return res.ok;\n } catch {\n return false;\n }\n }\n}\n\nexport const Traqio = new Client();\n", "// @traqio/web \u2014 the browser half of the Traqio web SDK.\n//\n// One job above all: keep the trackID (the ad click id Traqio's tracking link puts in\n// the landing URL as `traq_click`) from the landing page to the conversion, in\n// first-party storage, so the conversion can be tied to its click deterministically.\n// Around it: web events and visits, sent through the same engine as the mobile SDKs\n// (@traqio/core, bundled in), with consent and erasure.\n//\n// One package for every framework: it is plain JS with no UI, and a framework only\n// decides WHERE `init()` is called. SSR-safe: nothing touches `window` or `document`\n// at import time, and `init()` on a server is a no-op.\n//\n// What it deliberately does NOT do: report an install, or send the click id with an\n// event. A web key is public (it sits in the page), so it carries no attribution\n// authority \u2014 a conversion is tied to its click by the site's BACKEND, with a secret\n// key, reading the trackID this package kept (cookie `traq_click`, or `getTrackId()`).\nimport { Client } from \"@traqio/core\";\nimport { registrableDomain } from \"./cookies\";\nimport { BrowserStore, DEVICE_ID_KEY } from \"./storage\";\nimport { TrackIdKeeper } from \"./trackId\";\n\nexport const DEFAULT_ENDPOINT = \"https://api.traqio.app\";\nconst DEFAULT_TRACK_ID_DAYS = 30;\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\nexport interface WebInitOptions {\n /** The site's WEB key (`tq_web_\u2026`), from the console. Public by design: it is held to the site's origins. */\n sdkKey: string;\n /** Origin only, no path. Default `https://api.traqio.app`. */\n endpoint?: string;\n /** Your user id once known \u2014 the same id your backend sends with its conversions. */\n userId?: string;\n /**\n * The visitor's consent to SHARING with ad networks, if already known. Omitted =\n * not collected; the site's policy in the console decides.\n */\n consent?: boolean;\n /**\n * `true` = write nothing to the device (no localStorage, no cookie) until\n * `setConsent(true)`. The SDK still works for the current page, in memory. For\n * sites that must ask before storing anything (ePrivacy). Default `false`.\n */\n waitForConsent?: boolean;\n /**\n * How long the trackID is kept after the click, in days. Default 30. Keeping it\n * longer than the site's attribution window is harmless: the server refuses a\n * click outside the window.\n */\n trackIdDays?: number;\n /** `false` = never write a cookie, localStorage only (no sharing across subdomains). Default `true`. */\n cookies?: boolean;\n}\n\n/** What `track()` accepts beside the event name. */\nexport interface WebTrackProps {\n /** Revenue DECLARED by the page. Prefer sending purchases from your backend, where they are known. */\n value?: number;\n currency?: string;\n /** The payment's id at your processor (e.g. a Stripe payment intent): the purchase is then counted once. */\n transactionId?: string;\n /** Where the payment went through \u2014 `\"stripe\"` for Stripe. */\n store?: \"stripe\" | \"app_store\" | \"play_store\" | \"mac_app_store\" | \"amazon\";\n}\n\nfunction inBrowser(): boolean {\n return typeof window !== \"undefined\" && typeof document !== \"undefined\";\n}\n\nfunction randomId(): string | null {\n try {\n return typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\" ? crypto.randomUUID() : null;\n } catch {\n return null;\n }\n}\n\nexport class TraqioWeb {\n private readonly core = new Client();\n private store: BrowserStore | null = null;\n private trackIds: TrackIdKeeper | null = null;\n private waitForConsent = false;\n private started = false;\n /** A `setConsent()` made before `init()` \u2014 it decides whether init may store. */\n private earlyConsent: boolean | undefined;\n\n /**\n * Call once, as early as possible on every page (or once in a single-page app).\n * Reads the trackID from the current URL first, synchronously, so even a visitor\n * who leaves before the network answers keeps it. Safe to call on a server: it\n * does nothing there.\n */\n async init(opts: WebInitOptions): Promise<void> {\n if (this.started || !inBrowser()) return;\n this.started = true;\n this.waitForConsent = opts.waitForConsent === true;\n\n const cookies = opts.cookies !== false;\n let domain: string | null | undefined;\n // Probed lazily, once: it writes a test cookie, which must not happen before consent.\n const cookieDomain = (): string | null => (domain === undefined ? (domain = registrableDomain(location.hostname)) : domain);\n\n const consent = opts.consent ?? this.earlyConsent;\n const persistent = !this.waitForConsent || consent === true;\n this.store = new BrowserStore(persistent, cookieDomain, cookies);\n this.trackIds = new TrackIdKeeper(this.store, (opts.trackIdDays ?? DEFAULT_TRACK_ID_DAYS) * DAY_MS, cookieDomain, cookies);\n this.trackIds.capture(location.href);\n\n // A real random id rather than core's Math.random one, when the browser has it.\n // Seeded before core reads it; core keeps whatever is already there.\n if (!this.store.getSync(DEVICE_ID_KEY)) {\n const id = randomId();\n if (id) this.store.setSync(DEVICE_ID_KEY, id);\n }\n\n await this.core.init({\n sdkKey: opts.sdkKey,\n endpoint: (opts.endpoint ?? DEFAULT_ENDPOINT).replace(/\\/+$/, \"\"),\n storage: this.store,\n platform: \"web\",\n userId: opts.userId,\n consent,\n lifecycle: ({ background, foreground }) => {\n // `visibilitychange` is the last event a page reliably gets (tab switch,\n // close, navigation, mobile app switch); `pagehide` covers the bfcache.\n document.addEventListener(\"visibilitychange\", () => (document.visibilityState === \"hidden\" ? background() : foreground()));\n window.addEventListener(\"pagehide\", background);\n },\n });\n }\n\n /** Record an event \u2014 `signup`, `purchase`, `add_to_cart`\u2026 Batched, retried, kept across page loads. */\n track(name: string, props?: WebTrackProps): void {\n this.core.track(name, props);\n }\n\n /** Set the user id once known (after sign-in). */\n setUserId(id: string): void {\n this.core.setUserId(id);\n }\n\n /**\n * The visitor's consent answer. Governs sharing with ad networks, and \u2014 with\n * `waitForConsent` \u2014 whether anything may be stored: `true` writes out what the\n * page kept in memory (the trackID included), `false` removes everything this SDK\n * stored on the device.\n */\n async setConsent(granted: boolean): Promise<void> {\n if (!this.started) this.earlyConsent = granted;\n if (this.store && this.waitForConsent) {\n if (granted) {\n this.store.enable();\n this.trackIds?.persistCookie();\n } else {\n this.store.disable();\n }\n }\n await this.core.setConsent(granted);\n }\n\n /**\n * The trackID kept for this visitor, or null (no ad click, or expired). Pass it to\n * your backend with the sign-up or checkout \u2014 a hidden form field, a header \u2014 if\n * your backend cannot read the `traq_click` cookie itself.\n */\n getTrackId(): string | null {\n return this.trackIds?.get() ?? null;\n }\n\n /**\n * GDPR erasure from the page: the server deletes what it holds about this browser\n * and user, and this SDK stops sending and forgets the trackID. Irreversible.\n * Resolves false when the request did not reach the server \u2014 then nothing changed.\n */\n async forgetMe(): Promise<boolean> {\n const ok = await this.core.forgetMe();\n if (ok) this.trackIds?.clear();\n return ok;\n }\n\n /** Send what is queued now. Already wired to tab hide and page exit. */\n flush(): void {\n this.core.flush();\n }\n\n /** True once `forgetMe()` has been honoured: this browser sends nothing any more. */\n get forgotten(): boolean {\n return this.core.forgotten;\n }\n}\n\n/** The shared instance \u2014 `import { Traqio } from \"@traqio/web\"`. */\nexport const Traqio = new TraqioWeb();\n", "// First-party cookies, on the site's registrable domain when the browser allows it.\n//\n// Why a cookie at all, next to localStorage: localStorage is per ORIGIN, so a visitor\n// who lands on `www.example.com` and signs up on `app.example.com` would be two\n// strangers. A cookie on `example.com` is shared by both \u2014 and it reaches the site's\n// own backend with the sign-up request, which is how a server reads the trackID\n// without any JavaScript.\n\n/** Every cookie the SDK writes carries this prefix \u2014 the same namespace as the URL. */\nexport const COOKIE_PREFIX = \"traq_\";\n\nfunction doc(): Document | undefined {\n return typeof document === \"undefined\" ? undefined : document;\n}\n\nexport function readCookie(name: string): string | null {\n const d = doc();\n if (!d) return null;\n for (const part of d.cookie ? d.cookie.split(\";\") : []) {\n const eq = part.indexOf(\"=\");\n if (eq < 0) continue;\n if (part.slice(0, eq).trim() === name) {\n try {\n return decodeURIComponent(part.slice(eq + 1).trim());\n } catch {\n return null;\n }\n }\n }\n return null;\n}\n\nfunction serialize(name: string, value: string, maxAgeSeconds: number, domain: string | null): string {\n const secure = typeof location !== \"undefined\" && location.protocol === \"https:\" ? \"; Secure\" : \"\";\n const scope = domain ? `; Domain=${domain}` : \"\";\n return `${name}=${encodeURIComponent(value)}; Max-Age=${Math.floor(maxAgeSeconds)}; Path=/${scope}; SameSite=Lax${secure}`;\n}\n\n/**\n * The widest domain this page may set a cookie on \u2014 `example.co.uk` for\n * `shop.example.co.uk`. There is no public-suffix list in a browser, so ask the\n * browser itself: try the shortest candidates first, and keep the first one it\n * accepts (it refuses `co.uk`, a public suffix). Null on `localhost` and IP\n * addresses, where a host-only cookie is the only kind there is.\n */\nexport function registrableDomain(hostname: string): string | null {\n const d = doc();\n if (!d || !hostname.includes(\".\") || /^[\\d.]+$/.test(hostname) || hostname.includes(\":\")) return null;\n const labels = hostname.split(\".\");\n const probe = `${COOKIE_PREFIX}probe`;\n for (let i = labels.length - 2; i >= 0; i--) {\n const candidate = labels.slice(i).join(\".\");\n d.cookie = serialize(probe, \"1\", 10, candidate);\n if (readCookie(probe) === \"1\") {\n d.cookie = serialize(probe, \"\", 0, candidate);\n return candidate;\n }\n }\n return null;\n}\n\nexport function writeCookie(name: string, value: string, maxAgeSeconds: number, domain: string | null): void {\n const d = doc();\n if (!d) return;\n try {\n d.cookie = serialize(name, value, maxAgeSeconds, domain);\n } catch {\n /* cookies disabled \u2014 localStorage still holds it on this origin */\n }\n}\n\nexport function deleteCookie(name: string, domain: string | null): void {\n writeCookie(name, \"\", 0, domain);\n}\n", "import { COOKIE_PREFIX, deleteCookie, readCookie, writeCookie } from \"./cookies\";\n\n/**\n * Keys that are mirrored into a cookie on the registrable domain, so `www.` and\n * `app.` of the same site share them. Only identifiers \u2014 the event queue stays in\n * localStorage, where it belongs (a cookie rides along on every request).\n */\nexport const DEVICE_ID_KEY = \"traq_device_id\";\nconst MIRRORED = new Set([DEVICE_ID_KEY]);\nconst MIRROR_MAX_AGE_SECONDS = 395 * 24 * 60 * 60; // 13 months, the CNIL ceiling for a measurement cookie\n\nfunction local(): Storage | undefined {\n try {\n return typeof localStorage === \"undefined\" ? undefined : localStorage;\n } catch {\n return undefined; // Safari with storage blocked throws on mere access\n }\n}\n\n/**\n * @traqio/core's `KeyValueStore`, restated so the published .d.ts files never name\n * @traqio/core: it is bundled into this package, not installed next to it.\n */\ninterface KeyValueStore {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n}\n\n/**\n * The browser persistence behind @traqio/core: localStorage, plus a cookie mirror for\n * identifiers \u2014 or memory only, until the visitor agrees.\n *\n * `persistent: false` is the \"nothing on the device before consent\" mode: every\n * value lives in memory for this page, the SDK still works for this page view, and\n * `enable()` writes it all out the moment consent is given. `disable()` is the way\n * back: everything this SDK wrote is removed from the device, and the page goes on\n * in memory.\n */\nexport class BrowserStore implements KeyValueStore {\n private readonly memory = new Map<string, string>();\n\n constructor(\n private persistent: boolean,\n private readonly cookieDomain: () => string | null,\n private readonly cookies: boolean,\n ) {}\n\n get isPersistent(): boolean {\n return this.persistent;\n }\n\n async getItem(key: string): Promise<string | null> {\n return this.getSync(key);\n }\n\n async setItem(key: string, value: string): Promise<void> {\n this.setSync(key, value);\n }\n\n getSync(key: string): string | null {\n if (this.memory.has(key)) return this.memory.get(key) ?? null;\n if (!this.persistent) return null;\n let value: string | null = null;\n try {\n value = local()?.getItem(key) ?? null;\n } catch {\n /* blocked */\n }\n if (value === null && this.cookies && MIRRORED.has(key)) value = readCookie(key);\n return value;\n }\n\n setSync(key: string, value: string): void {\n if (!this.persistent) {\n this.memory.set(key, value);\n return;\n }\n let stored = false;\n try {\n const ls = local();\n if (ls) {\n ls.setItem(key, value);\n stored = true;\n }\n } catch {\n /* quota or blocked \u2014 fall through to memory */\n }\n if (!stored) this.memory.set(key, value);\n if (this.cookies && MIRRORED.has(key)) writeCookie(key, value, MIRROR_MAX_AGE_SECONDS, this.cookieDomain());\n }\n\n removeSync(key: string): void {\n this.memory.delete(key);\n try {\n local()?.removeItem(key);\n } catch {\n /* blocked */\n }\n if (this.cookies) deleteCookie(key, this.cookieDomain());\n }\n\n /** Consent given: what this page kept in memory goes to the device. */\n enable(): void {\n if (this.persistent) return;\n this.persistent = true;\n const pending = [...this.memory];\n this.memory.clear();\n for (const [key, value] of pending) this.setSync(key, value);\n }\n\n /**\n * Consent withdrawn: every `traq_*` value leaves the device (localStorage and\n * cookies) and stays in memory for the rest of this page, so nothing breaks\n * mid-visit and nothing survives it.\n */\n disable(): void {\n if (!this.persistent) return;\n const ls = local();\n const keys: string[] = [];\n try {\n for (let i = 0; ls && i < ls.length; i++) {\n const k = ls.key(i);\n if (k && k.startsWith(COOKIE_PREFIX)) keys.push(k);\n }\n } catch {\n /* blocked */\n }\n for (const k of MIRRORED) if (!keys.includes(k)) keys.push(k);\n for (const k of keys) {\n const value = this.getSync(k);\n if (value !== null) this.memory.set(k, value);\n }\n this.persistent = false;\n for (const k of keys) {\n try {\n ls?.removeItem(k);\n } catch {\n /* blocked */\n }\n if (this.cookies) deleteCookie(k, this.cookieDomain());\n }\n }\n}\n", "import { deleteCookie, readCookie, writeCookie } from \"./cookies\";\nimport type { BrowserStore } from \"./storage\";\n\n/**\n * The trackID \u2014 the click id Traqio's tracking link appends to the landing URL as\n * `traq_click` (the same `traq_` namespace as the Play Install Referrer, so it never\n * collides with the site's own `utm_*`).\n *\n * Kept twice, on purpose:\n * - localStorage `traq_click` = `{ id, exp }`: survives navigation on this origin;\n * - cookie `traq_click` = the bare id, on the registrable domain: shared with the\n * other subdomains, and sent by the browser to the site's OWN backend with the\n * sign-up or checkout request \u2014 where the conversion that counts is known.\n */\nexport const CLICK_PARAM = \"traq_click\";\nconst STORE_KEY = \"traq_click\";\n\n/** What a click id looks like: Traqio mints UUIDs; anything else is refused, not stored. */\nconst CLICK_ID = /^[A-Za-z0-9_-]{8,64}$/;\n\ninterface StoredClick {\n id: string;\n /** Epoch ms after which the id is no longer kept. */\n exp: number;\n}\n\n/** The click id carried by a URL, or null. Never throws on a malformed URL. */\nexport function clickIdFromUrl(href: string): string | null {\n try {\n const raw = new URL(href).searchParams.get(CLICK_PARAM);\n return raw && CLICK_ID.test(raw) ? raw : null;\n } catch {\n return null;\n }\n}\n\nexport class TrackIdKeeper {\n constructor(\n private readonly store: BrowserStore,\n private readonly maxAgeMs: number,\n private readonly cookieDomain: () => string | null,\n private readonly cookies: boolean,\n ) {}\n\n /**\n * Reads the landing URL. A new click REPLACES the kept one: the last ad clicked is\n * the one that brought the visitor this time. A URL without a click id changes\n * nothing \u2014 an internal navigation must not wipe the id the landing brought.\n */\n capture(href: string, now = Date.now()): string | null {\n const id = clickIdFromUrl(href);\n if (id) this.write(id, now);\n return id;\n }\n\n /** The kept click id, or null once it has expired or was never there. */\n get(now = Date.now()): string | null {\n const raw = this.store.getSync(STORE_KEY);\n if (raw) {\n try {\n const parsed = JSON.parse(raw) as StoredClick;\n if (parsed && typeof parsed.id === \"string\" && parsed.exp > now) return parsed.id;\n } catch {\n /* corrupt \u2014 fall back to the cookie */\n }\n }\n // Another subdomain set it (localStorage is per origin, the cookie is not). The\n // cookie's own Max-Age is its expiry, so a cookie that is still there is valid.\n if (this.cookies && this.store.isPersistent) {\n const fromCookie = readCookie(STORE_KEY);\n if (fromCookie && CLICK_ID.test(fromCookie)) return fromCookie;\n }\n return null;\n }\n\n /** Removes it everywhere \u2014 `forgetMe()`. */\n clear(): void {\n this.store.removeSync(STORE_KEY);\n if (this.cookies) deleteCookie(STORE_KEY, this.cookieDomain());\n }\n\n /** Writes the cookie half once storage becomes allowed (the localStorage half moves with the store). */\n persistCookie(now = Date.now()): void {\n const raw = this.store.getSync(STORE_KEY);\n if (!raw || !this.cookies || !this.store.isPersistent) return;\n try {\n const parsed = JSON.parse(raw) as StoredClick;\n if (parsed.exp > now) writeCookie(STORE_KEY, parsed.id, (parsed.exp - now) / 1000, this.cookieDomain());\n } catch {\n /* corrupt \u2014 nothing to mirror */\n }\n }\n\n private write(id: string, now: number): void {\n const record: StoredClick = { id, exp: now + this.maxAgeMs };\n this.store.setSync(STORE_KEY, JSON.stringify(record));\n if (this.cookies && this.store.isPersistent) writeCookie(STORE_KEY, id, this.maxAgeMs / 1000, this.cookieDomain());\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,YAAA,eAAA;AAcA,YAAA,mBAAA;AAyBA,YAAA,sBAAA;AASA,YAAA,qBAAA;AAcA,YAAA,wBAAA;AApFa,YAAA,qBAA8F;MACzG,EAAE,QAAQ,GAAG,YAAY,GAAG,UAAU,GAAE;MACxC,EAAE,QAAQ,GAAG,YAAY,IAAI,UAAU,IAAG;MAC1C,EAAE,QAAQ,GAAG,YAA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ions {
3
+ /** The site's WEB key (`tq_web_…`), from the console. Public by design: it is held to the site's origins. */
4
+ sdkKey: string;
5
+ /** Origin only, no path. Default `https://api.traqio.app`. */
6
+ endpoint?: string;
7
+ /** Your user id once known — the same id your backend sends with its conversions. */
8
+ userId?: string;
9
+ /**
10
+ * The visitor's consent to SHARING with ad networks, if already known. Omitted =
11
+ * not collected; the site's policy in the console decides.
12
+ */
13
+ consent?: boolean;
14
+ /**
15
+ * `true` = write nothing to the device (no localStorage, no cookie) until
16
+ * `setConsent(true)`. The SDK still works for the current page, in memory. For
17
+ * sites that must ask before storing anything (ePrivacy). Default `false`.
18
+ */
19
+ waitForConsent?: boolean;
20
+ /**
21
+ * How long the trackID is kept after the click, in days. Default 30. Keeping it
22
+ * longer than the site's attribution window is harmless: the server refuses a
23
+ * click outside the window.
24
+ */
25
+ trackIdDays?: number;
26
+ /** `false` = never write a cookie, localStorage only (no sharing across subdomains). Default `true`. */
27
+ cookies?: boolean;
28
+ }
29
+ /** What `track()` accepts beside the event name. */
30
+ export interface WebTrackProps {
31
+ /** Revenue DECLARED by the page. Prefer sending purchases from your backend, where they are known. */
32
+ value?: number;
33
+ currency?: string;
34
+ /** The payment's id at your processor (e.g. a Stripe payment intent): the purchase is then counted once. */
35
+ transactionId?: string;
36
+ /** Where the payment went through — `"stripe"` for Stripe. */
37
+ store?: "stripe" | "app_store" | "play_store" | "mac_app_store" | "amazon";
38
+ }
39
+ export declare class TraqioWeb {
40
+ private readonly core;
41
+ private store;
42
+ private trackIds;
43
+ private waitForConsent;
44
+ private started;
45
+ /** A `setConsent()` made before `init()` — it decides whether init may store. */
46
+ private earlyConsent;
47
+ /**
48
+ * Call once, as early as possible on every page (or once in a single-page app).
49
+ * Reads the trackID from the current URL first, synchronously, so even a visitor
50
+ * who leaves before the network answers keeps it. Safe to call on a server: it
51
+ * does nothing there.
52
+ */
53
+ init(opts: WebInitOptions): Promise<void>;
54
+ /** Record an event — `signup`, `purchase`, `add_to_cart`… Batched, retried, kept across page loads. */
55
+ track(name: string, props?: WebTrackProps): void;
56
+ /** Set the user id once known (after sign-in). */
57
+ setUserId(id: string): void;
58
+ /**
59
+ * The visitor's consent answer. Governs sharing with ad networks, and — with
60
+ * `waitForConsent` — whether anything may be stored: `true` writes out what the
61
+ * page kept in memory (the trackID included), `false` removes everything this SDK
62
+ * stored on the device.
63
+ */
64
+ setConsent(granted: boolean): Promise<void>;
65
+ /**
66
+ * The trackID kept for this visitor, or null (no ad click, or expired). Pass it to
67
+ * your backend with the sign-up or checkout — a hidden form field, a header — if
68
+ * your backend cannot read the `traq_click` cookie itself.
69
+ */
70
+ getTrackId(): string | null;
71
+ /**
72
+ * GDPR erasure from the page: the server deletes what it holds about this browser
73
+ * and user, and this SDK stops sending and forgets the trackID. Irreversible.
74
+ * Resolves false when the request did not reach the server — then nothing changed.
75
+ */
76
+ forgetMe(): Promise<boolean>;
77
+ /** Send what is queued now. Already wired to tab hide and page exit. */
78
+ flush(): void;
79
+ /** True once `forgetMe()` has been honoured: this browser sends nothing any more. */
80
+ get forgotten(): boolean;
81
+ }
82
+ /** The shared instance — `import { Traqio } from "@traqio/web"`. */
83
+ export declare const Traqio: TraqioWeb;