@depsmith/depsmith-sdk 0.9.0 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/depsmith-sdk.global.js +1 -1
- package/dist/depsmith-sdk.global.js.map +1 -1
- package/dist/depsmith-sdk.pixel.global.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -9
- package/dist/index.d.ts +2 -9
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/attribution.ts","../src/page.ts","../src/lifecycle.ts","../src/autocapture/load.ts","../src/tracking-options.ts","../src/autocapture/options.ts","../src/config.ts","../src/hash.ts","../src/fingerprint.ts","../src/geolocation.ts","../src/context.ts","../src/consent.ts","../src/utils/scheduler.ts","../src/queue/queue.ts","../src/utils/uuidv7.ts","../src/queue/storage.ts","../src/queue/storage-local.ts","../src/queue/tab-queue.ts","../src/identity.ts","../src/session.ts","../src/props.ts","../src/reserved.ts","../src/network-errors.ts","../src/web-vitals.ts","../src/super-properties.ts","../src/user-properties.ts","../src/utils/clock.ts","../src/transport/retry.ts","../src/transport/gzip.ts","../src/transport/beacon.ts","../src/transport/uploader.ts","../src/transport/breaker.ts","../src/utils/logger.ts","../src/url-scrub.ts","../src/depsmith-sdk.ts","../src/index.ts"],"sourcesContent":["/**\n * Marketing attribution: where this visitor came from, carried on EVERY event.\n *\n * Why every event rather than only the landing `$page_view`: answering \"how many Add to cart\n * events came from the Diwali campaign?\" otherwise needs a join back to whichever pageview\n * started the visit, which a warehouse query can do but a funnel definition cannot.\n *\n * The key shape here is NOT arbitrary — it is what the collector already reads. See\n * `backend/routers/collect.py` in the analytics repo, which maps\n * `context.campaign.{source,medium,name,term,content}` onto `$utm_*` and\n * `context.referrer.{domain,initial_url,initial_domain}` onto `$referring_domain` /\n * `$initial_referrer` / `$initial_referring_domain`. The product spec proposed putting\n * first-touch under `context.page.*` instead; that would have been accepted and silently\n * dropped, because the collector destructures a fixed set of context blocks and ignores the\n * rest. Match the consumer, not the proposal.\n *\n * `utm_id` and ad click IDs (gclid, fbclid, …) are deliberately NOT sent yet: the collector\n * does not read them, so emitting them would cost bytes on every event for no stored data.\n * Tracked in analytics#2491.\n */\nimport type { KVStorage } from './queue/storage';\n\n/** UTM parameter → the key the collector expects under `context.campaign`. */\nconst UTM_PARAMS: ReadonlyArray<readonly [string, string]> = [\n ['utm_source', 'source'],\n ['utm_medium', 'medium'],\n ['utm_campaign', 'name'],\n ['utm_term', 'term'],\n ['utm_content', 'content'],\n];\n\nexport const KEY_CAMPAIGN = 'depsmith_campaign';\nexport const KEY_REFERRER = 'depsmith_referrer';\n\nexport interface CampaignBlock {\n source?: string;\n medium?: string;\n name?: string;\n term?: string;\n content?: string;\n}\n\nexport interface ReferrerBlock {\n /** Referrer of the current landing. */\n url?: string;\n /** Host of `url`. */\n domain?: string;\n /** Referrer of the FIRST ever landing for this anonymous_id. Written once. */\n initial_url?: string;\n initial_domain?: string;\n}\n\nfunction hostOf(url: string): string | undefined {\n try {\n return new URL(url).host || undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Attribution state for this visitor, persisted so it survives reloads and outlives the\n * landing page. Reads storage once at construction: these values change only on a landing,\n * and `buildContext` runs on every captured event, so a per-event read would be pure cost.\n */\nexport class Attribution {\n private campaign: CampaignBlock = {};\n private referrer: ReferrerBlock = {};\n\n constructor(private storage: KVStorage) {\n this.campaign = this.read<CampaignBlock>(KEY_CAMPAIGN) ?? {};\n this.referrer = this.read<ReferrerBlock>(KEY_REFERRER) ?? {};\n }\n\n private read<T>(key: string): T | null {\n try {\n const raw = this.storage.get(key);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as unknown;\n // A corrupt value must not poison attribution for the rest of the install; treat it as\n // absent, same policy the queue uses for unparseable entries.\n return parsed && typeof parsed === 'object' ? (parsed as T) : null;\n } catch {\n return null;\n }\n }\n\n private write(key: string, value: object): void {\n try {\n this.storage.set(key, JSON.stringify(value));\n } catch {\n /* storage full or blocked — attribution degrades, capture must not */\n }\n }\n\n /**\n * Record a landing. Call on init and on every SPA route change.\n *\n * Three rules, each with a failure mode it prevents:\n * - **Latest campaign wins, as a set.** Any UTM present replaces ALL stored UTMs rather\n * than merging, so a `?utm_source=meta` visit cannot inherit the previous visit's\n * `utm_campaign` and report a campaign that never sent that click.\n * - **Internal navigation changes nothing.** Moving between our own pages has our own host\n * as `document.referrer`; treating that as a new referrer would overwrite the real source\n * on the second pageview of every visit.\n * - **First touch is written once.** `initial_*` is the acquisition source and must survive\n * every later campaign.\n */\n recordLanding(url: string, documentReferrer: string): void {\n let params: URLSearchParams;\n let currentHost: string | undefined;\n try {\n const parsed = new URL(url);\n params = parsed.searchParams;\n currentHost = parsed.host;\n } catch {\n return;\n }\n\n const incoming: CampaignBlock = {};\n for (const [param, key] of UTM_PARAMS) {\n const value = params.get(param);\n if (value) incoming[key as keyof CampaignBlock] = value;\n }\n if (Object.keys(incoming).length > 0) {\n this.campaign = incoming;\n this.write(KEY_CAMPAIGN, incoming);\n }\n\n const refHost = documentReferrer ? hostOf(documentReferrer) : undefined;\n const isExternal = Boolean(refHost) && refHost !== currentHost;\n\n let changed = false;\n if (isExternal) {\n this.referrer.url = documentReferrer;\n this.referrer.domain = refHost;\n changed = true;\n }\n // First touch is recorded on the first landing even when it is direct, so `$direct` can be\n // told apart from \"we never looked\". `initial_url` stays absent for direct; the domain\n // sentinel is what the collector keys on.\n if (this.referrer.initial_domain === undefined) {\n this.referrer.initial_domain = isExternal ? refHost : '$direct';\n if (isExternal) this.referrer.initial_url = documentReferrer;\n changed = true;\n }\n if (changed) this.write(KEY_REFERRER, this.referrer);\n }\n\n /** The `context.campaign` block, or undefined when nothing is known. */\n campaignBlock(): CampaignBlock | undefined {\n return Object.keys(this.campaign).length > 0 ? { ...this.campaign } : undefined;\n }\n\n /** The `context.referrer` block, or undefined when nothing is known. */\n referrerBlock(): ReferrerBlock | undefined {\n return Object.keys(this.referrer).length > 0 ? { ...this.referrer } : undefined;\n }\n\n /** `reset()` forgets the visitor, so it must forget where they came from too. */\n clear(): void {\n this.campaign = {};\n this.referrer = {};\n try {\n this.storage.remove(KEY_CAMPAIGN);\n this.storage.remove(KEY_REFERRER);\n } catch {\n /* ignore */\n }\n }\n}\n","/**\n * Per-visit page context: where the visitor was before this page, and how many pages in they are.\n *\n * Why this cannot just read `document.referrer`: the browser sets it once per document load and\n * never updates it for History API navigation. In a single-page app it therefore keeps pointing at\n * the original landing referrer for the rest of the visit, so \"where did users come from before\n * checkout?\" answers with the acquisition source instead of the previous route. The SDK has to\n * track it itself. `context.page.referrer` keeps the raw `document.referrer` for continuity.\n *\n * Session-scoped, not visitor-scoped: `counter` is \"pages seen this session\", so it must reset\n * when the session does. Held in memory rather than storage — a session cannot span a cold start\n * without also rotating, and a per-page storage write on the capture path is exactly the cost the\n * write-behind queue exists to avoid.\n */\n\nimport type { PageLocation, PageNames, ResolvedConfig } from './config';\nimport type { EventContext, Properties } from './types';\n\nexport type PreviousPageType = 'direct' | 'internal' | 'external';\n\nexport interface PageTracking {\n /**\n * Set only for `$page_leave`, which must describe the page being LEFT. By the time a History\n * navigation notifies the SDK, `window.location` is already the next URL, so these override\n * the derived values for that one event.\n */\n url?: string;\n path?: string;\n domain?: string;\n url_base?: string;\n previous_url?: string;\n previous_type?: PreviousPageType;\n counter?: number;\n}\n\nexport class PageTracker {\n private previousUrl?: string;\n private previousType?: PreviousPageType;\n private counter = 0;\n private currentUrl?: string;\n\n /**\n * Record arriving at `url`. Call once on init and once per History navigation.\n *\n * Returns true when this was a genuine new page, false when it was the same URL again — a\n * History `replaceState` to the identical URL, or a double-fired listener. The caller uses\n * that to avoid emitting two `$page_view`s for one page, which is the acceptance criterion\n * the spec states explicitly.\n */\n recordPage(url: string, documentReferrer: string): boolean {\n if (url === this.currentUrl) return false;\n\n if (this.currentUrl === undefined) {\n // First page of the session. The only honest source for \"what came before\" is\n // document.referrer, which at this point is correct.\n if (!documentReferrer) {\n this.previousType = 'direct';\n } else {\n this.previousUrl = documentReferrer;\n this.previousType = sameOrigin(documentReferrer, url) ? 'internal' : 'external';\n }\n } else {\n // Subsequent pages: we know exactly where they came from, because we were there.\n this.previousUrl = this.currentUrl;\n this.previousType = sameOrigin(this.currentUrl, url) ? 'internal' : 'external';\n }\n\n this.currentUrl = url;\n this.counter += 1;\n return true;\n }\n\n /** Fields for `context.page`. Empty before the first `recordPage`. */\n tracking(): PageTracking {\n const out: PageTracking = {};\n if (this.previousUrl !== undefined) out.previous_url = this.previousUrl;\n if (this.previousType !== undefined) out.previous_type = this.previousType;\n if (this.counter > 0) out.counter = this.counter;\n return out;\n }\n\n /** Pages seen so far this session; 0 before the first page. */\n get pageCount(): number {\n return this.counter;\n }\n\n /** The URL currently being viewed, for `$page_leave` to describe the page being left. */\n get current(): string | undefined {\n return this.currentUrl;\n }\n\n /** Session rotation resets the count — `counter` is defined as pages *this session*. */\n resetForNewSession(): void {\n this.counter = this.currentUrl === undefined ? 0 : 1;\n }\n}\n\n/** What {@link PageLifecycle} needs from the client: a clock and the capture pipeline. */\nexport interface PageEventSink {\n now(): number;\n /**\n * Goes through the client's full capture path — consent, sampling, session, queue.\n *\n * `at` and `page` are for a deferred `$page_view`: the event's timestamp is the navigation, and\n * its `context.page` the page navigated to, however late it is sent.\n */\n capture(\n name: string,\n type: 'page_view' | 'page_leave',\n properties: Properties,\n at?: number,\n page?: EventContext['page']\n ): void;\n}\n\n/**\n * Starts watching for the new route's `<title>`; calls `done` once, when it changes or a timeout\n * passes. Returns a canceller. Supplied by autocapture, which owns everything that observes the\n * DOM.\n */\nexport type TitleWatch = (titleAtNav: string, done: () => void) => () => void;\n\n/** An automatic `$page_view` recorded at navigation and waiting for the new title. */\ninterface PendingView {\n at: number;\n counter: number;\n location: PageLocation;\n /** `context.page` at navigation, title excepted: that is what is being waited for. */\n page: NonNullable<EventContext['page']>;\n cancel: () => void;\n}\n\n/**\n * The `$page_view` / `$page_leave` engine, and the state `context.page` reports.\n *\n * Lives here rather than on the client so the Shopify custom-pixel build can swap the whole\n * module for `page.noop.ts`. That build is deliberately unminified — see tsup.config.ts — so\n * anything it cannot use is still shipped, against an editor that refuses to save a file over\n * 64,000 characters. None of this is reachable there: the pixel sandbox's `window.location` is\n * the sandbox, and host context overrides replace `context.page` wholesale.\n */\nexport class PageLifecycle {\n private pages = new PageTracker();\n /** Clock ms when the current page view began, for $page_leave's duration. */\n private enteredAt = 0;\n /**\n * Set once the current view's $page_leave has been sent, so no second path can send another:\n * cleared when a new page is recorded and on a back/forward-cache restore.\n */\n private left = false;\n /** Set only while capturing $page_leave — the URL of the page being left. */\n private leaving?: string;\n /** Page key of the last emitted $page_view, so one page cannot produce two. */\n private lastViewed?: string;\n /** The SPA view waiting for its route's title, if any. Never sent twice. */\n private pending?: PendingView;\n /** URL and clock of an automatic view already SENT that no `page()` call has followed. */\n private autoViewed?: { url: string; at: number };\n\n /** `pageNames`, compiled once. */\n private rules?: PageNameRules;\n\n /**\n * Under `autocapture.pageviews: 'all'` a page is the whole URL. Otherwise it is the path, the\n * same key autocapture's navigation observer compares — so a `?sort=` change is neither a\n * navigation there nor a new page here.\n */\n private byHref: boolean;\n\n /** Takes the resolved config whole, so the pixel build's call site stays one argument short. */\n constructor(\n private sink: PageEventSink,\n config: Pick<ResolvedConfig, 'pageNames' | 'autocapture'> = { autocapture: false }\n ) {\n this.rules = pageNameRules(config.pageNames);\n this.byHref = !!config.autocapture && config.autocapture.pageviews === 'all';\n }\n\n /**\n * Seed navigation state at init, before anything can capture, so the first event already\n * carries `previous_url` / `counter` — often a `$session_start` ahead of any pageview.\n */\n start(url: string, documentReferrer: string): void {\n this.pages.recordPage(url, documentReferrer);\n this.enteredAt = this.sink.now();\n }\n\n get pageCount(): number {\n return this.pages.pageCount;\n }\n\n /**\n * Advances state for an explicit host `page()` call, and claims the page so autocapture does\n * not emit a second view for it. An app that drives pageviews by hand AND enables autocapture\n * would otherwise double count every page.\n */\n recordExplicit(): void {\n this.record();\n this.lastViewed = this.pageKey();\n this.autoViewed = undefined;\n }\n\n /**\n * A `page()` / `screen()` call. SDK keys after the client's, so they always describe this\n * view; a client `name` is left alone, since the SDK writes `$page_name`, never `name`.\n *\n * One page, one view — whichever of autocapture and the host gets there first:\n *\n * - **The call comes first** (same tick as `init()`, before the lazy chunk): it claims the\n * page and autocapture's view for it is skipped. That much always worked.\n * - **Autocapture's view is still waiting for its title**: the call REPLACES it. This is every\n * router hook — `pushState` runs before the after-navigation hook, so the automatic view was\n * already recorded, and flushing it ahead of the call (as this used to) sent two views per\n * route change. The host's view wins because it carries the host's name and properties.\n * - **Autocapture's view was already sent** for this exact URL (the landing page once the\n * chunk has loaded, or a route whose title arrived before the hook ran): the call is the\n * duplicate, and is dropped. Once, and only within {@link AUTO_VIEW_CLAIM_MS} of that view —\n * a second call for the same URL, or one long after it, is the host asking for another view\n * (a wizard step, a modal) and is sent, as is any call after the URL changes.\n *\n * Without autocapture page views none of this applies and every call is a view.\n */\n manual(name?: string, properties?: Properties, type?: string): void {\n const pending = this.pending;\n if (pending && this.keyOf(pending.location) === this.pageKey()) {\n this.discardPending();\n } else {\n // A pending view for some other page goes first: it was the earlier navigation.\n this.flushPending();\n const auto = this.autoViewed;\n this.autoViewed = undefined;\n if (auto && auto.url === href() && this.sink.now() - auto.at <= AUTO_VIEW_CLAIM_MS) return;\n }\n this.recordExplicit();\n this.sink.capture('$page_view', 'page_view', {\n ...properties,\n ...pageViewProperties({ source: 'manual', name, type }, this.rules),\n $page_counter: this.pages.pageCount,\n });\n }\n\n /**\n * Autocapture's pageview path: at most one `$page_view` per page (see {@link pageKey}).\n *\n * Deduped on what was EMITTED, not on what the tracker advanced — `start()` already fed the\n * landing URL to the tracker, so dedupeing on that would read the seed as \"already viewed\"\n * and swallow the landing pageview entirely.\n *\n * With `watchTitle` (an SPA navigation) the view is DEFERRED. Routers call `pushState` first\n * and set `document.title` only once the new route has rendered, so a view sent in the same\n * tick carried the previous page's title in `$page_name` and `context.page.title` next to the\n * new page's URL. Everything else is decided now — the dedupe, the counter, the timestamp and\n * `context.page` — and only the title waits, for its change or a timeout. Without `watchTitle`\n * (the landing page, whose title is set at load) it is sent at once.\n */\n autoPageView(watchTitle?: TitleWatch): void {\n // FIRST: a still-pending view belongs to the page before this one.\n this.flushPending();\n this.record();\n const key = this.pageKey();\n if (key !== undefined && key === this.lastViewed) return;\n this.lastViewed = key;\n const counter = this.pages.pageCount;\n if (!watchTitle) {\n this.emitView(location, counter);\n return;\n }\n const url = location.href;\n const pending: PendingView = {\n at: this.sink.now(),\n counter,\n // Parsed from the string, not `location` itself: that is live, and the flush may come\n // after the next navigation.\n location: new URL(url),\n page: {\n url,\n path: location.pathname,\n referrer: document.referrer,\n domain: domainOf(url),\n url_base: urlBase(url),\n ...this.pages.tracking(),\n },\n cancel: () => {},\n };\n this.pending = pending;\n // Assigned after `pending` is in place: a watch that resolved synchronously would otherwise\n // flush before there was anything to flush.\n pending.cancel = watchTitle(document.title, () => this.flushPending());\n }\n\n /**\n * Sends the pending view now, with the current title. Runs when the title watch resolves, and\n * ahead of anything that must come after the view: the next navigation and its `$page_leave`,\n * `pagehide`, a `page()` call, `shutdown()` and `reset()` — the view belongs to the user being\n * reset.\n */\n flushPending(): void {\n const view = this.pending;\n if (!view) return;\n this.pending = undefined;\n view.cancel();\n this.emitView(view.location, view.counter, view);\n }\n\n /**\n * Drops the pending view unsent, for `optOut()`: sending an event at the moment the visitor\n * opts out is wrong even where the consent gate would drop it.\n */\n discardPending(): void {\n this.pending?.cancel();\n this.pending = undefined;\n }\n\n private emitView(where: PageLocation, counter: number, pending?: PendingView): void {\n const title = document.title;\n this.autoViewed = { url: where.href, at: this.sink.now() };\n this.sink.capture(\n '$page_view',\n 'page_view',\n {\n ...pageViewProperties({ source: 'auto', location: where, title }, this.rules),\n $page_counter: counter,\n },\n pending?.at,\n pending && { ...pending.page, title }\n );\n }\n\n /**\n * `$page_leave`, paired one-to-one with `$page_view`: sent when the view ENDS — an SPA\n * navigation to another page, or `pagehide` — and at most once for it, whichever path asks.\n *\n * Not when the tab is merely hidden. That used to send one per tab switch, each measured from\n * the same pageview, so one view produced several leaves with overlapping durations.\n *\n * Duration excludes nothing today: wall clock since the pageview. The spec asks for time with\n * the tab hidden excluded, which needs visibility accounting and is deliberately left for a\n * follow-up rather than approximated here.\n *\n * A pending view is flushed first, so a view always precedes its own leave: A → B → C inside\n * the title wait sends view B, leave B, view C. That also covers `pagehide`, whose unload leave\n * comes through here.\n */\n leave(maxScroll?: number): void {\n this.flushPending();\n const leaving = this.pages.current;\n if (leaving === undefined || this.left) return;\n this.left = true;\n const properties: Properties = {\n $page_duration_ms: Math.max(0, this.sink.now() - this.enteredAt),\n };\n if (maxScroll !== undefined) properties.$page_max_scroll = maxScroll;\n // Read back by tracking() for this one capture. On `pagehide` the live location is still the\n // page being left and this changes nothing; it matters for SPA navigation, where History has\n // already moved on.\n this.leaving = leaving;\n try {\n this.sink.capture('$page_leave', 'page_leave', properties);\n } finally {\n this.leaving = undefined;\n }\n }\n\n /**\n * A bfcache restore puts the visitor back on a page a `$page_leave` already reported. They\n * will leave it again, so the leave is re-armed, and restarting the clock keeps the second\n * one from billing the frozen time as time on page.\n */\n restored(persisted: boolean): void {\n if (!persisted) return;\n this.left = false;\n this.enteredAt = this.sink.now();\n }\n\n /** `counter` is pages *this session*, so a rotation restarts the count. */\n newSession(): void {\n this.pages.resetForNewSession();\n }\n\n /** Fields for `context.page`, including the `$page_leave` overrides when one is in flight. */\n tracking(): PageTracking {\n const tracking = this.pages.tracking();\n if (this.leaving === undefined) return tracking;\n return {\n ...tracking,\n url: this.leaving,\n path: pathOf(this.leaving),\n domain: domainOf(this.leaving),\n url_base: urlBase(this.leaving),\n };\n }\n\n /** What makes a page distinct: the path, or the whole URL under `pageviews: 'all'`. */\n private pageKey(): string | undefined {\n const live = globalThis.location;\n return live && this.keyOf(live);\n }\n\n private keyOf(where: PageLocation): string {\n return this.byHref ? where.href : where.pathname;\n }\n\n /** Records the live URL. Resets the page clock only when this really is a new page. */\n private record(): void {\n const url = href();\n if (url === undefined) return;\n const moved = this.pages.recordPage(\n url,\n typeof document !== 'undefined' ? document.referrer : ''\n );\n if (moved) {\n this.enteredAt = this.sink.now();\n this.left = false;\n }\n }\n}\n\n/**\n * How long after an automatic `$page_view` a `page()` for the same URL is taken as its duplicate:\n * a router's after-navigation hook or a `DOMContentLoaded` handler, not a deliberate second view.\n */\nconst AUTO_VIEW_CLAIM_MS = 2000;\n\n/** How a `$page_view` was sent: by autocapture, or by a `page()` / `screen()` call. */\nexport type PageSource = 'auto' | 'manual';\n\n/** `pageNames`, compiled once: the readable name for a location, and its type for a pattern. */\nexport type PageNameRules = (location: PageLocation) => { name: string; type?: string } | undefined;\n\nexport interface PageViewInput {\n source: PageSource;\n /** The `page()` argument. */\n name?: string;\n /** The `page()` options' `type`. */\n type?: string;\n /** Defaults to the live `window.location`. */\n location?: PageLocation;\n /** Defaults to the live `document.title`. */\n title?: string;\n}\n\n/**\n * The SDK-owned properties of every `$page_view`, for both the automatic and the manual path.\n *\n * One function so the two cannot drift: they used to fall back differently (`title || 'Unknown'`\n * against `name ?? document.title ?? 'Unknown'`), which sent an empty name from `page()` on a page\n * without a `<title>`. A blank name or title counts as missing, and the path is the last resort —\n * more useful in a chart than \"Unknown\", which is only left for the no-`window` case.\n *\n * The name is the first non-blank of: the `page()` argument, a `pageNames` match, the title, the\n * path. A manual `page()` without a name goes through `pageNames` too, so one page gets the same\n * `$page_name` from both paths. `$page_type` is the `page()` options' `type`, else the matching\n * pattern's name, else absent; a `pageNames` function names pages but gives no type.\n *\n * `$page_name`, not `name`: `name` is the key clients use most for their own data, and the SDK\n * writing it overwrote theirs.\n */\nexport function pageViewProperties(\n {\n source,\n name,\n type,\n location = globalThis.location,\n title = globalThis.document?.title,\n }: PageViewInput,\n rules?: PageNameRules\n): { $page_name: string; $page_type?: string; $page_source: PageSource } {\n const match = location && rules?.(location);\n const pageType = type?.trim() || match?.type;\n return {\n // `||`, not `??`: a blank string is as missing as an absent one.\n $page_name:\n name?.trim() || match?.name.trim() || title?.trim() || location?.pathname || 'Unknown',\n ...(pageType ? { $page_type: pageType } : {}),\n $page_source: source,\n };\n}\n\n/**\n * Compiles `pageNames` once, at init.\n *\n * Patterns are path globs: `*` is one segment, `**` the rest of the path (`/a/**` matches `/a`\n * itself too). A trailing slash is ignored on both sides. The first match wins, in insertion\n * order for an object — so `'/a/*'` written before `'/a/b'` shadows it; the array-of-pairs form\n * makes that order explicit. A pattern's name is also its `$page_type`.\n *\n * A function is called per view and returns `undefined` for \"no rule\". One that throws, or returns\n * anything but a string, counts as no match: a bug in the host's rule must not cost the page view.\n */\nexport function pageNameRules(names: PageNames | undefined): PageNameRules | undefined {\n if (typeof names === 'function') {\n return (location) => {\n try {\n const name = names(location);\n return typeof name === 'string' ? { name } : undefined;\n } catch {\n return undefined;\n }\n };\n }\n if (!names || typeof names !== 'object') return undefined;\n // A non-string entry compiles to `false` and never matches.\n const rules = (Array.isArray(names) ? names : Object.entries(names)).map(\n ([glob, name]) =>\n [typeof glob === 'string' && typeof name === 'string' && globPattern(glob), name] as const\n );\n return (location) => {\n const path = trimSlash(location.pathname);\n for (const [pattern, name] of rules) if (pattern && pattern.test(path)) return { name, type: name };\n return undefined;\n };\n}\n\n/**\n * `*` is one path segment, `**` any number; everything else is literal. Escaped first — `*` is not\n * among the escaped characters — so the second pass sees only the glob's own stars.\n */\nfunction globPattern(glob: string): RegExp {\n const source = trimSlash(glob)\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/\\*\\*|\\*\\*?/g, (star) =>\n star === '*' ? '[^/]+' : star === '**' ? '.*' : '(?:/.*)?'\n );\n return new RegExp(`^${source}$`);\n}\n\n/** `/products/x/` matches like `/products/x`. The root keeps its slash. */\nfunction trimSlash(path: string): string {\n return path.replace(/(.)\\/$/, '$1');\n}\n\nfunction href(): string | undefined {\n if (typeof window === 'undefined' || !window.location) return undefined;\n return window.location.href;\n}\n\nfunction sameOrigin(a: string, b: string): boolean {\n try {\n return new URL(a).host === new URL(b).host;\n } catch {\n return false;\n }\n}\n\n/** Pathname of `url`, for `context.page.path`. */\nexport function pathOf(url: string): string | undefined {\n try {\n return new URL(url).pathname || undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Host of `url`, for `context.page.domain`. */\nexport function domainOf(url: string): string | undefined {\n try {\n return new URL(url).host || undefined;\n } catch {\n return undefined;\n }\n}\n\n/** `url` without query string or fragment, for `context.page.url_base`. */\nexport function urlBase(url: string): string | undefined {\n try {\n const u = new URL(url);\n return `${u.origin}${u.pathname}`;\n } catch {\n return undefined;\n }\n}\n","/**\n * The browser half of the client's lifecycle: the batch-interval timer and the `pagehide`,\n * `pageshow`, `visibilitychange` and `online` handlers (API_SPEC §9). Inert without a window.\n *\n * A module of its own so the Shopify custom-pixel build can swap it for `lifecycle.noop.ts`.\n * That build always passes `manualLifecycle: true` — the sandbox has no page to hide and the\n * pixel drives its own flush interval — so none of this can run there, and it is unminified\n * against an editor that refuses to save a file over 64,000 characters (see `tsup.config.ts`).\n */\n\n/** What the handlers need from the client. Every member is the client's own, guarded, method. */\nexport interface LifecycleHost {\n /** `batchIntervalMs`. */\n intervalMs: number;\n guard(fn: () => void): void;\n /** `$web_vitals`, once per page. */\n vitals(): void;\n /** Autocapture's unload-time `$page_leave`, when pageview tracking is on. Once per view. */\n leave(): void;\n /** A back/forward-cache restore (`pageshow`). */\n restored(persisted: boolean): void;\n /** The tab became visible again: run the session-timeout check. */\n resume(): void;\n /** Starts an upload when there is something to send and consent allows it. */\n flushIfQueued(): void;\n /** Forces the write-behind queue and session to storage. */\n persistNow(): void;\n /** The `sendBeacon` drain, if consent allows upload. */\n beacon(): void;\n /** Connectivity came back. */\n online(): void;\n}\n\nexport interface BrowserLifecycle {\n /**\n * Re-arms the teardown drain; the client calls it for every event it queues.\n *\n * `drained` exists only to stop `pagehide` and `visibilitychange`→hidden running the\n * same drain twice on one navigation. It must not outlive the work it covered: on\n * desktop, `visibilitychange`→hidden fires on an ordinary tab switch, and a backgrounded\n * tab keeps capturing (the batch-interval timer, `online`, a host-driven `track()`). If\n * that tab is then closed without ever becoming visible again, a latch left set would\n * skip both the final `sendBeaconAll()` and the teardown write, losing everything\n * captured while hidden — a correctness hole opened by a pure optimisation.\n */\n rearm(): void;\n /** Stops the timer and removes the listeners. */\n stop(): void;\n}\n\nexport function startLifecycle(host: LifecycleHost): BrowserLifecycle | undefined {\n // No window means no page: a server render, or a worker. Nothing is started there — not\n // the listeners, which have nothing to listen to, and not the timer. The timer used to start\n // regardless, and in Node an interval that is never cleared keeps the process alive and\n // retains the client it closes over: one leaked client per server render for a host that\n // builds `new DepsmithSdkClient()` in a component. A host without a window drives `flush()`\n // itself, as the Shopify pixel does.\n if (typeof window === 'undefined' || typeof document === 'undefined') return undefined;\n const flushTimer = setInterval(() => host.flushIfQueued(), host.intervalMs);\n // jsdom under Node (tests, prerendering) has a window AND Node's timers: do not let this one\n // hold the process open either. Browsers return a number, which has no `unref`.\n (flushTimer as { unref?: () => void }).unref?.();\n /**\n * Set once a teardown drain has run, so `pagehide` and `visibilitychange`→hidden do not\n * both run it on one navigation. Cleared on resume, on `pageshow`, and by any newly\n * captured event ({@link BrowserLifecycle.rearm}).\n */\n let drained = false;\n /** The fetch flush a tab-hide schedules; cancelled if the hide turns out to be an unload. */\n let hideFlush: ReturnType<typeof setTimeout> | undefined;\n\n // `pagehide` and `visibilitychange`→hidden both fire on a navigation, back-to-back on\n // mobile. Without this guard the whole drain ran twice per page transition, in the\n // handler that is already delaying that transition. Cleared on resume, and by any\n // newly captured event — see rearm().\n //\n // The two events are NOT the same thing, and treating them alike lost events:\n // - `pagehide` means the document is going away. There will be no response to wait for,\n // so this is the one place `sendBeacon` is used and events are removed on the UA's\n // acceptance rather than on a 2xx.\n // - `visibilitychange`→hidden usually means a tab or app switch, and the page lives on.\n // Beaconing there deleted events on every tab switch — including ones the collector\n // then answered with a 5xx, or never received at all. A hidden tab instead gets an\n // ordinary fetch flush (`keepalive`, removed only on 2xx, retried otherwise).\n // On a navigation both fire in the same task, in an order that differs between browsers,\n // so the hidden path defers its flush by a macrotask: if a `pagehide` arrives first or\n // right behind it, that cancels the fetch and beacons instead, and the batch is not sent\n // twice. If the page is frozen before the timer runs, the events are already persisted\n // (below) and replay on the next load.\n //\n // `$page_leave` belongs to `pagehide` alone. A hidden tab has not left the page: emitting\n // there produced one leave per tab switch for a single `$page_view`, each measured from the\n // same start, so summed time on page was overcounted several times over (API_SPEC §12.3\n // promises one per view). `$web_vitals` stays on the first hide, where its values are final.\n const onPageHide = (): void => {\n // `pendingHide`: a hidden a moment ago already latched, but deferred its upload to us —\n // the drain still has to run.\n const pendingHide = hideFlush;\n clearTimeout(pendingHide);\n hideFlush = undefined;\n // Both before the drain, so they ride out in the batch sendBeacon is about to post rather\n // than sitting in a queue this page never gets to flush. Each is latched by its owner —\n // vitals once per page, the leave once per view — so calling them again here is safe, and\n // capturing either re-arms `drained` (see rearm): a tab closed long after it was hidden\n // still beacons its leave.\n //\n // Guarded, because this is where the teardown path calls out to the autocapture module. A\n // throw here would escape before `sendBeaconAll()` and `persistNow()` ran and cost the page\n // its ENTIRE queue, not just this one event. Nothing in today's closure can throw, which is\n // exactly why the next person to extend it would not think to check.\n host.guard(() => host.vitals());\n host.guard(() => host.leave());\n // Nothing new since a drain already ran: the paired `visibilitychange`→hidden got here first.\n if (drained && !pendingHide) return;\n // Latched only now, after the captures above, because capturing clears the latch — which\n // would otherwise let a `visibilitychange`→hidden that follows run the drain a second time.\n drained = true;\n host.beacon();\n // The queue and session are write-behind; this is the point where deferring any\n // further would lose them. One synchronous write each, at teardown, instead of two\n // per captured event.\n host.persistNow();\n };\n const onVisibility = (): void => {\n if (document.visibilityState === 'hidden') {\n if (drained) return;\n host.guard(() => host.vitals());\n drained = true;\n // Persist first: if the page is frozen or killed before the timer below runs, this\n // write is what the next load replays.\n host.persistNow();\n hideFlush = setTimeout(() => {\n hideFlush = undefined;\n host.flushIfQueued();\n }, 0);\n } else {\n clearTimeout(hideFlush);\n drained = false;\n host.resume();\n }\n };\n // A bfcache restore can bring the page back without a visibilitychange, which would\n // otherwise leave `drained` stuck on and skip the final flush of the next navigation.\n const onPageShow = (event: PageTransitionEvent): void => {\n drained = false;\n // The visitor is back on a page whose `$page_leave` the `pagehide` already sent, and will\n // leave it again: the page lifecycle re-arms the leave and restarts its clock, so the\n // second one does not report the hours the tab spent frozen as time on page.\n host.restored(event.persisted);\n };\n const onOnline = (): void => host.online();\n\n window.addEventListener('pagehide', onPageHide);\n window.addEventListener('pageshow', onPageShow);\n document.addEventListener('visibilitychange', onVisibility);\n window.addEventListener('online', onOnline);\n return {\n rearm: () => {\n drained = false;\n },\n stop: () => {\n clearInterval(flushTimer);\n window.removeEventListener('pagehide', onPageHide);\n window.removeEventListener('pageshow', onPageShow);\n document.removeEventListener('visibilitychange', onVisibility);\n window.removeEventListener('online', onOnline);\n clearTimeout(hideFlush);\n },\n };\n}\n","import type { ResolvedAutocaptureConfig } from '../config';\nimport type { AutocaptureHooks } from './index';\n\n/** The subset of the autocapture module DepsmithSdkClient uses. */\nexport interface AutocaptureModule {\n startAutocapture(config: ResolvedAutocaptureConfig, hooks: AutocaptureHooks): () => void;\n}\n\n/**\n * Loads the autocapture engine on demand, keeping it out of the core bundle (<10 KB gz).\n *\n * This indirection exists so a build can swap in `load.noop.ts`: a dynamic `import()`\n * anywhere in the graph makes esbuild emit its `__esm` lazy-init helper, and Shopify's\n * pixel editor rejects that helper's `(0, fn[...])(fn = 0)` idiom outright. Dead-code\n * elimination can't save us there — the pixel build is deliberately unminified, and\n * esbuild only performs DCE while minifying.\n */\nexport function loadAutocapture(): Promise<AutocaptureModule | null> {\n return import('./index');\n}\n","import type { EventContext } from './types';\n\n/**\n * Per-field suppression of context signals (API_SPEC §12.2).\n *\n * Every key defaults true (collected). This filter is SUBTRACTIVE ONLY — leaving an option\n * true never re-enables a field that `deviceFingerprinting`, `childSafeMode` or consent\n * already suppressed, so the controls compose by intersection and no context field ends up\n * with two sources of truth.\n */\nexport interface TrackingOptions {\n /** context.app. Mobile only — web has no app-version concept. */\n appVersion?: boolean;\n /** context.browser. Populated only when deviceFingerprinting is on. */\n browser?: boolean;\n /** context.network.carrier. Implied by `network: false`. */\n carrier?: boolean;\n deviceManufacturer?: boolean;\n deviceModel?: boolean;\n deviceType?: boolean;\n /** context.device.idfv — iOS only, and the ONLY control over it: nothing else suppresses it. */\n idfv?: boolean;\n /** context.locale. */\n language?: boolean;\n /** context.network in full. Subsumes carrier. */\n network?: boolean;\n osName?: boolean;\n osVersion?: boolean;\n /** context.page. Not `$page_name` on $page_view — that is a property, not context. */\n page?: boolean;\n /** context.screen_size: display width, height and density. */\n screenSize?: boolean;\n timezone?: boolean;\n /** context.user_agent. */\n userAgent?: boolean;\n}\n\nexport type ResolvedTrackingOptions = Required<TrackingOptions>;\n\n/**\n * `[option, context key, sub-key]`. Omitting the sub-key drops the whole block.\n *\n * Table-driven rather than fourteen branches so the option set, the defaults and the\n * platform ports cannot drift apart — the mobile SDKs carry the identical table.\n * `library` is deliberately absent: it is the schema's one required context field.\n */\nconst SUPPRESSIONS: ReadonlyArray<readonly [keyof TrackingOptions, string, string?]> = [\n ['appVersion', 'app'],\n ['browser', 'browser'],\n ['carrier', 'network', 'carrier'],\n ['deviceManufacturer', 'device', 'manufacturer'],\n ['deviceModel', 'device', 'model'],\n ['deviceType', 'device', 'type'],\n ['idfv', 'device', 'idfv'],\n ['language', 'locale'],\n ['network', 'network'],\n ['osName', 'os', 'name'],\n ['osVersion', 'os', 'version'],\n ['page', 'page'],\n ['screenSize', 'screen_size'],\n ['timezone', 'timezone'],\n ['userAgent', 'user_agent'],\n];\n\n/** Derived from the table so an added option cannot be left out of the defaults. */\nexport const TRACKING_DEFAULTS = Object.fromEntries(\n SUPPRESSIONS.map(([option]) => [option, true])\n) as ResolvedTrackingOptions;\n\n/**\n * Only an explicit `false` suppresses.\n *\n * A plain spread would let an explicitly-`undefined` property overwrite the `true` default\n * — `{ page: cfg.capturePage }` with an undefined `capturePage` would strip `context.page`\n * from every event, which is data loss from a config the caller believes is a no-op. The\n * mobile ports already fall back to true for a missing or non-boolean entry\n * (`TrackingOptions.fromMap` on Android, `init(from:)` on iOS); this keeps web level.\n */\nexport function resolveTrackingOptions(options?: TrackingOptions): ResolvedTrackingOptions {\n const resolved = { ...TRACKING_DEFAULTS };\n if (!options) return resolved;\n for (const [option] of SUPPRESSIONS) {\n if (options[option] === false) resolved[option] = false;\n }\n return resolved;\n}\n\n/**\n * Removes suppressed fields, in place. Callers pass a freshly built context.\n *\n * Must run AFTER any host-supplied context override — the Shopify pixel supplies page\n * context on every event, and an embedder must not be able to resurrect a field the app\n * disabled.\n */\nexport function applyTrackingOptions(\n context: EventContext,\n options: ResolvedTrackingOptions\n): EventContext {\n const record = context as unknown as Record<string, unknown>;\n for (const [option, key, sub] of SUPPRESSIONS) {\n if (options[option]) continue;\n if (sub === undefined) {\n delete record[key];\n continue;\n }\n // Copy before deleting: override blocks are shallow-merged BY REFERENCE, so an in-place\n // delete would reach into the host's own object. Emptying a block removes the block —\n // suppressing osName and osVersion yields no `os`, not `os: {}`.\n const block = { ...(record[key] as Record<string, unknown> | undefined) };\n delete block[sub];\n if (Object.keys(block).length > 0) record[key] = block;\n else delete record[key];\n }\n return context;\n}\n","import type { AutocaptureConfig, ResolvedAutocaptureConfig } from '../config';\n\n// Autocapture's config defaults, apart from `config.ts` so the Shopify custom-pixel build can\n// swap them for `options.noop.ts`. The pixel always passes `autocapture: false` (there is no DOM\n// in its sandbox) and its autocapture loader is a no-op too, so none of this can run there — and\n// that bundle is unminified against a 64,000-character editor cap (see tsup.config.ts).\n\nexport const AUTOCAPTURE_DEFAULTS: ResolvedAutocaptureConfig = {\n // Interactive-only by default. Capturing every click on the page emitted an event for\n // taps on product images and layout containers — each one costing a queue write — and\n // buried the clicks that carry intent. 'all' restores the firehose explicitly.\n clicks: 'interactive',\n forms: true,\n // Off by default, for now: up to four `scroll_depth` events per page view on every site,\n // `autocapture: true` (the Shopify snippet) included. With it off nothing measures depth, so\n // `$page_leave` has no `$page_max_scroll` either — decision D1, documented in the schema.\n scrolls: false,\n // Path only by default. Counting every `href` change sent a page view and a `$page_leave` for\n // each filter ticked, each sort order, each `#reviews` click and each tag manager tidying\n // `utm_*` out of the URL — distorting page counts, `$page_counter` and time on page alike.\n pageviews: 'path',\n ignoredSelectors: [],\n selectorMaxDepth: 5,\n selectorIgnore: [] as string[],\n attributes: [] as string[],\n};\n\n/**\n * `autocapture` resolved: `true` is every default, an object overrides them, anything else is off.\n *\n * A defined-only merge, not a plain spread: `{ pageviews: undefined }` — which an untyped host or\n * a config built from optional fields produces easily — would otherwise overwrite the default\n * with `undefined` and read as \"off\". The same rule `resolveTrackingOptions` follows.\n */\nexport function resolveAutocapture(\n autocapture: boolean | AutocaptureConfig | undefined\n): false | ResolvedAutocaptureConfig {\n if (autocapture === true) return AUTOCAPTURE_DEFAULTS;\n if (!autocapture || typeof autocapture !== 'object') return false;\n const resolved = { ...AUTOCAPTURE_DEFAULTS } as Record<string, unknown>;\n for (const [key, value] of Object.entries(autocapture)) {\n if (value !== undefined) resolved[key] = value;\n }\n const { clicks, pageviews } = resolved;\n // `true` is an alias: 'interactive' for clicks, 'path' for page views. Only an explicit 'all'\n // asks for every click, or for a view per URL change.\n resolved.clicks = clicks === 'all' ? 'all' : clicks ? 'interactive' : false;\n resolved.pageviews = pageviews === 'all' ? 'all' : pageviews ? 'path' : false;\n return resolved as unknown as ResolvedAutocaptureConfig;\n}\n","import {\n resolveTrackingOptions,\n type ResolvedTrackingOptions,\n type TrackingOptions,\n} from './tracking-options';\nimport { resolveAutocapture } from './autocapture/options';\nimport type { Properties } from './types';\n\n/** Public config — keys mirror spec/schema/config.schema.json. */\nexport interface DepsmithSdkConfig {\n apiKey: string;\n endpoint: string;\n batchSize?: number;\n batchIntervalMs?: number;\n maxQueueSize?: number;\n /**\n * Ceiling on the serialised queue, in UTF-16 code units — the unit browsers meter\n * storage quota in. Bounds the bytes DepsmithSdk occupies in an origin-shared `localStorage`,\n * which `maxQueueSize` (a count) cannot. Oldest events are dropped first. Web only.\n */\n maxQueueBytes?: number;\n sessionTimeoutMs?: number;\n /** Fraction of SESSIONS captured, 0..1. Default 1. Session-sticky; see config.schema.json. */\n sampleRate?: number;\n /** Emit $session_start/$session_end as events, or leave them derivable server-side. Default 'emit'. */\n sessionEvents?: 'emit' | 'derive';\n consentMode?: 'granted' | 'pending';\n respectDnt?: boolean;\n maxRetries?: number;\n debug?: boolean;\n autocapture?: boolean | AutocaptureConfig;\n defaultProperties?: Properties;\n /** Batch upload compression. gzip when CompressionStream exists, transparent fallback otherwise. */\n compression?: 'gzip' | 'none';\n /** COPPA: memory-only identity, identify()/alias() disabled, anonymizeIp forced on. */\n childSafeMode?: boolean;\n /** Ask the server to strip the last IP octet (anonymize_ip on every batch). */\n anonymizeIp?: boolean;\n /** Device fingerprinting (browser/os/device.id/network). **Default true** — opt-OUT, unlike `geolocation`. Suppressed under DNT/childSafeMode/pending consent. */\n deviceFingerprinting?: boolean;\n /**\n * Opt-in device position on context.location (latitude/longitude/accuracy). Never prompts:\n * read only when the site already holds the geolocation permission. City/region/country\n * remain server-resolved from the request IP. Suppressed under DNT/childSafeMode/pending\n * consent, like deviceFingerprinting. Default false.\n */\n geolocation?: boolean;\n /**\n * Opt-in. Strip the fragment and query string from every URL the SDK sends — `context.page`\n * url/referrer/previous_url, `context.referrer`, `$ac_href`, `$ac_form_action`, `$net_*`.\n * `{ keepParams: ['utm_source'] }` keeps the named query parameters. Default false: URLs are\n * sent whole. See API_SPEC §12.\n */\n scrubUrls?: boolean | { keepParams?: string[] };\n /** Per-field context suppression, all keys default true. Subtractive only; see API_SPEC §12.2. */\n trackingOptions?: TrackingOptions;\n /** Persist identity keys in a cookie scoped to this domain (cross-subdomain identity). */\n cookieDomain?: string;\n /** Queue persistence backend. */\n storage?: 'localstorage' | 'indexeddb' | 'memory';\n /**\n * Readable `$page_name`s for automatic page views, and for `page()` calls made without a name.\n * A name passed to `page()` always wins; with no match the name falls back to the title.\n *\n * - **Patterns:** `{ '/products/*': 'Product', '/': 'Home' }`. `*` is one path segment, `**` the\n * rest of the path. The first match wins, in insertion order, so put specific patterns\n * before broad ones (or use the `[pattern, name]` array form). A pattern match also sets\n * `$page_type` to its name.\n * - **Function:** `(location) => string | undefined`, called per view. Sets the name only.\n * Web-only; config.schema.json can describe the object form alone.\n */\n pageNames?: PageNames;\n}\n\n/** What a `pageNames` function is handed: `window.location`, or a URL with the same fields. */\nexport type PageLocation = Pick<Location, 'href' | 'pathname' | 'search' | 'hash' | 'host'>;\n\nexport type PageNames =\n | Record<string, string>\n | ReadonlyArray<readonly [pattern: string, name: string]>\n | ((location: PageLocation) => string | undefined);\n\n/**\n * Which clicks produce a `$autocapture` event.\n * 'interactive' — only clicks resolving to a link/button/[role=button]/submit control\n * or an explicit [data-depsmith-sdk-capture]. The default.\n * 'all' — every click anywhere on the page, including layout containers.\n * true — alias of 'interactive'; false disables click capture.\n */\nexport type ClickCapture = boolean | 'interactive' | 'all';\n\n/**\n * When an automatic `$page_view` (and its `$page_leave`) is sent.\n * 'path' — when `location.pathname` changes. The default: a query-string or `#` change is\n * filters, sort order, pagination or an in-page anchor, not a new page.\n * 'all' — when anything in the URL changes, query and `#` included (the pre-0.8 behaviour).\n * true — alias of 'path'; false sends none automatically.\n */\nexport type PageViewCapture = boolean | 'path' | 'all';\n\nexport interface AutocaptureConfig {\n clicks?: ClickCapture;\n forms?: boolean;\n scrolls?: boolean;\n pageviews?: PageViewCapture;\n ignoredSelectors?: string[];\n selectorMaxDepth?: number;\n /**\n * Extra patterns for ids, classes and test-attribute values that `$ac_selector` should skip as\n * generated, on top of the built-in rules (CSS-in-JS and CSS-module hashes, utility classes,\n * long digit runs). Regex sources, e.g. `['^theme-', '^js-']`; an invalid one is skipped with\n * a debug warning.\n */\n selectorIgnore?: string[];\n /**\n * `data-*` attribute names to attach to click and change events as `$ac_attr_<name>`.\n *\n * An explicit allow-list, NOT a prefix, and empty by default. Data attributes routinely hold\n * exactly the values this SDK is careful never to capture — `data-user-email`,\n * `data-customer-id` — so a prefix rule means any attribute a developer adds later ships\n * silently from then on. Naming each one keeps the decision with the person who can see the\n * markup. Values obey the masking rules: nothing inside `[data-depsmith-sdk-mask]` is read.\n *\n * Given as bare names: `['product-id']` captures `data-product-id` as `$ac_attr_product_id`.\n */\n attributes?: string[];\n /**\n * `$network_request` for failed `fetch` calls, which wraps `window.fetch`. Default true (on\n * whenever autocapture is); false leaves `fetch` untouched while keeping the rest of\n * autocapture. See API_SPEC §12.6.\n */\n networkErrors?: boolean;\n}\n\n/** Every key present, with the aliases normalised away: `true` is never left in either mode. */\nexport interface ResolvedAutocaptureConfig\n extends Required<Omit<AutocaptureConfig, 'clicks' | 'pageviews' | 'networkErrors'>> {\n clicks: 'interactive' | 'all' | false;\n pageviews: 'path' | 'all' | false;\n /** Only ever present as an explicit `false`: absent means on. */\n networkErrors?: boolean;\n}\n\nexport interface ResolvedConfig\n extends Required<Omit<DepsmithSdkConfig, 'autocapture' | 'trackingOptions' | 'pageNames'>> {\n autocapture: false | ResolvedAutocaptureConfig;\n trackingOptions: ResolvedTrackingOptions;\n /** Compiled by the page lifecycle, not here: the pixel build has no page names to compile. */\n pageNames?: PageNames;\n}\n\n/** Validates and applies canonical defaults. Throws — callers (init only) catch and log. */\nexport function resolveConfig(config: DepsmithSdkConfig): ResolvedConfig {\n if (!config || typeof config.apiKey !== 'string' || config.apiKey.length === 0) {\n throw new Error('depsmith-sdk: apiKey is required');\n }\n if (typeof config.endpoint !== 'string' || !/^https?:\\/\\//.test(config.endpoint)) {\n throw new Error('depsmith-sdk: endpoint must be an http(s) URL');\n }\n\n const autocapture = resolveAutocapture(config.autocapture);\n\n return {\n apiKey: config.apiKey,\n endpoint: config.endpoint.replace(/\\/+$/, ''),\n // Every numeric key goes through num()/int(): see there for what a NaN used to do.\n batchSize: int(config.batchSize, 20, 1, 500),\n // The ceiling is what a timer can hold: past 2^31-1 ms `setInterval` overflows and fires\n // continuously.\n batchIntervalMs: int(config.batchIntervalMs, 60000, 1000, 2 ** 31 - 1),\n maxQueueSize: int(config.maxQueueSize, 1000, 1),\n // 512 Ki of a 5 Mi origin-shared budget. The floor keeps a misconfiguration from\n // making the queue effectively undeliverable.\n maxQueueBytes: int(config.maxQueueBytes, 512 * 1024, 4096),\n sessionTimeoutMs: int(config.sessionTimeoutMs, 1800000, 60000),\n sampleRate: num(config.sampleRate, 1, 0, 1),\n sessionEvents: config.sessionEvents === 'derive' ? 'derive' : 'emit',\n consentMode: config.consentMode ?? 'granted',\n respectDnt: config.respectDnt ?? true,\n maxRetries: int(config.maxRetries, 5, 0, 10),\n debug: config.debug ?? false,\n defaultProperties: config.defaultProperties ?? {},\n autocapture,\n compression: config.compression ?? 'gzip',\n childSafeMode: config.childSafeMode ?? false,\n // COPPA implies IP anonymization.\n anonymizeIp: (config.anonymizeIp ?? false) || (config.childSafeMode ?? false),\n deviceFingerprinting: config.deviceFingerprinting ?? true,\n geolocation: config.geolocation ?? false,\n scrubUrls: config.scrubUrls ?? false,\n trackingOptions: resolveTrackingOptions(config.trackingOptions),\n cookieDomain: config.cookieDomain ?? '',\n storage: config.storage ?? 'localstorage',\n pageNames: config.pageNames,\n };\n}\n\n/**\n * A numeric option: the default unless it is a finite number, then clamped.\n *\n * Non-finite falls back rather than clamping, because `clamp(NaN)` is NaN and a NaN does not\n * fail loudly, it poisons whatever reads it. An untyped host produces one easily\n * (`parseInt(settings.batch_size)` on an unset theme setting, `window.__depsmithSdkConfig` from\n * Liquid), and what each key then did:\n * - `batchSize`: `queue.peek(NaN)` is empty, so the uploader POSTed `batch: []`, removed\n * nothing and looped for the life of the page;\n * - `batchIntervalMs`: `setInterval(fn, NaN)` fires continuously;\n * - `maxRetries`: the attempt loop never ran, so nothing was ever uploaded;\n * - `maxQueueSize` / `maxQueueBytes`: every comparison false, so neither cap applied;\n * - `sampleRate`: every sample comparison false, so every non-identity event was dropped.\n */\nfunction num(value: unknown, fallback: number, min: number, max = Infinity): number {\n return Math.min(Math.max(Number.isFinite(value) ? (value as number) : fallback, min), max);\n}\n\n/** {@link num} for the keys config.schema.json types as integers. */\nfunction int(value: unknown, fallback: number, min: number, max?: number): number {\n return Math.floor(num(value, fallback, min, max));\n}\n","/** Tiny non-cryptographic string hashes. No dependencies; synchronous. */\n\n/** djb2 → base-36. Used for config-drift fingerprinting. */\nexport function djb2(input: string): string {\n let hash = 5381;\n for (let i = 0; i < input.length; i++) {\n hash = ((hash << 5) + hash + input.charCodeAt(i)) >>> 0;\n }\n return hash.toString(36);\n}\n\n/** FNV-1a (32-bit), raw. */\nexport function fnv1aInt(input: string): number {\n let hash = 2166136261;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 16777619) >>> 0;\n }\n return hash >>> 0;\n}\n\n/** FNV-1a (32-bit) → base-36. Different mixing than djb2 to cut collisions when combined. */\nexport function fnv1a(input: string): string {\n return fnv1aInt(input).toString(36);\n}\n\n/**\n * Deterministic [0,1) bucket for sampling.\n *\n * Derived from the input rather than Math.random() on purpose: the decision must be\n * STICKY for a session's whole lifetime, identical across tabs sharing that session,\n * reproducible in tests, and recomputable server-side. A random draw is none of those.\n */\nexport function bucket(input: string): number {\n return fnv1aInt(input) / 0x100000000;\n}\n\n/**\n * Stable ~13-char id from a signal string. Concatenates two independent hashes so\n * unrelated inputs are far less likely to collide than a single 32-bit hash.\n */\nexport function fingerprintHash(input: string): string {\n return djb2(input) + fnv1a(input);\n}\n","import { fingerprintHash } from './hash';\nimport type { EventContext, NetworkType } from './types';\n\n/**\n * Passive device fingerprinting for web (fingerprintjs-inspired, no dependencies).\n * All reads are best-effort and guarded — callers wrap this in try/catch too.\n *\n * Privacy: ON BY DEFAULT. `deviceFingerprinting` defaults to true (since 0.3.1) and consent to\n * `granted`, so a stock install renders a canvas and hashes it on the first captured event. The\n * caller (DepsmithSdkClient) invokes this only while `deviceFingerprinting` is on, consent is\n * granted, and childSafeMode/DNT are off — `consentMode: 'pending'` or\n * `deviceFingerprinting: false` turn it off. This module does not re-check.\n */\n\ntype Browser = NonNullable<EventContext['browser']>;\ntype OS = NonNullable<EventContext['os']>;\n\ninterface ParsedAgent {\n browser?: Browser;\n os?: OS;\n deviceType?: string;\n device?: { manufacturer?: string; model?: string };\n}\n\ninterface NavigatorUAData {\n brands?: Array<{ brand: string; version: string }>;\n mobile?: boolean;\n platform?: string;\n getHighEntropyValues?: (hints: string[]) => Promise<HighEntropy>;\n}\n\ninterface HighEntropy {\n model?: string;\n platformVersion?: string;\n platform?: string;\n}\n\nlet hints: HighEntropy = {};\nlet hintsRequested = false;\n\n/**\n * Requests the UA Client Hints that carry device model and a real OS version.\n *\n * Called ONCE, from the client constructor — never from `buildContext()`. `getHighEntropyValues`\n * returns a Promise, and `buildContext` runs on the capture path, which PR #19 just finished\n * clearing of blocking work; awaiting there would undo that. Resolving once into module state\n * means the capture path only ever does a property read.\n *\n * The trade-off is explicit: the first event or two of a session may lack `device.model` and\n * fall back to the UA-string OS version. That is inherent to an async-only API and strictly\n * better than delaying capture.\n *\n * Chromium-only and secure-context-only; absence and rejection (NotAllowedError under a\n * restrictive permissions policy) are both silently tolerated.\n */\nexport function primeClientHints(): void {\n if (hintsRequested) return;\n hintsRequested = true;\n try {\n const uaData = (navigator as Navigator & { userAgentData?: NavigatorUAData })?.userAgentData;\n if (typeof uaData?.getHighEntropyValues !== 'function') return;\n void uaData\n .getHighEntropyValues(['model', 'platformVersion'])\n .then((values) => {\n hints = values;\n })\n .catch(() => {\n /* insecure context or permissions policy — keep the UA-string fallbacks */\n });\n } catch {\n /* no userAgentData at all */\n }\n}\n\n/** Testing seam: clear the memoised client hints. */\nexport function resetClientHintsCache(): void {\n hints = {};\n hintsRequested = false;\n}\n\n/** Parse browser, OS, and device type from UA Client Hints (when present) + the UA string. */\nexport function parseUserAgent(): ParsedAgent {\n const result: ParsedAgent = {};\n if (typeof navigator === 'undefined') return result;\n\n const ua = navigator.userAgent || '';\n const uaData = (navigator as Navigator & { userAgentData?: NavigatorUAData }).userAgentData;\n\n const browser = parseBrowser(ua, uaData);\n if (browser) result.browser = browser;\n\n const os = parseOS(ua);\n if (os) {\n // The UA string's OS version is frozen on Chromium — Android is pinned to \"10\" and macOS to\n // \"10_15_7\" regardless of the real version — so the hint wins whenever it resolved.\n const hinted = normalizeOsVersion(os.name, hints.platformVersion);\n result.os = hinted ? { ...os, version: hinted } : os;\n }\n\n const deviceType = parseDeviceType(ua, uaData);\n if (deviceType) result.deviceType = deviceType;\n\n const device = parseDevice(ua, os);\n if (device) result.device = device;\n\n return result;\n}\n\n/**\n * Device make and model, to the extent the web platform admits them.\n *\n * `model` comes from the UA-CH hint, which on Android Chromium is the same string Android's\n * native `Build.MODEL` reports (\"moto g96 5G\") — so the flattened column agrees across the two\n * SDKs. Chromium returns \"\" on desktop, which stays absent.\n *\n * `manufacturer` is Apple-only by design. UA-CH exposes no vendor field, and inferring a brand\n * from a model string (\"Pixel 8\" → Google) is a lookup table that rots with every handset\n * launch for a coarse win. Apple is the one case that is deterministic from the OS.\n */\nfunction parseDevice(ua: string, os?: OS): { manufacturer?: string; model?: string } | undefined {\n const device: { manufacturer?: string; model?: string } = {};\n if (os?.name === 'iOS' || os?.name === 'macOS') device.manufacturer = 'Apple';\n\n const hinted = hints.model?.trim();\n if (hinted) device.model = hinted;\n else if (/iPhone/.test(ua)) device.model = 'iPhone';\n else if (/iPad/.test(ua)) device.model = 'iPad';\n\n return device.manufacturer || device.model ? device : undefined;\n}\n\n/**\n * Maps a UA-CH `platformVersion` onto the version users and dashboards recognise.\n *\n * Windows is the case that matters: Chromium reports the PLATFORM version, not the marketing\n * one, so Windows 11 arrives as 13 or above and Windows 10 as 1–12. Without this every Windows\n * 11 machine is labelled \"10\" — and the UA string is no better, since it froze at \"Windows NT\n * 10.0\". Elsewhere trailing \".0\" groups are trimmed so web-on-Android reports \"16\" like the\n * native SDK rather than \"16.0.0\".\n */\nexport function normalizeOsVersion(\n osName: string | undefined,\n platformVersion?: string\n): string | undefined {\n const raw = platformVersion?.trim();\n if (!raw) return undefined;\n\n if (osName === 'Windows') {\n const major = Number.parseInt(raw.split('.')[0] ?? '', 10);\n if (!Number.isFinite(major)) return undefined;\n if (major === 0) return undefined; // Chromium's \"unknown\" sentinel\n return major >= 13 ? '11' : '10';\n }\n\n return trimVersion(raw);\n}\n\n/**\n * Order matters: Edge/Opera UAs also contain \"Chrome\"; Chrome contains \"Safari\".\n * `requires` is an extra guard that must hold before the version pattern is tried.\n */\nconst BROWSER_RULES: ReadonlyArray<{\n pattern: RegExp;\n name: string;\n engine: string;\n requires?: RegExp;\n}> = [\n { pattern: /Edg(?:e|A|iOS)?\\/([\\d.]+)/, name: 'Edge', engine: 'Blink' },\n { pattern: /OPR\\/([\\d.]+)/, name: 'Opera', engine: 'Blink' },\n { pattern: /Firefox\\/([\\d.]+)/, name: 'Firefox', engine: 'Gecko' },\n { pattern: /Chrome\\/([\\d.]+)/, name: 'Chrome', engine: 'Blink' },\n { pattern: /Version\\/([\\d.]+)/, name: 'Safari', engine: 'WebKit', requires: /Safari/ },\n];\n\nfunction parseBrowser(ua: string, uaData?: NavigatorUAData): Browser | undefined {\n for (const rule of BROWSER_RULES) {\n if (rule.requires && !rule.requires.test(ua)) continue;\n const match = ua.match(rule.pattern);\n if (match) return { name: rule.name, version: match[1], engine: rule.engine };\n }\n // Fall back to UA Client Hints brand list (skip the \"Not/A)Brand\" placeholder).\n const brand = uaData?.brands?.find((b) => !/not.?a.?brand/i.test(b.brand));\n if (brand) return { name: brand.brand, version: brand.version };\n return undefined;\n}\n\n/** iOS must be checked before macOS (iPad UAs can contain \"Mac OS X\"). */\nconst OS_RULES: ReadonlyArray<{ pattern: RegExp; name: string; requires?: RegExp }> = [\n { pattern: /Windows NT ([\\d.]+)/, name: 'Windows' },\n { pattern: /OS ([\\d_]+)/, name: 'iOS', requires: /iPhone|iPad|iPod/ },\n { pattern: /Android ([\\d.]+)/, name: 'Android' },\n { pattern: /Mac OS X ([\\d_]+)/, name: 'macOS' },\n];\n\nfunction parseOS(ua: string): OS | undefined {\n for (const rule of OS_RULES) {\n if (rule.requires && !rule.requires.test(ua)) continue;\n const match = ua.match(rule.pattern);\n // Apple reports versions with underscores (10_15_7); the others can't contain one,\n // so the replace is a no-op there.\n //\n // Trailing zero groups are trimmed here for the same reason normalizeOsVersion trims\n // them: the client hint resolves ASYNCHRONOUSLY, so the first events of a page take this\n // UA-string path and later ones take the hint path. Without matching normalisation the\n // SAME device reports \"10.0\" then \"10\" within one session — the e2e capture showed 42\n // events of one and 33 of the other — and every group-by on os_version splits one machine\n // into two rows.\n if (match) return { name: rule.name, version: trimVersion((match[1] ?? '').replace(/_/g, '.')) };\n }\n if (/Linux/.test(ua)) return { name: 'Linux' };\n return undefined;\n}\n\n/** Drops trailing `.0` groups (\"10.0\" -> \"10\", \"16.3.1\" -> \"16.3.1\"). */\nfunction trimVersion(version: string): string {\n const trimmed = version.replace(/(\\.0)+$/, '');\n return trimmed.length > 0 ? trimmed : version;\n}\n\nfunction parseDeviceType(ua: string, uaData?: NavigatorUAData): string | undefined {\n if (/iPad|Tablet|Nexus 7|Kindle|Silk/.test(ua)) return 'tablet';\n if (uaData?.mobile === true) return 'mobile';\n if (/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(ua)) return 'mobile';\n if (/Android/.test(ua)) return 'tablet'; // Android without \"Mobile\" → tablet\n if (typeof navigator !== 'undefined' && ua) return 'desktop';\n return undefined;\n}\n\nlet cachedVisitorId: string | null = null;\nlet cachedComponents: FingerprintComponent[] | null = null;\n\n/** One named signal. `value` is what feeds the hash; `name` is what goes on the wire. */\ninterface FingerprintComponent {\n name: string;\n value: string;\n}\n\n/**\n * Collected once per page. The canvas render is the expensive part, and both the device id and\n * the wire components derive from this one array — so it must never run twice.\n */\nfunction components(): FingerprintComponent[] {\n if (cachedComponents !== null) return cachedComponents;\n cachedComponents = collectSignals();\n return cachedComponents;\n}\n\n/**\n * Stable device id hashed from passive signals (screen, hardware, canvas).\n * Computed once per page and memoized — the canvas render is the only costly part.\n */\nexport function computeVisitorId(): string {\n if (cachedVisitorId !== null) return cachedVisitorId;\n cachedVisitorId = fingerprintHash(components().map((c) => c.value).join('|'));\n return cachedVisitorId;\n}\n\n/**\n * The same signals the device id is hashed from, but broken out by name.\n *\n * A single opaque hash cannot be matched approximately: one signal drifting — a browser update\n * changing canvas output, a monitor swap changing the screen string — produces a completely\n * different id, and a returning visitor who has cleared storage is unrecoverable. Sending the\n * parts lets the collector do N-of-M matching instead: 5 of 6 components equal, same\n * user-agent family, inside a time window, and the prior device is recovered rather than lost.\n *\n * This is the half FingerprintJS Pro does server-side, and the reason their accuracy is not\n * what the open-source agent's is. The hash stays on every event because it is 13 characters;\n * the components ride on `$session_start` alone, since they cost a few hundred bytes and\n * cannot change within a session.\n */\nexport function fingerprintComponents(): Record<string, string> {\n const out: Record<string, string> = {};\n for (const component of components()) out[`$fp_${component.name}`] = component.value;\n return out;\n}\n\n/** Testing seam: clear the memoised fingerprint. */\nexport function resetVisitorIdCache(): void {\n cachedVisitorId = null;\n cachedComponents = null;\n}\n\n/**\n * Signals that go into the device id.\n *\n * A signal belongs here only if it is BOTH device-distinguishing and stable for the life of the\n * device. The hash is opaque, so one signal changing does not degrade the id — it replaces it,\n * and the same device is counted as a new one.\n *\n * Deliberately EXCLUDED, and each was previously included:\n *\n * - `devicePixelRatio` — changes when the visitor ZOOMS the page. A zoom is not a new device,\n * but it was producing a new device id.\n * - `timeZone` — changes when the visitor travels.\n * - `navigator.language` — changes when they change their settings.\n *\n * Removing them costs the collector nothing, which is the point: all three are already sent as\n * their own context fields on every event — `context.screen_size.density`, `context.timezone` and\n * `context.locale` (see buildContext in context.ts). So the server can still match on them,\n * independently and tolerantly, instead of having them welded into a hash where any change is\n * total loss.\n *\n * ORDER IS LOAD-BEARING: the values are joined in sequence to produce the device id, so\n * reordering or reformatting any entry silently re-identifies every existing visitor.\n */\nfunction collectSignals(): FingerprintComponent[] {\n const signals: FingerprintComponent[] = [];\n try {\n if (typeof screen !== 'undefined') {\n signals.push({\n name: 'screen',\n value: `${screen.width}x${screen.height}x${screen.colorDepth}`,\n });\n }\n if (typeof navigator !== 'undefined') {\n const nav = navigator as Navigator & { deviceMemory?: number };\n signals.push({ name: 'hc', value: `hc:${navigator.hardwareConcurrency ?? ''}` });\n signals.push({ name: 'dm', value: `dm:${nav.deviceMemory ?? ''}` });\n signals.push({ name: 'plat', value: `plat:${navigator.platform ?? ''}` });\n signals.push({ name: 'touch', value: `touch:${(navigator.maxTouchPoints ?? 0) > 0}` });\n }\n signals.push({ name: 'canvas', value: `canvas:${canvasFingerprint()}` });\n } catch {\n // best-effort; a partial signal set still yields a stable-enough id\n }\n return signals;\n}\n\n/** Render a fixed scene to an offscreen canvas and hash the pixel data URL. */\nfunction canvasFingerprint(): string {\n try {\n if (typeof document === 'undefined') return '';\n const canvas = document.createElement('canvas');\n canvas.width = 240;\n canvas.height = 60;\n const ctx = canvas.getContext('2d');\n if (!ctx) return '';\n ctx.textBaseline = 'top';\n ctx.font = \"14px 'Arial'\";\n ctx.fillStyle = '#f60';\n ctx.fillRect(10, 10, 100, 30);\n ctx.fillStyle = '#069';\n // Built at runtime: esbuild emits any spelling of this literal as `\\u{1F310}`, and\n // Shopify's custom-pixel editor rejects that escape and refuses to save the pixel.\n // The drawn text, and so every existing canvas hash, is unchanged.\n ctx.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(0x1f310)}`, 12, 15);\n ctx.strokeStyle = 'rgba(0,120,200,0.5)';\n ctx.arc(50, 30, 20, 0, Math.PI * 2);\n ctx.stroke();\n return fingerprintHash(canvas.toDataURL());\n } catch {\n return '';\n }\n}\n\ninterface NetworkInformation {\n type?: string;\n effectiveType?: string;\n}\n\n/**\n * Best-effort network type from the Network Information API. `vpn` is intentionally\n * omitted on web — there is no reliable in-browser VPN signal (detected server-side).\n */\nexport function readNetwork(): { type?: NetworkType } {\n try {\n if (typeof navigator === 'undefined') return {};\n const conn = (navigator as Navigator & { connection?: NetworkInformation }).connection;\n if (!conn) return {};\n\n // `type` (wifi/ethernet/cellular/none) is more specific than `effectiveType` when present.\n switch (conn.type) {\n case 'wifi':\n return { type: 'wifi' };\n case 'ethernet':\n return { type: 'ethernet' };\n case 'none':\n return { type: 'none' };\n }\n switch (conn.effectiveType) {\n case 'slow-2g':\n case '2g':\n return { type: '2g' };\n case '3g':\n return { type: '3g' };\n case '4g':\n return { type: '4g' };\n }\n return {};\n } catch {\n return {};\n }\n}\n","/**\n * Device position for `context.location` — and only when the user has ALREADY granted it.\n *\n * DepsmithSdk never prompts. `getCurrentPosition()` triggers the browser's permission dialog\n * whenever the state is `prompt`, and an analytics SDK popping a location request on page\n * load is exactly the behaviour that gets a site's tracking ripped out. So the Permissions\n * API is consulted first and the position is read only from a `granted` state; where the\n * Permissions API is absent (older Safari) nothing is requested at all, because there is no\n * way to tell `granted` from `prompt` without risking the dialog.\n *\n * Same shape as `primeClientHints()`: requested ONCE, off the capture path, resolved into\n * module state that `buildContext()` reads synchronously. The first event or two of a\n * session may therefore carry no position — inherent to an async-only API and strictly\n * better than delaying capture. Coarse accuracy is requested: Wi-Fi/cell positioning is\n * what analytics needs, and it avoids spinning up the GPS radio on every page view.\n *\n * Only latitude/longitude/accuracy are ever set here. City/region/country stay a collector\n * concern — it resolves them from the request IP and merges them over these coordinates.\n */\nexport interface GeoFix {\n latitude: number;\n longitude: number;\n accuracy?: number;\n /** Provenance, so a consumer can tell a device fix from the collector's IP fallback. */\n source: 'gps';\n}\n\n/** A fix older than this is refreshed (off the capture path) the next time it is read. */\nconst MAX_FIX_AGE_MS = 5 * 60_000;\nconst FIX_TIMEOUT_MS = 10_000;\n\nlet fix: GeoFix | null = null;\nlet fixAt = 0;\nlet primed = false;\nlet inFlight = false;\nlet permission: PermissionStatus | null = null;\n/** SDK consent, re-checked before every position read — see `primeGeolocation()`. */\nlet allowed: () => boolean = () => true;\n\n/**\n * Queries permission state once and, if already granted, requests a position.\n *\n * `allowed` is the SDK's consent gate. It is consulted before EVERY read, including the ones a\n * later permission change or a stale-fix refresh starts, so an `optOut()` after priming stops\n * further reads, and the next read drops the held fix (#87).\n */\nexport function primeGeolocation(gate = allowed): void {\n allowed = gate;\n if (primed) return;\n primed = true;\n try {\n if (typeof navigator === 'undefined' || !navigator.geolocation) return;\n const permissions = navigator.permissions;\n if (typeof permissions?.query !== 'function') return; // cannot rule out a prompt\n void permissions\n .query({ name: 'geolocation' })\n .then((status) => {\n permission = status;\n if (status.state === 'granted') requestFix();\n // The user may grant (or revoke) mid-session from the site's own UI; follow it\n // rather than freezing whatever the state was at init.\n status.onchange = () => {\n if (status.state === 'granted') requestFix();\n else fix = null;\n };\n })\n .catch(() => {\n /* permissions policy or unsupported name — stay silent, send nothing */\n });\n } catch {\n /* no navigator at all (SSR, worker sandbox) */\n }\n}\n\nfunction requestFix(): void {\n if (inFlight || !allowed()) return;\n inFlight = true;\n try {\n navigator.geolocation.getCurrentPosition(\n (position) => {\n inFlight = false;\n const { latitude, longitude, accuracy } = position.coords;\n if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return;\n const next: GeoFix = { latitude, longitude, source: 'gps' };\n if (Number.isFinite(accuracy)) next.accuracy = accuracy;\n fix = next;\n fixAt = Date.now();\n },\n () => {\n inFlight = false; // denied after all, timed out, or position unavailable — keep quiet\n },\n { enableHighAccuracy: false, maximumAge: MAX_FIX_AGE_MS, timeout: FIX_TIMEOUT_MS }\n );\n } catch {\n inFlight = false;\n }\n}\n\n/**\n * The last known position, or undefined when there is none. A stale fix is returned as-is\n * and a refresh is kicked off for later events — never awaited on the capture path.\n */\nexport function readGeolocation(): GeoFix | undefined {\n // Withdrawn consent also drops the fix in hand, including one an in-flight read delivered late.\n if (!allowed()) fix = null;\n if (!fix) return undefined;\n if (Date.now() - fixAt > MAX_FIX_AGE_MS && permission?.state === 'granted') requestFix();\n return { ...fix };\n}\n\n/** Testing seam: clear the memoised position and permission state. */\nexport function resetGeolocationCache(): void {\n fix = null;\n fixAt = 0;\n primed = false;\n inFlight = false;\n permission = null;\n allowed = () => true;\n}\n","import type { EventContext } from './types';\nimport type { Attribution } from './attribution';\nimport { domainOf, urlBase, type PageTracking } from './page';\nimport { parseUserAgent, readNetwork } from './fingerprint';\nimport { readGeolocation } from './geolocation';\nimport { applyTrackingOptions, type ResolvedTrackingOptions } from './tracking-options';\n\nexport const LIBRARY_NAME = '@depsmith/depsmith-sdk';\nexport const SDK_VERSION = '0.9.0';\n\nexport interface ContextOptions {\n /** Populate fingerprint context (browser/os/device type/network). The device_id itself is\n * stamped on the envelope by the capture sites, not here. Caller enforces privacy gating. */\n fingerprint?: boolean;\n /**\n * Attach the device position (context.location lat/long/accuracy) when one has already\n * been resolved from an already-granted permission. Caller enforces privacy gating.\n */\n geolocation?: boolean;\n /**\n * Host-supplied context, shallow-merged over the derived values (per top-level key).\n * For embedders where the real globals are absent or wrong — notably the Shopify\n * web-pixel sandbox, whose `window.location` points at the sandbox, not the storefront.\n */\n overrides?: Partial<EventContext>;\n /** Per-field context suppression (API_SPEC §12.2). Applied last, after `overrides`. */\n tracking?: ResolvedTrackingOptions;\n /**\n * Attribution state, when the client is tracking it. Supplies `context.campaign` and\n * `context.referrer`. Passed in rather than read from storage here so `buildContext` stays\n * free of storage access on the capture path.\n */\n attribution?: Attribution;\n /**\n * SDK-tracked navigation state (previous page, page counter), merged into `context.page`.\n * Supplied by the client rather than derived here, because only the client sees navigation.\n * A deferred `$page_view` passes the whole block as it stood at its navigation, title updated,\n * so its `url` and `path` stay the navigated page's even if the flush comes after the next one.\n */\n page?: PageTracking | EventContext['page'];\n}\n\n/**\n * Values that cannot change for the life of the document, memoised because buildContext\n * runs on every captured event.\n *\n * `Intl.DateTimeFormat()` is the one that mattered: constructing a formatter just to read\n * `resolvedOptions().timeZone` is far and away the most expensive thing in this function,\n * and it was being done per event on the capture path. Scalars only — the objects below\n * are rebuilt per call so no two events ever share a mutable nested block.\n */\ninterface InvariantContext {\n timezone?: string;\n locale?: string;\n userAgent?: string;\n}\n\nlet invariants: InvariantContext | null = null;\n\nfunction readInvariants(): InvariantContext {\n if (invariants) return invariants;\n const next: InvariantContext = {};\n try {\n next.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch {\n /* no Intl / restricted environment */\n }\n if (typeof navigator !== 'undefined') {\n next.locale = navigator.language;\n next.userAgent = navigator.userAgent;\n }\n invariants = next;\n return next;\n}\n\n/** Testing seam: clear the memoised per-document context. */\nexport function resetContextCache(): void {\n invariants = null;\n}\n\n/** Browser context attached to every event. Guarded for SSR / test environments. */\nexport function buildContext(opts: ContextOptions = {}): EventContext {\n const context: EventContext = {\n library: { name: LIBRARY_NAME, version: SDK_VERSION },\n };\n\n // Per block, not one blanket try. A single `try` around all of these meant a throw in an\n // early block silently abandoned every field after it — so one hostile `window.screen`\n // getter cost locale, timezone, user_agent and the entire fingerprint. Same defect Android's\n // context provider had, in a different shape.\n attempt(() => {\n if (typeof window !== 'undefined' && window.location) {\n const href = window.location.href;\n context.page = {\n url: href,\n path: window.location.pathname,\n referrer: typeof document !== 'undefined' ? document.referrer : undefined,\n title: typeof document !== 'undefined' ? document.title : undefined,\n domain: domainOf(href),\n url_base: urlBase(href),\n // previous_url / previous_type / counter come from the client's PageTracker, which is\n // the only thing that knows the in-app navigation history.\n ...(opts.page ?? {}),\n };\n }\n });\n attempt(() => {\n // Read live rather than memoised: these are plain property accesses with no layout\n // cost, and they do change on a zoom or a monitor switch.\n if (typeof window !== 'undefined' && window.screen) {\n context.screen_size = {\n width: window.screen.width,\n height: window.screen.height,\n density: window.devicePixelRatio,\n };\n }\n });\n attempt(() => {\n const cached = readInvariants();\n if (cached.locale !== undefined) context.locale = cached.locale;\n if (cached.userAgent !== undefined) context.user_agent = cached.userAgent;\n if (cached.timezone !== undefined) context.timezone = cached.timezone;\n });\n attempt(() => {\n // Form factor on EVERY event, not only under fingerprinting. Mobile-vs-desktop is the most\n // common web breakdown there is, and gating it meant most web events could not be split at\n // all. It is derived from the user agent, which is already sent unconditionally a few lines\n // down, so this discloses nothing that was not already on the wire.\n //\n // Written before `enrichFingerprint`, which merges into the same block when it runs and adds\n // manufacturer/model from Client Hints — those stay gated, because they are device detail\n // rather than form factor.\n const { deviceType } = parseUserAgent();\n if (deviceType) context.device = { ...context.device, type: deviceType };\n });\n attempt(() => {\n // Not fingerprint-gated: both blocks are derived from the landing URL and\n // `document.referrer`, neither of which is a device signal.\n if (opts.attribution) {\n const campaign = opts.attribution.campaignBlock();\n if (campaign) context.campaign = campaign;\n const referrer = opts.attribution.referrerBlock();\n if (referrer) context.referrer = referrer;\n }\n });\n attempt(() => {\n if (opts.fingerprint) enrichFingerprint(context);\n });\n attempt(() => {\n // Coordinates only. City/region/country are the collector's, resolved from the request\n // IP and merged over whatever is sent here — see enrich() in the reference collector.\n if (opts.geolocation) {\n const fix = readGeolocation();\n if (fix) context.location = fix;\n }\n });\n\n try {\n if (opts.overrides) {\n for (const [key, value] of Object.entries(opts.overrides)) {\n if (value !== undefined) (context as unknown as Record<string, unknown>)[key] = value;\n }\n context.library = { name: LIBRARY_NAME, version: SDK_VERSION }; // never overridable\n }\n } catch {\n // ignore malformed overrides\n }\n\n // Last, so an embedder's `overrides` cannot resurrect a field the app suppressed. The\n // Shopify pixel supplies page context on every event and would otherwise defeat\n // `page: false`.\n if (opts.tracking) applyTrackingOptions(context, opts.tracking);\n\n return context;\n}\n\n/**\n * Adds parsed browser/os/device attributes and network type.\n *\n * The device fingerprint itself is NOT here — it is the top-level `device_id`, stamped by the\n * capture sites in `depsmith-sdk.ts` from the same `opts.fingerprint` gate that reaches this function.\n */\nfunction enrichFingerprint(context: EventContext): void {\n const { browser, os, deviceType, device: hinted } = parseUserAgent();\n if (browser) context.browser = browser;\n if (os) context.os = os;\n\n // Starts from whatever buildContext already put here (the ungated `type`) so this merges\n // rather than replaces — otherwise enabling fingerprinting would drop the form factor.\n const device: NonNullable<EventContext['device']> = { ...context.device };\n if (deviceType) device.type = deviceType;\n // From UA Client Hints, primed once at init. Absent on non-Chromium and on the first event or\n // two while the hint promise is still in flight — never fabricated.\n if (hinted?.manufacturer) device.manufacturer = hinted.manufacturer;\n if (hinted?.model) device.model = hinted.model;\n // Only when something survived. The block used to be unconditional because `id` always\n // filled it; without that, a user agent that parses to no device type on a non-Chromium\n // browser (so no Client Hints either) would put a bare `device: {}` on every event.\n if (Object.keys(device).length > 0) context.device = device;\n\n const network = readNetwork();\n if (network.type) context.network = { ...context.network, type: network.type };\n}\n\n/** Runs one context block, isolating a failure to that block alone. */\nfunction attempt(fn: () => void): void {\n try {\n fn();\n } catch {\n // context enrichment is best-effort, per block\n }\n}\n\n/** navigator.doNotTrack === '1' (plus legacy vendor locations). */\nexport function dntEnabled(): boolean {\n try {\n if (typeof navigator === 'undefined') return false;\n const nav = navigator as Navigator & { msDoNotTrack?: string };\n const win = (typeof window !== 'undefined' ? window : {}) as Window & { doNotTrack?: string };\n const value = navigator.doNotTrack ?? win.doNotTrack ?? nav.msDoNotTrack;\n return value === '1' || value === 'yes';\n } catch {\n return false;\n }\n}\n","import type { KVStorage } from './queue/storage';\nimport type { ConsentState } from './types';\n\nconst KEY_CONSENT = 'depsmith_consent';\n\n/**\n * Consent state machine: pending | granted | denied (API_SPEC §6).\n * Persisted state from a previous run always wins over config's consentMode.\n * DNT (web) is a non-persistent override that behaves as denied while set.\n */\nexport class ConsentManager {\n private state: ConsentState;\n\n constructor(\n private storage: KVStorage,\n initialMode: 'granted' | 'pending',\n private dntActive: boolean\n ) {\n const persisted = storage.get(KEY_CONSENT) as ConsentState | null;\n this.state =\n persisted === 'granted' || persisted === 'denied' || persisted === 'pending'\n ? persisted\n : initialMode;\n }\n\n private effective(): ConsentState {\n return this.dntActive ? 'denied' : this.state;\n }\n\n /** May this event be captured (persisted locally)? */\n canCapture(): boolean {\n return this.effective() !== 'denied';\n }\n\n /** May queued events be uploaded? */\n canUpload(): boolean {\n return this.effective() === 'granted';\n }\n\n get current(): ConsentState {\n return this.effective();\n }\n\n optIn(): void {\n this.state = 'granted';\n this.storage.set(KEY_CONSENT, 'granted');\n }\n\n optOut(): void {\n this.state = 'denied';\n this.storage.set(KEY_CONSENT, 'denied');\n }\n}\n","/**\n * Deferred work scheduling.\n *\n * Exists so persistence can be moved off the capture task. Writing to `localStorage` is\n * synchronous and blocks the main thread; doing it inside a click handler is what put\n * DepsmithSdk on the critical path of every shopper interaction. Coalescing those writes onto\n * an idle callback keeps the interaction cheap and collapses a burst of events into a\n * single write.\n */\nexport type Scheduler = (fn: () => void) => void;\n\n/**\n * The most a scheduled write may be deferred. Short on purpose: the point is to leave the\n * *current* task, not to wait for genuine idleness. Anything longer widens the window in\n * which a hard crash loses events for no additional performance gain.\n */\nconst IDLE_TIMEOUT_MS = 250;\n\ninterface IdleWindow {\n requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number;\n}\n\n/**\n * Runs `fn` at the next idle moment, or within {@link IDLE_TIMEOUT_MS} at the latest.\n *\n * Falls back to a macrotask where `requestIdleCallback` is absent — Safari below 16.4 and\n * jsdom. The fallback is still correct, just less considerate about when it lands.\n */\nexport const idleScheduler: Scheduler = (fn) => {\n const idle = (globalThis as IdleWindow).requestIdleCallback;\n if (typeof idle === 'function') {\n idle(fn, { timeout: IDLE_TIMEOUT_MS });\n return;\n }\n setTimeout(fn, 0);\n};\n\n/**\n * Runs `fn` immediately, restoring write-through behaviour.\n *\n * The seam tests use to assert persisted state without pumping timers, and the escape\n * hatch for any host that needs durability over latency.\n */\nexport const syncScheduler: Scheduler = (fn) => fn();\n","import type { KVStorage } from './storage';\nimport type { Logger } from '../utils/logger';\nimport type { DepsmithSdkEvent } from '../types';\nimport { idleScheduler, type Scheduler } from '../utils/scheduler';\n\nexport const KEY_QUEUE = 'depsmith_queue';\n\n/**\n * Ceiling on the serialised queue, in UTF-16 code units.\n *\n * `maxSize` alone bounds the queue by *count*, which says nothing about the bytes on disk:\n * 1000 events at ~700 chars each is ~700 KB of a 5 MB origin-shared `localStorage` budget\n * that the host page and every other script on the origin also draw on. It is also what\n * sets the worst case for the serialise-on-write below, so capping it bounds both.\n *\n * Code units rather than bytes because that is the unit browsers actually meter\n * `localStorage` quota in, and it needs no encoding pass to measure.\n */\nconst DEFAULT_MAX_CHARS = 512 * 1024;\n\n/** `[` + `]` — the serialised length of an empty queue. */\nconst BRACKETS = 2;\n\n/**\n * Event types evicted LAST, because losing one is not proportional to losing an event.\n *\n * An ordinary event dropped under queue pressure costs that event. A dropped `$identify`\n * costs every anonymous event that came before it, forever: it carries the only edge binding\n * `anonymous_id` to `user_id` (API_SPEC §4.1), the SDK never re-emits it unless the app calls\n * `identify()` again, and a collector resolving history has nothing to join on. `$alias` and\n * `$group` are the same shape — an explicit, one-shot statement about identity.\n *\n * This mirrors the sampling exemption one layer up (`inSample` in depsmith-sdk.ts), and for exactly\n * the same reason. Sampling already refuses to drop these; the queue was still free to.\n */\nconst IDENTITY_EVENT_TYPES = new Set(['identify', 'alias', 'group']);\n\n/** A malformed restored entry has no event_type and is treated as ordinary — safe default. */\nfunction isIdentityEvent(event: DepsmithSdkEvent): boolean {\n return IDENTITY_EVENT_TYPES.has(event?.event_type);\n}\n\nexport interface EventQueueOptions {\n /** Serialised-size ceiling in UTF-16 code units. Defaults to 512 Ki. */\n maxChars?: number;\n /**\n * How a persist is deferred. Defaults to an idle callback; tests and hosts that need\n * write-through pass `syncScheduler`.\n */\n schedule?: Scheduler;\n}\n\n/**\n * Persist-before-send event queue (API_SPEC §1, §8). In-memory mirror with\n * **write-behind** persistence; corrupt entries are discarded individually on load.\n *\n * Persistence is coalesced onto an idle callback rather than written through on every\n * mutation. `localStorage.setItem` is a synchronous main-thread call and the value is the\n * whole queue, so writing through meant every captured event paid an O(queue) serialise\n * plus a blocking write — inside the click handler that captured it.\n *\n * The durability cost is one idle tick: only a hard crash inside that window loses events.\n * Ordinary teardown is covered because the client force-flushes via {@link persistNow} on\n * `pagehide`, and privacy-critical paths (`clear`) write through unconditionally.\n *\n * The byte ceiling is enforced where events ENTER the queue, never inside a persist.\n * Trimming during `persistNow()` would mutate the queue from a call the uploader makes\n * between `peek()` and the network send, so an over-budget queue could discard the very\n * events that were in flight. Sizes are tracked incrementally instead, which also means\n * enforcing the cap costs no re-serialise at all.\n */\nexport class EventQueue {\n protected events: DepsmithSdkEvent[] = [];\n /** Serialised length of each entry in `events`, same order, same length. */\n private sizes: number[] = [];\n /** Running sum of `sizes`, so the budget check touches no JSON. */\n private sizeSum = 0;\n protected maxChars: number;\n private schedule: Scheduler;\n /** Set when `events` has diverged from what is on disk. */\n protected dirty = false;\n /** Set between scheduling a write and it running, so a burst schedules only one. */\n private scheduled = false;\n\n constructor(\n protected storage: KVStorage,\n protected maxSize: number,\n private logger: Logger,\n options: EventQueueOptions = {}\n ) {\n this.maxChars = options.maxChars ?? DEFAULT_MAX_CHARS;\n this.schedule = options.schedule ?? idleScheduler;\n this.restore();\n }\n\n private restore(): void {\n try {\n const raw = this.storage.get(KEY_QUEUE);\n if (!raw) return;\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return;\n const kept = parsed.filter(\n (e): e is DepsmithSdkEvent =>\n !!e && typeof e === 'object' && typeof (e as DepsmithSdkEvent).event_id === 'string'\n );\n this.reset(kept);\n if (kept.length !== parsed.length) {\n this.logger.warn('discarded corrupt queued events on restore');\n this.markDirty();\n }\n // A ceiling lowered between sessions, or a record written by an older build, can\n // leave a restored queue over budget.\n if (this.trimToBudget()) this.markDirty();\n } catch {\n this.logger.warn('queue storage corrupt; starting empty');\n this.reset([]);\n this.storage.remove(KEY_QUEUE);\n }\n }\n\n /** Replaces the queue and rebuilds the size index in one pass. */\n private reset(events: DepsmithSdkEvent[]): void {\n this.events = events;\n this.sizes = events.map((e) => measure(e));\n this.sizeSum = this.sizes.reduce((a, b) => a + b, 0);\n }\n\n /**\n * Exact length of `JSON.stringify(this.events)` without building it: every entry, plus\n * one comma between each pair, plus the brackets.\n */\n protected serializedLength(): number {\n if (this.events.length === 0) return BRACKETS;\n return this.sizeSum + (this.events.length - 1) + BRACKETS;\n }\n\n /**\n * Drops events until the queue fits `maxChars`. Returns whether it dropped any.\n *\n * Identity events go last here too. This is the second eviction path, and protecting only\n * the count cap would have left the merge edge just as droppable — a queue of big events\n * hits the byte ceiling long before the count one.\n */\n private trimToBudget(): boolean {\n let dropped = 0;\n while (this.events.length > 0 && this.serializedLength() > this.maxChars) {\n this.evictAt(this.victimIndex());\n dropped++;\n }\n if (dropped > 0) {\n this.logger.warn(`queue byte cap reached; dropped ${dropped} event(s)`);\n }\n return dropped > 0;\n }\n\n /** Marks the queue for persistence and schedules a single coalesced write. */\n private markDirty(): void {\n this.dirty = true;\n if (this.scheduled) return;\n this.scheduled = true;\n this.schedule(() => {\n this.scheduled = false;\n this.persistNow();\n });\n }\n\n /**\n * Writes immediately, if there is anything to write.\n *\n * Called on `pagehide`, `shutdown()`, and by the uploader before each batch leaves — the\n * points where deferring any further would mean losing the events outright. Idempotent\n * and cheap when the queue is clean, and never mutates the queue: the budget is already\n * enforced at enqueue, so what is in memory is by construction writable.\n */\n persistNow(): void {\n if (!this.dirty) return;\n this.dirty = false;\n this.storage.set(KEY_QUEUE, JSON.stringify(this.events));\n }\n\n /**\n * Prepend OLDER events recovered after async storage hydration (IndexedDB).\n * Dedupes by event_id; cap still drops oldest first.\n */\n prepend(events: DepsmithSdkEvent[]): void {\n const existing = new Set(this.events.map((e) => e.event_id));\n const fresh = events.filter(\n (e): e is DepsmithSdkEvent =>\n !!e && typeof e === 'object' && typeof e.event_id === 'string' && !existing.has(e.event_id)\n );\n if (fresh.length === 0) return;\n this.reset([...fresh, ...this.events]);\n if (this.events.length > this.maxSize) {\n this.dropOldest(this.events.length - this.maxSize);\n }\n this.trimToBudget();\n this.markDirty();\n }\n\n enqueue(event: DepsmithSdkEvent): void {\n const size = measure(event);\n // Rejected rather than admitted and then trimmed around. Admitting it would evict the\n // whole rest of the queue on the way to discovering it still does not fit, so one\n // bloated event would take every good one with it.\n if (size + BRACKETS > this.maxChars) {\n this.logger.warn(`event ${event.event_id} exceeds the queue byte cap; dropped`);\n return;\n }\n this.events.push(event);\n this.sizes.push(size);\n this.sizeSum += size;\n if (this.events.length > this.maxSize) {\n const dropped = this.events.length - this.maxSize;\n this.dropOldest(dropped);\n this.logger.warn(`queue cap reached; dropped ${dropped} event(s)`);\n }\n this.trimToBudget();\n this.markDirty();\n }\n\n /**\n * Index of the next event to evict: the oldest NON-identity event, else the oldest event.\n *\n * The fallback matters — a queue holding nothing but identity events must still be\n * evictable, or the cap stops being a cap and both loops here stop terminating.\n *\n * Linear, but it returns 0 on the first comparison in the ordinary case (the oldest event\n * is not an identity event), so the scan only walks as far as the identity events actually\n * queued ahead of it.\n */\n private victimIndex(): number {\n for (let i = 0; i < this.events.length; i++) {\n if (!isIdentityEvent(this.events[i]!)) return i;\n }\n return 0;\n }\n\n /** Removes entry `index`, keeping the size index and running sum in step. */\n private evictAt(index: number): void {\n this.events.splice(index, 1);\n this.sizeSum -= this.sizes.splice(index, 1)[0] ?? 0;\n }\n\n /**\n * Removes `count` entries, identity events last. Relative order of survivors is preserved.\n *\n * Named for the policy rather than the mechanism: this is no longer strictly drop-oldest,\n * and a caller that wants FIFO regardless does not exist.\n */\n private dropOldest(count: number): void {\n for (let n = 0; n < count && this.events.length > 0; n++) {\n this.evictAt(this.victimIndex());\n }\n }\n\n get size(): number {\n return this.events.length;\n }\n\n /**\n * Oldest-first view for uploading, from index `from`: up to `count` events whose serialised\n * size (plus a comma each) stays within `maxChars` — but always at least one, so an event\n * larger than the budget still leaves on its own instead of wedging the head. Does not remove.\n */\n peek(count: number, maxChars = Infinity, from = 0): DepsmithSdkEvent[] {\n let end = from;\n for (let total = 0; end < this.events.length && end - from < count; end++) {\n total += this.sizes[end]! + 1;\n if (end > from && total > maxChars) break;\n }\n return this.events.slice(from, end);\n }\n\n /** Remove uploaded (or poison) events by id. */\n remove(eventIds: string[]): void {\n const ids = new Set(eventIds);\n const events: DepsmithSdkEvent[] = [];\n const sizes: number[] = [];\n let sizeSum = 0;\n for (let i = 0; i < this.events.length; i++) {\n const event = this.events[i]!;\n if (ids.has(event.event_id)) continue;\n const size = this.sizes[i]!;\n events.push(event);\n sizes.push(size);\n sizeSum += size;\n }\n this.events = events;\n this.sizes = sizes;\n this.sizeSum = sizeSum;\n this.markDirty();\n }\n\n /** Releases anything held for the page's lifetime. Nothing here; see `tab-queue.ts`. */\n close(): void {}\n\n /**\n * Empties the queue and storage immediately.\n *\n * Write-through on purpose: this is the opt-out path, and a deferred delete would leave\n * a withdrawn visitor's events sitting on disk for an idle tick.\n */\n clear(): void {\n this.reset([]);\n this.dirty = false;\n this.storage.remove(KEY_QUEUE);\n }\n}\n\n/** Serialised length of one event — what it will contribute to the persisted array. */\nfunction measure(event: DepsmithSdkEvent): number {\n return JSON.stringify(event).length;\n}\n","/** The millisecond the counter below belongs to, and its value there. */\nlet lastMs = -1;\nlet lastSeq = 0;\n\n/** 26 bits: `rand_a` (12) plus the first 14 bits of `rand_b`. */\nconst SEQ_MASK = 0x3ffffff;\n\n/**\n * RFC 9562 UUID v7: 48-bit unix-ms timestamp, a 26-bit counter, 48 random bits.\n *\n * Time-ordered, so `event_id` doubles as a capture-order tiebreaker — which needs the counter.\n * With every non-timestamp bit random, two ids minted in the same millisecond sorted in a random\n * order, and that is the ordinary case rather than a rare one: `$session_start` and the event\n * that opened the session, `$web_vitals` and `$page_leave` at unload, any burst of `track()`.\n *\n * So ids minted for the same `now` count up (RFC 9562 §6.2 method 1, a fixed-length dedicated\n * counter). The counter is re-seeded at random for each new millisecond with its top bit clear,\n * leaving 2^25 increments before it could wrap; it sits in `rand_a` and the head of `rand_b`, so\n * plain string comparison of two ids gives capture order.\n *\n * The timestamp is always exactly `now`, never nudged forward: `session_started_at` is read back\n * out of a session id (see {@link uuidv7ToMs}). A `now` EARLIER than the last one — a deferred\n * `$page_view` stamped at its navigation — gets a fresh random counter and leaves the running one\n * alone, so the ids around it stay ordered. Monotonic per page, not across tabs.\n */\nexport function uuidv7(now: number): string {\n const bytes = new Uint8Array(16);\n if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n\n // 48-bit big-endian timestamp\n bytes[0] = (now / 2 ** 40) & 0xff;\n bytes[1] = (now / 2 ** 32) & 0xff;\n bytes[2] = (now / 2 ** 24) & 0xff;\n bytes[3] = (now / 2 ** 16) & 0xff;\n bytes[4] = (now / 2 ** 8) & 0xff;\n bytes[5] = now & 0xff;\n\n // 25 random bits, from the positions the counter is written back to.\n let seq = ((bytes[6]! & 0x07) << 22) | (bytes[7]! << 14) | ((bytes[8]! & 0x3f) << 8) | bytes[9]!;\n if (now === lastMs) {\n seq = lastSeq = (lastSeq + 1) & SEQ_MASK;\n } else if (now > lastMs) {\n lastMs = now;\n lastSeq = seq;\n }\n bytes[6] = 0x70 | (seq >>> 22); // version 7 + counter bits 25..22\n bytes[7] = (seq >>> 14) & 0xff;\n bytes[8] = 0x80 | ((seq >>> 8) & 0x3f); // variant 10 + counter bits 13..8\n bytes[9] = seq & 0xff;\n\n let hex = '';\n for (let i = 0; i < 16; i++) hex += (bytes[i]! + 0x100).toString(16).slice(1);\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/**\n * Recover the creation time from a UUID v7 — the first 48 bits are the unix-ms timestamp.\n *\n * This is what makes `session_started_at` free to add: a session already persisted in the\n * field has no stored start time, but its id *is* one. So there is no backfill, no lossy\n * default and no storage format version — old records decode exactly.\n *\n * Returns null if the string isn't a v7 uuid, so a caller can fall back rather than\n * silently trusting a garbage timestamp.\n */\nexport function uuidv7ToMs(id: string): number | null {\n if (!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id)) {\n return null;\n }\n const hex = id.slice(0, 8) + id.slice(9, 13); // first 48 bits, dashes removed\n const ms = parseInt(hex, 16);\n return Number.isFinite(ms) ? ms : null;\n}\n","import { uuidv7ToMs } from '../utils/uuidv7';\n\n/**\n * Key-value storage abstraction. localStorage when available (synchronous — safe to\n * write during pagehide), in-memory fallback for SSR / privacy modes that block storage.\n */\nexport interface KVStorage {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n}\n\nexport const DEPSMITH_SDK_STORAGE_KEYS = [\n 'depsmith_anonymous_id',\n 'depsmith_anon_reset_at',\n 'depsmith_user_id',\n 'depsmith_group_id',\n 'depsmith_user_props',\n 'depsmith_session',\n 'depsmith_consent',\n 'depsmith_queue',\n 'depsmith_config_fp',\n 'depsmith_net_breaker',\n 'depsmith_campaign',\n 'depsmith_referrer',\n 'depsmith_super_props',\n] as const;\n\nexport class MemoryAdapter implements KVStorage {\n private data = new Map<string, string>();\n\n get(key: string): string | null {\n return this.data.get(key) ?? null;\n }\n\n set(key: string, value: string): void {\n this.data.set(key, value);\n }\n\n remove(key: string): void {\n this.data.delete(key);\n }\n}\n\n/**\n * First-party cookie storage.\n *\n * `domain` is optional. With one, the cookie is shared across subdomains (the `cookieDomain`\n * config). Without one the browser sets a host-only cookie, which is what the identity mirror\n * wants: same origin, no widening of scope, and no configuration required to get a second copy\n * of the device identity.\n */\nexport class CookieAdapter implements KVStorage {\n constructor(private domain?: string) {}\n\n get(key: string): string | null {\n try {\n const prefix = `${encodeURIComponent(key)}=`;\n for (const part of document.cookie.split('; ')) {\n if (part.startsWith(prefix)) return decodeURIComponent(part.slice(prefix.length));\n }\n } catch {\n /* no document / cookies blocked */\n }\n return null;\n }\n\n private attributes(maxAge: number): string {\n // 400 days is the ceiling Chrome clamps cookie lifetime to, so asking for more is silently\n // truncated and just misrepresents the intent.\n const domain = this.domain ? `; domain=${this.domain}` : '';\n // Secure is required for SameSite=None and harmless on https; omitted on http so local\n // development over plain HTTP still works.\n const secure =\n typeof location !== 'undefined' && location.protocol === 'https:' ? '; Secure' : '';\n return `${domain}; path=/; max-age=${maxAge}; SameSite=Lax${secure}`;\n }\n\n set(key: string, value: string): void {\n try {\n const maxAge = 60 * 60 * 24 * 400;\n document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}${this.attributes(maxAge)}`;\n } catch {\n /* ignore */\n }\n }\n\n remove(key: string): void {\n try {\n document.cookie = `${encodeURIComponent(key)}=${this.attributes(0)}`;\n } catch {\n /* ignore */\n }\n }\n}\n\n/**\n * When `reset()` last rotated the anonymous id, epoch ms. Written by `IdentityManager.reset()`\n * and mirrored with the id it retires — see the conflict rule in {@link RedundantAdapter}.\n */\nexport const KEY_ANON_RESET = 'depsmith_anon_reset_at';\n\n/**\n * Keys mirrored across both identity stores.\n *\n * `depsmith_anonymous_id` and the reset marker that travels with it. The id is the device\n * identity — the thing whose loss makes a returning visitor look new — and it is always a\n * UUIDv7, which is what makes the conflict rule below well-defined. `depsmith_user_id` and\n * `depsmith_group_id` are deliberately NOT mirrored: they are caller-supplied values the app\n * re-establishes by calling identify() again after login, so copying them into a cookie would\n * widen PII exposure to buy nothing. `depsmith_user_props` is unbounded and would not fit a\n * 4 KB cookie anyway.\n */\nexport const MIRRORED_IDENTITY_KEYS: ReadonlySet<string> = new Set([\n 'depsmith_anonymous_id',\n KEY_ANON_RESET,\n]);\n\n/**\n * Two stores holding one identity: read from either, write to both, and heal whichever lost it.\n *\n * localStorage and cookies are cleared by different user actions and different browser policies —\n * \"clear site data\" takes both, but a cookie-only purge, an ITP eviction, or a storage quota\n * reset takes one. Keeping the device identity in both means it survives losing either, which is\n * the entire point: a returning visitor stays the same visitor.\n *\n * Two copies, not five. Adding IndexedDB, the Cache API and ETag redundancy on top is evercookie\n * behaviour — it defeats deletion rather than tolerating partial loss, and it is out of scope.\n * Both of these are ordinary first-party stores the user can clear, and clearing both works.\n */\nexport class RedundantAdapter implements KVStorage {\n constructor(\n private primary: KVStorage,\n private secondary: KVStorage,\n private mirrored: ReadonlySet<string> = MIRRORED_IDENTITY_KEYS\n ) {}\n\n get(key: string): string | null {\n const fromPrimary = this.primary.get(key);\n if (!this.mirrored.has(key)) return fromPrimary;\n\n const fromSecondary = this.secondary.get(key);\n if (fromPrimary === fromSecondary) return fromPrimary;\n\n // One store lost it — restore from the other. This is the healing case that makes a\n // partial clear survivable rather than merely detectable.\n if (fromPrimary === null && fromSecondary !== null) {\n this.primary.set(key, fromSecondary);\n return fromSecondary;\n }\n if (fromSecondary === null && fromPrimary !== null) {\n this.secondary.set(key, fromPrimary);\n return fromPrimary;\n }\n\n const winner = this.pick(fromPrimary!, fromSecondary!);\n this.primary.set(key, winner);\n this.secondary.set(key, winner);\n return winner;\n }\n\n /**\n * Both stores hold an id and they disagree.\n *\n * Prefer the OLDER one: without a `reset()`, a newer id can only have been minted after a\n * store was cleared, so the older is the device's original identity and keeps the visitor\n * continuous. UUIDv7 is time-ordered, so \"older\" is readable from the value itself. Falls\n * back to the primary for a non-v7 value.\n *\n * **Unless `reset()` retired it.** `reset()` deliberately mints a newer id, and with\n * `cookieDomain` the cookie is shared by subdomains whose localStorage is not: log out on\n * app.example.com, visit www.example.com, and older-wins read www's stale id back into the\n * shared cookie — the next person on that browser inherited the previous user's anonymous_id,\n * the cross-user merge `reset()` exists to prevent (API_SPEC §4.1). So `reset()` records when\n * it ran, and an id minted before that moment has been retired and loses to one that was not.\n * The marker is taken from whichever store has the later one and written to both, so it\n * reaches the stores that never saw the reset together with the id it protects.\n */\n private pick(a: string, b: string): string {\n // `a` is the primary's. Short names on purpose: the pixel build ships this unminified.\n const aMs = uuidv7ToMs(a);\n const bMs = uuidv7ToMs(b);\n if (aMs === null || bMs === null) return a;\n const stores = [this.primary, this.secondary];\n const at = Math.max(...stores.map((s) => Number(s.get(KEY_ANON_RESET)) || 0));\n if (at) stores.forEach((s) => s.set(KEY_ANON_RESET, `${at}`));\n // \"Live\": minted at or after the last reset.\n const live = aMs >= at;\n if (live !== bMs >= at) return live ? a : b;\n return aMs <= bMs ? a : b;\n }\n\n set(key: string, value: string): void {\n this.primary.set(key, value);\n if (this.mirrored.has(key)) this.secondary.set(key, value);\n }\n\n remove(key: string): void {\n this.primary.remove(key);\n // Unconditional: a key that stopped being mirrored must still be cleared from the store it\n // used to live in, or reset() would leave a copy behind for get() to heal back into place.\n this.secondary.remove(key);\n }\n}\n\n/**\n * Minimal async key-value backend. Shaped to accept Shopify's `browser.localStorage`\n * / `browser.sessionStorage` directly (all methods Promise-returning, proxied to the\n * top frame from the web-pixel sandbox).\n */\nexport interface AsyncKV {\n getItem(key: string): Promise<string | null | undefined>;\n setItem(key: string, value: string): Promise<unknown>;\n removeItem(key: string): Promise<unknown>;\n}\n\n/**\n * Synchronous `KVStorage` over an asynchronous backend: an in-memory mirror serves\n * reads, writes go through to the mirror and are flushed write-behind.\n *\n * `hydrate()` must be awaited **before** constructing a DepsmithSdkClient over this\n * adapter — IdentityManager/SessionManager/EventQueue all read in their constructors,\n * and a cold mirror would mint a fresh anonymousId over a returning visitor's.\n */\nexport class AsyncMirrorAdapter implements KVStorage {\n private mirror = new Map<string, string>();\n private hydrated: Promise<void> | null = null;\n\n constructor(\n private backend: AsyncKV,\n private keys: readonly string[] = DEPSMITH_SDK_STORAGE_KEYS\n ) {}\n\n /** Bulk-loads `keys` into the mirror. Idempotent; never rejects. */\n hydrate(): Promise<void> {\n this.hydrated ??= Promise.all(\n this.keys.map(async (key) => {\n try {\n const value = await this.backend.getItem(key);\n // Don't clobber values written before hydration resolved.\n if (typeof value === 'string' && !this.mirror.has(key)) this.mirror.set(key, value);\n } catch {\n /* degrade to memory-only for this key */\n }\n })\n ).then(() => undefined);\n return this.hydrated;\n }\n\n get(key: string): string | null {\n return this.mirror.get(key) ?? null;\n }\n\n set(key: string, value: string): void {\n this.mirror.set(key, value);\n void Promise.resolve(this.backend.setItem(key, value)).catch(() => {\n /* quota / sandbox teardown — mirror still serves reads */\n });\n }\n\n remove(key: string): void {\n this.mirror.delete(key);\n void Promise.resolve(this.backend.removeItem(key)).catch(() => {\n /* ignore */\n });\n }\n}\n","import type { DepsmithSdkEvent } from '../types';\nimport type { Logger } from '../utils/logger';\nimport { MemoryAdapter, type KVStorage } from './storage';\n\n/**\n * The browser-storage backends the SDK picks for itself: localStorage and IndexedDB.\n *\n * Split out of `storage.ts` so the Shopify custom-pixel build can compile them away. That build\n * ALWAYS injects its own `AsyncMirrorAdapter` over the sandbox's async storage, so `defaultStorage()`\n * is never called and neither adapter can execute — yet the build is deliberately unminified, so both\n * shipped anyway, against an editor that refuses to save a file over 64,000 characters.\n *\n * Everything still reachable in that build — MemoryAdapter, CookieAdapter, RedundantAdapter,\n * AsyncMirrorAdapter — stays in `storage.ts`, which is why this is a split rather than a swap of the\n * whole module.\n */\n/**\n * Every key DepsmithSdk persists. Single source of truth for hosts that must enumerate\n * them up front — e.g. `AsyncMirrorAdapter`, whose backend has no bulk read.\n * Kept in sync with the `KEY_*` consts in identity/session/consent/queue/depsmith-sdk/breaker.\n */\nexport class LocalStorageAdapter implements KVStorage {\n /** `ls` is public so the cross-tab queue can match `StorageEvent.storageArea` against it. */\n constructor(readonly ls: Storage) {}\n\n get(key: string): string | null {\n try {\n return this.ls.getItem(key);\n } catch {\n return null;\n }\n }\n\n set(key: string, value: string): void {\n try {\n this.ls.setItem(key, value);\n } catch {\n // quota exceeded / private mode — silently degrade\n }\n }\n\n remove(key: string): void {\n try {\n this.ls.removeItem(key);\n } catch {\n /* ignore */\n }\n }\n}\n\n/**\n * IndexedDB-backed storage: in-memory write-through mirror with async write-behind\n * persistence. Reads are synchronous against the mirror; `hydrate()` must be awaited\n * before trusting reads for pre-existing data (DepsmithSdkClient gates uploads on it).\n */\nexport class IndexedDBAdapter implements KVStorage {\n private mirror = new Map<string, string>();\n private snapshot = new Map<string, string>();\n private db: IDBDatabase | null = null;\n private ready: Promise<void>;\n\n constructor(dbName = 'depsmith-sdk') {\n this.ready = this.open(dbName);\n }\n\n private open(dbName: string): Promise<void> {\n return new Promise((resolve) => {\n try {\n const request = indexedDB.open(dbName, 1);\n request.onupgradeneeded = () => request.result.createObjectStore('kv');\n request.onsuccess = () => {\n this.db = request.result;\n const tx = this.db.transaction('kv', 'readonly').objectStore('kv');\n const keysReq = tx.getAllKeys();\n const valuesReq = tx.getAll();\n valuesReq.onsuccess = () => {\n const keys = keysReq.result as string[];\n (valuesReq.result as string[]).forEach((value, i) => {\n const key = keys[i];\n if (key === undefined) return;\n this.snapshot.set(key, value);\n // hydrate without clobbering values written before hydration completed\n if (!this.mirror.has(key)) this.mirror.set(key, value);\n });\n resolve();\n };\n valuesReq.onerror = () => resolve();\n };\n request.onerror = () => resolve(); // degrade to memory-only\n } catch {\n resolve();\n }\n });\n }\n\n /**\n * Resolves with the persisted snapshot once loaded. Keys written before hydration\n * are NOT overwritten in the mirror — the caller merges conflicts (e.g. the queue\n * prepends persisted events to ones captured during startup).\n */\n hydrate(): Promise<ReadonlyMap<string, string>> {\n return this.ready.then(() => this.snapshot);\n }\n\n get(key: string): string | null {\n return this.mirror.get(key) ?? null;\n }\n\n set(key: string, value: string): void {\n this.mirror.set(key, value);\n void this.ready.then(() => {\n try {\n this.db?.transaction('kv', 'readwrite').objectStore('kv').put(value, key);\n } catch {\n /* quota / closing — mirror still serves reads */\n }\n });\n }\n\n remove(key: string): void {\n this.mirror.delete(key);\n void this.ready.then(() => {\n try {\n this.db?.transaction('kv', 'readwrite').objectStore('kv').delete(key);\n } catch {\n /* ignore */\n }\n });\n }\n}\n\n/** Picks localStorage if usable, else memory. */\nexport function defaultStorage(): KVStorage {\n try {\n if (typeof window !== 'undefined' && window.localStorage) {\n const probe = '__depsmith_probe__';\n window.localStorage.setItem(probe, '1');\n window.localStorage.removeItem(probe);\n return new LocalStorageAdapter(window.localStorage);\n }\n } catch {\n /* fall through */\n }\n return new MemoryAdapter();\n}\n\n/** The queue's store: IndexedDB when `storage: 'indexeddb'` asks for it and it exists, else `fallback`. */\nexport function pickQueueStorage(mode: string | undefined, fallback: KVStorage): KVStorage {\n return mode === 'indexeddb' && typeof indexedDB !== 'undefined' ? new IndexedDBAdapter() : fallback;\n}\n\n/**\n * Merges the events IndexedDB persisted on a previous page back into the queue, once they\n * have loaded. Resolves immediately for any other store. Uploads wait on the returned promise.\n *\n * Lives here rather than in the client because it is IndexedDB-only, and the Shopify pixel\n * build swaps this whole module out.\n */\nexport function hydrateQueue(\n queueStorage: KVStorage,\n storage: KVStorage,\n consent: { canCapture(): boolean; optOut(): void },\n queue: { clear(): void; prepend(events: DepsmithSdkEvent[]): void },\n drifted: boolean,\n logger: Logger\n): Promise<void> {\n if (!(queueStorage instanceof IndexedDBAdapter)) return Promise.resolve();\n return queueStorage.hydrate().then((persisted) => {\n try {\n // Builds before this one kept consent in IndexedDB as well. An opt-out recorded there\n // must still be honoured the first time this build runs.\n const KEY = 'depsmith_consent';\n if (persisted.get(KEY) === 'denied' && !storage.get(KEY)) consent.optOut();\n // The persisted events are only merged back for a visitor who may still be tracked and\n // a project they still belong to. Otherwise an opt-out (now, or between init and this\n // callback) or an apiKey change would be undone by the queue it had just cleared.\n if (drifted || !consent.canCapture()) {\n queue.clear();\n return;\n }\n const raw = persisted.get('depsmith_queue');\n if (raw) queue.prepend(JSON.parse(raw) as DepsmithSdkEvent[]);\n } catch {\n logger.warn('persisted queue corrupt; discarded');\n }\n });\n}\n","import type { DepsmithSdkEvent } from '../types';\nimport { EventQueue as BaseQueue, KEY_QUEUE } from './queue';\nimport { LocalStorageAdapter } from './storage-local';\n\n/** The event ids in a stored queue value, or null if it is not a readable array. */\nfunction storedEvents(raw: string | null): DepsmithSdkEvent[] | null {\n try {\n const parsed: unknown = JSON.parse(raw || '[]');\n if (!Array.isArray(parsed)) return null;\n return parsed.filter(\n (e): e is DepsmithSdkEvent =>\n !!e && typeof e === 'object' && typeof (e as DepsmithSdkEvent).event_id === 'string'\n );\n } catch {\n return null;\n }\n}\n\n/**\n * The event queue as the browser builds use it: one storage key shared by every open tab.\n *\n * {@link BaseQueue} treats that key as its own — it restores the array once and then\n * overwrites it with its in-memory copy. With two tabs open that lost and duplicated events\n * (deep-dive WC-03):\n * - **loss** — tab B's write replaced tab A's persisted events; A was not dirty, so it never\n * wrote them back, and closing A dropped them. Worst under `pending` consent or offline,\n * where events sit in storage for a long time;\n * - **resurrection** — a tab that had restored events another tab later uploaded wrote them\n * back on its next persist, and they were sent again on the next page load.\n *\n * Two rules fix both, with no locks and no change to the stored format:\n *\n * 1. **A write merges instead of overwriting.** Entries in storage that this tab has never\n * held belong to another tab and are written back untouched. Entries this tab DID hold and\n * no longer does were uploaded (or evicted) here, so they are left out.\n * 2. **A removal in another tab is followed here.** The `storage` event carries the new value;\n * any event this tab knew to be in storage and that is now gone was removed by its other\n * holder, so it is dropped from memory too rather than written back or sent again.\n *\n * Nothing foreign is ever adopted mid-page: another tab's events are that tab's to send, and if\n * it closes first they are restored by the next page load, exactly as before.\n *\n * What this does not do: two tabs holding the same restored events can still upload them at\n * the same moment — delivery is at-least-once (API_SPEC §10). The window is now the length of\n * one upload rather than \"always\".\n *\n * Scope: localStorage only. With `storage: 'indexeddb'` each tab reads its own in-memory mirror,\n * which other tabs' writes never reach, so the merge sees no foreign events and the last tab\n * to write still wins — the pre-WC-03 behaviour, for that opt-in mode. Closing it needs the\n * read-merge-write inside one IndexedDB transaction; tracked as a follow-up.\n *\n * A separate class because the Shopify custom-pixel bundle has one sandbox, no `storage`\n * events and a 64,000-character ceiling; that build resolves this module to the plain queue\n * (see `tab-queue.noop.ts` and `tsup.config.ts`).\n */\nexport class EventQueue extends BaseQueue {\n /** Ids this tab holds and has seen in storage — restored from it, or written to it. */\n private known = new Set<string>(this.ids());\n /**\n * Ids this tab held and removed (uploaded, evicted, or removed by another tab), kept while a\n * copy may still be in storage. Without them a stale copy — written by a tab that had not yet\n * seen the removal, or left behind by a write that failed on quota — reads as another tab's\n * event and is written back, to be sent again on the next page load.\n */\n private removed = new Set<string>();\n\n /** The `Storage` this queue persists to, when that is `localStorage`; else null. */\n private area: Storage | null = null;\n\n private onStorage = (event: StorageEvent): void => {\n // Only this queue's key in this queue's store. A `clear()` (key null) is not a removal by\n // another holder — nobody uploaded those events — so it is ignored: the next persist here\n // writes this tab's events back. An opt-out elsewhere removes KEY_QUEUE and IS followed.\n if (event.key !== KEY_QUEUE || event.storageArea !== this.area) return;\n const stored = storedEvents(event.newValue);\n if (!stored) return;\n const present = new Set<string>();\n for (const e of stored) present.add(e.event_id);\n const gone: string[] = [];\n this.known.forEach((id) => {\n if (!present.has(id)) gone.push(id);\n });\n if (gone.length === 0) return;\n for (const id of gone) {\n this.known.delete(id);\n this.removed.add(id);\n }\n this.remove(gone);\n };\n\n constructor(...args: ConstructorParameters<typeof BaseQueue>) {\n super(...args);\n // `storage` events only ever describe localStorage/sessionStorage. A memory- or\n // IndexedDB-backed queue shares nothing with other tabs, so it must not listen: another\n // tab's localStorage queue would otherwise read as removals from this one.\n if (!(this.storage instanceof LocalStorageAdapter)) return;\n this.area = this.storage.ls;\n try {\n if (typeof window !== 'undefined') window.addEventListener('storage', this.onStorage);\n } catch {\n /* no storage events here — the merge-on-write half still applies */\n }\n }\n\n private ids(): string[] {\n const ids: string[] = [];\n for (const e of this.events) ids.push(e.event_id);\n return ids;\n }\n\n override persistNow(): void {\n if (!this.dirty) return;\n this.dirty = false;\n const mine = new Set(this.ids());\n // Known-but-not-mine: I held it and removed it, so it must not come back.\n this.known.forEach((id) => {\n if (!mine.has(id)) this.removed.add(id);\n });\n const foreign: DepsmithSdkEvent[] = [];\n const present = new Set<string>();\n for (const e of storedEvents(this.storage.get(KEY_QUEUE)) ?? []) {\n present.add(e.event_id);\n // Not mine and never removed here: another tab's.\n if (!mine.has(e.event_id) && !this.removed.has(e.event_id)) foreign.push(e);\n }\n this.storage.set(KEY_QUEUE, JSON.stringify(this.bounded(foreign).concat(this.events)));\n this.known = mine;\n // A tombstone is needed only while some copy is still stored; this keeps the set bounded\n // by the stored queue rather than growing for the life of the page.\n this.removed.forEach((id) => {\n if (!present.has(id)) this.removed.delete(id);\n });\n }\n\n /**\n * The oldest-first tail of `foreign` that fits beside this tab's events within the queue's\n * count and character caps. This tab's own events are bounded at enqueue; the merge must not\n * let N tabs together exceed what one queue may store, or the write fails on quota and every\n * tab's events are lost with it. Evicting a foreign entry here is what the cap would have done\n * in its own tab: the owner sees it gone from storage and drops it.\n */\n private bounded(foreign: DepsmithSdkEvent[]): DepsmithSdkEvent[] {\n if (foreign.length === 0) return foreign;\n let room = this.maxSize - this.events.length;\n let chars = this.maxChars - this.serializedLength();\n const kept: DepsmithSdkEvent[] = [];\n for (let i = foreign.length - 1; i >= 0 && room > 0; i--) {\n const size = JSON.stringify(foreign[i]).length + 1; // plus its comma\n if (size > chars) break;\n chars -= size;\n room--;\n kept.push(foreign[i]!);\n }\n return kept.reverse();\n }\n\n override clear(): void {\n super.clear();\n this.known.clear();\n this.removed.clear();\n }\n\n override close(): void {\n try {\n if (typeof window !== 'undefined') window.removeEventListener('storage', this.onStorage);\n } catch {\n /* nothing was attached */\n }\n }\n}\n","import { KEY_ANON_RESET, type KVStorage } from './queue/storage';\nimport type { Clock } from './utils/clock';\nimport type { Properties } from './types';\nimport { uuidv7 } from './utils/uuidv7';\n\nconst KEY_ANON = 'depsmith_anonymous_id';\nconst KEY_USER = 'depsmith_user_id';\nconst KEY_GROUP = 'depsmith_group_id';\nconst KEY_PROPS = 'depsmith_user_props';\n\n/** Anonymous-first identity. anonymous_id rotates ONLY via reset(). See API_SPEC §4. */\nexport class IdentityManager {\n constructor(\n private storage: KVStorage,\n private clock: Clock\n ) {}\n\n get anonymousId(): string {\n let id = this.storage.get(KEY_ANON);\n if (!id) {\n id = uuidv7(this.clock.now());\n this.storage.set(KEY_ANON, id);\n }\n return id;\n }\n\n get userId(): string | null {\n return this.storage.get(KEY_USER);\n }\n\n get groupId(): string | null {\n return this.storage.get(KEY_GROUP);\n }\n\n identify(userId: string): void {\n this.storage.set(KEY_USER, userId);\n }\n\n setGroup(groupId: string): void {\n this.storage.set(KEY_GROUP, groupId);\n }\n\n /** Persisted user-property map, used for setOnceProperty checks. */\n getUserProps(): Properties {\n try {\n return JSON.parse(this.storage.get(KEY_PROPS) ?? '{}') as Properties;\n } catch {\n return {};\n }\n }\n\n setUserProp(key: string, value: Properties[string]): void {\n const props = this.getUserProps();\n props[key] = value;\n this.storage.set(KEY_PROPS, JSON.stringify(props));\n }\n\n hasUserProp(key: string): boolean {\n return key in this.getUserProps();\n }\n\n unsetUserProp(key: string): void {\n const props = this.getUserProps();\n delete props[key];\n this.storage.set(KEY_PROPS, JSON.stringify(props));\n }\n\n /**\n * Clears user/group/props and rotates anonymous_id.\n *\n * Also records WHEN, beside the id. The id lives in two stores, and one of them (the cookie,\n * under `cookieDomain`) is shared with origins this page cannot write to; without the marker\n * their copy of the old id looks like the device's original identity and is restored over the\n * new one. See `RedundantAdapter.pick`.\n */\n reset(): string {\n this.storage.remove(KEY_USER);\n this.storage.remove(KEY_GROUP);\n this.storage.remove(KEY_PROPS);\n const now = this.clock.now();\n this.storage.set(KEY_ANON_RESET, `${now}`);\n const fresh = uuidv7(now);\n this.storage.set(KEY_ANON, fresh);\n return fresh;\n }\n}\n","import type { KVStorage } from './queue/storage';\nimport type { Clock } from './utils/clock';\nimport { uuidv7, uuidv7ToMs } from './utils/uuidv7';\nimport { idleScheduler, type Scheduler } from './utils/scheduler';\n\nconst KEY_SESSION = 'depsmith_session';\n\ninterface StoredSession {\n id: string;\n lastActivityAt: number;\n /** Absent on records written before 0.3.0 — recovered from the id, see load(). */\n startedAt?: number;\n}\n\nexport interface SessionTouch {\n sessionId: string;\n /** When this session began. Rides every event so session length is computable per row. */\n startedAt: number;\n /** Present when this touch expired a previous session — caller emits $session_end for it. */\n endedSession?: { id: string; lastActivityAt: number; startedAt: number };\n /** Present when this touch minted a session — caller emits $session_start for it. */\n startedSession?: { id: string; startedAt: number };\n}\n\n/**\n * 30-min inactivity sessions, persisted so they survive restarts.\n * Order matters: check timeout FIRST, then stamp activity (API_SPEC §5).\n *\n * Writes are coalesced onto an idle callback for the same reason `EventQueue`'s are: a\n * synchronous `localStorage.setItem` on every `touch()` — that is, on every captured\n * event — put a blocking main-thread write inside every click handler. Reads still go to\n * storage so a session stays shared across tabs; see load().\n */\nexport class SessionManager {\n /** Written but not yet persisted. Kept so load() can see our own latest write. */\n private pending: StoredSession | null = null;\n private scheduled = false;\n private schedule: Scheduler;\n\n constructor(\n private storage: KVStorage,\n private clock: Clock,\n private timeoutMs: number,\n schedule: Scheduler = idleScheduler\n ) {\n this.schedule = schedule;\n }\n\n /**\n * Reads the stored session, recovering `startedAt` for records written before 0.3.0.\n *\n * A session already in the field has no stored start time, but its id is a UUID v7\n * whose first 48 bits ARE that time — so the value is exact, not an approximation.\n * That is why this field needed no backfill and no storage format version. The\n * `?? lastActivityAt` is a last resort for an id that somehow isn't v7; it can only\n * under-report the session's age, never invent a future start.\n *\n * Deliberately still reads storage even when a write is pending: sessions are shared\n * across tabs through `localStorage`, and serving a purely in-memory value would let two\n * tabs drift into separate sessions. The pending write wins only when it is at least as\n * recent as what is stored — if another tab has written something newer (it rotated the\n * session, say), that wins and our pending write is dropped rather than allowed to\n * clobber it. Last-activity-wins, which is what the write-through version resolved to\n * anyway.\n */\n private load(): StoredSession | null {\n const stored = this.readStored();\n const pending = this.pending;\n if (!pending) return stored;\n if (!stored || pending.lastActivityAt >= stored.lastActivityAt) return pending;\n this.pending = null; // another tab won; do not clobber it\n return stored;\n }\n\n private readStored(): StoredSession | null {\n try {\n const raw = this.storage.get(KEY_SESSION);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as StoredSession;\n if (typeof parsed.id !== 'string' || typeof parsed.lastActivityAt !== 'number') return null;\n if (typeof parsed.startedAt !== 'number') {\n parsed.startedAt = uuidv7ToMs(parsed.id) ?? parsed.lastActivityAt;\n }\n return parsed;\n } catch {\n return null;\n }\n }\n\n private save(session: StoredSession): void {\n this.pending = session;\n if (this.scheduled) return;\n this.scheduled = true;\n this.schedule(() => {\n this.scheduled = false;\n this.persistNow();\n });\n }\n\n /** Writes any pending session immediately. Called on `pagehide` and `shutdown()`. */\n persistNow(): void {\n const pending = this.pending;\n if (!pending) return;\n this.pending = null;\n this.storage.set(KEY_SESSION, JSON.stringify(pending));\n }\n\n private mint(now: number): StoredSession {\n const fresh = { id: uuidv7(now), lastActivityAt: now, startedAt: now };\n this.save(fresh);\n return fresh;\n }\n\n /** Called on every capture and on visibility resume. */\n touch(): SessionTouch {\n const now = this.clock.now();\n const current = this.load();\n\n if (!current) {\n const fresh = this.mint(now);\n return {\n sessionId: fresh.id,\n startedAt: now,\n startedSession: { id: fresh.id, startedAt: now },\n };\n }\n\n if (now - current.lastActivityAt > this.timeoutMs) {\n const fresh = this.mint(now);\n return {\n sessionId: fresh.id,\n startedAt: now,\n // Order matters downstream: $session_end for the old session is emitted before\n // $session_start for the new one (API_SPEC §5).\n endedSession: {\n id: current.id,\n lastActivityAt: current.lastActivityAt,\n startedAt: current.startedAt!,\n },\n startedSession: { id: fresh.id, startedAt: now },\n };\n }\n\n this.save({ id: current.id, lastActivityAt: now, startedAt: current.startedAt! });\n return { sessionId: current.id, startedAt: current.startedAt! };\n }\n\n /**\n * Current id without stamping activity (getSessionId bridge/testing API).\n *\n * Deliberately does NOT rotate an expired session. This used to delegate to touch(),\n * which rotated and returned an `endedSession` that peek() then dropped on the floor —\n * so merely *reading* the id destroyed the `$session_end` for the session that just\n * expired, and stamped activity that kept a dead session alive. Rotation is left to\n * the next capture(), which emits the `$session_end` properly.\n */\n peek(): string {\n const current = this.load();\n if (current) return current.id;\n // No session yet: mint and persist, so repeated reads are stable. Deliberately does\n // NOT emit $session_start — emitting analytics from a getter is the class of bug the\n // peek() fix above removed. The next capture() adopts this session silently.\n return this.mint(this.clock.now()).id;\n }\n\n /**\n * Adopts an externally supplied session id — the `setSessionId()` public API.\n *\n * Exists so a session can span contexts the SDK cannot see across: a web→app handoff, a\n * server-rendered page continuing into the client, or two subdomains that do not share\n * storage. Without it those are unavoidably separate sessions, and every funnel spanning\n * them is wrong rather than merely noisy.\n *\n * Returns false for a non-UUIDv7 id rather than adopting it. A session id whose first 48\n * bits are not a timestamp would make `session_started_at` unrecoverable and break the\n * ordering `event_id` and `session_id` both rely on, so a bad id is refused at the door\n * rather than persisted and dealt with later.\n *\n * `startedAt` is optional because the id already carries it exactly (RFC 9562). The\n * parameter exists for the case where the caller knows the session began before the id\n * was minted; it can only ever move the start earlier in practice, and is trusted as given.\n *\n * Deliberately emits NO `$session_start`: an externally supplied session is not a boundary\n * this SDK observed. Same reasoning that keeps `rotate()` and `peek()` silent — see\n * API_SPEC §5.\n */\n adopt(id: string, startedAt?: number): boolean {\n const embedded = uuidv7ToMs(id);\n if (embedded === null) return false;\n this.save({ id, lastActivityAt: this.clock.now(), startedAt: startedAt ?? embedded });\n return true;\n }\n\n /**\n * reset() rotates the session unconditionally — no $session_end AND no $session_start.\n * Start and end stay symmetric: reset() is an explicit user action, not a session\n * boundary the SDK observed, so it announces neither side.\n */\n rotate(): string {\n return this.mint(this.clock.now()).id;\n }\n}\n","import type { Logger } from './utils/logger';\nimport type { Properties, PropertyValue, Scalar } from './types';\n\nconst MAX_TOP_LEVEL_KEYS = 200;\nconst MAX_ARRAY_ITEMS = 100;\nconst MAX_OBJECT_KEYS = 50;\n\n/**\n * Enqueue-time validation & coercion (API_SPEC §7). Never throws:\n * Dates → ISO strings, deep nesting → JSON string at depth 1, NaN/Infinity → dropped.\n */\nexport function sanitizeProperties(input: unknown, logger: Logger): Properties {\n if (input === null || input === undefined) return {};\n if (typeof input !== 'object' || Array.isArray(input)) {\n logger.warn('properties must be an object; ignoring', input);\n return {};\n }\n\n const out: Properties = {};\n let count = 0;\n for (const [rawKey, rawValue] of Object.entries(input as Record<string, unknown>)) {\n if (count >= MAX_TOP_LEVEL_KEYS) {\n logger.warn(`properties exceed ${MAX_TOP_LEVEL_KEYS} keys; excess dropped`);\n break;\n }\n const value = coerceValue(rawValue, logger);\n if (value === undefined) {\n logger.debug(`property \"${rawKey}\" dropped (unsupported value)`);\n continue;\n }\n out[String(rawKey)] = value;\n count++;\n }\n return out;\n}\n\nfunction coerceScalar(value: unknown): Scalar | undefined {\n if (value === null) return null;\n const t = typeof value;\n if (t === 'string' || t === 'boolean') return value as Scalar;\n if (t === 'number') return Number.isFinite(value as number) ? (value as number) : undefined;\n if (value instanceof Date) return isNaN(value.getTime()) ? undefined : value.toISOString();\n return undefined;\n}\n\nfunction coerceValue(value: unknown, logger: Logger): PropertyValue | undefined {\n const scalar = coerceScalar(value);\n if (scalar !== undefined) return scalar;\n if (value === undefined || typeof value === 'function' || typeof value === 'symbol') return undefined;\n\n if (Array.isArray(value)) {\n const items: Scalar[] = [];\n for (const item of value.slice(0, MAX_ARRAY_ITEMS)) {\n const coerced = coerceScalar(item);\n // non-scalar array members get JSON-stringified (depth-1 flattening)\n items.push(coerced !== undefined ? coerced : safeStringify(item));\n }\n return items;\n }\n\n if (typeof value === 'object') {\n const out: Record<string, Scalar> = {};\n let count = 0;\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (count >= MAX_OBJECT_KEYS) {\n logger.debug(`nested object exceeds ${MAX_OBJECT_KEYS} keys; excess dropped`);\n break;\n }\n const coerced = coerceScalar(v);\n out[String(k)] = coerced !== undefined ? coerced : safeStringify(v);\n count++;\n }\n return out;\n }\n\n return undefined;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? 'null';\n } catch {\n return String(value);\n }\n}\n","import type { Logger } from './utils/logger';\n\n// `$` property keys are the SDK's (API_SPEC §7). Its own module so the Shopify custom-pixel build\n// can swap it for `reserved.noop.ts`: nothing in the pixel sandbox calls a public method — the\n// pixel uses the internal entry points — and that bundle has no characters to spare.\n\n/**\n * Drops `$`-prefixed keys a client passed to a public method.\n *\n * `$` marks SDK-owned data (`$page_name`, `$page_counter`, `$ac_*`), the same namespace `track()`\n * reserves for event names and `register()` for super-property keys. Without this a client\n * could send `$page_name` on its own events and no reader could tell system data from client\n * data again. The SDK's own events never pass through here: autocapture, the page lifecycle and\n * the internal entry points capture directly.\n *\n * Returns the input itself when nothing is reserved.\n */\nexport function stripReserved<T extends object>(\n input: T | undefined,\n method: string,\n logger: Logger\n): T | undefined {\n const out = { ...input } as Record<string, unknown>;\n let hit;\n for (const key in out) if (isReserved(key, method, logger)) hit = delete out[key];\n return hit ? (out as T) : input;\n}\n\n/** True, with a debug warning naming the key, when `key` is in the SDK's `$` namespace. */\nexport function isReserved(key: string, method: string, logger: Logger): boolean {\n // `?.[0]`, not startsWith: a JS caller can pass a non-string key, and this must not throw.\n if (key?.[0] !== '$') return false;\n logger.warn(`${method}: \"$\"-prefixed keys are reserved; ignored \"${key}\"`);\n return true;\n}\n","import type { ResolvedConfig } from './config';\nimport type { Properties } from './types';\n\n/**\n * `$network_request` when a request the app made fails (default-events spec item 15).\n *\n * Failure means a 5xx response, or no response at all. A 4xx is deliberately excluded: a 404 on a\n * probe or a 401 driving a token refresh is ordinary application flow, and reporting those would bury\n * the server failures this exists to surface.\n *\n * **Bodies are never read, only sizes.** That is the spec's acceptance criterion and it is also what\n * makes this safe to ship: a request body is the single most PII-dense thing a page touches, and this\n * SDK has no masking primitive for it. Sizes come from the `Content-Length` header, so reading them\n * never consumes the stream — cloning a response to measure it would both cost memory and change the\n * host's own timing.\n *\n * The SDK's OWN uploads are excluded by endpoint prefix. Without that, a collector outage becomes a\n * feedback loop: the failing upload reports itself, which queues another event, which fails too.\n *\n * **Volume is bounded, and a request the app gave up on is not a failure.** Reporting every\n * rejection made this a firehose in exactly the apps that use `fetch` most: a typeahead or a\n * query library aborts a request per keystroke and per route change, and a dashboard polling\n * while the device is offline fails once a second — each one an event in a bounded,\n * drop-oldest queue, crowding out real events that cannot upload either. So:\n * - an aborted request is not reported (a timeout still is — the server was too slow);\n * - nothing is reported while the browser says it is offline: that is the device, not a server;\n * - a given failure (method, URL without query, status or \"no response\") is reported once per\n * {@link WINDOW_MS}, and at most {@link MAX_PER_WINDOW} distinct ones in that time.\n */\nexport interface NetworkErrors {\n stop(): void;\n}\n\n/** The rate-limit window. */\nconst WINDOW_MS = 60_000;\n/** Distinct failures reported per window; the rest are dropped, not queued for later. */\nconst MAX_PER_WINDOW = 10;\n\n/**\n * True when the request was cancelled by the page rather than failed by the network.\n *\n * `AbortError` is what an `AbortController` produces by default; `abort(reason)` rejects with the\n * reason itself, so the signal is checked as well. `TimeoutError` (`AbortSignal.timeout`) is the\n * exception: nobody changed their mind, the server did not answer in time.\n */\nfunction wasAborted(error: unknown, signal: AbortSignal | null | undefined): boolean {\n const name = (error as { name?: unknown } | null | undefined)?.name;\n return name === 'AbortError' || (name !== 'TimeoutError' && !!signal?.aborted);\n}\n\n/** By shape, not `instanceof Error`: a rejection from another realm fails that test. */\nfunction errorMessage(error: unknown): string {\n const message = (error as { message?: unknown } | null | undefined)?.message;\n return typeof message === 'string' && message ? message.slice(0, 255) : 'network error';\n}\n\n/** Only a server failure or a transport failure. 4xx is application flow, not an outage. */\nfunction isFailure(status: number): boolean {\n return status >= 500;\n}\n\n/** Query and fragment are reported separately, so `$net_url` stays a groupable key. */\nfunction urlParts(raw: string): Properties {\n const properties: Properties = {};\n try {\n const url = new URL(raw, typeof location !== 'undefined' ? location.href : undefined);\n properties.$net_url = `${url.origin}${url.pathname}`;\n if (url.search.length > 1) properties.$net_query = url.search.slice(1);\n if (url.hash.length > 1) properties.$net_fragment = url.hash.slice(1);\n } catch {\n // An unparseable URL still identifies the request well enough to be worth reporting.\n properties.$net_url = raw.slice(0, 255);\n }\n return properties;\n}\n\nfunction contentLength(headers: Headers | null): number | undefined {\n try {\n const value = headers?.get('content-length');\n if (!value) return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The two facts about a request this reports, read the way `fetch` itself reads its arguments. */\nfunction describeRequest(\n input: unknown,\n init: RequestInit | undefined\n): { raw: string; method: string; signal?: AbortSignal | null } {\n // A Request is used as is; ANYTHING else is stringified — a URL (from this realm or another),\n // `window.location`, an `<a>`, a router's URL-like object. Tested by tag rather than\n // `instanceof`, which is false for a Request or URL created in an iframe.\n const request =\n Object.prototype.toString.call(input) === '[object Request]' ? (input as Request) : undefined;\n return {\n raw: String(request ? request.url : input),\n method: String(init?.method ?? request?.method ?? 'GET').toUpperCase(),\n signal: init?.signal ?? request?.signal,\n };\n}\n\n/**\n * Patches `fetch` to report failures.\n *\n * **The patch is transparent.** The original is called first, with the caller's own `this` and\n * arguments, before this file has looked at either — so whatever it accepts, returns or throws\n * is what the caller gets. The earlier wrapper derived the URL up front and assumed a string, a\n * same-realm `URL` or a `Request`; for anything else native `fetch` accepts (`fetch(location)`,\n * `fetch(anchor)`, a cross-realm `URL`, any object with a `toString()`) it threw on `undefined`\n * before delegating, so a request that works without the SDK was rejected and never sent with it.\n * A request this cannot describe is now simply not observed.\n *\n * XHR is deliberately left alone. Patching it means wrapping `open`, `send` and a `readystatechange`\n * listener on every request a page makes, which is a much larger surface to get wrong inside a\n * third-party SDK — and `fetch` is what application code uses today. An XHR-only app reports nothing\n * here rather than reporting something broken.\n */\nexport function observeNetworkErrors(\n config: Pick<ResolvedConfig, 'endpoint' | 'autocapture'>,\n emit: (properties: Properties) => void\n): NetworkErrors {\n // `autocapture.networkErrors: false` is the switch for a host that wants clicks without having\n // `fetch` wrapped. On by default, as it has been since this shipped.\n const off = config.autocapture && config.autocapture.networkErrors === false;\n if (off || typeof fetch !== 'function') return { stop: () => {} };\n\n const original = fetch;\n // Compared as a prefix, so the collector's /e/ and any future path under it are both excluded.\n const own = config.endpoint.replace(/\\/+$/, '');\n let stopped = false;\n\n let windowStart = 0;\n let seen = new Set<string>();\n /** One report per distinct failure per window, and a ceiling on distinct failures. */\n const admit = (key: string): boolean => {\n const now = Date.now();\n if (now - windowStart >= WINDOW_MS) {\n windowStart = now;\n seen = new Set();\n }\n if (seen.size >= MAX_PER_WINDOW || seen.has(key)) return false;\n seen.add(key);\n return true;\n };\n\n /** Reporting is best-effort: nothing in it may change what the caller's promise settles to. */\n const report = (outcome: string | number, build: () => Properties): void => {\n try {\n const properties = build();\n if (admit(`${String(properties.$net_method)} ${String(properties.$net_url)} ${outcome}`)) {\n emit(properties);\n }\n } catch {\n /* the request's own outcome is all the caller should ever see */\n }\n };\n\n const patched = function (this: unknown, ...args: Parameters<typeof fetch>): Promise<Response> {\n const started = Date.now();\n const promise = original.apply(this, args);\n // Left in someone else's chain after stop() (see below): pass through and report nothing.\n // Likewise for a replaced `fetch` that returns something other than a promise.\n if (stopped || typeof promise?.then !== 'function') return promise;\n\n let raw: string;\n let method: string;\n let signal: AbortSignal | null | undefined;\n try {\n ({ raw, method, signal } = describeRequest(args[0], args[1]));\n // Our own uploads, excluded before anything else: a collector outage would otherwise report\n // itself, queue another event, and fail again.\n if (raw.startsWith(own)) return promise;\n } catch {\n return promise;\n }\n const init = args[1];\n\n // A derived promise rather than a side branch on the original: a handler attached to the\n // original would mark its rejection as handled, and the host's `unhandledrejection` reporting\n // for a failed request nobody caught would go quiet. This one settles exactly as the original.\n return promise.then(\n (response) => {\n if (isFailure(response.status)) {\n report(response.status, () => ({\n ...urlParts(raw),\n $net_method: method,\n $net_status: response.status,\n $net_start: started,\n $net_end: Date.now(),\n $net_duration_ms: Date.now() - started,\n ...sizes(init, response),\n }));\n }\n return response;\n },\n (error: unknown) => {\n // No response at all: DNS, CORS, a dropped connection. Not a cancelled request, and not\n // while the device itself is offline — neither says anything about a server.\n const offline = typeof navigator !== 'undefined' && navigator.onLine === false;\n if (offline || wasAborted(error, signal)) throw error;\n // The message is the only detail the platform gives, and it is short by nature.\n report('error', () => ({\n ...urlParts(raw),\n $net_method: method,\n $net_error_message: errorMessage(error),\n $net_start: started,\n $net_end: Date.now(),\n $net_duration_ms: Date.now() - started,\n }));\n // Rethrown unchanged: observing a failure must not change how the caller sees it.\n throw error;\n }\n );\n } as typeof fetch;\n\n (globalThis as { fetch: typeof fetch }).fetch = patched;\n return {\n stop: () => {\n stopped = true;\n // Only if nobody else patched on top of us — restoring over a later wrapper would silently\n // uninstall theirs, which is the same mistake this file avoids with the crash-handler chain.\n // Their wrapper still calls this one, so it stays in the chain and goes inert (`stopped`).\n if ((globalThis as { fetch: typeof fetch }).fetch === patched) {\n (globalThis as { fetch: typeof fetch }).fetch = original;\n }\n },\n };\n}\n\n/** Sizes from Content-Length only — never by reading or cloning a body. */\nfunction sizes(init: RequestInit | undefined, response: Response): Properties {\n const properties: Properties = {};\n const requestBytes = typeof init?.body === 'string' ? init.body.length : undefined;\n if (requestBytes !== undefined) properties.$net_req_bytes = requestBytes;\n const responseBytes = contentLength(response.headers);\n if (responseBytes !== undefined) properties.$net_res_bytes = responseBytes;\n return properties;\n}\n","import type { Properties } from './types';\n\n/**\n * Google's Core Web Vitals, collected with PerformanceObserver and reported once per page\n * (default-events spec item 14).\n *\n * Emitted when the tab is HIDDEN rather than on load, because three of the five are not final until\n * then: LCP can be superseded by a later paint, CLS accumulates for the life of the page, and INP is\n * the worst interaction so far. Reporting at load would systematically under-report all three — which\n * is worse than not reporting them, because the numbers would look plausible.\n *\n * Observers only, no wrapping of anything. Every registration is individually guarded: these entry\n * types have uneven support (`event` timing is Chromium-only today), and an unsupported type throws\n * from `observe()` rather than degrading, so one missing type must not cost the other four.\n */\nexport interface Vitals {\n /** Collected so far. Values absent rather than zero when nothing was observed. */\n snapshot(): Properties;\n /** True once there is at least one metric worth sending. */\n hasAny(): boolean;\n stop(): void;\n}\n\n/** Rounded to whole milliseconds — sub-millisecond precision in a page-speed metric is noise. */\nfunction ms(value: number): number {\n return Math.round(value);\n}\n\nexport function observeVitals(): Vitals {\n let lcp: number | undefined;\n let fcp: number | undefined;\n let inp: number | undefined;\n let cls = 0;\n let sawLayoutShift = false;\n let ttfb: number | undefined;\n const observers: PerformanceObserver[] = [];\n\n const observe = (type: string, handler: (entries: PerformanceEntryList) => void): void => {\n try {\n const observer = new PerformanceObserver((list) => handler(list.getEntries()));\n // `buffered: true` replays entries that occurred before the SDK loaded, which matters most for\n // FCP and LCP: an async-loaded SDK would otherwise miss the very paints it exists to measure.\n observer.observe({ type, buffered: true } as PerformanceObserverInit);\n observers.push(observer);\n } catch {\n /* entry type unsupported in this browser — the metric stays absent, never zero */\n }\n };\n\n // Last entry wins: LCP is redefined upward until the page stops painting.\n observe('largest-contentful-paint', (entries) => {\n const last = entries[entries.length - 1];\n if (last) lcp = ms(last.startTime);\n });\n\n observe('paint', (entries) => {\n for (const entry of entries) {\n if (entry.name === 'first-contentful-paint') fcp = ms(entry.startTime);\n }\n });\n\n // CLS sums every shift NOT caused by recent input — a layout change the user themselves triggered\n // by tapping is expected, and counting it would penalise responsive UI.\n observe('layout-shift', (entries) => {\n for (const entry of entries as Array<PerformanceEntry & { value?: number; hadRecentInput?: boolean }>) {\n if (entry.hadRecentInput) continue;\n cls += entry.value ?? 0;\n sawLayoutShift = true;\n }\n });\n\n // INP approximated as the worst interaction latency seen. The official metric uses a high\n // percentile across all interactions; the maximum is the honest simplification at one page's\n // scale, where a percentile over three interactions means nothing.\n observe('event', (entries) => {\n for (const entry of entries) {\n const duration = ms(entry.duration);\n if (inp === undefined || duration > inp) inp = duration;\n }\n });\n\n try {\n // TTFB comes from the navigation entry, which exists immediately — no observer needed, and\n // nothing to wait for.\n const [navigation] = performance.getEntriesByType('navigation');\n const timing = navigation as (PerformanceEntry & { responseStart?: number }) | undefined;\n if (timing?.responseStart !== undefined && timing.responseStart > 0) {\n ttfb = ms(timing.responseStart);\n }\n } catch {\n /* no Navigation Timing — TTFB stays absent */\n }\n\n return {\n snapshot(): Properties {\n const out: Properties = {};\n if (lcp !== undefined) out.$wv_lcp = lcp;\n if (fcp !== undefined) out.$wv_fcp = fcp;\n if (inp !== undefined) out.$wv_inp = inp;\n // Reported only if a shift was actually observed. A literal 0 is a real and good CLS score, so\n // it must be distinguishable from \"this browser told us nothing\".\n if (sawLayoutShift) out.$wv_cls = Math.round(cls * 1000) / 1000;\n if (ttfb !== undefined) out.$wv_ttfb = ttfb;\n return out;\n },\n hasAny(): boolean {\n return (\n lcp !== undefined ||\n fcp !== undefined ||\n inp !== undefined ||\n sawLayoutShift ||\n ttfb !== undefined\n );\n },\n stop(): void {\n for (const observer of observers.splice(0)) {\n try {\n observer.disconnect();\n } catch {\n /* ignore */\n }\n }\n },\n };\n}\n","import type { Properties } from './types';\nimport { isReserved } from './reserved';\nimport type { KVStorage } from './queue/storage';\nimport type { Logger } from './utils/logger';\n\n/**\n * Registered (\"super\") properties: values attached to every later event (common-properties item 4).\n *\n * The problem they solve is a client passing `plan` and `ab_variant` to every single `track()` call,\n * which is both noise and a place to forget. Registered once, they ride along.\n *\n * Precedence, which is the rule that matters: a property passed directly to `track()` WINS over a\n * registered one with the same key. The call site is more specific than the registration, and the\n * alternative — registration winning — would make a per-event override impossible to express.\n *\n * Distinct from `config.defaultProperties`, which is static and set at init. These are mutable at\n * runtime and persisted, so they survive a reload. Where both define a key, the registered one wins:\n * it was set later, and by a call rather than a constant.\n */\nexport const KEY_SUPER_PROPERTIES = 'depsmith_super_props';\n\n/** Rejected for the same reason `track()` rejects `$`-prefixed event names: reserved namespace. */\nfunction usableKey(key: string, logger: Logger): boolean {\n if (key.length === 0) {\n logger.warn('register: empty property key ignored');\n return false;\n }\n return !isReserved(key, 'register', logger);\n}\n\nexport class SuperProperties {\n private properties: Properties = {};\n\n constructor(\n private storage: KVStorage,\n private logger: Logger\n ) {\n try {\n const stored = this.storage.get(KEY_SUPER_PROPERTIES);\n if (stored) {\n const parsed: unknown = JSON.parse(stored);\n // Guarded: a hand-edited localStorage value, or a value written by a future version with a\n // different shape, must not take the SDK down at construction.\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n this.properties = parsed as Properties;\n }\n }\n } catch {\n /* unreadable or malformed — start empty rather than throw in a constructor */\n }\n }\n\n /** Overwrites each given key. */\n register(properties: Properties): void {\n let changed = false;\n for (const [key, value] of Object.entries(properties)) {\n if (!usableKey(key, this.logger)) continue;\n this.properties[key] = value;\n changed = true;\n }\n if (changed) this.persist();\n }\n\n /**\n * Sets only keys that are not registered yet — for first-touch values like the plan someone\n * signed up on, which must not be overwritten by a later state.\n *\n * \"Not registered yet\" means absent, not falsy: a registered `false` or `0` is a value someone\n * chose, and treating it as missing would silently replace it on the next call.\n */\n registerOnce(properties: Properties): void {\n let changed = false;\n for (const [key, value] of Object.entries(properties)) {\n if (!usableKey(key, this.logger)) continue;\n if (Object.prototype.hasOwnProperty.call(this.properties, key)) continue;\n this.properties[key] = value;\n changed = true;\n }\n if (changed) this.persist();\n }\n\n unregister(key: string): void {\n if (!Object.prototype.hasOwnProperty.call(this.properties, key)) return;\n delete this.properties[key];\n this.persist();\n }\n\n /** Cleared by reset(), like every other visitor-scoped value. */\n clear(): void {\n if (Object.keys(this.properties).length === 0) return;\n this.properties = {};\n try {\n this.storage.remove(KEY_SUPER_PROPERTIES);\n } catch {\n /* ignore */\n }\n }\n\n /**\n * A copy, so a caller mutating the returned object cannot change registered state — and so the\n * spread at the capture site cannot alias one object across every event in a batch.\n */\n current(): Properties {\n return { ...this.properties };\n }\n\n private persist(): void {\n try {\n this.storage.set(KEY_SUPER_PROPERTIES, JSON.stringify(this.properties));\n } catch {\n // Quota or a blocked store: they still apply for this page, they just will not survive it.\n this.logger.debug('register: could not persist super properties');\n }\n }\n}\n","/**\n * User-property operators (API_SPEC §14).\n *\n * The operators exist because applying them on a client is wrong, not merely inconvenient:\n * `$add` on a device is a read-modify-write race between tabs, and `$append` cannot converge\n * at all. So the SDK's job is to *describe* the change and let the collector apply it.\n *\n * Two invariants are the client's responsibility, and both are here rather than in the\n * collector — the schema's own comment explains why: they are what keep the collector free\n * of operator algebra.\n *\n * 1. A key appears under AT MOST ONE operator per event. Without it, `$set` then `$add` on\n * one key is only resolvable by assuming the value is numeric.\n * 2. `$clear_all` is exclusive. Combining it with anything else makes the result depend on\n * ordering that is otherwise unobservable.\n *\n * Both are enforced by dropping the offending entry with a debug warning, never by throwing:\n * the public API is fire-and-forget and must not break a host page over a analytics call.\n */\nimport type { Logger } from './utils/logger';\nimport { sanitizeProperties } from './props';\nimport { isReserved } from './reserved';\nimport type { Properties, PropertyValue } from './types';\n\n/** Operators taking a map of traits. */\nexport type TraitOperator =\n | '$set'\n | '$set_once'\n | '$append'\n | '$prepend'\n | '$pre_insert'\n | '$post_insert'\n | '$remove';\n\n/**\n * The closed operator set, exactly as `event.schema.json` `$defs.userPropertyOps` declares it.\n * Closed on purpose: level 2 is a fixed 10-member enum the collector knows at compile time,\n * which is what lets `user_properties.$add.orders` flatten deterministically into a warehouse\n * column despite being three levels from the root.\n */\nexport interface UserPropertyOps {\n $set?: Properties;\n $set_once?: Properties;\n $append?: Properties;\n $prepend?: Properties;\n $pre_insert?: Properties;\n $post_insert?: Properties;\n $remove?: Properties;\n /** Numeric increments. Absent counts as 0; negative is allowed. */\n $add?: Record<string, number>;\n $unset?: string[];\n /** Deletes every user property for this identity. Exclusive. */\n $clear_all?: true;\n}\n\nconst TRAIT_OPERATORS: readonly TraitOperator[] = [\n '$set',\n '$set_once',\n '$append',\n '$prepend',\n '$pre_insert',\n '$post_insert',\n '$remove',\n];\n\n/** Mirrors the schema's `maxProperties` / `maxItems` so an over-sized map is trimmed, not rejected. */\nconst MAX_ADD_KEYS = 50;\nconst MAX_UNSET_KEYS = 200;\n\n/**\n * Validates, sanitises and de-duplicates an operator map.\n *\n * Returns `undefined` when nothing survives, so a caller can omit `user_properties` entirely\n * rather than send `{}` — which the schema forbids via `minProperties: 1`.\n */\nexport function normalizeUserPropertyOps(\n ops: UserPropertyOps,\n logger: Logger\n): UserPropertyOps | undefined {\n if (!ops || typeof ops !== 'object') return undefined;\n\n // $clear_all first, and alone. Checked before anything else so the exclusivity warning\n // names what was discarded rather than silently winning a race with it.\n if (ops.$clear_all === true) {\n const others = Object.keys(ops).filter((k) => k !== '$clear_all');\n if (others.length > 0) {\n logger.warn(`$clear_all is exclusive; ignored ${others.join(', ')}`);\n }\n return { $clear_all: true };\n }\n\n const out: UserPropertyOps = {};\n /** Keys already claimed, so invariant 1 can be enforced across operators. */\n const claimed = new Set<string>();\n\n const claim = (key: string, operator: string): boolean => {\n // Reserved for the SDK, as on every other public method. The operator names themselves\n // (`$set`, `$add`, …) are syntax, not keys, and are never checked here.\n if (isReserved(key, operator, logger)) return false;\n if (claimed.has(key)) {\n logger.debug(`\"${key}\" has an operator already; ${operator} dropped`);\n return false;\n }\n claimed.add(key);\n return true;\n };\n\n for (const operator of TRAIT_OPERATORS) {\n const raw = ops[operator];\n if (!raw || typeof raw !== 'object') continue;\n // Reuse the event-property sanitiser: traits are the same value space, so a Date here\n // coerces exactly as it would in properties, and the two cannot drift apart.\n const clean = sanitizeProperties(raw, logger);\n const kept: Properties = {};\n for (const [key, value] of Object.entries(clean)) {\n if (!claim(key, operator)) continue;\n kept[key] = value as PropertyValue;\n }\n if (Object.keys(kept).length > 0) out[operator] = kept;\n }\n\n if (ops.$add && typeof ops.$add === 'object') {\n const kept: Record<string, number> = {};\n let count = 0;\n for (const [key, value] of Object.entries(ops.$add)) {\n if (count >= MAX_ADD_KEYS) {\n logger.debug(`$add over ${MAX_ADD_KEYS} keys; excess dropped`);\n break;\n }\n // A non-finite increment would serialise to null and the collector would treat it as\n // a value rather than a no-op, so it is dropped here where the cause is still visible.\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n logger.debug(`$add \"${key}\" is not finite; dropped`);\n continue;\n }\n if (!claim(key, '$add')) continue;\n kept[key] = value;\n count++;\n }\n if (Object.keys(kept).length > 0) out.$add = kept;\n }\n\n if (Array.isArray(ops.$unset)) {\n const kept: string[] = [];\n for (const key of ops.$unset) {\n if (kept.length >= MAX_UNSET_KEYS) {\n logger.debug(`$unset over ${MAX_UNSET_KEYS} keys; excess dropped`);\n break;\n }\n if (typeof key !== 'string' || key.length === 0) continue;\n if (!claim(key, '$unset')) continue;\n kept.push(key);\n }\n if (kept.length > 0) out.$unset = kept;\n }\n\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * Wraps traits the caller has ALREADY run through `sanitizeProperties` in a single operator.\n *\n * `identify`, `setProperty` and `setOnceProperty` sanitise once for `context.traits`; routing\n * that result back through `normalizeUserPropertyOps` would coerce every value a second time\n * and repeat each sanitiser warning. Neither invariant can be violated by one operator over\n * one map, so there is nothing left for the full normaliser to do.\n */\nexport function sanitizedTraitOp(operator: TraitOperator, clean: Properties): UserPropertyOps | undefined {\n return Object.keys(clean).length > 0 ? { [operator]: clean } : undefined;\n}\n","/** Injectable time source — the conformance runner substitutes a controllable clock. */\nexport interface Clock {\n now(): number;\n}\n\nexport const systemClock: Clock = {\n now: () => Date.now(),\n};\n\nexport function isoTimestamp(ms: number): string {\n return new Date(ms).toISOString().replace(/(\\.\\d{3})\\d*Z$/, '$1Z');\n}\n","/** Retry classification & backoff (API_SPEC §10). */\n\n/** Network errors are represented as status 0. */\nexport function isRetryable(status: number): boolean {\n return status === 0 || status === 408 || status === 429 || status >= 500;\n}\n\nconst BASE_MS = 1000;\nconst MAX_BACKOFF_MS = 32000;\n\n/**\n * Exponential backoff 1s→32s with **full jitter**: uniform over [0, base].\n *\n * The previous form was `base * (1 + random() * 0.25)` — additive and upward-only, so a\n * wait was never shorter than base and every client retried in a correlated band. That is\n * not full jitter, despite what this comment and API_SPEC §10 both used to claim. Full\n * jitter (the AWS-canonical form) decorrelates clients by spreading retries across the\n * whole window, which is the entire point of jittering a thundering herd.\n *\n * Consequence worth knowing: this can return 0, i.e. an immediate retry on the first\n * attempt. That is intended — `maxRetries` bounds the total, and a single fast retry is\n * how a client recovers from a transient blip without waiting a full second.\n *\n * attempt is 0-based.\n */\nexport function backoffMs(attempt: number, random: () => number = Math.random): number {\n const base = Math.min(BASE_MS * 2 ** attempt, MAX_BACKOFF_MS);\n return Math.round(random() * base);\n}\n\n/**\n * `Retry-After` as a delay in ms: delay-seconds or an HTTP-date (RFC 9110 §10.2.3). 0 when\n * absent, unreadable or not in the future. The caller caps it (breaker.hold: 60 min).\n */\nexport function retryAfterMs(value: string | null | undefined, now: number): number {\n if (!value) return 0;\n const seconds = Number(value);\n const ms = seconds === seconds ? seconds * 1000 : Date.parse(value) - now;\n return ms > 0 ? ms : 0;\n}\n","/**\n * Request-body compression for the fetch upload path.\n *\n * A module of its own so the Shopify custom-pixel build can swap it for `gzip.noop.ts`: the\n * pixel forces `compression: 'none'` (it keeps the cross-origin request headers minimal), so\n * none of this can run there, and that build is unminified against a 64,000-character editor\n * limit (see `tsup.config.ts`).\n */\n\n/** gzip a string via the streams API (available in all evergreen browsers + Node 18+). */\nasync function gzip(text: string): Promise<Uint8Array<ArrayBuffer>> {\n const cs = new CompressionStream('gzip');\n const writer = cs.writable.getWriter();\n // Fire-and-forget: data flows as the reader below pulls (awaiting here can deadlock).\n writer.write(new TextEncoder().encode(text)).catch(() => {});\n writer.close().catch(() => {});\n\n const reader = cs.readable.getReader();\n const chunks: Uint8Array[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n const total = chunks.reduce((n, c) => n + c.length, 0);\n const out = new Uint8Array(new ArrayBuffer(total));\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.length;\n }\n return out;\n}\n\n/**\n * `text` gzipped, or null when it should go out as plain JSON: compression is off, the platform\n * has no `CompressionStream`, or compressing failed.\n */\nexport async function compress(\n text: string,\n mode: 'gzip' | 'none' | undefined\n): Promise<Uint8Array<ArrayBuffer> | null> {\n if (mode === 'none' || typeof CompressionStream === 'undefined') return null;\n try {\n return await gzip(text);\n } catch {\n return null;\n }\n}\n","import type { EventQueue } from '../queue/queue';\nimport type { BatchPayload, DepsmithSdkEvent } from '../types';\nimport type { NetworkBreaker } from './breaker';\n\n/**\n * The `sendBeacon` drain, apart from the uploader so the Shopify custom-pixel build can swap it\n * for `beacon.noop.ts`: the pixel has no `pagehide` and never calls it, and that build is\n * unminified against a 64,000-character editor limit (see `tsup.config.ts`).\n */\n\n/**\n * Ceiling on batches drained synchronously in the unload handler.\n *\n * `sendBeacon` itself has a UA-level queue cap that this stays well under, but the real\n * reason for the bound is wall-clock: every batch is a `JSON.stringify` plus a `Blob`\n * allocation, and this loop delays the navigation the visitor just asked for. At the\n * default batchSize of 20 this ships up to 200 events, and anything beyond that is a\n * backlog that a timed flush should have drained already.\n */\nconst MAX_UNLOAD_BATCHES = 10;\n\n/**\n * Event budget per beacon, in UTF-16 code units of their JSON. The Fetch spec caps keepalive\n * bodies — sendBeacon included — at 64 KiB in flight per document, and a beacon over it is\n * refused outright. Counting events, a `batchSize` of 100 with ordinary 1 KB events was over\n * the cap, so every unload flush was refused at its first batch (deep-dive WC-14). 48 K leaves\n * room for the envelope and some non-ASCII text; the rest of the 64 KiB is the host page's.\n */\nconst BEACON_MAX_CHARS = 48_000;\n\n/**\n * Best-effort final flush on `pagehide` via navigator.sendBeacon (fire-and-forget;\n * survives page teardown). Queued events are removed only if the UA accepted them.\n *\n * **This is the one path that deletes without a 2xx** (API_SPEC §1.7, §9): `sendBeacon`\n * returning true means the UA queued the request, not that the collector took it, and there\n * is no response to wait for on a document that is going away. So it is confined to the\n * cases where that bet is reasonable, and everything else stays persisted for the fetch\n * path, which does wait for a 2xx:\n * - **not while offline** — the UA accepts the beacon, the request fails, and the events\n * were already gone;\n * - **not while the collector is unreachable** (breaker open, or the last cycle ended in\n * network errors) — the same loss, into an ad-blocker or DNS filter, on every hide;\n * - **never the batch the fetch drain is uploading** — it is already on the wire with\n * `keepalive`, and beaconing it too delivered it twice.\n * The caller additionally restricts this to a real `pagehide`; a tab merely being hidden\n * uses the fetch path (see the client's lifecycle handlers).\n *\n * This runs inside the unload handler, so on a multi-page site it is on the critical\n * path of *every* navigation. Two things keep it off that path:\n * - the per-batch `queue.remove()` no longer writes to storage (EventQueue is\n * write-behind); the caller force-persists once, after this returns;\n * - the drain is bounded by MAX_UNLOAD_BATCHES, so a large backlog can never stall a\n * navigation. Whatever is left stays persisted and replays on the next page load.\n */\nexport function sendBeacons(\n queue: EventQueue,\n config: { endpoint: string; batchSize: number },\n deps: { isOnline: () => boolean; breaker?: NetworkBreaker },\n /** Events at the head of the queue that a fetch upload has in flight. */\n uploading: number,\n buildPayload: (batch: DepsmithSdkEvent[]) => BatchPayload\n): void {\n try {\n if (typeof navigator === 'undefined' || !navigator.sendBeacon) return;\n const breaker = deps.breaker;\n if (!deps.isOnline() || breaker?.open() || breaker?.suspect()) return;\n let from = uploading;\n for (let n = 0; n < MAX_UNLOAD_BATCHES; n++) {\n const batch = queue.peek(config.batchSize, BEACON_MAX_CHARS, from);\n if (!batch.length) return;\n const payload = buildPayload(batch); // always uncompressed: sendBeacon has no header control\n // `text/plain`, not `application/json`, and the body is still JSON. This is the one\n // CORS-safelisted content type a Blob can carry, so the POST needs no preflight —\n // and a preflight is fatal here: the document is already being torn down, so the UA\n // never gets to send the follow-up request. sendBeacon would still return true, the\n // batch would still be removed from the queue below, and the events would be lost\n // rather than deferred. The fetch path keeps `application/json` (API_SPEC §6).\n const accepted = navigator.sendBeacon(\n `${config.endpoint}/e/`,\n new Blob([JSON.stringify(payload)], { type: 'text/plain' })\n );\n if (accepted) queue.remove(batch.map((event) => event.event_id));\n else if (batch.length > 1) return; // UA queue full — keep events persisted\n else from++; // one event too large for any beacon: the fetch path will send it\n }\n } catch {\n // events remain persisted; next page load replays them\n }\n}\n","import type { EventQueue } from '../queue/queue';\nimport type { Clock } from '../utils/clock';\nimport type { Logger } from '../utils/logger';\nimport type { BatchPayload, DepsmithSdkEvent } from '../types';\nimport { isoTimestamp } from '../utils/clock';\nimport type { NetworkBreaker } from './breaker';\nimport { backoffMs, isRetryable, retryAfterMs } from './retry';\n// Separate modules so the Shopify pixel build can compile them away: it never compresses and\n// has no `pagehide`. See gzip.noop.ts and beacon.noop.ts.\nimport { compress } from './gzip';\nimport { sendBeacons } from './beacon';\n\n/**\n * Hoisted out of the drain loops on purpose: an inline `batch.map(e => e.event_id)`\n * puts a function literal inside a `while` body, which Shopify's pixel-editor linter\n * rejects (\"Functions declared within loops\"), blocking the merchant from saving.\n */\nfunction eventIds(batch: DepsmithSdkEvent[]): string[] {\n const ids: string[] = [];\n for (const event of batch) ids.push(event.event_id);\n return ids;\n}\n\n/**\n * Overall cap on a single upload attempt. Without it a hung connection never settles,\n * and because flush() memoizes `inFlight` every later flush coalesces onto that stuck\n * promise — the SDK goes permanently silent with a full queue. Matches the read/write\n * timeout the Android transport already sets, so the platforms agree.\n */\nexport const REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * The Fetch spec caps `keepalive` request bodies at 64 KiB *across all in-flight\n * keepalive requests*; over that the promise rejects outright. 60 KiB leaves headroom.\n */\nconst KEEPALIVE_MAX_BYTES = 60_000;\n\n/**\n * Ceiling on the events in one fetch batch, in UTF-16 code units of their JSON — the queue\n * already knows each event's, so this costs no serialisation. `batchSize` alone counted events\n * and said nothing about bytes: 500 events, or one 300 KB property, made a body any collector\n * limit could refuse (deep-dive WC-14). At most ~768 KB of UTF-8 even if every character is\n * non-ASCII, so a collector accepting 1 MB bodies takes every multi-event batch. A single event\n * over the budget is still sent, alone.\n */\nexport const MAX_BATCH_CHARS = 256_000;\n\n/** Byte length of whatever we're about to send, for the keepalive check. */\nfunction bodyBytes(body: BodyInit): number {\n if (typeof body === 'string') return new TextEncoder().encode(body).byteLength;\n if (body instanceof Uint8Array) return body.byteLength;\n return 0; // unknown shape — treat as small rather than refusing keepalive\n}\n\nexport interface UploaderConfig {\n endpoint: string;\n apiKey: string;\n batchSize: number;\n maxRetries: number;\n /** gzip via CompressionStream when available; plain JSON fallback. */\n compression?: 'gzip' | 'none';\n /** Adds anonymize_ip: true to every batch body. */\n anonymizeIp?: boolean;\n /** Per-attempt timeout. Injectable so tests don't wait 30s. */\n requestTimeoutMs?: number;\n}\n\nexport interface UploaderDeps {\n fetchFn: typeof fetch;\n clock: Clock;\n logger: Logger;\n /** Injectable so tests/conformance can fast-forward backoff waits. */\n sleep: (ms: number) => Promise<void>;\n isOnline: () => boolean;\n /** Pauses uploads while the collector is unreachable (status 0 only). Absent = never pause. */\n breaker?: NetworkBreaker;\n /**\n * Current consent, re-read before every retry (API_SPEC §6): an `optOut()` during a backoff\n * sleep must stop the retry, not just empty the queue behind it. Between batches no check is\n * needed: every batch is peeked from the queue, which `optOut()` has already cleared.\n * Absent = always allowed.\n */\n canUpload?: () => boolean;\n}\n\n/** Synthetic status for a response fetch reached through a redirect; a 3xx, so refused. */\nconst REDIRECTED = 399;\n\n/** 3xx, 401, 403: about the key or the endpoint, not the events. Kept, and uploads pause. */\nfunction refused(status: number): boolean {\n return (status > 299 && status < 400) || status === 401 || status === 403;\n}\n\n/**\n * First pause after a cycle the collector answered without accepting (refused, or 408/429/5xx\n * through every retry); doubles per such cycle, capped. `Retry-After` replaces it when sent.\n */\nexport const HOLD_BASE_MS = 30_000;\nexport const HOLD_MAX_MS = 60 * 60_000;\n\n/**\n * Drains the queue oldest-first, one in-flight upload at a time (API_SPEC §10, §11).\n *\n * - **2xx** delete.\n * - **Network error / 408 / 429 / 5xx** retry with backoff up to maxRetries; the events stay.\n * A cycle that got answers but no 2xx then pauses uploads like a refusal below, or for the\n * `Retry-After` the collector sent (which also ends the cycle at once).\n * - **401 / 403 / 3xx** (including any response fetch reached by following a redirect) — refused: the answer is about the key or the endpoint, not these\n * events, so dropping would walk the whole queue into the bin one batch at a time. The batch\n * stays, the cycle ends and uploads pause (`deps.breaker.hold`), 30 s doubling to 60 min.\n * - **400 / 413** — something in this batch, or its size: halve it and go again, down to a\n * single event, which is then dropped and the size returns to `batchSize`. The smaller size is\n * kept for the rest of the cycle. A dropped 400 also ends the cycle: one isolated invalid event\n * per cycle, so a collector rejecting everything is not sent the queue one request at a time.\n * - **`Retry-After`** on any answer the cycle would retry ends the cycle; uploads pause until\n * then, capped at 60 min and persisted with the breaker, so a navigation honours it.\n * - **Other 4xx** (404, 422…) drop the batch: a poison batch must not wedge the queue.\n *\n * Every drop is logged with `notice`, which prints whether or not `debug` is on.\n * Repeated network errors (no HTTP response) open `deps.breaker` — see breaker.ts.\n */\nexport class BatchUploader {\n private inFlight: Promise<void> | null = null;\n /**\n * Size of the batch the fetch drain is uploading right now; 0 between batches. That batch is\n * always the head of the queue, so a count is enough to step over it — and if an eviction\n * ever shifts the head mid-upload, the error is on the safe side: an event is left persisted\n * for the next load rather than beaconed.\n */\n private uploading = 0;\n /** Batch size after a 400/413 halving; 0 = `config.batchSize`. Reset by every cycle. */\n private limit = 0;\n /** Consecutive cycles the collector answered but did not accept; sets the next pause. */\n private strikes = 0;\n /** `Retry-After` of the last response, in ms; 0 when it had none. */\n private wait = 0;\n\n constructor(\n private queue: EventQueue,\n private config: UploaderConfig,\n private deps: UploaderDeps\n ) {}\n\n /** Resolves once any in-flight drain settles, without starting a new one. */\n pending(): Promise<void> {\n return this.inFlight ?? Promise.resolve();\n }\n\n /** Connectivity came back: let the next flush try again immediately. */\n resetNetworkBreaker(): void {\n this.deps.breaker?.ok();\n }\n\n /** Resolves when the current drain attempt completes. Never rejects. */\n flush(): Promise<void> {\n if (this.inFlight) return this.inFlight;\n this.inFlight = this.drain()\n .catch((err) => this.deps.logger.error('flush failed', err))\n .finally(() => {\n this.inFlight = null;\n });\n return this.inFlight;\n }\n\n private async drain(): Promise<void> {\n this.limit = 0;\n while (this.queue.size > 0) {\n if (!this.deps.isOnline()) {\n this.deps.logger.debug('offline; deferring upload');\n return;\n }\n // Before persistNow() on purpose: a paused cycle should cost nothing at all — not the\n // storage write, not the stringify, not the request. The queue is left as it is.\n if (this.deps.breaker?.open()) {\n this.deps.logger.debug('uploads paused');\n return;\n }\n const max = this.config.batchSize;\n const batch = this.queue.peek(this.limit || max, MAX_BATCH_CHARS);\n // API_SPEC §1 step 4: durable storage BEFORE any network attempt. The queue is\n // write-behind, so this is the point that makes the invariant hold — and the right\n // point, because it costs one write per batch actually sent rather than one per\n // event captured. A no-op when nothing has changed since the last write.\n this.queue.persistNow();\n this.uploading = batch.length;\n const status = await this.uploadWithRetry(batch); // never rejects: post() catches\n this.uploading = 0;\n if (refused(status) || isRetryable(status)) return; // kept for a later cycle; see uploadWithRetry\n if (status === 400 || status === 413) {\n if (batch.length > 1) {\n this.limit = batch.length >> 1;\n continue;\n }\n this.limit = 0;\n }\n if (status > 299) this.deps.logger.notice(`collector answered ${status}; dropped ${batch.length} event(s)`);\n this.queue.remove(eventIds(batch));\n // One isolated poison event per cycle: a collector rejecting every event would\n // otherwise be sent the whole queue one request at a time, back to back.\n if (status === 400) return;\n }\n }\n\n /** The final status of up to `maxRetries + 1` attempts. Pauses uploads when the collector\n * answered without accepting. */\n private async uploadWithRetry(batch: DepsmithSdkEvent[]): Promise<number> {\n const breaker = this.deps.breaker;\n let answered = false; // did ANY attempt get an HTTP response?\n let status = 0;\n for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {\n // A retry re-sends a batch selected before the backoff sleep. Send it only if consent\n // still allows uploads and the batch is still the head of the queue: optOut() clears the\n // queue but cannot reach this local copy, and a withdrawn event must not be sent again\n // (#83). The cycle ends with the last retryable status, so the drain stops and a later\n // cycle re-peeks whatever the queue holds by then.\n if (\n attempt &&\n (this.deps.canUpload?.() === false || this.queue.peek(1)[0]?.event_id !== batch[0]!.event_id)\n ) {\n break;\n }\n status = await this.post(batch);\n if (status) answered = true;\n // A Retry-After ends the cycle: retrying inside it would be sooner than we were told.\n if (!isRetryable(status) || this.wait) break;\n this.deps.logger.debug(`upload attempt ${attempt + 1} failed (${status})`);\n // The previous cycle already ended in network errors, so this one does not spend\n // its whole retry budget re-proving it. One attempt per cycle until the breaker opens.\n if (!answered && breaker?.suspect()) break;\n if (attempt < this.config.maxRetries) await this.deps.sleep(backoffMs(attempt));\n }\n if (!answered) {\n breaker?.fail();\n } else {\n breaker?.ok(); // reachable, whatever it said\n if (status > 199 && status < 300) this.strikes = 0;\n else if (refused(status) || isRetryable(status)) {\n // Without this pause the next capture started a fresh six-attempt cycle at once, and a\n // struggling collector was hit continuously by every busy tab (WC-10).\n if (refused(status)) this.deps.logger.notice(`collector refused uploads (${status}); paused`);\n breaker?.hold(this.wait || Math.min(HOLD_BASE_MS * 2 ** this.strikes++, HOLD_MAX_MS));\n }\n }\n return status;\n }\n\n private buildPayload(batch: DepsmithSdkEvent[]): BatchPayload {\n const payload: BatchPayload = {\n batch,\n api_key: this.config.apiKey,\n source: 'sdk',\n sent_at: isoTimestamp(this.deps.clock.now()),\n };\n if (this.config.anonymizeIp) payload.anonymize_ip = true;\n return payload;\n }\n\n /** Returns HTTP status; 0 for network errors/timeouts. */\n private async post(batch: DepsmithSdkEvent[]): Promise<number> {\n this.wait = 0;\n const json = JSON.stringify(this.buildPayload(batch));\n // Declared outside the try so the finally can always clear it.\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n try {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n // Null means plain JSON: compression off, unsupported, or failed.\n const zipped = await compress(json, this.config.compression);\n if (zipped) headers['Content-Encoding'] = 'gzip';\n const body: BodyInit = zipped ?? json;\n // Oversized bodies are rejected outright by the UA when keepalive is set, and the\n // payload is deterministic — so it would fail identically on every retry and the\n // batch would never drain. A plain fetch has no size cap; the only thing given up\n // is surviving page teardown, which beats never delivering at all.\n const keepalive = bodyBytes(body) <= KEEPALIVE_MAX_BYTES;\n if (!keepalive) {\n this.deps.logger.debug('payload over keepalive cap; sending without keepalive');\n }\n\n const init: RequestInit = { method: 'POST', headers, body, keepalive };\n if (controller) {\n init.signal = controller.signal;\n // AbortController rather than AbortSignal.timeout(): the build targets es2020\n // and AbortSignal.timeout is a 2022 API.\n timer = setTimeout(() => controller.abort(), this.timeoutMs());\n }\n\n const res = await this.deps.fetchFn(`${this.config.endpoint}/e/`, init);\n // fetch follows redirects, so a 3xx never reaches us: a captive portal's 302 to its 200\n // login page would read as delivered and delete the batch. Whatever answered at the end\n // of a redirect is not the collector — refused, like the 3xx it was.\n if (res.redirected) return REDIRECTED;\n // Readable cross-origin only if the collector lists it in Access-Control-Expose-Headers.\n this.wait = retryAfterMs(res.headers?.get('Retry-After'), this.deps.clock.now());\n return res.status;\n } catch {\n // Includes AbortError. isRetryable(0) is true, so a timeout retries with backoff.\n return 0;\n } finally {\n if (timer !== null) clearTimeout(timer);\n }\n }\n\n private timeoutMs(): number {\n const configured = this.config.requestTimeoutMs;\n return typeof configured === 'number' && configured > 0 ? configured : REQUEST_TIMEOUT_MS;\n }\n\n /** The `pagehide` drain — see `beacon.ts`. Skips the batch a fetch upload has in flight. */\n sendBeaconAll(): void {\n sendBeacons(this.queue, this.config, this.deps, this.uploading, (batch) =>\n this.buildPayload(batch)\n );\n }\n}\n","import type { KVStorage } from '../queue/storage';\nimport type { Clock } from '../utils/clock';\n\n/** Persisted so a visitor who cannot reach the collector does not restart the storm per page. */\nexport const KEY_NET_BREAKER = 'depsmith_net_breaker';\n\n/** Consecutive flush cycles that got no HTTP response at all before uploads pause. */\nexport const TRIP_AFTER_CYCLES = 3;\nexport const BASE_COOLDOWN_MS = 5 * 60_000;\nexport const MAX_COOLDOWN_MS = 60 * 60_000;\n\nexport interface NetworkBreaker {\n /** True while cooling down: the caller skips the network entirely. */\n open(): boolean;\n /**\n * True once a cycle has already ended in network errors. The next network error then ends\n * its cycle at once instead of spending the full retry budget on a host that just failed.\n */\n suspect(): boolean;\n /** A cycle ended with status 0 on every attempt it made. */\n fail(): void;\n /** The collector answered with any HTTP status, or connectivity changed. Closes it. */\n ok(): void;\n /**\n * The collector answered but asked for a pause (refused key, Retry-After, …): stay open for\n * `ms`, capped at MAX_COOLDOWN_MS. Persisted like a trip. No request is made while it\n * runs, so nothing calls `ok()` early except a connectivity change after a network trip.\n */\n hold(ms: number): void;\n}\n\n/**\n * Circuit breaker for a collector the browser cannot reach (API_SPEC §10).\n *\n * Status 0 is retryable because it is usually a blip. It is also exactly what an\n * ad-blocker, a DNS filter or a CORS misconfiguration produces, and those never heal: each\n * flush cycle then stringifies, gzips and persists a batch, fails six times in a row, and\n * logs an error per attempt — every 60 s, every 20 events, on every page, for the whole\n * visit. Only status 0 counts. Any HTTP response, error statuses included, proves the\n * collector is reachable and closes the breaker; 5xx/429 keep the ordinary backoff.\n *\n * Events are never dropped here. A paused cycle leaves the queue untouched, so the\n * at-least-once guarantee is the same as for any other requeue.\n *\n * A closure over locals rather than a class: property and method names survive\n * minification, and the core bundle has a size gate this would otherwise exceed.\n * Persisted as `[failures, openUntil, nextCooldownMs]` for the same reason.\n */\nexport function createNetworkBreaker(storage: KVStorage, clock: Clock): NetworkBreaker {\n let loaded = false;\n let failures = 0;\n /** Epoch ms; uploads are skipped while `now < openUntil`. 0 = closed. */\n let openUntil = 0;\n /** The cooldown the NEXT trip uses. Doubles per trip, capped at MAX_COOLDOWN_MS. */\n let cooldown = BASE_COOLDOWN_MS;\n\n const clamp = (v: unknown, lo: number, hi: number): number =>\n typeof v === 'number' && v === v ? Math.min(Math.max(v, lo), hi) : lo;\n\n // Read lazily, not at construction: IndexedDB and Shopify's async storage are only\n // hydrated by the first flush, and an eager read would always see them empty.\n const load = (): void => {\n if (loaded) return;\n loaded = true;\n try {\n const s = JSON.parse(storage.get(KEY_NET_BREAKER) ?? '0') as unknown;\n if (!Array.isArray(s)) return;\n failures = clamp(s[0], 0, TRIP_AFTER_CYCLES);\n // Clamped so a corrupt or clock-skewed value can never pause uploads for longer\n // than one maximum cooldown from now.\n openUntil = clamp(s[1], 0, clock.now() + MAX_COOLDOWN_MS);\n cooldown = clamp(s[2], BASE_COOLDOWN_MS, MAX_COOLDOWN_MS);\n } catch {\n // unreadable state is the same as none: closed\n }\n };\n\n const save = (): void => {\n try {\n if (failures || openUntil > clock.now()) storage.set(KEY_NET_BREAKER, JSON.stringify([failures, openUntil, cooldown]));\n else storage.remove(KEY_NET_BREAKER);\n } catch {\n // storage full or denied: the in-memory state still protects this page\n }\n };\n\n return {\n // Re-clamped on every read: a clock set back during a pause must not stretch it past the cap.\n open: () => (load(), clock.now() < (openUntil = Math.min(openUntil, clock.now() + MAX_COOLDOWN_MS))),\n suspect: () => (load(), failures > 0),\n fail: () => {\n load();\n if (++failures >= TRIP_AFTER_CYCLES) {\n openUntil = clock.now() + cooldown;\n cooldown = Math.min(cooldown * 2, MAX_COOLDOWN_MS);\n // Left at the threshold, not zeroed: the single probe after the cooldown must\n // re-trip on failure rather than earning another three cycles of retries.\n failures = TRIP_AFTER_CYCLES;\n }\n save();\n },\n ok: () => {\n load();\n if (!failures) return;\n failures = openUntil = 0;\n cooldown = BASE_COOLDOWN_MS;\n save();\n },\n hold: (ms) => {\n load();\n openUntil = Math.max(openUntil, clock.now() + Math.min(ms, MAX_COOLDOWN_MS));\n save();\n },\n };\n}\n","/** Debug-gated logger. The SDK never throws to the host app; failures surface here in debug mode only. */\nexport class Logger {\n constructor(private enabled: boolean) {}\n\n setEnabled(enabled: boolean): void {\n this.enabled = enabled;\n }\n\n debug(...args: unknown[]): void {\n if (this.enabled) console.debug('[depsmith-sdk]', ...args);\n }\n\n warn(...args: unknown[]): void {\n if (this.enabled) console.warn('[depsmith-sdk]', ...args);\n }\n\n /**\n * Always printed, `debug` or not. Reserved for the collector refusing or discarding data\n * (API_SPEC §10): a site whose events are being dropped must be able to see it without\n * first knowing to turn debug on. Rare by construction — once per dropped batch or refused cycle.\n */\n notice(...args: unknown[]): void {\n console.warn('[depsmith-sdk]', ...args);\n }\n\n error(...args: unknown[]): void {\n if (this.enabled) console.error('[depsmith-sdk]', ...args);\n }\n}\n","/**\n * `scrubUrls`: opt-in removal of query strings and fragments from every URL the SDK sends.\n *\n * Off by default, and then nothing here runs: URLs are sent whole, as they always were. Reset\n * links, OAuth callbacks (`#access_token=`), signed storage URLs and search terms all live in the\n * query or fragment, so a site that has them can turn this on rather than suppress `context.page`\n * altogether.\n *\n * Applied once per event, on the finished event just before it is queued, so every source is\n * covered by one pass — the page context, the attribution block, autocapture and the network\n * error reporter — and the persisted queue never holds the unscrubbed form.\n */\nimport type { DepsmithSdkEvent } from './types';\n\n/** `true` drops every query parameter; `keepParams` names the ones to keep. Fragments always go. */\nexport type ScrubUrls = boolean | { keepParams?: string[] };\n\n/** Full URLs in `context.page` (url, referrer, previous_url) and `context.referrer`. */\nconst CONTEXT_KEYS = ['url', 'referrer', 'previous_url', 'initial_url'];\n/** URL-valued SDK properties. `$net_query` / `$net_fragment` are handled on their own. */\nconst URL_PROPERTIES = ['$ac_href', '$ac_form_action', '$net_url', '$fr_error_file'];\n\n/**\n * Removes the fragment, and every query parameter not in `keep`. String surgery rather than\n * `new URL`, so relative URLs (a form's raw `action`) and unparseable ones are handled too, and a\n * kept parameter is sent exactly as it was written.\n */\nexport function scrubUrl(url: string, keep: ReadonlySet<string>): string {\n const bare = url.split('#')[0]!;\n const q = bare.indexOf('?');\n if (q < 0) return bare;\n const kept = bare\n .slice(q + 1)\n .split('&')\n .filter((pair) => keep.has(paramName(pair)));\n return bare.slice(0, q) + (kept.length ? `?${kept.join('&')}` : '');\n}\n\nfunction paramName(pair: string): string {\n const name = pair.split('=')[0]!.replace(/\\+/g, ' ');\n try {\n return decodeURIComponent(name);\n } catch {\n return name;\n }\n}\n\n/**\n * Scrubs `event` in place. A no-op unless `option` turns scrubbing on. Never throws. Fields the\n * host wrote itself are left alone: only SDK-owned keys are touched.\n */\nexport function scrubEventUrls(event: DepsmithSdkEvent, option: ScrubUrls | undefined): void {\n if (!option) return;\n try {\n const params = (option as { keepParams?: unknown }).keepParams;\n const keep = new Set(Array.isArray(params) ? params : []);\n const targets: Array<[Record<string, unknown> | undefined, string[]]> = [\n [event.context.page, CONTEXT_KEYS],\n [event.context.referrer, CONTEXT_KEYS],\n [event.properties, URL_PROPERTIES],\n ];\n for (const [target, keys] of targets) {\n for (const key of keys) {\n const value = target?.[key];\n if (typeof value === 'string') target![key] = scrubUrl(value, keep);\n }\n }\n const props = event.properties;\n if (!props) return;\n delete props.$net_fragment;\n if (typeof props.$net_query === 'string') {\n const query = scrubUrl(`?${props.$net_query}`, keep).slice(1);\n if (query) props.$net_query = query;\n else delete props.$net_query;\n }\n } catch {\n /* never lose an event to the scrubber */\n }\n}\n","import { Attribution } from './attribution';\nimport { PageLifecycle } from './page';\n// Separate module so the Shopify pixel build can compile the handlers away — it always passes\n// `manualLifecycle`. See src/lifecycle.noop.ts.\nimport { startLifecycle, type BrowserLifecycle } from './lifecycle';\nimport { loadAutocapture } from './autocapture/load';\nimport { resolveConfig, type DepsmithSdkConfig, type ResolvedConfig } from './config';\nimport {\n buildContext,\n dntEnabled,\n LIBRARY_NAME,\n SDK_VERSION,\n type ContextOptions,\n} from './context';\nimport { computeVisitorId, fingerprintComponents, primeClientHints } from './fingerprint';\nimport { primeGeolocation } from './geolocation';\nimport { ConsentManager } from './consent';\nimport { EventQueue } from './queue/tab-queue';\nimport {\n CookieAdapter,\n MemoryAdapter,\n RedundantAdapter,\n type KVStorage,\n} from './queue/storage';\n// Separate module so the Shopify pixel build can compile these away — it always injects its own\n// storage, so neither adapter is reachable there. See src/queue/storage-local.noop.ts.\nimport { defaultStorage, hydrateQueue, pickQueueStorage } from './queue/storage-local';\nimport { IdentityManager } from './identity';\nimport { SessionManager, type SessionTouch } from './session';\nimport { sanitizeProperties } from './props';\nimport { isReserved, stripReserved } from './reserved';\nimport { observeNetworkErrors } from './network-errors';\nimport { observeVitals, type Vitals } from './web-vitals';\nimport { SuperProperties } from './super-properties';\nimport { normalizeUserPropertyOps, sanitizedTraitOp, type UserPropertyOps } from './user-properties';\nimport { BatchUploader } from './transport/uploader';\nimport { createNetworkBreaker, KEY_NET_BREAKER } from './transport/breaker';\nimport { isoTimestamp, systemClock, type Clock } from './utils/clock';\nimport { Logger } from './utils/logger';\nimport { uuidv7 } from './utils/uuidv7';\nimport type { Scheduler } from './utils/scheduler';\nimport { bucket, djb2 } from './hash';\nimport { scrubEventUrls } from './url-scrub';\nimport type { DepsmithSdkEvent, EventContext, EventType, PageOptions, Properties } from './types';\n\n/** The fingerprint of the apiKey that last initialised on this origin (see detectConfigDrift). */\nconst KEY_CONFIG_FP = 'depsmith_config_fp';\n\n/**\n * Mirrors the `maxLength` on `event`, `user_id` and `group_id` in event.schema.json. Enforced\n * client-side because the collector enforces it with a 400, and a 400 costs the event plus the\n * requests the uploader spends bisecting down to it (API_SPEC §10).\n */\nconst MAX_ENVELOPE_ID_LENGTH = 255;\n\n/** Test/conformance seams. Not part of the public API contract. */\nexport interface InternalOverrides {\n storage?: KVStorage;\n clock?: Clock;\n fetchFn?: typeof fetch;\n isOnline?: () => boolean;\n sleep?: (ms: number) => Promise<void>;\n dnt?: boolean;\n /** Per-attempt upload timeout. Test seam so a hung-request test needn't wait 30s. */\n requestTimeoutMs?: number;\n /** Disable timers/listeners (conformance runners drive flushes explicitly). */\n manualLifecycle?: boolean;\n /**\n * Called at capture time for host-supplied `context` fields, shallow-merged over the\n * derived ones. Used by the Shopify web-pixel adapter, which gets fresh page context\n * on every event and cannot read the real `window`/`document`.\n */\n contextProvider?: () => Partial<EventContext>;\n /**\n * How queue/session persistence is deferred. Defaults to an idle callback, which is what\n * keeps the blocking `localStorage` write off the capture path. Pass `syncScheduler` to\n * restore write-through — tests do, and so does any host whose storage is already\n * non-blocking (the Shopify pixel's async-mirrored storage).\n */\n schedule?: Scheduler;\n}\n\nexport class DepsmithSdkClient {\n private config: ResolvedConfig;\n private logger: Logger;\n private storage: KVStorage;\n private clock: Clock;\n private identity: IdentityManager;\n private session: SessionManager;\n private consent: ConsentManager;\n private attribution: Attribution;\n private superProperties: SuperProperties;\n /**\n * `$page_view` / `$page_leave` and the navigation half of `context.page`. Everything but this\n * handle lives in `page.ts`, which the Shopify pixel build swaps for a no-op — see the note\n * on {@link PageLifecycle}.\n */\n private pageLife: PageLifecycle;\n /**\n * Autocapture's unload-time `$page_leave` trigger, when pageview tracking is on.\n *\n * The client owns the call site rather than autocapture, because it must run BEFORE the\n * teardown drain — see `lifecycle.ts`. Undefined means no page-leave tracking:\n * autocapture is off, compiled out, or still loading.\n */\n private leaveOnUnload?: () => void;\n /** Core Web Vitals, when autocapture is on. Reported once, on the first hide. */\n private vitals?: Vitals;\n /** Set once $web_vitals has been emitted, so a tab shown and hidden again does not repeat it. */\n private vitalsReported = false;\n private queue: EventQueue;\n private uploader: BatchUploader;\n /** Timer and page listeners. Undefined under `manualLifecycle`, and in the pixel build. */\n private lifecycle?: BrowserLifecycle;\n /** Set by shutdown(); a lazily loaded autocapture chunk checks it before starting. */\n private stopped = false;\n private teardownFns: Array<() => void> = [];\n private contextProvider?: () => Partial<EventContext>;\n\n /** Resolves once async storage (IndexedDB) is hydrated; uploads gate on this. */\n private ready: Promise<void> = Promise.resolve();\n\n constructor(config: DepsmithSdkConfig, overrides: InternalOverrides = {}) {\n this.config = resolveConfig(config); // throws on invalid config — the one construction-time error\n this.logger = new Logger(this.config.debug);\n this.clock = overrides.clock ?? systemClock;\n this.storage = overrides.storage ?? this.pickStorage();\n // `storage: 'indexeddb'` moves the QUEUE to IndexedDB (the larger quota is the point) and\n // nothing else. IndexedDB can only be read asynchronously, and consent, identity, session\n // and the config fingerprint are all read synchronously right here in the constructor —\n // on a store that had not loaded yet they were simply absent. A persisted opt-out was\n // ignored on every page load, each load minted a new session, and apiKey drift was never\n // seen. Those keys now stay in the synchronous store; only the queue waits for hydration.\n const queueStorage = overrides.storage\n ? this.storage\n : pickQueueStorage(this.config.storage, this.storage);\n this.contextProvider = overrides.contextProvider;\n this.pageLife = new PageLifecycle(\n {\n now: () => this.clock.now(),\n capture: (name, type, properties, at, page) =>\n this.capture(name, type, properties, undefined, undefined, at, page),\n },\n this.config\n );\n\n // COPPA child-safe mode: identity is memory-only (nothing identifying persists).\n // Otherwise cookieDomain moves identity keys to a cross-subdomain cookie.\n // Identity lives in TWO first-party stores, read-any/write-both, so losing either one does\n // not make a returning visitor look new — localStorage and cookies are cleared by different\n // user actions and different browser policies. `cookieDomain` still widens the cookie across\n // subdomains when set; without it the cookie is host-only, which needs no configuration.\n //\n // Skipped for `storage: 'memory'`, which is the SSR/test backend: someone who asked for no\n // persistence should not get a cookie. And for childSafeMode, where COPPA requires that\n // nothing identifying persists at all.\n const identityStorage: KVStorage = this.config.childSafeMode\n ? new MemoryAdapter()\n : this.config.storage === 'memory'\n ? this.storage\n : new RedundantAdapter(\n this.storage,\n new CookieAdapter(this.config.cookieDomain || undefined)\n );\n\n this.identity = new IdentityManager(identityStorage, this.clock);\n this.session = new SessionManager(\n this.storage,\n this.clock,\n this.config.sessionTimeoutMs,\n overrides.schedule\n );\n this.consent = new ConsentManager(\n this.storage,\n this.config.consentMode,\n this.config.respectDnt && (overrides.dnt ?? dntEnabled())\n );\n // Shares `identityStorage`, not `this.storage`: attribution is visitor-scoped like the\n // anonymous_id, so COPPA's memory-only rule and the cookie mirror must apply to it too.\n // A campaign surviving in localStorage after childSafeMode moved identity to memory would\n // re-link a child across launches by their acquisition source.\n this.attribution = new Attribution(identityStorage);\n // Plain `this.storage`, NOT identityStorage: registered properties are app state the client\n // chose (plan, A/B variant, store id), not identity — so the cookie mirror and COPPA's\n // memory-only rule do not apply to them.\n this.superProperties = new SuperProperties(this.storage, this.logger);\n // Record the landing before anything can capture, so the first event already carries it.\n //\n // Skipped when the host supplies a contextProvider, which is precisely the \"my globals are\n // not the page\" signal — the Shopify pixel's `window.location` points at its sandbox, not\n // the storefront. Writing from there would store the sandbox URL as the acquisition source\n // and, because the pixel shares these keys with the theme build through AsyncMirrorAdapter,\n // could overwrite the theme's correctly-captured campaign or pin first-touch to `$direct`\n // before the theme half ever ran. The pixel still READS the shared values and emits them,\n // so checkout events inherit the campaign the theme captured.\n if (!this.contextProvider && typeof window !== 'undefined' && window.location) {\n this.attribution.recordLanding(\n window.location.href,\n typeof document !== 'undefined' ? document.referrer : ''\n );\n // Seeds previous_url / previous_type / counter for the very first event, which may be a\n // $session_start emitted before any $page_view.\n this.pageLife.start(\n window.location.href,\n typeof document !== 'undefined' ? document.referrer : ''\n );\n }\n // The queue key is shared by every apiKey on the origin (deep-dive WC-11): it cannot be\n // namespaced without stranding queues the Shopify pixel mirrors by fixed key. So a write is\n // made only while this project still owns the origin (the config fingerprint is its own).\n // Once another apiKey has initialised here, this instance stops persisting — its events\n // still upload while the page lives — so none can be restored and sent under that key.\n const fp = djb2(this.config.apiKey);\n const owned: KVStorage = {\n get: (key) => queueStorage.get(key),\n set: (key, value) => {\n if (this.storage.get(KEY_CONFIG_FP) === fp) queueStorage.set(key, value);\n },\n remove: (key) => queueStorage.remove(key),\n };\n this.queue = new EventQueue(owned, this.config.maxQueueSize, this.logger, {\n maxChars: this.config.maxQueueBytes,\n schedule: overrides.schedule,\n });\n const drifted = this.detectConfigDrift(fp);\n this.primeDeviceSignals();\n\n // IndexedDB write-behind: merge the persisted queue once hydrated, gate uploads until then.\n this.ready = hydrateQueue(queueStorage, this.storage, this.consent, this.queue, drifted, this.logger);\n\n this.uploader = new BatchUploader(\n this.queue,\n {\n endpoint: this.config.endpoint,\n apiKey: this.config.apiKey,\n batchSize: this.config.batchSize,\n maxRetries: this.config.maxRetries,\n compression: this.config.compression,\n anonymizeIp: this.config.anonymizeIp,\n requestTimeoutMs: overrides.requestTimeoutMs,\n },\n {\n fetchFn: overrides.fetchFn ?? ((...args) => fetch(...args)),\n clock: this.clock,\n logger: this.logger,\n sleep: overrides.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))),\n isOnline:\n overrides.isOnline ??\n (() => (typeof navigator === 'undefined' ? true : navigator.onLine !== false)),\n breaker: createNetworkBreaker(this.storage, this.clock),\n canUpload: () => this.consent.canUpload(),\n }\n );\n\n if (!overrides.manualLifecycle) {\n this.lifecycle = startLifecycle({\n intervalMs: this.config.batchIntervalMs,\n guard: (fn) => this.guard(fn),\n vitals: () => this.emitWebVitals(),\n leave: () => this.leaveOnUnload?.(),\n restored: (persisted) => this.pageLife.restored(persisted),\n resume: () => this.resumeSession(),\n flushIfQueued: () => this.flushIfQueued(),\n persistNow: () => this.persistNow(),\n beacon: () => {\n if (this.consent.canUpload()) this.uploader.sendBeaconAll();\n },\n online: () => {\n // A network change is the one signal that a paused collector may be reachable again.\n this.uploader.resetNetworkBreaker();\n this.flushIfQueued();\n },\n });\n this.startAutocapture();\n }\n this.logger.debug('initialized', { endpoint: this.config.endpoint });\n }\n\n // ── Public API (API_SPEC §2) — every method is guarded: never throws ──────────\n\n track(name: string, properties?: Properties): void {\n this.trackInternal(name, stripReserved(properties, 'track', this.logger));\n }\n\n /**\n * `track()` without the `$`-key check on properties, for the SDK's own integrations. Not part\n * of the public API: the Shopify pixel needs it because it stamps `$shopify_client_id` on every\n * event it maps, which a public `track()` would now drop as reserved. Event names are checked\n * exactly as in `track()`.\n */\n trackInternal(name: string, properties?: Properties): void {\n this.guard(() => {\n if (typeof name !== 'string' || name.length === 0) {\n this.logger.warn('track: event name required');\n return;\n }\n if (isReserved(name, 'track', this.logger)) return;\n if (this.tooLong(name, 'track: event name')) return;\n this.capture(name, 'track', properties);\n });\n }\n\n /**\n * Rejects an envelope id the collector's schema would refuse, at the point it enters the SDK.\n *\n * Dropping the call is harsh, and it is the lesser harm. `event`, `user_id` and `group_id` are\n * all capped at 255 in event.schema.json, the collector validates every batch with Ajv, and a\n * 400 is non-retryable — the uploader bisects the batch and drops the event that fails. For\n * `user_id` and `group_id` that is not a one-event loss either: both are persisted and ride on\n * every subsequent event, so a single over-long id silently destroys everything that user sends\n * until reset(). A JWT or a concatenated composite key passed as a user id does it.\n *\n * Truncating instead would keep the events but silently merge two users sharing a 255-char\n * prefix, inventing data rather than losing it. Rejecting a schema-invalid value at capture is\n * the rule throughout: such an event would 400 and be dropped at upload, after a bisection.\n */\n /** Client traits as sent: `$` keys dropped, then sanitised like event properties. */\n private traits(traits: Properties | undefined, method: string): Properties {\n return sanitizeProperties(stripReserved(traits, method, this.logger), this.logger);\n }\n\n private tooLong(value: string, label: string): boolean {\n if (value.length <= MAX_ENVELOPE_ID_LENGTH) return false;\n this.logger.warn(\n `${label} exceeds ${MAX_ENVELOPE_ID_LENGTH} characters (got ${value.length}); dropped`\n );\n return true;\n }\n\n /** `options.type` is sent as `$page_type` (API_SPEC §2). */\n page(name?: string, properties?: Properties, options?: PageOptions): void {\n this.pageInternal(name, stripReserved(properties, 'page', this.logger), options);\n }\n\n /**\n * `page()` without the `$`-key check, for the SDK's own integrations. Not part of the public\n * API: the Shopify pixel sends checkout page views with `$checkout_step` and\n * `$shopify_client_id`, which a public `page()` would now drop as reserved. Still a manual\n * view — it is a call, not autocapture.\n *\n * Advances navigation state even for an explicit call, so an app that drives pageviews by hand\n * (no autocapture) still gets previous_url and counter — and claims the URL so autocapture\n * cannot emit a second view for the same page.\n */\n pageInternal(name?: string, properties?: Properties, options?: PageOptions): void {\n this.guard(() => this.pageLife.manual(name, properties, options?.type));\n }\n\n /**\n * `$web_vitals`, once per page, on the first time the tab is hidden.\n *\n * Hidden rather than loaded, because three of the five are not final until then: LCP can be\n * superseded by a later paint, CLS accumulates for the life of the page, and INP is the worst\n * interaction so far. Reporting at load would under-report all three — worse than not reporting,\n * because the numbers would look plausible.\n *\n * Once, not per hide: a tab switched away and back has the same page-load metrics, and a second\n * event would double-count the page in every average built on it.\n */\n private emitWebVitals(): void {\n if (this.vitalsReported || !this.vitals?.hasAny()) return;\n this.vitalsReported = true;\n this.capture('$web_vitals', 'track', this.vitals.snapshot());\n }\n\n /** Alias of page() — unified mobile naming. */\n screen(name?: string, properties?: Properties, options?: PageOptions): void {\n this.page(name, properties, options);\n }\n\n identify(userId: string, traits?: Properties): void {\n this.guard(() => {\n if (this.config.childSafeMode) {\n this.logger.warn('identify: disabled in childSafeMode (COPPA)');\n return;\n }\n if (typeof userId !== 'string' || userId.length === 0) {\n this.logger.warn('identify: userId required');\n return;\n }\n // Before identity.identify(), which PERSISTS it onto every subsequent event.\n if (this.tooLong(userId, 'identify: userId')) return;\n this.identity.identify(userId);\n const clean = this.traits(traits, 'identify');\n // Traits keep riding on context.traits, where every existing consumer reads them, AND\n // now describe a $set so they actually land as user properties. Before this they did\n // not: the collector applies `user_properties` only, so identify() traits reached the\n // warehouse as event context and never as properties of the person.\n this.capture('$identify', 'identify', undefined, clean, sanitizedTraitOp('$set', clean));\n });\n }\n\n alias(aliasId: string): void {\n this.guard(() => {\n if (this.config.childSafeMode) {\n this.logger.warn('alias: disabled in childSafeMode (COPPA)');\n return;\n }\n if (typeof aliasId !== 'string' || aliasId.length === 0) {\n this.logger.warn('alias: aliasId required');\n return;\n }\n this.capture('$alias', 'alias', { alias: aliasId });\n });\n }\n\n reset(): void {\n this.guard(() => {\n // A page view still waiting for its title belongs to the user being reset.\n this.pageLife.flushPending();\n this.identity.reset();\n this.session.rotate();\n // Forgetting the visitor has to include forgetting where they came from, otherwise the\n // next person on a shared browser inherits the previous one's acquisition source.\n this.attribution.clear();\n this.superProperties.clear();\n this.logger.debug('reset: identity, session and attribution cleared');\n });\n }\n\n group(groupId: string, traits?: Properties): void {\n this.guard(() => {\n if (typeof groupId !== 'string' || groupId.length === 0) {\n this.logger.warn('group: groupId required');\n return;\n }\n // Before identity.setGroup(), which PERSISTS it onto every subsequent event.\n if (this.tooLong(groupId, 'group: groupId')) return;\n this.identity.setGroup(groupId);\n const clean = this.traits(traits, 'group');\n this.capture('$group', 'group', undefined, clean);\n });\n }\n\n setGroupTraits(traits: Properties): void {\n this.guard(() => {\n if (!this.identity.groupId) {\n this.logger.warn('setGroupTraits: no group set');\n return;\n }\n const clean = this.traits(traits, 'setGroupTraits');\n this.capture('$group', 'group', undefined, clean);\n });\n }\n\n setProperty(key: string, value: Properties[string]): void {\n this.guard(() => {\n if (isReserved(key, 'setProperty', this.logger)) return;\n this.setUserProp(key, value, '$set');\n });\n }\n\n /** The shared tail of setProperty / setOnceProperty: remember it locally, emit the operator. */\n private setUserProp(key: string, value: Properties[string], op: '$set' | '$set_once'): void {\n this.identity.setUserProp(key, value);\n const traits = sanitizeProperties({ [key]: value }, this.logger);\n this.capture('$identify', 'identify', undefined, traits, sanitizedTraitOp(op, traits));\n }\n\n /**\n * Sets a property only if this device has not already set it.\n *\n * The local check is the cross-SDK contract (`spec/conformance/fixtures/\n * user_props_set_setonce_unset.json` asserts that a repeat call emits nothing), so it\n * stays. It is an optimisation, not the guarantee: a client can only see THIS device, and\n * a returning visitor on a second browser looks like a first write. `$set_once` closes\n * that, because the collector evaluates it against the stored identity.\n */\n setOnceProperty(key: string, value: Properties[string]): void {\n this.guard(() => {\n if (isReserved(key, 'setOnceProperty', this.logger)) return;\n if (this.identity.hasUserProp(key)) {\n this.logger.debug(`setOnceProperty: \"${key}\" already set`);\n return;\n }\n this.setUserProp(key, value, '$set_once');\n });\n }\n\n unsetProperty(key: string): void {\n this.guard(() => {\n if (isReserved(key, 'unsetProperty', this.logger)) return;\n this.identity.unsetUserProp(key);\n this.capture(\n '$identify',\n 'identify',\n undefined,\n { [key]: null },\n normalizeUserPropertyOps({ $unset: [key] }, this.logger)\n );\n });\n }\n\n /**\n * Applies user-property operators server-side (API_SPEC §14).\n *\n * The whole closed operator set in one call — `$set`, `$set_once`, `$add`, `$append`,\n * `$prepend`, `$pre_insert`, `$post_insert`, `$remove`, `$unset`, `$clear_all` — rather\n * than ten methods, because the set is fixed by the schema and a typed map keeps the\n * public surface proportional to what it buys.\n *\n * `$add` is the reason this exists at all: incrementing on the client is a\n * read-modify-write race between tabs, and no amount of care on one device fixes it.\n *\n * Unlike the three convenience methods above, this sends NO `context.traits`. Those carry\n * traits for compatibility with consumers that read them today; a caller reaching for the\n * operators directly is asking for the server-applied semantics, and duplicating an\n * `$append` into a trait would misreport it as an overwrite.\n *\n * Silently does nothing when nothing survives validation — a key claimed twice, a\n * non-finite `$add`, an empty map — since the schema forbids an empty operator object.\n */\n /**\n * Registers properties attached to every later event, surviving a reload.\n *\n * A property passed directly to `track()` wins over a registered one with the same key.\n * `$`-prefixed keys are rejected, as everywhere else. Cleared by `reset()`.\n */\n register(properties: Properties): void {\n this.guard(() => this.superProperties.register(properties));\n }\n\n /**\n * Registers only keys that are not registered yet — for first-touch values like the plan a user\n * signed up on, which a later state change must not overwrite.\n */\n registerOnce(properties: Properties): void {\n this.guard(() => this.superProperties.registerOnce(properties));\n }\n\n unregister(key: string): void {\n this.guard(() => this.superProperties.unregister(key));\n }\n\n setUserProperties(ops: UserPropertyOps): void {\n this.guard(() => {\n const normalized = normalizeUserPropertyOps(ops, this.logger);\n if (!normalized) return;\n this.capture('$identify', 'identify', undefined, undefined, normalized);\n });\n }\n\n optIn(): void {\n this.guard(() => {\n this.consent.optIn();\n this.logger.debug('consent granted');\n this.primeDeviceSignals();\n void this.flushUploads();\n });\n }\n\n optOut(): void {\n this.guard(() => {\n // Discarded, not flushed: never send an event at the moment the visitor opts out.\n this.pageLife.discardPending();\n this.consent.optOut();\n this.queue.clear();\n this.logger.debug('consent denied; queue cleared');\n });\n }\n\n async flush(): Promise<void> {\n try {\n if (!this.consent.canUpload()) {\n this.logger.debug('flush skipped: consent not granted');\n return;\n }\n await this.flushUploads(); // persists, then gates on IndexedDB hydration\n } catch (err) {\n this.logger.error('flush error', err);\n }\n }\n\n /**\n * Autocapture engine entry point ($autocapture events). Not part of the public API —\n * the lazily-loaded engine calls this through its `emit` hook.\n *\n * Named rather than inlined into startAutocapture() so the conformance runner can drive\n * it by reflection, exactly as Android's `autocapture()` and iOS's `autocapture(_:)`\n * already allow. Without a named entry point the whole subsystem is unreachable from a\n * shared fixture, which is why it had none.\n */\n autocapture(properties: Properties): void {\n this.guard(() => this.capture('$autocapture', 'autocapture', properties));\n }\n\n /** Conformance/testing: await any in-flight upload (incl. retries) without forcing one. */\n drainInFlight(): Promise<void> {\n return this.uploader.pending();\n }\n\n getAnonymousId(): string {\n return this.identity.anonymousId;\n }\n\n getSessionId(): string {\n return this.session.peek();\n }\n\n /**\n * Adopts an externally supplied session id, so a session can span a web→app handoff or\n * two contexts that do not share storage. Must be a UUIDv7; anything else is a debug-warn\n * no-op rather than a corrupted session. Emits no `$session_start` (API_SPEC §5).\n */\n setSessionId(sessionId: string, startedAt?: number): void {\n this.guard(() => {\n if (typeof sessionId !== 'string' || !this.session.adopt(sessionId, startedAt)) {\n this.logger.warn(`setSessionId: expected a UUIDv7; ignored \"${String(sessionId)}\"`);\n }\n });\n }\n\n /** Stops timers/listeners. Queued events stay persisted. */\n shutdown(): void {\n // Before the teardown and the write below, so a view waiting for its title is kept.\n this.guard(() => this.pageLife.flushPending());\n this.stopped = true;\n this.lifecycle?.stop();\n for (const fn of this.teardownFns.splice(0)) fn();\n // Nothing will run the deferred writes once the timers are gone.\n this.persistNow();\n this.queue.close();\n }\n\n /**\n * Forces the write-behind queue and session state to storage now.\n *\n * Persistence is deferred to an idle callback so a captured event does not pay a\n * blocking `localStorage` write on the interaction that produced it. This is the escape\n * hatch for the moments where there may be no later tick: page teardown and shutdown.\n */\n private persistNow(): void {\n try {\n this.queue.persistNow();\n this.session.persistNow();\n } catch {\n /* storage unavailable — events stay in memory, nothing else to do */\n }\n }\n\n /**\n * Device signals (fingerprint, Client Hints, position) may be read and sent: not COPPA mode,\n * and consent granted — `canUpload()` is false while pending, after opt-out and under DNT.\n * The ONE gate for both the reads below and the emission in `contextOptions()` (#87).\n */\n private deviceSignals(): boolean {\n return !this.config.childSafeMode && this.consent.canUpload();\n }\n\n /**\n * Starts the once-per-document device-signal reads (high-entropy Client Hints, and the\n * geolocation permission query + position), off the capture path — only when their results\n * could be sent. Under pending or denied consent, or DNT, nothing is read; `optIn()` calls\n * this again. Defaults are unchanged: this only skips reads whose results would be discarded.\n * The geolocation gate is re-checked before every later read (permission change, stale-fix\n * refresh), so `optOut()` stops those too.\n */\n private primeDeviceSignals(): void {\n if (!this.deviceSignals()) return;\n if (this.config.deviceFingerprinting) primeClientHints();\n // One permission query per document, and a position read only from an already-granted\n // state (never a prompt).\n if (this.config.geolocation) primeGeolocation(() => this.deviceSignals());\n }\n\n /** Queues an event and re-arms the teardown drain — see {@link BrowserLifecycle.rearm}. */\n private enqueueEvent(event: DepsmithSdkEvent): void {\n scrubEventUrls(event, this.config.scrubUrls);\n this.queue.enqueue(event);\n this.lifecycle?.rearm();\n }\n\n /**\n * The single entry point for starting an upload.\n *\n * Persistence is NOT forced here. API_SPEC §1 step 4 (durable storage before any network\n * attempt) is upheld inside the uploader's drain loop, which persists per batch it is\n * about to send. Forcing it here instead meant a synchronous write on every capture once\n * the queue sat at or above `batchSize` — which is the regression this whole change\n * exists to remove, reappearing in the exact case that matters most (a backed-up queue).\n */\n private flushUploads(): Promise<void> {\n return this.ready.then(() => this.uploader.flush());\n }\n\n /** Starts an upload when there is something to send and consent allows it. */\n private flushIfQueued(): void {\n if (this.queue.size > 0 && this.consent.canUpload()) void this.flushUploads();\n }\n\n // ── Pipeline ──────────────────────────────────────────────────────────────────\n\n /**\n * Fingerprinting is on by default (opt-out via `deviceFingerprinting: false`) and\n * privacy-gated: it requires granted consent (consent.current is 'denied' under DNT and\n * never 'granted' while pending) and non-COPPA mode.\n */\n private contextOptions(): ContextOptions {\n let overrides: Partial<EventContext> | undefined;\n try {\n overrides = this.contextProvider?.();\n } catch {\n // a throwing host provider must not break capture\n }\n const signals = this.deviceSignals();\n return {\n fingerprint: this.config.deviceFingerprinting && signals,\n // Position is gated identically: a precise coordinate is at least as identifying as\n // a device fingerprint, so DNT, COPPA and ungranted consent all suppress it.\n geolocation: this.config.geolocation && signals,\n overrides,\n // Subtractive only: this narrows what the two gates above already allowed, it never\n // re-enables anything they suppressed (API_SPEC §12.2).\n tracking: this.config.trackingOptions,\n // Not gated on fingerprinting: campaign and referrer come from the landing URL and\n // document.referrer, which are not device signals. Consent still applies, because the\n // whole event is held back upstream when consent is pending.\n attribution: this.attribution,\n page: this.pageLife.tracking(),\n };\n }\n\n /**\n * Session-sticky sampling.\n *\n * The decision is derived from (apiKey, session_id) rather than drawn at random, so it\n * is stable for the session's whole lifetime and identical across tabs sharing that\n * session. A random draw per event would split sessions in half, which is worse than\n * useless: a funnel built from partial sessions is wrong rather than merely noisy.\n *\n * Salted with the apiKey so a future, independently-configured sampler at the same rate\n * does not select the identical set of sessions.\n *\n * Identity events are NEVER sampled. Dropping $identify for 90% of users would stop\n * their user properties applying at all — that is not less data, it is wrong data.\n * Everything else follows the session: a session is wholly in or wholly out. Scale\n * sampled metrics by 1/sampleRate.\n */\n private sessionInSample(sessionId: string): boolean {\n if (this.config.sampleRate >= 1) return true;\n return bucket(`${this.config.apiKey}:${sessionId}`) < this.config.sampleRate;\n }\n\n /** Identity events are exempt; everything else follows its session. */\n private inSample(sessionId: string, type: EventType): boolean {\n if (type === 'identify' || type === 'alias' || type === 'group') return true;\n return this.sessionInSample(sessionId);\n }\n\n private capture(\n name: string,\n type: EventType,\n properties?: Properties,\n traits?: Properties,\n userProperties?: UserPropertyOps,\n // A deferred `$page_view` (see PageLifecycle.autoPageView): stamped at its navigation, with\n // that page's `context.page`, however late it is sent.\n at?: number,\n page?: EventContext['page']\n ): void {\n if (!this.consent.canCapture()) {\n this.logger.debug(`capture dropped (consent denied): ${name}`);\n return;\n }\n\n // Sampling is evaluated AFTER the touch so a mid-page rotation is re-diced, and BEFORE\n // anything is enqueued so out-of-sample events never consume queue or storage — the\n // whole point of sampling at capture rather than at upload.\n const touch = this.touchSession();\n\n if (!this.inSample(touch.sessionId, type)) {\n this.logger.debug(`capture dropped (out of sample): ${name}`);\n return;\n }\n\n const now = at ?? this.clock.now();\n // Read once. It was being computed twice by the ternary below, and the device id needs\n // the same answer the context block got — two reads could straddle a consent change and\n // put a device_id on an event whose context was built without the fingerprint.\n const contextOptions = this.contextOptions();\n if (page) contextOptions.page = page;\n const event: DepsmithSdkEvent = {\n event_id: uuidv7(now),\n event: name,\n event_type: type,\n timestamp: isoTimestamp(now),\n session_id: touch.sessionId,\n session_started_at: isoTimestamp(touch.startedAt),\n anonymous_id: this.identity.anonymousId,\n context: traits\n ? { ...buildContext(contextOptions), traits }\n : buildContext(contextOptions),\n platform: 'web',\n sdk_version: SDK_VERSION,\n };\n\n // §14 operators are described here and applied by the collector; the schema forbids an\n // empty map (`minProperties: 1`), so an op set that fully normalises away is omitted.\n if (userProperties) event.user_properties = userProperties;\n\n // Precedence, widest to narrowest: static config, then runtime registrations, then the call\n // site. A property passed to track() must win over a registered one — the call is the more\n // specific statement, and the reverse would make a per-event override impossible to express.\n //\n // The MERGED set is sanitised, not just the call site's. `defaultProperties` and registered\n // values come from the integrator too, and they ride on every event: one nested object or\n // BigInt there made the collector reject every batch (or threw before the enqueue), losing\n // all analytics until someone unregistered it — and a registered value is persisted, so a\n // reload did not help. Sanitising here also covers a value already sitting in storage, and\n // applies the 200-key cap to what is actually sent.\n const props = sanitizeProperties(\n {\n ...this.config.defaultProperties,\n ...this.superProperties.current(),\n ...sanitizeProperties(properties, this.logger),\n },\n this.logger\n );\n if (Object.keys(props).length > 0) event.properties = props;\n\n const userId = this.identity.userId;\n if (userId) event.user_id = userId;\n const groupId = this.identity.groupId;\n if (groupId) event.group_id = groupId;\n // Memoised per document (the canvas render is the only costly part), so this is a map\n // lookup after the first event.\n if (contextOptions.fingerprint) event.device_id = computeVisitorId();\n\n this.enqueueEvent(event);\n this.logger.debug(`captured ${name}`, event);\n\n if (this.queue.size >= this.config.batchSize && this.consent.canUpload()) {\n void this.flushUploads();\n }\n }\n\n /**\n * Config drift (guidelines §12): events queued under a different apiKey belong to\n * another project — drop them rather than misattribute. Fingerprint, not raw key.\n * The upload pause goes too: a 401 or Retry-After for that key says nothing about this one.\n */\n private detectConfigDrift(fingerprint: string): boolean {\n const stored = this.storage.get(KEY_CONFIG_FP);\n const drifted = stored !== null && stored !== fingerprint;\n if (drifted) {\n this.logger.warn('apiKey changed since last run; dropping queued events for the old project');\n this.queue.clear();\n this.storage.remove(KEY_NET_BREAKER);\n }\n this.storage.set(KEY_CONFIG_FP, fingerprint);\n return drifted;\n }\n\n /** The synchronous store. IndexedDB is never returned here — see the constructor. */\n private pickStorage(): KVStorage {\n return this.config.storage === 'memory' ? new MemoryAdapter() : defaultStorage();\n }\n\n private enqueueSessionEnd(ended: {\n id: string;\n lastActivityAt: number;\n startedAt: number;\n }): void {\n this.enqueueSessionBoundary('end', ended.id, ended.lastActivityAt, ended.startedAt);\n }\n\n /**\n * Announces a session the SDK just observed beginning.\n *\n * Not emitted by reset()/rotate() (an explicit user action, not an observed boundary)\n * nor by peek()'s mint-if-absent branch (analytics from a getter).\n */\n private enqueueSessionStart(started: { id: string; startedAt: number }): void {\n // Stamped at the session's start, not \"now\" — they are the same instant on the\n // capture path, but the resume path can observe a rotation slightly later.\n this.enqueueSessionBoundary('start', started.id, started.startedAt, started.startedAt);\n }\n\n /**\n * `$session_start` / `$session_end`, built in one place: the two envelopes differ only in\n * their name, their timestamp and the fingerprint components the opening one carries.\n */\n private enqueueSessionBoundary(\n kind: 'start' | 'end',\n id: string,\n at: number,\n startedAt: number\n ): void {\n // Checked here rather than at the call sites for the same reason the consent gate is:\n // the visibilitychange resume path reaches this without going through capture(), so a\n // gate placed at the call sites would be one `if` short of covering the feature.\n if (this.config.sessionEvents === 'derive') return;\n // Same gate capture() applies. This path is also reachable from the\n // visibilitychange handler, which does not go through capture() — without the\n // check, a denied visitor's anonymous_id was persisted to the queue on tab\n // resume, and would upload if consent later flipped to granted. Under `pending`\n // consent canCapture() is true, so it is queued and held — matching capture() exactly.\n if (!this.consent.canCapture()) {\n this.logger.debug(`session_${kind} dropped (consent denied)`);\n return;\n }\n const contextOptions = this.contextOptions();\n const event: DepsmithSdkEvent = {\n event_id: uuidv7(this.clock.now()),\n event: `$session_${kind}`,\n event_type: `session_${kind}`,\n timestamp: isoTimestamp(at),\n session_id: id,\n session_started_at: isoTimestamp(startedAt),\n anonymous_id: this.identity.anonymousId,\n context: buildContext(contextOptions),\n platform: 'web',\n sdk_version: SDK_VERSION,\n };\n const userId = this.identity.userId;\n if (userId) event.user_id = userId;\n if (contextOptions.fingerprint) {\n event.device_id = computeVisitorId();\n // Fingerprint components ride the session-opening event and nothing else.\n //\n // The device id is a single opaque hash, so it cannot be matched approximately: one\n // signal drifting produces a completely different id, and a returning visitor who\n // cleared both stores is unrecoverable. Sending the parts lets the collector do N-of-M\n // matching and recover them instead. They cost a few hundred bytes and cannot change\n // within a session, so per-event transmission would be pure waste — the hash alone\n // stays on every event.\n //\n // Gated on the same `fingerprint` flag as device_id, so deviceFingerprinting,\n // childSafeMode, DNT and ungranted consent all suppress it identically. Note this means\n // `sessionEvents: 'derive'` transmits no components at all: that mode exists to stop\n // paying for boundary rows, and smuggling the payload onto an ordinary event would both\n // contradict that and pollute a caller's own event properties.\n if (kind === 'start') event.properties = fingerprintComponents();\n }\n this.enqueueEvent(event);\n }\n\n // ── Lifecycle ─────────────────────────────────────────────────────────────────\n\n /**\n * Stamps session activity and emits the boundary events that revealed. The one place a\n * session is touched, for capture() and for the tab-resume path alike: the resume path used\n * to emit both boundaries with no sample check, so at `sampleRate: 0.1` nine in ten resumed\n * sessions reached the warehouse as a bare `$session_start` with nothing after it.\n *\n * Order is load-bearing (API_SPEC §5): the old session's end precedes the new session's\n * start, and both precede the event that triggered the rotation.\n *\n * Each boundary follows ITS OWN session's sample decision, not the current event's: the\n * ending and starting sessions have different ids and can therefore decide differently, and\n * an exempt $identify must not drag a boundary event into an out-of-sample session.\n */\n private touchSession(): SessionTouch {\n const touch = this.session.touch();\n // Ahead of the sampling gates, because `counter` is \"pages this session\" whether or not\n // this session's boundary events are sampled in.\n if (touch.startedSession) this.pageLife.newSession();\n if (touch.endedSession && this.sessionInSample(touch.endedSession.id)) {\n this.enqueueSessionEnd(touch.endedSession);\n }\n if (touch.startedSession && this.sessionInSample(touch.startedSession.id)) {\n this.enqueueSessionStart(touch.startedSession);\n }\n return touch;\n }\n\n /**\n * `visibilitychange`→visible: run the session-timeout check.\n *\n * Not at all while capture is denied. capture() returns before touching the session in that\n * state; this path did not, so every refocus by an opted-out or DNT visitor wrote a session id\n * and an activity timestamp to storage.\n */\n private resumeSession(): void {\n if (this.consent.canCapture()) this.touchSession();\n }\n\n /** Lazily loads the autocapture engine so the core bundle stays <10KB gz. */\n private startAutocapture(): void {\n const autocaptureConfig = this.config.autocapture;\n if (!autocaptureConfig || typeof window === 'undefined') return;\n // Started here rather than in the lazy chunk: these are PerformanceObservers with\n // `buffered: true`, and the entries they replay — FCP, LCP — happen before a dynamic import\n // could possibly resolve. Registering late would miss the paints this exists to measure.\n if (typeof PerformanceObserver !== 'undefined') {\n this.vitals = observeVitals();\n this.teardownFns.push(() => this.vitals?.stop());\n }\n // Patches `fetch`, so it is kept here beside the observers rather than in the lazy chunk: a\n // request that fails during startup is exactly the kind worth knowing about, and a dynamic\n // import would miss it.\n const network = observeNetworkErrors(this.config, (properties) =>\n this.guard(() => this.capture('$network_request', 'track', properties))\n );\n this.teardownFns.push(() => network.stop());\n void loadAutocapture()\n .then((module) => {\n if (!module) return; // build has autocapture compiled out (Shopify pixel)\n // shutdown() ran while the chunk was loading: its teardown list is already spent, so an\n // engine started now would keep its listeners and History patch for the life of the page.\n if (this.stopped) return;\n this.teardownFns.push(\n module.startAutocapture(autocaptureConfig, {\n // Same entry point the conformance fixtures drive, so the shared fixtures\n // exercise the real path rather than a parallel one.\n emit: (properties) => this.autocapture(properties),\n page: (watchTitle) => this.guard(() => this.pageLife.autoPageView(watchTitle)),\n pageLeave: (maxScroll) => this.guard(() => this.pageLife.leave(maxScroll)),\n warn: (message) => this.logger.warn(message),\n armUnloadLeave: (leave) => {\n this.leaveOnUnload = leave;\n },\n })\n );\n this.teardownFns.push(() => {\n this.leaveOnUnload = undefined;\n });\n })\n .catch((err) => this.logger.debug('autocapture load failed', err));\n }\n\n private guard(fn: () => void): void {\n try {\n fn();\n } catch (err) {\n this.logger.error('internal error', err);\n }\n }\n}\n\nexport { LIBRARY_NAME, SDK_VERSION };\n","import { DepsmithSdkClient, type InternalOverrides } from './depsmith-sdk';\nimport type { DepsmithSdkConfig } from './config';\nimport type { PageOptions, Properties } from './types';\nimport type { UserPropertyOps } from './user-properties';\n\nexport { DepsmithSdkClient } from './depsmith-sdk';\nexport type { InternalOverrides } from './depsmith-sdk';\nexport type { DepsmithSdkConfig, AutocaptureConfig, PageNames, PageLocation } from './config';\nexport type { TrackingOptions } from './tracking-options';\nexport type { UserPropertyOps } from './user-properties';\nexport type {\n DepsmithSdkEvent,\n BatchPayload,\n EventContext,\n EventType,\n PageOptions,\n Properties,\n PropertyValue,\n ConsentState,\n} from './types';\nexport type { KVStorage, AsyncKV } from './queue/storage';\nexport { AsyncMirrorAdapter, DEPSMITH_SDK_STORAGE_KEYS } from './queue/storage';\nexport type { Scheduler } from './utils/scheduler';\nexport { idleScheduler, syncScheduler } from './utils/scheduler';\n\nlet client: DepsmithSdkClient | null = null;\nlet initApiKey: string | null = null;\n\n/**\n * Default singleton facade:\n *\n * import { DepsmithSdk } from '@depsmith/depsmith-sdk';\n * DepsmithSdk.init({ apiKey: '...', endpoint: 'https://collector.example.com' });\n * DepsmithSdk.track('button_clicked', { color: 'red' });\n *\n * Re-init with the same apiKey is a no-op; a different apiKey replaces the client (API_SPEC §2).\n * Without a `window` (server rendering) init() does nothing and returns null — see below.\n */\nexport const DepsmithSdk = {\n init(config: DepsmithSdkConfig, overrides?: InternalOverrides): DepsmithSdkClient | null {\n try {\n if (client && initApiKey === config.apiKey) {\n return client;\n }\n // No window: this module is being evaluated on a server (Next.js, Remix, a prerender).\n // A singleton there is one client for every request — one anonymous_id, and after an\n // identify() during a render, one user_id — queueing in server memory and uploading\n // with no page behind it. So init() declines, and every facade method stays the no-op\n // it is before init. Two ways to say \"I mean it\": `storage: 'memory'`, the documented\n // SSR/test backend, or an injected store (the Shopify pixel, the conformance runner).\n if (typeof window === 'undefined' && config.storage !== 'memory' && !overrides?.storage) {\n if (config.debug) console.warn('[depsmith-sdk] init skipped: no window');\n return null;\n }\n client?.shutdown();\n client = new DepsmithSdkClient(config, overrides);\n initApiKey = config.apiKey;\n return client;\n } catch (err) {\n if (config?.debug) console.error('[depsmith-sdk] init failed:', err);\n return null;\n }\n },\n\n track: (name: string, properties?: Properties): void => client?.track(name, properties),\n page: (name?: string, properties?: Properties, options?: PageOptions): void =>\n client?.page(name, properties, options),\n screen: (name?: string, properties?: Properties, options?: PageOptions): void =>\n client?.screen(name, properties, options),\n identify: (userId: string, traits?: Properties): void => client?.identify(userId, traits),\n alias: (aliasId: string): void => client?.alias(aliasId),\n reset: (): void => client?.reset(),\n group: (groupId: string, traits?: Properties): void => client?.group(groupId, traits),\n setGroupTraits: (traits: Properties): void => client?.setGroupTraits(traits),\n setProperty: (key: string, value: Properties[string]): void => client?.setProperty(key, value),\n setOnceProperty: (key: string, value: Properties[string]): void =>\n client?.setOnceProperty(key, value),\n unsetProperty: (key: string): void => client?.unsetProperty(key),\n /** Applies the §14 operator set server-side: $set, $add, $append, $unset, $clear_all, … */\n setUserProperties: (ops: UserPropertyOps): void => client?.setUserProperties(ops),\n /** Properties attached to every later event. A direct track() property wins over these. */\n register: (properties: Properties): void => client?.register(properties),\n /** Only keys not registered yet — first-touch values a later state must not overwrite. */\n registerOnce: (properties: Properties): void => client?.registerOnce(properties),\n unregister: (key: string): void => client?.unregister(key),\n optIn: (): void => client?.optIn(),\n optOut: (): void => client?.optOut(),\n flush: (): Promise<void> => client?.flush() ?? Promise.resolve(),\n getAnonymousId: (): string | undefined => client?.getAnonymousId(),\n getSessionId: (): string | undefined => client?.getSessionId(),\n setSessionId: (sessionId: string, startedAt?: number): void =>\n client?.setSessionId(sessionId, startedAt),\n\n /** Testing/teardown: stop timers and forget the singleton. */\n shutdown(): void {\n client?.shutdown();\n client = null;\n initApiKey = null;\n },\n};\n"],"mappings":"AAuBA,IAAMA,GAAuD,CAC3D,CAAC,aAAc,QAAQ,EACvB,CAAC,aAAc,QAAQ,EACvB,CAAC,eAAgB,MAAM,EACvB,CAAC,WAAY,MAAM,EACnB,CAAC,cAAe,SAAS,CAC3B,EAEaC,GAAe,oBACfC,GAAe,oBAoB5B,SAASC,GAAOC,EAAiC,CAC/C,GAAI,CACF,OAAO,IAAI,IAAIA,CAAG,EAAE,MAAQ,MAC9B,MAAQ,CACN,MACF,CACF,CA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OAAQ,CAACF,EAAeC,EAAyBC,IAC/CT,GAAQ,OAAOO,EAAMC,EAAYC,CAAO,EAC1C,SAAU,CAACC,EAAgBC,IAA8BX,GAAQ,SAASU,EAAQC,CAAM,EACxF,MAAQC,GAA0BZ,GAAQ,MAAMY,CAAO,EACvD,MAAO,IAAYZ,GAAQ,MAAM,EACjC,MAAO,CAACa,EAAiBF,IAA8BX,GAAQ,MAAMa,EAASF,CAAM,EACpF,eAAiBA,GAA6BX,GAAQ,eAAeW,CAAM,EAC3E,YAAa,CAACG,EAAaC,IAAoCf,GAAQ,YAAYc,EAAKC,CAAK,EAC7F,gBAAiB,CAACD,EAAaC,IAC7Bf,GAAQ,gBAAgBc,EAAKC,CAAK,EACpC,cAAgBD,GAAsBd,GAAQ,cAAcc,CAAG,EAE/D,kBAAoBE,GAA+BhB,GAAQ,kBAAkBgB,CAAG,EAEhF,SAAWR,GAAiCR,GAAQ,SAASQ,CAAU,EAEvE,aAAeA,GAAiCR,GAAQ,aAAaQ,CAAU,EAC/E,WAAaM,GAAsBd,GAAQ,WAAWc,CAAG,EACzD,MAAO,IAAYd,GAAQ,MAAM,EACjC,OAAQ,IAAYA,GAAQ,OAAO,EACnC,MAAO,IAAqBA,GAAQ,MAAM,GAAK,QAAQ,QAAQ,EAC/D,eAAgB,IAA0BA,GAAQ,eAAe,EACjE,aAAc,IAA0BA,GAAQ,aAAa,EAC7D,aAAc,CAACiB,EAAmBC,IAChClB,GAAQ,aAAaiB,EAAWC,CAAS,EAG3C,UAAiB,CACflB,GAAQ,SAAS,EACjBA,EAAS,KACTC,GAAa,IACf,CACF","names":["UTM_PARAMS","KEY_CAMPAIGN","KEY_REFERRER","hostOf","url","Attribution","storage","key","raw","parsed","value","documentReferrer","params","currentHost","incoming","param","refHost","isExternal","changed","PageTracker","url","documentReferrer","sameOrigin","out","PageLifecycle","sink","config","pageNameRules","name","properties","type","pending","auto","href","AUTO_VIEW_CLAIM_MS","pageViewProperties","watchTitle","key","counter","domainOf","urlBase","view","where","title","maxScroll","leaving","persisted","tracking","pathOf","live","source","location","rules","match","pageType","names","glob","globPattern","path","trimSlash","pattern","star","a","b","u","startLifecycle","host","flushTimer","drained","hideFlush","onPageHide","pendingHide","onVisibility","onPageShow","event","onOnline","loadAutocapture","SUPPRESSIONS","TRACKING_DEFAULTS","option","resolveTrackingOptions","options","resolved","applyTrackingOptions","context","record","key","sub","block","AUTOCAPTURE_DEFAULTS","resolveAutocapture","autocapture","resolved","key","value","clicks","pageviews","resolveConfig","config","autocapture","resolveAutocapture","int","num","resolveTrackingOptions","value","fallback","min","max","djb2","input","hash","i","fnv1aInt","fnv1a","bucket","fingerprintHash","hints","hintsRequested","primeClientHints","uaData","values","parseUserAgent","result","ua","uaData","browser","parseBrowser","os","parseOS","hinted","normalizeOsVersion","hints","deviceType","parseDeviceType","device","parseDevice","osName","platformVersion","raw","major","trimVersion","BROWSER_RULES","rule","match","brand","b","OS_RULES","version","trimmed","cachedVisitorId","cachedComponents","components","collectSignals","computeVisitorId","fingerprintHash","c","fingerprintComponents","out","component","collectSignals","signals","nav","canvasFingerprint","canvas","ctx","fingerprintHash","readNetwork","conn","fix","fixAt","primed","inFlight","permission","allowed","primeGeolocation","gate","permissions","status","requestFix","position","latitude","longitude","accuracy","next","readGeolocation","LIBRARY_NAME","SDK_VERSION","invariants","readInvariants","next","buildContext","opts","context","LIBRARY_NAME","SDK_VERSION","attempt","href","domainOf","urlBase","cached","readInvariants","deviceType","parseUserAgent","campaign","referrer","enrichFingerprint","fix","readGeolocation","key","value","applyTrackingOptions","browser","os","hinted","device","network","readNetwork","fn","dntEnabled","nav","win","KEY_CONSENT","ConsentManager","storage","initialMode","dntActive","persisted","idleScheduler","fn","idle","syncScheduler","KEY_QUEUE","DEFAULT_MAX_CHARS","BRACKETS","IDENTITY_EVENT_TYPES","isIdentityEvent","event","EventQueue","storage","maxSize","logger","options","idleScheduler","raw","parsed","kept","e","events","measure","a","b","dropped","existing","fresh","size","i","index","count","n","maxChars","from","end","total","eventIds","ids","sizes","sizeSum","lastMs","lastSeq","SEQ_MASK","uuidv7","now","bytes","i","seq","hex","uuidv7ToMs","id","ms","DEPSMITH_SDK_STORAGE_KEYS","MemoryAdapter","key","value","CookieAdapter","domain","prefix","part","maxAge","secure","KEY_ANON_RESET","MIRRORED_IDENTITY_KEYS","RedundantAdapter","primary","secondary","mirrored","fromPrimary","fromSecondary","winner","a","b","aMs","uuidv7ToMs","bMs","stores","at","s","live","AsyncMirrorAdapter","backend","keys","LocalStorageAdapter","ls","key","value","IndexedDBAdapter","dbName","resolve","request","tx","keysReq","valuesReq","keys","i","defaultStorage","probe","MemoryAdapter","pickQueueStorage","mode","fallback","hydrateQueue","queueStorage","storage","consent","queue","drifted","logger","persisted","KEY","raw","storedEvents","raw","parsed","e","EventQueue","args","event","KEY_QUEUE","stored","present","gone","id","LocalStorageAdapter","ids","mine","foreign","room","chars","kept","i","size","KEY_ANON","KEY_USER","KEY_GROUP","KEY_PROPS","IdentityManager","storage","clock","id","uuidv7","userId","groupId","key","value","props","now","KEY_ANON_RESET","fresh","KEY_SESSION","SessionManager","storage","clock","timeoutMs","schedule","idleScheduler","stored","pending","raw","parsed","uuidv7ToMs","session","now","fresh","uuidv7","current","id","startedAt","embedded","sanitizeProperties","input","logger","out","count","rawKey","rawValue","value","coerceValue","coerceScalar","t","scalar","items","item","coerced","safeStringify","k","v","stripReserved","input","method","logger","out","hit","key","isReserved","wasAborted","error","signal","name","errorMessage","message","isFailure","status","urlParts","raw","properties","url","contentLength","headers","value","parsed","describeRequest","input","init","request","observeNetworkErrors","config","emit","original","own","stopped","windowStart","seen","admit","key","now","report","outcome","build","patched","args","started","promise","method","response","sizes","requestBytes","responseBytes","ms","value","observeVitals","lcp","fcp","inp","cls","sawLayoutShift","ttfb","observers","observe","type","handler","observer","list","entries","last","entry","duration","navigation","timing","out","KEY_SUPER_PROPERTIES","usableKey","key","logger","isReserved","SuperProperties","storage","stored","parsed","properties","changed","value","TRAIT_OPERATORS","MAX_ADD_KEYS","MAX_UNSET_KEYS","normalizeUserPropertyOps","ops","logger","others","k","out","claimed","claim","key","operator","isReserved","raw","clean","sanitizeProperties","kept","value","count","sanitizedTraitOp","systemClock","isoTimestamp","ms","isRetryable","status","BASE_MS","MAX_BACKOFF_MS","backoffMs","attempt","random","base","retryAfterMs","value","now","seconds","ms","gzip","text","cs","writer","reader","chunks","done","value","total","n","c","out","offset","chunk","compress","mode","sendBeacons","queue","config","deps","uploading","buildPayload","breaker","from","n","batch","payload","event","eventIds","batch","ids","event","REQUEST_TIMEOUT_MS","KEEPALIVE_MAX_BYTES","MAX_BATCH_CHARS","bodyBytes","body","REDIRECTED","refused","status","HOLD_BASE_MS","HOLD_MAX_MS","BatchUploader","queue","config","deps","err","max","isRetryable","breaker","answered","attempt","backoffMs","payload","isoTimestamp","json","controller","timer","headers","zipped","compress","keepalive","init","res","retryAfterMs","configured","sendBeacons","KEY_NET_BREAKER","createNetworkBreaker","storage","clock","loaded","failures","openUntil","cooldown","clamp","v","lo","hi","load","s","KEY_NET_BREAKER","save","ms","Logger","enabled","args","CONTEXT_KEYS","URL_PROPERTIES","scrubUrl","url","keep","bare","q","kept","pair","paramName","name","scrubEventUrls","event","option","params","targets","target","keys","key","value","props","query","KEY_CONFIG_FP","MAX_ENVELOPE_ID_LENGTH","DepsmithSdkClient","config","overrides","resolveConfig","Logger","systemClock","queueStorage","pickQueueStorage","PageLifecycle","name","type","properties","at","page","identityStorage","MemoryAdapter","RedundantAdapter","CookieAdapter","IdentityManager","SessionManager","ConsentManager","dntEnabled","Attribution","SuperProperties","fp","djb2","owned","key","value","EventQueue","drifted","hydrateQueue","BatchUploader","args","ms","r","createNetworkBreaker","startLifecycle","fn","persisted","stripReserved","isReserved","traits","method","sanitizeProperties","label","options","userId","clean","sanitizedTraitOp","aliasId","groupId","op","normalizeUserPropertyOps","ops","normalized","err","sessionId","startedAt","primeClientHints","primeGeolocation","event","scrubEventUrls","signals","bucket","userProperties","touch","now","contextOptions","uuidv7","isoTimestamp","buildContext","SDK_VERSION","props","computeVisitorId","fingerprint","stored","KEY_NET_BREAKER","defaultStorage","ended","started","kind","id","fingerprintComponents","autocaptureConfig","observeVitals","network","observeNetworkErrors","loadAutocapture","module","watchTitle","maxScroll","message","leave","client","initApiKey","DepsmithSdk","config","overrides","DepsmithSdkClient","err","name","properties","options","userId","traits","aliasId","groupId","key","value","ops","sessionId","startedAt"]}
|
|
1
|
+
{"version":3,"sources":["../src/page.ts","../src/attribution.ts","../src/lifecycle.ts","../src/autocapture/load.ts","../src/tracking-options.ts","../src/autocapture/options.ts","../src/config.ts","../src/hash.ts","../src/fingerprint.ts","../src/geolocation.ts","../src/context.ts","../src/consent.ts","../src/utils/scheduler.ts","../src/queue/queue.ts","../src/utils/uuidv7.ts","../src/queue/storage.ts","../src/queue/storage-local.ts","../src/queue/tab-queue.ts","../src/identity.ts","../src/session.ts","../src/props.ts","../src/reserved.ts","../src/network-errors.ts","../src/web-vitals.ts","../src/super-properties.ts","../src/user-properties.ts","../src/utils/clock.ts","../src/transport/retry.ts","../src/transport/gzip.ts","../src/transport/beacon.ts","../src/transport/uploader.ts","../src/transport/breaker.ts","../src/utils/logger.ts","../src/url-scrub.ts","../src/depsmith-sdk.ts","../src/index.ts"],"sourcesContent":["/**\n * Per-visit page context: where the visitor was before this page, and how many pages in they are.\n *\n * Why this cannot just read `document.referrer`: the browser sets it once per document load and\n * never updates it for History API navigation. In a single-page app it therefore keeps pointing at\n * the original landing referrer for the rest of the visit, so \"where did users come from before\n * checkout?\" answers with the acquisition source instead of the previous route. The SDK has to\n * track it itself. `context.page.referrer` keeps the raw `document.referrer` for continuity.\n *\n * Session-scoped, not visitor-scoped: `counter` is \"pages seen this session\", so it must reset\n * when the session does. Held in memory rather than storage — a session cannot span a cold start\n * without also rotating, and a per-page storage write on the capture path is exactly the cost the\n * write-behind queue exists to avoid.\n */\n\nimport type { PageLocation, PageNames, ResolvedConfig } from './config';\nimport type { EventContext, Properties } from './types';\n\nexport type PreviousPageType = 'direct' | 'internal' | 'external';\n\nexport interface PageTracking {\n /**\n * Set only for `$page_leave`, which must describe the page being LEFT. By the time a History\n * navigation notifies the SDK, `window.location` is already the next URL, so these override\n * the derived values for that one event.\n */\n url?: string;\n path?: string;\n domain?: string;\n url_base?: string;\n previous_url?: string;\n previous_type?: PreviousPageType;\n counter?: number;\n}\n\nexport class PageTracker {\n private previousUrl?: string;\n private previousType?: PreviousPageType;\n private counter = 0;\n private currentUrl?: string;\n\n /**\n * Record arriving at `url`. Call once on init and once per History navigation.\n *\n * Returns true when this was a genuine new page, false when it was the same URL again — a\n * History `replaceState` to the identical URL, or a double-fired listener. The caller uses\n * that to avoid emitting two `$page_view`s for one page, which is the acceptance criterion\n * the spec states explicitly.\n */\n recordPage(url: string, documentReferrer: string): boolean {\n if (url === this.currentUrl) return false;\n\n if (this.currentUrl === undefined) {\n // First page of the session. The only honest source for \"what came before\" is\n // document.referrer, which at this point is correct.\n if (!documentReferrer) {\n this.previousType = 'direct';\n } else {\n this.previousUrl = documentReferrer;\n this.previousType = sameOrigin(documentReferrer, url) ? 'internal' : 'external';\n }\n } else {\n // Subsequent pages: we know exactly where they came from, because we were there.\n this.previousUrl = this.currentUrl;\n this.previousType = sameOrigin(this.currentUrl, url) ? 'internal' : 'external';\n }\n\n this.currentUrl = url;\n this.counter += 1;\n return true;\n }\n\n /** Fields for `context.page`. Empty before the first `recordPage`. */\n tracking(): PageTracking {\n const out: PageTracking = {};\n if (this.previousUrl !== undefined) out.previous_url = this.previousUrl;\n if (this.previousType !== undefined) out.previous_type = this.previousType;\n if (this.counter > 0) out.counter = this.counter;\n return out;\n }\n\n /** Pages seen so far this session; 0 before the first page. */\n get pageCount(): number {\n return this.counter;\n }\n\n /** The URL currently being viewed, for `$page_leave` to describe the page being left. */\n get current(): string | undefined {\n return this.currentUrl;\n }\n\n /** Session rotation resets the count — `counter` is defined as pages *this session*. */\n resetForNewSession(): void {\n this.counter = this.currentUrl === undefined ? 0 : 1;\n }\n}\n\n/** What {@link PageLifecycle} needs from the client: a clock and the capture pipeline. */\nexport interface PageEventSink {\n now(): number;\n /**\n * Goes through the client's full capture path — consent, sampling, session, queue.\n *\n * `at` and `page` are for a deferred `$page_view`: the event's timestamp is the navigation, and\n * its `context.page` the page navigated to, however late it is sent.\n */\n capture(\n name: string,\n type: 'page_view' | 'page_leave',\n properties: Properties,\n at?: number,\n page?: EventContext['page']\n ): void;\n}\n\n/**\n * Starts watching for the new route's `<title>`; calls `done` once, when it changes or a timeout\n * passes. Returns a canceller. Supplied by autocapture, which owns everything that observes the\n * DOM.\n */\nexport type TitleWatch = (titleAtNav: string, done: () => void) => () => void;\n\n/** An automatic `$page_view` recorded at navigation and waiting for the new title. */\ninterface PendingView {\n at: number;\n counter: number;\n location: PageLocation;\n /** `context.page` at navigation, title excepted: that is what is being waited for. */\n page: NonNullable<EventContext['page']>;\n cancel: () => void;\n}\n\n/**\n * The `$page_view` / `$page_leave` engine, and the state `context.page` reports.\n *\n * Lives here rather than on the client so the Shopify custom-pixel build can swap the whole\n * module for `page.noop.ts`. That build is deliberately unminified — see tsup.config.ts — so\n * anything it cannot use is still shipped, against an editor that refuses to save a file over\n * 64,000 characters. None of this is reachable there: the pixel sandbox's `window.location` is\n * the sandbox, and host context overrides replace `context.page` wholesale.\n */\nexport class PageLifecycle {\n private pages = new PageTracker();\n /** Clock ms when the current page view began, for $page_leave's duration. */\n private enteredAt = 0;\n /**\n * Set once the current view's $page_leave has been sent, so no second path can send another:\n * cleared when a new page is recorded and on a back/forward-cache restore.\n */\n private left = false;\n /** Set only while capturing $page_leave — the URL of the page being left. */\n private leaving?: string;\n /** Page key of the last emitted $page_view, so one page cannot produce two. */\n private lastViewed?: string;\n /** The SPA view waiting for its route's title, if any. Never sent twice. */\n private pending?: PendingView;\n /** URL and clock of an automatic view already SENT that no `page()` call has followed. */\n private autoViewed?: { url: string; at: number };\n\n /** `pageNames`, compiled once. */\n private rules?: PageNameRules;\n\n /**\n * Under `autocapture.pageviews: 'all'` a page is the whole URL. Otherwise it is the path, the\n * same key autocapture's navigation observer compares — so a `?sort=` change is neither a\n * navigation there nor a new page here.\n */\n private byHref: boolean;\n\n /** Takes the resolved config whole, so the pixel build's call site stays one argument short. */\n constructor(\n private sink: PageEventSink,\n config: Pick<ResolvedConfig, 'pageNames' | 'autocapture'> = { autocapture: false }\n ) {\n this.rules = pageNameRules(config.pageNames);\n this.byHref = !!config.autocapture && config.autocapture.pageviews === 'all';\n }\n\n /**\n * Seed navigation state at init, before anything can capture, so the first event already\n * carries `previous_url` / `counter` — often a `$session_start` ahead of any pageview.\n */\n start(url: string, documentReferrer: string): void {\n this.pages.recordPage(url, documentReferrer);\n this.enteredAt = this.sink.now();\n }\n\n get pageCount(): number {\n return this.pages.pageCount;\n }\n\n /**\n * Advances state for an explicit host `page()` call, and claims the page so autocapture does\n * not emit a second view for it. An app that drives pageviews by hand AND enables autocapture\n * would otherwise double count every page.\n */\n recordExplicit(): void {\n this.record();\n this.lastViewed = this.pageKey();\n this.autoViewed = undefined;\n }\n\n /**\n * A `page()` / `screen()` call. SDK keys after the client's, so they always describe this\n * view; a client `name` is left alone, since the SDK writes `$page_name`, never `name`.\n *\n * One page, one view — whichever of autocapture and the host gets there first:\n *\n * - **The call comes first** (same tick as `init()`, before the lazy chunk): it claims the\n * page and autocapture's view for it is skipped. That much always worked.\n * - **Autocapture's view is still waiting for its title**: the call REPLACES it. This is every\n * router hook — `pushState` runs before the after-navigation hook, so the automatic view was\n * already recorded, and flushing it ahead of the call (as this used to) sent two views per\n * route change. The host's view wins because it carries the host's name and properties.\n * - **Autocapture's view was already sent** for this exact URL (the landing page once the\n * chunk has loaded, or a route whose title arrived before the hook ran): the call is the\n * duplicate, and is dropped. Once, and only within {@link AUTO_VIEW_CLAIM_MS} of that view —\n * a second call for the same URL, or one long after it, is the host asking for another view\n * (a wizard step, a modal) and is sent, as is any call after the URL changes.\n *\n * Without autocapture page views none of this applies and every call is a view.\n */\n manual(name?: string, properties?: Properties, type?: string): void {\n const pending = this.pending;\n if (pending && this.keyOf(pending.location) === this.pageKey()) {\n this.discardPending();\n } else {\n // A pending view for some other page goes first: it was the earlier navigation.\n this.flushPending();\n const auto = this.autoViewed;\n this.autoViewed = undefined;\n if (auto && auto.url === href() && this.sink.now() - auto.at <= AUTO_VIEW_CLAIM_MS) return;\n }\n this.recordExplicit();\n this.sink.capture('$page_view', 'page_view', {\n ...properties,\n ...pageViewProperties({ source: 'manual', name, type }, this.rules),\n $page_counter: this.pages.pageCount,\n });\n }\n\n /**\n * Autocapture's pageview path: at most one `$page_view` per page (see {@link pageKey}).\n *\n * Deduped on what was EMITTED, not on what the tracker advanced — `start()` already fed the\n * landing URL to the tracker, so dedupeing on that would read the seed as \"already viewed\"\n * and swallow the landing pageview entirely.\n *\n * With `watchTitle` (an SPA navigation) the view is DEFERRED. Routers call `pushState` first\n * and set `document.title` only once the new route has rendered, so a view sent in the same\n * tick carried the previous page's title in `$page_name` and `context.page.title` next to the\n * new page's URL. Everything else is decided now — the dedupe, the counter, the timestamp and\n * `context.page` — and only the title waits, for its change or a timeout. Without `watchTitle`\n * (the landing page, whose title is set at load) it is sent at once.\n */\n autoPageView(watchTitle?: TitleWatch): void {\n // FIRST: a still-pending view belongs to the page before this one.\n this.flushPending();\n this.record();\n const key = this.pageKey();\n if (key !== undefined && key === this.lastViewed) return;\n this.lastViewed = key;\n const counter = this.pages.pageCount;\n if (!watchTitle) {\n this.emitView(location, counter);\n return;\n }\n const url = location.href;\n const pending: PendingView = {\n at: this.sink.now(),\n counter,\n // Parsed from the string, not `location` itself: that is live, and the flush may come\n // after the next navigation.\n location: new URL(url),\n page: {\n url,\n path: location.pathname,\n referrer: document.referrer,\n domain: domainOf(url),\n url_base: urlBase(url),\n ...this.pages.tracking(),\n },\n cancel: () => {},\n };\n this.pending = pending;\n // Assigned after `pending` is in place: a watch that resolved synchronously would otherwise\n // flush before there was anything to flush.\n pending.cancel = watchTitle(document.title, () => this.flushPending());\n }\n\n /**\n * Sends the pending view now, with the current title. Runs when the title watch resolves, and\n * ahead of anything that must come after the view: the next navigation and its `$page_leave`,\n * `pagehide`, a `page()` call, `shutdown()` and `reset()` — the view belongs to the user being\n * reset.\n */\n flushPending(): void {\n const view = this.pending;\n if (!view) return;\n this.pending = undefined;\n view.cancel();\n this.emitView(view.location, view.counter, view);\n }\n\n /**\n * Drops the pending view unsent, for `optOut()`: sending an event at the moment the visitor\n * opts out is wrong even where the consent gate would drop it.\n */\n discardPending(): void {\n this.pending?.cancel();\n this.pending = undefined;\n }\n\n private emitView(where: PageLocation, counter: number, pending?: PendingView): void {\n const title = document.title;\n this.autoViewed = { url: where.href, at: this.sink.now() };\n this.sink.capture(\n '$page_view',\n 'page_view',\n {\n ...pageViewProperties({ source: 'auto', location: where, title }, this.rules),\n $page_counter: counter,\n },\n pending?.at,\n pending && { ...pending.page, title }\n );\n }\n\n /**\n * `$page_leave`, paired one-to-one with `$page_view`: sent when the view ENDS — an SPA\n * navigation to another page, or `pagehide` — and at most once for it, whichever path asks.\n *\n * Not when the tab is merely hidden. That used to send one per tab switch, each measured from\n * the same pageview, so one view produced several leaves with overlapping durations.\n *\n * Duration excludes nothing today: wall clock since the pageview. The spec asks for time with\n * the tab hidden excluded, which needs visibility accounting and is deliberately left for a\n * follow-up rather than approximated here.\n *\n * A pending view is flushed first, so a view always precedes its own leave: A → B → C inside\n * the title wait sends view B, leave B, view C. That also covers `pagehide`, whose unload leave\n * comes through here.\n */\n leave(maxScroll?: number): void {\n this.flushPending();\n const leaving = this.pages.current;\n if (leaving === undefined || this.left) return;\n this.left = true;\n const properties: Properties = {\n $page_duration_ms: Math.max(0, this.sink.now() - this.enteredAt),\n };\n if (maxScroll !== undefined) properties.$page_max_scroll = maxScroll;\n // Read back by tracking() for this one capture. On `pagehide` the live location is still the\n // page being left and this changes nothing; it matters for SPA navigation, where History has\n // already moved on.\n this.leaving = leaving;\n try {\n this.sink.capture('$page_leave', 'page_leave', properties);\n } finally {\n this.leaving = undefined;\n }\n }\n\n /**\n * A bfcache restore puts the visitor back on a page a `$page_leave` already reported. They\n * will leave it again, so the leave is re-armed, and restarting the clock keeps the second\n * one from billing the frozen time as time on page.\n */\n restored(persisted: boolean): void {\n if (!persisted) return;\n this.left = false;\n this.enteredAt = this.sink.now();\n }\n\n /** `counter` is pages *this session*, so a rotation restarts the count. */\n newSession(): void {\n this.pages.resetForNewSession();\n }\n\n /** Fields for `context.page`, including the `$page_leave` overrides when one is in flight. */\n tracking(): PageTracking {\n const tracking = this.pages.tracking();\n if (this.leaving === undefined) return tracking;\n return {\n ...tracking,\n url: this.leaving,\n path: pathOf(this.leaving),\n domain: domainOf(this.leaving),\n url_base: urlBase(this.leaving),\n };\n }\n\n /** What makes a page distinct: the path, or the whole URL under `pageviews: 'all'`. */\n private pageKey(): string | undefined {\n const live = globalThis.location;\n return live && this.keyOf(live);\n }\n\n private keyOf(where: PageLocation): string {\n return this.byHref ? where.href : where.pathname;\n }\n\n /** Records the live URL. Resets the page clock only when this really is a new page. */\n private record(): void {\n const url = href();\n if (url === undefined) return;\n const moved = this.pages.recordPage(\n url,\n typeof document !== 'undefined' ? document.referrer : ''\n );\n if (moved) {\n this.enteredAt = this.sink.now();\n this.left = false;\n }\n }\n}\n\n/**\n * How long after an automatic `$page_view` a `page()` for the same URL is taken as its duplicate:\n * a router's after-navigation hook or a `DOMContentLoaded` handler, not a deliberate second view.\n */\nconst AUTO_VIEW_CLAIM_MS = 2000;\n\n/** How a `$page_view` was sent: by autocapture, or by a `page()` / `screen()` call. */\nexport type PageSource = 'auto' | 'manual';\n\n/** `pageNames`, compiled once: the readable name for a location, and its type for a pattern. */\nexport type PageNameRules = (location: PageLocation) => { name: string; type?: string } | undefined;\n\nexport interface PageViewInput {\n source: PageSource;\n /** The `page()` argument. */\n name?: string;\n /** The `page()` options' `type`. */\n type?: string;\n /** Defaults to the live `window.location`. */\n location?: PageLocation;\n /** Defaults to the live `document.title`. */\n title?: string;\n}\n\n/**\n * The SDK-owned properties of every `$page_view`, for both the automatic and the manual path.\n *\n * One function so the two cannot drift: they used to fall back differently (`title || 'Unknown'`\n * against `name ?? document.title ?? 'Unknown'`), which sent an empty name from `page()` on a page\n * without a `<title>`. A blank name or title counts as missing, and the path is the last resort —\n * more useful in a chart than \"Unknown\", which is only left for the no-`window` case.\n *\n * The name is the first non-blank of: the `page()` argument, a `pageNames` match, the title, the\n * path. A manual `page()` without a name goes through `pageNames` too, so one page gets the same\n * `$page_name` from both paths. `$page_type` is the `page()` options' `type`, else the matching\n * pattern's name, else absent; a `pageNames` function names pages but gives no type.\n *\n * `$page_name`, not `name`: `name` is the key clients use most for their own data, and the SDK\n * writing it overwrote theirs.\n */\nexport function pageViewProperties(\n {\n source,\n name,\n type,\n location = globalThis.location,\n title = globalThis.document?.title,\n }: PageViewInput,\n rules?: PageNameRules\n): { $page_name: string; $page_type?: string; $page_source: PageSource } {\n const match = location && rules?.(location);\n const pageType = type?.trim() || match?.type;\n return {\n // `||`, not `??`: a blank string is as missing as an absent one.\n $page_name:\n name?.trim() || match?.name.trim() || title?.trim() || location?.pathname || 'Unknown',\n ...(pageType ? { $page_type: pageType } : {}),\n $page_source: source,\n };\n}\n\n/**\n * Compiles `pageNames` once, at init.\n *\n * Patterns are path globs: `*` is one segment, `**` the rest of the path (`/a/**` matches `/a`\n * itself too). A trailing slash is ignored on both sides. The first match wins, in insertion\n * order for an object — so `'/a/*'` written before `'/a/b'` shadows it; the array-of-pairs form\n * makes that order explicit. A pattern's name is also its `$page_type`.\n *\n * A function is called per view and returns `undefined` for \"no rule\". One that throws, or returns\n * anything but a string, counts as no match: a bug in the host's rule must not cost the page view.\n */\nexport function pageNameRules(names: PageNames | undefined): PageNameRules | undefined {\n if (typeof names === 'function') {\n return (location) => {\n try {\n const name = names(location);\n return typeof name === 'string' ? { name } : undefined;\n } catch {\n return undefined;\n }\n };\n }\n if (!names || typeof names !== 'object') return undefined;\n // A non-string entry compiles to `false` and never matches.\n const rules = (Array.isArray(names) ? names : Object.entries(names)).map(\n ([glob, name]) =>\n [typeof glob === 'string' && typeof name === 'string' && globPattern(glob), name] as const\n );\n return (location) => {\n const path = trimSlash(location.pathname);\n for (const [pattern, name] of rules) if (pattern && pattern.test(path)) return { name, type: name };\n return undefined;\n };\n}\n\n/**\n * `*` is one path segment, `**` any number; everything else is literal. Escaped first — `*` is not\n * among the escaped characters — so the second pass sees only the glob's own stars.\n */\nfunction globPattern(glob: string): RegExp {\n const source = trimSlash(glob)\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\/\\*\\*|\\*\\*?/g, (star) =>\n star === '*' ? '[^/]+' : star === '**' ? '.*' : '(?:/.*)?'\n );\n return new RegExp(`^${source}$`);\n}\n\n/** `/products/x/` matches like `/products/x`. The root keeps its slash. */\nfunction trimSlash(path: string): string {\n return path.replace(/(.)\\/$/, '$1');\n}\n\nfunction href(): string | undefined {\n if (typeof window === 'undefined' || !window.location) return undefined;\n return window.location.href;\n}\n\nfunction sameOrigin(a: string, b: string): boolean {\n try {\n return new URL(a).host === new URL(b).host;\n } catch {\n return false;\n }\n}\n\n/** Pathname of `url`, for `context.page.path`. */\nexport function pathOf(url: string): string | undefined {\n try {\n return new URL(url).pathname || undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Host of `url`, for `context.page.domain`. */\nexport function domainOf(url: string): string | undefined {\n try {\n return new URL(url).host || undefined;\n } catch {\n return undefined;\n }\n}\n\n/** `url` without query string or fragment, for `context.page.url_base`. */\nexport function urlBase(url: string): string | undefined {\n try {\n const u = new URL(url);\n return `${u.origin}${u.pathname}`;\n } catch {\n return undefined;\n }\n}\n","/**\n * Marketing attribution: where this visitor came from, carried on EVERY event.\n *\n * Why every event rather than only the landing `$page_view`: answering \"how many Add to cart\n * events came from the Diwali campaign?\" otherwise needs a join back to whichever pageview\n * started the visit, which a warehouse query can do but a funnel definition cannot.\n *\n * The key shape here is NOT arbitrary — it is what the collector already reads. See\n * `backend/routers/collect.py` in the analytics repo, which maps\n * `context.campaign.{source,medium,name,term,content}` onto `$utm_*` and\n * `context.referrer.{domain,initial_url,initial_domain}` onto `$referring_domain` /\n * `$initial_referrer` / `$initial_referring_domain`. The product spec proposed putting\n * first-touch under `context.page.*` instead; that would have been accepted and silently\n * dropped, because the collector destructures a fixed set of context blocks and ignores the\n * rest. Match the consumer, not the proposal.\n *\n * `utm_id` and ad click IDs (gclid, fbclid, …) are deliberately NOT sent yet: the collector\n * does not read them, so emitting them would cost bytes on every event for no stored data.\n * Tracked in analytics#2491.\n */\nimport type { KVStorage } from './queue/storage';\nimport { domainOf as hostOf } from './page';\n\n/** UTM parameter → the key the collector expects under `context.campaign`. */\nconst UTM_PARAMS: ReadonlyArray<readonly [string, string]> = [\n ['utm_source', 'source'],\n ['utm_medium', 'medium'],\n ['utm_campaign', 'name'],\n ['utm_term', 'term'],\n ['utm_content', 'content'],\n];\n\nexport const KEY_CAMPAIGN = 'depsmith_campaign';\nexport const KEY_REFERRER = 'depsmith_referrer';\n\nexport interface CampaignBlock {\n source?: string;\n medium?: string;\n name?: string;\n term?: string;\n content?: string;\n}\n\nexport interface ReferrerBlock {\n /** Referrer of the current landing. */\n url?: string;\n /** Host of `url`. */\n domain?: string;\n /** Referrer of the FIRST ever landing for this anonymous_id. Written once. */\n initial_url?: string;\n initial_domain?: string;\n}\n\n\n/**\n * Attribution state for this visitor, persisted so it survives reloads and outlives the\n * landing page. Reads storage once at construction: these values change only on a landing,\n * and `buildContext` runs on every captured event, so a per-event read would be pure cost.\n */\nexport class Attribution {\n private campaign: CampaignBlock = {};\n private referrer: ReferrerBlock = {};\n\n constructor(private storage: KVStorage) {\n this.campaign = this.read<CampaignBlock>(KEY_CAMPAIGN) ?? {};\n this.referrer = this.read<ReferrerBlock>(KEY_REFERRER) ?? {};\n }\n\n private read<T>(key: string): T | null {\n try {\n const raw = this.storage.get(key);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as unknown;\n // A corrupt value must not poison attribution for the rest of the install; treat it as\n // absent, same policy the queue uses for unparseable entries.\n return parsed && typeof parsed === 'object' ? (parsed as T) : null;\n } catch {\n return null;\n }\n }\n\n private write(key: string, value: object): void {\n try {\n this.storage.set(key, JSON.stringify(value));\n } catch {\n /* storage full or blocked — attribution degrades, capture must not */\n }\n }\n\n /**\n * Record a landing. Call on init and on every SPA route change.\n *\n * Three rules, each with a failure mode it prevents:\n * - **Latest campaign wins, as a set.** Any UTM present replaces ALL stored UTMs rather\n * than merging, so a `?utm_source=meta` visit cannot inherit the previous visit's\n * `utm_campaign` and report a campaign that never sent that click.\n * - **Internal navigation changes nothing.** Moving between our own pages has our own host\n * as `document.referrer`; treating that as a new referrer would overwrite the real source\n * on the second pageview of every visit.\n * - **First touch is written once.** `initial_*` is the acquisition source and must survive\n * every later campaign.\n */\n recordLanding(url: string, documentReferrer: string): void {\n let params: URLSearchParams;\n let currentHost: string | undefined;\n try {\n const parsed = new URL(url);\n params = parsed.searchParams;\n currentHost = parsed.host;\n } catch {\n return;\n }\n\n const incoming: CampaignBlock = {};\n for (const [param, key] of UTM_PARAMS) {\n const value = params.get(param);\n if (value) incoming[key as keyof CampaignBlock] = value;\n }\n if (Object.keys(incoming).length > 0) {\n this.campaign = incoming;\n this.write(KEY_CAMPAIGN, incoming);\n }\n\n const refHost = documentReferrer ? hostOf(documentReferrer) : undefined;\n const isExternal = Boolean(refHost) && refHost !== currentHost;\n\n let changed = false;\n if (isExternal) {\n this.referrer.url = documentReferrer;\n this.referrer.domain = refHost;\n changed = true;\n }\n // First touch is recorded on the first landing even when it is direct, so `$direct` can be\n // told apart from \"we never looked\". `initial_url` stays absent for direct; the domain\n // sentinel is what the collector keys on.\n if (this.referrer.initial_domain === undefined) {\n this.referrer.initial_domain = isExternal ? refHost : '$direct';\n if (isExternal) this.referrer.initial_url = documentReferrer;\n changed = true;\n }\n if (changed) this.write(KEY_REFERRER, this.referrer);\n }\n\n /** The `context.campaign` block, or undefined when nothing is known. */\n campaignBlock(): CampaignBlock | undefined {\n return Object.keys(this.campaign).length > 0 ? { ...this.campaign } : undefined;\n }\n\n /** The `context.referrer` block, or undefined when nothing is known. */\n referrerBlock(): ReferrerBlock | undefined {\n return Object.keys(this.referrer).length > 0 ? { ...this.referrer } : undefined;\n }\n\n /** `reset()` forgets the visitor, so it must forget where they came from too. */\n clear(): void {\n this.campaign = {};\n this.referrer = {};\n try {\n this.storage.remove(KEY_CAMPAIGN);\n this.storage.remove(KEY_REFERRER);\n } catch {\n /* ignore */\n }\n }\n}\n","/**\n * The browser half of the client's lifecycle: the batch-interval timer and the `pagehide`,\n * `pageshow`, `visibilitychange` and `online` handlers (API_SPEC §9). Inert without a window.\n *\n * A module of its own so the Shopify custom-pixel build can swap it for `lifecycle.noop.ts`.\n * That build always passes `manualLifecycle: true` — the sandbox has no page to hide and the\n * pixel drives its own flush interval — so none of this can run there, and it is unminified\n * against an editor that refuses to save a file over 64,000 characters (see `tsup.config.ts`).\n */\n\n/** What the handlers need from the client. Every member is the client's own, guarded, method. */\nexport interface LifecycleHost {\n /** `batchIntervalMs`. */\n intervalMs: number;\n guard(fn: () => void): void;\n /** `$web_vitals`, once per page. */\n vitals(): void;\n /** Autocapture's unload-time `$page_leave`, when pageview tracking is on. Once per view. */\n leave(): void;\n /** A back/forward-cache restore (`pageshow`). */\n restored(persisted: boolean): void;\n /** The tab became visible again: run the session-timeout check. */\n resume(): void;\n /** Starts an upload when there is something to send and consent allows it. */\n flushIfQueued(): void;\n /** Forces the write-behind queue and session to storage. */\n persistNow(): void;\n /** The `sendBeacon` drain, if consent allows upload. */\n beacon(): void;\n /** Connectivity came back. */\n online(): void;\n}\n\nexport interface BrowserLifecycle {\n /**\n * Re-arms the teardown drain; the client calls it for every event it queues.\n *\n * `drained` exists only to stop `pagehide` and `visibilitychange`→hidden running the\n * same drain twice on one navigation. It must not outlive the work it covered: on\n * desktop, `visibilitychange`→hidden fires on an ordinary tab switch, and a backgrounded\n * tab keeps capturing (the batch-interval timer, `online`, a host-driven `track()`). If\n * that tab is then closed without ever becoming visible again, a latch left set would\n * skip both the final `sendBeaconAll()` and the teardown write, losing everything\n * captured while hidden — a correctness hole opened by a pure optimisation.\n */\n rearm(): void;\n /** Stops the timer and removes the listeners. */\n stop(): void;\n}\n\nexport function startLifecycle(host: LifecycleHost): BrowserLifecycle | undefined {\n // No window means no page: a server render, or a worker. Nothing is started there — not\n // the listeners, which have nothing to listen to, and not the timer. The timer used to start\n // regardless, and in Node an interval that is never cleared keeps the process alive and\n // retains the client it closes over: one leaked client per server render for a host that\n // builds `new DepsmithSdkClient()` in a component. A host without a window drives `flush()`\n // itself, as the Shopify pixel does.\n if (typeof window === 'undefined' || typeof document === 'undefined') return undefined;\n const flushTimer = setInterval(() => host.flushIfQueued(), host.intervalMs);\n // jsdom under Node (tests, prerendering) has a window AND Node's timers: do not let this one\n // hold the process open either. Browsers return a number, which has no `unref`.\n (flushTimer as { unref?: () => void }).unref?.();\n /**\n * Set once a teardown drain has run, so `pagehide` and `visibilitychange`→hidden do not\n * both run it on one navigation. Cleared on resume, on `pageshow`, and by any newly\n * captured event ({@link BrowserLifecycle.rearm}).\n */\n let drained = false;\n /** The fetch flush a tab-hide schedules; cancelled if the hide turns out to be an unload. */\n let hideFlush: ReturnType<typeof setTimeout> | undefined;\n\n // `pagehide` and `visibilitychange`→hidden both fire on a navigation, back-to-back on\n // mobile. Without this guard the whole drain ran twice per page transition, in the\n // handler that is already delaying that transition. Cleared on resume, and by any\n // newly captured event — see rearm().\n //\n // The two events are NOT the same thing, and treating them alike lost events:\n // - `pagehide` means the document is going away. There will be no response to wait for,\n // so this is the one place `sendBeacon` is used and events are removed on the UA's\n // acceptance rather than on a 2xx.\n // - `visibilitychange`→hidden usually means a tab or app switch, and the page lives on.\n // Beaconing there deleted events on every tab switch — including ones the collector\n // then answered with a 5xx, or never received at all. A hidden tab instead gets an\n // ordinary fetch flush (`keepalive`, removed only on 2xx, retried otherwise).\n // On a navigation both fire in the same task, in an order that differs between browsers,\n // so the hidden path defers its flush by a macrotask: if a `pagehide` arrives first or\n // right behind it, that cancels the fetch and beacons instead, and the batch is not sent\n // twice. If the page is frozen before the timer runs, the events are already persisted\n // (below) and replay on the next load.\n //\n // `$page_leave` belongs to `pagehide` alone. A hidden tab has not left the page: emitting\n // there produced one leave per tab switch for a single `$page_view`, each measured from the\n // same start, so summed time on page was overcounted several times over (API_SPEC §12.3\n // promises one per view). `$web_vitals` stays on the first hide, where its values are final.\n const onPageHide = (): void => {\n // `pendingHide`: a hidden a moment ago already latched, but deferred its upload to us —\n // the drain still has to run.\n const pendingHide = hideFlush;\n clearTimeout(pendingHide);\n hideFlush = undefined;\n // Both before the drain, so they ride out in the batch sendBeacon is about to post rather\n // than sitting in a queue this page never gets to flush. Each is latched by its owner —\n // vitals once per page, the leave once per view — so calling them again here is safe, and\n // capturing either re-arms `drained` (see rearm): a tab closed long after it was hidden\n // still beacons its leave.\n //\n // Guarded, because this is where the teardown path calls out to the autocapture module. A\n // throw here would escape before `sendBeaconAll()` and `persistNow()` ran and cost the page\n // its ENTIRE queue, not just this one event. Nothing in today's closure can throw, which is\n // exactly why the next person to extend it would not think to check.\n host.guard(() => host.vitals());\n host.guard(() => host.leave());\n // Nothing new since a drain already ran: the paired `visibilitychange`→hidden got here first.\n if (drained && !pendingHide) return;\n // Latched only now, after the captures above, because capturing clears the latch — which\n // would otherwise let a `visibilitychange`→hidden that follows run the drain a second time.\n drained = true;\n host.beacon();\n // The queue and session are write-behind; this is the point where deferring any\n // further would lose them. One synchronous write each, at teardown, instead of two\n // per captured event.\n host.persistNow();\n };\n const onVisibility = (): void => {\n if (document.visibilityState === 'hidden') {\n if (drained) return;\n host.guard(() => host.vitals());\n drained = true;\n // Persist first: if the page is frozen or killed before the timer below runs, this\n // write is what the next load replays.\n host.persistNow();\n hideFlush = setTimeout(() => {\n hideFlush = undefined;\n host.flushIfQueued();\n }, 0);\n } else {\n clearTimeout(hideFlush);\n drained = false;\n host.resume();\n }\n };\n // A bfcache restore can bring the page back without a visibilitychange, which would\n // otherwise leave `drained` stuck on and skip the final flush of the next navigation.\n const onPageShow = (event: PageTransitionEvent): void => {\n drained = false;\n // The visitor is back on a page whose `$page_leave` the `pagehide` already sent, and will\n // leave it again: the page lifecycle re-arms the leave and restarts its clock, so the\n // second one does not report the hours the tab spent frozen as time on page.\n host.restored(event.persisted);\n };\n const onOnline = (): void => host.online();\n\n window.addEventListener('pagehide', onPageHide);\n window.addEventListener('pageshow', onPageShow);\n document.addEventListener('visibilitychange', onVisibility);\n window.addEventListener('online', onOnline);\n return {\n rearm: () => {\n drained = false;\n },\n stop: () => {\n clearInterval(flushTimer);\n window.removeEventListener('pagehide', onPageHide);\n window.removeEventListener('pageshow', onPageShow);\n document.removeEventListener('visibilitychange', onVisibility);\n window.removeEventListener('online', onOnline);\n clearTimeout(hideFlush);\n },\n };\n}\n","import type { ResolvedAutocaptureConfig } from '../config';\nimport type { AutocaptureHooks } from './index';\n\n/** The subset of the autocapture module DepsmithSdkClient uses. */\nexport interface AutocaptureModule {\n startAutocapture(config: ResolvedAutocaptureConfig, hooks: AutocaptureHooks): () => void;\n}\n\n/**\n * Loads the autocapture engine on demand, keeping it out of the core bundle (<10 KB gz).\n *\n * This indirection exists so a build can swap in `load.noop.ts`: a dynamic `import()`\n * anywhere in the graph makes esbuild emit its `__esm` lazy-init helper, and Shopify's\n * pixel editor rejects that helper's `(0, fn[...])(fn = 0)` idiom outright. Dead-code\n * elimination can't save us there — the pixel build is deliberately unminified, and\n * esbuild only performs DCE while minifying.\n */\nexport function loadAutocapture(): Promise<AutocaptureModule | null> {\n return import('./index');\n}\n","import type { EventContext } from './types';\n\n/**\n * Per-field suppression of context signals (API_SPEC §12.2).\n *\n * Every key defaults true (collected). This filter is SUBTRACTIVE ONLY — leaving an option\n * true never re-enables a field that `deviceFingerprinting`, `childSafeMode` or consent\n * already suppressed, so the controls compose by intersection and no context field ends up\n * with two sources of truth.\n */\nexport interface TrackingOptions {\n /** context.app. Mobile only — web has no app-version concept. */\n appVersion?: boolean;\n /** context.browser. Populated only when deviceFingerprinting is on. */\n browser?: boolean;\n /** context.network.carrier. Implied by `network: false`. */\n carrier?: boolean;\n deviceManufacturer?: boolean;\n deviceModel?: boolean;\n deviceType?: boolean;\n /** context.device.idfv — iOS only, and the ONLY control over it: nothing else suppresses it. */\n idfv?: boolean;\n /** context.locale. */\n language?: boolean;\n /** context.network in full. Subsumes carrier. */\n network?: boolean;\n osName?: boolean;\n osVersion?: boolean;\n /** context.page. Not `$page_name` on $page_view — that is a property, not context. */\n page?: boolean;\n /** context.screen_size: display width, height and density. */\n screenSize?: boolean;\n timezone?: boolean;\n /** context.user_agent. */\n userAgent?: boolean;\n}\n\nexport type ResolvedTrackingOptions = Required<TrackingOptions>;\n\n/**\n * `[option, context key, sub-key]`. Omitting the sub-key drops the whole block.\n *\n * Table-driven rather than fourteen branches so the option set, the defaults and the\n * platform ports cannot drift apart — the mobile SDKs carry the identical table.\n * `library` is deliberately absent: it is the schema's one required context field.\n */\nconst SUPPRESSIONS: ReadonlyArray<readonly [keyof TrackingOptions, string, string?]> = [\n ['appVersion', 'app'],\n ['browser', 'browser'],\n ['carrier', 'network', 'carrier'],\n ['deviceManufacturer', 'device', 'manufacturer'],\n ['deviceModel', 'device', 'model'],\n ['deviceType', 'device', 'type'],\n ['idfv', 'device', 'idfv'],\n ['language', 'locale'],\n ['network', 'network'],\n ['osName', 'os', 'name'],\n ['osVersion', 'os', 'version'],\n ['page', 'page'],\n ['screenSize', 'screen_size'],\n ['timezone', 'timezone'],\n ['userAgent', 'user_agent'],\n];\n\n/** Derived from the table so an added option cannot be left out of the defaults. */\nexport const TRACKING_DEFAULTS = Object.fromEntries(\n SUPPRESSIONS.map(([option]) => [option, true])\n) as ResolvedTrackingOptions;\n\n/**\n * Only an explicit `false` suppresses.\n *\n * A plain spread would let an explicitly-`undefined` property overwrite the `true` default\n * — `{ page: cfg.capturePage }` with an undefined `capturePage` would strip `context.page`\n * from every event, which is data loss from a config the caller believes is a no-op. The\n * mobile ports already fall back to true for a missing or non-boolean entry\n * (`TrackingOptions.fromMap` on Android, `init(from:)` on iOS); this keeps web level.\n */\nexport function resolveTrackingOptions(options?: TrackingOptions): ResolvedTrackingOptions {\n const resolved = { ...TRACKING_DEFAULTS };\n if (!options) return resolved;\n for (const [option] of SUPPRESSIONS) {\n if (options[option] === false) resolved[option] = false;\n }\n return resolved;\n}\n\n/**\n * Removes suppressed fields, in place. Callers pass a freshly built context.\n *\n * Must run AFTER any host-supplied context override — the Shopify pixel supplies page\n * context on every event, and an embedder must not be able to resurrect a field the app\n * disabled.\n */\nexport function applyTrackingOptions(\n context: EventContext,\n options: ResolvedTrackingOptions\n): EventContext {\n const record = context as unknown as Record<string, unknown>;\n for (const [option, key, sub] of SUPPRESSIONS) {\n if (options[option]) continue;\n if (sub === undefined) {\n delete record[key];\n continue;\n }\n // Copy before deleting: override blocks are shallow-merged BY REFERENCE, so an in-place\n // delete would reach into the host's own object. Emptying a block removes the block —\n // suppressing osName and osVersion yields no `os`, not `os: {}`.\n const block = { ...(record[key] as Record<string, unknown> | undefined) };\n delete block[sub];\n if (Object.keys(block).length > 0) record[key] = block;\n else delete record[key];\n }\n return context;\n}\n","import type { AutocaptureConfig, ResolvedAutocaptureConfig } from '../config';\n\n// Autocapture's config defaults, apart from `config.ts` so the Shopify custom-pixel build can\n// swap them for `options.noop.ts`. The pixel always passes `autocapture: false` (there is no DOM\n// in its sandbox) and its autocapture loader is a no-op too, so none of this can run there — and\n// that bundle is unminified against a 64,000-character editor cap (see tsup.config.ts).\n\nexport const AUTOCAPTURE_DEFAULTS: ResolvedAutocaptureConfig = {\n // Interactive-only by default. Capturing every click on the page emitted an event for\n // taps on product images and layout containers — each one costing a queue write — and\n // buried the clicks that carry intent. 'all' restores the firehose explicitly.\n clicks: 'interactive',\n forms: true,\n // Off by default, for now: up to four `scroll_depth` events per page view on every site,\n // `autocapture: true` (the Shopify snippet) included. With it off nothing measures depth, so\n // `$page_leave` has no `$page_max_scroll` either — decision D1, documented in the schema.\n scrolls: false,\n // Path only by default. Counting every `href` change sent a page view and a `$page_leave` for\n // each filter ticked, each sort order, each `#reviews` click and each tag manager tidying\n // `utm_*` out of the URL — distorting page counts, `$page_counter` and time on page alike.\n pageviews: 'path',\n ignoredSelectors: [],\n selectorMaxDepth: 5,\n selectorIgnore: [] as string[],\n attributes: [] as string[],\n};\n\n/**\n * `autocapture` resolved: `true` is every default, an object overrides them, anything else is off.\n *\n * A defined-only merge, not a plain spread: `{ pageviews: undefined }` — which an untyped host or\n * a config built from optional fields produces easily — would otherwise overwrite the default\n * with `undefined` and read as \"off\". The same rule `resolveTrackingOptions` follows.\n */\nexport function resolveAutocapture(\n autocapture: boolean | AutocaptureConfig | undefined\n): false | ResolvedAutocaptureConfig {\n if (autocapture === true) return AUTOCAPTURE_DEFAULTS;\n if (!autocapture || typeof autocapture !== 'object') return false;\n const resolved = { ...AUTOCAPTURE_DEFAULTS } as Record<string, unknown>;\n for (const [key, value] of Object.entries(autocapture)) {\n if (value !== undefined) resolved[key] = value;\n }\n const { clicks, pageviews } = resolved;\n // `true` is an alias: 'interactive' for clicks, 'path' for page views. Only an explicit 'all'\n // asks for every click, or for a view per URL change.\n resolved.clicks = clicks === 'all' ? 'all' : clicks ? 'interactive' : false;\n resolved.pageviews = pageviews === 'all' ? 'all' : pageviews ? 'path' : false;\n return resolved as unknown as ResolvedAutocaptureConfig;\n}\n","import {\n resolveTrackingOptions,\n type ResolvedTrackingOptions,\n type TrackingOptions,\n} from './tracking-options';\nimport { resolveAutocapture } from './autocapture/options';\nimport type { Properties } from './types';\n\n/** Public config — keys mirror spec/schema/config.schema.json. */\nexport interface DepsmithSdkConfig {\n apiKey: string;\n endpoint: string;\n batchSize?: number;\n batchIntervalMs?: number;\n maxQueueSize?: number;\n /**\n * Ceiling on the serialised queue, in UTF-16 code units — the unit browsers meter\n * storage quota in. Bounds the bytes DepsmithSdk occupies in an origin-shared `localStorage`,\n * which `maxQueueSize` (a count) cannot. Oldest events are dropped first. Web only.\n */\n maxQueueBytes?: number;\n sessionTimeoutMs?: number;\n /** Fraction of SESSIONS captured, 0..1. Default 1. Session-sticky; see config.schema.json. */\n sampleRate?: number;\n /** Emit $session_start/$session_end as events, or leave them derivable server-side. Default 'emit'. */\n sessionEvents?: 'emit' | 'derive';\n consentMode?: 'granted' | 'pending';\n respectDnt?: boolean;\n maxRetries?: number;\n debug?: boolean;\n autocapture?: boolean | AutocaptureConfig;\n defaultProperties?: Properties;\n /** Batch upload compression. gzip when CompressionStream exists, transparent fallback otherwise. */\n compression?: 'gzip' | 'none';\n /** COPPA: memory-only identity, identify()/alias() disabled, anonymizeIp forced on. */\n childSafeMode?: boolean;\n /** Ask the server to strip the last IP octet (anonymize_ip on every batch). */\n anonymizeIp?: boolean;\n /** Device fingerprinting (browser/os/device.id/network). **Default true** — opt-OUT, unlike `geolocation`. Suppressed under DNT/childSafeMode/pending consent. */\n deviceFingerprinting?: boolean;\n /**\n * Opt-in device position on context.location (latitude/longitude/accuracy). Never prompts:\n * read only when the site already holds the geolocation permission. City/region/country\n * remain server-resolved from the request IP. Suppressed under DNT/childSafeMode/pending\n * consent, like deviceFingerprinting. Default false.\n */\n geolocation?: boolean;\n /**\n * Opt-in. Strip the fragment and query string from every URL the SDK sends — `context.page`\n * url/referrer/previous_url, `context.referrer`, `$ac_href`, `$ac_form_action`, `$net_*`.\n * `{ keepParams: ['utm_source'] }` keeps the named query parameters. Default false: URLs are\n * sent whole. See API_SPEC §12.\n */\n scrubUrls?: boolean | { keepParams?: string[] };\n /** Per-field context suppression, all keys default true. Subtractive only; see API_SPEC §12.2. */\n trackingOptions?: TrackingOptions;\n /** Persist identity keys in a cookie scoped to this domain (cross-subdomain identity). */\n cookieDomain?: string;\n /** Queue persistence backend. */\n storage?: 'localstorage' | 'indexeddb' | 'memory';\n /**\n * Readable `$page_name`s for automatic page views, and for `page()` calls made without a name.\n * A name passed to `page()` always wins; with no match the name falls back to the title.\n *\n * - **Patterns:** `{ '/products/*': 'Product', '/': 'Home' }`. `*` is one path segment, `**` the\n * rest of the path. The first match wins, in insertion order, so put specific patterns\n * before broad ones (or use the `[pattern, name]` array form). A pattern match also sets\n * `$page_type` to its name.\n * - **Function:** `(location) => string | undefined`, called per view. Sets the name only.\n * Web-only; config.schema.json can describe the object form alone.\n */\n pageNames?: PageNames;\n}\n\n/** What a `pageNames` function is handed: `window.location`, or a URL with the same fields. */\nexport type PageLocation = Pick<Location, 'href' | 'pathname' | 'search' | 'hash' | 'host'>;\n\nexport type PageNames =\n | Record<string, string>\n | ReadonlyArray<readonly [pattern: string, name: string]>\n | ((location: PageLocation) => string | undefined);\n\n/**\n * Which clicks produce a `$autocapture` event.\n * 'interactive' — only clicks resolving to a link/button/[role=button]/submit control\n * or an explicit [data-depsmith-sdk-capture]. The default.\n * 'all' — every click anywhere on the page, including layout containers.\n * true — alias of 'interactive'; false disables click capture.\n */\nexport type ClickCapture = boolean | 'interactive' | 'all';\n\n/**\n * When an automatic `$page_view` (and its `$page_leave`) is sent.\n * 'path' — when `location.pathname` changes. The default: a query-string or `#` change is\n * filters, sort order, pagination or an in-page anchor, not a new page.\n * 'all' — when anything in the URL changes, query and `#` included (the pre-0.8 behaviour).\n * true — alias of 'path'; false sends none automatically.\n */\nexport type PageViewCapture = boolean | 'path' | 'all';\n\nexport interface AutocaptureConfig {\n clicks?: ClickCapture;\n forms?: boolean;\n scrolls?: boolean;\n pageviews?: PageViewCapture;\n ignoredSelectors?: string[];\n selectorMaxDepth?: number;\n /**\n * Extra patterns for ids, classes and test-attribute values that `$ac_selector` should skip as\n * generated, on top of the built-in rules (CSS-in-JS and CSS-module hashes, utility classes,\n * long digit runs). Regex sources, e.g. `['^theme-', '^js-']`; an invalid one is skipped with\n * a debug warning.\n */\n selectorIgnore?: string[];\n /**\n * `data-*` attribute names to attach to click and change events as `$ac_attr_<name>`.\n *\n * An explicit allow-list, NOT a prefix, and empty by default. Data attributes routinely hold\n * exactly the values this SDK is careful never to capture — `data-user-email`,\n * `data-customer-id` — so a prefix rule means any attribute a developer adds later ships\n * silently from then on. Naming each one keeps the decision with the person who can see the\n * markup. Values obey the masking rules: nothing inside `[data-depsmith-sdk-mask]` is read.\n *\n * Given as bare names: `['product-id']` captures `data-product-id` as `$ac_attr_product_id`.\n */\n attributes?: string[];\n /**\n * `$network_request` for failed `fetch` calls, which wraps `window.fetch`. Default true (on\n * whenever autocapture is); false leaves `fetch` untouched while keeping the rest of\n * autocapture. See API_SPEC §12.6.\n */\n networkErrors?: boolean;\n}\n\n/** Every key present, with the aliases normalised away: `true` is never left in either mode. */\nexport interface ResolvedAutocaptureConfig\n extends Required<Omit<AutocaptureConfig, 'clicks' | 'pageviews' | 'networkErrors'>> {\n clicks: 'interactive' | 'all' | false;\n pageviews: 'path' | 'all' | false;\n /** Only ever present as an explicit `false`: absent means on. */\n networkErrors?: boolean;\n}\n\nexport interface ResolvedConfig\n extends Required<Omit<DepsmithSdkConfig, 'autocapture' | 'trackingOptions' | 'pageNames'>> {\n autocapture: false | ResolvedAutocaptureConfig;\n trackingOptions: ResolvedTrackingOptions;\n /** Compiled by the page lifecycle, not here: the pixel build has no page names to compile. */\n pageNames?: PageNames;\n}\n\n/** Validates and applies canonical defaults. Throws — callers (init only) catch and log. */\nexport function resolveConfig(config: DepsmithSdkConfig): ResolvedConfig {\n if (!config || typeof config.apiKey !== 'string' || config.apiKey.length === 0) {\n throw new Error('depsmith-sdk: apiKey is required');\n }\n if (typeof config.endpoint !== 'string' || !/^https?:\\/\\//.test(config.endpoint)) {\n throw new Error('depsmith-sdk: endpoint must be an http(s) URL');\n }\n\n const autocapture = resolveAutocapture(config.autocapture);\n\n return {\n apiKey: config.apiKey,\n endpoint: config.endpoint.replace(/\\/+$/, ''),\n // Every numeric key goes through num()/int(): see there for what a NaN used to do.\n batchSize: int(config.batchSize, 20, 1, 500),\n // The ceiling is what a timer can hold: past 2^31-1 ms `setInterval` overflows and fires\n // continuously.\n batchIntervalMs: int(config.batchIntervalMs, 60000, 1000, 2 ** 31 - 1),\n maxQueueSize: int(config.maxQueueSize, 1000, 1),\n // 512 Ki of a 5 Mi origin-shared budget. The floor keeps a misconfiguration from\n // making the queue effectively undeliverable.\n maxQueueBytes: int(config.maxQueueBytes, 512 * 1024, 4096),\n sessionTimeoutMs: int(config.sessionTimeoutMs, 1800000, 60000),\n sampleRate: num(config.sampleRate, 1, 0, 1),\n sessionEvents: config.sessionEvents === 'derive' ? 'derive' : 'emit',\n consentMode: config.consentMode ?? 'granted',\n respectDnt: config.respectDnt ?? true,\n maxRetries: int(config.maxRetries, 5, 0, 10),\n debug: config.debug ?? false,\n defaultProperties: config.defaultProperties ?? {},\n autocapture,\n compression: config.compression ?? 'gzip',\n childSafeMode: config.childSafeMode ?? false,\n // COPPA implies IP anonymization.\n anonymizeIp: (config.anonymizeIp ?? false) || (config.childSafeMode ?? false),\n deviceFingerprinting: config.deviceFingerprinting ?? true,\n geolocation: config.geolocation ?? false,\n scrubUrls: config.scrubUrls ?? false,\n trackingOptions: resolveTrackingOptions(config.trackingOptions),\n cookieDomain: config.cookieDomain ?? '',\n storage: config.storage ?? 'localstorage',\n pageNames: config.pageNames,\n };\n}\n\n/**\n * A numeric option: the default unless it is a finite number, then clamped.\n *\n * Non-finite falls back rather than clamping, because `clamp(NaN)` is NaN and a NaN does not\n * fail loudly, it poisons whatever reads it. An untyped host produces one easily\n * (`parseInt(settings.batch_size)` on an unset theme setting, `window.__depsmithSdkConfig` from\n * Liquid), and what each key then did:\n * - `batchSize`: `queue.peek(NaN)` is empty, so the uploader POSTed `batch: []`, removed\n * nothing and looped for the life of the page;\n * - `batchIntervalMs`: `setInterval(fn, NaN)` fires continuously;\n * - `maxRetries`: the attempt loop never ran, so nothing was ever uploaded;\n * - `maxQueueSize` / `maxQueueBytes`: every comparison false, so neither cap applied;\n * - `sampleRate`: every sample comparison false, so every non-identity event was dropped.\n */\nfunction num(value: unknown, fallback: number, min: number, max = Infinity): number {\n return Math.min(Math.max(Number.isFinite(value) ? (value as number) : fallback, min), max);\n}\n\n/** {@link num} for the keys config.schema.json types as integers. */\nfunction int(value: unknown, fallback: number, min: number, max?: number): number {\n return Math.floor(num(value, fallback, min, max));\n}\n","/** Tiny non-cryptographic string hashes. No dependencies; synchronous. */\n\n/** djb2 → base-36. Used for config-drift fingerprinting. */\nexport function djb2(input: string): string {\n let hash = 5381;\n for (let i = 0; i < input.length; i++) {\n hash = ((hash << 5) + hash + input.charCodeAt(i)) >>> 0;\n }\n return hash.toString(36);\n}\n\n/** FNV-1a (32-bit), raw. */\nexport function fnv1aInt(input: string): number {\n let hash = 2166136261;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 16777619) >>> 0;\n }\n // Already uint32: every iteration ends in `>>> 0`, and the offset basis is unsigned.\n return hash;\n}\n\n/** FNV-1a (32-bit) → base-36. Different mixing than djb2 to cut collisions when combined. */\nexport function fnv1a(input: string): string {\n return fnv1aInt(input).toString(36);\n}\n\n/**\n * Deterministic [0,1) bucket for sampling.\n *\n * Derived from the input rather than Math.random() on purpose: the decision must be\n * STICKY for a session's whole lifetime, identical across tabs sharing that session,\n * reproducible in tests, and recomputable server-side. A random draw is none of those.\n */\nexport function bucket(input: string): number {\n return fnv1aInt(input) / 0x100000000;\n}\n\n/**\n * Stable ~13-char id from a signal string. Concatenates two independent hashes so\n * unrelated inputs are far less likely to collide than a single 32-bit hash.\n */\nexport function fingerprintHash(input: string): string {\n return djb2(input) + fnv1a(input);\n}\n","import { fingerprintHash } from './hash';\nimport type { EventContext, NetworkType } from './types';\n\n/**\n * Passive device fingerprinting for web (fingerprintjs-inspired, no dependencies).\n * All reads are best-effort and guarded — callers wrap this in try/catch too.\n *\n * Privacy: ON BY DEFAULT. `deviceFingerprinting` defaults to true (since 0.3.1) and consent to\n * `granted`, so a stock install renders a canvas and hashes it on the first captured event. The\n * caller (DepsmithSdkClient) invokes this only while `deviceFingerprinting` is on, consent is\n * granted, and childSafeMode/DNT are off — `consentMode: 'pending'` or\n * `deviceFingerprinting: false` turn it off. This module does not re-check.\n */\n\ntype Browser = NonNullable<EventContext['browser']>;\ntype OS = NonNullable<EventContext['os']>;\n\ninterface ParsedAgent {\n browser?: Browser;\n os?: OS;\n deviceType?: string;\n device?: { manufacturer?: string; model?: string };\n}\n\ninterface NavigatorUAData {\n brands?: Array<{ brand: string; version: string }>;\n mobile?: boolean;\n platform?: string;\n getHighEntropyValues?: (hints: string[]) => Promise<HighEntropy>;\n}\n\ninterface HighEntropy {\n model?: string;\n platformVersion?: string;\n platform?: string;\n}\n\nlet hints: HighEntropy = {};\nlet hintsRequested = false;\n\n/**\n * Requests the UA Client Hints that carry device model and a real OS version.\n *\n * Called ONCE, from the client constructor — never from `buildContext()`. `getHighEntropyValues`\n * returns a Promise, and `buildContext` runs on the capture path, which PR #19 just finished\n * clearing of blocking work; awaiting there would undo that. Resolving once into module state\n * means the capture path only ever does a property read.\n *\n * The trade-off is explicit: the first event or two of a session may lack `device.model` and\n * fall back to the UA-string OS version. That is inherent to an async-only API and strictly\n * better than delaying capture.\n *\n * Chromium-only and secure-context-only; absence and rejection (NotAllowedError under a\n * restrictive permissions policy) are both silently tolerated.\n */\nexport function primeClientHints(): void {\n if (hintsRequested) return;\n hintsRequested = true;\n try {\n const uaData = (navigator as Navigator & { userAgentData?: NavigatorUAData })?.userAgentData;\n if (typeof uaData?.getHighEntropyValues !== 'function') return;\n void uaData\n .getHighEntropyValues(['model', 'platformVersion'])\n .then((values) => {\n hints = values;\n })\n .catch(() => {\n /* insecure context or permissions policy — keep the UA-string fallbacks */\n });\n } catch {\n /* no userAgentData at all */\n }\n}\n\n/** Testing seam: clear the memoised client hints. */\nexport function resetClientHintsCache(): void {\n hints = {};\n hintsRequested = false;\n}\n\n/** Parse browser, OS, and device type from UA Client Hints (when present) + the UA string. */\nexport function parseUserAgent(): ParsedAgent {\n const result: ParsedAgent = {};\n if (typeof navigator === 'undefined') return result;\n\n const ua = navigator.userAgent || '';\n const uaData = (navigator as Navigator & { userAgentData?: NavigatorUAData }).userAgentData;\n\n const browser = parseBrowser(ua, uaData);\n if (browser) result.browser = browser;\n\n const os = parseOS(ua);\n if (os) {\n // The UA string's OS version is frozen on Chromium — Android is pinned to \"10\" and macOS to\n // \"10_15_7\" regardless of the real version — so the hint wins whenever it resolved.\n const hinted = normalizeOsVersion(os.name, hints.platformVersion);\n result.os = hinted ? { ...os, version: hinted } : os;\n }\n\n const deviceType = parseDeviceType(ua, uaData);\n if (deviceType) result.deviceType = deviceType;\n\n const device = parseDevice(ua, os);\n if (device) result.device = device;\n\n return result;\n}\n\n/**\n * Device make and model, to the extent the web platform admits them.\n *\n * `model` comes from the UA-CH hint, which on Android Chromium is the same string Android's\n * native `Build.MODEL` reports (\"moto g96 5G\") — so the flattened column agrees across the two\n * SDKs. Chromium returns \"\" on desktop, which stays absent.\n *\n * `manufacturer` is Apple-only by design. UA-CH exposes no vendor field, and inferring a brand\n * from a model string (\"Pixel 8\" → Google) is a lookup table that rots with every handset\n * launch for a coarse win. Apple is the one case that is deterministic from the OS.\n */\nfunction parseDevice(ua: string, os?: OS): { manufacturer?: string; model?: string } | undefined {\n const device: { manufacturer?: string; model?: string } = {};\n if (os?.name === 'iOS' || os?.name === 'macOS') device.manufacturer = 'Apple';\n\n const hinted = hints.model?.trim();\n if (hinted) device.model = hinted;\n else if (/iPhone/.test(ua)) device.model = 'iPhone';\n else if (/iPad/.test(ua)) device.model = 'iPad';\n\n return device.manufacturer || device.model ? device : undefined;\n}\n\n/**\n * Maps a UA-CH `platformVersion` onto the version users and dashboards recognise.\n *\n * Windows is the case that matters: Chromium reports the PLATFORM version, not the marketing\n * one, so Windows 11 arrives as 13 or above and Windows 10 as 1–12. Without this every Windows\n * 11 machine is labelled \"10\" — and the UA string is no better, since it froze at \"Windows NT\n * 10.0\". Elsewhere trailing \".0\" groups are trimmed so web-on-Android reports \"16\" like the\n * native SDK rather than \"16.0.0\".\n */\nexport function normalizeOsVersion(\n osName: string | undefined,\n platformVersion?: string\n): string | undefined {\n const raw = platformVersion?.trim();\n if (!raw) return undefined;\n\n if (osName === 'Windows') {\n const major = Number.parseInt(raw.split('.')[0] ?? '', 10);\n if (!Number.isFinite(major)) return undefined;\n if (major === 0) return undefined; // Chromium's \"unknown\" sentinel\n return major >= 13 ? '11' : '10';\n }\n\n return trimVersion(raw);\n}\n\n/**\n * Order matters: Edge/Opera UAs also contain \"Chrome\"; Chrome contains \"Safari\".\n * `requires` is an extra guard that must hold before the version pattern is tried.\n */\nconst BROWSER_RULES: ReadonlyArray<{\n pattern: RegExp;\n name: string;\n engine: string;\n requires?: RegExp;\n}> = [\n { pattern: /Edg(?:e|A|iOS)?\\/([\\d.]+)/, name: 'Edge', engine: 'Blink' },\n { pattern: /OPR\\/([\\d.]+)/, name: 'Opera', engine: 'Blink' },\n { pattern: /Firefox\\/([\\d.]+)/, name: 'Firefox', engine: 'Gecko' },\n { pattern: /Chrome\\/([\\d.]+)/, name: 'Chrome', engine: 'Blink' },\n { pattern: /Version\\/([\\d.]+)/, name: 'Safari', engine: 'WebKit', requires: /Safari/ },\n];\n\nfunction parseBrowser(ua: string, uaData?: NavigatorUAData): Browser | undefined {\n for (const rule of BROWSER_RULES) {\n if (rule.requires && !rule.requires.test(ua)) continue;\n const match = ua.match(rule.pattern);\n if (match) return { name: rule.name, version: match[1], engine: rule.engine };\n }\n // Fall back to UA Client Hints brand list (skip the \"Not/A)Brand\" placeholder).\n const brand = uaData?.brands?.find((b) => !/not.?a.?brand/i.test(b.brand));\n if (brand) return { name: brand.brand, version: brand.version };\n return undefined;\n}\n\n/** iOS must be checked before macOS (iPad UAs can contain \"Mac OS X\"). */\nconst OS_RULES: ReadonlyArray<{ pattern: RegExp; name: string; requires?: RegExp }> = [\n { pattern: /Windows NT ([\\d.]+)/, name: 'Windows' },\n { pattern: /OS ([\\d_]+)/, name: 'iOS', requires: /iPhone|iPad|iPod/ },\n { pattern: /Android ([\\d.]+)/, name: 'Android' },\n { pattern: /Mac OS X ([\\d_]+)/, name: 'macOS' },\n];\n\nfunction parseOS(ua: string): OS | undefined {\n for (const rule of OS_RULES) {\n if (rule.requires && !rule.requires.test(ua)) continue;\n const match = ua.match(rule.pattern);\n // Apple reports versions with underscores (10_15_7); the others can't contain one,\n // so the replace is a no-op there.\n //\n // Trailing zero groups are trimmed here for the same reason normalizeOsVersion trims\n // them: the client hint resolves ASYNCHRONOUSLY, so the first events of a page take this\n // UA-string path and later ones take the hint path. Without matching normalisation the\n // SAME device reports \"10.0\" then \"10\" within one session — the e2e capture showed 42\n // events of one and 33 of the other — and every group-by on os_version splits one machine\n // into two rows.\n if (match) return { name: rule.name, version: trimVersion((match[1] ?? '').replace(/_/g, '.')) };\n }\n if (/Linux/.test(ua)) return { name: 'Linux' };\n return undefined;\n}\n\n/** Drops trailing `.0` groups (\"10.0\" -> \"10\", \"16.3.1\" -> \"16.3.1\"). */\nfunction trimVersion(version: string): string {\n const trimmed = version.replace(/(\\.0)+$/, '');\n return trimmed.length > 0 ? trimmed : version;\n}\n\nfunction parseDeviceType(ua: string, uaData?: NavigatorUAData): string | undefined {\n if (/iPad|Tablet|Nexus 7|Kindle|Silk/.test(ua)) return 'tablet';\n if (uaData?.mobile === true) return 'mobile';\n if (/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(ua)) return 'mobile';\n if (/Android/.test(ua)) return 'tablet'; // Android without \"Mobile\" → tablet\n if (typeof navigator !== 'undefined' && ua) return 'desktop';\n return undefined;\n}\n\nlet cachedVisitorId: string | null = null;\nlet cachedComponents: FingerprintComponent[] | null = null;\n\n/** One named signal. `value` is what feeds the hash; `name` is what goes on the wire. */\ninterface FingerprintComponent {\n name: string;\n value: string;\n}\n\n/**\n * Collected once per page. The canvas render is the expensive part, and both the device id and\n * the wire components derive from this one array — so it must never run twice.\n */\nfunction components(): FingerprintComponent[] {\n if (cachedComponents !== null) return cachedComponents;\n cachedComponents = collectSignals();\n return cachedComponents;\n}\n\n/**\n * Stable device id hashed from passive signals (screen, hardware, canvas).\n * Computed once per page and memoized — the canvas render is the only costly part.\n */\nexport function computeVisitorId(): string {\n if (cachedVisitorId !== null) return cachedVisitorId;\n cachedVisitorId = fingerprintHash(components().map((c) => c.value).join('|'));\n return cachedVisitorId;\n}\n\n/**\n * The same signals the device id is hashed from, but broken out by name.\n *\n * A single opaque hash cannot be matched approximately: one signal drifting — a browser update\n * changing canvas output, a monitor swap changing the screen string — produces a completely\n * different id, and a returning visitor who has cleared storage is unrecoverable. Sending the\n * parts lets the collector do N-of-M matching instead: 5 of 6 components equal, same\n * user-agent family, inside a time window, and the prior device is recovered rather than lost.\n *\n * This is the half FingerprintJS Pro does server-side, and the reason their accuracy is not\n * what the open-source agent's is. The hash stays on every event because it is 13 characters;\n * the components ride on `$session_start` alone, since they cost a few hundred bytes and\n * cannot change within a session.\n */\nexport function fingerprintComponents(): Record<string, string> {\n const out: Record<string, string> = {};\n for (const component of components()) out[`$fp_${component.name}`] = component.value;\n return out;\n}\n\n/** Testing seam: clear the memoised fingerprint. */\nexport function resetVisitorIdCache(): void {\n cachedVisitorId = null;\n cachedComponents = null;\n}\n\n/**\n * Signals that go into the device id.\n *\n * A signal belongs here only if it is BOTH device-distinguishing and stable for the life of the\n * device. The hash is opaque, so one signal changing does not degrade the id — it replaces it,\n * and the same device is counted as a new one.\n *\n * Deliberately EXCLUDED, and each was previously included:\n *\n * - `devicePixelRatio` — changes when the visitor ZOOMS the page. A zoom is not a new device,\n * but it was producing a new device id.\n * - `timeZone` — changes when the visitor travels.\n * - `navigator.language` — changes when they change their settings.\n *\n * Removing them costs the collector nothing, which is the point: all three are already sent as\n * their own context fields on every event — `context.screen_size.density`, `context.timezone` and\n * `context.locale` (see buildContext in context.ts). So the server can still match on them,\n * independently and tolerantly, instead of having them welded into a hash where any change is\n * total loss.\n *\n * ORDER IS LOAD-BEARING: the values are joined in sequence to produce the device id, so\n * reordering or reformatting any entry silently re-identifies every existing visitor.\n */\nfunction collectSignals(): FingerprintComponent[] {\n const signals: FingerprintComponent[] = [];\n try {\n if (typeof screen !== 'undefined') {\n signals.push({\n name: 'screen',\n value: `${screen.width}x${screen.height}x${screen.colorDepth}`,\n });\n }\n if (typeof navigator !== 'undefined') {\n const nav = navigator as Navigator & { deviceMemory?: number };\n signals.push({ name: 'hc', value: `hc:${navigator.hardwareConcurrency ?? ''}` });\n signals.push({ name: 'dm', value: `dm:${nav.deviceMemory ?? ''}` });\n signals.push({ name: 'plat', value: `plat:${navigator.platform ?? ''}` });\n signals.push({ name: 'touch', value: `touch:${(navigator.maxTouchPoints ?? 0) > 0}` });\n }\n signals.push({ name: 'canvas', value: `canvas:${canvasFingerprint()}` });\n } catch {\n // best-effort; a partial signal set still yields a stable-enough id\n }\n return signals;\n}\n\n/** Render a fixed scene to an offscreen canvas and hash the pixel data URL. */\nfunction canvasFingerprint(): string {\n try {\n if (typeof document === 'undefined') return '';\n const canvas = document.createElement('canvas');\n canvas.width = 240;\n canvas.height = 60;\n const ctx = canvas.getContext('2d');\n if (!ctx) return '';\n ctx.textBaseline = 'top';\n ctx.font = \"14px 'Arial'\";\n ctx.fillStyle = '#f60';\n ctx.fillRect(10, 10, 100, 30);\n ctx.fillStyle = '#069';\n // Built at runtime: esbuild emits any spelling of this literal as `\\u{1F310}`, and\n // Shopify's custom-pixel editor rejects that escape and refuses to save the pixel.\n // The drawn text, and so every existing canvas hash, is unchanged.\n ctx.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(0x1f310)}`, 12, 15);\n ctx.strokeStyle = 'rgba(0,120,200,0.5)';\n ctx.arc(50, 30, 20, 0, Math.PI * 2);\n ctx.stroke();\n return fingerprintHash(canvas.toDataURL());\n } catch {\n return '';\n }\n}\n\ninterface NetworkInformation {\n type?: string;\n effectiveType?: string;\n}\n\n/**\n * Best-effort network type from the Network Information API. `vpn` is intentionally\n * omitted on web — there is no reliable in-browser VPN signal (detected server-side).\n */\nexport function readNetwork(): { type?: NetworkType } {\n try {\n if (typeof navigator === 'undefined') return {};\n const conn = (navigator as Navigator & { connection?: NetworkInformation }).connection;\n if (!conn) return {};\n\n // `type` (wifi/ethernet/cellular/none) is more specific than `effectiveType` when present.\n const type = conn.type;\n if (type === 'wifi' || type === 'ethernet' || type === 'none') return { type };\n switch (conn.effectiveType) {\n case 'slow-2g':\n case '2g':\n return { type: '2g' };\n case '3g':\n return { type: '3g' };\n case '4g':\n return { type: '4g' };\n }\n return {};\n } catch {\n return {};\n }\n}\n","/**\n * Device position for `context.location` — and only when the user has ALREADY granted it.\n *\n * DepsmithSdk never prompts. `getCurrentPosition()` triggers the browser's permission dialog\n * whenever the state is `prompt`, and an analytics SDK popping a location request on page\n * load is exactly the behaviour that gets a site's tracking ripped out. So the Permissions\n * API is consulted first and the position is read only from a `granted` state; where the\n * Permissions API is absent (older Safari) nothing is requested at all, because there is no\n * way to tell `granted` from `prompt` without risking the dialog.\n *\n * Same shape as `primeClientHints()`: requested ONCE, off the capture path, resolved into\n * module state that `buildContext()` reads synchronously. The first event or two of a\n * session may therefore carry no position — inherent to an async-only API and strictly\n * better than delaying capture. Coarse accuracy is requested: Wi-Fi/cell positioning is\n * what analytics needs, and it avoids spinning up the GPS radio on every page view.\n *\n * Only latitude/longitude/accuracy are ever set here. City/region/country stay a collector\n * concern — it resolves them from the request IP and merges them over these coordinates.\n */\nexport interface GeoFix {\n latitude: number;\n longitude: number;\n accuracy?: number;\n /** Provenance, so a consumer can tell a device fix from the collector's IP fallback. */\n source: 'gps';\n}\n\n/** A fix older than this is refreshed (off the capture path) the next time it is read. */\nconst MAX_FIX_AGE_MS = 5 * 60_000;\nconst FIX_TIMEOUT_MS = 10_000;\n\nlet fix: GeoFix | null = null;\nlet fixAt = 0;\nlet primed = false;\nlet inFlight = false;\nlet permission: PermissionStatus | null = null;\n/** SDK consent, re-checked before every position read — see `primeGeolocation()`. */\nlet allowed: () => boolean = () => true;\n\n/**\n * Queries permission state once and, if already granted, requests a position.\n *\n * `allowed` is the SDK's consent gate. It is consulted before EVERY read, including the ones a\n * later permission change or a stale-fix refresh starts, so an `optOut()` after priming stops\n * further reads, and the next read drops the held fix (#87).\n */\nexport function primeGeolocation(gate = allowed): void {\n allowed = gate;\n if (primed) return;\n primed = true;\n try {\n if (typeof navigator === 'undefined' || !navigator.geolocation) return;\n const permissions = navigator.permissions;\n if (typeof permissions?.query !== 'function') return; // cannot rule out a prompt\n void permissions\n .query({ name: 'geolocation' })\n .then((status) => {\n permission = status;\n if (status.state === 'granted') requestFix();\n // The user may grant (or revoke) mid-session from the site's own UI; follow it\n // rather than freezing whatever the state was at init.\n status.onchange = () => {\n if (status.state === 'granted') requestFix();\n else fix = null;\n };\n })\n .catch(() => {\n /* permissions policy or unsupported name — stay silent, send nothing */\n });\n } catch {\n /* no navigator at all (SSR, worker sandbox) */\n }\n}\n\nfunction requestFix(): void {\n if (inFlight || !allowed()) return;\n inFlight = true;\n try {\n navigator.geolocation.getCurrentPosition(\n (position) => {\n inFlight = false;\n const { latitude, longitude, accuracy } = position.coords;\n if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return;\n const next: GeoFix = { latitude, longitude, source: 'gps' };\n if (Number.isFinite(accuracy)) next.accuracy = accuracy;\n fix = next;\n fixAt = Date.now();\n },\n () => {\n inFlight = false; // denied after all, timed out, or position unavailable — keep quiet\n },\n { enableHighAccuracy: false, maximumAge: MAX_FIX_AGE_MS, timeout: FIX_TIMEOUT_MS }\n );\n } catch {\n inFlight = false;\n }\n}\n\n/**\n * The last known position, or undefined when there is none. A stale fix is returned as-is\n * and a refresh is kicked off for later events — never awaited on the capture path.\n */\nexport function readGeolocation(): GeoFix | undefined {\n // Withdrawn consent also drops the fix in hand, including one an in-flight read delivered late.\n if (!allowed()) fix = null;\n if (!fix) return undefined;\n if (Date.now() - fixAt > MAX_FIX_AGE_MS && permission?.state === 'granted') requestFix();\n return { ...fix };\n}\n\n/** Testing seam: clear the memoised position and permission state. */\nexport function resetGeolocationCache(): void {\n fix = null;\n fixAt = 0;\n primed = false;\n inFlight = false;\n permission = null;\n allowed = () => true;\n}\n","import type { EventContext } from './types';\nimport type { Attribution } from './attribution';\nimport { domainOf, urlBase, type PageTracking } from './page';\nimport { parseUserAgent, readNetwork } from './fingerprint';\nimport { readGeolocation } from './geolocation';\nimport { applyTrackingOptions, type ResolvedTrackingOptions } from './tracking-options';\n\nexport const LIBRARY_NAME = '@depsmith/depsmith-sdk';\nexport const SDK_VERSION = '0.9.2';\n\nexport interface ContextOptions {\n /** Populate fingerprint context (browser/os/device type/network). The device_id itself is\n * stamped on the envelope by the capture sites, not here. Caller enforces privacy gating. */\n fingerprint?: boolean;\n /**\n * Attach the device position (context.location lat/long/accuracy) when one has already\n * been resolved from an already-granted permission. Caller enforces privacy gating.\n */\n geolocation?: boolean;\n /**\n * Host-supplied context, shallow-merged over the derived values (per top-level key).\n * For embedders where the real globals are absent or wrong — notably the Shopify\n * web-pixel sandbox, whose `window.location` points at the sandbox, not the storefront.\n */\n overrides?: Partial<EventContext>;\n /** Per-field context suppression (API_SPEC §12.2). Applied last, after `overrides`. */\n tracking?: ResolvedTrackingOptions;\n /**\n * Attribution state, when the client is tracking it. Supplies `context.campaign` and\n * `context.referrer`. Passed in rather than read from storage here so `buildContext` stays\n * free of storage access on the capture path.\n */\n attribution?: Attribution;\n /**\n * SDK-tracked navigation state (previous page, page counter), merged into `context.page`.\n * Supplied by the client rather than derived here, because only the client sees navigation.\n * A deferred `$page_view` passes the whole block as it stood at its navigation, title updated,\n * so its `url` and `path` stay the navigated page's even if the flush comes after the next one.\n */\n page?: PageTracking | EventContext['page'];\n}\n\n/**\n * Values that cannot change for the life of the document, memoised because buildContext\n * runs on every captured event.\n *\n * `Intl.DateTimeFormat()` is the one that mattered: constructing a formatter just to read\n * `resolvedOptions().timeZone` is far and away the most expensive thing in this function,\n * and it was being done per event on the capture path. Scalars only — the objects below\n * are rebuilt per call so no two events ever share a mutable nested block.\n */\ninterface InvariantContext {\n timezone?: string;\n locale?: string;\n userAgent?: string;\n}\n\nlet invariants: InvariantContext | null = null;\n\nfunction readInvariants(): InvariantContext {\n if (invariants) return invariants;\n const next: InvariantContext = {};\n try {\n next.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n } catch {\n /* no Intl / restricted environment */\n }\n if (typeof navigator !== 'undefined') {\n next.locale = navigator.language;\n next.userAgent = navigator.userAgent;\n }\n invariants = next;\n return next;\n}\n\n/** Testing seam: clear the memoised per-document context. */\nexport function resetContextCache(): void {\n invariants = null;\n}\n\n/** Browser context attached to every event. Guarded for SSR / test environments. */\nexport function buildContext(opts: ContextOptions = {}): EventContext {\n const context: EventContext = {\n library: { name: LIBRARY_NAME, version: SDK_VERSION },\n };\n\n // Per block, not one blanket try. A single `try` around all of these meant a throw in an\n // early block silently abandoned every field after it — so one hostile `window.screen`\n // getter cost locale, timezone, user_agent and the entire fingerprint. Same defect Android's\n // context provider had, in a different shape.\n attempt(() => {\n if (typeof window !== 'undefined' && window.location) {\n const href = window.location.href;\n context.page = {\n url: href,\n path: window.location.pathname,\n referrer: typeof document !== 'undefined' ? document.referrer : undefined,\n title: typeof document !== 'undefined' ? document.title : undefined,\n domain: domainOf(href),\n url_base: urlBase(href),\n // previous_url / previous_type / counter come from the client's PageTracker, which is\n // the only thing that knows the in-app navigation history.\n ...(opts.page ?? {}),\n };\n }\n });\n attempt(() => {\n // Read live rather than memoised: these are plain property accesses with no layout\n // cost, and they do change on a zoom or a monitor switch.\n if (typeof window !== 'undefined' && window.screen) {\n context.screen_size = {\n width: window.screen.width,\n height: window.screen.height,\n density: window.devicePixelRatio,\n };\n }\n });\n attempt(() => {\n const cached = readInvariants();\n if (cached.locale !== undefined) context.locale = cached.locale;\n if (cached.userAgent !== undefined) context.user_agent = cached.userAgent;\n if (cached.timezone !== undefined) context.timezone = cached.timezone;\n });\n attempt(() => {\n // Form factor on EVERY event, not only under fingerprinting. Mobile-vs-desktop is the most\n // common web breakdown there is, and gating it meant most web events could not be split at\n // all. It is derived from the user agent, which is already sent unconditionally a few lines\n // down, so this discloses nothing that was not already on the wire.\n //\n // Written before `enrichFingerprint`, which merges into the same block when it runs and adds\n // manufacturer/model from Client Hints — those stay gated, because they are device detail\n // rather than form factor.\n const { deviceType } = parseUserAgent();\n if (deviceType) context.device = { ...context.device, type: deviceType };\n });\n attempt(() => {\n // Not fingerprint-gated: both blocks are derived from the landing URL and\n // `document.referrer`, neither of which is a device signal.\n if (opts.attribution) {\n const campaign = opts.attribution.campaignBlock();\n if (campaign) context.campaign = campaign;\n const referrer = opts.attribution.referrerBlock();\n if (referrer) context.referrer = referrer;\n }\n });\n attempt(() => {\n if (opts.fingerprint) enrichFingerprint(context);\n });\n attempt(() => {\n // Coordinates only. City/region/country are the collector's, resolved from the request\n // IP and merged over whatever is sent here — see enrich() in the reference collector.\n if (opts.geolocation) {\n const fix = readGeolocation();\n if (fix) context.location = fix;\n }\n });\n\n try {\n if (opts.overrides) {\n for (const [key, value] of Object.entries(opts.overrides)) {\n if (value !== undefined) (context as unknown as Record<string, unknown>)[key] = value;\n }\n context.library = { name: LIBRARY_NAME, version: SDK_VERSION }; // never overridable\n }\n } catch {\n // ignore malformed overrides\n }\n\n // Last, so an embedder's `overrides` cannot resurrect a field the app suppressed. The\n // Shopify pixel supplies page context on every event and would otherwise defeat\n // `page: false`.\n if (opts.tracking) applyTrackingOptions(context, opts.tracking);\n\n return context;\n}\n\n/**\n * Adds parsed browser/os/device attributes and network type.\n *\n * The device fingerprint itself is NOT here — it is the top-level `device_id`, stamped by the\n * capture sites in `depsmith-sdk.ts` from the same `opts.fingerprint` gate that reaches this function.\n */\nfunction enrichFingerprint(context: EventContext): void {\n const { browser, os, deviceType, device: hinted } = parseUserAgent();\n if (browser) context.browser = browser;\n if (os) context.os = os;\n\n // Starts from whatever buildContext already put here (the ungated `type`) so this merges\n // rather than replaces — otherwise enabling fingerprinting would drop the form factor.\n const device: NonNullable<EventContext['device']> = { ...context.device };\n if (deviceType) device.type = deviceType;\n // From UA Client Hints, primed once at init. Absent on non-Chromium and on the first event or\n // two while the hint promise is still in flight — never fabricated.\n if (hinted?.manufacturer) device.manufacturer = hinted.manufacturer;\n if (hinted?.model) device.model = hinted.model;\n // Only when something survived. The block used to be unconditional because `id` always\n // filled it; without that, a user agent that parses to no device type on a non-Chromium\n // browser (so no Client Hints either) would put a bare `device: {}` on every event.\n if (Object.keys(device).length > 0) context.device = device;\n\n const network = readNetwork();\n if (network.type) context.network = { ...context.network, type: network.type };\n}\n\n/** Runs one context block, isolating a failure to that block alone. */\nfunction attempt(fn: () => void): void {\n try {\n fn();\n } catch {\n // context enrichment is best-effort, per block\n }\n}\n\n/** navigator.doNotTrack === '1' (plus legacy vendor locations). */\nexport function dntEnabled(): boolean {\n try {\n if (typeof navigator === 'undefined') return false;\n const nav = navigator as Navigator & { msDoNotTrack?: string };\n const win = (typeof window !== 'undefined' ? window : {}) as Window & { doNotTrack?: string };\n const value = navigator.doNotTrack ?? win.doNotTrack ?? nav.msDoNotTrack;\n return value === '1' || value === 'yes';\n } catch {\n return false;\n }\n}\n","import type { KVStorage } from './queue/storage';\nimport type { ConsentState } from './types';\n\nconst KEY_CONSENT = 'depsmith_consent';\n\n/**\n * Consent state machine: pending | granted | denied (API_SPEC §6).\n * Persisted state from a previous run always wins over config's consentMode.\n * DNT (web) is a non-persistent override that behaves as denied while set.\n */\nexport class ConsentManager {\n private state: ConsentState;\n\n constructor(\n private storage: KVStorage,\n initialMode: 'granted' | 'pending',\n private dntActive: boolean\n ) {\n const persisted = storage.get(KEY_CONSENT) as ConsentState | null;\n this.state =\n persisted === 'granted' || persisted === 'denied' || persisted === 'pending'\n ? persisted\n : initialMode;\n }\n\n private effective(): ConsentState {\n return this.dntActive ? 'denied' : this.state;\n }\n\n /** May this event be captured (persisted locally)? */\n canCapture(): boolean {\n return this.effective() !== 'denied';\n }\n\n /** May queued events be uploaded? */\n canUpload(): boolean {\n return this.effective() === 'granted';\n }\n\n get current(): ConsentState {\n return this.effective();\n }\n\n optIn(): void {\n this.state = 'granted';\n this.storage.set(KEY_CONSENT, 'granted');\n }\n\n optOut(): void {\n this.state = 'denied';\n this.storage.set(KEY_CONSENT, 'denied');\n }\n}\n","/**\n * Deferred work scheduling.\n *\n * Exists so persistence can be moved off the capture task. Writing to `localStorage` is\n * synchronous and blocks the main thread; doing it inside a click handler is what put\n * DepsmithSdk on the critical path of every shopper interaction. Coalescing those writes onto\n * an idle callback keeps the interaction cheap and collapses a burst of events into a\n * single write.\n */\nexport type Scheduler = (fn: () => void) => void;\n\n/**\n * The most a scheduled write may be deferred. Short on purpose: the point is to leave the\n * *current* task, not to wait for genuine idleness. Anything longer widens the window in\n * which a hard crash loses events for no additional performance gain.\n */\nconst IDLE_TIMEOUT_MS = 250;\n\ninterface IdleWindow {\n requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number;\n}\n\n/**\n * Runs `fn` at the next idle moment, or within {@link IDLE_TIMEOUT_MS} at the latest.\n *\n * Falls back to a macrotask where `requestIdleCallback` is absent — Safari below 16.4 and\n * jsdom. The fallback is still correct, just less considerate about when it lands.\n */\nexport const idleScheduler: Scheduler = (fn) => {\n const idle = (globalThis as IdleWindow).requestIdleCallback;\n if (typeof idle === 'function') {\n idle(fn, { timeout: IDLE_TIMEOUT_MS });\n return;\n }\n setTimeout(fn, 0);\n};\n\n/**\n * Runs `fn` immediately, restoring write-through behaviour.\n *\n * The seam tests use to assert persisted state without pumping timers, and the escape\n * hatch for any host that needs durability over latency.\n */\nexport const syncScheduler: Scheduler = (fn) => fn();\n","import type { KVStorage } from './storage';\nimport type { Logger } from '../utils/logger';\nimport type { DepsmithSdkEvent } from '../types';\nimport { idleScheduler, type Scheduler } from '../utils/scheduler';\n\nexport const KEY_QUEUE = 'depsmith_queue';\n\n/**\n * Ceiling on the serialised queue, in UTF-16 code units.\n *\n * `maxSize` alone bounds the queue by *count*, which says nothing about the bytes on disk:\n * 1000 events at ~700 chars each is ~700 KB of a 5 MB origin-shared `localStorage` budget\n * that the host page and every other script on the origin also draw on. It is also what\n * sets the worst case for the serialise-on-write below, so capping it bounds both.\n *\n * Code units rather than bytes because that is the unit browsers actually meter\n * `localStorage` quota in, and it needs no encoding pass to measure.\n */\nconst DEFAULT_MAX_CHARS = 512 * 1024;\n\n/** `[` + `]` — the serialised length of an empty queue. */\nconst BRACKETS = 2;\n\n/**\n * Event types evicted LAST, because losing one is not proportional to losing an event.\n *\n * An ordinary event dropped under queue pressure costs that event. A dropped `$identify`\n * costs every anonymous event that came before it, forever: it carries the only edge binding\n * `anonymous_id` to `user_id` (API_SPEC §4.1), the SDK never re-emits it unless the app calls\n * `identify()` again, and a collector resolving history has nothing to join on. `$alias` and\n * `$group` are the same shape — an explicit, one-shot statement about identity.\n *\n * This mirrors the sampling exemption one layer up (`inSample` in depsmith-sdk.ts), and for exactly\n * the same reason. Sampling already refuses to drop these; the queue was still free to.\n */\nconst IDENTITY_EVENT_TYPES = new Set(['identify', 'alias', 'group']);\n\n/** A malformed restored entry has no event_type and is treated as ordinary — safe default. */\nfunction isIdentityEvent(event: DepsmithSdkEvent): boolean {\n return IDENTITY_EVENT_TYPES.has(event?.event_type);\n}\n\nexport interface EventQueueOptions {\n /** Serialised-size ceiling in UTF-16 code units. Defaults to 512 Ki. */\n maxChars?: number;\n /**\n * How a persist is deferred. Defaults to an idle callback; tests and hosts that need\n * write-through pass `syncScheduler`.\n */\n schedule?: Scheduler;\n}\n\n/**\n * Persist-before-send event queue (API_SPEC §1, §8). In-memory mirror with\n * **write-behind** persistence; corrupt entries are discarded individually on load.\n *\n * Persistence is coalesced onto an idle callback rather than written through on every\n * mutation. `localStorage.setItem` is a synchronous main-thread call and the value is the\n * whole queue, so writing through meant every captured event paid an O(queue) serialise\n * plus a blocking write — inside the click handler that captured it.\n *\n * The durability cost is one idle tick: only a hard crash inside that window loses events.\n * Ordinary teardown is covered because the client force-flushes via {@link persistNow} on\n * `pagehide`, and privacy-critical paths (`clear`) write through unconditionally.\n *\n * The byte ceiling is enforced where events ENTER the queue, never inside a persist.\n * Trimming during `persistNow()` would mutate the queue from a call the uploader makes\n * between `peek()` and the network send, so an over-budget queue could discard the very\n * events that were in flight. Sizes are tracked incrementally instead, which also means\n * enforcing the cap costs no re-serialise at all.\n */\nexport class EventQueue {\n protected events: DepsmithSdkEvent[] = [];\n /** Serialised length of each entry in `events`, same order, same length. */\n private sizes: number[] = [];\n /** Running sum of `sizes`, so the budget check touches no JSON. */\n private sizeSum = 0;\n protected maxChars: number;\n private schedule: Scheduler;\n /** Set when `events` has diverged from what is on disk. */\n protected dirty = false;\n /** Set between scheduling a write and it running, so a burst schedules only one. */\n private scheduled = false;\n\n constructor(\n protected storage: KVStorage,\n protected maxSize: number,\n private logger: Logger,\n options: EventQueueOptions = {}\n ) {\n this.maxChars = options.maxChars ?? DEFAULT_MAX_CHARS;\n this.schedule = options.schedule ?? idleScheduler;\n this.restore();\n }\n\n private restore(): void {\n try {\n const raw = this.storage.get(KEY_QUEUE);\n if (!raw) return;\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) return;\n const kept = parsed.filter(\n (e): e is DepsmithSdkEvent =>\n !!e && typeof e === 'object' && typeof (e as DepsmithSdkEvent).event_id === 'string'\n );\n this.reset(kept);\n if (kept.length !== parsed.length) {\n this.logger.warn('discarded corrupt queued events on restore');\n this.markDirty();\n }\n // A ceiling lowered between sessions, or a record written by an older build, can\n // leave a restored queue over budget.\n if (this.trimToBudget()) this.markDirty();\n } catch {\n this.logger.warn('queue storage corrupt; starting empty');\n this.reset([]);\n this.storage.remove(KEY_QUEUE);\n }\n }\n\n /** Replaces the queue and rebuilds the size index in one pass. */\n private reset(events: DepsmithSdkEvent[]): void {\n this.events = events;\n this.sizes = events.map((e) => measure(e));\n this.sizeSum = this.sizes.reduce((a, b) => a + b, 0);\n }\n\n /**\n * Exact length of `JSON.stringify(this.events)` without building it: every entry, plus\n * one comma between each pair, plus the brackets.\n */\n protected serializedLength(): number {\n if (this.events.length === 0) return BRACKETS;\n return this.sizeSum + (this.events.length - 1) + BRACKETS;\n }\n\n /**\n * Drops events until the queue fits `maxChars`. Returns whether it dropped any.\n *\n * Identity events go last here too. This is the second eviction path, and protecting only\n * the count cap would have left the merge edge just as droppable — a queue of big events\n * hits the byte ceiling long before the count one.\n */\n private trimToBudget(): boolean {\n let dropped = 0;\n while (this.events.length > 0 && this.serializedLength() > this.maxChars) {\n this.evictAt(this.victimIndex());\n dropped++;\n }\n if (dropped > 0) {\n this.logger.warn(`queue byte cap reached; dropped ${dropped} event(s)`);\n }\n return dropped > 0;\n }\n\n /** Marks the queue for persistence and schedules a single coalesced write. */\n private markDirty(): void {\n this.dirty = true;\n if (this.scheduled) return;\n this.scheduled = true;\n this.schedule(() => {\n this.scheduled = false;\n this.persistNow();\n });\n }\n\n /**\n * Writes immediately, if there is anything to write.\n *\n * Called on `pagehide`, `shutdown()`, and by the uploader before each batch leaves — the\n * points where deferring any further would mean losing the events outright. Idempotent\n * and cheap when the queue is clean, and never mutates the queue: the budget is already\n * enforced at enqueue, so what is in memory is by construction writable.\n */\n persistNow(): void {\n if (!this.dirty) return;\n this.dirty = false;\n this.storage.set(KEY_QUEUE, JSON.stringify(this.events));\n }\n\n /**\n * Prepend OLDER events recovered after async storage hydration (IndexedDB).\n * Dedupes by event_id; cap still drops oldest first.\n */\n prepend(events: DepsmithSdkEvent[]): void {\n const existing = new Set(this.events.map((e) => e.event_id));\n const fresh = events.filter(\n (e): e is DepsmithSdkEvent =>\n !!e && typeof e === 'object' && typeof e.event_id === 'string' && !existing.has(e.event_id)\n );\n if (fresh.length === 0) return;\n this.reset([...fresh, ...this.events]);\n if (this.events.length > this.maxSize) {\n this.dropOldest(this.events.length - this.maxSize);\n }\n this.trimToBudget();\n this.markDirty();\n }\n\n enqueue(event: DepsmithSdkEvent): void {\n const size = measure(event);\n // Rejected rather than admitted and then trimmed around. Admitting it would evict the\n // whole rest of the queue on the way to discovering it still does not fit, so one\n // bloated event would take every good one with it.\n if (size + BRACKETS > this.maxChars) {\n this.logger.warn(`event ${event.event_id} exceeds the queue byte cap; dropped`);\n return;\n }\n this.events.push(event);\n this.sizes.push(size);\n this.sizeSum += size;\n if (this.events.length > this.maxSize) {\n const dropped = this.events.length - this.maxSize;\n this.dropOldest(dropped);\n this.logger.warn(`queue cap reached; dropped ${dropped} event(s)`);\n }\n this.trimToBudget();\n this.markDirty();\n }\n\n /**\n * Index of the next event to evict: the oldest NON-identity event, else the oldest event.\n *\n * The fallback matters — a queue holding nothing but identity events must still be\n * evictable, or the cap stops being a cap and both loops here stop terminating.\n *\n * Linear, but it returns 0 on the first comparison in the ordinary case (the oldest event\n * is not an identity event), so the scan only walks as far as the identity events actually\n * queued ahead of it.\n */\n private victimIndex(): number {\n for (let i = 0; i < this.events.length; i++) {\n if (!isIdentityEvent(this.events[i]!)) return i;\n }\n return 0;\n }\n\n /** Removes entry `index`, keeping the size index and running sum in step. */\n private evictAt(index: number): void {\n this.events.splice(index, 1);\n this.sizeSum -= this.sizes.splice(index, 1)[0] ?? 0;\n }\n\n /**\n * Removes `count` entries, identity events last. Relative order of survivors is preserved.\n *\n * Named for the policy rather than the mechanism: this is no longer strictly drop-oldest,\n * and a caller that wants FIFO regardless does not exist.\n */\n private dropOldest(count: number): void {\n for (let n = 0; n < count && this.events.length > 0; n++) {\n this.evictAt(this.victimIndex());\n }\n }\n\n get size(): number {\n return this.events.length;\n }\n\n /**\n * Oldest-first view for uploading, from index `from`: up to `count` events whose serialised\n * size (plus a comma each) stays within `maxChars` — but always at least one, so an event\n * larger than the budget still leaves on its own instead of wedging the head. Does not remove.\n */\n peek(count: number, maxChars = Infinity, from = 0): DepsmithSdkEvent[] {\n let end = from;\n for (let total = 0; end < this.events.length && end - from < count; end++) {\n total += this.sizes[end]! + 1;\n if (end > from && total > maxChars) break;\n }\n return this.events.slice(from, end);\n }\n\n /** Remove uploaded (or poison) events by id. */\n remove(eventIds: string[]): void {\n const ids = new Set(eventIds);\n const events: DepsmithSdkEvent[] = [];\n const sizes: number[] = [];\n let sizeSum = 0;\n for (let i = 0; i < this.events.length; i++) {\n const event = this.events[i]!;\n if (ids.has(event.event_id)) continue;\n const size = this.sizes[i]!;\n events.push(event);\n sizes.push(size);\n sizeSum += size;\n }\n this.events = events;\n this.sizes = sizes;\n this.sizeSum = sizeSum;\n this.markDirty();\n }\n\n /** Releases anything held for the page's lifetime. Nothing here; see `tab-queue.ts`. */\n close(): void {}\n\n /**\n * Empties the queue and storage immediately.\n *\n * Write-through on purpose: this is the opt-out path, and a deferred delete would leave\n * a withdrawn visitor's events sitting on disk for an idle tick.\n */\n clear(): void {\n this.reset([]);\n this.dirty = false;\n this.storage.remove(KEY_QUEUE);\n }\n}\n\n/** Serialised length of one event — what it will contribute to the persisted array. */\nfunction measure(event: DepsmithSdkEvent): number {\n return JSON.stringify(event).length;\n}\n","/** The millisecond the counter below belongs to, and its value there. */\nlet lastMs = -1;\nlet lastSeq = 0;\n\n/** 26 bits: `rand_a` (12) plus the first 14 bits of `rand_b`. */\nconst SEQ_MASK = 0x3ffffff;\n\n/**\n * RFC 9562 UUID v7: 48-bit unix-ms timestamp, a 26-bit counter, 48 random bits.\n *\n * Time-ordered, so `event_id` doubles as a capture-order tiebreaker — which needs the counter.\n * With every non-timestamp bit random, two ids minted in the same millisecond sorted in a random\n * order, and that is the ordinary case rather than a rare one: `$session_start` and the event\n * that opened the session, `$web_vitals` and `$page_leave` at unload, any burst of `track()`.\n *\n * So ids minted for the same `now` count up (RFC 9562 §6.2 method 1, a fixed-length dedicated\n * counter). The counter is re-seeded at random for each new millisecond with its top bit clear,\n * leaving 2^25 increments before it could wrap; it sits in `rand_a` and the head of `rand_b`, so\n * plain string comparison of two ids gives capture order.\n *\n * The timestamp is always exactly `now`, never nudged forward: `session_started_at` is read back\n * out of a session id (see {@link uuidv7ToMs}). A `now` EARLIER than the last one — a deferred\n * `$page_view` stamped at its navigation — gets a fresh random counter and leaves the running one\n * alone, so the ids around it stay ordered. Monotonic per page, not across tabs.\n */\nexport function uuidv7(now: number): string {\n const bytes = new Uint8Array(16);\n if (typeof crypto !== 'undefined' && crypto.getRandomValues) {\n crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n\n // 48-bit big-endian timestamp\n bytes[0] = (now / 2 ** 40) & 0xff;\n bytes[1] = (now / 2 ** 32) & 0xff;\n bytes[2] = (now / 2 ** 24) & 0xff;\n bytes[3] = (now / 2 ** 16) & 0xff;\n bytes[4] = (now / 2 ** 8) & 0xff;\n bytes[5] = now & 0xff;\n\n // 25 random bits, from the positions the counter is written back to.\n let seq = ((bytes[6]! & 0x07) << 22) | (bytes[7]! << 14) | ((bytes[8]! & 0x3f) << 8) | bytes[9]!;\n if (now === lastMs) {\n seq = lastSeq = (lastSeq + 1) & SEQ_MASK;\n } else if (now > lastMs) {\n lastMs = now;\n lastSeq = seq;\n }\n bytes[6] = 0x70 | (seq >>> 22); // version 7 + counter bits 25..22\n bytes[7] = (seq >>> 14) & 0xff;\n bytes[8] = 0x80 | ((seq >>> 8) & 0x3f); // variant 10 + counter bits 13..8\n bytes[9] = seq & 0xff;\n\n let hex = '';\n for (let i = 0; i < 16; i++) hex += (bytes[i]! + 0x100).toString(16).slice(1);\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/**\n * Recover the creation time from a UUID v7 — the first 48 bits are the unix-ms timestamp.\n *\n * This is what makes `session_started_at` free to add: a session already persisted in the\n * field has no stored start time, but its id *is* one. So there is no backfill, no lossy\n * default and no storage format version — old records decode exactly.\n *\n * Returns null if the string isn't a v7 uuid, so a caller can fall back rather than\n * silently trusting a garbage timestamp.\n */\nexport function uuidv7ToMs(id: string): number | null {\n if (!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id)) {\n return null;\n }\n const hex = id.slice(0, 8) + id.slice(9, 13); // first 48 bits, dashes removed\n const ms = parseInt(hex, 16);\n return Number.isFinite(ms) ? ms : null;\n}\n","import { uuidv7ToMs } from '../utils/uuidv7';\n\n/**\n * Key-value storage abstraction. localStorage when available (synchronous — safe to\n * write during pagehide), in-memory fallback for SSR / privacy modes that block storage.\n */\nexport interface KVStorage {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n}\n\nexport const DEPSMITH_SDK_STORAGE_KEYS = [\n 'depsmith_anonymous_id',\n 'depsmith_anon_reset_at',\n 'depsmith_user_id',\n 'depsmith_group_id',\n 'depsmith_user_props',\n 'depsmith_session',\n 'depsmith_consent',\n 'depsmith_queue',\n 'depsmith_config_fp',\n 'depsmith_net_breaker',\n 'depsmith_campaign',\n 'depsmith_referrer',\n 'depsmith_super_props',\n] as const;\n\nexport class MemoryAdapter implements KVStorage {\n private data = new Map<string, string>();\n\n get(key: string): string | null {\n return this.data.get(key) ?? null;\n }\n\n set(key: string, value: string): void {\n this.data.set(key, value);\n }\n\n remove(key: string): void {\n this.data.delete(key);\n }\n}\n\n/**\n * First-party cookie storage.\n *\n * `domain` is optional. With one, the cookie is shared across subdomains (the `cookieDomain`\n * config). Without one the browser sets a host-only cookie, which is what the identity mirror\n * wants: same origin, no widening of scope, and no configuration required to get a second copy\n * of the device identity.\n */\nexport class CookieAdapter implements KVStorage {\n constructor(private domain?: string) {}\n\n get(key: string): string | null {\n try {\n const prefix = `${encodeURIComponent(key)}=`;\n for (const part of document.cookie.split('; ')) {\n if (part.startsWith(prefix)) return decodeURIComponent(part.slice(prefix.length));\n }\n } catch {\n /* no document / cookies blocked */\n }\n return null;\n }\n\n private attributes(maxAge: number): string {\n // 400 days is the ceiling Chrome clamps cookie lifetime to, so asking for more is silently\n // truncated and just misrepresents the intent.\n const domain = this.domain ? `; domain=${this.domain}` : '';\n // Secure is required for SameSite=None and harmless on https; omitted on http so local\n // development over plain HTTP still works.\n const secure =\n typeof location !== 'undefined' && location.protocol === 'https:' ? '; Secure' : '';\n return `${domain}; path=/; max-age=${maxAge}; SameSite=Lax${secure}`;\n }\n\n set(key: string, value: string): void {\n try {\n const maxAge = 60 * 60 * 24 * 400;\n document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}${this.attributes(maxAge)}`;\n } catch {\n /* ignore */\n }\n }\n\n remove(key: string): void {\n try {\n document.cookie = `${encodeURIComponent(key)}=${this.attributes(0)}`;\n } catch {\n /* ignore */\n }\n }\n}\n\n/**\n * When `reset()` last rotated the anonymous id, epoch ms. Written by `IdentityManager.reset()`\n * and mirrored with the id it retires — see the conflict rule in {@link RedundantAdapter}.\n */\nexport const KEY_ANON_RESET = 'depsmith_anon_reset_at';\n\n/**\n * Keys mirrored across both identity stores.\n *\n * `depsmith_anonymous_id` and the reset marker that travels with it. The id is the device\n * identity — the thing whose loss makes a returning visitor look new — and it is always a\n * UUIDv7, which is what makes the conflict rule below well-defined. `depsmith_user_id` and\n * `depsmith_group_id` are deliberately NOT mirrored: they are caller-supplied values the app\n * re-establishes by calling identify() again after login, so copying them into a cookie would\n * widen PII exposure to buy nothing. `depsmith_user_props` is unbounded and would not fit a\n * 4 KB cookie anyway.\n */\nexport const MIRRORED_IDENTITY_KEYS: ReadonlySet<string> = new Set([\n 'depsmith_anonymous_id',\n KEY_ANON_RESET,\n]);\n\n/**\n * Two stores holding one identity: read from either, write to both, and heal whichever lost it.\n *\n * localStorage and cookies are cleared by different user actions and different browser policies —\n * \"clear site data\" takes both, but a cookie-only purge, an ITP eviction, or a storage quota\n * reset takes one. Keeping the device identity in both means it survives losing either, which is\n * the entire point: a returning visitor stays the same visitor.\n *\n * Two copies, not five. Adding IndexedDB, the Cache API and ETag redundancy on top is evercookie\n * behaviour — it defeats deletion rather than tolerating partial loss, and it is out of scope.\n * Both of these are ordinary first-party stores the user can clear, and clearing both works.\n */\nexport class RedundantAdapter implements KVStorage {\n constructor(\n private primary: KVStorage,\n private secondary: KVStorage,\n private mirrored: ReadonlySet<string> = MIRRORED_IDENTITY_KEYS\n ) {}\n\n get(key: string): string | null {\n const fromPrimary = this.primary.get(key);\n if (!this.mirrored.has(key)) return fromPrimary;\n\n const fromSecondary = this.secondary.get(key);\n if (fromPrimary === fromSecondary) return fromPrimary;\n\n // One store lost it — restore from the other. This is the healing case that makes a\n // partial clear survivable rather than merely detectable.\n if (fromPrimary === null && fromSecondary !== null) {\n this.primary.set(key, fromSecondary);\n return fromSecondary;\n }\n if (fromSecondary === null && fromPrimary !== null) {\n this.secondary.set(key, fromPrimary);\n return fromPrimary;\n }\n\n const winner = this.pick(fromPrimary!, fromSecondary!);\n this.primary.set(key, winner);\n this.secondary.set(key, winner);\n return winner;\n }\n\n /**\n * Both stores hold an id and they disagree.\n *\n * Prefer the OLDER one: without a `reset()`, a newer id can only have been minted after a\n * store was cleared, so the older is the device's original identity and keeps the visitor\n * continuous. UUIDv7 is time-ordered, so \"older\" is readable from the value itself. Falls\n * back to the primary for a non-v7 value.\n *\n * **Unless `reset()` retired it.** `reset()` deliberately mints a newer id, and with\n * `cookieDomain` the cookie is shared by subdomains whose localStorage is not: log out on\n * app.example.com, visit www.example.com, and older-wins read www's stale id back into the\n * shared cookie — the next person on that browser inherited the previous user's anonymous_id,\n * the cross-user merge `reset()` exists to prevent (API_SPEC §4.1). So `reset()` records when\n * it ran, and an id minted before that moment has been retired and loses to one that was not.\n * The marker is taken from whichever store has the later one and written to both, so it\n * reaches the stores that never saw the reset together with the id it protects.\n */\n private pick(a: string, b: string): string {\n // `a` is the primary's. Short names on purpose: the pixel build ships this unminified.\n const aMs = uuidv7ToMs(a);\n const bMs = uuidv7ToMs(b);\n if (aMs === null || bMs === null) return a;\n const stores = [this.primary, this.secondary];\n const at = Math.max(...stores.map((s) => Number(s.get(KEY_ANON_RESET)) || 0));\n if (at) stores.forEach((s) => s.set(KEY_ANON_RESET, `${at}`));\n // \"Live\": minted at or after the last reset.\n const live = aMs >= at;\n if (live !== bMs >= at) return live ? a : b;\n return aMs <= bMs ? a : b;\n }\n\n set(key: string, value: string): void {\n this.primary.set(key, value);\n if (this.mirrored.has(key)) this.secondary.set(key, value);\n }\n\n remove(key: string): void {\n this.primary.remove(key);\n // Unconditional: a key that stopped being mirrored must still be cleared from the store it\n // used to live in, or reset() would leave a copy behind for get() to heal back into place.\n this.secondary.remove(key);\n }\n}\n\n/**\n * Minimal async key-value backend. Shaped to accept Shopify's `browser.localStorage`\n * / `browser.sessionStorage` directly (all methods Promise-returning, proxied to the\n * top frame from the web-pixel sandbox).\n */\nexport interface AsyncKV {\n getItem(key: string): Promise<string | null | undefined>;\n setItem(key: string, value: string): Promise<unknown>;\n removeItem(key: string): Promise<unknown>;\n}\n\n/**\n * Synchronous `KVStorage` over an asynchronous backend: an in-memory mirror serves\n * reads, writes go through to the mirror and are flushed write-behind.\n *\n * `hydrate()` must be awaited **before** constructing a DepsmithSdkClient over this\n * adapter — IdentityManager/SessionManager/EventQueue all read in their constructors,\n * and a cold mirror would mint a fresh anonymousId over a returning visitor's.\n */\nexport class AsyncMirrorAdapter implements KVStorage {\n private mirror = new Map<string, string>();\n private hydrated: Promise<void> | null = null;\n\n constructor(\n private backend: AsyncKV,\n private keys: readonly string[] = DEPSMITH_SDK_STORAGE_KEYS\n ) {}\n\n /** Bulk-loads `keys` into the mirror. Idempotent; never rejects. */\n hydrate(): Promise<void> {\n this.hydrated ??= Promise.all(\n this.keys.map(async (key) => {\n try {\n const value = await this.backend.getItem(key);\n // Don't clobber values written before hydration resolved.\n if (typeof value === 'string' && !this.mirror.has(key)) this.mirror.set(key, value);\n } catch {\n /* degrade to memory-only for this key */\n }\n })\n ).then(() => undefined);\n return this.hydrated;\n }\n\n get(key: string): string | null {\n return this.mirror.get(key) ?? null;\n }\n\n set(key: string, value: string): void {\n this.mirror.set(key, value);\n void Promise.resolve(this.backend.setItem(key, value)).catch(() => {\n /* quota / sandbox teardown — mirror still serves reads */\n });\n }\n\n remove(key: string): void {\n this.mirror.delete(key);\n void Promise.resolve(this.backend.removeItem(key)).catch(() => {\n /* ignore */\n });\n }\n}\n","import type { DepsmithSdkEvent } from '../types';\nimport type { Logger } from '../utils/logger';\nimport { MemoryAdapter, type KVStorage } from './storage';\n\n/**\n * The browser-storage backends the SDK picks for itself: localStorage and IndexedDB.\n *\n * Split out of `storage.ts` so the Shopify custom-pixel build can compile them away. That build\n * ALWAYS injects its own `AsyncMirrorAdapter` over the sandbox's async storage, so `defaultStorage()`\n * is never called and neither adapter can execute — yet the build is deliberately unminified, so both\n * shipped anyway, against an editor that refuses to save a file over 64,000 characters.\n *\n * Everything still reachable in that build — MemoryAdapter, CookieAdapter, RedundantAdapter,\n * AsyncMirrorAdapter — stays in `storage.ts`, which is why this is a split rather than a swap of the\n * whole module.\n */\n/**\n * Every key DepsmithSdk persists. Single source of truth for hosts that must enumerate\n * them up front — e.g. `AsyncMirrorAdapter`, whose backend has no bulk read.\n * Kept in sync with the `KEY_*` consts in identity/session/consent/queue/depsmith-sdk/breaker.\n */\nexport class LocalStorageAdapter implements KVStorage {\n /** `ls` is public so the cross-tab queue can match `StorageEvent.storageArea` against it. */\n constructor(readonly ls: Storage) {}\n\n get(key: string): string | null {\n try {\n return this.ls.getItem(key);\n } catch {\n return null;\n }\n }\n\n set(key: string, value: string): void {\n try {\n this.ls.setItem(key, value);\n } catch {\n // quota exceeded / private mode — silently degrade\n }\n }\n\n remove(key: string): void {\n try {\n this.ls.removeItem(key);\n } catch {\n /* ignore */\n }\n }\n}\n\n/**\n * IndexedDB-backed storage: in-memory write-through mirror with async write-behind\n * persistence. Reads are synchronous against the mirror; `hydrate()` must be awaited\n * before trusting reads for pre-existing data (DepsmithSdkClient gates uploads on it).\n */\nexport class IndexedDBAdapter implements KVStorage {\n private mirror = new Map<string, string>();\n private snapshot = new Map<string, string>();\n private db: IDBDatabase | null = null;\n private ready: Promise<void>;\n\n constructor(dbName = 'depsmith-sdk') {\n this.ready = this.open(dbName);\n }\n\n private open(dbName: string): Promise<void> {\n return new Promise((resolve) => {\n try {\n const request = indexedDB.open(dbName, 1);\n request.onupgradeneeded = () => request.result.createObjectStore('kv');\n request.onsuccess = () => {\n this.db = request.result;\n const tx = this.db.transaction('kv', 'readonly').objectStore('kv');\n const keysReq = tx.getAllKeys();\n const valuesReq = tx.getAll();\n valuesReq.onsuccess = () => {\n const keys = keysReq.result as string[];\n (valuesReq.result as string[]).forEach((value, i) => {\n const key = keys[i];\n if (key === undefined) return;\n this.snapshot.set(key, value);\n // hydrate without clobbering values written before hydration completed\n if (!this.mirror.has(key)) this.mirror.set(key, value);\n });\n resolve();\n };\n valuesReq.onerror = () => resolve();\n };\n request.onerror = () => resolve(); // degrade to memory-only\n } catch {\n resolve();\n }\n });\n }\n\n /**\n * Resolves with the persisted snapshot once loaded. Keys written before hydration\n * are NOT overwritten in the mirror — the caller merges conflicts (e.g. the queue\n * prepends persisted events to ones captured during startup).\n */\n hydrate(): Promise<ReadonlyMap<string, string>> {\n return this.ready.then(() => this.snapshot);\n }\n\n get(key: string): string | null {\n return this.mirror.get(key) ?? null;\n }\n\n set(key: string, value: string): void {\n this.mirror.set(key, value);\n void this.ready.then(() => {\n try {\n this.db?.transaction('kv', 'readwrite').objectStore('kv').put(value, key);\n } catch {\n /* quota / closing — mirror still serves reads */\n }\n });\n }\n\n remove(key: string): void {\n this.mirror.delete(key);\n void this.ready.then(() => {\n try {\n this.db?.transaction('kv', 'readwrite').objectStore('kv').delete(key);\n } catch {\n /* ignore */\n }\n });\n }\n}\n\n/** Picks localStorage if usable, else memory. */\nexport function defaultStorage(): KVStorage {\n try {\n if (typeof window !== 'undefined' && window.localStorage) {\n const probe = '__depsmith_probe__';\n window.localStorage.setItem(probe, '1');\n window.localStorage.removeItem(probe);\n return new LocalStorageAdapter(window.localStorage);\n }\n } catch {\n /* fall through */\n }\n return new MemoryAdapter();\n}\n\n/** The queue's store: IndexedDB when `storage: 'indexeddb'` asks for it and it exists, else `fallback`. */\nexport function pickQueueStorage(mode: string | undefined, fallback: KVStorage): KVStorage {\n return mode === 'indexeddb' && typeof indexedDB !== 'undefined' ? new IndexedDBAdapter() : fallback;\n}\n\n/**\n * Merges the events IndexedDB persisted on a previous page back into the queue, once they\n * have loaded. Resolves immediately for any other store. Uploads wait on the returned promise.\n *\n * Lives here rather than in the client because it is IndexedDB-only, and the Shopify pixel\n * build swaps this whole module out.\n */\nexport function hydrateQueue(\n queueStorage: KVStorage,\n storage: KVStorage,\n consent: { canCapture(): boolean; optOut(): void },\n queue: { clear(): void; prepend(events: DepsmithSdkEvent[]): void },\n drifted: boolean,\n logger: Logger\n): Promise<void> {\n if (!(queueStorage instanceof IndexedDBAdapter)) return Promise.resolve();\n return queueStorage.hydrate().then((persisted) => {\n try {\n // Builds before this one kept consent in IndexedDB as well. An opt-out recorded there\n // must still be honoured the first time this build runs.\n const KEY = 'depsmith_consent';\n if (persisted.get(KEY) === 'denied' && !storage.get(KEY)) consent.optOut();\n // The persisted events are only merged back for a visitor who may still be tracked and\n // a project they still belong to. Otherwise an opt-out (now, or between init and this\n // callback) or an apiKey change would be undone by the queue it had just cleared.\n if (drifted || !consent.canCapture()) {\n queue.clear();\n return;\n }\n const raw = persisted.get('depsmith_queue');\n if (raw) queue.prepend(JSON.parse(raw) as DepsmithSdkEvent[]);\n } catch {\n logger.warn('persisted queue corrupt; discarded');\n }\n });\n}\n","import type { DepsmithSdkEvent } from '../types';\nimport { EventQueue as BaseQueue, KEY_QUEUE } from './queue';\nimport { LocalStorageAdapter } from './storage-local';\n\n/** The event ids in a stored queue value, or null if it is not a readable array. */\nfunction storedEvents(raw: string | null): DepsmithSdkEvent[] | null {\n try {\n const parsed: unknown = JSON.parse(raw || '[]');\n if (!Array.isArray(parsed)) return null;\n return parsed.filter(\n (e): e is DepsmithSdkEvent =>\n !!e && typeof e === 'object' && typeof (e as DepsmithSdkEvent).event_id === 'string'\n );\n } catch {\n return null;\n }\n}\n\n/**\n * The event queue as the browser builds use it: one storage key shared by every open tab.\n *\n * {@link BaseQueue} treats that key as its own — it restores the array once and then\n * overwrites it with its in-memory copy. With two tabs open that lost and duplicated events\n * (deep-dive WC-03):\n * - **loss** — tab B's write replaced tab A's persisted events; A was not dirty, so it never\n * wrote them back, and closing A dropped them. Worst under `pending` consent or offline,\n * where events sit in storage for a long time;\n * - **resurrection** — a tab that had restored events another tab later uploaded wrote them\n * back on its next persist, and they were sent again on the next page load.\n *\n * Two rules fix both, with no locks and no change to the stored format:\n *\n * 1. **A write merges instead of overwriting.** Entries in storage that this tab has never\n * held belong to another tab and are written back untouched. Entries this tab DID hold and\n * no longer does were uploaded (or evicted) here, so they are left out.\n * 2. **A removal in another tab is followed here.** The `storage` event carries the new value;\n * any event this tab knew to be in storage and that is now gone was removed by its other\n * holder, so it is dropped from memory too rather than written back or sent again.\n *\n * Nothing foreign is ever adopted mid-page: another tab's events are that tab's to send, and if\n * it closes first they are restored by the next page load, exactly as before.\n *\n * What this does not do: two tabs holding the same restored events can still upload them at\n * the same moment — delivery is at-least-once (API_SPEC §10). The window is now the length of\n * one upload rather than \"always\".\n *\n * Scope: localStorage only. With `storage: 'indexeddb'` each tab reads its own in-memory mirror,\n * which other tabs' writes never reach, so the merge sees no foreign events and the last tab\n * to write still wins — the pre-WC-03 behaviour, for that opt-in mode. Closing it needs the\n * read-merge-write inside one IndexedDB transaction; tracked as a follow-up.\n *\n * A separate class because the Shopify custom-pixel bundle has one sandbox, no `storage`\n * events and a 64,000-character ceiling; that build resolves this module to the plain queue\n * (see `tab-queue.noop.ts` and `tsup.config.ts`).\n */\nexport class EventQueue extends BaseQueue {\n /** Ids this tab holds and has seen in storage — restored from it, or written to it. */\n private known = new Set<string>(this.ids());\n /**\n * Ids this tab held and removed (uploaded, evicted, or removed by another tab), kept while a\n * copy may still be in storage. Without them a stale copy — written by a tab that had not yet\n * seen the removal, or left behind by a write that failed on quota — reads as another tab's\n * event and is written back, to be sent again on the next page load.\n */\n private removed = new Set<string>();\n\n /** The `Storage` this queue persists to, when that is `localStorage`; else null. */\n private area: Storage | null = null;\n\n private onStorage = (event: StorageEvent): void => {\n // Only this queue's key in this queue's store. A `clear()` (key null) is not a removal by\n // another holder — nobody uploaded those events — so it is ignored: the next persist here\n // writes this tab's events back. An opt-out elsewhere removes KEY_QUEUE and IS followed.\n if (event.key !== KEY_QUEUE || event.storageArea !== this.area) return;\n const stored = storedEvents(event.newValue);\n if (!stored) return;\n const present = new Set<string>();\n for (const e of stored) present.add(e.event_id);\n const gone: string[] = [];\n this.known.forEach((id) => {\n if (!present.has(id)) gone.push(id);\n });\n if (gone.length === 0) return;\n for (const id of gone) {\n this.known.delete(id);\n this.removed.add(id);\n }\n this.remove(gone);\n };\n\n constructor(...args: ConstructorParameters<typeof BaseQueue>) {\n super(...args);\n // `storage` events only ever describe localStorage/sessionStorage. A memory- or\n // IndexedDB-backed queue shares nothing with other tabs, so it must not listen: another\n // tab's localStorage queue would otherwise read as removals from this one.\n if (!(this.storage instanceof LocalStorageAdapter)) return;\n this.area = this.storage.ls;\n try {\n if (typeof window !== 'undefined') window.addEventListener('storage', this.onStorage);\n } catch {\n /* no storage events here — the merge-on-write half still applies */\n }\n }\n\n private ids(): string[] {\n return this.events.map((e) => e.event_id);\n }\n\n override persistNow(): void {\n if (!this.dirty) return;\n this.dirty = false;\n const mine = new Set(this.ids());\n // Known-but-not-mine: I held it and removed it, so it must not come back.\n this.known.forEach((id) => {\n if (!mine.has(id)) this.removed.add(id);\n });\n const foreign: DepsmithSdkEvent[] = [];\n const present = new Set<string>();\n for (const e of storedEvents(this.storage.get(KEY_QUEUE)) ?? []) {\n present.add(e.event_id);\n // Not mine and never removed here: another tab's.\n if (!mine.has(e.event_id) && !this.removed.has(e.event_id)) foreign.push(e);\n }\n this.storage.set(KEY_QUEUE, JSON.stringify(this.bounded(foreign).concat(this.events)));\n this.known = mine;\n // A tombstone is needed only while some copy is still stored; this keeps the set bounded\n // by the stored queue rather than growing for the life of the page.\n this.removed.forEach((id) => {\n if (!present.has(id)) this.removed.delete(id);\n });\n }\n\n /**\n * The oldest-first tail of `foreign` that fits beside this tab's events within the queue's\n * count and character caps. This tab's own events are bounded at enqueue; the merge must not\n * let N tabs together exceed what one queue may store, or the write fails on quota and every\n * tab's events are lost with it. Evicting a foreign entry here is what the cap would have done\n * in its own tab: the owner sees it gone from storage and drops it.\n */\n private bounded(foreign: DepsmithSdkEvent[]): DepsmithSdkEvent[] {\n if (foreign.length === 0) return foreign;\n let room = this.maxSize - this.events.length;\n let chars = this.maxChars - this.serializedLength();\n const kept: DepsmithSdkEvent[] = [];\n for (let i = foreign.length - 1; i >= 0 && room > 0; i--) {\n const size = JSON.stringify(foreign[i]).length + 1; // plus its comma\n if (size > chars) break;\n chars -= size;\n room--;\n kept.push(foreign[i]!);\n }\n return kept.reverse();\n }\n\n override clear(): void {\n super.clear();\n this.known.clear();\n this.removed.clear();\n }\n\n override close(): void {\n try {\n if (typeof window !== 'undefined') window.removeEventListener('storage', this.onStorage);\n } catch {\n /* nothing was attached */\n }\n }\n}\n","import { KEY_ANON_RESET, type KVStorage } from './queue/storage';\nimport type { Clock } from './utils/clock';\nimport type { Properties } from './types';\nimport { uuidv7 } from './utils/uuidv7';\n\nconst KEY_ANON = 'depsmith_anonymous_id';\nconst KEY_USER = 'depsmith_user_id';\nconst KEY_GROUP = 'depsmith_group_id';\nconst KEY_PROPS = 'depsmith_user_props';\n\n/** Anonymous-first identity. anonymous_id rotates ONLY via reset(). See API_SPEC §4. */\nexport class IdentityManager {\n constructor(\n private storage: KVStorage,\n private clock: Clock\n ) {}\n\n get anonymousId(): string {\n let id = this.storage.get(KEY_ANON);\n if (!id) {\n id = uuidv7(this.clock.now());\n this.storage.set(KEY_ANON, id);\n }\n return id;\n }\n\n get userId(): string | null {\n return this.storage.get(KEY_USER);\n }\n\n get groupId(): string | null {\n return this.storage.get(KEY_GROUP);\n }\n\n identify(userId: string): void {\n this.storage.set(KEY_USER, userId);\n }\n\n setGroup(groupId: string): void {\n this.storage.set(KEY_GROUP, groupId);\n }\n\n /** Persisted user-property map, used for setOnceProperty checks. */\n getUserProps(): Properties {\n try {\n return JSON.parse(this.storage.get(KEY_PROPS) ?? '{}') as Properties;\n } catch {\n return {};\n }\n }\n\n setUserProp(key: string, value: Properties[string]): void {\n const props = this.getUserProps();\n props[key] = value;\n this.storage.set(KEY_PROPS, JSON.stringify(props));\n }\n\n hasUserProp(key: string): boolean {\n return key in this.getUserProps();\n }\n\n unsetUserProp(key: string): void {\n const props = this.getUserProps();\n delete props[key];\n this.storage.set(KEY_PROPS, JSON.stringify(props));\n }\n\n /**\n * Clears user/group/props and rotates anonymous_id.\n *\n * Also records WHEN, beside the id. The id lives in two stores, and one of them (the cookie,\n * under `cookieDomain`) is shared with origins this page cannot write to; without the marker\n * their copy of the old id looks like the device's original identity and is restored over the\n * new one. See `RedundantAdapter.pick`.\n */\n reset(): string {\n this.storage.remove(KEY_USER);\n this.storage.remove(KEY_GROUP);\n this.storage.remove(KEY_PROPS);\n const now = this.clock.now();\n this.storage.set(KEY_ANON_RESET, `${now}`);\n const fresh = uuidv7(now);\n this.storage.set(KEY_ANON, fresh);\n return fresh;\n }\n}\n","import type { KVStorage } from './queue/storage';\nimport type { Clock } from './utils/clock';\nimport { uuidv7, uuidv7ToMs } from './utils/uuidv7';\nimport { idleScheduler, type Scheduler } from './utils/scheduler';\n\nconst KEY_SESSION = 'depsmith_session';\n\ninterface StoredSession {\n id: string;\n lastActivityAt: number;\n /** Absent on records written before 0.3.0 — recovered from the id, see load(). */\n startedAt?: number;\n}\n\nexport interface SessionTouch {\n sessionId: string;\n /** When this session began. Rides every event so session length is computable per row. */\n startedAt: number;\n /** Present when this touch expired a previous session — caller emits $session_end for it. */\n endedSession?: { id: string; lastActivityAt: number; startedAt: number };\n /** Present when this touch minted a session — caller emits $session_start for it. */\n startedSession?: { id: string; startedAt: number };\n}\n\n/**\n * 30-min inactivity sessions, persisted so they survive restarts.\n * Order matters: check timeout FIRST, then stamp activity (API_SPEC §5).\n *\n * Writes are coalesced onto an idle callback for the same reason `EventQueue`'s are: a\n * synchronous `localStorage.setItem` on every `touch()` — that is, on every captured\n * event — put a blocking main-thread write inside every click handler. Reads still go to\n * storage so a session stays shared across tabs; see load().\n */\nexport class SessionManager {\n /** Written but not yet persisted. Kept so load() can see our own latest write. */\n private pending: StoredSession | null = null;\n private scheduled = false;\n private schedule: Scheduler;\n\n constructor(\n private storage: KVStorage,\n private clock: Clock,\n private timeoutMs: number,\n schedule: Scheduler = idleScheduler\n ) {\n this.schedule = schedule;\n }\n\n /**\n * Reads the stored session, recovering `startedAt` for records written before 0.3.0.\n *\n * A session already in the field has no stored start time, but its id is a UUID v7\n * whose first 48 bits ARE that time — so the value is exact, not an approximation.\n * That is why this field needed no backfill and no storage format version. The\n * `?? lastActivityAt` is a last resort for an id that somehow isn't v7; it can only\n * under-report the session's age, never invent a future start.\n *\n * Deliberately still reads storage even when a write is pending: sessions are shared\n * across tabs through `localStorage`, and serving a purely in-memory value would let two\n * tabs drift into separate sessions. The pending write wins only when it is at least as\n * recent as what is stored — if another tab has written something newer (it rotated the\n * session, say), that wins and our pending write is dropped rather than allowed to\n * clobber it. Last-activity-wins, which is what the write-through version resolved to\n * anyway.\n */\n private load(): StoredSession | null {\n const stored = this.readStored();\n const pending = this.pending;\n if (!pending) return stored;\n if (!stored || pending.lastActivityAt >= stored.lastActivityAt) return pending;\n this.pending = null; // another tab won; do not clobber it\n return stored;\n }\n\n private readStored(): StoredSession | null {\n try {\n const raw = this.storage.get(KEY_SESSION);\n if (!raw) return null;\n const parsed = JSON.parse(raw) as StoredSession;\n if (typeof parsed.id !== 'string' || typeof parsed.lastActivityAt !== 'number') return null;\n if (typeof parsed.startedAt !== 'number') {\n parsed.startedAt = uuidv7ToMs(parsed.id) ?? parsed.lastActivityAt;\n }\n return parsed;\n } catch {\n return null;\n }\n }\n\n private save(session: StoredSession): void {\n this.pending = session;\n if (this.scheduled) return;\n this.scheduled = true;\n this.schedule(() => {\n this.scheduled = false;\n this.persistNow();\n });\n }\n\n /** Writes any pending session immediately. Called on `pagehide` and `shutdown()`. */\n persistNow(): void {\n const pending = this.pending;\n if (!pending) return;\n this.pending = null;\n this.storage.set(KEY_SESSION, JSON.stringify(pending));\n }\n\n private mint(now: number): StoredSession {\n const fresh = { id: uuidv7(now), lastActivityAt: now, startedAt: now };\n this.save(fresh);\n return fresh;\n }\n\n /** Called on every capture and on visibility resume. */\n touch(): SessionTouch {\n const now = this.clock.now();\n const current = this.load();\n\n if (!current) {\n const fresh = this.mint(now);\n return {\n sessionId: fresh.id,\n startedAt: now,\n startedSession: { id: fresh.id, startedAt: now },\n };\n }\n\n if (now - current.lastActivityAt > this.timeoutMs) {\n const fresh = this.mint(now);\n return {\n sessionId: fresh.id,\n startedAt: now,\n // Order matters downstream: $session_end for the old session is emitted before\n // $session_start for the new one (API_SPEC §5).\n endedSession: {\n id: current.id,\n lastActivityAt: current.lastActivityAt,\n startedAt: current.startedAt!,\n },\n startedSession: { id: fresh.id, startedAt: now },\n };\n }\n\n this.save({ id: current.id, lastActivityAt: now, startedAt: current.startedAt! });\n return { sessionId: current.id, startedAt: current.startedAt! };\n }\n\n /**\n * Current id without stamping activity (getSessionId bridge/testing API).\n *\n * Deliberately does NOT rotate an expired session. This used to delegate to touch(),\n * which rotated and returned an `endedSession` that peek() then dropped on the floor —\n * so merely *reading* the id destroyed the `$session_end` for the session that just\n * expired, and stamped activity that kept a dead session alive. Rotation is left to\n * the next capture(), which emits the `$session_end` properly.\n */\n peek(): string {\n const current = this.load();\n if (current) return current.id;\n // No session yet: mint and persist, so repeated reads are stable. Deliberately does\n // NOT emit $session_start — emitting analytics from a getter is the class of bug the\n // peek() fix above removed. The next capture() adopts this session silently.\n return this.mint(this.clock.now()).id;\n }\n\n /**\n * Adopts an externally supplied session id — the `setSessionId()` public API.\n *\n * Exists so a session can span contexts the SDK cannot see across: a web→app handoff, a\n * server-rendered page continuing into the client, or two subdomains that do not share\n * storage. Without it those are unavoidably separate sessions, and every funnel spanning\n * them is wrong rather than merely noisy.\n *\n * Returns false for a non-UUIDv7 id rather than adopting it. A session id whose first 48\n * bits are not a timestamp would make `session_started_at` unrecoverable and break the\n * ordering `event_id` and `session_id` both rely on, so a bad id is refused at the door\n * rather than persisted and dealt with later.\n *\n * `startedAt` is optional because the id already carries it exactly (RFC 9562). The\n * parameter exists for the case where the caller knows the session began before the id\n * was minted; it can only ever move the start earlier in practice, and is trusted as given.\n *\n * Deliberately emits NO `$session_start`: an externally supplied session is not a boundary\n * this SDK observed. Same reasoning that keeps `rotate()` and `peek()` silent — see\n * API_SPEC §5.\n */\n adopt(id: string, startedAt?: number): boolean {\n const embedded = uuidv7ToMs(id);\n if (embedded === null) return false;\n this.save({ id, lastActivityAt: this.clock.now(), startedAt: startedAt ?? embedded });\n return true;\n }\n\n /**\n * reset() rotates the session unconditionally — no $session_end AND no $session_start.\n * Start and end stay symmetric: reset() is an explicit user action, not a session\n * boundary the SDK observed, so it announces neither side.\n */\n rotate(): string {\n return this.mint(this.clock.now()).id;\n }\n}\n","import type { Logger } from './utils/logger';\nimport type { Properties, PropertyValue, Scalar } from './types';\n\nconst MAX_TOP_LEVEL_KEYS = 200;\nconst MAX_ARRAY_ITEMS = 100;\nconst MAX_OBJECT_KEYS = 50;\n\n/**\n * Enqueue-time validation & coercion (API_SPEC §7). Never throws:\n * Dates → ISO strings, deep nesting → JSON string at depth 1, NaN/Infinity → dropped.\n */\nexport function sanitizeProperties(input: unknown, logger: Logger): Properties {\n if (input === null || input === undefined) return {};\n if (typeof input !== 'object' || Array.isArray(input)) {\n logger.warn('properties must be an object; ignoring', input);\n return {};\n }\n\n const out: Properties = {};\n let count = 0;\n for (const [rawKey, rawValue] of Object.entries(input as Record<string, unknown>)) {\n if (count >= MAX_TOP_LEVEL_KEYS) {\n logger.warn(`properties exceed ${MAX_TOP_LEVEL_KEYS} keys; excess dropped`);\n break;\n }\n const value = coerceValue(rawValue, logger);\n if (value === undefined) {\n logger.debug(`property \"${rawKey}\" dropped (unsupported value)`);\n continue;\n }\n out[String(rawKey)] = value;\n count++;\n }\n return out;\n}\n\nfunction coerceScalar(value: unknown): Scalar | undefined {\n if (value === null) return null;\n const t = typeof value;\n if (t === 'string' || t === 'boolean') return value as Scalar;\n if (t === 'number') return Number.isFinite(value as number) ? (value as number) : undefined;\n if (value instanceof Date) return isNaN(value.getTime()) ? undefined : value.toISOString();\n return undefined;\n}\n\nfunction coerceValue(value: unknown, logger: Logger): PropertyValue | undefined {\n const scalar = coerceScalar(value);\n if (scalar !== undefined) return scalar;\n if (value === undefined || typeof value === 'function' || typeof value === 'symbol') return undefined;\n\n if (Array.isArray(value)) {\n const items: Scalar[] = [];\n for (const item of value.slice(0, MAX_ARRAY_ITEMS)) {\n const coerced = coerceScalar(item);\n // non-scalar array members get JSON-stringified (depth-1 flattening)\n items.push(coerced !== undefined ? coerced : safeStringify(item));\n }\n return items;\n }\n\n if (typeof value === 'object') {\n const out: Record<string, Scalar> = {};\n let count = 0;\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (count >= MAX_OBJECT_KEYS) {\n logger.debug(`nested object exceeds ${MAX_OBJECT_KEYS} keys; excess dropped`);\n break;\n }\n const coerced = coerceScalar(v);\n out[String(k)] = coerced !== undefined ? coerced : safeStringify(v);\n count++;\n }\n return out;\n }\n\n return undefined;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? 'null';\n } catch {\n return String(value);\n }\n}\n","import type { Logger } from './utils/logger';\n\n// `$` property keys are the SDK's (API_SPEC §7). Its own module so the Shopify custom-pixel build\n// can swap it for `reserved.noop.ts`: nothing in the pixel sandbox calls a public method — the\n// pixel uses the internal entry points — and that bundle has no characters to spare.\n\n/**\n * Drops `$`-prefixed keys a client passed to a public method.\n *\n * `$` marks SDK-owned data (`$page_name`, `$page_counter`, `$ac_*`), the same namespace `track()`\n * reserves for event names and `register()` for super-property keys. Without this a client\n * could send `$page_name` on its own events and no reader could tell system data from client\n * data again. The SDK's own events never pass through here: autocapture, the page lifecycle and\n * the internal entry points capture directly.\n *\n * Returns the input itself when nothing is reserved.\n */\nexport function stripReserved<T extends object>(\n input: T | undefined,\n method: string,\n logger: Logger\n): T | undefined {\n const out = { ...input } as Record<string, unknown>;\n let hit;\n for (const key in out) if (isReserved(key, method, logger)) hit = delete out[key];\n return hit ? (out as T) : input;\n}\n\n/** True, with a debug warning naming the key, when `key` is in the SDK's `$` namespace. */\nexport function isReserved(key: string, method: string, logger: Logger): boolean {\n // `?.[0]`, not startsWith: a JS caller can pass a non-string key, and this must not throw.\n if (key?.[0] !== '$') return false;\n logger.warn(`${method}: \"$\"-prefixed keys are reserved; ignored \"${key}\"`);\n return true;\n}\n","import type { ResolvedConfig } from './config';\nimport type { Properties } from './types';\n\n/**\n * `$network_request` when a request the app made fails (default-events spec item 15).\n *\n * Failure means a 5xx response, or no response at all. A 4xx is deliberately excluded: a 404 on a\n * probe or a 401 driving a token refresh is ordinary application flow, and reporting those would bury\n * the server failures this exists to surface.\n *\n * **Bodies are never read, only sizes.** That is the spec's acceptance criterion and it is also what\n * makes this safe to ship: a request body is the single most PII-dense thing a page touches, and this\n * SDK has no masking primitive for it. Sizes come from the `Content-Length` header, so reading them\n * never consumes the stream — cloning a response to measure it would both cost memory and change the\n * host's own timing.\n *\n * The SDK's OWN uploads are excluded by endpoint prefix. Without that, a collector outage becomes a\n * feedback loop: the failing upload reports itself, which queues another event, which fails too.\n *\n * **Volume is bounded, and a request the app gave up on is not a failure.** Reporting every\n * rejection made this a firehose in exactly the apps that use `fetch` most: a typeahead or a\n * query library aborts a request per keystroke and per route change, and a dashboard polling\n * while the device is offline fails once a second — each one an event in a bounded,\n * drop-oldest queue, crowding out real events that cannot upload either. So:\n * - an aborted request is not reported (a timeout still is — the server was too slow);\n * - nothing is reported while the browser says it is offline: that is the device, not a server;\n * - a given failure (method, URL without query, status or \"no response\") is reported once per\n * {@link WINDOW_MS}, and at most {@link MAX_PER_WINDOW} distinct ones in that time.\n */\nexport interface NetworkErrors {\n stop(): void;\n}\n\n/** The rate-limit window. */\nconst WINDOW_MS = 60_000;\n/** Distinct failures reported per window; the rest are dropped, not queued for later. */\nconst MAX_PER_WINDOW = 10;\n\n/**\n * True when the request was cancelled by the page rather than failed by the network.\n *\n * `AbortError` is what an `AbortController` produces by default; `abort(reason)` rejects with the\n * reason itself, so the signal is checked as well. `TimeoutError` (`AbortSignal.timeout`) is the\n * exception: nobody changed their mind, the server did not answer in time.\n */\nfunction wasAborted(error: unknown, signal: AbortSignal | null | undefined): boolean {\n const name = (error as { name?: unknown } | null | undefined)?.name;\n return name === 'AbortError' || (name !== 'TimeoutError' && !!signal?.aborted);\n}\n\n/** By shape, not `instanceof Error`: a rejection from another realm fails that test. */\nfunction errorMessage(error: unknown): string {\n const message = (error as { message?: unknown } | null | undefined)?.message;\n return typeof message === 'string' && message ? message.slice(0, 255) : 'network error';\n}\n\n/** Only a server failure or a transport failure. 4xx is application flow, not an outage. */\nfunction isFailure(status: number): boolean {\n return status >= 500;\n}\n\n/** Query and fragment are reported separately, so `$net_url` stays a groupable key. */\nfunction urlParts(raw: string): Properties {\n const properties: Properties = {};\n try {\n const url = new URL(raw, typeof location !== 'undefined' ? location.href : undefined);\n properties.$net_url = `${url.origin}${url.pathname}`;\n if (url.search.length > 1) properties.$net_query = url.search.slice(1);\n if (url.hash.length > 1) properties.$net_fragment = url.hash.slice(1);\n } catch {\n // An unparseable URL still identifies the request well enough to be worth reporting.\n properties.$net_url = raw.slice(0, 255);\n }\n return properties;\n}\n\nfunction contentLength(headers: Headers | null): number | undefined {\n try {\n const value = headers?.get('content-length');\n if (!value) return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The two facts about a request this reports, read the way `fetch` itself reads its arguments. */\nfunction describeRequest(\n input: unknown,\n init: RequestInit | undefined\n): { raw: string; method: string; signal?: AbortSignal | null } {\n // A Request is used as is; ANYTHING else is stringified — a URL (from this realm or another),\n // `window.location`, an `<a>`, a router's URL-like object. Tested by tag rather than\n // `instanceof`, which is false for a Request or URL created in an iframe.\n const request =\n Object.prototype.toString.call(input) === '[object Request]' ? (input as Request) : undefined;\n return {\n raw: String(request ? request.url : input),\n method: String(init?.method ?? request?.method ?? 'GET').toUpperCase(),\n signal: init?.signal ?? request?.signal,\n };\n}\n\n/**\n * Patches `fetch` to report failures.\n *\n * **The patch is transparent.** The original is called first, with the caller's own `this` and\n * arguments, before this file has looked at either — so whatever it accepts, returns or throws\n * is what the caller gets. The earlier wrapper derived the URL up front and assumed a string, a\n * same-realm `URL` or a `Request`; for anything else native `fetch` accepts (`fetch(location)`,\n * `fetch(anchor)`, a cross-realm `URL`, any object with a `toString()`) it threw on `undefined`\n * before delegating, so a request that works without the SDK was rejected and never sent with it.\n * A request this cannot describe is now simply not observed.\n *\n * XHR is deliberately left alone. Patching it means wrapping `open`, `send` and a `readystatechange`\n * listener on every request a page makes, which is a much larger surface to get wrong inside a\n * third-party SDK — and `fetch` is what application code uses today. An XHR-only app reports nothing\n * here rather than reporting something broken.\n */\nexport function observeNetworkErrors(\n config: Pick<ResolvedConfig, 'endpoint' | 'autocapture'>,\n emit: (properties: Properties) => void\n): NetworkErrors {\n // `autocapture.networkErrors: false` is the switch for a host that wants clicks without having\n // `fetch` wrapped. On by default, as it has been since this shipped.\n const off = config.autocapture && config.autocapture.networkErrors === false;\n if (off || typeof fetch !== 'function') return { stop: () => {} };\n\n const original = fetch;\n // Compared as a prefix, so the collector's /e/ and any future path under it are both excluded.\n const own = config.endpoint.replace(/\\/+$/, '');\n let stopped = false;\n\n let windowStart = 0;\n let seen = new Set<string>();\n /** One report per distinct failure per window, and a ceiling on distinct failures. */\n const admit = (key: string): boolean => {\n const now = Date.now();\n if (now - windowStart >= WINDOW_MS) {\n windowStart = now;\n seen = new Set();\n }\n if (seen.size >= MAX_PER_WINDOW || seen.has(key)) return false;\n seen.add(key);\n return true;\n };\n\n /** Reporting is best-effort: nothing in it may change what the caller's promise settles to. */\n const report = (outcome: string | number, build: () => Properties): void => {\n try {\n const properties = build();\n if (admit(`${String(properties.$net_method)} ${String(properties.$net_url)} ${outcome}`)) {\n emit(properties);\n }\n } catch {\n /* the request's own outcome is all the caller should ever see */\n }\n };\n\n const patched = function (this: unknown, ...args: Parameters<typeof fetch>): Promise<Response> {\n const started = Date.now();\n const promise = original.apply(this, args);\n // Left in someone else's chain after stop() (see below): pass through and report nothing.\n // Likewise for a replaced `fetch` that returns something other than a promise.\n if (stopped || typeof promise?.then !== 'function') return promise;\n\n let raw: string;\n let method: string;\n let signal: AbortSignal | null | undefined;\n try {\n ({ raw, method, signal } = describeRequest(args[0], args[1]));\n // Our own uploads, excluded before anything else: a collector outage would otherwise report\n // itself, queue another event, and fail again.\n if (raw.startsWith(own)) return promise;\n } catch {\n return promise;\n }\n const init = args[1];\n\n // A derived promise rather than a side branch on the original: a handler attached to the\n // original would mark its rejection as handled, and the host's `unhandledrejection` reporting\n // for a failed request nobody caught would go quiet. This one settles exactly as the original.\n return promise.then(\n (response) => {\n if (isFailure(response.status)) {\n report(response.status, () => ({\n ...urlParts(raw),\n $net_method: method,\n $net_status: response.status,\n $net_start: started,\n $net_end: Date.now(),\n $net_duration_ms: Date.now() - started,\n ...sizes(init, response),\n }));\n }\n return response;\n },\n (error: unknown) => {\n // No response at all: DNS, CORS, a dropped connection. Not a cancelled request, and not\n // while the device itself is offline — neither says anything about a server.\n const offline = typeof navigator !== 'undefined' && navigator.onLine === false;\n if (offline || wasAborted(error, signal)) throw error;\n // The message is the only detail the platform gives, and it is short by nature.\n report('error', () => ({\n ...urlParts(raw),\n $net_method: method,\n $net_error_message: errorMessage(error),\n $net_start: started,\n $net_end: Date.now(),\n $net_duration_ms: Date.now() - started,\n }));\n // Rethrown unchanged: observing a failure must not change how the caller sees it.\n throw error;\n }\n );\n } as typeof fetch;\n\n (globalThis as { fetch: typeof fetch }).fetch = patched;\n return {\n stop: () => {\n stopped = true;\n // Only if nobody else patched on top of us — restoring over a later wrapper would silently\n // uninstall theirs, which is the same mistake this file avoids with the crash-handler chain.\n // Their wrapper still calls this one, so it stays in the chain and goes inert (`stopped`).\n if ((globalThis as { fetch: typeof fetch }).fetch === patched) {\n (globalThis as { fetch: typeof fetch }).fetch = original;\n }\n },\n };\n}\n\n/** Sizes from Content-Length only — never by reading or cloning a body. */\nfunction sizes(init: RequestInit | undefined, response: Response): Properties {\n const properties: Properties = {};\n const requestBytes = typeof init?.body === 'string' ? init.body.length : undefined;\n if (requestBytes !== undefined) properties.$net_req_bytes = requestBytes;\n const responseBytes = contentLength(response.headers);\n if (responseBytes !== undefined) properties.$net_res_bytes = responseBytes;\n return properties;\n}\n","import type { Properties } from './types';\n\n/**\n * Google's Core Web Vitals, collected with PerformanceObserver and reported once per page\n * (default-events spec item 14).\n *\n * Emitted when the tab is HIDDEN rather than on load, because three of the five are not final until\n * then: LCP can be superseded by a later paint, CLS accumulates for the life of the page, and INP is\n * the worst interaction so far. Reporting at load would systematically under-report all three — which\n * is worse than not reporting them, because the numbers would look plausible.\n *\n * Observers only, no wrapping of anything. Every registration is individually guarded: these entry\n * types have uneven support (`event` timing is Chromium-only today), and an unsupported type throws\n * from `observe()` rather than degrading, so one missing type must not cost the other four.\n */\nexport interface Vitals {\n /** Collected so far. Values absent rather than zero when nothing was observed. */\n snapshot(): Properties;\n /** True once there is at least one metric worth sending. */\n hasAny(): boolean;\n stop(): void;\n}\n\n/** Rounded to whole milliseconds — sub-millisecond precision in a page-speed metric is noise. */\nfunction ms(value: number): number {\n return Math.round(value);\n}\n\nexport function observeVitals(): Vitals {\n let lcp: number | undefined;\n let fcp: number | undefined;\n let inp: number | undefined;\n let cls = 0;\n let sawLayoutShift = false;\n let ttfb: number | undefined;\n const observers: PerformanceObserver[] = [];\n\n const observe = (type: string, handler: (entries: PerformanceEntryList) => void): void => {\n try {\n const observer = new PerformanceObserver((list) => handler(list.getEntries()));\n // `buffered: true` replays entries that occurred before the SDK loaded, which matters most for\n // FCP and LCP: an async-loaded SDK would otherwise miss the very paints it exists to measure.\n observer.observe({ type, buffered: true } as PerformanceObserverInit);\n observers.push(observer);\n } catch {\n /* entry type unsupported in this browser — the metric stays absent, never zero */\n }\n };\n\n // Last entry wins: LCP is redefined upward until the page stops painting.\n observe('largest-contentful-paint', (entries) => {\n const last = entries[entries.length - 1];\n if (last) lcp = ms(last.startTime);\n });\n\n observe('paint', (entries) => {\n for (const entry of entries) {\n if (entry.name === 'first-contentful-paint') fcp = ms(entry.startTime);\n }\n });\n\n // CLS sums every shift NOT caused by recent input — a layout change the user themselves triggered\n // by tapping is expected, and counting it would penalise responsive UI.\n observe('layout-shift', (entries) => {\n for (const entry of entries as Array<PerformanceEntry & { value?: number; hadRecentInput?: boolean }>) {\n if (entry.hadRecentInput) continue;\n cls += entry.value ?? 0;\n sawLayoutShift = true;\n }\n });\n\n // INP approximated as the worst interaction latency seen. The official metric uses a high\n // percentile across all interactions; the maximum is the honest simplification at one page's\n // scale, where a percentile over three interactions means nothing.\n observe('event', (entries) => {\n for (const entry of entries) {\n const duration = ms(entry.duration);\n if (inp === undefined || duration > inp) inp = duration;\n }\n });\n\n try {\n // TTFB comes from the navigation entry, which exists immediately — no observer needed, and\n // nothing to wait for.\n const [navigation] = performance.getEntriesByType('navigation');\n const timing = navigation as (PerformanceEntry & { responseStart?: number }) | undefined;\n if (timing?.responseStart !== undefined && timing.responseStart > 0) {\n ttfb = ms(timing.responseStart);\n }\n } catch {\n /* no Navigation Timing — TTFB stays absent */\n }\n\n return {\n snapshot(): Properties {\n const out: Properties = {};\n if (lcp !== undefined) out.$wv_lcp = lcp;\n if (fcp !== undefined) out.$wv_fcp = fcp;\n if (inp !== undefined) out.$wv_inp = inp;\n // Reported only if a shift was actually observed. A literal 0 is a real and good CLS score, so\n // it must be distinguishable from \"this browser told us nothing\".\n if (sawLayoutShift) out.$wv_cls = Math.round(cls * 1000) / 1000;\n if (ttfb !== undefined) out.$wv_ttfb = ttfb;\n return out;\n },\n hasAny(): boolean {\n return (\n lcp !== undefined ||\n fcp !== undefined ||\n inp !== undefined ||\n sawLayoutShift ||\n ttfb !== undefined\n );\n },\n stop(): void {\n for (const observer of observers.splice(0)) {\n try {\n observer.disconnect();\n } catch {\n /* ignore */\n }\n }\n },\n };\n}\n","import type { Properties } from './types';\nimport { isReserved } from './reserved';\nimport type { KVStorage } from './queue/storage';\nimport type { Logger } from './utils/logger';\n\n/**\n * Registered (\"super\") properties: values attached to every later event (common-properties item 4).\n *\n * The problem they solve is a client passing `plan` and `ab_variant` to every single `track()` call,\n * which is both noise and a place to forget. Registered once, they ride along.\n *\n * Precedence, which is the rule that matters: a property passed directly to `track()` WINS over a\n * registered one with the same key. The call site is more specific than the registration, and the\n * alternative — registration winning — would make a per-event override impossible to express.\n *\n * Distinct from `config.defaultProperties`, which is static and set at init. These are mutable at\n * runtime and persisted, so they survive a reload. Where both define a key, the registered one wins:\n * it was set later, and by a call rather than a constant.\n */\nexport const KEY_SUPER_PROPERTIES = 'depsmith_super_props';\n\n/** Rejected for the same reason `track()` rejects `$`-prefixed event names: reserved namespace. */\nfunction usableKey(key: string, logger: Logger): boolean {\n if (key.length === 0) {\n logger.warn('register: empty property key ignored');\n return false;\n }\n return !isReserved(key, 'register', logger);\n}\n\nexport class SuperProperties {\n private properties: Properties = {};\n\n constructor(\n private storage: KVStorage,\n private logger: Logger\n ) {\n try {\n const stored = this.storage.get(KEY_SUPER_PROPERTIES);\n if (stored) {\n const parsed: unknown = JSON.parse(stored);\n // Guarded: a hand-edited localStorage value, or a value written by a future version with a\n // different shape, must not take the SDK down at construction.\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n this.properties = parsed as Properties;\n }\n }\n } catch {\n /* unreadable or malformed — start empty rather than throw in a constructor */\n }\n }\n\n /** Overwrites each given key. */\n register(properties: Properties): void {\n let changed = false;\n for (const [key, value] of Object.entries(properties)) {\n if (!usableKey(key, this.logger)) continue;\n this.properties[key] = value;\n changed = true;\n }\n if (changed) this.persist();\n }\n\n /**\n * Sets only keys that are not registered yet — for first-touch values like the plan someone\n * signed up on, which must not be overwritten by a later state.\n *\n * \"Not registered yet\" means absent, not falsy: a registered `false` or `0` is a value someone\n * chose, and treating it as missing would silently replace it on the next call.\n */\n registerOnce(properties: Properties): void {\n let changed = false;\n for (const [key, value] of Object.entries(properties)) {\n if (!usableKey(key, this.logger)) continue;\n if (Object.prototype.hasOwnProperty.call(this.properties, key)) continue;\n this.properties[key] = value;\n changed = true;\n }\n if (changed) this.persist();\n }\n\n unregister(key: string): void {\n if (!Object.prototype.hasOwnProperty.call(this.properties, key)) return;\n delete this.properties[key];\n this.persist();\n }\n\n /** Cleared by reset(), like every other visitor-scoped value. */\n clear(): void {\n if (Object.keys(this.properties).length === 0) return;\n this.properties = {};\n try {\n this.storage.remove(KEY_SUPER_PROPERTIES);\n } catch {\n /* ignore */\n }\n }\n\n /**\n * A copy, so a caller mutating the returned object cannot change registered state — and so the\n * spread at the capture site cannot alias one object across every event in a batch.\n */\n current(): Properties {\n return { ...this.properties };\n }\n\n private persist(): void {\n try {\n this.storage.set(KEY_SUPER_PROPERTIES, JSON.stringify(this.properties));\n } catch {\n // Quota or a blocked store: they still apply for this page, they just will not survive it.\n this.logger.debug('register: could not persist super properties');\n }\n }\n}\n","/**\n * User-property operators (API_SPEC §14).\n *\n * The operators exist because applying them on a client is wrong, not merely inconvenient:\n * `$add` on a device is a read-modify-write race between tabs, and `$append` cannot converge\n * at all. So the SDK's job is to *describe* the change and let the collector apply it.\n *\n * Two invariants are the client's responsibility, and both are here rather than in the\n * collector — the schema's own comment explains why: they are what keep the collector free\n * of operator algebra.\n *\n * 1. A key appears under AT MOST ONE operator per event. Without it, `$set` then `$add` on\n * one key is only resolvable by assuming the value is numeric.\n * 2. `$clear_all` is exclusive. Combining it with anything else makes the result depend on\n * ordering that is otherwise unobservable.\n *\n * Both are enforced by dropping the offending entry with a debug warning, never by throwing:\n * the public API is fire-and-forget and must not break a host page over a analytics call.\n */\nimport type { Logger } from './utils/logger';\nimport { sanitizeProperties } from './props';\nimport { isReserved } from './reserved';\nimport type { Properties, PropertyValue } from './types';\n\n/** Operators taking a map of traits. */\nexport type TraitOperator =\n | '$set'\n | '$set_once'\n | '$append'\n | '$prepend'\n | '$pre_insert'\n | '$post_insert'\n | '$remove';\n\n/**\n * The closed operator set, exactly as `event.schema.json` `$defs.userPropertyOps` declares it.\n * Closed on purpose: level 2 is a fixed 10-member enum the collector knows at compile time,\n * which is what lets `user_properties.$add.orders` flatten deterministically into a warehouse\n * column despite being three levels from the root.\n */\nexport interface UserPropertyOps {\n $set?: Properties;\n $set_once?: Properties;\n $append?: Properties;\n $prepend?: Properties;\n $pre_insert?: Properties;\n $post_insert?: Properties;\n $remove?: Properties;\n /** Numeric increments. Absent counts as 0; negative is allowed. */\n $add?: Record<string, number>;\n $unset?: string[];\n /** Deletes every user property for this identity. Exclusive. */\n $clear_all?: true;\n}\n\nconst TRAIT_OPERATORS: readonly TraitOperator[] = [\n '$set',\n '$set_once',\n '$append',\n '$prepend',\n '$pre_insert',\n '$post_insert',\n '$remove',\n];\n\n/** Mirrors the schema's `maxProperties` / `maxItems` so an over-sized map is trimmed, not rejected. */\nconst MAX_ADD_KEYS = 50;\nconst MAX_UNSET_KEYS = 200;\n\n/**\n * Validates, sanitises and de-duplicates an operator map.\n *\n * Returns `undefined` when nothing survives, so a caller can omit `user_properties` entirely\n * rather than send `{}` — which the schema forbids via `minProperties: 1`.\n */\nexport function normalizeUserPropertyOps(\n ops: UserPropertyOps,\n logger: Logger\n): UserPropertyOps | undefined {\n if (!ops || typeof ops !== 'object') return undefined;\n\n // $clear_all first, and alone. Checked before anything else so the exclusivity warning\n // names what was discarded rather than silently winning a race with it.\n if (ops.$clear_all === true) {\n const others = Object.keys(ops).filter((k) => k !== '$clear_all');\n if (others.length > 0) {\n logger.warn(`$clear_all is exclusive; ignored ${others.join(', ')}`);\n }\n return { $clear_all: true };\n }\n\n const out: UserPropertyOps = {};\n /** Keys already claimed, so invariant 1 can be enforced across operators. */\n const claimed = new Set<string>();\n\n const claim = (key: string, operator: string): boolean => {\n // Reserved for the SDK, as on every other public method. The operator names themselves\n // (`$set`, `$add`, …) are syntax, not keys, and are never checked here.\n if (isReserved(key, operator, logger)) return false;\n if (claimed.has(key)) {\n logger.debug(`\"${key}\" has an operator already; ${operator} dropped`);\n return false;\n }\n claimed.add(key);\n return true;\n };\n\n for (const operator of TRAIT_OPERATORS) {\n const raw = ops[operator];\n if (!raw || typeof raw !== 'object') continue;\n // Reuse the event-property sanitiser: traits are the same value space, so a Date here\n // coerces exactly as it would in properties, and the two cannot drift apart.\n const clean = sanitizeProperties(raw, logger);\n const kept: Properties = {};\n for (const [key, value] of Object.entries(clean)) {\n if (!claim(key, operator)) continue;\n kept[key] = value as PropertyValue;\n }\n if (Object.keys(kept).length > 0) out[operator] = kept;\n }\n\n if (ops.$add && typeof ops.$add === 'object') {\n const kept: Record<string, number> = {};\n let count = 0;\n for (const [key, value] of Object.entries(ops.$add)) {\n if (count >= MAX_ADD_KEYS) {\n logger.debug(`$add over ${MAX_ADD_KEYS} keys; excess dropped`);\n break;\n }\n // A non-finite increment would serialise to null and the collector would treat it as\n // a value rather than a no-op, so it is dropped here where the cause is still visible.\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n logger.debug(`$add \"${key}\" is not finite; dropped`);\n continue;\n }\n if (!claim(key, '$add')) continue;\n kept[key] = value;\n count++;\n }\n if (Object.keys(kept).length > 0) out.$add = kept;\n }\n\n if (Array.isArray(ops.$unset)) {\n const kept: string[] = [];\n for (const key of ops.$unset) {\n if (kept.length >= MAX_UNSET_KEYS) {\n logger.debug(`$unset over ${MAX_UNSET_KEYS} keys; excess dropped`);\n break;\n }\n if (typeof key !== 'string' || key.length === 0) continue;\n if (!claim(key, '$unset')) continue;\n kept.push(key);\n }\n if (kept.length > 0) out.$unset = kept;\n }\n\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * Wraps traits the caller has ALREADY run through `sanitizeProperties` in a single operator.\n *\n * `identify`, `setProperty` and `setOnceProperty` sanitise once for `context.traits`; routing\n * that result back through `normalizeUserPropertyOps` would coerce every value a second time\n * and repeat each sanitiser warning. Neither invariant can be violated by one operator over\n * one map, so there is nothing left for the full normaliser to do.\n */\nexport function sanitizedTraitOp(operator: TraitOperator, clean: Properties): UserPropertyOps | undefined {\n return Object.keys(clean).length > 0 ? { [operator]: clean } : undefined;\n}\n","/** Injectable time source — the conformance runner substitutes a controllable clock. */\nexport interface Clock {\n now(): number;\n}\n\nexport const systemClock: Clock = {\n now: () => Date.now(),\n};\n\nexport function isoTimestamp(ms: number): string {\n return new Date(ms).toISOString().replace(/(\\.\\d{3})\\d*Z$/, '$1Z');\n}\n","/** Retry classification & backoff (API_SPEC §10). */\n\n/** Network errors are represented as status 0. */\nexport function isRetryable(status: number): boolean {\n return status === 0 || status === 408 || status === 429 || status >= 500;\n}\n\nconst BASE_MS = 1000;\nconst MAX_BACKOFF_MS = 32000;\n\n/**\n * Exponential backoff 1s→32s with **full jitter**: uniform over [0, base].\n *\n * The previous form was `base * (1 + random() * 0.25)` — additive and upward-only, so a\n * wait was never shorter than base and every client retried in a correlated band. That is\n * not full jitter, despite what this comment and API_SPEC §10 both used to claim. Full\n * jitter (the AWS-canonical form) decorrelates clients by spreading retries across the\n * whole window, which is the entire point of jittering a thundering herd.\n *\n * Consequence worth knowing: this can return 0, i.e. an immediate retry on the first\n * attempt. That is intended — `maxRetries` bounds the total, and a single fast retry is\n * how a client recovers from a transient blip without waiting a full second.\n *\n * attempt is 0-based.\n */\nexport function backoffMs(attempt: number, random: () => number = Math.random): number {\n const base = Math.min(BASE_MS * 2 ** attempt, MAX_BACKOFF_MS);\n return Math.round(random() * base);\n}\n\n/**\n * `Retry-After` as a delay in ms: delay-seconds or an HTTP-date (RFC 9110 §10.2.3). 0 when\n * absent, unreadable or not in the future. The caller caps it (breaker.hold: 60 min).\n */\nexport function retryAfterMs(value: string | null | undefined, now: number): number {\n if (!value) return 0;\n const seconds = Number(value);\n const ms = seconds === seconds ? seconds * 1000 : Date.parse(value) - now;\n return ms > 0 ? ms : 0;\n}\n","/**\n * Request-body compression for the fetch upload path.\n *\n * A module of its own so the Shopify custom-pixel build can swap it for `gzip.noop.ts`: the\n * pixel forces `compression: 'none'` (it keeps the cross-origin request headers minimal), so\n * none of this can run there, and that build is unminified against a 64,000-character editor\n * limit (see `tsup.config.ts`).\n */\n\n/** gzip a string via the streams API (available in all evergreen browsers + Node 18+). */\nasync function gzip(text: string): Promise<Uint8Array<ArrayBuffer>> {\n const cs = new CompressionStream('gzip');\n const writer = cs.writable.getWriter();\n // Fire-and-forget: data flows as the reader below pulls (awaiting here can deadlock).\n writer.write(new TextEncoder().encode(text)).catch(() => {});\n writer.close().catch(() => {});\n\n const reader = cs.readable.getReader();\n const chunks: Uint8Array[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(value);\n }\n const total = chunks.reduce((n, c) => n + c.length, 0);\n const out = new Uint8Array(new ArrayBuffer(total));\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.length;\n }\n return out;\n}\n\n/**\n * `text` gzipped, or null when it should go out as plain JSON: compression is off, the platform\n * has no `CompressionStream`, or compressing failed.\n */\nexport async function compress(\n text: string,\n mode: 'gzip' | 'none' | undefined\n): Promise<Uint8Array<ArrayBuffer> | null> {\n if (mode === 'none' || typeof CompressionStream === 'undefined') return null;\n try {\n return await gzip(text);\n } catch {\n return null;\n }\n}\n","import type { EventQueue } from '../queue/queue';\nimport type { BatchPayload, DepsmithSdkEvent } from '../types';\nimport type { NetworkBreaker } from './breaker';\n\n/**\n * The `sendBeacon` drain, apart from the uploader so the Shopify custom-pixel build can swap it\n * for `beacon.noop.ts`: the pixel has no `pagehide` and never calls it, and that build is\n * unminified against a 64,000-character editor limit (see `tsup.config.ts`).\n */\n\n/**\n * Ceiling on batches drained synchronously in the unload handler.\n *\n * `sendBeacon` itself has a UA-level queue cap that this stays well under, but the real\n * reason for the bound is wall-clock: every batch is a `JSON.stringify` plus a `Blob`\n * allocation, and this loop delays the navigation the visitor just asked for. At the\n * default batchSize of 20 this ships up to 200 events, and anything beyond that is a\n * backlog that a timed flush should have drained already.\n */\nconst MAX_UNLOAD_BATCHES = 10;\n\n/**\n * Event budget per beacon, in UTF-16 code units of their JSON. The Fetch spec caps keepalive\n * bodies — sendBeacon included — at 64 KiB in flight per document, and a beacon over it is\n * refused outright. Counting events, a `batchSize` of 100 with ordinary 1 KB events was over\n * the cap, so every unload flush was refused at its first batch (deep-dive WC-14). 48 K leaves\n * room for the envelope and some non-ASCII text; the rest of the 64 KiB is the host page's.\n */\nconst BEACON_MAX_CHARS = 48_000;\n\n/**\n * Best-effort final flush on `pagehide` via navigator.sendBeacon (fire-and-forget;\n * survives page teardown). Queued events are removed only if the UA accepted them.\n *\n * **This is the one path that deletes without a 2xx** (API_SPEC §1.7, §9): `sendBeacon`\n * returning true means the UA queued the request, not that the collector took it, and there\n * is no response to wait for on a document that is going away. So it is confined to the\n * cases where that bet is reasonable, and everything else stays persisted for the fetch\n * path, which does wait for a 2xx:\n * - **not while offline** — the UA accepts the beacon, the request fails, and the events\n * were already gone;\n * - **not while the collector is unreachable** (breaker open, or the last cycle ended in\n * network errors) — the same loss, into an ad-blocker or DNS filter, on every hide;\n * - **never the batch the fetch drain is uploading** — it is already on the wire with\n * `keepalive`, and beaconing it too delivered it twice.\n * The caller additionally restricts this to a real `pagehide`; a tab merely being hidden\n * uses the fetch path (see the client's lifecycle handlers).\n *\n * This runs inside the unload handler, so on a multi-page site it is on the critical\n * path of *every* navigation. Two things keep it off that path:\n * - the per-batch `queue.remove()` no longer writes to storage (EventQueue is\n * write-behind); the caller force-persists once, after this returns;\n * - the drain is bounded by MAX_UNLOAD_BATCHES, so a large backlog can never stall a\n * navigation. Whatever is left stays persisted and replays on the next page load.\n */\nexport function sendBeacons(\n queue: EventQueue,\n config: { endpoint: string; batchSize: number },\n deps: { isOnline: () => boolean; breaker?: NetworkBreaker },\n /** Events at the head of the queue that a fetch upload has in flight. */\n uploading: number,\n buildPayload: (batch: DepsmithSdkEvent[]) => BatchPayload\n): void {\n try {\n if (typeof navigator === 'undefined' || !navigator.sendBeacon) return;\n const breaker = deps.breaker;\n if (!deps.isOnline() || breaker?.open() || breaker?.suspect()) return;\n let from = uploading;\n for (let n = 0; n < MAX_UNLOAD_BATCHES; n++) {\n const batch = queue.peek(config.batchSize, BEACON_MAX_CHARS, from);\n if (!batch.length) return;\n const payload = buildPayload(batch); // always uncompressed: sendBeacon has no header control\n // `text/plain`, not `application/json`, and the body is still JSON. This is the one\n // CORS-safelisted content type a Blob can carry, so the POST needs no preflight —\n // and a preflight is fatal here: the document is already being torn down, so the UA\n // never gets to send the follow-up request. sendBeacon would still return true, the\n // batch would still be removed from the queue below, and the events would be lost\n // rather than deferred. The fetch path keeps `application/json` (API_SPEC §6).\n const accepted = navigator.sendBeacon(\n `${config.endpoint}/e/`,\n new Blob([JSON.stringify(payload)], { type: 'text/plain' })\n );\n if (accepted) queue.remove(batch.map((event) => event.event_id));\n else if (batch.length > 1) return; // UA queue full — keep events persisted\n else from++; // one event too large for any beacon: the fetch path will send it\n }\n } catch {\n // events remain persisted; next page load replays them\n }\n}\n","import type { EventQueue } from '../queue/queue';\nimport type { Clock } from '../utils/clock';\nimport type { Logger } from '../utils/logger';\nimport type { BatchPayload, DepsmithSdkEvent } from '../types';\nimport { isoTimestamp } from '../utils/clock';\nimport type { NetworkBreaker } from './breaker';\nimport { backoffMs, isRetryable, retryAfterMs } from './retry';\n// Separate modules so the Shopify pixel build can compile them away: it never compresses and\n// has no `pagehide`. See gzip.noop.ts and beacon.noop.ts.\nimport { compress } from './gzip';\nimport { sendBeacons } from './beacon';\n\n/**\n * Hoisted out of the drain loops on purpose: an inline `batch.map(e => e.event_id)`\n * puts a function literal inside a `while` body, which Shopify's pixel-editor linter\n * rejects (\"Functions declared within loops\"), blocking the merchant from saving.\n */\nfunction eventIds(batch: DepsmithSdkEvent[]): string[] {\n // The literal lives in this hoisted function, not in a loop body, so the linter rule holds.\n return batch.map((event) => event.event_id);\n}\n\n/**\n * Overall cap on a single upload attempt. Without it a hung connection never settles,\n * and because flush() memoizes `inFlight` every later flush coalesces onto that stuck\n * promise — the SDK goes permanently silent with a full queue. Matches the read/write\n * timeout the Android transport already sets, so the platforms agree.\n */\nexport const REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * The Fetch spec caps `keepalive` request bodies at 64 KiB *across all in-flight\n * keepalive requests*; over that the promise rejects outright. 60 KiB leaves headroom.\n */\nconst KEEPALIVE_MAX_BYTES = 60_000;\n\n/**\n * Ceiling on the events in one fetch batch, in UTF-16 code units of their JSON — the queue\n * already knows each event's, so this costs no serialisation. `batchSize` alone counted events\n * and said nothing about bytes: 500 events, or one 300 KB property, made a body any collector\n * limit could refuse (deep-dive WC-14). At most ~768 KB of UTF-8 even if every character is\n * non-ASCII, so a collector accepting 1 MB bodies takes every multi-event batch. A single event\n * over the budget is still sent, alone.\n */\nexport const MAX_BATCH_CHARS = 256_000;\n\n/** Byte length of whatever we're about to send, for the keepalive check. */\nfunction bodyBytes(body: BodyInit): number {\n if (typeof body === 'string') return new TextEncoder().encode(body).byteLength;\n if (body instanceof Uint8Array) return body.byteLength;\n return 0; // unknown shape — treat as small rather than refusing keepalive\n}\n\nexport interface UploaderConfig {\n endpoint: string;\n apiKey: string;\n batchSize: number;\n maxRetries: number;\n /** gzip via CompressionStream when available; plain JSON fallback. */\n compression?: 'gzip' | 'none';\n /** Adds anonymize_ip: true to every batch body. */\n anonymizeIp?: boolean;\n /** Per-attempt timeout. Injectable so tests don't wait 30s. */\n requestTimeoutMs?: number;\n}\n\nexport interface UploaderDeps {\n fetchFn: typeof fetch;\n clock: Clock;\n logger: Logger;\n /** Injectable so tests/conformance can fast-forward backoff waits. */\n sleep: (ms: number) => Promise<void>;\n isOnline: () => boolean;\n /** Pauses uploads while the collector is unreachable (status 0 only). Absent = never pause. */\n breaker?: NetworkBreaker;\n /**\n * Current consent, re-read before every retry (API_SPEC §6): an `optOut()` during a backoff\n * sleep must stop the retry, not just empty the queue behind it. Between batches no check is\n * needed: every batch is peeked from the queue, which `optOut()` has already cleared.\n * Absent = always allowed.\n */\n canUpload?: () => boolean;\n}\n\n/** Synthetic status for a response fetch reached through a redirect; a 3xx, so refused. */\nconst REDIRECTED = 399;\n\n/** 3xx, 401, 403: about the key or the endpoint, not the events. Kept, and uploads pause. */\nfunction refused(status: number): boolean {\n return (status > 299 && status < 400) || status === 401 || status === 403;\n}\n\n/**\n * First pause after a cycle the collector answered without accepting (refused, or 408/429/5xx\n * through every retry); doubles per such cycle, capped. `Retry-After` replaces it when sent.\n */\nexport const HOLD_BASE_MS = 30_000;\nexport const HOLD_MAX_MS = 60 * 60_000;\n\n/**\n * Drains the queue oldest-first, one in-flight upload at a time (API_SPEC §10, §11).\n *\n * - **2xx** delete.\n * - **Network error / 408 / 429 / 5xx** retry with backoff up to maxRetries; the events stay.\n * A cycle that got answers but no 2xx then pauses uploads like a refusal below, or for the\n * `Retry-After` the collector sent (which also ends the cycle at once).\n * - **401 / 403 / 3xx** (including any response fetch reached by following a redirect) — refused: the answer is about the key or the endpoint, not these\n * events, so dropping would walk the whole queue into the bin one batch at a time. The batch\n * stays, the cycle ends and uploads pause (`deps.breaker.hold`), 30 s doubling to 60 min.\n * - **400 / 413** — something in this batch, or its size: halve it and go again, down to a\n * single event, which is then dropped and the size returns to `batchSize`. The smaller size is\n * kept for the rest of the cycle. A dropped 400 also ends the cycle: one isolated invalid event\n * per cycle, so a collector rejecting everything is not sent the queue one request at a time.\n * - **`Retry-After`** on any answer the cycle would retry ends the cycle; uploads pause until\n * then, capped at 60 min and persisted with the breaker, so a navigation honours it.\n * - **Other 4xx** (404, 422…) drop the batch: a poison batch must not wedge the queue.\n *\n * Every drop is logged with `notice`, which prints whether or not `debug` is on.\n * Repeated network errors (no HTTP response) open `deps.breaker` — see breaker.ts.\n */\nexport class BatchUploader {\n private inFlight: Promise<void> | null = null;\n /**\n * Size of the batch the fetch drain is uploading right now; 0 between batches. That batch is\n * always the head of the queue, so a count is enough to step over it — and if an eviction\n * ever shifts the head mid-upload, the error is on the safe side: an event is left persisted\n * for the next load rather than beaconed.\n */\n private uploading = 0;\n /** Batch size after a 400/413 halving; 0 = `config.batchSize`. Reset by every cycle. */\n private limit = 0;\n /** Consecutive cycles the collector answered but did not accept; sets the next pause. */\n private strikes = 0;\n /** `Retry-After` of the last response, in ms; 0 when it had none. */\n private wait = 0;\n\n constructor(\n private queue: EventQueue,\n private config: UploaderConfig,\n private deps: UploaderDeps\n ) {}\n\n /** Resolves once any in-flight drain settles, without starting a new one. */\n pending(): Promise<void> {\n return this.inFlight ?? Promise.resolve();\n }\n\n /** Connectivity came back: let the next flush try again immediately. */\n resetNetworkBreaker(): void {\n this.deps.breaker?.ok();\n }\n\n /** Resolves when the current drain attempt completes. Never rejects. */\n flush(): Promise<void> {\n if (this.inFlight) return this.inFlight;\n this.inFlight = this.drain()\n .catch((err) => this.deps.logger.error('flush failed', err))\n .finally(() => {\n this.inFlight = null;\n });\n return this.inFlight;\n }\n\n private async drain(): Promise<void> {\n this.limit = 0;\n while (this.queue.size > 0) {\n if (!this.deps.isOnline()) {\n this.deps.logger.debug('offline; deferring upload');\n return;\n }\n // Before persistNow() on purpose: a paused cycle should cost nothing at all — not the\n // storage write, not the stringify, not the request. The queue is left as it is.\n if (this.deps.breaker?.open()) {\n this.deps.logger.debug('uploads paused');\n return;\n }\n const max = this.config.batchSize;\n const batch = this.queue.peek(this.limit || max, MAX_BATCH_CHARS);\n // API_SPEC §1 step 4: durable storage BEFORE any network attempt. The queue is\n // write-behind, so this is the point that makes the invariant hold — and the right\n // point, because it costs one write per batch actually sent rather than one per\n // event captured. A no-op when nothing has changed since the last write.\n this.queue.persistNow();\n this.uploading = batch.length;\n const status = await this.uploadWithRetry(batch); // never rejects: post() catches\n this.uploading = 0;\n if (refused(status) || isRetryable(status)) return; // kept for a later cycle; see uploadWithRetry\n if (status === 400 || status === 413) {\n if (batch.length > 1) {\n this.limit = batch.length >> 1;\n continue;\n }\n this.limit = 0;\n }\n if (status > 299) this.deps.logger.notice(`collector answered ${status}; dropped ${batch.length} event(s)`);\n this.queue.remove(eventIds(batch));\n // One isolated poison event per cycle: a collector rejecting every event would\n // otherwise be sent the whole queue one request at a time, back to back.\n if (status === 400) return;\n }\n }\n\n /** The final status of up to `maxRetries + 1` attempts. Pauses uploads when the collector\n * answered without accepting. */\n private async uploadWithRetry(batch: DepsmithSdkEvent[]): Promise<number> {\n const breaker = this.deps.breaker;\n let answered = false; // did ANY attempt get an HTTP response?\n let status = 0;\n for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {\n // A retry re-sends a batch selected before the backoff sleep. Send it only if consent\n // still allows uploads and the batch is still the head of the queue: optOut() clears the\n // queue but cannot reach this local copy, and a withdrawn event must not be sent again\n // (#83). The cycle ends with the last retryable status, so the drain stops and a later\n // cycle re-peeks whatever the queue holds by then.\n if (\n attempt &&\n (this.deps.canUpload?.() === false || this.queue.peek(1)[0]?.event_id !== batch[0]!.event_id)\n ) {\n break;\n }\n status = await this.post(batch);\n if (status) answered = true;\n // A Retry-After ends the cycle: retrying inside it would be sooner than we were told.\n if (!isRetryable(status) || this.wait) break;\n this.deps.logger.debug(`upload attempt ${attempt + 1} failed (${status})`);\n // The previous cycle already ended in network errors, so this one does not spend\n // its whole retry budget re-proving it. One attempt per cycle until the breaker opens.\n if (!answered && breaker?.suspect()) break;\n if (attempt < this.config.maxRetries) await this.deps.sleep(backoffMs(attempt));\n }\n if (!answered) {\n breaker?.fail();\n } else {\n breaker?.ok(); // reachable, whatever it said\n if (status > 199 && status < 300) this.strikes = 0;\n else if (refused(status) || isRetryable(status)) {\n // Without this pause the next capture started a fresh six-attempt cycle at once, and a\n // struggling collector was hit continuously by every busy tab (WC-10).\n if (refused(status)) this.deps.logger.notice(`collector refused uploads (${status}); paused`);\n breaker?.hold(this.wait || Math.min(HOLD_BASE_MS * 2 ** this.strikes++, HOLD_MAX_MS));\n }\n }\n return status;\n }\n\n private buildPayload(batch: DepsmithSdkEvent[]): BatchPayload {\n const payload: BatchPayload = {\n batch,\n api_key: this.config.apiKey,\n source: 'sdk',\n sent_at: isoTimestamp(this.deps.clock.now()),\n };\n if (this.config.anonymizeIp) payload.anonymize_ip = true;\n return payload;\n }\n\n /** Returns HTTP status; 0 for network errors/timeouts. */\n private async post(batch: DepsmithSdkEvent[]): Promise<number> {\n this.wait = 0;\n const json = JSON.stringify(this.buildPayload(batch));\n // Declared outside the try so the finally can always clear it.\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n try {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n // Null means plain JSON: compression off, unsupported, or failed.\n const zipped = await compress(json, this.config.compression);\n if (zipped) headers['Content-Encoding'] = 'gzip';\n const body: BodyInit = zipped ?? json;\n // Oversized bodies are rejected outright by the UA when keepalive is set, and the\n // payload is deterministic — so it would fail identically on every retry and the\n // batch would never drain. A plain fetch has no size cap; the only thing given up\n // is surviving page teardown, which beats never delivering at all.\n const keepalive = bodyBytes(body) <= KEEPALIVE_MAX_BYTES;\n if (!keepalive) {\n this.deps.logger.debug('payload over keepalive cap; sending without keepalive');\n }\n\n const init: RequestInit = { method: 'POST', headers, body, keepalive };\n if (controller) {\n init.signal = controller.signal;\n // AbortController rather than AbortSignal.timeout(): the build targets es2020\n // and AbortSignal.timeout is a 2022 API.\n timer = setTimeout(() => controller.abort(), this.timeoutMs());\n }\n\n const res = await this.deps.fetchFn(`${this.config.endpoint}/e/`, init);\n // fetch follows redirects, so a 3xx never reaches us: a captive portal's 302 to its 200\n // login page would read as delivered and delete the batch. Whatever answered at the end\n // of a redirect is not the collector — refused, like the 3xx it was.\n if (res.redirected) return REDIRECTED;\n // Readable cross-origin only if the collector lists it in Access-Control-Expose-Headers.\n this.wait = retryAfterMs(res.headers?.get('Retry-After'), this.deps.clock.now());\n return res.status;\n } catch {\n // Includes AbortError. isRetryable(0) is true, so a timeout retries with backoff.\n return 0;\n } finally {\n if (timer !== null) clearTimeout(timer);\n }\n }\n\n private timeoutMs(): number {\n const configured = this.config.requestTimeoutMs;\n return typeof configured === 'number' && configured > 0 ? configured : REQUEST_TIMEOUT_MS;\n }\n\n /** The `pagehide` drain — see `beacon.ts`. Skips the batch a fetch upload has in flight. */\n sendBeaconAll(): void {\n sendBeacons(this.queue, this.config, this.deps, this.uploading, (batch) =>\n this.buildPayload(batch)\n );\n }\n}\n","import type { KVStorage } from '../queue/storage';\nimport type { Clock } from '../utils/clock';\n\n/** Persisted so a visitor who cannot reach the collector does not restart the storm per page. */\nexport const KEY_NET_BREAKER = 'depsmith_net_breaker';\n\n/** Consecutive flush cycles that got no HTTP response at all before uploads pause. */\nexport const TRIP_AFTER_CYCLES = 3;\nexport const BASE_COOLDOWN_MS = 5 * 60_000;\nexport const MAX_COOLDOWN_MS = 60 * 60_000;\n\nexport interface NetworkBreaker {\n /** True while cooling down: the caller skips the network entirely. */\n open(): boolean;\n /**\n * True once a cycle has already ended in network errors. The next network error then ends\n * its cycle at once instead of spending the full retry budget on a host that just failed.\n */\n suspect(): boolean;\n /** A cycle ended with status 0 on every attempt it made. */\n fail(): void;\n /** The collector answered with any HTTP status, or connectivity changed. Closes it. */\n ok(): void;\n /**\n * The collector answered but asked for a pause (refused key, Retry-After, …): stay open for\n * `ms`, capped at MAX_COOLDOWN_MS. Persisted like a trip. No request is made while it\n * runs, so nothing calls `ok()` early except a connectivity change after a network trip.\n */\n hold(ms: number): void;\n}\n\n/**\n * Circuit breaker for a collector the browser cannot reach (API_SPEC §10).\n *\n * Status 0 is retryable because it is usually a blip. It is also exactly what an\n * ad-blocker, a DNS filter or a CORS misconfiguration produces, and those never heal: each\n * flush cycle then stringifies, gzips and persists a batch, fails six times in a row, and\n * logs an error per attempt — every 60 s, every 20 events, on every page, for the whole\n * visit. Only status 0 counts. Any HTTP response, error statuses included, proves the\n * collector is reachable and closes the breaker; 5xx/429 keep the ordinary backoff.\n *\n * Events are never dropped here. A paused cycle leaves the queue untouched, so the\n * at-least-once guarantee is the same as for any other requeue.\n *\n * A closure over locals rather than a class: property and method names survive\n * minification, and the core bundle has a size gate this would otherwise exceed.\n * Persisted as `[failures, openUntil, nextCooldownMs]` for the same reason.\n */\nexport function createNetworkBreaker(storage: KVStorage, clock: Clock): NetworkBreaker {\n let loaded = false;\n let failures = 0;\n /** Epoch ms; uploads are skipped while `now < openUntil`. 0 = closed. */\n let openUntil = 0;\n /** The cooldown the NEXT trip uses. Doubles per trip, capped at MAX_COOLDOWN_MS. */\n let cooldown = BASE_COOLDOWN_MS;\n\n const clamp = (v: unknown, lo: number, hi: number): number =>\n typeof v === 'number' && v === v ? Math.min(Math.max(v, lo), hi) : lo;\n\n // Read lazily, not at construction: IndexedDB and Shopify's async storage are only\n // hydrated by the first flush, and an eager read would always see them empty.\n const load = (): void => {\n if (loaded) return;\n loaded = true;\n try {\n const s = JSON.parse(storage.get(KEY_NET_BREAKER) ?? '0') as unknown;\n if (!Array.isArray(s)) return;\n failures = clamp(s[0], 0, TRIP_AFTER_CYCLES);\n // Clamped so a corrupt or clock-skewed value can never pause uploads for longer\n // than one maximum cooldown from now.\n openUntil = clamp(s[1], 0, clock.now() + MAX_COOLDOWN_MS);\n cooldown = clamp(s[2], BASE_COOLDOWN_MS, MAX_COOLDOWN_MS);\n } catch {\n // unreadable state is the same as none: closed\n }\n };\n\n const save = (): void => {\n try {\n if (failures || openUntil > clock.now()) storage.set(KEY_NET_BREAKER, JSON.stringify([failures, openUntil, cooldown]));\n else storage.remove(KEY_NET_BREAKER);\n } catch {\n // storage full or denied: the in-memory state still protects this page\n }\n };\n\n return {\n // Re-clamped on every read: a clock set back during a pause must not stretch it past the cap.\n open: () => (load(), clock.now() < (openUntil = Math.min(openUntil, clock.now() + MAX_COOLDOWN_MS))),\n suspect: () => (load(), failures > 0),\n fail: () => {\n load();\n if (++failures >= TRIP_AFTER_CYCLES) {\n openUntil = clock.now() + cooldown;\n cooldown = Math.min(cooldown * 2, MAX_COOLDOWN_MS);\n // Left at the threshold, not zeroed: the single probe after the cooldown must\n // re-trip on failure rather than earning another three cycles of retries.\n failures = TRIP_AFTER_CYCLES;\n }\n save();\n },\n ok: () => {\n load();\n if (!failures) return;\n failures = openUntil = 0;\n cooldown = BASE_COOLDOWN_MS;\n save();\n },\n hold: (ms) => {\n load();\n openUntil = Math.max(openUntil, clock.now() + Math.min(ms, MAX_COOLDOWN_MS));\n save();\n },\n };\n}\n","/** Debug-gated logger. The SDK never throws to the host app; failures surface here in debug mode only. */\nexport class Logger {\n constructor(private enabled: boolean) {}\n\n setEnabled(enabled: boolean): void {\n this.enabled = enabled;\n }\n\n debug(...args: unknown[]): void {\n if (this.enabled) console.debug('[depsmith-sdk]', ...args);\n }\n\n warn(...args: unknown[]): void {\n if (this.enabled) console.warn('[depsmith-sdk]', ...args);\n }\n\n /**\n * Always printed, `debug` or not. Reserved for the collector refusing or discarding data\n * (API_SPEC §10): a site whose events are being dropped must be able to see it without\n * first knowing to turn debug on. Rare by construction — once per dropped batch or refused cycle.\n */\n notice(...args: unknown[]): void {\n console.warn('[depsmith-sdk]', ...args);\n }\n\n error(...args: unknown[]): void {\n if (this.enabled) console.error('[depsmith-sdk]', ...args);\n }\n}\n","/**\n * `scrubUrls`: opt-in removal of query strings and fragments from every URL the SDK sends.\n *\n * Off by default, and then nothing here runs: URLs are sent whole, as they always were. Reset\n * links, OAuth callbacks (`#access_token=`), signed storage URLs and search terms all live in the\n * query or fragment, so a site that has them can turn this on rather than suppress `context.page`\n * altogether.\n *\n * Applied once per event, on the finished event just before it is queued, so every source is\n * covered by one pass — the page context, the attribution block, autocapture and the network\n * error reporter — and the persisted queue never holds the unscrubbed form.\n */\nimport type { DepsmithSdkEvent } from './types';\n\n/** `true` drops every query parameter; `keepParams` names the ones to keep. Fragments always go. */\nexport type ScrubUrls = boolean | { keepParams?: string[] };\n\n/** Full URLs in `context.page` (url, referrer, previous_url) and `context.referrer`. */\nconst CONTEXT_KEYS = ['url', 'referrer', 'previous_url', 'initial_url'];\n/** URL-valued SDK properties. `$net_query` / `$net_fragment` are handled on their own. */\nconst URL_PROPERTIES = ['$ac_href', '$ac_form_action', '$net_url', '$fr_error_file'];\n\n/**\n * Removes the fragment, and every query parameter not in `keep`. String surgery rather than\n * `new URL`, so relative URLs (a form's raw `action`) and unparseable ones are handled too, and a\n * kept parameter is sent exactly as it was written.\n */\nexport function scrubUrl(url: string, keep: ReadonlySet<string>): string {\n const bare = url.split('#')[0]!;\n const q = bare.indexOf('?');\n if (q < 0) return bare;\n const kept = bare\n .slice(q + 1)\n .split('&')\n .filter((pair) => keep.has(paramName(pair)));\n return bare.slice(0, q) + (kept.length ? `?${kept.join('&')}` : '');\n}\n\nfunction paramName(pair: string): string {\n const name = pair.split('=')[0]!.replace(/\\+/g, ' ');\n try {\n return decodeURIComponent(name);\n } catch {\n return name;\n }\n}\n\n/**\n * Scrubs `event` in place. A no-op unless `option` turns scrubbing on. Never throws. Fields the\n * host wrote itself are left alone: only SDK-owned keys are touched.\n */\nexport function scrubEventUrls(event: DepsmithSdkEvent, option: ScrubUrls | undefined): void {\n if (!option) return;\n try {\n const params = (option as { keepParams?: unknown }).keepParams;\n const keep = new Set(Array.isArray(params) ? params : []);\n const targets: Array<[Record<string, unknown> | undefined, string[]]> = [\n [event.context.page, CONTEXT_KEYS],\n [event.context.referrer, CONTEXT_KEYS],\n [event.properties, URL_PROPERTIES],\n ];\n for (const [target, keys] of targets) {\n for (const key of keys) {\n const value = target?.[key];\n if (typeof value === 'string') target![key] = scrubUrl(value, keep);\n }\n }\n const props = event.properties;\n if (!props) return;\n delete props.$net_fragment;\n if (typeof props.$net_query === 'string') {\n const query = scrubUrl(`?${props.$net_query}`, keep).slice(1);\n if (query) props.$net_query = query;\n else delete props.$net_query;\n }\n } catch {\n /* never lose an event to the scrubber */\n }\n}\n","import { Attribution } from './attribution';\nimport { PageLifecycle } from './page';\n// Separate module so the Shopify pixel build can compile the handlers away — it always passes\n// `manualLifecycle`. See src/lifecycle.noop.ts.\nimport { startLifecycle, type BrowserLifecycle } from './lifecycle';\nimport { loadAutocapture } from './autocapture/load';\nimport { resolveConfig, type DepsmithSdkConfig, type ResolvedConfig } from './config';\nimport {\n buildContext,\n dntEnabled,\n LIBRARY_NAME,\n SDK_VERSION,\n type ContextOptions,\n} from './context';\nimport { computeVisitorId, fingerprintComponents, primeClientHints } from './fingerprint';\nimport { primeGeolocation } from './geolocation';\nimport { ConsentManager } from './consent';\nimport { EventQueue } from './queue/tab-queue';\nimport {\n CookieAdapter,\n MemoryAdapter,\n RedundantAdapter,\n type KVStorage,\n} from './queue/storage';\n// Separate module so the Shopify pixel build can compile these away — it always injects its own\n// storage, so neither adapter is reachable there. See src/queue/storage-local.noop.ts.\nimport { defaultStorage, hydrateQueue, pickQueueStorage } from './queue/storage-local';\nimport { IdentityManager } from './identity';\nimport { SessionManager, type SessionTouch } from './session';\nimport { sanitizeProperties } from './props';\nimport { isReserved, stripReserved } from './reserved';\nimport { observeNetworkErrors } from './network-errors';\nimport { observeVitals, type Vitals } from './web-vitals';\nimport { SuperProperties } from './super-properties';\nimport { normalizeUserPropertyOps, sanitizedTraitOp, type UserPropertyOps } from './user-properties';\nimport { BatchUploader } from './transport/uploader';\nimport { createNetworkBreaker, KEY_NET_BREAKER } from './transport/breaker';\nimport { isoTimestamp, systemClock, type Clock } from './utils/clock';\nimport { Logger } from './utils/logger';\nimport { uuidv7 } from './utils/uuidv7';\nimport type { Scheduler } from './utils/scheduler';\nimport { bucket, djb2 } from './hash';\nimport { scrubEventUrls } from './url-scrub';\nimport type { DepsmithSdkEvent, EventContext, EventType, PageOptions, Properties } from './types';\n\n/** The fingerprint of the apiKey that last initialised on this origin (see detectConfigDrift). */\nconst KEY_CONFIG_FP = 'depsmith_config_fp';\n\n/**\n * Mirrors the `maxLength` on `event`, `user_id` and `group_id` in event.schema.json. Enforced\n * client-side because the collector enforces it with a 400, and a 400 costs the event plus the\n * requests the uploader spends bisecting down to it (API_SPEC §10).\n */\nconst MAX_ENVELOPE_ID_LENGTH = 255;\n\n/** Test/conformance seams. Not part of the public API contract. */\nexport interface InternalOverrides {\n storage?: KVStorage;\n clock?: Clock;\n fetchFn?: typeof fetch;\n isOnline?: () => boolean;\n sleep?: (ms: number) => Promise<void>;\n dnt?: boolean;\n /** Per-attempt upload timeout. Test seam so a hung-request test needn't wait 30s. */\n requestTimeoutMs?: number;\n /** Disable timers/listeners (conformance runners drive flushes explicitly). */\n manualLifecycle?: boolean;\n /**\n * Called at capture time for host-supplied `context` fields, shallow-merged over the\n * derived ones. Used by the Shopify web-pixel adapter, which gets fresh page context\n * on every event and cannot read the real `window`/`document`.\n */\n contextProvider?: () => Partial<EventContext>;\n /**\n * How queue/session persistence is deferred. Defaults to an idle callback, which is what\n * keeps the blocking `localStorage` write off the capture path. Pass `syncScheduler` to\n * restore write-through — tests do, and so does any host whose storage is already\n * non-blocking (the Shopify pixel's async-mirrored storage).\n */\n schedule?: Scheduler;\n}\n\nexport class DepsmithSdkClient {\n private config: ResolvedConfig;\n private logger: Logger;\n private storage: KVStorage;\n private clock: Clock;\n private identity: IdentityManager;\n private session: SessionManager;\n private consent: ConsentManager;\n private attribution: Attribution;\n private superProperties: SuperProperties;\n /**\n * `$page_view` / `$page_leave` and the navigation half of `context.page`. Everything but this\n * handle lives in `page.ts`, which the Shopify pixel build swaps for a no-op — see the note\n * on {@link PageLifecycle}.\n */\n private pageLife: PageLifecycle;\n /**\n * Autocapture's unload-time `$page_leave` trigger, when pageview tracking is on.\n *\n * The client owns the call site rather than autocapture, because it must run BEFORE the\n * teardown drain — see `lifecycle.ts`. Undefined means no page-leave tracking:\n * autocapture is off, compiled out, or still loading.\n */\n private leaveOnUnload?: () => void;\n /** Core Web Vitals, when autocapture is on. Reported once, on the first hide. */\n private vitals?: Vitals;\n /** Set once $web_vitals has been emitted, so a tab shown and hidden again does not repeat it. */\n private vitalsReported = false;\n private queue: EventQueue;\n private uploader: BatchUploader;\n /** Timer and page listeners. Undefined under `manualLifecycle`, and in the pixel build. */\n private lifecycle?: BrowserLifecycle;\n /** Set by shutdown(); a lazily loaded autocapture chunk checks it before starting. */\n private stopped = false;\n private teardownFns: Array<() => void> = [];\n private contextProvider?: () => Partial<EventContext>;\n\n /** Resolves once async storage (IndexedDB) is hydrated; uploads gate on this. */\n private ready: Promise<void> = Promise.resolve();\n\n constructor(config: DepsmithSdkConfig, overrides: InternalOverrides = {}) {\n this.config = resolveConfig(config); // throws on invalid config — the one construction-time error\n this.logger = new Logger(this.config.debug);\n this.clock = overrides.clock ?? systemClock;\n this.storage = overrides.storage ?? this.pickStorage();\n // `storage: 'indexeddb'` moves the QUEUE to IndexedDB (the larger quota is the point) and\n // nothing else. IndexedDB can only be read asynchronously, and consent, identity, session\n // and the config fingerprint are all read synchronously right here in the constructor —\n // on a store that had not loaded yet they were simply absent. A persisted opt-out was\n // ignored on every page load, each load minted a new session, and apiKey drift was never\n // seen. Those keys now stay in the synchronous store; only the queue waits for hydration.\n const queueStorage = overrides.storage\n ? this.storage\n : pickQueueStorage(this.config.storage, this.storage);\n this.contextProvider = overrides.contextProvider;\n this.pageLife = new PageLifecycle(\n {\n now: () => this.clock.now(),\n capture: (name, type, properties, at, page) =>\n this.capture(name, type, properties, undefined, undefined, at, page),\n },\n this.config\n );\n\n // COPPA child-safe mode: identity is memory-only (nothing identifying persists).\n // Otherwise cookieDomain moves identity keys to a cross-subdomain cookie.\n // Identity lives in TWO first-party stores, read-any/write-both, so losing either one does\n // not make a returning visitor look new — localStorage and cookies are cleared by different\n // user actions and different browser policies. `cookieDomain` still widens the cookie across\n // subdomains when set; without it the cookie is host-only, which needs no configuration.\n //\n // Skipped for `storage: 'memory'`, which is the SSR/test backend: someone who asked for no\n // persistence should not get a cookie. And for childSafeMode, where COPPA requires that\n // nothing identifying persists at all.\n const identityStorage: KVStorage = this.config.childSafeMode\n ? new MemoryAdapter()\n : this.config.storage === 'memory'\n ? this.storage\n : new RedundantAdapter(\n this.storage,\n new CookieAdapter(this.config.cookieDomain || undefined)\n );\n\n this.identity = new IdentityManager(identityStorage, this.clock);\n this.session = new SessionManager(\n this.storage,\n this.clock,\n this.config.sessionTimeoutMs,\n overrides.schedule\n );\n this.consent = new ConsentManager(\n this.storage,\n this.config.consentMode,\n this.config.respectDnt && (overrides.dnt ?? dntEnabled())\n );\n // Shares `identityStorage`, not `this.storage`: attribution is visitor-scoped like the\n // anonymous_id, so COPPA's memory-only rule and the cookie mirror must apply to it too.\n // A campaign surviving in localStorage after childSafeMode moved identity to memory would\n // re-link a child across launches by their acquisition source.\n this.attribution = new Attribution(identityStorage);\n // Plain `this.storage`, NOT identityStorage: registered properties are app state the client\n // chose (plan, A/B variant, store id), not identity — so the cookie mirror and COPPA's\n // memory-only rule do not apply to them.\n this.superProperties = new SuperProperties(this.storage, this.logger);\n // Record the landing before anything can capture, so the first event already carries it.\n //\n // Skipped when the host supplies a contextProvider, which is precisely the \"my globals are\n // not the page\" signal — the Shopify pixel's `window.location` points at its sandbox, not\n // the storefront. Writing from there would store the sandbox URL as the acquisition source\n // and, because the pixel shares these keys with the theme build through AsyncMirrorAdapter,\n // could overwrite the theme's correctly-captured campaign or pin first-touch to `$direct`\n // before the theme half ever ran. The pixel still READS the shared values and emits them,\n // so checkout events inherit the campaign the theme captured.\n if (!this.contextProvider && typeof window !== 'undefined' && window.location) {\n this.attribution.recordLanding(\n window.location.href,\n typeof document !== 'undefined' ? document.referrer : ''\n );\n // Seeds previous_url / previous_type / counter for the very first event, which may be a\n // $session_start emitted before any $page_view.\n this.pageLife.start(\n window.location.href,\n typeof document !== 'undefined' ? document.referrer : ''\n );\n }\n // The queue key is shared by every apiKey on the origin (deep-dive WC-11): it cannot be\n // namespaced without stranding queues the Shopify pixel mirrors by fixed key. So a write is\n // made only while this project still owns the origin (the config fingerprint is its own).\n // Once another apiKey has initialised here, this instance stops persisting — its events\n // still upload while the page lives — so none can be restored and sent under that key.\n const fp = djb2(this.config.apiKey);\n const owned: KVStorage = {\n get: (key) => queueStorage.get(key),\n set: (key, value) => {\n if (this.storage.get(KEY_CONFIG_FP) === fp) queueStorage.set(key, value);\n },\n remove: (key) => queueStorage.remove(key),\n };\n this.queue = new EventQueue(owned, this.config.maxQueueSize, this.logger, {\n maxChars: this.config.maxQueueBytes,\n schedule: overrides.schedule,\n });\n const drifted = this.detectConfigDrift(fp);\n this.primeDeviceSignals();\n\n // IndexedDB write-behind: merge the persisted queue once hydrated, gate uploads until then.\n this.ready = hydrateQueue(queueStorage, this.storage, this.consent, this.queue, drifted, this.logger);\n\n this.uploader = new BatchUploader(\n this.queue,\n {\n endpoint: this.config.endpoint,\n apiKey: this.config.apiKey,\n batchSize: this.config.batchSize,\n maxRetries: this.config.maxRetries,\n compression: this.config.compression,\n anonymizeIp: this.config.anonymizeIp,\n requestTimeoutMs: overrides.requestTimeoutMs,\n },\n {\n fetchFn: overrides.fetchFn ?? ((...args) => fetch(...args)),\n clock: this.clock,\n logger: this.logger,\n sleep: overrides.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))),\n isOnline:\n overrides.isOnline ??\n (() => (typeof navigator === 'undefined' ? true : navigator.onLine !== false)),\n breaker: createNetworkBreaker(this.storage, this.clock),\n canUpload: () => this.consent.canUpload(),\n }\n );\n\n if (!overrides.manualLifecycle) {\n this.lifecycle = startLifecycle({\n intervalMs: this.config.batchIntervalMs,\n guard: (fn) => this.guard(fn),\n vitals: () => this.emitWebVitals(),\n leave: () => this.leaveOnUnload?.(),\n restored: (persisted) => this.pageLife.restored(persisted),\n resume: () => this.resumeSession(),\n flushIfQueued: () => this.flushIfQueued(),\n persistNow: () => this.persistNow(),\n beacon: () => {\n if (this.consent.canUpload()) this.uploader.sendBeaconAll();\n },\n online: () => {\n // A network change is the one signal that a paused collector may be reachable again.\n this.uploader.resetNetworkBreaker();\n this.flushIfQueued();\n },\n });\n this.startAutocapture();\n }\n this.logger.debug('initialized', { endpoint: this.config.endpoint });\n }\n\n // ── Public API (API_SPEC §2) — every method is guarded: never throws ──────────\n\n track(name: string, properties?: Properties): void {\n this.trackInternal(name, stripReserved(properties, 'track', this.logger));\n }\n\n /**\n * `track()` without the `$`-key check on properties, for the SDK's own integrations. Not part\n * of the public API: the Shopify pixel needs it because it stamps `$shopify_client_id` on every\n * event it maps, which a public `track()` would now drop as reserved. Event names are checked\n * exactly as in `track()`.\n */\n trackInternal(name: string, properties?: Properties): void {\n this.guard(() => {\n if (typeof name !== 'string' || name.length === 0) {\n this.logger.warn('track: event name required');\n return;\n }\n if (isReserved(name, 'track', this.logger)) return;\n if (this.tooLong(name, 'track: event name')) return;\n this.capture(name, 'track', properties);\n });\n }\n\n /**\n * Rejects an envelope id the collector's schema would refuse, at the point it enters the SDK.\n *\n * Dropping the call is harsh, and it is the lesser harm. `event`, `user_id` and `group_id` are\n * all capped at 255 in event.schema.json, the collector validates every batch with Ajv, and a\n * 400 is non-retryable — the uploader bisects the batch and drops the event that fails. For\n * `user_id` and `group_id` that is not a one-event loss either: both are persisted and ride on\n * every subsequent event, so a single over-long id silently destroys everything that user sends\n * until reset(). A JWT or a concatenated composite key passed as a user id does it.\n *\n * Truncating instead would keep the events but silently merge two users sharing a 255-char\n * prefix, inventing data rather than losing it. Rejecting a schema-invalid value at capture is\n * the rule throughout: such an event would 400 and be dropped at upload, after a bisection.\n */\n /** Client traits as sent: `$` keys dropped, then sanitised like event properties. */\n private traits(traits: Properties | undefined, method: string): Properties {\n return sanitizeProperties(stripReserved(traits, method, this.logger), this.logger);\n }\n\n private tooLong(value: string, label: string): boolean {\n if (value.length <= MAX_ENVELOPE_ID_LENGTH) return false;\n this.logger.warn(\n `${label} exceeds ${MAX_ENVELOPE_ID_LENGTH} characters (got ${value.length}); dropped`\n );\n return true;\n }\n\n /** `options.type` is sent as `$page_type` (API_SPEC §2). */\n page(name?: string, properties?: Properties, options?: PageOptions): void {\n this.pageInternal(name, stripReserved(properties, 'page', this.logger), options);\n }\n\n /**\n * `page()` without the `$`-key check, for the SDK's own integrations. Not part of the public\n * API: the Shopify pixel sends checkout page views with `$checkout_step` and\n * `$shopify_client_id`, which a public `page()` would now drop as reserved. Still a manual\n * view — it is a call, not autocapture.\n *\n * Advances navigation state even for an explicit call, so an app that drives pageviews by hand\n * (no autocapture) still gets previous_url and counter — and claims the URL so autocapture\n * cannot emit a second view for the same page.\n */\n pageInternal(name?: string, properties?: Properties, options?: PageOptions): void {\n this.guard(() => this.pageLife.manual(name, properties, options?.type));\n }\n\n /**\n * `$web_vitals`, once per page, on the first time the tab is hidden.\n *\n * Hidden rather than loaded, because three of the five are not final until then: LCP can be\n * superseded by a later paint, CLS accumulates for the life of the page, and INP is the worst\n * interaction so far. Reporting at load would under-report all three — worse than not reporting,\n * because the numbers would look plausible.\n *\n * Once, not per hide: a tab switched away and back has the same page-load metrics, and a second\n * event would double-count the page in every average built on it.\n */\n private emitWebVitals(): void {\n if (this.vitalsReported || !this.vitals?.hasAny()) return;\n this.vitalsReported = true;\n this.capture('$web_vitals', 'track', this.vitals.snapshot());\n }\n\n /** Alias of page() — unified mobile naming. */\n screen(name?: string, properties?: Properties, options?: PageOptions): void {\n this.page(name, properties, options);\n }\n\n identify(userId: string, traits?: Properties): void {\n this.guard(() => {\n if (this.config.childSafeMode) {\n this.logger.warn('identify: disabled in childSafeMode (COPPA)');\n return;\n }\n if (typeof userId !== 'string' || userId.length === 0) {\n this.logger.warn('identify: userId required');\n return;\n }\n // Before identity.identify(), which PERSISTS it onto every subsequent event.\n if (this.tooLong(userId, 'identify: userId')) return;\n this.identity.identify(userId);\n const clean = this.traits(traits, 'identify');\n // Traits keep riding on context.traits, where every existing consumer reads them, AND\n // now describe a $set so they actually land as user properties. Before this they did\n // not: the collector applies `user_properties` only, so identify() traits reached the\n // warehouse as event context and never as properties of the person.\n this.capture('$identify', 'identify', undefined, clean, sanitizedTraitOp('$set', clean));\n });\n }\n\n alias(aliasId: string): void {\n this.guard(() => {\n if (this.config.childSafeMode) {\n this.logger.warn('alias: disabled in childSafeMode (COPPA)');\n return;\n }\n if (typeof aliasId !== 'string' || aliasId.length === 0) {\n this.logger.warn('alias: aliasId required');\n return;\n }\n this.capture('$alias', 'alias', { alias: aliasId });\n });\n }\n\n reset(): void {\n this.guard(() => {\n // A page view still waiting for its title belongs to the user being reset.\n this.pageLife.flushPending();\n this.identity.reset();\n this.session.rotate();\n // Forgetting the visitor has to include forgetting where they came from, otherwise the\n // next person on a shared browser inherits the previous one's acquisition source.\n this.attribution.clear();\n this.superProperties.clear();\n this.logger.debug('reset: identity, session and attribution cleared');\n });\n }\n\n group(groupId: string, traits?: Properties): void {\n this.guard(() => {\n if (typeof groupId !== 'string' || groupId.length === 0) {\n this.logger.warn('group: groupId required');\n return;\n }\n // Before identity.setGroup(), which PERSISTS it onto every subsequent event.\n if (this.tooLong(groupId, 'group: groupId')) return;\n this.identity.setGroup(groupId);\n const clean = this.traits(traits, 'group');\n this.capture('$group', 'group', undefined, clean);\n });\n }\n\n setGroupTraits(traits: Properties): void {\n this.guard(() => {\n if (!this.identity.groupId) {\n this.logger.warn('setGroupTraits: no group set');\n return;\n }\n const clean = this.traits(traits, 'setGroupTraits');\n this.capture('$group', 'group', undefined, clean);\n });\n }\n\n setProperty(key: string, value: Properties[string]): void {\n this.guard(() => {\n if (isReserved(key, 'setProperty', this.logger)) return;\n this.setUserProp(key, value, '$set');\n });\n }\n\n /** The shared tail of setProperty / setOnceProperty: remember it locally, emit the operator. */\n private setUserProp(key: string, value: Properties[string], op: '$set' | '$set_once'): void {\n this.identity.setUserProp(key, value);\n const traits = sanitizeProperties({ [key]: value }, this.logger);\n this.capture('$identify', 'identify', undefined, traits, sanitizedTraitOp(op, traits));\n }\n\n /**\n * Sets a property only if this device has not already set it.\n *\n * The local check is the cross-SDK contract (`spec/conformance/fixtures/\n * user_props_set_setonce_unset.json` asserts that a repeat call emits nothing), so it\n * stays. It is an optimisation, not the guarantee: a client can only see THIS device, and\n * a returning visitor on a second browser looks like a first write. `$set_once` closes\n * that, because the collector evaluates it against the stored identity.\n */\n setOnceProperty(key: string, value: Properties[string]): void {\n this.guard(() => {\n if (isReserved(key, 'setOnceProperty', this.logger)) return;\n if (this.identity.hasUserProp(key)) {\n this.logger.debug(`setOnceProperty: \"${key}\" already set`);\n return;\n }\n this.setUserProp(key, value, '$set_once');\n });\n }\n\n unsetProperty(key: string): void {\n this.guard(() => {\n if (isReserved(key, 'unsetProperty', this.logger)) return;\n this.identity.unsetUserProp(key);\n this.capture(\n '$identify',\n 'identify',\n undefined,\n { [key]: null },\n normalizeUserPropertyOps({ $unset: [key] }, this.logger)\n );\n });\n }\n\n /**\n * Applies user-property operators server-side (API_SPEC §14).\n *\n * The whole closed operator set in one call — `$set`, `$set_once`, `$add`, `$append`,\n * `$prepend`, `$pre_insert`, `$post_insert`, `$remove`, `$unset`, `$clear_all` — rather\n * than ten methods, because the set is fixed by the schema and a typed map keeps the\n * public surface proportional to what it buys.\n *\n * `$add` is the reason this exists at all: incrementing on the client is a\n * read-modify-write race between tabs, and no amount of care on one device fixes it.\n *\n * Unlike the three convenience methods above, this sends NO `context.traits`. Those carry\n * traits for compatibility with consumers that read them today; a caller reaching for the\n * operators directly is asking for the server-applied semantics, and duplicating an\n * `$append` into a trait would misreport it as an overwrite.\n *\n * Silently does nothing when nothing survives validation — a key claimed twice, a\n * non-finite `$add`, an empty map — since the schema forbids an empty operator object.\n */\n /**\n * Registers properties attached to every later event, surviving a reload.\n *\n * A property passed directly to `track()` wins over a registered one with the same key.\n * `$`-prefixed keys are rejected, as everywhere else. Cleared by `reset()`.\n */\n register(properties: Properties): void {\n this.guard(() => this.superProperties.register(properties));\n }\n\n /**\n * Registers only keys that are not registered yet — for first-touch values like the plan a user\n * signed up on, which a later state change must not overwrite.\n */\n registerOnce(properties: Properties): void {\n this.guard(() => this.superProperties.registerOnce(properties));\n }\n\n unregister(key: string): void {\n this.guard(() => this.superProperties.unregister(key));\n }\n\n setUserProperties(ops: UserPropertyOps): void {\n this.guard(() => {\n const normalized = normalizeUserPropertyOps(ops, this.logger);\n if (!normalized) return;\n this.capture('$identify', 'identify', undefined, undefined, normalized);\n });\n }\n\n optIn(): void {\n this.guard(() => {\n this.consent.optIn();\n this.logger.debug('consent granted');\n this.primeDeviceSignals();\n void this.flushUploads();\n });\n }\n\n optOut(): void {\n this.guard(() => {\n // Discarded, not flushed: never send an event at the moment the visitor opts out.\n this.pageLife.discardPending();\n this.consent.optOut();\n this.queue.clear();\n this.logger.debug('consent denied; queue cleared');\n });\n }\n\n async flush(): Promise<void> {\n try {\n if (!this.consent.canUpload()) {\n this.logger.debug('flush skipped: consent not granted');\n return;\n }\n await this.flushUploads(); // persists, then gates on IndexedDB hydration\n } catch (err) {\n this.logger.error('flush error', err);\n }\n }\n\n /**\n * Autocapture engine entry point ($autocapture events). Not part of the public API —\n * the lazily-loaded engine calls this through its `emit` hook.\n *\n * Named rather than inlined into startAutocapture() so the conformance runner can drive\n * it by reflection, exactly as Android's `autocapture()` and iOS's `autocapture(_:)`\n * already allow. Without a named entry point the whole subsystem is unreachable from a\n * shared fixture, which is why it had none.\n */\n autocapture(properties: Properties): void {\n this.guard(() => this.capture('$autocapture', 'autocapture', properties));\n }\n\n /** Conformance/testing: await any in-flight upload (incl. retries) without forcing one. */\n drainInFlight(): Promise<void> {\n return this.uploader.pending();\n }\n\n getAnonymousId(): string {\n return this.identity.anonymousId;\n }\n\n getSessionId(): string {\n return this.session.peek();\n }\n\n /**\n * Adopts an externally supplied session id, so a session can span a web→app handoff or\n * two contexts that do not share storage. Must be a UUIDv7; anything else is a debug-warn\n * no-op rather than a corrupted session. Emits no `$session_start` (API_SPEC §5).\n */\n setSessionId(sessionId: string, startedAt?: number): void {\n this.guard(() => {\n if (typeof sessionId !== 'string' || !this.session.adopt(sessionId, startedAt)) {\n this.logger.warn(`setSessionId: expected a UUIDv7; ignored \"${String(sessionId)}\"`);\n }\n });\n }\n\n /** Stops timers/listeners. Queued events stay persisted. */\n shutdown(): void {\n // Before the teardown and the write below, so a view waiting for its title is kept.\n this.guard(() => this.pageLife.flushPending());\n this.stopped = true;\n this.lifecycle?.stop();\n for (const fn of this.teardownFns.splice(0)) fn();\n // Nothing will run the deferred writes once the timers are gone.\n this.persistNow();\n this.queue.close();\n }\n\n /**\n * Forces the write-behind queue and session state to storage now.\n *\n * Persistence is deferred to an idle callback so a captured event does not pay a\n * blocking `localStorage` write on the interaction that produced it. This is the escape\n * hatch for the moments where there may be no later tick: page teardown and shutdown.\n */\n private persistNow(): void {\n try {\n this.queue.persistNow();\n this.session.persistNow();\n } catch {\n /* storage unavailable — events stay in memory, nothing else to do */\n }\n }\n\n /**\n * Device signals (fingerprint, Client Hints, position) may be read and sent: not COPPA mode,\n * and consent granted — `canUpload()` is false while pending, after opt-out and under DNT.\n * The ONE gate for both the reads below and the emission in `contextOptions()` (#87).\n */\n private deviceSignals(): boolean {\n return !this.config.childSafeMode && this.consent.canUpload();\n }\n\n /**\n * Starts the once-per-document device-signal reads (high-entropy Client Hints, and the\n * geolocation permission query + position), off the capture path — only when their results\n * could be sent. Under pending or denied consent, or DNT, nothing is read; `optIn()` calls\n * this again. Defaults are unchanged: this only skips reads whose results would be discarded.\n * The geolocation gate is re-checked before every later read (permission change, stale-fix\n * refresh), so `optOut()` stops those too.\n */\n private primeDeviceSignals(): void {\n if (!this.deviceSignals()) return;\n if (this.config.deviceFingerprinting) primeClientHints();\n // One permission query per document, and a position read only from an already-granted\n // state (never a prompt).\n if (this.config.geolocation) primeGeolocation(() => this.deviceSignals());\n }\n\n /** Queues an event and re-arms the teardown drain — see {@link BrowserLifecycle.rearm}. */\n private enqueueEvent(event: DepsmithSdkEvent): void {\n scrubEventUrls(event, this.config.scrubUrls);\n this.queue.enqueue(event);\n this.lifecycle?.rearm();\n }\n\n /**\n * The single entry point for starting an upload.\n *\n * Persistence is NOT forced here. API_SPEC §1 step 4 (durable storage before any network\n * attempt) is upheld inside the uploader's drain loop, which persists per batch it is\n * about to send. Forcing it here instead meant a synchronous write on every capture once\n * the queue sat at or above `batchSize` — which is the regression this whole change\n * exists to remove, reappearing in the exact case that matters most (a backed-up queue).\n */\n private flushUploads(): Promise<void> {\n return this.ready.then(() => this.uploader.flush());\n }\n\n /** Starts an upload when there is something to send and consent allows it. */\n private flushIfQueued(): void {\n if (this.queue.size > 0 && this.consent.canUpload()) void this.flushUploads();\n }\n\n // ── Pipeline ──────────────────────────────────────────────────────────────────\n\n /**\n * Fingerprinting is on by default (opt-out via `deviceFingerprinting: false`) and\n * privacy-gated: it requires granted consent (consent.current is 'denied' under DNT and\n * never 'granted' while pending) and non-COPPA mode.\n */\n private contextOptions(): ContextOptions {\n let overrides: Partial<EventContext> | undefined;\n try {\n overrides = this.contextProvider?.();\n } catch {\n // a throwing host provider must not break capture\n }\n const signals = this.deviceSignals();\n return {\n fingerprint: this.config.deviceFingerprinting && signals,\n // Position is gated identically: a precise coordinate is at least as identifying as\n // a device fingerprint, so DNT, COPPA and ungranted consent all suppress it.\n geolocation: this.config.geolocation && signals,\n overrides,\n // Subtractive only: this narrows what the two gates above already allowed, it never\n // re-enables anything they suppressed (API_SPEC §12.2).\n tracking: this.config.trackingOptions,\n // Not gated on fingerprinting: campaign and referrer come from the landing URL and\n // document.referrer, which are not device signals. Consent still applies, because the\n // whole event is held back upstream when consent is pending.\n attribution: this.attribution,\n page: this.pageLife.tracking(),\n };\n }\n\n /**\n * Session-sticky sampling.\n *\n * The decision is derived from (apiKey, session_id) rather than drawn at random, so it\n * is stable for the session's whole lifetime and identical across tabs sharing that\n * session. A random draw per event would split sessions in half, which is worse than\n * useless: a funnel built from partial sessions is wrong rather than merely noisy.\n *\n * Salted with the apiKey so a future, independently-configured sampler at the same rate\n * does not select the identical set of sessions.\n *\n * Identity events are NEVER sampled. Dropping $identify for 90% of users would stop\n * their user properties applying at all — that is not less data, it is wrong data.\n * Everything else follows the session: a session is wholly in or wholly out. Scale\n * sampled metrics by 1/sampleRate.\n */\n private sessionInSample(sessionId: string): boolean {\n if (this.config.sampleRate >= 1) return true;\n return bucket(`${this.config.apiKey}:${sessionId}`) < this.config.sampleRate;\n }\n\n /** Identity events are exempt; everything else follows its session. */\n private inSample(sessionId: string, type: EventType): boolean {\n if (type === 'identify' || type === 'alias' || type === 'group') return true;\n return this.sessionInSample(sessionId);\n }\n\n private capture(\n name: string,\n type: EventType,\n properties?: Properties,\n traits?: Properties,\n userProperties?: UserPropertyOps,\n // A deferred `$page_view` (see PageLifecycle.autoPageView): stamped at its navigation, with\n // that page's `context.page`, however late it is sent.\n at?: number,\n page?: EventContext['page']\n ): void {\n if (!this.consent.canCapture()) {\n this.logger.debug(`capture dropped (consent denied): ${name}`);\n return;\n }\n\n // Sampling is evaluated AFTER the touch so a mid-page rotation is re-diced, and BEFORE\n // anything is enqueued so out-of-sample events never consume queue or storage — the\n // whole point of sampling at capture rather than at upload.\n const touch = this.touchSession();\n\n if (!this.inSample(touch.sessionId, type)) {\n this.logger.debug(`capture dropped (out of sample): ${name}`);\n return;\n }\n\n const now = at ?? this.clock.now();\n // Read once. It was being computed twice by the ternary below, and the device id needs\n // the same answer the context block got — two reads could straddle a consent change and\n // put a device_id on an event whose context was built without the fingerprint.\n const contextOptions = this.contextOptions();\n if (page) contextOptions.page = page;\n const event: DepsmithSdkEvent = {\n event_id: uuidv7(now),\n event: name,\n event_type: type,\n timestamp: isoTimestamp(now),\n session_id: touch.sessionId,\n session_started_at: isoTimestamp(touch.startedAt),\n anonymous_id: this.identity.anonymousId,\n context: traits\n ? { ...buildContext(contextOptions), traits }\n : buildContext(contextOptions),\n platform: 'Web',\n sdk_version: SDK_VERSION,\n };\n\n // §14 operators are described here and applied by the collector; the schema forbids an\n // empty map (`minProperties: 1`), so an op set that fully normalises away is omitted.\n if (userProperties) event.user_properties = userProperties;\n\n // Precedence, widest to narrowest: static config, then runtime registrations, then the call\n // site. A property passed to track() must win over a registered one — the call is the more\n // specific statement, and the reverse would make a per-event override impossible to express.\n //\n // The MERGED set is sanitised, not just the call site's. `defaultProperties` and registered\n // values come from the integrator too, and they ride on every event: one nested object or\n // BigInt there made the collector reject every batch (or threw before the enqueue), losing\n // all analytics until someone unregistered it — and a registered value is persisted, so a\n // reload did not help. Sanitising here also covers a value already sitting in storage, and\n // applies the 200-key cap to what is actually sent.\n const props = sanitizeProperties(\n {\n ...this.config.defaultProperties,\n ...this.superProperties.current(),\n ...sanitizeProperties(properties, this.logger),\n },\n this.logger\n );\n if (Object.keys(props).length > 0) event.properties = props;\n\n const userId = this.identity.userId;\n if (userId) event.user_id = userId;\n const groupId = this.identity.groupId;\n if (groupId) event.group_id = groupId;\n // Memoised per document (the canvas render is the only costly part), so this is a map\n // lookup after the first event.\n if (contextOptions.fingerprint) event.device_id = computeVisitorId();\n\n this.enqueueEvent(event);\n this.logger.debug(`captured ${name}`, event);\n\n if (this.queue.size >= this.config.batchSize && this.consent.canUpload()) {\n void this.flushUploads();\n }\n }\n\n /**\n * Config drift (guidelines §12): events queued under a different apiKey belong to\n * another project — drop them rather than misattribute. Fingerprint, not raw key.\n * The upload pause goes too: a 401 or Retry-After for that key says nothing about this one.\n */\n private detectConfigDrift(fingerprint: string): boolean {\n const stored = this.storage.get(KEY_CONFIG_FP);\n const drifted = stored !== null && stored !== fingerprint;\n if (drifted) {\n this.logger.warn('apiKey changed since last run; dropping queued events for the old project');\n this.queue.clear();\n this.storage.remove(KEY_NET_BREAKER);\n }\n this.storage.set(KEY_CONFIG_FP, fingerprint);\n return drifted;\n }\n\n /** The synchronous store. IndexedDB is never returned here — see the constructor. */\n private pickStorage(): KVStorage {\n return this.config.storage === 'memory' ? new MemoryAdapter() : defaultStorage();\n }\n\n /**\n * `$session_start` / `$session_end`, built in one place: the two envelopes differ only in\n * their name, their timestamp and the fingerprint components the opening one carries.\n */\n private enqueueSessionBoundary(\n kind: 'start' | 'end',\n id: string,\n at: number,\n startedAt: number\n ): void {\n // Checked here rather than at the call sites for the same reason the consent gate is:\n // the visibilitychange resume path reaches this without going through capture(), so a\n // gate placed at the call sites would be one `if` short of covering the feature.\n if (this.config.sessionEvents === 'derive') return;\n // Same gate capture() applies. This path is also reachable from the\n // visibilitychange handler, which does not go through capture() — without the\n // check, a denied visitor's anonymous_id was persisted to the queue on tab\n // resume, and would upload if consent later flipped to granted. Under `pending`\n // consent canCapture() is true, so it is queued and held — matching capture() exactly.\n if (!this.consent.canCapture()) {\n this.logger.debug(`session_${kind} dropped (consent denied)`);\n return;\n }\n const contextOptions = this.contextOptions();\n const event: DepsmithSdkEvent = {\n event_id: uuidv7(this.clock.now()),\n event: `$session_${kind}`,\n event_type: `session_${kind}`,\n timestamp: isoTimestamp(at),\n session_id: id,\n session_started_at: isoTimestamp(startedAt),\n anonymous_id: this.identity.anonymousId,\n context: buildContext(contextOptions),\n platform: 'Web',\n sdk_version: SDK_VERSION,\n };\n const userId = this.identity.userId;\n if (userId) event.user_id = userId;\n if (contextOptions.fingerprint) {\n event.device_id = computeVisitorId();\n // Fingerprint components ride the session-opening event and nothing else.\n //\n // The device id is a single opaque hash, so it cannot be matched approximately: one\n // signal drifting produces a completely different id, and a returning visitor who\n // cleared both stores is unrecoverable. Sending the parts lets the collector do N-of-M\n // matching and recover them instead. They cost a few hundred bytes and cannot change\n // within a session, so per-event transmission would be pure waste — the hash alone\n // stays on every event.\n //\n // Gated on the same `fingerprint` flag as device_id, so deviceFingerprinting,\n // childSafeMode, DNT and ungranted consent all suppress it identically. Note this means\n // `sessionEvents: 'derive'` transmits no components at all: that mode exists to stop\n // paying for boundary rows, and smuggling the payload onto an ordinary event would both\n // contradict that and pollute a caller's own event properties.\n if (kind === 'start') event.properties = fingerprintComponents();\n }\n this.enqueueEvent(event);\n }\n\n // ── Lifecycle ─────────────────────────────────────────────────────────────────\n\n /**\n * Stamps session activity and emits the boundary events that revealed. The one place a\n * session is touched, for capture() and for the tab-resume path alike: the resume path used\n * to emit both boundaries with no sample check, so at `sampleRate: 0.1` nine in ten resumed\n * sessions reached the warehouse as a bare `$session_start` with nothing after it.\n *\n * Order is load-bearing (API_SPEC §5): the old session's end precedes the new session's\n * start, and both precede the event that triggered the rotation.\n *\n * Each boundary follows ITS OWN session's sample decision, not the current event's: the\n * ending and starting sessions have different ids and can therefore decide differently, and\n * an exempt $identify must not drag a boundary event into an out-of-sample session.\n */\n private touchSession(): SessionTouch {\n const touch = this.session.touch();\n // Ahead of the sampling gates, because `counter` is \"pages this session\" whether or not\n // this session's boundary events are sampled in.\n if (touch.startedSession) this.pageLife.newSession();\n if (touch.endedSession && this.sessionInSample(touch.endedSession.id)) {\n const ended = touch.endedSession;\n this.enqueueSessionBoundary('end', ended.id, ended.lastActivityAt, ended.startedAt);\n }\n if (touch.startedSession && this.sessionInSample(touch.startedSession.id)) {\n // Announces a session the SDK just observed beginning. Not emitted by reset()/rotate()\n // (an explicit user action, not an observed boundary) nor by peek()'s mint-if-absent\n // branch (analytics from a getter). Stamped at the session's start, not \"now\" — the\n // same instant on the capture path, but the resume path can observe a rotation later.\n const started = touch.startedSession;\n this.enqueueSessionBoundary('start', started.id, started.startedAt, started.startedAt);\n }\n return touch;\n }\n\n /**\n * `visibilitychange`→visible: run the session-timeout check.\n *\n * Not at all while capture is denied. capture() returns before touching the session in that\n * state; this path did not, so every refocus by an opted-out or DNT visitor wrote a session id\n * and an activity timestamp to storage.\n */\n private resumeSession(): void {\n if (this.consent.canCapture()) this.touchSession();\n }\n\n /** Lazily loads the autocapture engine so the core bundle stays <10KB gz. */\n private startAutocapture(): void {\n const autocaptureConfig = this.config.autocapture;\n if (!autocaptureConfig || typeof window === 'undefined') return;\n // Started here rather than in the lazy chunk: these are PerformanceObservers with\n // `buffered: true`, and the entries they replay — FCP, LCP — happen before a dynamic import\n // could possibly resolve. Registering late would miss the paints this exists to measure.\n if (typeof PerformanceObserver !== 'undefined') {\n this.vitals = observeVitals();\n this.teardownFns.push(() => this.vitals?.stop());\n }\n // Patches `fetch`, so it is kept here beside the observers rather than in the lazy chunk: a\n // request that fails during startup is exactly the kind worth knowing about, and a dynamic\n // import would miss it.\n const network = observeNetworkErrors(this.config, (properties) =>\n this.guard(() => this.capture('$network_request', 'track', properties))\n );\n this.teardownFns.push(() => network.stop());\n void loadAutocapture()\n .then((module) => {\n if (!module) return; // build has autocapture compiled out (Shopify pixel)\n // shutdown() ran while the chunk was loading: its teardown list is already spent, so an\n // engine started now would keep its listeners and History patch for the life of the page.\n if (this.stopped) return;\n this.teardownFns.push(\n module.startAutocapture(autocaptureConfig, {\n // Same entry point the conformance fixtures drive, so the shared fixtures\n // exercise the real path rather than a parallel one.\n emit: (properties) => this.autocapture(properties),\n page: (watchTitle) => this.guard(() => this.pageLife.autoPageView(watchTitle)),\n pageLeave: (maxScroll) => this.guard(() => this.pageLife.leave(maxScroll)),\n warn: (message) => this.logger.warn(message),\n armUnloadLeave: (leave) => {\n this.leaveOnUnload = leave;\n },\n })\n );\n this.teardownFns.push(() => {\n this.leaveOnUnload = undefined;\n });\n })\n .catch((err) => this.logger.debug('autocapture load failed', err));\n }\n\n private guard(fn: () => void): void {\n try {\n fn();\n } catch (err) {\n this.logger.error('internal error', err);\n }\n }\n}\n\nexport { LIBRARY_NAME, SDK_VERSION };\n","import { DepsmithSdkClient, type InternalOverrides } from './depsmith-sdk';\nimport type { DepsmithSdkConfig } from './config';\nimport type { PageOptions, Properties } from './types';\nimport type { UserPropertyOps } from './user-properties';\n\nexport { DepsmithSdkClient } from './depsmith-sdk';\nexport type { InternalOverrides } from './depsmith-sdk';\nexport type { DepsmithSdkConfig, AutocaptureConfig, PageNames, PageLocation } from './config';\nexport type { TrackingOptions } from './tracking-options';\nexport type { UserPropertyOps } from './user-properties';\nexport type {\n DepsmithSdkEvent,\n BatchPayload,\n EventContext,\n EventType,\n PageOptions,\n Properties,\n PropertyValue,\n ConsentState,\n} from './types';\nexport type { KVStorage, AsyncKV } from './queue/storage';\nexport { AsyncMirrorAdapter, DEPSMITH_SDK_STORAGE_KEYS } from './queue/storage';\nexport type { Scheduler } from './utils/scheduler';\nexport { idleScheduler, syncScheduler } from './utils/scheduler';\n\nlet client: DepsmithSdkClient | null = null;\nlet initApiKey: string | null = null;\n\n/**\n * Default singleton facade:\n *\n * import { DepsmithSdk } from '@depsmith/depsmith-sdk';\n * DepsmithSdk.init({ apiKey: '...', endpoint: 'https://collector.example.com' });\n * DepsmithSdk.track('button_clicked', { color: 'red' });\n *\n * Re-init with the same apiKey is a no-op; a different apiKey replaces the client (API_SPEC §2).\n * Without a `window` (server rendering) init() does nothing and returns null — see below.\n */\nexport const DepsmithSdk = {\n init(config: DepsmithSdkConfig, overrides?: InternalOverrides): DepsmithSdkClient | null {\n try {\n if (client && initApiKey === config.apiKey) {\n return client;\n }\n // No window: this module is being evaluated on a server (Next.js, Remix, a prerender).\n // A singleton there is one client for every request — one anonymous_id, and after an\n // identify() during a render, one user_id — queueing in server memory and uploading\n // with no page behind it. So init() declines, and every facade method stays the no-op\n // it is before init. Two ways to say \"I mean it\": `storage: 'memory'`, the documented\n // SSR/test backend, or an injected store (the Shopify pixel, the conformance runner).\n if (typeof window === 'undefined' && config.storage !== 'memory' && !overrides?.storage) {\n if (config.debug) console.warn('[depsmith-sdk] init skipped: no window');\n return null;\n }\n client?.shutdown();\n client = new DepsmithSdkClient(config, overrides);\n initApiKey = config.apiKey;\n return client;\n } catch (err) {\n if (config?.debug) console.error('[depsmith-sdk] init failed:', err);\n return null;\n }\n },\n\n track: (name: string, properties?: Properties): void => client?.track(name, properties),\n page: (name?: string, properties?: Properties, options?: PageOptions): void =>\n client?.page(name, properties, options),\n screen: (name?: string, properties?: Properties, options?: PageOptions): void =>\n client?.screen(name, properties, options),\n identify: (userId: string, traits?: Properties): void => client?.identify(userId, traits),\n alias: (aliasId: string): void => client?.alias(aliasId),\n reset: (): void => client?.reset(),\n group: (groupId: string, traits?: Properties): void => client?.group(groupId, traits),\n setGroupTraits: (traits: Properties): void => client?.setGroupTraits(traits),\n setProperty: (key: string, value: Properties[string]): void => client?.setProperty(key, value),\n setOnceProperty: (key: string, value: Properties[string]): void =>\n client?.setOnceProperty(key, value),\n unsetProperty: (key: string): void => client?.unsetProperty(key),\n /** Applies the §14 operator set server-side: $set, $add, $append, $unset, $clear_all, … */\n setUserProperties: (ops: UserPropertyOps): void => client?.setUserProperties(ops),\n /** Properties attached to every later event. A direct track() property wins over these. */\n register: (properties: Properties): void => client?.register(properties),\n /** Only keys not registered yet — first-touch values a later state must not overwrite. */\n registerOnce: (properties: Properties): void => client?.registerOnce(properties),\n unregister: (key: string): void => client?.unregister(key),\n optIn: (): void => client?.optIn(),\n optOut: (): void => client?.optOut(),\n flush: (): Promise<void> => client?.flush() ?? Promise.resolve(),\n getAnonymousId: (): string | undefined => client?.getAnonymousId(),\n getSessionId: (): string | undefined => client?.getSessionId(),\n setSessionId: (sessionId: string, startedAt?: number): void =>\n client?.setSessionId(sessionId, startedAt),\n\n /** Testing/teardown: stop timers and forget the singleton. */\n shutdown(): void {\n client?.shutdown();\n client = null;\n initApiKey = null;\n },\n};\n"],"mappings":"AAmCO,IAAMA,GAAN,KAAkB,CAAlB,cAGL,KAAQ,QAAU,EAWlB,WAAWC,EAAaC,EAAmC,CACzD,OAAID,IAAQ,KAAK,WAAmB,IAEhC,KAAK,aAAe,OAGjBC,GAGH,KAAK,YAAcA,EACnB,KAAK,aAAeC,GAAWD,EAAkBD,CAAG,EAAI,WAAa,YAHrE,KAAK,aAAe,UAOtB,KAAK,YAAc,KAAK,WACxB,KAAK,aAAeE,GAAW,KAAK,WAAYF,CAAG,EAAI,WAAa,YAGtE,KAAK,WAAaA,EAClB,KAAK,SAAW,EACT,GACT,CAGA,UAAyB,CACvB,IAAMG,EAAoB,CAAC,EAC3B,OAAI,KAAK,cAAgB,SAAWA,EAAI,aAAe,KAAK,aACxD,KAAK,eAAiB,SAAWA,EAAI,cAAgB,KAAK,cAC1D,KAAK,QAAU,IAAGA,EAAI,QAAU,KAAK,SAClCA,CACT,CAGA,IAAI,WAAoB,CACtB,OAAO,KAAK,OACd,CAGA,IAAI,SAA8B,CAChC,OAAO,KAAK,UACd,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sBd,GAAQ,WAAWc,CAAG,EACzD,MAAO,IAAYd,GAAQ,MAAM,EACjC,OAAQ,IAAYA,GAAQ,OAAO,EACnC,MAAO,IAAqBA,GAAQ,MAAM,GAAK,QAAQ,QAAQ,EAC/D,eAAgB,IAA0BA,GAAQ,eAAe,EACjE,aAAc,IAA0BA,GAAQ,aAAa,EAC7D,aAAc,CAACiB,EAAmBC,IAChClB,GAAQ,aAAaiB,EAAWC,CAAS,EAG3C,UAAiB,CACflB,GAAQ,SAAS,EACjBA,EAAS,KACTC,GAAa,IACf,CACF","names":["PageTracker","url","documentReferrer","sameOrigin","out","PageLifecycle","sink","config","pageNameRules","name","properties","type","pending","auto","href","AUTO_VIEW_CLAIM_MS","pageViewProperties","watchTitle","key","counter","domainOf","urlBase","view","where","title","maxScroll","leaving","persisted","tracking","pathOf","live","source","location","rules","match","pageType","names","glob","globPattern","path","trimSlash","pattern","star","a","b","u","UTM_PARAMS","KEY_CAMPAIGN","KEY_REFERRER","Attribution","storage","key","raw","parsed","value","url","documentReferrer","params","currentHost","incoming","param","refHost","domainOf","isExternal","changed","startLifecycle","host","flushTimer","drained","hideFlush","onPageHide","pendingHide","onVisibility","onPageShow","event","onOnline","loadAutocapture","SUPPRESSIONS","TRACKING_DEFAULTS","option","resolveTrackingOptions","options","resolved","applyTrackingOptions","context","record","key","sub","block","AUTOCAPTURE_DEFAULTS","resolveAutocapture","autocapture","resolved","key","value","clicks","pageviews","resolveConfig","config","autocapture","resolveAutocapture","int","num","resolveTrackingOptions","value","fallback","min","max","djb2","input","hash","i","fnv1aInt","fnv1a","bucket","fingerprintHash","hints","hintsRequested","primeClientHints","uaData","values","parseUserAgent","result","ua","uaData","browser","parseBrowser","os","parseOS","hinted","normalizeOsVersion","hints","deviceType","parseDeviceType","device","parseDevice","osName","platformVersion","raw","major","trimVersion","BROWSER_RULES","rule","match","brand","b","OS_RULES","version","trimmed","cachedVisitorId","cachedComponents","components","collectSignals","computeVisitorId","fingerprintHash","c","fingerprintComponents","out","component","collectSignals","signals","nav","canvasFingerprint","canvas","ctx","fingerprintHash","readNetwork","conn","type","fix","fixAt","primed","inFlight","permission","allowed","primeGeolocation","gate","permissions","status","requestFix","position","latitude","longitude","accuracy","next","readGeolocation","LIBRARY_NAME","SDK_VERSION","invariants","readInvariants","next","buildContext","opts","context","LIBRARY_NAME","SDK_VERSION","attempt","href","domainOf","urlBase","cached","readInvariants","deviceType","parseUserAgent","campaign","referrer","enrichFingerprint","fix","readGeolocation","key","value","applyTrackingOptions","browser","os","hinted","device","network","readNetwork","fn","dntEnabled","nav","win","KEY_CONSENT","ConsentManager","storage","initialMode","dntActive","persisted","idleScheduler","fn","idle","syncScheduler","KEY_QUEUE","DEFAULT_MAX_CHARS","BRACKETS","IDENTITY_EVENT_TYPES","isIdentityEvent","event","EventQueue","storage","maxSize","logger","options","idleScheduler","raw","parsed","kept","e","events","measure","a","b","dropped","existing","fresh","size","i","index","count","n","maxChars","from","end","total","eventIds","ids","sizes","sizeSum","lastMs","lastSeq","SEQ_MASK","uuidv7","now","bytes","i","seq","hex","uuidv7ToMs","id","ms","DEPSMITH_SDK_STORAGE_KEYS","MemoryAdapter","key","value","CookieAdapter","domain","prefix","part","maxAge","secure","KEY_ANON_RESET","MIRRORED_IDENTITY_KEYS","RedundantAdapter","primary","secondary","mirrored","fromPrimary","fromSecondary","winner","a","b","aMs","uuidv7ToMs","bMs","stores","at","s","live","AsyncMirrorAdapter","backend","keys","LocalStorageAdapter","ls","key","value","IndexedDBAdapter","dbName","resolve","request","tx","keysReq","valuesReq","keys","i","defaultStorage","probe","MemoryAdapter","pickQueueStorage","mode","fallback","hydrateQueue","queueStorage","storage","consent","queue","drifted","logger","persisted","KEY","raw","storedEvents","raw","parsed","e","EventQueue","args","event","KEY_QUEUE","stored","present","gone","id","LocalStorageAdapter","mine","foreign","room","chars","kept","i","size","KEY_ANON","KEY_USER","KEY_GROUP","KEY_PROPS","IdentityManager","storage","clock","id","uuidv7","userId","groupId","key","value","props","now","KEY_ANON_RESET","fresh","KEY_SESSION","SessionManager","storage","clock","timeoutMs","schedule","idleScheduler","stored","pending","raw","parsed","uuidv7ToMs","session","now","fresh","uuidv7","current","id","startedAt","embedded","sanitizeProperties","input","logger","out","count","rawKey","rawValue","value","coerceValue","coerceScalar","t","scalar","items","item","coerced","safeStringify","k","v","stripReserved","input","method","logger","out","hit","key","isReserved","wasAborted","error","signal","name","errorMessage","message","isFailure","status","urlParts","raw","properties","url","contentLength","headers","value","parsed","describeRequest","input","init","request","observeNetworkErrors","config","emit","original","own","stopped","windowStart","seen","admit","key","now","report","outcome","build","patched","args","started","promise","method","response","sizes","requestBytes","responseBytes","ms","value","observeVitals","lcp","fcp","inp","cls","sawLayoutShift","ttfb","observers","observe","type","handler","observer","list","entries","last","entry","duration","navigation","timing","out","KEY_SUPER_PROPERTIES","usableKey","key","logger","isReserved","SuperProperties","storage","stored","parsed","properties","changed","value","TRAIT_OPERATORS","MAX_ADD_KEYS","MAX_UNSET_KEYS","normalizeUserPropertyOps","ops","logger","others","k","out","claimed","claim","key","operator","isReserved","raw","clean","sanitizeProperties","kept","value","count","sanitizedTraitOp","systemClock","isoTimestamp","ms","isRetryable","status","BASE_MS","MAX_BACKOFF_MS","backoffMs","attempt","random","base","retryAfterMs","value","now","seconds","ms","gzip","text","cs","writer","reader","chunks","done","value","total","n","c","out","offset","chunk","compress","mode","sendBeacons","queue","config","deps","uploading","buildPayload","breaker","from","n","batch","payload","event","eventIds","batch","event","REQUEST_TIMEOUT_MS","KEEPALIVE_MAX_BYTES","MAX_BATCH_CHARS","bodyBytes","body","REDIRECTED","refused","status","HOLD_BASE_MS","HOLD_MAX_MS","BatchUploader","queue","config","deps","err","max","isRetryable","breaker","answered","attempt","backoffMs","payload","isoTimestamp","json","controller","timer","headers","zipped","compress","keepalive","init","res","retryAfterMs","configured","sendBeacons","KEY_NET_BREAKER","createNetworkBreaker","storage","clock","loaded","failures","openUntil","cooldown","clamp","v","lo","hi","load","s","KEY_NET_BREAKER","save","ms","Logger","enabled","args","CONTEXT_KEYS","URL_PROPERTIES","scrubUrl","url","keep","bare","q","kept","pair","paramName","name","scrubEventUrls","event","option","params","targets","target","keys","key","value","props","query","KEY_CONFIG_FP","MAX_ENVELOPE_ID_LENGTH","DepsmithSdkClient","config","overrides","resolveConfig","Logger","systemClock","queueStorage","pickQueueStorage","PageLifecycle","name","type","properties","at","page","identityStorage","MemoryAdapter","RedundantAdapter","CookieAdapter","IdentityManager","SessionManager","ConsentManager","dntEnabled","Attribution","SuperProperties","fp","djb2","owned","key","value","EventQueue","drifted","hydrateQueue","BatchUploader","args","ms","r","createNetworkBreaker","startLifecycle","fn","persisted","stripReserved","isReserved","traits","method","sanitizeProperties","label","options","userId","clean","sanitizedTraitOp","aliasId","groupId","op","normalizeUserPropertyOps","ops","normalized","err","sessionId","startedAt","primeClientHints","primeGeolocation","event","scrubEventUrls","signals","bucket","userProperties","touch","now","contextOptions","uuidv7","isoTimestamp","buildContext","SDK_VERSION","props","computeVisitorId","fingerprint","stored","KEY_NET_BREAKER","defaultStorage","kind","id","fingerprintComponents","ended","started","autocaptureConfig","observeVitals","network","observeNetworkErrors","loadAutocapture","module","watchTitle","maxScroll","message","leave","client","initApiKey","DepsmithSdk","config","overrides","DepsmithSdkClient","err","name","properties","options","userId","traits","aliasId","groupId","key","value","ops","sessionId","startedAt"]}
|