@depsmith/depsmith-sdk 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/autocapture/selector.ts","../src/autocapture/index.ts","../src/index.ts","../src/autocapture/load.ts","../src/tracking-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/identity.ts","../src/session.ts","../src/props.ts","../src/user-properties.ts","../src/utils/clock.ts","../src/transport/retry.ts","../src/transport/uploader.ts","../src/transport/breaker.ts","../src/utils/logger.ts","../src/depsmith-sdk.ts"],"sourcesContent":["/** CSS selector generation for autocaptured elements, capped at a configurable depth. */\nexport function elementSelector(element: Element, maxDepth: number): string {\n const parts: string[] = [];\n let current: Element | null = element;\n\n while (current && current !== document.documentElement && parts.length < maxDepth) {\n let part = current.tagName.toLowerCase();\n if (current.id) {\n parts.unshift(`${part}#${current.id}`);\n break; // ids are unique enough — stop here\n }\n const classes = Array.from(current.classList).slice(0, 3);\n if (classes.length) part += `.${classes.join('.')}`;\n\n const parent: Element | null = current.parentElement;\n if (parent) {\n const siblings = Array.from(parent.children).filter((c) => c.tagName === current!.tagName);\n if (siblings.length > 1) part += `:nth-of-type(${siblings.indexOf(current) + 1})`;\n }\n parts.unshift(part);\n current = parent;\n }\n\n return parts.join(' > ');\n}\n\n/** True when the element (or an ancestor) opts out of autocapture. */\nexport function isIgnored(element: Element, ignoredSelectors: string[]): boolean {\n if (element.closest('[data-depsmith-sdk-no-capture]')) return true;\n for (const selector of ignoredSelectors) {\n try {\n if (element.closest(selector)) return true;\n } catch {\n // invalid selector in config — skip it\n }\n }\n return false;\n}\n\nconst SENSITIVE_INPUT_TYPES = new Set(['password', 'email', 'tel', 'hidden', 'number']);\n\n/** Element text, aggressively masked: never inputs, never [data-depsmith-sdk-mask], 255-char cap. */\nexport function safeText(element: Element): string | undefined {\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) return undefined;\n if (element.closest('[data-depsmith-sdk-mask]')) return undefined;\n const text = element.textContent?.trim().replace(/\\s+/g, ' ');\n return text ? text.slice(0, 255) : undefined;\n}\n\nexport function isSensitiveField(input: Element): boolean {\n if (!(input instanceof HTMLInputElement)) return false;\n return SENSITIVE_INPUT_TYPES.has(input.type) || !!input.closest('[data-depsmith-sdk-mask]');\n}\n","/**\n * Web autocapture engine — lazily loaded so the core bundle stays under 10KB gz.\n * Clicks (delegation), form submits (values never captured), scroll depth\n * (quartiles), and SPA pageviews (History API patch). See API_SPEC §3 for the\n * reserved $autocapture event.\n */\nimport type { AutocaptureConfig } from '../config';\nimport type { Properties } from '../types';\nimport { elementSelector, isIgnored, isSensitiveField, safeText } from './selector';\n\nexport interface AutocaptureHooks {\n /** Emits a $autocapture event through the client pipeline. */\n emit(properties: Properties): void;\n /** Emits a $page_view through the client pipeline (SPA navigation). */\n page(): void;\n}\n\n/** Elements a click is attributed to when `clicks: 'interactive'`. */\nconst INTERACTIVE_SELECTOR =\n 'a, button, [role=\"button\"], input[type=\"submit\"], input[type=\"button\"], [data-depsmith-sdk-capture]';\n\nexport function startAutocapture(\n config: Required<AutocaptureConfig>,\n hooks: AutocaptureHooks\n): () => void {\n const teardowns: Array<() => void> = [];\n /** Run on SPA navigation, in registration order. */\n const onNavigate: Array<() => void> = [];\n\n if (config.clicks) teardowns.push(captureClicks(config, hooks));\n if (config.forms) teardowns.push(captureForms(config, hooks));\n if (config.scrolls) {\n const scroll = captureScrollDepth(hooks);\n teardowns.push(scroll.stop);\n // Re-arm before the pageview so the new page's quartiles are live by the time it fires.\n onNavigate.push(scroll.rearm);\n }\n if (config.pageviews) onNavigate.push(hooks.page);\n\n // One History patch feeding every navigation-sensitive feature, rather than one per\n // feature. Scroll depth needs the same signal pageviews do — without it, a re-armed\n // quartile set on an SPA route change is unreachable once the listener has detached.\n if (onNavigate.length > 0) {\n teardowns.push(\n observeNavigation(() => {\n for (const fn of onNavigate) fn();\n })\n );\n }\n\n return () => {\n for (const stop of teardowns.splice(0)) stop();\n };\n}\n\nfunction captureClicks(config: Required<AutocaptureConfig>, hooks: AutocaptureHooks): () => void {\n // `true` means \"capture clicks\", not \"capture every click on the page\" — it resolves to\n // the interactive gate like the default does. Emitting a $autocapture for a tap on a\n // product image or a bare layout <div> is a firehose that costs a queue write per event\n // and buries the clicks that carry intent, so it takes an explicit 'all' to ask for it.\n const interactiveOnly = config.clicks !== 'all';\n\n const onClick = (event: MouseEvent): void => {\n const target = event.target;\n if (!(target instanceof Element)) return;\n const interactive = target.closest(INTERACTIVE_SELECTOR);\n if (interactiveOnly && !interactive) return;\n const element = interactive ?? target;\n if (isIgnored(element, config.ignoredSelectors)) return;\n\n const properties: Properties = {\n $ac_kind: 'click',\n $ac_selector: elementSelector(element, config.selectorMaxDepth),\n $ac_tag: element.tagName.toLowerCase(),\n };\n const text = safeText(element);\n if (text) properties.$ac_text = text;\n if (element instanceof HTMLAnchorElement && element.href) properties.$ac_href = element.href;\n\n hooks.emit(properties);\n };\n\n document.documentElement.addEventListener('click', onClick, { capture: true, passive: true });\n return () => document.documentElement.removeEventListener('click', onClick, { capture: true });\n}\n\nfunction captureForms(config: Required<AutocaptureConfig>, hooks: AutocaptureHooks): () => void {\n const onSubmit = (event: Event): void => {\n const form = event.target;\n if (!(form instanceof HTMLFormElement)) return;\n if (isIgnored(form, config.ignoredSelectors)) return;\n\n // Field NAMES only — values are never captured (privacy by construction).\n const fields = Array.from(form.elements)\n .filter((el): el is HTMLInputElement => el instanceof HTMLInputElement && !isSensitiveField(el))\n .map((el) => el.name || el.id)\n .filter(Boolean)\n .slice(0, 50);\n\n hooks.emit({\n $ac_kind: 'form_submit',\n $ac_selector: elementSelector(form, config.selectorMaxDepth),\n $ac_form_id: form.id || null,\n $ac_form_fields: fields,\n });\n };\n\n document.documentElement.addEventListener('submit', onSubmit, { capture: true, passive: true });\n return () => document.documentElement.removeEventListener('submit', onSubmit, { capture: true });\n}\n\nconst QUARTILES = [25, 50, 75, 100] as const;\n\n/**\n * Vertical overflow an element needs before it counts as the page's scroller.\n *\n * Roughly a phone viewport. Below it a box is an in-page control — a size-guide popover, a\n * variant list, a sticky mini-cart — and reporting \"100% scroll depth\" because someone\n * flicked through six shipping options would be worse than reporting nothing.\n */\nconst MIN_HOST_SCROLLABLE_PX = 240;\n\ninterface ScrollTracker {\n stop(): void;\n /** Re-arms the quartiles for a new SPA route, re-attaching if we had detached at 100%. */\n rearm(): void;\n}\n\n/**\n * Scroll-depth quartiles, without a layout read per scroll event.\n *\n * The previous version read `document.documentElement.scrollHeight` inside the scroll\n * handler. That forces a synchronous style + layout flush, and scroll fires at input\n * frequency — so it was a forced reflow per frame, for the life of the page, and the\n * listener stayed attached long after all four quartiles had fired.\n *\n * Three changes make it cheap:\n * - handling is coalesced into one `requestAnimationFrame` callback per frame;\n * - the scrollable height is cached, invalidated whenever the document actually resizes,\n * and otherwise re-measured only when the cached value says we are about to cross a\n * quartile — so a lazily growing page still reports accurately, at ≤4 layout reads;\n * - the listener detaches once 100% is reached, since there is nothing left to report.\n *\n * Depth is measured against whichever box actually scrolls. Listening on `window` only\n * ever sees the viewport, so a theme whose `documentElement` and `body` are both\n * `overflow: hidden` — the content scrolling inside a wrapper instead, which is common on\n * modern Shopify themes — emitted nothing at all, for the life of the page, with no error\n * and no way to tell from the outside that the feature was inert.\n *\n * The document has ABSOLUTE PRECEDENCE in that choice: if the document can scroll at all,\n * depth is the document's, no matter which box happened to scroll first. An in-page\n * scroller is only ever adopted on a page where the document is flat. That ordering is what\n * keeps this strictly additive — every page that reported correctly before still does, and\n * the wrapper themes that reported nothing now report too.\n *\n * Invalidation watches the DOCUMENT, not just the window. `resize` fires for the viewport\n * only, so in-page height changes — a filter removing rows, an accordion collapsing, a\n * dismissed banner — left a stale, too-large `scrollable` behind, and `percent()` then\n * under-reported forever: no further quartile could ever fire. The same staleness made a\n * first measurement of exactly 0 (content one viewport tall, lazy content still to land)\n * permanent, because 0 does not satisfy the `< 0` re-measure guard.\n */\nfunction captureScrollDepth(hooks: AutocaptureHooks): ScrollTracker {\n /** Index into QUARTILES; everything below it has already been emitted. */\n let reached = 0;\n /** Cached scrollable extent of {@link host}. -1 means \"needs measuring\". */\n let scrollable = -1;\n /** Pending frame handle, or 0 when none is scheduled. */\n let frame = 0;\n let attached = false;\n /**\n * What depth is measured against, as a three-state value: `undefined` is \"not resolved\n * yet\", `null` is the viewport, an Element is an in-page scroller.\n *\n * Resolved from the first qualifying scroll event rather than searched for, so a\n * container that only exists after hydration is picked up for free — and so resolution\n * costs one layout read for the life of the page instead of a DOM walk at init.\n */\n let host: Element | null | undefined;\n\n const measure = (): void => {\n scrollable = host\n ? host.scrollHeight - host.clientHeight\n : document.documentElement.scrollHeight - window.innerHeight;\n };\n\n const percent = (): number =>\n Math.min(100, Math.round(((host ? host.scrollTop : window.scrollY) / scrollable) * 100));\n\n const evaluate = (): void => {\n frame = 0;\n // `<= 0`, not `< 0`: a page that measured as unscrollable must be re-measured rather\n // than written off, or content arriving after first paint never becomes reportable.\n // Costs nothing in the steady state — an unscrollable page emits no scroll events.\n if (scrollable <= 0) measure();\n if (scrollable <= 0) return;\n // Cheap path: cached metrics say we have not reached the next quartile, so there is\n // nothing to report and no reason to touch layout.\n if (percent() < QUARTILES[reached]!) return;\n\n // About to emit — confirm against live layout, since the page may have grown since we\n // last measured (lazy images, infinite scroll) and the cached value would over-report.\n measure();\n if (scrollable <= 0) return;\n const depth = percent();\n while (reached < QUARTILES.length && depth >= QUARTILES[reached]!) {\n hooks.emit({ $ac_kind: 'scroll_depth', $ac_depth: QUARTILES[reached]! });\n reached++;\n }\n if (reached >= QUARTILES.length) detach();\n };\n\n const onScroll = (event: Event): void => {\n // Give the host back when it can no longer be the page, and let the next branch resolve\n // again. Two ways that happens:\n //\n // - an ELEMENT host went away. A wrapper re-mounted without a history change — a\n // filter rebuilding the product grid — leaves a detached node whose metrics freeze.\n // - the VIEWPORT was adopted, has since measured as genuinely unscrollable, and\n // something else just scrolled. Only reachable once `evaluate` has measured a real\n // zero, so it costs nothing on a page that scrolls, and it keeps the viewport's\n // precedence below from being a one-way door on a theme that fires a stray window\n // scroll before its wrapper ever moves.\n //\n // `reached` deliberately survives both: still the same route, so quartiles already\n // reported must not report a second time.\n if (host && !host.isConnected) host = undefined;\n if (host === null && scrollable === 0) host = undefined;\n\n if (host === undefined) {\n // Resolved from the first scroll that actually happens, rather than by searching the\n // DOM at init: a wrapper that only exists after hydration is picked up for free, and\n // the layout reads below are paid once for the life of the page, not once per frame.\n const target = event.target;\n // THE PAGE WINS WHENEVER THE PAGE CAN SCROLL AT ALL — whatever fired this event.\n // `scroll_depth` has always meant \"how far down the page\", and on an ordinary page an\n // in-page box (a size-guide modal, a cart drawer, a sticky filter rail) is a control\n // WITHIN the page, not a replacement for it. Resolving by \"whichever box scrolled\n // first\" instead meant a shopper who nudged a modal before reading the page lost page\n // depth for the rest of the route — a page that reported correctly before the in-page\n // path existed. Anchoring on the document means this can only ever ADD coverage.\n //\n // The two tests are ordered so the common case costs nothing: a scroll from the\n // document's own scrollport IS the page and needs no measurement, so the viewport\n // path's layout-read budget is exactly what it was before in-page scrollers existed.\n // Only a scroll from some other box has to ask how far the document can go.\n //\n // No `MIN_HOST_SCROLLABLE_PX` on that second test, on purpose: the threshold exists to\n // tell a page from a control, and the document is never a control. A document with\n // 100px of overflow is still the page, and was always reported as one.\n //\n // The document measurement is not cached: a zero means \"cannot scroll YET\", and a page\n // that starts one viewport tall and grows when lazy content lands has to be able to\n // change that answer without waiting on a resize that may never come.\n //\n // The scrollport test is deliberately NOT `target === window`. A Window identity check\n // is unreliable across realms — under vitest's jsdom the event's Window and the\n // module's `window` are different objects, and the same holds inside an iframe — so it\n // silently failed and every viewport scroll was discarded. Window and Document are the\n // two scroll targets that are not Elements, and `documentElement` is the Element that\n // means the same thing; none of that needs identity. `body` is pointedly excluded: it\n // is a viewport proxy in the standard shape but a scroll container in its own right\n // under `html { overflow: hidden } body { overflow: auto }`, where the viewport\n // metrics it would send us to read are inert — which is how that theme reported\n // nothing. It goes to the element path below and is measured for real.\n if (\n !(target instanceof Element) ||\n target === document.documentElement ||\n document.documentElement.scrollHeight > window.innerHeight\n ) {\n host = null;\n } else {\n // The document cannot scroll and something else did: the wrapper-scroller theme, or\n // the `body { overflow: auto }` variant of it, which lands here too because `body`\n // is a real scroll container in that shape and `body.scrollTop` is the live value.\n //\n // A horizontal carousel has no vertical overflow and is filtered out here, as is a\n // small popover — neither is \"the page\", and reporting depth for a box the shopper\n // barely touched would be worse than reporting nothing. Returning without\n // committing leaves the host unresolved, so a real wrapper can still claim it.\n const box = target as Element;\n if (box.scrollHeight - box.clientHeight < MIN_HOST_SCROLLABLE_PX) return;\n host = box;\n }\n scrollable = -1; // metrics now come from a different box\n observeHost();\n // Not the box we report depth for: a mini-cart drawer scrolled to its end must not\n // read as \"the shopper reached the bottom of the page\".\n //\n // Only an ELEMENT host filters by target. Once the viewport is the host there is\n // nothing to filter against: depth comes from `window.scrollY`, which no in-page box\n // can move, so a stray scroll from a drawer costs one coalesced frame and emits\n // nothing. Not asking also means it no longer matters whether an engine targets\n // `document` or `body` for a page scroll — a distinction that was load-bearing here\n // and is not worth depending on.\n } else if (host && event.target !== host) {\n return;\n }\n if (frame !== 0) return; // a frame is already pending — coalesce into it\n frame = scheduleFrame(evaluate);\n };\n\n // Content height and viewport both change here, so the cache is no longer trustworthy.\n const onResize = (): void => {\n scrollable = -1;\n };\n\n /**\n * Catches content-height changes, which `resize` does not report. Without it a page that\n * SHRINKS keeps a too-large cached height and silently stops reporting quartiles.\n * Absent in older Safari and in jsdom, where the window listeners remain the fallback.\n *\n * Re-pointed at the host once one is resolved: an in-page scroller's content can grow\n * while the document's never changes, so observing the document would miss it entirely.\n *\n * An element host is observed together with its children, because the host's own box is\n * its SCROLLPORT — pinned to the viewport (`height: 100vh`) in every theme that scrolls a\n * wrapper, so it does not resize when the content inside it does. Observing it alone gave\n * the host path none of the shrink protection the document path has a test for: a wrapper\n * primed at 20,000px and then collapsed kept the stale extent, and scrolling to its true\n * bottom read ~16% and emitted nothing further. The children are what actually change\n * height. `documentElement` is no substitute here — in exactly these themes it is pinned\n * to 100vh as well.\n */\n let observer: ResizeObserver | null = null;\n const observeHost = (): void => {\n if (typeof ResizeObserver === 'undefined') return;\n try {\n observer?.disconnect();\n observer = new ResizeObserver(onResize);\n observer.observe(host ?? document.documentElement);\n // Index loop, not `for…of`: HTMLCollection is not iterable under this tsconfig's lib,\n // and a spread would cost an array per resolution for no gain.\n if (host) {\n const content = host.children;\n for (let i = 0; i < content.length; i++) observer.observe(content[i]!);\n }\n } catch {\n observer = null; // never let instrumentation break the page\n }\n };\n\n const attach = (): void => {\n if (attached) return;\n attached = true;\n // CAPTURE phase — that single flag is the whole fix. Scroll events do not bubble, so a\n // plain window listener sees only the viewport, and a theme that scrolls an inner\n // wrapper (documentElement and body both `overflow: hidden`, common on modern Shopify\n // themes) emitted nothing at all, silently, for the life of the page. The capture\n // phase runs from the root down to the target, so it delivers scroll from ANY element\n // even though the event never bubbles back up — one listener, both shapes, no DOM\n // search, and the listener stays on `window` exactly as before.\n window.addEventListener('scroll', onScroll, { capture: true, passive: true });\n window.addEventListener('resize', onResize, { passive: true });\n window.addEventListener('orientationchange', onResize, { passive: true });\n observeHost();\n };\n\n const detach = (): void => {\n if (!attached) return;\n attached = false;\n // The capture flag is part of the listener's identity — omitting it here would leave\n // the listener attached for the life of the page.\n window.removeEventListener('scroll', onScroll, { capture: true });\n window.removeEventListener('resize', onResize);\n window.removeEventListener('orientationchange', onResize);\n observer?.disconnect();\n observer = null;\n };\n\n attach();\n\n return {\n stop: () => {\n if (frame !== 0) cancelFrame(frame);\n frame = 0;\n detach();\n },\n rearm: () => {\n reached = 0;\n scrollable = -1;\n // A new route can scroll a different box — a PDP with a document-level scroll after\n // a collection page that scrolled an inner wrapper. Re-resolve rather than keep\n // measuring the old route's container, which may no longer be in the document.\n host = undefined;\n attach();\n },\n };\n}\n\n/** rAF where available; a macrotask in jsdom and other non-visual hosts. */\nfunction scheduleFrame(fn: () => void): number {\n if (typeof requestAnimationFrame === 'function') return requestAnimationFrame(fn);\n return setTimeout(fn, 16) as unknown as number;\n}\n\nfunction cancelFrame(handle: number): void {\n if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(handle);\n else clearTimeout(handle);\n}\n\n/**\n * Calls `onNavigate` when the History API or a popstate changes the URL.\n * Returns a teardown that restores the original History methods.\n */\nfunction observeNavigation(onNavigate: () => void): () => void {\n let lastUrl = location.href;\n const emitIfChanged = (): void => {\n if (location.href === lastUrl) return;\n lastUrl = location.href;\n onNavigate();\n };\n\n const originalPush = history.pushState.bind(history);\n const originalReplace = history.replaceState.bind(history);\n\n history.pushState = (...args: Parameters<History['pushState']>) => {\n originalPush(...args);\n emitIfChanged();\n };\n history.replaceState = (...args: Parameters<History['replaceState']>) => {\n originalReplace(...args);\n emitIfChanged();\n };\n window.addEventListener('popstate', emitIfChanged);\n\n return () => {\n history.pushState = originalPush;\n history.replaceState = originalReplace;\n window.removeEventListener('popstate', emitIfChanged);\n };\n}\n","import { DepsmithSdkClient, type InternalOverrides } from './depsmith-sdk';\nimport type { DepsmithSdkConfig } from './config';\nimport type { 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 } 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 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 */\nexport const DepsmithSdk = {\n init(config: DepsmithSdkConfig, overrides?: InternalOverrides): DepsmithSdkClient | null {\n try {\n if (client && initApiKey === config.apiKey) {\n return client;\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): void => client?.page(name, properties),\n screen: (name?: string, properties?: Properties): void => client?.screen(name, properties),\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 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","import type { AutocaptureConfig } from '../config';\nimport type { AutocaptureHooks } from './index';\n\n/** The subset of the autocapture module DepsmithSdkClient uses. */\nexport interface AutocaptureModule {\n startAutocapture(config: Required<AutocaptureConfig>, 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.locale. */\n language?: boolean;\n /** context.network in full. Subsumes carrier. */\n network?: boolean;\n osName?: boolean;\n osVersion?: boolean;\n /** context.page. Not the `name` property on $page_view — that is a property, not context. */\n page?: boolean;\n screen?: 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 ['language', 'locale'],\n ['network', 'network'],\n ['osName', 'os', 'name'],\n ['osVersion', 'os', 'version'],\n ['page', 'page'],\n ['screen', 'screen'],\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 {\n resolveTrackingOptions,\n type ResolvedTrackingOptions,\n type TrackingOptions,\n} from './tracking-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 /** 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\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\nexport interface AutocaptureConfig {\n clicks?: ClickCapture;\n forms?: boolean;\n scrolls?: boolean;\n pageviews?: boolean;\n ignoredSelectors?: string[];\n selectorMaxDepth?: number;\n}\n\nexport interface ResolvedConfig\n extends Required<Omit<DepsmithSdkConfig, 'autocapture' | 'trackingOptions'>> {\n autocapture: false | Required<AutocaptureConfig>;\n trackingOptions: ResolvedTrackingOptions;\n}\n\nconst AUTOCAPTURE_DEFAULTS: Required<AutocaptureConfig> = {\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 scrolls: true,\n pageviews: true,\n ignoredSelectors: [],\n selectorMaxDepth: 5,\n};\n\n/** `true` is an alias of 'interactive'; only an explicit 'all' asks for every click. */\nfunction resolveClicks(clicks: ClickCapture | undefined): ClickCapture {\n if (clicks === undefined) return AUTOCAPTURE_DEFAULTS.clicks;\n if (clicks === true) return 'interactive';\n return clicks;\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 =\n config.autocapture === true\n ? AUTOCAPTURE_DEFAULTS\n : config.autocapture && typeof config.autocapture === 'object'\n ? {\n ...AUTOCAPTURE_DEFAULTS,\n ...config.autocapture,\n clicks: resolveClicks(config.autocapture.clicks),\n }\n : (false as const);\n\n return {\n apiKey: config.apiKey,\n endpoint: config.endpoint.replace(/\\/+$/, ''),\n batchSize: clamp(config.batchSize ?? 20, 1, 500),\n batchIntervalMs: Math.max(config.batchIntervalMs ?? 60000, 1000),\n maxQueueSize: Math.max(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: Math.max(config.maxQueueBytes ?? 512 * 1024, 4096),\n sessionTimeoutMs: Math.max(config.sessionTimeoutMs ?? 1800000, 60000),\n // Non-finite falls back to 1 rather than clamping. `clamp(NaN)` is NaN, and every\n // sample comparison against NaN is false — so an untyped host passing a bad value\n // (window.__depsmithSdkConfig from Liquid, say) would silently drop 100% of non-identity\n // events with nothing but a debug line to show for it.\n sampleRate: Number.isFinite(config.sampleRate) ? clamp(config.sampleRate!, 0, 1) : 1,\n sessionEvents: config.sessionEvents === 'derive' ? 'derive' : 'emit',\n consentMode: config.consentMode ?? 'granted',\n respectDnt: config.respectDnt ?? true,\n maxRetries: clamp(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 trackingOptions: resolveTrackingOptions(config.trackingOptions),\n cookieDomain: config.cookieDomain ?? '',\n storage: config.storage ?? 'localstorage',\n };\n}\n\nfunction clamp(n: number, min: number, max: number): number {\n return Math.min(Math.max(n, 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: the caller (DepsmithSdkClient) only invokes this when the host app has opted in\n * AND consent is granted AND childSafeMode/DNT are 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.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\n/** Queries permission state once and, if already granted, requests a position. */\nexport function primeGeolocation(): void {\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) 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 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}\n","import type { EventContext } from './types';\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.6.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\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 context.page = {\n url: window.location.href,\n path: window.location.pathname,\n referrer: typeof document !== 'undefined' ? document.referrer : undefined,\n title: typeof document !== 'undefined' ? document.title : undefined,\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 = {\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 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 const device: NonNullable<EventContext['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\nconst 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 private 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 private maxChars: number;\n private schedule: Scheduler;\n /** Set when `events` has diverged from what is on disk. */\n private 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 private storage: KVStorage,\n private 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 private 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 /** Oldest-first view for uploading. Does not remove. */\n peek(count: number): DepsmithSdkEvent[] {\n return this.events.slice(0, count);\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 /**\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","/** RFC 9562 UUID v7: 48-bit unix-ms timestamp + random. Time-ordered, so event_id doubles as a capture-order tiebreaker. */\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 bytes[6] = (bytes[6]! & 0x0f) | 0x70; // version 7\n bytes[8] = (bytes[8]! & 0x3f) | 0x80; // variant 10\n\n const hex: string[] = [];\n for (let i = 0; i < 16; i++) hex.push(bytes[i]!.toString(16).padStart(2, '0'));\n return `${hex[0]}${hex[1]}${hex[2]}${hex[3]}-${hex[4]}${hex[5]}-${hex[6]}${hex[7]}-${hex[8]}${hex[9]}-${hex[10]}${hex[11]}${hex[12]}${hex[13]}${hex[14]}${hex[15]}`;\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\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 const DEPSMITH_SDK_STORAGE_KEYS = [\n 'depsmith_anonymous_id',\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] 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\nexport class LocalStorageAdapter implements KVStorage {\n constructor(private 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 * 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 * Keys mirrored across both identity stores.\n *\n * Only `depsmith_anonymous_id`. It is the device identity — the thing whose loss makes a returning\n * visitor look new — and it is always a UUIDv7, which is what makes the conflict rule below\n * well-defined. `depsmith_user_id` and `depsmith_group_id` are deliberately NOT mirrored: they are\n * caller-supplied values the app re-establishes by calling identify() again after login, so\n * copying them into a cookie would widen PII exposure to buy nothing. `depsmith_user_props` is\n * unbounded and would not fit a 4 KB cookie anyway.\n */\nexport const MIRRORED_IDENTITY_KEYS: ReadonlySet<string> = new Set(['depsmith_anonymous_id']);\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 // Both present and disagreeing. Prefer the OLDER id: a newer one can only have been minted\n // after this store was cleared, so the older is the device's original identity and keeps\n // the visitor continuous. UUIDv7 is time-ordered, so \"older\" is readable from the value\n // itself with no extra bookkeeping. Falls back to the primary for a non-v7 value.\n const winner = olderUuidV7(fromPrimary!, fromSecondary!) ?? fromPrimary!;\n this.primary.set(key, winner);\n this.secondary.set(key, winner);\n return winner;\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/** The earlier of two UUIDv7s by embedded timestamp, or null if either is not a v7. */\nfunction olderUuidV7(a: string, b: string): string | null {\n const aMs = uuidv7ToMs(a);\n const bMs = uuidv7ToMs(b);\n if (aMs === null || bMs === null) return null;\n return aMs <= bMs ? a : b;\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/**\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\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","import 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 /** Clears user/group/props and rotates anonymous_id. */\n reset(): string {\n this.storage.remove(KEY_USER);\n this.storage.remove(KEY_GROUP);\n this.storage.remove(KEY_PROPS);\n const fresh = uuidv7(this.clock.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","/**\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 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 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","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 } from './retry';\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 * 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 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/** 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\ntype UploadResult = 'sent' | 'dropped' | 'requeue';\n\n/**\n * Drains the queue oldest-first, one in-flight upload at a time (API_SPEC §10, §11).\n * 2xx → delete from queue. Retryable → backoff up to maxRetries, then events stay\n * queued for the next cycle. Non-retryable 4xx → drop the batch (poison-pill protection).\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 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 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('collector unreachable; uploads paused');\n return;\n }\n const batch = this.queue.peek(this.config.batchSize);\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 const result = await this.uploadWithRetry(batch);\n if (result === 'requeue') return; // retries exhausted — next cycle picks them up\n if (result === 'dropped') this.deps.logger.warn(`dropped poison batch of ${batch.length}`);\n this.queue.remove(eventIds(batch));\n }\n }\n\n private async uploadWithRetry(batch: DepsmithSdkEvent[]): Promise<UploadResult> {\n const breaker = this.deps.breaker;\n let answered = false; // did ANY attempt get an HTTP response?\n for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {\n const status = await this.post(batch);\n if (status !== 0) answered = true;\n if (status >= 200 && status < 300) {\n breaker?.ok();\n return 'sent';\n }\n if (!isRetryable(status)) {\n breaker?.ok();\n this.deps.logger.warn(`non-retryable ${status}; dropping batch`);\n return 'dropped';\n }\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 (status === 0 && !answered && breaker?.suspect()) break;\n if (attempt < this.config.maxRetries) await this.deps.sleep(backoffMs(attempt));\n }\n if (answered) breaker?.ok(); // 5xx/429: reachable, just unwell\n else breaker?.fail();\n return 'requeue';\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 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 let body: BodyInit = json;\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (this.config.compression !== 'none' && typeof CompressionStream !== 'undefined') {\n try {\n body = await gzip(json);\n headers['Content-Encoding'] = 'gzip';\n } catch {\n body = json; // compression failed — fall back to plain JSON\n }\n }\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 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 /**\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 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 */\n sendBeaconAll(): void {\n try {\n if (typeof navigator === 'undefined' || !navigator.sendBeacon) return;\n let batches = 0;\n while (this.queue.size > 0 && batches < MAX_UNLOAD_BATCHES) {\n const batch = this.queue.peek(this.config.batchSize);\n const payload = this.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 `${this.config.endpoint}/e/`,\n new Blob([JSON.stringify(payload)], { type: 'text/plain' })\n );\n if (!accepted) return; // UA queue full — keep events persisted\n this.queue.remove(eventIds(batch));\n batches++;\n }\n } catch {\n // events remain persisted; next page load replays them\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\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) 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 open: () => (load(), clock.now() < openUntil),\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 };\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 error(...args: unknown[]): void {\n if (this.enabled) console.error('[depsmith-sdk]', ...args);\n }\n}\n","import { 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/queue';\nimport {\n CookieAdapter,\n IndexedDBAdapter,\n MemoryAdapter,\n RedundantAdapter,\n defaultStorage,\n type KVStorage,\n} from './queue/storage';\nimport { IdentityManager } from './identity';\nimport { SessionManager } from './session';\nimport { sanitizeProperties } from './props';\nimport { normalizeUserPropertyOps, sanitizedTraitOp, type UserPropertyOps } from './user-properties';\nimport { BatchUploader } from './transport/uploader';\nimport { createNetworkBreaker } 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 type { DepsmithSdkEvent, EventContext, EventType, Properties } from './types';\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 whole batch.\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 queue: EventQueue;\n private uploader: BatchUploader;\n private flushTimer: ReturnType<typeof setInterval> | null = null;\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 enqueueEvent}).\n */\n private drained = 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 this.contextProvider = overrides.contextProvider;\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 this.queue = new EventQueue(this.storage, this.config.maxQueueSize, this.logger, {\n maxChars: this.config.maxQueueBytes,\n schedule: overrides.schedule,\n });\n this.detectConfigDrift();\n // Once per document, off the capture path — see primeClientHints(). Gated on the same\n // config the values are used behind, so nothing is requested for an install that has\n // fingerprinting off or COPPA on. Consent is re-checked per event at contextOptions().\n if (this.config.deviceFingerprinting && !this.config.childSafeMode) {\n primeClientHints();\n }\n // Same discipline for the device position: one permission query per document, a\n // position read only from an already-granted state (never a prompt), and nothing at\n // all for an install that has not opted in or is in COPPA mode.\n if (this.config.geolocation && !this.config.childSafeMode) {\n primeGeolocation();\n }\n\n // IndexedDB write-behind: merge the persisted queue once hydrated, gate uploads until then.\n if (this.storage instanceof IndexedDBAdapter) {\n this.ready = this.storage.hydrate().then((persisted) => {\n try {\n const raw = persisted.get('depsmith_queue');\n if (raw) this.queue.prepend(JSON.parse(raw) as DepsmithSdkEvent[]);\n } catch {\n this.logger.warn('persisted queue corrupt; discarded');\n }\n });\n }\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 }\n );\n\n if (!overrides.manualLifecycle) {\n this.startFlushTimer();\n this.attachLifecycle();\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.guard(() => {\n if (typeof name !== 'string' || name.length === 0) {\n this.logger.warn('track: event name required');\n return;\n }\n if (name.startsWith('$')) {\n this.logger.warn(`track: \"$\"-prefixed names are reserved; dropped \"${name}\"`);\n return;\n }\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 — so the uploader discards the WHOLE batch as a poison pill. For\n * `user_id` and `group_id` that is not a one-batch 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 take the whole batch with it.\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 page(name?: string, properties?: Properties): void {\n this.guard(() => {\n const pageName =\n name ?? (typeof document !== 'undefined' ? document.title : undefined) ?? 'Unknown';\n this.capture('$page_view', 'page_view', { ...properties, name: pageName });\n });\n }\n\n /** Alias of page() — unified mobile naming. */\n screen(name?: string, properties?: Properties): void {\n this.page(name, properties);\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 = sanitizeProperties(traits, this.logger);\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 this.identity.reset();\n this.session.rotate();\n this.logger.debug('reset: identity and session rotated');\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 this.capture('$group', 'group', undefined, sanitizeProperties(traits, this.logger));\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 this.capture('$group', 'group', undefined, sanitizeProperties(traits, this.logger));\n });\n }\n\n setProperty(key: string, value: Properties[string]): void {\n this.guard(() => {\n this.identity.setUserProp(key, value);\n const traits = sanitizeProperties({ [key]: value }, this.logger);\n this.capture(\n '$identify',\n 'identify',\n undefined,\n traits,\n sanitizedTraitOp('$set', traits)\n );\n });\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 (this.identity.hasUserProp(key)) {\n this.logger.debug(`setOnceProperty: \"${key}\" already set`);\n return;\n }\n this.identity.setUserProp(key, value);\n const traits = sanitizeProperties({ [key]: value }, this.logger);\n this.capture(\n '$identify',\n 'identify',\n undefined,\n traits,\n sanitizedTraitOp('$set_once', traits)\n );\n });\n }\n\n unsetProperty(key: string): void {\n this.guard(() => {\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 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 void this.flushUploads();\n });\n }\n\n optOut(): void {\n this.guard(() => {\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 if (this.flushTimer !== null) clearInterval(this.flushTimer);\n this.flushTimer = null;\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 }\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 * Queues an event and re-arms the teardown drain.\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 private enqueueEvent(event: DepsmithSdkEvent): void {\n this.queue.enqueue(event);\n this.drained = false;\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 // ── Pipeline ──────────────────────────────────────────────────────────────────\n\n /**\n * Fingerprinting is opt-in and privacy-gated: it requires explicit config, granted\n * consent (consent.current is 'denied' under DNT and never 'granted' while pending),\n * 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 return {\n fingerprint:\n this.config.deviceFingerprinting &&\n !this.config.childSafeMode &&\n this.consent.current === 'granted',\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:\n this.config.geolocation &&\n !this.config.childSafeMode &&\n this.consent.current === 'granted',\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 };\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 ): void {\n if (!this.consent.canCapture()) {\n this.logger.debug(`capture dropped (consent denied): ${name}`);\n return;\n }\n\n const touch = this.session.touch();\n // Sampling is evaluated AFTER 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 // Order is load-bearing (API_SPEC §5): the old session's end precedes the new\n // session's 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:\n // the ending and starting sessions have different ids and can therefore decide\n // differently, and an exempt $identify must not drag a boundary event into an\n // out-of-sample session.\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\n if (!this.inSample(touch.sessionId, type)) {\n this.logger.debug(`capture dropped (out of sample): ${name}`);\n return;\n }\n\n const now = 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 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 const props = {\n ...this.config.defaultProperties,\n ...sanitizeProperties(properties, 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 */\n private detectConfigDrift(): void {\n const KEY = 'depsmith_config_fp';\n const fingerprint = djb2(this.config.apiKey);\n const stored = this.storage.get(KEY);\n if (stored !== null && stored !== fingerprint) {\n this.logger.warn('apiKey changed since last run; dropping queued events for the old project');\n this.queue.clear();\n }\n this.storage.set(KEY, fingerprint);\n }\n\n private pickStorage(): KVStorage {\n if (this.config.storage === 'memory') return new MemoryAdapter();\n if (this.config.storage === 'indexeddb' && typeof indexedDB !== 'undefined') {\n return new IndexedDBAdapter();\n }\n return defaultStorage();\n }\n\n private enqueueSessionEnd(ended: {\n id: string;\n lastActivityAt: 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.\n if (!this.consent.canCapture()) {\n this.logger.debug('session_end 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_end',\n event_type: 'session_end',\n timestamp: isoTimestamp(ended.lastActivityAt),\n session_id: ended.id,\n session_started_at: isoTimestamp(ended.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) event.device_id = computeVisitorId();\n this.enqueueEvent(event);\n }\n\n /**\n * Announces a session the SDK just observed beginning.\n *\n * Consent-gated for the same reason as enqueueSessionEnd: the visibilitychange resume\n * path reaches this without going through capture(). Under `pending` consent\n * canCapture() is true, so it is queued and held — matching capture() exactly.\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 if (this.config.sessionEvents === 'derive') return;\n if (!this.consent.canCapture()) {\n this.logger.debug('session_start 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_start',\n event_type: 'session_start',\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 timestamp: isoTimestamp(started.startedAt),\n session_id: started.id,\n session_started_at: isoTimestamp(started.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) event.device_id = computeVisitorId();\n\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 signal\n // drifting produces a completely different id, and a returning visitor who cleared both\n // stores is unrecoverable. Sending the parts lets the collector do N-of-M matching and\n // recover them instead. They cost a few hundred bytes and cannot change within a session,\n // so per-event transmission would be pure waste — the hash alone 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 paying\n // for boundary rows, and smuggling the payload onto an ordinary event would both contradict\n // that and pollute a caller's own event properties.\n if (contextOptions.fingerprint) {\n event.properties = { ...event.properties, ...fingerprintComponents() };\n }\n\n this.enqueueEvent(event);\n }\n\n // ── Lifecycle ─────────────────────────────────────────────────────────────────\n\n private startFlushTimer(): void {\n this.flushTimer = setInterval(() => {\n if (this.queue.size > 0 && this.consent.canUpload()) void this.flushUploads();\n }, this.config.batchIntervalMs);\n }\n\n private attachLifecycle(): void {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\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 enqueueEvent().\n const onPageHide = (): void => {\n if (this.drained) return;\n this.drained = true;\n if (this.consent.canUpload()) this.uploader.sendBeaconAll();\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 this.persistNow();\n };\n const onVisibility = (): void => {\n if (document.visibilityState === 'hidden') {\n onPageHide();\n } else {\n this.drained = false;\n // resume: run the session-timeout check\n const touch = this.session.touch();\n if (touch.endedSession) this.enqueueSessionEnd(touch.endedSession);\n if (touch.startedSession) this.enqueueSessionStart(touch.startedSession);\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 = (): void => {\n this.drained = false;\n };\n const onOnline = (): void => {\n // A network change is the one signal that a paused collector may be reachable again.\n this.uploader.resetNetworkBreaker();\n if (this.queue.size > 0 && this.consent.canUpload()) void this.flushUploads();\n };\n\n window.addEventListener('pagehide', onPageHide);\n window.addEventListener('pageshow', onPageShow);\n document.addEventListener('visibilitychange', onVisibility);\n window.addEventListener('online', onOnline);\n this.teardownFns.push(() => {\n window.removeEventListener('pagehide', onPageHide);\n window.removeEventListener('pageshow', onPageShow);\n document.removeEventListener('visibilitychange', onVisibility);\n window.removeEventListener('online', onOnline);\n });\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 void loadAutocapture()\n .then((module) => {\n if (!module) return; // build has autocapture compiled out (Shopify pixel)\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: () => this.page(),\n })\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"],"mappings":"udACO,SAASA,EAAgBC,EAAkBC,EAA0B,CAC1E,IAAMC,EAAkB,CAAC,EACrBC,EAA0BH,EAE9B,KAAOG,GAAWA,IAAY,SAAS,iBAAmBD,EAAM,OAASD,GAAU,CACjF,IAAIG,EAAOD,EAAQ,QAAQ,YAAY,EACvC,GAAIA,EAAQ,GAAI,CACdD,EAAM,QAAQ,GAAGE,CAAI,IAAID,EAAQ,EAAE,EAAE,EACrC,KACF,CACA,IAAME,EAAU,MAAM,KAAKF,EAAQ,SAAS,EAAE,MAAM,EAAG,CAAC,EACpDE,EAAQ,SAAQD,GAAQ,IAAIC,EAAQ,KAAK,GAAG,CAAC,IAEjD,IAAMC,EAAyBH,EAAQ,cACvC,GAAIG,EAAQ,CACV,IAAMC,EAAW,MAAM,KAAKD,EAAO,QAAQ,EAAE,OAAQE,GAAMA,EAAE,UAAYL,EAAS,OAAO,EACrFI,EAAS,OAAS,IAAGH,GAAQ,gBAAgBG,EAAS,QAAQJ,CAAO,EAAI,CAAC,IAChF,CACAD,EAAM,QAA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AEA,MAAO,CAACC,EAAcC,IAAkCR,GAAQ,MAAMO,EAAMC,CAAU,EACtF,KAAM,CAACD,EAAeC,IAAkCR,GAAQ,KAAKO,EAAMC,CAAU,EACrF,OAAQ,CAACD,EAAeC,IAAkCR,GAAQ,OAAOO,EAAMC,CAAU,EACzF,SAAU,CAACC,EAAgBC,IAA8BV,GAAQ,SAASS,EAAQC,CAAM,EACxF,MAAQC,GAA0BX,GAAQ,MAAMW,CAAO,EACvD,MAAO,IAAYX,GAAQ,MAAM,EACjC,MAAO,CAACY,EAAiBF,IAA8BV,GAAQ,MAAMY,EAASF,CAAM,EACpF,eAAiBA,GAA6BV,GAAQ,eAAeU,CAAM,EAC3E,YAAa,CAACG,EAAaC,IAAoCd,GAAQ,YAAYa,EAAKC,CAAK,EAC7F,gBAAiB,CAACD,EAAaC,IAC7Bd,GAAQ,gBAAgBa,EAAKC,CAAK,EACpC,cAAgBD,GAAsBb,GAAQ,cAAca,CAAG,EAE/D,kBAAoBE,GAA+Bf,GAAQ,kBAAkBe,CAAG,EAChF,MAAO,IAAYf,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,CAACgB,EAAmBC,IAChCjB,GAAQ,aAAagB,EAAWC,CAAS,EAG3C,UAAiB,CACfjB,GAAQ,SAAS,EACjBA,EAAS,KACTC,GAAa,IACf,CACF","names":["elementSelector","element","maxDepth","parts","current","part","classes","parent","siblings","c","isIgnored","ignoredSelectors","selector","safeText","text","isSensitiveField","input","SENSITIVE_INPUT_TYPES","init_selector","__esmMin","autocapture_exports","__export","startAutocapture","config","hooks","teardowns","onNavigate","captureClicks","captureForms","scroll","captureScrollDepth","observeNavigation","fn","stop","interactiveOnly","onClick","event","target","interactive","INTERACTIVE_SELECTOR","element","isIgnored","properties","elementSelector","text","safeText","onSubmit","form","fields","el","isSensitiveField","reached","scrollable","frame","attached","host","measure","percent","evaluate","QUARTILES","depth","detach","onScroll","box","MIN_HOST_SCROLLABLE_PX","observeHost","scheduleFrame","onResize","observer","content","i","attach","cancelFrame","handle","lastUrl","emitIfChanged","originalPush","originalReplace","args","init_autocapture","__esmMin","init_selector","src_exports","__export","AsyncMirrorAdapter","DEPSMITH_SDK_STORAGE_KEYS","DepsmithSdk","DepsmithSdkClient","idleScheduler","syncScheduler","__toCommonJS","loadAutocapture","SUPPRESSIONS","TRACKING_DEFAULTS","option","resolveTrackingOptions","options","resolved","applyTrackingOptions","context","record","key","sub","block","AUTOCAPTURE_DEFAULTS","resolveClicks","clicks","resolveConfig","config","autocapture","clamp","resolveTrackingOptions","n","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","primeGeolocation","permissions","status","requestFix","position","latitude","longitude","accuracy","next","readGeolocation","LIBRARY_NAME","SDK_VERSION","invariants","readInvariants","next","buildContext","opts","context","LIBRARY_NAME","SDK_VERSION","attempt","cached","readInvariants","enrichFingerprint","fix","readGeolocation","key","value","applyTrackingOptions","browser","os","deviceType","hinted","parseUserAgent","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","eventIds","ids","sizes","sizeSum","uuidv7","now","bytes","i","hex","uuidv7ToMs","id","ms","DEPSMITH_SDK_STORAGE_KEYS","MemoryAdapter","key","value","LocalStorageAdapter","ls","CookieAdapter","domain","prefix","part","maxAge","secure","MIRRORED_IDENTITY_KEYS","RedundantAdapter","primary","secondary","mirrored","fromPrimary","fromSecondary","winner","olderUuidV7","a","b","aMs","uuidv7ToMs","bMs","IndexedDBAdapter","dbName","resolve","request","tx","keysReq","valuesReq","keys","i","AsyncMirrorAdapter","backend","defaultStorage","probe","KEY_ANON","KEY_USER","KEY_GROUP","KEY_PROPS","IdentityManager","storage","clock","id","uuidv7","userId","groupId","key","value","props","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","TRAIT_OPERATORS","MAX_ADD_KEYS","MAX_UNSET_KEYS","normalizeUserPropertyOps","ops","logger","others","k","out","claimed","claim","key","operator","raw","clean","sanitizeProperties","kept","value","count","sanitizedTraitOp","systemClock","isoTimestamp","ms","isRetryable","status","BASE_MS","MAX_BACKOFF_MS","backoffMs","attempt","random","base","gzip","text","cs","writer","reader","chunks","done","value","total","n","c","out","offset","chunk","eventIds","batch","ids","event","REQUEST_TIMEOUT_MS","KEEPALIVE_MAX_BYTES","MAX_UNLOAD_BATCHES","bodyBytes","body","BatchUploader","queue","config","deps","err","result","breaker","answered","attempt","status","isRetryable","backoffMs","payload","isoTimestamp","json","controller","timer","headers","keepalive","init","configured","batches","KEY_NET_BREAKER","createNetworkBreaker","storage","clock","loaded","failures","openUntil","cooldown","clamp","v","lo","hi","load","s","KEY_NET_BREAKER","save","Logger","enabled","args","MAX_ENVELOPE_ID_LENGTH","DepsmithSdkClient","config","overrides","resolveConfig","Logger","systemClock","identityStorage","MemoryAdapter","RedundantAdapter","CookieAdapter","IdentityManager","SessionManager","ConsentManager","dntEnabled","EventQueue","primeClientHints","primeGeolocation","IndexedDBAdapter","persisted","raw","BatchUploader","args","ms","r","createNetworkBreaker","name","properties","value","label","pageName","userId","traits","clean","sanitizeProperties","sanitizedTraitOp","aliasId","groupId","key","normalizeUserPropertyOps","ops","normalized","err","sessionId","startedAt","fn","event","bucket","type","userProperties","touch","now","contextOptions","uuidv7","isoTimestamp","buildContext","SDK_VERSION","props","computeVisitorId","KEY","fingerprint","djb2","stored","defaultStorage","ended","started","fingerprintComponents","onPageHide","onVisibility","onPageShow","onOnline","autocaptureConfig","loadAutocapture","module","client","initApiKey","DepsmithSdk","config","overrides","DepsmithSdkClient","err","name","properties","userId","traits","aliasId","groupId","key","value","ops","sessionId","startedAt"]}