@sagepilot-ai/web-events-addon 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../sdk-installation-client/src/index.ts","../package.json","../src/projection.ts","../src/product.ts","../src/dom.ts","../src/collectors.ts","../src/network.ts","../src/storage.ts","../src/popup-design.ts","../src/popup.ts","../src/index.ts"],"sourcesContent":["/** Distinguishes transport failures from HTTP rejections of an installation request. */\nexport class SagepilotInstallationError extends Error {\n readonly status?: number;\n readonly cause?: unknown;\n\n constructor(\n readonly code: \"invalid_response\" | \"network_error\",\n message: string,\n options: { status?: number; cause?: unknown } = {},\n ) {\n super(message);\n this.name = \"SagepilotInstallationError\";\n this.status = options.status;\n this.cause = options.cause;\n }\n}\n\ntype InstallationStorage = {\n getItem(key: string): string | null | Promise<string | null>;\n setItem(key: string, value: string): void | Promise<void>;\n removeItem(key: string): void | Promise<void>;\n};\n\nexport type SagepilotInstallationOwner = { session_id: string; customer_id: string | null };\nexport type SDKPopupBlock =\n | { kind: \"logo\" | \"title\" | \"body\" | \"hero\" | \"form\" }\n | { kind: \"heading\" | \"text\"; text: string }\n | { kind: \"image\"; url: string; alt: string }\n | { kind: \"link\"; url: string; text: string };\n\nexport type SDKPopupDesign = {\n layout: \"centered\" | \"image_left\" | \"image_right\" | \"bottom_sheet\";\n background_color: string;\n text_color: string;\n button_text_color: string;\n border_radius: number;\n padding: number;\n width: number;\n font_family: string | null;\n font_url: string | null;\n image_url: string | null;\n image_alt: string;\n blocks: SDKPopupBlock[] | null;\n};\n\nexport type SagepilotPopupConfig = {\n revision: number; enabled: boolean; title: string; body: string; button_text: string; success_text: string;\n logo_url: string | null; accent_color: string; fields: { name: boolean; email: boolean; phone: boolean };\n required_fields: Array<\"name\" | \"email\" | \"phone\">; consent: { required: boolean; label: string };\n trigger: { delay_seconds: number; scroll_percent: number; page_paths: string[] };\n frequency_hours: number; verification: \"email\" | \"none\";\n design?: SDKPopupDesign | null;\n};\nexport type SagepilotContactInput = {\n submission_id: string; popup_revision: number; name?: string; email?: string; phone?: string; marketing_consent: boolean;\n};\nexport type SagepilotContactResult = { status: \"verification_required\" | \"recorded\"; challenge_id?: string; expires_at?: string };\nexport type SagepilotSDKObservation = {\n event_id: string;\n kind: \"navigation\" | \"interaction\" | \"network\" | \"lifecycle\" | \"screen\";\n occurred_at: string;\n owner: SagepilotInstallationOwner & { identity_epoch: string };\n data: Record<string, unknown>;\n [key: string]: unknown;\n};\nexport type SagepilotInstallationReceipt = {\n results: Array<{ event_id: string; status: \"admitted\" | \"duplicate\" | \"disabled\" | \"invalid\" | \"retryable\" }>;\n};\nexport type SagepilotInstallationSession = SagepilotInstallationOwner & {\n workspace_id: string;\n installation_id: string;\n anonymous_id: string;\n platform: \"web\" | \"android\" | \"ios\";\n session_token: string;\n expires_at: string;\n collection_enabled: boolean;\n visitor_cookie_enabled?: boolean;\n revision: number;\n ingestion_url: string;\n popup?: SagepilotPopupConfig | null;\n};\ntype SagepilotBrowserVisitor = {\n anonymous_id: string | null;\n popup_completed: boolean;\n restored: boolean;\n};\nexport type SagepilotInstallationOptions = {\n key: string;\n /** Gateway origin; HTTPS is required except for loopback development. */\n apiHost?: string;\n platform: \"web\" | \"android\" | \"ios\";\n sdk: { name: string; version: string };\n appId?: string;\n fetch?: typeof fetch;\n /** Optional scoped session persistence; tokens never enter the observation journal. */\n storage?: InstallationStorage;\n};\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst VISITOR_ID = /^[A-Za-z0-9_-]{1,128}$/;\nconst TERMINAL = new Set([\"admitted\", \"duplicate\", \"disabled\", \"invalid\", \"retryable\"]);\n\n/** Restricts credential-bearing requests to HTTPS or an explicit loopback development endpoint. */\nfunction safeURL(value: string): URL {\n const url = new URL(value);\n if (url.username || url.password || url.search || url.hash ||\n (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\", \"10.0.2.2\"].includes(url.hostname)))) {\n throw new Error(\"SDK endpoints require HTTPS and cannot contain credentials, queries or fragments.\");\n }\n return url;\n}\n\n/** Checks receipt identity before any collector may discard a journal record. */\nexport function validateSagepilotInstallationReceipt(value: unknown, requestedIDs: string[]): SagepilotInstallationReceipt {\n const results = (value as SagepilotInstallationReceipt | null)?.results;\n if (!Array.isArray(results)) throw new Error(\"SDK admission receipt is missing.\");\n const requested = new Set(requestedIDs), seen = new Set<string>();\n if (requested.size !== requestedIDs.length) throw new Error(\"SDK batch contains duplicate observation IDs.\");\n for (const item of results) {\n if (!item || !requested.has(item.event_id) || seen.has(item.event_id) || !TERMINAL.has(item.status)) {\n throw new Error(\"SDK admission receipt does not match the requested observations.\");\n }\n seen.add(item.event_id);\n }\n return { results };\n}\n\n/** Installation-scoped anonymous sessions shared by browser and native event collectors. */\nexport class SagepilotInstallationClient {\n readonly workspaceId: string;\n readonly installationId: string;\n readonly apiHost: string;\n private readonly fetchImpl: typeof fetch;\n private readonly storageKey: string;\n private current: SagepilotInstallationSession | null = null;\n private anonymousId: string | null = null;\n private pending: Promise<SagepilotInstallationSession> | null = null;\n private startup: Promise<SagepilotInstallationSession> | null = null;\n private generation = 0;\n private uploadRevision = 0;\n private transitioning = false;\n private readonly owners = new Map<string, SagepilotInstallationSession>();\n private readonly requests = new Set<AbortController>();\n\n /** Validates the public installation binding without treating it as customer authentication. */\n constructor(private readonly options: SagepilotInstallationOptions) {\n const parts = options.key.split(\":\");\n if (parts.length !== 2 || !parts.every(value => UUID.test(value))) throw new Error(\"SDK key must be workspace_id:installation_id UUIDs.\");\n this.workspaceId = parts[0]!.toLowerCase(); this.installationId = parts[1]!.toLowerCase();\n const host = safeURL(options.apiHost ?? \"https://api.sagepilot.ai\");\n if (host.pathname !== \"/\") throw new Error(\"SDK apiHost must be a gateway origin.\");\n this.apiHost = host.origin;\n this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.storageKey = `sagepilot:sdk-session:${this.workspaceId}:${this.installationId}`;\n }\n\n /** Returns a copy of the active anonymous session without allowing mutation of capture ownership. */\n session(): SagepilotInstallationSession | null { return this.current ? { ...this.current } : null; }\n\n /** The merchant route owns the cookie path and forwards only the visitor cookie. */\n get visitorCookiePath(): string { return `/sagepilot/visitor/${this.workspaceId}/${this.installationId}`; }\n\n /** Resolves browser continuity on the storefront without sending an upload token or contact data. */\n async syncVisitorCookie(anonymousId: string | null, analyticsAllowed: boolean, popupCompleted: boolean): Promise<SagepilotBrowserVisitor> {\n if (this.options.platform !== \"web\" || typeof location === \"undefined\") throw new Error(\"Visitor cookies require a website.\");\n const endpoint = safeURL(location.origin + this.visitorCookiePath);\n const value = await this.request(endpoint.href, {\n method: \"POST\",\n mode: \"same-origin\",\n credentials: \"same-origin\",\n body: JSON.stringify({ analytics_allowed: analyticsAllowed, anonymous_id: anonymousId, popup_completed: popupCompleted }),\n }, 2500) as SagepilotBrowserVisitor;\n if (!value || (value.anonymous_id !== null && (typeof value.anonymous_id !== \"string\" || !VISITOR_ID.test(value.anonymous_id))) ||\n typeof value.popup_completed !== \"boolean\" || typeof value.restored !== \"boolean\") {\n throw new Error(\"Invalid SDK visitor cookie response.\");\n }\n return value;\n }\n\n /** Reports whether this runtime still holds matching capture authority for a queued owner. */\n hasCaptureOwner(owner: SagepilotInstallationOwner): boolean {\n const session = this.owners.get(owner.session_id) ?? this.current;\n return !!session && session.session_id === owner.session_id && session.customer_id === owner.customer_id;\n }\n\n /** Restores only the requested browser/device owner, then obtains a fresh server-authorized session. */\n async start(anonymousId: string): Promise<SagepilotInstallationSession> {\n if (!anonymousId.trim() || anonymousId.length > 128) throw new Error(\"SDK anonymous ID must contain 1–128 characters.\");\n if (this.anonymousId && this.anonymousId !== anonymousId) throw new Error(\"Destroy this SDK client before changing its anonymous owner.\");\n this.anonymousId = anonymousId;\n if (this.startup) return this.startup;\n const generation = this.generation;\n const startup = (async () => {\n if (!this.current && this.options.storage) {\n let restored: SagepilotInstallationSession | null = null;\n try {\n const raw = await this.options.storage.getItem(this.storageKey);\n if (raw && raw.length <= 16384) restored = this.validateSession(JSON.parse(raw));\n const previous = await this.options.storage.getItem(this.storageKey + \":owners\");\n if (previous && previous.length <= 65536) {\n const entries: unknown = JSON.parse(previous);\n if (Array.isArray(entries) && entries.length <= 4) for (const entry of entries) {\n const owner = this.validateSession(entry); this.owners.set(owner.session_id, owner);\n }\n }\n } catch { /* Corrupt or unavailable optional storage cannot select another owner. */ }\n if (generation !== this.generation) throw new Error(\"SDK session restoration was cancelled.\");\n this.current = restored;\n }\n if (generation !== this.generation) throw new Error(\"SDK session startup was cancelled.\");\n return this.refresh(true);\n })().finally(() => { if (this.startup === startup) this.startup = null; });\n this.startup = startup;\n return startup;\n }\n\n /** Renews the owner or, when allowed for web capture, starts fresh after an expired browser session. */\n async refresh(recoverAnonymous = false): Promise<SagepilotInstallationSession> {\n if (this.pending) return this.pending;\n if (!this.anonymousId) throw new Error(\"Start the installation client before renewing it.\");\n const generation = this.generation, prior = this.current;\n const pending = (async () => {\n let renewing = prior;\n let value: unknown;\n try { value = await this.requestSession(prior?.session_token); }\n catch (error) {\n if (!recoverAnonymous || !prior || this.options.platform !== \"web\" || generation !== this.generation ||\n !(error instanceof SagepilotInstallationError) || error.status !== 401) throw error;\n renewing = null;\n value = await this.requestSession();\n }\n const next = this.validateSession(value);\n if (generation !== this.generation) throw new Error(\"SDK session startup was cancelled.\");\n if (renewing && (next.session_id !== renewing.session_id || next.customer_id !== renewing.customer_id) ||\n !renewing && (next.customer_id !== null || next.session_id === prior?.session_id)) {\n throw new Error(\"SDK session renewal changed capture ownership.\");\n }\n if (prior && !renewing) this.owners.delete(prior.session_id);\n this.current = next;\n this.remember(next);\n try { await this.options.storage?.setItem(this.storageKey, JSON.stringify(next)); } catch { /* Event journals report their own storage gaps. */ }\n return { ...next };\n })().finally(() => { if (this.pending === pending) this.pending = null; });\n this.pending = pending;\n return pending;\n }\n\n /** Requests policy for this browser or device with the original token when renewing. */\n private requestSession(token?: string): Promise<unknown> {\n return this.request(`${this.apiHost}/platform-api/v1/sdk/sessions`, {\n method: \"POST\",\n headers: token ? { Authorization: `Bearer ${token}` } : {},\n body: JSON.stringify({ key: `${this.workspaceId}:${this.installationId}`, anonymous_id: this.anonymousId, platform: this.options.platform,\n ...(this.options.appId ? { app_id: this.options.appId } : {}) })\n });\n }\n\n /** Supplies a short-lived native upload authorization only for the original capture owner. */\n async authorize(owner: SagepilotInstallationOwner): Promise<{ url: string; headers: Record<string, string> }> {\n let session = this.owners.get(owner.session_id) ?? this.current;\n if (!session || owner.customer_id !== session.customer_id || owner.session_id !== session.session_id) throw new Error(\"SDK capture ownership changed.\");\n if (Date.parse(session.expires_at) - Date.now() < 60000) {\n if (session.session_id === this.current?.session_id) session = await this.refresh();\n else {\n const original = session;\n session = this.validateSession(await this.requestSession(session.session_token));\n if (session.session_id !== original.session_id || session.customer_id !== original.customer_id) throw new Error(\"Historical capture ownership changed.\");\n this.remember(session);\n }\n }\n if (!session.collection_enabled || owner.session_id !== session.session_id || owner.customer_id !== session.customer_id) throw new Error(\"SDK collection is disabled or its owner changed.\");\n return { url: session.ingestion_url, headers: { Authorization: `Bearer ${session.session_token}`,\n \"Content-Type\": \"application/json\", \"X-Sagepilot-Sdk-Name\": this.options.sdk.name, \"X-Sagepilot-Sdk-Version\": this.options.sdk.version } };\n }\n\n /** Posts one bounded immutable batch; collectors own backoff and retain missing/retryable receipts. */\n async upload(observations: SagepilotSDKObservation[], owner: SagepilotInstallationOwner): Promise<SagepilotInstallationReceipt> {\n if (!observations.length || observations.length > 100) throw new Error(\"SDK batches require 1–100 observations.\");\n for (const item of observations) {\n if (item.owner.session_id !== owner.session_id || item.owner.customer_id !== owner.customer_id) throw new Error(\"SDK batch mixes capture ownership.\");\n }\n const revision = this.uploadRevision;\n const auth = await this.authorize(owner);\n if (revision !== this.uploadRevision) throw new Error(\"SDK upload was cancelled.\");\n const body = JSON.stringify({ schema_version: 1, observations });\n if (new TextEncoder().encode(body).byteLength > 128 * 1024) throw new Error(\"SDK batch exceeds the upload limit.\");\n return validateSagepilotInstallationReceipt(await this.request(auth.url, { method: \"POST\", headers: auth.headers, body }), observations.map(item => item.event_id));\n }\n\n /** Submits explicit popup contacts independently from ordinary observation payloads. */\n async submitContact(input: SagepilotContactInput): Promise<SagepilotContactResult> {\n if (!UUID.test(input.submission_id) || !Number.isSafeInteger(input.popup_revision) || input.popup_revision < 1 || typeof input.marketing_consent !== \"boolean\") throw new Error(\"Invalid popup submission.\");\n const result = await this.authenticated(\"/contact\", input) as SagepilotContactResult;\n if (!result || ![\"recorded\", \"verification_required\"].includes(result.status) ||\n result.status === \"verification_required\" && (!result.challenge_id || !UUID.test(result.challenge_id) || !Number.isFinite(Date.parse(result.expires_at ?? \"\")))) throw new Error(\"Invalid popup submission response.\");\n return result;\n }\n\n /** Adopts customer authority only from the server's completed verification operation. */\n async verifyContact(challengeId: string, code: string): Promise<SagepilotInstallationSession> {\n if (!UUID.test(challengeId) || !/^\\d{6}$/.test(code)) throw new Error(\"Enter the six-digit verification code.\");\n return this.transition(\"/contact/verify\", { challenge_id: challengeId, code }, true);\n }\n\n /** Revokes the current identified grant and establishes a fresh anonymous capture owner. */\n async logout(): Promise<SagepilotInstallationSession> { return this.transition(\"/logout\", {}, false); }\n\n /** Keeps a bounded credential cache separate from observations so old anonymous batches retain their owner. */\n private remember(session: SagepilotInstallationSession): void {\n this.owners.set(session.session_id, { ...session });\n while (this.owners.size > 4) this.owners.delete(this.owners.keys().next().value!);\n try { void Promise.resolve(this.options.storage?.setItem(this.storageKey + \":owners\", JSON.stringify([...this.owners.values()]))).catch(() => {}); } catch { /* Optional credential storage may be unavailable. */ }\n }\n\n /** Uses the current scoped credential for identity operations without attaching it to event records. */\n private async authenticated(path: string, body: unknown): Promise<unknown> {\n const prior = this.current;\n if (!prior) throw new Error(\"Start the installation client first.\");\n if (Date.parse(prior.expires_at) - Date.now() < 60000) await this.refresh();\n if (this.current?.session_id !== prior.session_id) throw new Error(\"SDK identity session changed.\");\n return this.request(`${this.apiHost}/platform-api/v1/sdk${path}`, { method: \"POST\", headers: { Authorization: `Bearer ${this.current.session_token}` }, body: JSON.stringify(body) });\n }\n\n /** Serializes explicit ownership transitions and rejects unrelated or stale server responses. */\n private async transition(path: string, body: unknown, identified: boolean): Promise<SagepilotInstallationSession> {\n if (this.transitioning) throw new Error(\"An SDK identity operation is already running.\");\n this.transitioning = true;\n const generation = this.generation, prior = this.current;\n try {\n const next = this.validateSession(await this.authenticated(path, body));\n if (generation !== this.generation || !prior || next.session_id === prior.session_id || (identified ? next.customer_id === null : next.customer_id !== null)) throw new Error(\"Invalid SDK identity transition.\");\n this.generation++; this.cancelPending(); this.pending = null;\n if (path === \"/logout\") this.owners.delete(prior.session_id);\n else this.remember(prior);\n this.current = next; this.remember(next);\n try { await this.options.storage?.setItem(this.storageKey, JSON.stringify(next)); } catch { /* Optional session storage is isolated from capture. */ }\n return { ...next };\n } finally { this.transitioning = false; }\n }\n\n /** Cancels requests on permission/ownership boundaries while preserving the current session for safe renewal. */\n cancelPending(): void { this.uploadRevision++; for (const controller of this.requests) controller.abort(); }\n\n /** Fences in-flight session adoption and stops all outstanding requests. */\n destroy(): void { this.generation++; this.cancelPending(); this.current = null; this.anonymousId = null; this.pending = null; this.startup = null; this.owners.clear(); }\n\n /** Rejects foreign, identified or malformed session responses before credentials are used. */\n private validateSession(value: unknown): SagepilotInstallationSession {\n const session = value as SagepilotInstallationSession;\n if (!session || session.workspace_id !== this.workspaceId || session.installation_id !== this.installationId ||\n session.platform !== this.options.platform || session.anonymous_id !== this.anonymousId || (session.customer_id !== null && (typeof session.customer_id !== \"string\" || !UUID.test(session.customer_id))) ||\n !UUID.test(session.session_id) || typeof session.session_token !== \"string\" || session.session_token.length > 16384 || !session.session_token ||\n !Number.isFinite(Date.parse(session.expires_at)) || typeof session.collection_enabled !== \"boolean\" ||\n (session.visitor_cookie_enabled !== undefined && typeof session.visitor_cookie_enabled !== \"boolean\") ||\n !Number.isSafeInteger(session.revision)) {\n throw new Error(\"SDK session response has invalid scope or ownership.\");\n }\n const url = safeURL(session.ingestion_url);\n if (url.pathname !== \"/events/v1/sdk/observations\") throw new Error(\"SDK ingestion route is invalid.\");\n return { ...session };\n }\n\n /** Performs bounded SDK HTTP requests without retrying mutations or following credential redirects. */\n private async request(url: string, init: RequestInit, timeoutMs = 15000): Promise<unknown> {\n const controller = new AbortController(); this.requests.add(controller);\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const headers = new Headers(init.headers);\n headers.set(\"Content-Type\", \"application/json\");\n headers.set(\"X-Sagepilot-Sdk-Name\", this.options.sdk.name);\n headers.set(\"X-Sagepilot-Sdk-Version\", this.options.sdk.version);\n const response = await this.fetchImpl(url, { ...init, headers, signal: controller.signal, redirect: \"error\", credentials: init.credentials ?? \"omit\" });\n if (!response.ok) {\n void response.body?.cancel().catch(() => {});\n throw new SagepilotInstallationError(\"invalid_response\", `SDK request failed with HTTP ${response.status}.`, { status: response.status });\n }\n if (Number(response.headers.get(\"content-length\") ?? 0) > 65536) throw new Error(\"SDK response exceeds limit.\");\n let text = \"\";\n if (response.body?.getReader) {\n const reader = response.body.getReader(), decoder = new TextDecoder(); let bytes = 0;\n try {\n for (;;) {\n const part = await reader.read(); if (part.done) break;\n bytes += part.value.byteLength;\n if (bytes > 65536) { await reader.cancel(); throw new Error(\"SDK response exceeds limit.\"); }\n text += decoder.decode(part.value, { stream: true });\n }\n text += decoder.decode();\n } finally { reader.releaseLock(); }\n } else {\n text = await response.text();\n if (text.length > 65536) throw new Error(\"SDK response exceeds limit.\");\n }\n return JSON.parse(text);\n } catch (error) {\n if (controller.signal.aborted || error instanceof TypeError) {\n throw new SagepilotInstallationError(\"network_error\", \"SDK request could not reach the server.\", { cause: error });\n }\n throw error;\n } finally { clearTimeout(timeout); this.requests.delete(controller); }\n }\n}\n\n/** Creates the shared anonymous installation-session transport without initializing chat or channels. */\nexport function createSagepilotInstallationClient(options: SagepilotInstallationOptions): SagepilotInstallationClient {\n return new SagepilotInstallationClient(options);\n}\n","{\n \"name\": \"@sagepilot-ai/web-events-addon\",\n \"version\": \"0.2.1\",\n \"description\": \"Optional automatic browser observations for Sagepilot SDK installations\",\n \"license\": \"UNLICENSED\",\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./sagepilot-web-events.js\": \"./dist/sagepilot-web-events.global.js\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"sideEffects\": [\n \"./dist/sagepilot-web-events.global.js\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"typecheck\": \"tsc --noEmit\",\n \"prepublishOnly\": \"npm run typecheck && npm run build\"\n },\n \"devDependencies\": {\n \"@sagepilot-ai/sdk-installation-client\": \"0.0.0\",\n \"tsup\": \"^8.3.5\",\n \"typescript\": \"^5.7.2\"\n }\n}\n","export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };\ntype Projection = { fields: Json[]; structure: Json[]; limited: boolean };\nconst sensitive = /password|passwd|secret|token|authorization|cookie|session|email|phone|contact|address|card|payment|cvv|ssn|dob|birth|customer|user|account|person|profile|name|description|message|content|text|search|query/i;\nconst compact = /^[A-Za-z0-9_.:-]{1,128}$/;\nconst routes = new Map<string, Promise<string | null>>();\n\n/** Projects only bounded, typed, non-contact JSON facts; arbitrary strings are omitted. */\nexport function project(value: unknown): Projection {\n const output: Projection = { fields: [], structure: [], limited: false };\n let budget = 256;\n /** Visits plain JSON containers within shared depth, node and scalar limits. */\n function visit(input: unknown, path: string, depth: number): void {\n if (--budget < 0 || depth > 8 || output.fields.length >= 48) { output.limited = true; return; }\n if (input === null || typeof input === \"boolean\" || typeof input === \"number\") {\n if (typeof input === \"number\" && (!Number.isFinite(input) || Math.abs(input) > Number.MAX_SAFE_INTEGER)) return;\n output.fields.push({ path, type: input === null ? \"null\" : typeof input, value: input }); return;\n }\n if (typeof input === \"string\") {\n // Numeric product references retain precision; general phone-like strings and long credentials are omitted.\n const numericProductReference = /\\.(?:product_id|variant_id|sku)$/.test(path) && /^\\d{1,20}$/.test(input);\n if (numericProductReference || compact.test(input) && !/^\\+?\\d{7,}$/.test(input) && !/^[A-Za-z0-9_-]{32,}$/.test(input)) output.fields.push({ path, type: \"string\", value: input });\n else output.fields.push({ path, type: \"string\", omitted: \"privacy_or_size\" });\n return;\n }\n if (Array.isArray(input)) {\n output.structure.push({ path, type: \"array\" });\n for (let index = 0; index < Math.min(input.length, 10); index++) visit(input[index], `${path}[${index}]`, depth + 1);\n if (input.length > 10) output.limited = true;\n return;\n }\n if (!input || typeof input !== \"object\" || Object.getPrototypeOf(input) !== Object.prototype) return;\n output.structure.push({ path, type: \"object\" });\n const keys: string[] = [];\n for (const key in input) { if (Object.prototype.hasOwnProperty.call(input, key)) keys.push(key); if (keys.length > 32) break; }\n keys.sort();\n if (keys.length > 32) output.limited = true;\n for (const key of keys.slice(0, 32)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]{0,47}$/.test(key) || sensitive.test(key)) continue;\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (descriptor && \"value\" in descriptor) visit(descriptor.value, `${path}.${key}`, depth + 1);\n }\n }\n visit(value, \"$\", 0);\n return output;\n}\n\n/** Parses only a bounded existing JSON string; it never reads an application stream. */\nexport function projectText(value: unknown): Projection | null {\n if (typeof value !== \"string\" || value.length > 65536 || !/^\\s*[\\[{]/.test(value.slice(0, 64))) return null;\n try { return project(JSON.parse(value)); } catch { return null; }\n}\n\n/** Produces bounded operation fingerprints without URL credentials, query, fragments or path values. */\nexport function routeFor(input: string): Promise<string | null> {\n if (input.length > 2048) return Promise.resolve(null);\n let url: URL;\n try { url = new URL(input, globalThis.location?.href); } catch { return Promise.resolve(null); }\n if (!/^https?:$/.test(url.protocol) || url.username || url.password) return Promise.resolve(null);\n const cacheKey = url.origin + url.pathname;\n const existing = routes.get(cacheKey);\n if (existing) return existing;\n /** Hashes alphabetic operation segments and masks likely dynamic identifiers. */\n const fingerprint = (async () => {\n if (!globalThis.crypto?.subtle) return null;\n const segments: string[] = [];\n for (const segment of url.pathname.split(\"/\").filter(Boolean).slice(0, 12)) {\n if (/^v\\d{1,2}$/i.test(segment)) { segments.push(segment.toLowerCase()); continue; }\n if (!/^[A-Za-z_-]{1,64}$/.test(segment)) { segments.push(\":id\"); continue; }\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(segment));\n segments.push(\":op_\" + Array.from(new Uint8Array(digest)).slice(0, 8).map(byte => byte.toString(16).padStart(2, \"0\")).join(\"\"));\n }\n return url.origin + \"/\" + segments.join(\"/\");\n })().catch(() => null);\n if (routes.size >= 128) routes.delete(routes.keys().next().value!);\n routes.set(cacheKey, fingerprint);\n return fingerprint;\n}\n","import type { Json } from \"./projection\";\n\nexport type ProductSnapshot = Record<string, Json> & { metadata: {\n resolution: \"resolved\" | \"unresolved\" | \"ambiguous\"; identifiers: Record<string, string>;\n variant_identifiers: Record<string, string>; attributes: Record<string, Json>;\n provenance: { source: string; source_ref: string; match: string }; limited: boolean;\n} };\nexport type ProductMatch = { snapshot: ProductSnapshot; product_ref: string };\ntype Entry = { snapshot: ProductSnapshot; ref: string; expires: number; images: string[]; rawImages?: string[]; url?: string; sku?: string; variant?: string; group?: { url?: string; name: string }; blocked?: boolean; ids?: string[] };\nconst privateKey = /pass|secret|token|auth|cookie|session|customer|buyer|user|account|profile|email|phone|mobile|contact|address|payment|credit|cvv|order|personal|customiz|monogram|option|review|message|comment|__proto__|constructor|prototype/i;\nconst identifier = /^(?:@?id|schema_product(?:ID|SKU)|productGroup(?:ID|SKU)|(?:product[_-]?)?sku|(?:product|catalog(?:ue)?|variant|item|article|part|model)[_-]?(?:id|code|number|ref)|mpn|gtin(?:8|12|13|14)?|upc|ean|isbn|reference|code)$/i;\nconst aliases = { product_id: /^(?:product[_-]?id|id)$/i, variant_id: /^(?:variant[_-]?id)$/i, sku: /^(?:product[_-]?)?sku$/i };\nconst publicField = /^(?:@type|@id|name|title|product_name|slug|id|productGroupID|product[_-]?(?:id|sku|url)|variant[_-]?id|sku|mpn|gtin\\d*|url|image|images|image_url|imageUrl|offers|variants|hasVariant|price|priceValue|sale_price|price[_-]?Currency|currency|currencyId|currencyFormat|brand|category|color|size|material|availability|stockRemaining|available|selected|selectedVariantId)$/i;\n/** Normalizes public labels for exact comparisons; no fuzzy title match can select an identity. */\nfunction normalized(value: unknown): string { return typeof value === \"string\" ? value.normalize(\"NFKC\").trim().toLowerCase().replace(/\\s+/g, \" \") : \"\"; }\n\n/** Removes only a terminal displayed price from an otherwise exact commerce action label. */\nexport function commerceAction(value: string): string {\n const label = value.normalize(\"NFKC\").trim();\n return label.replace(/\\s*[·|–—-]\\s*(?:₹|\\$|€|£|INR|USD|EUR|GBP)\\s*(?:\\d{1,8}|\\d{1,3}(?:,\\d{3}){1,2}|\\d{1,2}(?:,\\d{2}){1,2},\\d{3})(?:\\.\\d{1,2})?\\s*$/i, \"\").trim();\n}\n\n/** Compares an explicitly typed Shopify variant GID with its declared URL selector without inventing an ID. */\nfunction sameVariant(left: string | undefined | null, right: string | undefined | null): boolean {\n return !!left && !!right && (left === right || left.replace(/^gid:\\/\\/shopify\\/ProductVariant\\/(\\d+)$/, \"$1\") === right.replace(/^gid:\\/\\/shopify\\/ProductVariant\\/(\\d+)$/, \"$1\"));\n}\n\n/** Reads only native commerce identifier fields, never customer or general form values. */\nfunction nativeForms(): { form: Element; product?: string; variant: string }[] | null {\n const result: { form: Element; product?: string; variant: string }[] = [], forms = [...document.querySelectorAll(\"form[action]\")];\n if (forms.length > 32) return null;\n for (const form of forms) {\n const action = publicURL(form.getAttribute(\"action\"));\n if (!action || new URL(action).origin !== location.origin || !/\\/cart\\/add\\/?$/.test(new URL(action).pathname)) continue;\n const inputs = [...form.querySelectorAll('input[type=\"hidden\"][name=\"id\"]')], products = [...form.querySelectorAll('input[type=\"hidden\"][name=\"product-id\"]')];\n if (inputs.length !== 1 || products.length > 1) continue;\n const variant = id((inputs[0] as HTMLInputElement).value ?? inputs[0]!.getAttribute(\"value\"));\n const product = id(products.length ? (products[0] as HTMLInputElement).value ?? products[0]!.getAttribute(\"value\") : form.closest(\"[data-product-id]\")?.getAttribute(\"data-product-id\"));\n if (variant) result.push({ form, product, variant });\n }\n return result;\n}\n\n/** Reads one explicitly labeled public product identifier without copying arbitrary page text. */\nfunction labeledProductID(): string | undefined {\n const labels = [...document.querySelectorAll(\"span,dt,th,label\")], values: string[] = []; if (labels.length > 1024) return;\n for (const label of labels) {\n const value = label.nextElementSibling;\n if (label.childElementCount || normalized(label.textContent) !== \"product id:\" || !value || value.childElementCount || [label, value].some(node => node.closest('header,footer,form,dialog,[role=\"dialog\"],[hidden],[aria-hidden=\"true\"],[data-sagepilot-popup],[itemprop=\"review\"],[itemtype$=\"/Review\"],[data-review-id]'))) continue;\n const product = id(value.textContent?.trim()); if (product) values.push(product);\n }\n return values.length === 1 ? values[0] : undefined;\n}\n\n/** Accepts public product URLs without signed queries, credentials, fragments or script schemes. */\nfunction publicURL(value: unknown, base = location.href, image = false): string | undefined {\n if (typeof value !== \"string\" || value.length > 1024) return;\n try {\n const url = new URL(value, base);\n const keys = [...url.searchParams.keys()];\n if (url.username || url.password || /[<>\\x00-\\x1f\\x7f@]/.test(decodeURIComponent(url.href)) || new Set(keys).size !== keys.length || keys.some(key => /token|signature|auth|credential|password|secret|policy|expires|x-amz|^sig$|^key$/i.test(key))) return;\n if (image && /\\/_next\\/image$/.test(url.pathname) && keys.every(key => key === \"url\" || key === \"w\" && /^\\d{1,5}$/.test(url.searchParams.get(key)!) || key === \"q\" && /^\\d{1,3}$/.test(url.searchParams.get(key)!) && Number(url.searchParams.get(key)) <= 100)) return publicURL(url.searchParams.get(\"url\"), base, true);\n if (image && keys.length) {\n if (!/\\.(?:jpe?g|png|webp|avif|gif|svg)$/i.test(url.pathname) || !keys.every(key => {\n const value = url.searchParams.get(key)!;\n return /^(?:w|h|width|height)$/.test(key) ? /^\\d{1,5}$/.test(value) && Number(value) > 0\n : /^(?:q|quality)$/.test(key) ? /^\\d{1,3}$/.test(value) && Number(value) > 0 && Number(value) <= 100\n : key === \"v\" ? /^\\d{1,20}$/.test(value)\n : key === \"dpr\" ? /^(?:[1-7](?:\\.\\d{1,2})?|0\\.[1-9]\\d?|8)$/.test(value)\n : /^(?:f|format)$/.test(key) ? /^(?:jpe?g|png|webp|avif|gif|svg|xxs|xs|s|m|l|xl|xxl|u|xu)$/.test(value)\n : key === \"fit\" ? /^(?:cover|contain|fill|inside|outside|max|crop)$/.test(value)\n : key === \"auto\" ? /^(?:format|compress|format,compress|compress,format)$/.test(value)\n : key === \"crop\" && /^(?:center|faces|top|bottom|left|right)$/.test(value);\n })) return;\n url.search = \"\";\n }\n if (!image && keys.length && (keys.length > 1 || !keys.every(key => /^(?:variant|variant_id)$/.test(key) && !!id(url.searchParams.get(key))))) return;\n if (!image && /^(?:#content|#product|#variant)?$/.test(url.hash)) url.hash = \"\";\n if ((url.protocol === \"https:\" || url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)) &&\n !url.username && !url.password && !url.hash && !/[<>\\x00-\\x1f\\x7f@]/.test(decodeURIComponent(url.href))) return url.href;\n } catch { /* Unusable source evidence stays unavailable. */ }\n}\n\n/** Removes only standard analytics attribution keys from document identity without retaining their values. */\nfunction documentURL(): string | undefined {\n try {\n const url = new URL(location.href);\n for (const key of [...url.searchParams.keys()]) if (/^utm_(?:source|medium|campaign|term|content|id|source_platform|creative_format|marketing_tactic)$/.test(key)) url.searchParams.delete(key);\n return publicURL(url.href);\n } catch { return; }\n}\n\n/** Excludes private account/order resources before product body access or projection. */\nfunction productSourceURL(value: string): string | undefined {\n const url = publicURL(value);\n return url && !/(?:^|[/_.-])(?:customers?|buyers?|users?|accounts?|profiles?|orders?|checkout|auth|login|sessions?|private|tokens?|contacts?|addresses|payments?)(?=[/_.-]|$)/i.test(decodeURIComponent(new URL(url).pathname)) ? url : undefined;\n}\n\n/** Screens product text before retaining it; catalog context does not authorize customer data. */\nfunction scalar(value: unknown): Json | undefined {\n if (value === null || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") return Number.isFinite(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER ? value : undefined;\n if (typeof value !== \"string\" || value.length > 256 || /[<>\\x00-\\x1f\\x7f]|@|https?:|\\+?\\d[\\d\\s().-]{5,}\\d|[A-Za-z0-9_-]{32,}|\\b(?:bearer|sk_live_|sk_test_|ghp_)|personalized|personalised|monogram|recommended for|your name/i.test(value.normalize(\"NFKC\"))) return;\n return value;\n}\n\n/** Preserves exact identifier strings and never claims rounded parsed numbers as original IDs. */\nfunction id(value: unknown): string | undefined {\n if (typeof value === \"number\") return Number.isSafeInteger(value) ? String(value) : undefined;\n return typeof value === \"string\" && /^[A-Za-z0-9_:/+=.-]{1,128}$/.test(value) && !/^(?:bearer|sk_live_|sk_test_|ghp_|eyJ[A-Za-z0-9_-]+\\.)/i.test(value) ? value : undefined;\n}\n\n/** Reads only declared public asset and SKU evidence for both accepted and rejected product rows. */\nfunction links(facts: Record<string, unknown>, base: string): Pick<Entry, \"url\" | \"images\" | \"rawImages\" | \"sku\"> {\n const image = facts.image_url ?? facts.imageUrl ?? facts.image ?? facts.images, offers = Array.isArray(facts.offers) ? facts.offers : [facts.offers];\n const assets = (Array.isArray(image) ? image : image === undefined ? [] : [image]), rawImages: string[] = []; let complete = assets.length <= 16;\n for (const value of assets.slice(0, 16)) {\n const uri = value && typeof value === \"object\" ? (value as Record<string, unknown>).url ?? (value as Record<string, unknown>).contentUrl : value;\n if (typeof uri === \"string\" && /^(?:https?:\\/\\/|\\/)/i.test(uri) && publicURL(uri, base, true)) rawImages.push(new URL(uri, base).href); else complete = false;\n }\n const urls = offers.map(value => value && typeof value === \"object\" ? publicURL((value as Record<string, unknown>).url, base) : undefined).filter(Boolean);\n return { rawImages: complete ? rawImages : undefined, url: publicURL(facts.url ?? facts.product_url ?? facts.productUrl ?? (typeof facts[\"@id\"] === \"string\" && /[/?]/.test(facts[\"@id\"]) ? facts[\"@id\"] : undefined), base) ?? (urls.length === offers.length && new Set(urls).size === 1 ? urls[0] : undefined), sku: id(facts.sku ?? facts.productSku ?? facts.product_sku),\n images: (Array.isArray(image) ? image.slice(0, 8) : [image]).map(value => {\n const uri = value && typeof value === \"object\" ? (value as Record<string, unknown>).url ?? (value as Record<string, unknown>).contentUrl : value;\n return typeof uri === \"string\" && /^(?:https?:\\/\\/|\\/)/i.test(uri) ? publicURL(uri, base, true) : undefined;\n }).filter((value): value is string => !!value) };\n}\n\n/** Parses only existing bounded JSON text, preserving identifier number lexemes when supported. */\nexport function parseProductJSON(value: string, limit = 262144): unknown {\n if (value.length > limit || new TextEncoder().encode(value).length > limit) return null;\n try {\n return JSON.parse(value, (key: string, item: unknown, context?: { source?: string }) => {\n if (identifier.test(key) && typeof item === \"number\") return context?.source && /^-?\\d+$/.test(context.source) ? context.source : id(item);\n return item;\n });\n } catch { return null; }\n}\n\n/** Parses framed public Flight JSON while skipping opaque/text payloads by their exact UTF-8 byte length. */\nfunction flightRows(value: string): unknown[] {\n // shortcut: public Flight framing is implementation-specific; unknown framing stays unresolved until a measured new format is supported.\n const bytes = new TextEncoder().encode(value), decoder = new TextDecoder(), rows: unknown[] = [];\n let offset = 0;\n while (offset < bytes.length) {\n if (bytes[offset] === 10) { offset++; continue; }\n const colon = bytes.indexOf(58, offset);\n if (colon < offset || colon - offset > 16 || !/^[\\da-f]*$/i.test(decoder.decode(bytes.subarray(offset, colon)))) return [];\n const start = colon + 1, comma = bytes.indexOf(44, start), tag = String.fromCharCode(bytes[start]!);\n if (/^[A-Za-z]$/.test(tag) && comma > start + 1 && comma - start < 16 && /^[\\da-f]+$/i.test(decoder.decode(bytes.subarray(start + 1, comma)))) {\n const size = parseInt(decoder.decode(bytes.subarray(start + 1, comma)), 16);\n if (comma + 1 + size > bytes.length) return []; offset = comma + 1 + size; continue;\n }\n const newline = bytes.indexOf(10, start), end = newline < 0 ? bytes.length : newline;\n if (bytes[start] === 91 || bytes[start] === 123) { const row = parseProductJSON(decoder.decode(bytes.subarray(start, end))); if (row === null) return []; rows.push(row); }\n offset = end + 1;\n }\n return rows;\n}\n\n/** Projects only independently bound product identifier records from inert indexed JSON; framework state is never restored. */\nfunction indexedProducts(graph: unknown, source: string, title: string, schemas: Record<string, unknown>[]): Record<string, unknown>[] {\n if (!Array.isArray(graph) || graph.length > 8192 || !Array.isArray(graph[0]) || graph[0][0] !== \"ShallowReactive\") return [];\n const values = graph;\n /** Reads one in-range integer reference without recursive graph expansion or framework revivers. */\n function ref(index: unknown): unknown { return typeof index === \"number\" && Number.isInteger(index) && index >= 0 && index < values.length ? values[index] : undefined; }\n const tail = new URL(source).pathname.split(\"/\").filter(Boolean).pop(), result: Record<string, unknown>[] = [];\n for (const row of graph) {\n if (!row || typeof row !== \"object\" || Array.isArray(row) || !Object.prototype.hasOwnProperty.call(row, \"productVariants\") || normalized(ref(row.name)) !== title) continue;\n const variants = ref(row.productVariants); if (!Array.isArray(variants) || variants.length > 16) return [];\n for (const index of variants) {\n const value = ref(index); if (!value || typeof value !== \"object\" || Array.isArray(value)) return []; const variant = value as Record<string, unknown>;\n const product_id = id(ref(row.id)), variant_id = id(ref(variant.id)), sku = id(ref(variant.sku)), name = ref(variant.name);\n if (!product_id || !variant_id || !sku || variant_id !== tail || normalized(name) !== title) continue;\n const matching = schemas.filter(value => {\n const offers = Array.isArray(value.offers) ? value.offers : [value.offers], declared = [value.url, value.product_url, value.productUrl, value[\"@id\"], ...offers.map(row => row && typeof row === \"object\" ? row.url : undefined)].filter(uri => uri !== undefined);\n return declared.every(uri => publicURL(uri, source) === source) && normalized(value.name) === title && [variant_id, sku].includes(String(value.sku));\n });\n if (matching.length !== 1) return [];\n result.push({ product_id, variant_id, sku, name, url: source, image: links(matching[0]!, source).images[0], schema_productSKU: String(matching[0]!.sku) });\n }\n }\n return result.length === 1 ? result : [];\n}\n\n/** Projects one confirmed product and optional selected variant into common fields plus safe metadata. */\nfunction project(row: Record<string, unknown>, source: string, source_ref: string, variant?: Record<string, unknown>): Entry | null {\n if (Array.isArray(row.offers) && row.offers.length > 16 || Array.isArray(variant?.offers) && variant.offers.length > 16) return null;\n const identifiers: Record<string, string> = {}, variant_identifiers: Record<string, string> = {}, attributes: Record<string, Json> = {};\n let limited = false;\n for (const [record, ids] of [[row, identifiers], ...(variant ? [[variant, variant_identifiers]] : [])] as [Record<string, unknown>, Record<string, string>][]) {\n const keys = Object.keys(record); if (keys.length > 48) limited = true;\n for (const key of keys.slice(0, 48)) {\n if (!/^[A-Za-z_@][A-Za-z0-9_@-]{0,63}$/.test(key) || privateKey.test(key) || [\"variants\", \"offers\", \"@type\", \"@context\"].includes(key) || source !== \"catalog_response\" && !identifier.test(key) && !publicField.test(key)) continue;\n if (record === row && variant && /^(?:image|images|image_url|imageUrl)$/.test(key) && links(variant, source_ref).images.length) continue;\n const value = record[key];\n if (identifier.test(key)) {\n const exact = id(value), target = record === row && /^variant[_-]?(?:id|code|number|ref)$/i.test(key) ? variant_identifiers : ids;\n if (exact !== undefined && Object.keys(target).length < 32) target[key] = exact;\n else if (exact !== undefined) limited = true;\n continue;\n }\n if (Object.keys(attributes).length >= 32) { limited = true; continue; }\n if (Array.isArray(value)) {\n if (value.length > 16) { limited = true; continue; }\n const projected = value.map(scalar); if (projected.every(item => item !== undefined)) attributes[key] = projected as Json[];\n } else { const projected = scalar(value); if (projected !== undefined) attributes[key] = projected; }\n }\n }\n const snapshot: ProductSnapshot = { metadata: { resolution: \"resolved\", identifiers, variant_identifiers, attributes,\n provenance: { source, source_ref, match: \"unresolved\" }, limited } };\n for (const [field, pattern] of Object.entries(aliases)) {\n const variantSKU = Object.keys(variant_identifiers).some(key => /^sku$/i.test(key));\n if (field === \"sku\" && variant && !variantSKU && variant_identifiers.id !== undefined && !Object.entries(identifiers).some(([key, value]) => aliases.sku.test(key) && value === variant_identifiers.id)) continue;\n const pool = field === \"product_id\" ? identifiers : field === \"sku\" ? variantSKU ? variant_identifiers : identifiers : { ...identifiers, ...variant_identifiers };\n const values = Object.keys(pool).filter(key => pattern.test(key)).map(key => pool[key]!);\n if (field === \"variant_id\" && !values.length && variant_identifiers.id !== undefined) values.push(variant_identifiers.id);\n const unique = [...new Set(values)]; if (unique.length > 1) return null;\n if (unique.length) snapshot[field] = unique[0]!;\n }\n const facts = { ...row, ...variant }, name = scalar(row.name ?? row.title ?? row.product_name ?? facts.name ?? facts.title), offer = facts.offers;\n const offers = (Array.isArray(offer) ? offer : [offer]).filter(value => value && typeof value === \"object\") as Record<string, unknown>[];\n if (offers.some(value => Array.isArray(value.priceSpecification) && value.priceSpecification.length > 16)) return null;\n if (typeof name === \"string\" && name.length <= 160) snapshot.name = name;\n const specifications = offers.map(value => {\n const specs = (Array.isArray(value.priceSpecification) ? value.priceSpecification : [value.priceSpecification]).filter(spec => spec && typeof spec === \"object\") as Record<string, unknown>[];\n return specs.filter(spec => !spec.priceType || /(?:^|\\/)SalePrice$/.test(String(spec.priceType)));\n });\n const prices = offers.map((value, n) => value.price ?? (value.lowPrice !== undefined && value.lowPrice === value.highPrice ? value.lowPrice : undefined) ?? (specifications[n]!.length && specifications[n]!.every(spec => spec.price === specifications[n]![0]!.price) ? specifications[n]![0]!.price : undefined));\n const money = facts.price && typeof facts.price === \"object\" && !Array.isArray(facts.price) ? facts.price as Record<string, unknown> : undefined;\n const amount = facts.sale_price ?? facts.priceValue ?? (money ? /^[A-Z]{3}$/.test(String(money.currencyCode)) ? money.amount : undefined : facts.price) ?? (prices.length && prices.every(value => value === prices[0]) ? prices[0] : undefined);\n if ((typeof amount === \"number\" || typeof amount === \"string\" && /^\\d{1,10}(?:\\.\\d{1,4})?$/.test(amount)) && Number.isFinite(Number(amount)) && Number(amount) >= 0 && Number(amount) <= Number.MAX_SAFE_INTEGER) snapshot.price = Number(amount);\n const currencies = offers.map((value, n) => value.priceCurrency ?? (specifications[n]!.length && specifications[n]!.every(spec => spec.priceCurrency === specifications[n]![0]!.priceCurrency) ? specifications[n]![0]!.priceCurrency : undefined)).filter(Boolean);\n const currency = facts.currency ?? facts.currencyId ?? facts.price_currency ?? facts.priceCurrency ?? money?.currencyCode ?? (new Set(currencies).size === 1 ? currencies[0] : undefined);\n if (typeof currency === \"string\" && /^[A-Z]{3}$/.test(currency)) snapshot.currency = currency;\n if (money && [facts.currency, facts.currencyId, facts.price_currency, facts.priceCurrency, ...currencies].some(value => value !== undefined && value !== money.currencyCode)) { delete snapshot.price; delete snapshot.currency; }\n const { url, images, rawImages } = links(facts, source_ref);\n if (url) snapshot.url = url; if (images.length) snapshot.image_url = images[0]!;\n if (!Object.keys(identifiers).length && !Object.keys(variant_identifiers).length || typeof name !== \"string\" || snapshot.price === undefined && !images.length) return null;\n if (new TextEncoder().encode(JSON.stringify(snapshot)).length > 8192) return null;\n return { snapshot, ref: crypto.randomUUID(), images, rawImages, url, sku: snapshot.sku as string | undefined, variant: snapshot.variant_id as string | undefined, expires: Date.now() + 900000 };\n}\n\n/** Identifies the same observed source record without retaining a raw response or changing its local correlation reference. */\nfunction entryKey(value: Entry): string {\n const identity = value.snapshot.metadata.provenance.source === \"public_hydration\" && value.snapshot.product_id ? [value.snapshot.product_id, value.snapshot.variant_id, value.snapshot.sku] : [Object.entries(value.snapshot.metadata.identifiers).sort(), Object.entries(value.snapshot.metadata.variant_identifiers).sort()];\n return JSON.stringify([identity, value.snapshot.metadata.provenance.source_ref, value.blocked && !Object.keys(value.snapshot.metadata.identifiers).length ? [value.sku, value.url, value.images, value.ids] : null]);\n}\n\n/** Builds a bounded per-runtime product index and a permission-gated startup XHR bridge. */\nexport function createProductIndex(options: { epoch: () => string | null }): {\n observe(value: unknown, source: string, kind?: string): void; track(xhr: XMLHttpRequest, url: string, method: string): void;\n activate(): void; resolve(root: Element, price?: number, currency?: string, label?: string): ProductMatch; pause(): void; destroy(): void;\n} {\n let records: Entry[] = [], limited = false, pageLimited = false, stopped = false, active: string | null = null, jsonPage = \"\", jsonPageTime = 0;\n const generations = new WeakMap<XMLHttpRequest, number>(), startup: { ref: WeakRef<XMLHttpRequest>; url: string; generation: number }[] = [];\n const listeners = new Set<() => void>();\n const timeout = setTimeout(() => { if (startup.length || listeners.size) limited = true; startup.length = 0; for (const stop of [...listeners]) stop(); listeners.clear(); }, 10000);\n /** Clears transient authorization-bound references while retaining only sanitized public product facts. */\n function pause(): void { active = null; startup.length = 0; for (const stop of [...listeners]) stop(); }\n /** Reads only confirmed product containers, without descending into customer or arbitrary item trees. */\n function observe(value: unknown, source: string, kind = \"catalog_response\"): void {\n const epoch = options.epoch(), source_ref = productSourceURL(source); if (!epoch || stopped || !source_ref) return;\n if (typeof value === \"string\") value = parseProductJSON(value);\n const filename = new URL(source_ref).pathname.split(\"/\").pop() ?? \"\";\n const queue: { value: unknown; product: boolean; depth: number; group?: Entry[\"group\"] }[] = [{ value, product: kind !== \"json_ld\" && /(?:^|[-_.])(?:products?|catalog)(?:[-_.]|$)/i.test(filename), depth: 0 }];\n let visited = 0;\n while (queue.length && visited++ < 512) {\n const item = queue.shift()!; if (item.depth > 5) { limited = true; continue; }\n if (Array.isArray(item.value)) { for (const child of item.value.slice(0, 128)) queue.push({ value: child, product: item.product, depth: item.depth + 1 }); if (item.value.length > 128) limited = true; continue; }\n if (!item.value || typeof item.value !== \"object\") continue;\n const row = item.value as Record<string, unknown>, types = Array.isArray(row[\"@type\"]) ? row[\"@type\"] : [row[\"@type\"]];\n if (types.includes(\"ProductGroup\") && Array.isArray(row.hasVariant)) {\n if (row.hasVariant.length > 16) { limited = true; continue; }\n const { id: groupID, productID: groupProductID, hasVariant, ...group } = row;\n const parent = Object.fromEntries(Object.entries(group).filter(([key]) => !aliases.product_id.test(key) && !aliases.sku.test(key) && !/^(?:url|@id|product[_-]?url)$/i.test(key)));\n for (const child of hasVariant) if (child && typeof child === \"object\") queue.push({ value: { ...parent, ...(child as object), url: links(child as Record<string, unknown>, source_ref).url, productGroupID: row.productGroupID ?? groupProductID ?? groupID, productGroupSKU: row.sku, \"@type\": \"Product\" }, product: true, depth: item.depth + 1, group: { url: links(row, source_ref).url, name: normalized(row.name) } });\n continue;\n }\n const product = types.some(type => [\"Product\", \"IndividualProduct\"].includes(String(type))) || item.product;\n if (product && Object.keys(row).some(key => identifier.test(key))) {\n const variants = Array.isArray(row.variants) ? row.variants : [undefined];\n if (variants.length > 16) { limited = true; continue; }\n if (variants.some(value => value !== undefined && (!value || typeof value !== \"object\" || Array.isArray(value)))) continue;\n for (const variant of variants.slice(0, 16)) {\n const selected = variant && typeof variant === \"object\" ? variant as Record<string, unknown> : undefined;\n let entry = project(row, kind, source_ref, selected);\n if (!entry) {\n const facts = { ...row, ...selected }, evidence = links(facts, source_ref);\n const ids = Object.keys(facts).filter(key => aliases.product_id.test(key)).map(key => id(facts[key])).filter((value): value is string => value !== undefined);\n if (!evidence.sku && !evidence.url && !evidence.images.length && !ids.length) continue;\n entry = { ...evidence, ids, variant: id(selected?.variant_id ?? selected?.variantId ?? selected?.id ?? row.variant_id ?? row.variantId), ref: crypto.randomUUID(), blocked: true, expires: Date.now() + 900000, snapshot: { metadata: { resolution: \"ambiguous\", identifiers: {}, variant_identifiers: {}, attributes: {}, provenance: { source: kind, source_ref, match: \"unresolved\" }, limited: false } } };\n }\n if (entry.snapshot.metadata.limited) limited = true;\n entry.group = item.group;\n const signature = entryKey(entry);\n const previous = records.find(existing => entryKey(existing) === signature);\n if ([\"json_ld\", \"public_hydration\"].includes(kind) && previous && !entry.blocked) {\n const conflict = previous.blocked || [\"price\", \"currency\", \"url\"].some(key => previous.snapshot[key] !== undefined && entry!.snapshot[key] !== undefined && previous.snapshot[key] !== entry!.snapshot[key]) || [\"identifiers\", \"variant_identifiers\"].some(key => Object.entries(previous.snapshot.metadata[key as \"identifiers\"]).some(([name, value]) => entry!.snapshot.metadata[key as \"identifiers\"][name] !== undefined && entry!.snapshot.metadata[key as \"identifiers\"][name] !== value));\n const strong = previous.url ? previous : entry, weak = strong === entry ? previous : entry;\n entry.snapshot = { ...weak.snapshot, ...strong.snapshot, metadata: { ...strong.snapshot.metadata, identifiers: { ...weak.snapshot.metadata.identifiers, ...strong.snapshot.metadata.identifiers }, variant_identifiers: { ...weak.snapshot.metadata.variant_identifiers, ...strong.snapshot.metadata.variant_identifiers }, attributes: { ...weak.snapshot.metadata.attributes, ...strong.snapshot.metadata.attributes } } };\n entry.url = strong.url ?? weak.url; entry.group = strong.group ?? weak.group;\n entry.images = [...new Set([...strong.images, ...weak.images])];\n entry.rawImages = strong.rawImages && weak.rawImages ? [...new Set([...strong.rawImages, ...weak.rawImages])] : undefined;\n if (entry.images.length > 16 || (entry.rawImages?.length ?? 0) > 16 || Object.keys(entry.snapshot.metadata.attributes).length > 32 || Object.keys(entry.snapshot.metadata.identifiers).length > 32 || Object.keys(entry.snapshot.metadata.variant_identifiers).length > 32) limited = true;\n if (conflict || limited) { entry.blocked = true; entry.snapshot.metadata.resolution = \"ambiguous\"; }\n }\n entry.ref = previous?.ref ?? entry.ref;\n records = records.filter(existing => entryKey(existing) !== signature && existing.expires > Date.now());\n if (records.length >= 128) { limited = true; continue; } records.push(entry);\n }\n }\n for (const key of [\"products\", \"product\", \"catalog\", \"data\", \"@graph\", \"items\", \"itemListElement\", \"item\", \"mainEntity\"]) if (row[key] !== undefined && (key !== \"items\" || product)) queue.push({ value: row[key], product: product || [\"products\", \"product\", \"catalog\"].includes(key), depth: item.depth + 1 });\n }\n if (queue.length) limited = true;\n }\n /** Reads JSON-only public document data, binding hydration candidates to independent current-page product evidence. */\n function readPage(): void {\n /** Refuses incomplete public sources on every access instead of caching a usable partial prefix. */\n function incomplete(): void { pageLimited = true; jsonPage = \"\"; }\n const currentDocument = documentURL(), source = currentDocument && productSourceURL(currentDocument), canonical = publicURL(document.querySelector('link[rel=\"canonical\"]')?.getAttribute(\"href\")) ?? source;\n if (!source || !canonical) return;\n const native = nativeForms(); if (!native) { incomplete(); return; }\n const scripts: HTMLScriptElement[] = []; let work = 0, hydrationWork = 0, schemaCount = 0, hydrationCount = 0, hydrationLimited = false, hash = 2166136261, second = 5381;\n for (const script of document.scripts) {\n if (script.src || script.type === \"application/json\" && privateKey.test(script.id)) continue;\n const text = script.textContent ?? \"\";\n if (script.type !== \"application/ld+json\" && script.type !== \"application/json\" && script.id !== \"__NEXT_DATA__\" && !text.slice(0, 128).includes(\"self.__next_f\")) continue;\n if (script.type === \"application/ld+json\") {\n if (++schemaCount > 256 || text.length > 262144 || (work += new TextEncoder().encode(text).length) > 1048576) { incomplete(); return; }\n } else if (++hydrationCount > 256 || hydrationLimited || text.length > 1048576 - hydrationWork || (hydrationWork += new TextEncoder().encode(text).length) > 1048576) { hydrationLimited = true; continue; }\n scripts.push(script);\n for (let n = 0; n < text.length; n++) { const code = text.charCodeAt(n); hash = Math.imul(hash ^ code, 16777619) >>> 0; second = (Math.imul(second, 33) ^ code) >>> 0; }\n }\n const signature = [source, canonical, document.querySelector(\"h1\")?.textContent, document.readyState, scripts.length, hydrationLimited, hash, second, JSON.stringify(native.map(({ product, variant }) => [product, variant]))].join(\":\");\n if (jsonPage === signature && Date.now() - jsonPageTime < 900000) return; pageLimited = false; jsonPage = signature; jsonPageTime = Date.now();\n const previousRefs = new Map(records.filter(entry => entry.expires > Date.now()).map(entry => [entryKey(entry), entry.ref]));\n records = records.filter(entry => ![\"json_ld\", \"public_hydration\"].includes(entry.snapshot.metadata.provenance.source) || entry.snapshot.metadata.provenance.source_ref !== source);\n const schemas: Record<string, unknown>[] = [], roots: unknown[] = [], chunks: string[] = [], variantSources: { rows: Record<string, unknown>[]; parent: string }[] = [];\n let bytes = 0, indexed: unknown, indexedCount = 0;\n for (const script of scripts) {\n const text = script.textContent ?? \"\";\n if (script.type === \"application/ld+json\") {\n if (new TextEncoder().encode(text).length > 262144) { incomplete(); return; }\n const pending: unknown[] = [parseProductJSON(text)];\n for (let n = 0; pending.length && n < 256; n++) {\n const value = pending.shift();\n if (Array.isArray(value)) { if (value.length > 64) { incomplete(); return; } pending.push(...value); continue; }\n if (!value || typeof value !== \"object\") continue;\n const row = value as Record<string, unknown>, types = Array.isArray(row[\"@type\"]) ? row[\"@type\"] : [row[\"@type\"]];\n if (types.some(type => [\"Product\", \"ProductGroup\", \"IndividualProduct\"].includes(String(type)))) schemas.push(row);\n for (const key of [\"@graph\", \"mainEntity\", \"itemListElement\", \"item\"]) if (row[key]) pending.push(row[key]);\n }\n if (pending.length) { incomplete(); return; }\n } else if (hydrationLimited) continue;\n else if (script.type === \"application/json\" && script.id === \"__NUXT_DATA__\") {\n bytes += new TextEncoder().encode(text).length; if (++indexedCount > 1) hydrationLimited = true;\n try { indexed = JSON.parse(text); } catch { hydrationLimited = true; }\n } else if (script.type === \"application/json\" && script.id !== \"__NEXT_DATA__\") {\n bytes += new TextEncoder().encode(text).length; const parsed = parseProductJSON(text), variants = Array.isArray(parsed) ? parsed : parsed && typeof parsed === \"object\" ? (parsed as Record<string, unknown>).variants : undefined;\n if (Array.isArray(variants) && variants.length <= 16 && variants.every(row => row && typeof row === \"object\" && !Array.isArray(row) && id(row.id))) {\n const root = parsed && !Array.isArray(parsed) && typeof parsed === \"object\" && (parsed as Record<string, unknown>).handle === new URL(canonical).pathname.split(\"/\").pop() ? parsed as Record<string, unknown> : undefined;\n const declared = root ? [...new Set(Object.entries(root).filter(([key]) => aliases.product_id.test(key)).map(([, value]) => id(value)).filter((value): value is string => value !== undefined))] : [];\n if (declared.length > 1) { pageLimited = true; continue; }\n const parentIDs = variants.map(row => id(row.featured_image?.product_id)), parent = root ? declared[0] : parentIDs.every(value => value && value === parentIDs[0]) ? parentIDs[0] : undefined;\n if (parent) variantSources.push({ rows: variants, parent });\n }\n } else if (script.id === \"__NEXT_DATA__\" && text.length <= 1048576) { bytes += new TextEncoder().encode(text).length; roots.push(parseProductJSON(text, 1048576)); }\n else if (text.includes(\"self.__next_f.push\")) for (const match of text.length <= 1048576 ? text.matchAll(/self\\.__next_f\\.push\\(\\[1\\s*,\\s*(\"(?:[^\"\\\\]|\\\\.)*\")\\s*\\]\\)/g) : []) {\n try { const chunk: unknown = JSON.parse(match[1]!); if (typeof chunk === \"string\") { bytes += new TextEncoder().encode(chunk).length; if (bytes <= 1048576) chunks.push(chunk); } } catch { /* Non-JSON/executable script syntax is never evaluated. */ }\n }\n }\n if (bytes > 1048576) hydrationLimited = true;\n if (!hydrationLimited) roots.push(...flightRows(chunks.join(\"\"))); else roots.length = 0;\n const title = normalized(document.querySelector(\"h1\")?.textContent), hydrated: { row: Record<string, unknown>; schema?: Record<string, unknown>; url?: string; structured: boolean }[] = [], typedVariants = new Map<string, Record<string, unknown>[]>();\n const anchors = [...document.querySelectorAll(\"a[href]\")].slice(0, 512).map(node => publicURL(node.getAttribute(\"href\"))).filter((value): value is string => !!value);\n const pending = roots.map(value => ({ value, product: false, depth: 0 })); let visited = 0;\n while (pending.length && visited++ < 8192) {\n const item = pending.shift()!;\n if (Array.isArray(item.value)) { if (item.value.length > 128) { hydrationLimited = true; continue; } for (const value of item.value) if (value && typeof value === \"object\") pending.push({ value, product: item.product, depth: item.depth + 1 }); continue; }\n if (!item.value || typeof item.value !== \"object\") continue;\n const original = item.value as Record<string, unknown>, core = original.product;\n const row = core && typeof core === \"object\" && !Array.isArray(core) && Array.isArray(original.variants) ? { ...core as Record<string, unknown>, variants: original.variants } : original, name = normalized(row.name ?? row.title ?? row.product_name);\n const typedID = id(row.id); if (typedID && /^gid:\\/\\/shopify\\/ProductVariant\\/\\d+$/.test(typedID)) typedVariants.set(typedID, [...typedVariants.get(typedID) ?? [], row]);\n const schema = schemas.filter(value => normalized(value.name) === name && (links(value, source).url === canonical || name === title));\n const segments = new URL(canonical).pathname.split(\"/\").filter(Boolean).map(decodeURIComponent);\n const slugValue = row.slug ?? row.handle ?? (schema.length === 1 && name === title ? row.url : undefined);\n const slug = typeof slugValue === \"string\" && /^[a-z0-9-]{1,160}$/.test(slugValue) && segments[segments.length - 1] === slugValue;\n const productLinks = typeof row.handle === \"string\" && /^[a-z0-9-]{1,160}$/.test(row.handle) && /^gid:\\/\\/shopify\\/Product\\/\\d+$/.test(typedID ?? \"\") ? [...new Set(anchors.filter(value => new URL(value).origin === location.origin && new URL(value).pathname.endsWith(\"/products/\" + row.handle)))] : [];\n const declaredID = Object.entries(row).some(([key, value]) => /^(?:id|product[_-]?id|sku)$/i.test(key) && id(value) !== undefined && segments.includes(id(value)!));\n const publicFacts = [row.price, row.priceValue, row.sale_price, row.image, row.image_url].some(value => value !== undefined) || Array.isArray(row.variants) && row.variants.length > 0;\n if (name && publicFacts && (slug && (row.handle === undefined || schema.length === 1) || productLinks.length === 1 || links(row, source).url === canonical || item.product && declaredID && schema.length === 1 && name === title) &&\n (Object.keys(row).some(key => identifier.test(key)) || Array.isArray(row.variants))) hydrated.push({ row, schema: schema.length === 1 ? schema[0] : undefined, url: productLinks.length === 1 ? productLinks[0] : undefined, structured: row !== original || /^gid:\\/\\/shopify\\/Product\\/\\d+$/.test(typedID ?? \"\") });\n for (const [key, value] of Object.entries(original)) if (!privateKey.test(key) && value && typeof value === \"object\") pending.push({ value, product: item.product || /product/i.test(key), depth: item.depth + 1 });\n }\n const consumed = new Set<Record<string, unknown>>();\n const schemaVariants = schemas.flatMap(row => Array.isArray(row.hasVariant) ? row.hasVariant : [row]).filter((row): row is Record<string, unknown> => !!row && typeof row === \"object\" && !Array.isArray(row));\n if (!pending.length && !hydrationLimited && bytes <= 1048576) for (const item of hydrated) {\n const variantID = id(item.row.variantId), concrete = variantID && /^gid:\\/\\/shopify\\/ProductVariant\\/\\d+$/.test(variantID) ? typedVariants.get(variantID) : undefined;\n const concreteFacts = concrete?.map(row => JSON.stringify([row.price, row.image, row.sku]));\n if (concreteFacts && new Set(concreteFacts).size !== 1) { pageLimited = true; continue; }\n const row = concrete?.length ? { ...item.row, variants: [concrete[0]] } : item.row;\n const safe = Object.fromEntries(Object.entries(row).filter(([key]) => (publicField.test(key) || identifier.test(key)) && !privateKey.test(key)));\n if (typeof safe.price === \"string\" && /^\\$[\\da-f]+:/i.test(safe.price)) delete safe.price;\n if (item.structured && (!safe.price || typeof safe.price !== \"object\")) delete safe.price;\n if (![...links(safe, source).images].length) { delete safe.image; delete safe.images; delete safe.image_url; delete safe.imageUrl; }\n if (Array.isArray(safe.variants)) safe.variants = safe.variants.map(value => {\n if (!value || typeof value !== \"object\") return null;\n const variant = Object.fromEntries(Object.entries(value).filter(([key]) => (publicField.test(key) || identifier.test(key)) && !privateKey.test(key))), money = variant.price as Record<string, unknown> | undefined;\n const facts = schemaVariants.filter(row => sameVariant(id(variant.id ?? variant.variantId), links(row, source).url && new URL(links(row, source).url!).searchParams.get(\"variant\"))).map(row => project(row, \"json_ld\", source)?.snapshot).filter(Boolean);\n if (item.structured && (!money || typeof money !== \"object\" || !/^[A-Z]{3}$/.test(String(money.currencyCode))) || money && typeof money === \"object\" && facts.some(fact => fact!.price !== undefined && Number(money.amount) !== fact!.price || fact!.currency !== undefined && money.currencyCode !== fact!.currency)) for (const key of [\"price\", \"currency\", \"priceCurrency\", \"price_currency\", \"offers\"]) variant[key] = undefined;\n return variant;\n });\n const schema = { ...item.schema };\n if (item.row.special_price !== undefined) {\n const declared = item.schema && project(item.schema, \"json_ld\", source)?.snapshot; delete safe.price;\n if (declared?.price !== undefined && declared.currency && Number(item.row.special_price) === declared.price) safe.sale_price = declared.price;\n else for (const key of [\"price\", \"offers\", \"currency\", \"currencyId\", \"priceCurrency\", \"price_currency\"]) { delete schema[key]; delete safe[key]; }\n }\n if (id(safe.id) && schema.productID !== undefined && id(schema.productID) !== id(safe.id)) { schema.schema_productID = schema.productID; delete schema.productID; }\n const combined = { ...schema, ...safe, \"@type\": \"Product\", name: safe.name ?? safe.title ?? safe.product_name, url: links(safe, source).url ?? item.url ?? canonical };\n observe({ products: [combined] }, source, \"public_hydration\"); if (item.schema) consumed.add(item.schema);\n }\n for (const row of schemas) if (!consumed.has(row)) observe(row, source, \"json_ld\");\n if (!hydrationLimited && source === canonical) for (const row of indexedProducts(indexed, source, title, schemas)) {\n observe({ products: [row] }, source, \"public_hydration\");\n records = records.filter(entry => entry.snapshot.metadata.provenance.source !== \"json_ld\" || entry.snapshot.metadata.provenance.source_ref !== source || entry.sku !== row.schema_productSKU || normalized(entry.snapshot.name) !== title || entry.url && entry.url !== source);\n }\n if (!pending.length && !hydrationLimited) for (const { rows: variants, parent: parentID } of variantSources) {\n const bindings = native.filter(form => form.product && variants.some(row => sameVariant(id(row.id), form.variant)));\n const parents = [...new Set(bindings.map(form => form.product!))]; if (!parents.length) continue;\n if (parents.length !== 1 || parents[0] !== parentID) { pageLimited = true; continue; }\n for (const entry of records.filter(value => [\"json_ld\", \"public_hydration\"].includes(value.snapshot.metadata.provenance.source) && value.snapshot.metadata.provenance.source_ref === source)) {\n const selector = entry.url && new URL(entry.url).searchParams.get(\"variant\"), matches = variants.filter(row => sameVariant(id(row.id), selector));\n if (!selector || matches.length !== 1 || !entry.url || new URL(entry.url).origin + new URL(entry.url).pathname !== new URL(canonical).origin + new URL(canonical).pathname) continue;\n const row = matches[0]!, image = row.featured_image as Record<string, unknown> | undefined, parent = id(image?.product_id);\n if (parent && parent !== parents[0] || row.sku !== undefined && id(row.sku) !== entry.sku || entry.snapshot.product_id && entry.snapshot.product_id !== parents[0]) { pageLimited = true; continue; }\n entry.snapshot.product_id = parents[0]!; entry.snapshot.variant_id = id(row.id)!; entry.variant = id(row.id);\n entry.snapshot.metadata.identifiers.product_id = parents[0]!; entry.snapshot.metadata.variant_identifiers.variant_id = id(row.id)!;\n entry.snapshot.metadata.provenance.source = \"public_hydration\";\n }\n }\n for (const entry of records) entry.ref = previousRefs.get(entryKey(entry)) ?? entry.ref;\n }\n /** Checks deferred and live XHR reads through the same current-permission and request-generation boundary. */\n function consume(candidate: typeof startup[number]): void {\n const xhr = candidate.ref.deref(); if (!xhr || stopped || !active || options.epoch() !== active || generations.get(xhr) !== candidate.generation) return;\n if (xhr.readyState !== 4) return;\n try { if (xhr.status >= 200 && xhr.status < 300 && publicURL(xhr.responseURL) === candidate.url && /json/i.test(xhr.getResponseHeader(\"content-type\") ?? \"\")) observe(xhr.responseType === \"json\" ? xhr.response : xhr.responseText, candidate.url); } catch { /* Detached/unsupported response types stay unavailable. */ }\n }\n return {\n observe,\n /** Stores only safe request metadata and weak references before server authorization. */\n track(xhr, input, method): void {\n const generation = (generations.get(xhr) ?? 0) + 1; generations.set(xhr, generation);\n const url = productSourceURL(input); if (active || stopped || !url || method.toUpperCase() !== \"GET\" || !/\\/(?:products?|catalog)\\.json$/i.test(new URL(url).pathname) || typeof WeakRef === \"undefined\") return;\n if (startup.length >= 32) { limited = true; return; }\n startup.push({ ref: new WeakRef(xhr), url, generation });\n },\n /** Activates after both gates, reading only still-live completed or subsequently completed XHRs. */\n activate(): void {\n const epoch = options.epoch(); if (!epoch || stopped || active) return; active = epoch;\n for (const candidate of startup.splice(0)) {\n const xhr = candidate.ref.deref(); if (!xhr) { limited = true; continue; }\n consume(candidate);\n if (xhr.readyState !== 4) {\n /** Releases one deferred listener after completion, timeout or permission revocation. */\n const stop = () => { candidate.ref.deref()?.removeEventListener(\"loadend\", complete); listeners.delete(stop); };\n /** Rechecks authorization before accessing the original completed response. */\n const complete = () => { consume(candidate); stop(); };\n listeners.add(stop); xhr.addEventListener(\"loadend\", complete, { once: true });\n }\n }\n },\n /** Resolves the actual target before considering current-page context; an off-page link never inherits its ancestor product. */\n resolve(root, observedPrice, observedCurrency, observedLabel): ProductMatch {\n const source_ref = location.origin + \"/\";\n const empty = (resolution: \"unresolved\" | \"ambiguous\"): ProductMatch => ({ product_ref: crypto.randomUUID(), snapshot: { metadata: { resolution, identifiers: {}, variant_identifiers: {}, attributes: {}, provenance: { source: \"dom\", source_ref, match: \"unresolved\" }, limited: limited || pageLimited } } });\n if (stopped || !options.epoch() || root.closest(\"header,footer,[data-sagepilot-popup]\")) return empty(\"unresolved\");\n readPage(); records = records.filter(entry => entry.expires > Date.now()); if (limited || pageLimited) return empty(\"ambiguous\");\n const anchor = root.closest(\"a[href]\"), targetURL = anchor ? publicURL(anchor.getAttribute(\"href\")) : undefined;\n if (anchor && !targetURL) return empty(\"unresolved\");\n const current = documentURL(), canonical = publicURL(document.querySelector('link[rel=\"canonical\"]')?.getAttribute(\"href\")) ?? current;\n if (!current) return empty(\"unresolved\");\n const samePage = current && canonical && new URL(current).origin + new URL(current).pathname === new URL(canonical).origin + new URL(canonical).pathname;\n const currentSelector = current ? new URL(current).searchParams.get(\"variant\") ?? new URL(current).searchParams.get(\"variant_id\") : undefined;\n const clickedImage = /^img$/i.test(root.tagName) && root.getClientRects().length ? publicURL((root as HTMLImageElement).currentSrc || root.getAttribute(\"src\"), location.href, true) : undefined;\n const literalImage = clickedImage ? new URL((root as HTMLImageElement).currentSrc || root.getAttribute(\"src\")!, location.href).href : undefined;\n const action = commerceAction(root.getAttribute(\"aria-label\") ?? (root as HTMLElement).innerText ?? root.textContent ?? \"\");\n const primary = /^h1$/i.test(root.tagName) || (root.matches(\"button,[role='button']\") && /^(?:add(?: to (?:cart|bag|basket))?|buy(?: now)?|rent(?: now)?)[.!]?$/i.test(action));\n if (!anchor && primary && !samePage) return empty(\"unresolved\");\n const form = (root as HTMLButtonElement).form ?? root.closest(\"form\"), privateForm = form && [...form.querySelectorAll(\"input:not([type='hidden']),textarea,select\")].some(node => node.tagName === \"TEXTAREA\" || !/^(?:quantity|qty|variant(?:_id)?|option(?:\\[.*\\])?|attribute_[A-Za-z0-9_]+)$/i.test(node.getAttribute(\"name\") ?? \"\"));\n if (privateForm) return empty(\"unresolved\");\n let pageContext = !anchor && primary && samePage && !privateForm && !root.closest(\"dialog,[role='dialog']\");\n const images = new Set<string>(), urls = new Set<string>(), skus = new Set<string>(), variants = new Set<string>(), ids = new Set<string>();\n const bound = records.filter(entry => entry.snapshot.metadata.provenance.source_ref === current && entry.url && new URL(entry.url).origin + new URL(entry.url).pathname === new URL(canonical!).origin + new URL(canonical!).pathname);\n const native = nativeForms(), owner = (root as HTMLButtonElement).form ?? root.closest(\"form\"); if (!native) return empty(\"ambiguous\");\n const own = native.find(value => value.form === owner);\n const ownerAction = owner && publicURL(owner.getAttribute(\"action\"));\n if (primary && ownerAction && new URL(ownerAction).origin === location.origin && /\\/cart\\/add\\/?$/.test(new URL(ownerAction).pathname) && !own) return empty(\"ambiguous\");\n const forms = native.filter(form => bound.some(entry => sameVariant(entry.variant, form.variant) || sameVariant(entry.url && new URL(entry.url).searchParams.get(\"variant\"), form.variant)));\n if (primary && own && !forms.includes(own)) return empty(\"unresolved\");\n const checked = [...document.querySelectorAll('input[type=\"radio\"]:checked')]; if (checked.length > 32) return empty(\"ambiguous\");\n const controls = checked.map(node => id((node as HTMLInputElement).value)).filter(value => value && bound.some(entry => entry.variant === value));\n const selections = [...new Set([...(own ? forms.filter(value => value === own) : forms).map(form => form.variant), ...controls])];\n const nativeConflict = selections.length && (selections.length !== 1 || currentSelector && !sameVariant(selections[0], currentSelector));\n const nativeVariant = samePage && selections.length === 1 && (!currentSelector || sameVariant(selections[0], currentSelector)) ? selections[0] : undefined;\n let exactVariant = id(root.getAttribute(\"data-variant-id\") ?? root.getAttribute(\"data-variant_id\") ?? anchor?.getAttribute(\"data-variant-id\"));\n const exactProduct = id(root.getAttribute(\"data-product-id\") ?? root.getAttribute(\"data-product_id\") ?? anchor?.getAttribute(\"data-product-id\"));\n const exactSKU = id(root.getAttribute(\"data-sku\") ?? anchor?.getAttribute(\"data-sku\"));\n let card: Element | null = root, direct: Element | null = null;\n for (let depth = 0; card && depth < 6 && card !== document.body; depth++, card = card.parentElement) {\n const nodes: Element[] = [card], walker = document.createTreeWalker(card, NodeFilter.SHOW_ELEMENT); let next: Node | null;\n while ((next = walker.nextNode()) && nodes.length <= 64) nodes.push(next as Element);\n if (nodes.length > 64) break;\n if (!direct && card.matches(\"[data-product-id],[data-variant-id],[data-product_id],[data-variant_id]\")) direct = card;\n for (const node of nodes) {\n const image = publicURL(node.getAttribute(\"src\") ?? undefined, location.href, true); if (image) images.add(image);\n for (const match of String(getComputedStyle(node).backgroundImage ?? \"\").matchAll(/url\\([\"']?([^\"')]+)[\"']?\\)/g)) { const value = publicURL(match[1], location.href, true); if (value) images.add(value); }\n const url = publicURL(node.getAttribute(\"href\") ?? undefined); if (url) urls.add(url);\n const sku = id(node.getAttribute(\"data-sku\") ?? (node.getAttribute(\"itemprop\") === \"sku\" ? node.getAttribute(\"content\") : null)); if (sku) skus.add(sku);\n const variant = id(node.getAttribute(\"data-variant-id\") ?? node.getAttribute(\"data-variant_id\")); if (variant) variants.add(variant);\n const product = id(node.getAttribute(\"data-product-id\") ?? node.getAttribute(\"data-product_id\") ?? (node.getAttribute(\"itemprop\") === \"productID\" ? node.getAttribute(\"content\") : null)); if (product) ids.add(product);\n }\n if (targetURL || images.size && urls.size) break;\n }\n const desired = targetURL ?? (urls.size === 1 ? [...urls][0] : undefined);\n if (primary && desired && new URL(desired).origin + new URL(desired).pathname !== new URL(canonical!).origin + new URL(canonical!).pathname) pageContext = false;\n if (pageContext && nativeConflict) return empty(\"ambiguous\"); exactVariant ??= pageContext ? nativeVariant : undefined;\n const labelCandidate = pageContext && current === canonical && records.some(entry => entry.snapshot.product_id === undefined && entry.snapshot.metadata.provenance.source === \"json_ld\" && entry.snapshot.metadata.provenance.source_ref === current && entry.url === current && entry.sku && new URL(current).pathname.split(\"/\").map(decodeURIComponent).includes(entry.sku));\n const labeled = labelCandidate ? labeledProductID() : undefined, productLabel = labeled && new URL(current).pathname.split(\"/\").map(decodeURIComponent).includes(labeled) ? labeled : undefined;\n if (exactVariant) { variants.clear(); variants.add(exactVariant); } if (exactProduct) { ids.clear(); ids.add(exactProduct); } if (exactSKU) { skus.clear(); skus.add(exactSKU); }\n const sharedImages = new Set([...images].filter(value => records.filter(entry => entry.images.includes(value)).length > 1));\n const pageSchema = records.filter(entry => entry.snapshot.metadata.provenance.source === \"json_ld\" && entry.snapshot.metadata.provenance.source_ref === current);\n const uniqueLiteral = literalImage && pageSchema.every(entry => entry.rawImages !== undefined) && pageSchema.filter(entry => entry.rawImages?.includes(literalImage)).length === 1;\n const matches: { entry: Entry; match: string; rank: number; image?: string }[] = [];\n for (const entry of records) {\n if (pageContext && [\"json_ld\", \"public_hydration\"].includes(entry.snapshot.metadata.provenance.source) && entry.snapshot.metadata.provenance.source_ref !== current) continue;\n const declaredVariantURL = entry.url ? new URL(entry.url).searchParams.get(\"variant\") ?? new URL(entry.url).searchParams.get(\"variant_id\") : undefined;\n const labelMatch = productLabel && entry.sku === productLabel && entry.url === current && entry.snapshot.metadata.provenance.source === \"json_ld\";\n if (labelMatch && entry.snapshot.product_id !== undefined && entry.snapshot.product_id !== productLabel) return empty(\"ambiguous\");\n if (exactVariant && !sameVariant(entry.variant ?? declaredVariantURL, exactVariant)) continue;\n const query = desired ? new URL(desired).searchParams : current ? new URL(current).searchParams : null;\n const selected = query?.get(\"variant\") ?? query?.get(\"variant_id\"), variantValues = Object.values(entry.snapshot.metadata.variant_identifiers);\n if (pageContext && currentSelector && ![entry.variant, entry.sku, declaredVariantURL, ...variantValues].some(value => sameVariant(value, currentSelector))) continue;\n const exactURL = !!desired && (entry.url === desired || !!selected && entry.url?.split(\"?\")[0] === desired.split(\"?\")[0] && [entry.variant, entry.sku, ...variantValues].some(value => sameVariant(value, selected)));\n const image = entry.images.find(value => images.has(value) && !sharedImages.has(value)), token = entry.sku && new RegExp(`(?:^|[^A-Za-z0-9])${entry.sku.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}(?:$|[^A-Za-z0-9])`);\n const skuImage = token ? [...images].find(value => !sharedImages.has(value) && token.test(new URL(value).pathname)) : undefined;\n const title = normalized(entry.snapshot.name), titleOnPage = [...document.querySelectorAll(\"h1\")].slice(0, 8).some(node => node.getClientRects().length && normalized(node.textContent) === title);\n const groupOnPage = entry.group?.url === canonical && samePage && entry.snapshot.metadata.provenance.source_ref === current && [...document.querySelectorAll(\"h1\")].slice(0, 8).some(node => node.getClientRects().length && normalized(node.textContent) === entry.group?.name);\n const directImage = uniqueLiteral && !targetURL && samePage && pageSchema.includes(entry) && entry.rawImages?.includes(literalImage!) && !sharedImages.has(clickedImage!) && (!entry.url || entry.url.split(\"?\")[0] === canonical!.split(\"?\")[0]) && (!currentSelector || [entry.variant, entry.sku, declaredVariantURL, ...variantValues].includes(currentSelector));\n const corroborated = title && title === normalized(observedLabel) && observedPrice !== undefined && entry.snapshot.price === observedPrice;\n let match = exactURL ? \"exact_url\" : !targetURL && (entry.variant && variants.has(entry.variant) || exactVariant && sameVariant(entry.variant ?? declaredVariantURL, exactVariant)) ? \"exact_variant\" : labelMatch || !targetURL && typeof entry.snapshot.product_id === \"string\" && ids.has(entry.snapshot.product_id) ? \"direct_id\"\n : !targetURL && entry.sku && skus.has(entry.sku) ? \"exact_sku\" : skuImage && (!targetURL || !entry.url) ? \"exact_sku\" : directImage || image && (corroborated || entry.blocked || entry.url === current && titleOnPage || groupOnPage) && (!targetURL || !entry.url) ? \"exact_image\" : null;\n if (!match && pageContext && titleOnPage && (entry.snapshot.metadata.provenance.source === \"catalog_response\" || entry.snapshot.metadata.provenance.source_ref === current) && (entry.url === current || entry.url === canonical) && (!selected || [entry.variant, entry.sku, ...variantValues].some(value => sameVariant(value, selected)))) match = \"exact_url\";\n if (match) matches.push({ entry, match, rank: exactURL ? 3 : match === \"exact_url\" ? 1 : 2, image: skuImage ?? image });\n }\n const rank = Math.max(0, ...matches.map(value => value.rank)), best = matches.filter(value => value.rank === rank);\n const directSelector = direct && id(direct.getAttribute(\"data-variant-id\") ?? direct.getAttribute(\"data-variant_id\") ?? direct.getAttribute(\"data-sku\"));\n if (!best.length && direct && (!anchor || direct === anchor) && !/^h1$/i.test(root.tagName) && (!primary || samePage && (!currentSelector || currentSelector === directSelector)) && !root.closest(\"dialog,[role='dialog']\")) {\n const identifiers: Record<string, string> = {}, variant_identifiers: Record<string, string> = {};\n const product = id(direct.getAttribute(\"data-product-id\") ?? direct.getAttribute(\"data-product_id\")), variant = id(direct.getAttribute(\"data-variant-id\") ?? direct.getAttribute(\"data-variant_id\"));\n if (product) identifiers.product_id = product; if (variant) variant_identifiers.variant_id = variant;\n if (product || variant) {\n const snapshot: ProductSnapshot = { ...(product ? { product_id: product } : {}), ...(variant ? { variant_id: variant } : {}), metadata: { resolution: \"resolved\", identifiers, variant_identifiers, attributes: {}, provenance: { source: \"dom_attribute\", source_ref, match: \"direct_id\" }, limited: false } };\n const price = direct.getAttribute(\"data-price\"), currency = direct.getAttribute(\"data-currency\");\n if (price && /^\\d{1,8}(?:\\.\\d{1,4})?$/.test(price)) snapshot.price = Number(price);\n if (currency && /^[A-Z]{3}$/.test(currency)) snapshot.currency = currency;\n const old = records.find(value => value.snapshot.product_id === product && value.snapshot.variant_id === variant && value.snapshot.metadata.provenance.source === \"dom_attribute\");\n const entry: Entry = old ?? { snapshot, ref: crypto.randomUUID(), images: [], expires: Date.now() + 900000 }; if (!old && records.length < 128) records.push(entry);\n return { snapshot, product_ref: entry.ref };\n }\n }\n if (best.length !== 1 || best[0]?.entry.blocked) return empty(best.length || sharedImages.size ? \"ambiguous\" : \"unresolved\");\n const result = JSON.parse(JSON.stringify(best[0]!.entry.snapshot)) as ProductSnapshot;\n if (productLabel && best[0]!.entry.sku === productLabel && best[0]!.entry.url === current && best[0]!.entry.snapshot.metadata.provenance.source === \"json_ld\") { result.product_id = productLabel; result.metadata.identifiers.product_id = productLabel; result.metadata.provenance.source = \"dom\"; }\n if (exactVariant && !result.variant_id) { result.variant_id = exactVariant; result.metadata.variant_identifiers.variant_id = exactVariant; }\n const chosen = best[0]!.entry, groupID = chosen.snapshot.metadata.identifiers.productGroupID;\n if (pageContext && groupID && chosen.group?.url === canonical && chosen.snapshot.metadata.provenance.source_ref === current) {\n const selected = chosen.url && (new URL(chosen.url).searchParams.get(\"variant\") ?? new URL(chosen.url).searchParams.get(\"variant_id\")), parents = [...new Set(forms.filter(form => form.product && sameVariant(form.variant, selected)).map(form => form.product!))];\n if (parents.length > 1 || parents[0] === groupID && result.product_id !== undefined && result.product_id !== parents[0]) return empty(\"ambiguous\");\n if (parents[0] === groupID && result.product_id === undefined) { result.product_id = parents[0]!; result.metadata.identifiers.product_id = parents[0]!; result.metadata.provenance.source = \"dom\"; }\n }\n if (typeof result.price === \"number\" && observedPrice !== undefined && Math.abs(result.price - observedPrice) > 1e-9 || result.currency && observedCurrency && result.currency !== observedCurrency) return empty(\"unresolved\");\n if (!result.image_url && best[0]!.image) result.image_url = best[0]!.image!;\n result.metadata.provenance.match = best[0]!.match;\n return new TextEncoder().encode(JSON.stringify(result)).length <= 8192 ? { snapshot: result, product_ref: best[0]!.entry.ref } : empty(\"unresolved\");\n },\n /** Clears every startup weak reference, deferred listener and retained product fact. */\n pause,\n destroy(): void { stopped = true; clearTimeout(timeout); pause(); records = []; }\n };\n}\n","import type { Capture } from \"./network\";\nimport type { Json } from \"./projection\";\nimport type { ProductMatch } from \"./product\";\nimport { commerceAction } from \"./product\";\n\ntype Product = { node: Element; label: string; price: number; currency?: string };\ntype Cart = { node: Element; ref: string; quantity: number };\ntype Pending = { label: string; epoch: string; trigger: string; before: Cart; changed: number; deadline: number; network: number; suppressed: boolean; product: Record<string, Json>; timer: ReturnType<typeof setTimeout> };\nconst imageSelector = \"img[alt],div[alt],[role='img'][aria-label]\";\nconst privateRegion = \"form,input,textarea,select,[contenteditable='true'],[data-sagepilot-popup],[hidden],[aria-hidden='true']\";\n\n/** Reads only a bounded subtree; an oversized or ambiguous region stays unavailable. */\nfunction nodes(root: Element, limit: number): Element[] | null {\n const result = [root], walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);\n let next: Node | null;\n while ((next = walker.nextNode())) { if (result.length >= limit) return null; result.push(next as Element); }\n return result;\n}\n\n/** Reads short displayed fragments without copying arbitrary parent text or input values. */\nfunction text(root: Element): string | null {\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n let result = \"\", next: Node | null, count = 0;\n while ((next = walker.nextNode())) {\n if (++count > 16 || (next.nodeValue?.length ?? 0) > 120) return null;\n const parent = next.parentElement;\n if (parent && (!parent.getClientRects().length || parent.closest(\"[aria-hidden='true']\") || getComputedStyle(parent).visibility === \"hidden\")) continue;\n result += next.nodeValue ?? \"\"; if (result.length > 120) return null;\n }\n return result.trim().replace(/\\s+/g, \" \");\n}\n\n/** Rejects contact-like and personalized labels before hashing; hashes do not make private text safe. */\nfunction label(value: string | null): string | null {\n value = value?.normalize(\"NFKC\") ?? null;\n if (!value || value.length < 3 || value.length > 80 || /\\d[\\d\\s().-]{5,}\\d|@|https?:|\\+\\d|[A-Za-z0-9_-]{24,}|\\b(?:your|my|account|profile|personalized|personalised|customized|customised|monogram|email|phone|address|password|token|customer|name)\\b/i.test(value)) return null;\n return value.trim().toLowerCase().replace(/\\s+/g, \" \");\n}\n\n/** Recognizes a displayed price, retaining currency only when an explicit ISO code is present. */\nfunction price(value: string | null): { price: number; currency?: string } | null {\n const match = value?.match(/^(?:rent at\\s+)?(?:(USD|EUR|GBP|INR|CAD|AUD|JPY)\\s*)?[$€£¥₹]?\\s*(\\d{1,8}(?:[.,]\\d{1,2})?|(?:\\d{1,3}(?:,\\d{3})+|\\d{1,3}(?:,\\d{2})*,\\d{3})(?:\\.\\d{1,2})?)\\s*(USD|EUR|GBP|INR|CAD|AUD|JPY)?(?:\\s*\\/\\s*(?:mo|month))?$/i);\n if (!match || !/[$€£¥₹]|\\b(?:USD|EUR|GBP|INR|CAD|AUD|JPY)\\b/i.test(value!)) return null;\n if (match[1] && match[3] && match[1].toUpperCase() !== match[3].toUpperCase()) return null;\n const amount = Number(/,\\d{3}(?:\\.|$)/.test(match[2]!) ? match[2]!.replace(/,/g, \"\") : match[2]!.replace(\",\", \".\")), currency = match[1] ?? match[3];\n return Number.isFinite(amount) && amount <= Number.MAX_SAFE_INTEGER ? { price: amount, ...(currency ? { currency: currency.toUpperCase() } : {}) } : null;\n}\n\n/** Finds a small unambiguous ordinary card for opaque context and DOM quantity proofs. */\nfunction productAt(target: Element): Product | null {\n let candidate: Element | null = target;\n for (let depth = 0; candidate && depth < 6 && candidate !== document.body; depth++, candidate = candidate.parentElement) {\n if (candidate.closest(privateRegion)) return null;\n const children = nodes(candidate, 64); if (!children) return null;\n if (children.some(node => node.matches(\"input,textarea,select,[contenteditable='true']\"))) return null;\n const images = children.filter(node => node.matches(imageSelector));\n if (images.length > 1) return null;\n if (images.length !== 1) continue;\n const name = label(images[0]!.getAttribute(\"alt\") ?? images[0]!.getAttribute(\"aria-label\"));\n if (!name || !children.some(node => node !== images[0] && !node.childElementCount && node.getClientRects().length &&\n getComputedStyle(node).visibility !== \"hidden\" && label(text(node)) === name)) continue;\n const amounts = children.filter(node => node.matches(\"p,span,[itemprop='price']\") && !node.closest(\"del,s\") && node.getClientRects().length &&\n getComputedStyle(node).visibility !== \"hidden\").map(node => price(text(node))).filter(Boolean);\n if (!amounts.length || new Set(amounts.map(amount => `${amount!.price}:${amount!.currency ?? \"\"}`)).size > 1) continue;\n const siblings = candidate.parentElement?.children;\n if (siblings && siblings.length > 64) return null;\n for (const sibling of siblings ? [...siblings] : []) {\n if (sibling === candidate) continue;\n const entries = nodes(sibling, 64); if (!entries) return null;\n if (entries.some(node => node.matches(imageSelector) && label(node.getAttribute(\"alt\") ?? node.getAttribute(\"aria-label\")) === name)) return null;\n }\n return { node: candidate, label: name, ...amounts[0]! };\n }\n return null;\n}\n\n/** Reads an explicit line quantity; unrelated digits, totals and input values cannot supply it. */\nfunction quantity(product: Product): number | null {\n const values = (nodes(product.node, 64) ?? []).filter(node => (!node.childElementCount || node.matches(\"p\")) &&\n node.getClientRects().length && getComputedStyle(node).visibility !== \"hidden\")\n .map(node => text(node)?.match(/^(?:.*\\s)?(?:quantity|qty)\\s*:\\s*(\\d{1,6})$/i)?.[1]).filter(value => value !== undefined);\n const unique = [...new Set(values)];\n return unique.length === 1 ? Number(unique[0]) : null;\n}\n\n/** Creates a private bounded observer for rendered cart changes; it never reads framework state. */\nexport function createDOMCart(options: { epoch: () => string | null; emit: Capture; networkVersion: () => number;\n productSnapshot?: (target: Element, price?: number, currency?: string, label?: string) => ProductMatch | undefined }): {\n click(target: Element, epoch: string, trigger: string): Record<string, Json> | Promise<Record<string, Json>>; destroy(): void;\n} {\n const regions = new WeakMap<Element, string>(), pending = new Map<string, Pending>();\n let stopped = false;\n /** Locates a positive Cart/Checkout region and counts only unique, fully readable product lines. */\n function cart(wanted: string): Cart | null {\n const markers: Element[] = [], possible = document.querySelectorAll(\"h1,h2,h3,h4,h5,h6,span,[aria-label],aside,[role='dialog']\");\n for (let index = 0; index < Math.min(possible.length, 128); index++) {\n const node = possible[index]!;\n if (!node.childElementCount && /^(?:shopping )?(?:cart|bag)$/i.test(text(node) ?? \"\")) markers.push(node);\n }\n const candidates = new Set<Element>();\n for (const marker of markers.slice(0, 8)) {\n let node = marker.parentElement;\n for (let depth = 0; node && node !== document.body && depth < 6; depth++, node = node.parentElement) {\n const children = nodes(node, 256); if (!children) break;\n if (children.some(child => child.getClientRects().length && getComputedStyle(child).visibility !== \"hidden\" &&\n (child.matches(\"[aria-busy='true'],[role='progressbar']\") || !child.childElementCount && /^(?:loading|updating)[.\\s…]*$/i.test(text(child) ?? \"\")))) break;\n const buttons = children.filter(child => child.matches(\"button,[role='button']\"));\n if (!buttons.some(button => /^(?:proceed to )?checkout$/i.test(text(button) ?? \"\"))) continue;\n if (buttons.some(button => /\\badd\\b.*\\bcart\\b/i.test(text(button) ?? \"\")) || node.closest(\"[hidden],[aria-hidden='true'],[aria-busy='true']\")) break;\n const style = getComputedStyle(node); if (style.display === \"none\" || style.visibility === \"hidden\") break;\n candidates.add(node); break;\n }\n }\n if (candidates.size !== 1) return null;\n const node = [...candidates][0]!, images = (nodes(node, 256) ?? []).filter(child => child.matches(imageSelector));\n if (images.length > 16) return null;\n if (!images.length && !(nodes(node, 256) ?? []).some(child => /^(?:(?:your|the|shopping)\\s+)?(?:cart|bag)\\s+(?:is\\s+)?empty[.!:]?$|^add some products (?:in|to) (?:the|your) (?:cart|bag)\\b/i.test(text(child) ?? \"\"))) return null;\n const seen = new Set<string>(); let count = 0;\n for (const image of images) {\n const product = productAt(image), amount = product ? quantity(product) : null;\n if (!product || !node.contains(product.node) || amount === null || seen.has(product.label)) return null;\n seen.add(product.label); if (product.label === wanted) count = amount;\n }\n let ref = regions.get(node); if (!ref) { ref = crypto.randomUUID(); regions.set(node, ref); }\n return { node, ref, quantity: count };\n }\n /** Disconnects observation whenever no bounded pending click remains. */\n function remove(key: string): void { const item = pending.get(key); if (item) clearTimeout(item.timer); pending.delete(key); if (!pending.size) observer.disconnect(); }\n /** Accepts one settled positive delta with the same region, permission and network snapshot. */\n function finish(key: string): void {\n const item = pending.get(key); if (!item) return;\n let after: Cart | null = null;\n try { after = cart(item.label); } catch { /* A detached or unreadable host DOM cannot establish success. */ }\n remove(key);\n if (stopped || item.suppressed || !item.product.product_ref || options.epoch() !== item.epoch || options.networkVersion() !== item.network ||\n performance.now() > item.deadline + 250 || performance.now() - item.changed < 300 ||\n !after || after.node !== item.before.node || after.quantity <= item.before.quantity) return;\n options.emit(\"interaction\", { action: \"cart_change\", confirmation: \"dom_cart_quantity_increase\", trigger_id: item.trigger,\n cart_region_ref: after.ref, before_quantity: item.before.quantity, after_quantity: after.quantity,\n product: { ...item.product, quantity: after.quantity - item.before.quantity } }, item.epoch, Date.now());\n }\n const observer = new MutationObserver(records => {\n for (const item of pending.values()) if (records.some(record => item.before.node.contains(record.target) || record.target.contains(item.before.node))) item.changed = performance.now();\n });\n return {\n /** Resolves the actual clicked product independently from the stricter cart-outcome reader. */\n click(target, epoch, trigger): Record<string, Json> | Promise<Record<string, Json>> {\n if (stopped) return {};\n const product = productAt(target), before = product ? cart(product.label) : null;\n const match = options.productSnapshot?.(target, before?.node.contains(target) ? undefined : product?.price, product?.currency, product?.label);\n const resolved = match?.snapshot.metadata.resolution === \"resolved\";\n if (!product && !resolved) return {};\n const action = commerceAction((target.getAttribute(\"aria-label\") ?? text(target) ?? \"\").slice(0, 256)).toLowerCase();\n const excluded = /\\b(?:wishlist|compare|address|tag|subscribe|contact)\\b/i.test(action + \" \" + (target.getAttribute(\"title\") ?? \"\").slice(0, 256));\n const add = !excluded && /\\badd\\b.*\\bcart\\b/.test(action), increment = /^(?:\\+|increase(?: quantity)?|increment(?: quantity)?)$/.test(action);\n const intent = resolved && !excluded && target.matches(\"button,[role='button']\") && !target.closest(\"dialog,[role='dialog']\") && /^(?:add|add to (?:cart|bag|basket))$/.test(action);\n const existing = product ? pending.get(product.label) : undefined;\n if (existing) existing.suppressed = true;\n const network = options.networkVersion();\n let watching: Pending | undefined;\n const sameProduct = !resolved || !product || typeof match?.snapshot.name !== \"string\" || label(match.snapshot.name) === product.label;\n if (product && sameProduct && before && !existing && pending.size < 3 && (add || increment && before.node.contains(target))) {\n watching = { label: product.label, epoch, trigger, before, network, changed: performance.now(), deadline: performance.now() + 2000, suppressed: false,\n product: {}, timer: setTimeout(() => finish(product.label), 2000) };\n pending.set(product.label, watching); observer.observe(document.body, { childList: true, characterData: true, subtree: true });\n }\n /** Keeps the same evidence and owner fence for synchronous source matches and legacy hashes. */\n const context = (product_ref: string): Record<string, Json> => {\n const snapshot = match?.snapshot, common = resolved ? snapshot : null;\n const evidence: Record<string, Json> = { product_ref, ...(!resolved && product ? { price: product.price, ...(product.currency ? { currency: product.currency } : {}) } : {}), ...(snapshot ? { snapshot } : {}) };\n for (const key of [\"product_id\", \"variant_id\", \"sku\", \"price\", \"currency\"]) if (common?.[key] !== undefined) evidence[key] = common[key]!;\n const amount = (add || intent) ? target.closest(\"[data-quantity]\")?.getAttribute(\"data-quantity\") : null;\n if (amount && /^\\d{1,8}(?:\\.\\d{1,4})?$/.test(amount)) evidence.quantity = Number(amount);\n if (watching && product && !stopped && options.epoch() === epoch && pending.get(product.label) === watching)\n watching.product = { product_ref, ...(add ? { price: product.price, ...(product.currency ? { currency: product.currency } : {}) } : {}), ...(snapshot ? { snapshot } : {}) };\n return { product: evidence, ...(intent ? { intent: \"add_to_cart\" } : {}) };\n };\n if (resolved) return context(match!.product_ref);\n return crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(location.origin + \"\\n\" + product!.label)).then(digest =>\n context(\"dom_\" + [...new Uint8Array(digest)].slice(0, 16).map(byte => byte.toString(16).padStart(2, \"0\")).join(\"\")));\n },\n /** Fences delayed observations and clears all retained transient product context. */\n destroy(): void { stopped = true; observer.disconnect(); for (const key of [...pending.keys()]) remove(key); }\n };\n}\n","import { routeFor, type Json } from \"./projection\";\nimport type { Capture } from \"./network\";\nimport { createDOMCart } from \"./dom\";\nimport type { ProductMatch } from \"./product\";\n\n/** Captures fingerprinted navigation, structural clicks and verified product-source context. */\nexport function observePage(options: { epoch: () => string | null; emit: Capture; dropped: () => void; networkVersion?: () => number;\n productSnapshot?: (target: Element, price?: number, currency?: string, label?: string) => ProductMatch | undefined }): () => void {\n const originalPush = history.pushState, originalReplace = history.replaceState;\n let stopped = false, previous = \"\", current = \"\", currentPage: string | null = null, pendingClicks = 0, pendingRoutes = 0;\n const roles = new Set([\"button\", \"link\", \"checkbox\", \"radio\", \"textbox\", \"combobox\", \"menuitem\", \"tab\", \"option\", \"switch\", \"listbox\", \"slider\"]);\n const dom = createDOMCart({ epoch: options.epoch, emit: options.emit, networkVersion: options.networkVersion ?? (() => 0), productSnapshot: options.productSnapshot });\n /** Emits a route observation only after a real URL change. */\n function navigation(): void {\n const epoch = options.epoch(), url = location.href;\n if (stopped || !epoch || url === current) return;\n const old = current; current = url; currentPage = null;\n if (pendingRoutes >= 128) { options.dropped(); return; }\n pendingRoutes++;\n const time = Date.now();\n void Promise.all([routeFor(url), old ? routeFor(old) : Promise.resolve(null)]).then(([page, from]) => {\n if (!page || stopped || options.epoch() !== epoch) return;\n if (current === url) currentPage = page;\n previous = from ?? \"\";\n let match: ProductMatch | undefined;\n try {\n const heading = current === url ? document.querySelector(\"main h1\") ?? document.querySelector(\"h1\") : null;\n match = heading ? options.productSnapshot?.(heading) : undefined;\n } catch { options.dropped(); }\n options.emit(\"navigation\", { action: \"page_view\", page, ...(previous ? { previous_page: previous } : {}),\n ...(match?.snapshot.metadata.resolution === \"resolved\" ? { product: { product_ref: match.product_ref, snapshot: match.snapshot } } : {}) }, epoch, time);\n }).catch(options.dropped).finally(() => { pendingRoutes--; });\n }\n /** Preserves History.pushState semantics and observes completed route changes. */\n function push(this: History, ...args: Parameters<History[\"pushState\"]>): void { Reflect.apply(originalPush, this, args); navigation(); }\n /** Preserves History.replaceState semantics and observes completed route changes. */\n function replace(this: History, ...args: Parameters<History[\"replaceState\"]>): void { Reflect.apply(originalReplace, this, args); navigation(); }\n /** Captures bounded ancestry/actions without merchant form values or arbitrary labels. */\n function click(event: MouseEvent): void {\n const epoch = options.epoch();\n if (stopped || !epoch || !(event.target instanceof Element) || event.composedPath().some(node => node instanceof Element && node.hasAttribute(\"data-sagepilot-popup\"))) return;\n if (pendingClicks >= 128) { options.dropped(); return; }\n try {\n const target = event.target.closest(\"button,a,input,select,textarea,[role='button']\") ?? event.target;\n const path: Json[] = [];\n let node: Element | null = target;\n for (let depth = 0; node && depth < 6; depth++, node = node.parentElement) {\n const role = node.getAttribute(\"role\"), type = node.getAttribute(\"type\"), parent: Element | null = node.parentElement;\n const sibling = parent && parent.children.length <= 64 ? Array.prototype.indexOf.call(parent.children, node) as number : -1;\n path.push({ tag: node.tagName.toLowerCase(), sibling_index: sibling, ...(role && roles.has(role) ? { role } : {}),\n ...(type && /^(button|submit|reset|checkbox|radio)$/.test(type) ? { type } : {}) });\n }\n const time = Date.now(), targetTag = target.tagName.toLowerCase();\n const evidence = semanticEvidence(target);\n let product: Record<string, Json> | Promise<Record<string, Json>> = {};\n try { product = dom.click(target, epoch, crypto.randomUUID()); } catch { options.dropped(); }\n /** Hands resolved source evidence to the journal before the merchant's navigation handler runs. */\n const emit = (ordinary: Record<string, Json>, page: string | null) => {\n if (!stopped && options.epoch() === epoch) options.emit(\"interaction\", { action: \"click\", target_tag: targetTag, target_path: path, ...evidence, ...ordinary, ...(page ? { page } : {}) }, epoch, time);\n };\n pendingClicks++;\n if (typeof (product as Promise<Record<string, Json>>).then !== \"function\") { try { emit(product as Record<string, Json>, current === location.href ? currentPage : null); } finally { queueMicrotask(() => { pendingClicks--; }); } }\n else void Promise.all([routeFor(location.href), Promise.resolve(product).catch(() => { options.dropped(); return {}; })]).then(([page, ordinary]) => emit(ordinary, page)).catch(options.dropped).finally(() => { pendingClicks--; });\n } catch { options.dropped(); }\n }\n history.pushState = push; history.replaceState = replace;\n document.addEventListener(\"click\", click, true);\n window.addEventListener(\"popstate\", navigation); window.addEventListener(\"hashchange\", navigation);\n navigation();\n /** Stops listeners without overwriting hooks installed by another library after ours. */\n return function stopPage(): void {\n stopped = true;\n dom.destroy();\n document.removeEventListener(\"click\", click, true);\n window.removeEventListener(\"popstate\", navigation); window.removeEventListener(\"hashchange\", navigation);\n if (history.pushState === push) history.pushState = originalPush;\n if (history.replaceState === replace) history.replaceState = originalReplace;\n };\n}\n\n/** Extracts an action vocabulary only; product identity is owned by the target-aware resolver. */\nfunction semanticEvidence(target: Element): Record<string, Json> {\n const hints = new Set([\"add\", \"cart\", \"remove\", \"checkout\", \"buy\", \"purchase\", \"wishlist\", \"product\", \"search\", \"subscribe\", \"submit\"]);\n const label = (target.getAttribute(\"aria-label\") ?? target.textContent ?? \"\").slice(0, 256).toLowerCase();\n const semanticTokens = [...new Set(label.split(/[^a-z]+/).filter(token => hints.has(token)))].sort();\n return { semantic_tokens: semanticTokens };\n}\n","import { project, projectText, routeFor, type Json } from \"./projection\";\nexport type Capture = (kind: \"network\" | \"navigation\" | \"interaction\" | \"lifecycle\", data: Record<string, Json>, epoch: string, time: number) => void;\ntype State = { id: string; epoch: string; method: string; url: string; route: Promise<string | null>; start: number; request: Json | null; status: number; bodySeen: boolean; cleanup?: () => void };\n\n/** Observes supported app-consumed bodies without cloning or initiating a read. */\nexport function observeNetwork(options: { epoch: () => string | null; excluded: (url: string) => boolean; emit: Capture; dropped: () => void; mutation?: () => void;\n products?: { observe(value: unknown, source: string): void; track(xhr: XMLHttpRequest, url: string, method: string): void } }): () => void {\n const fetchOriginal = globalThis.fetch, proto = globalThis.Response?.prototype;\n const textOriginal = proto?.text, jsonOriginal = proto?.json;\n const xhr = globalThis.XMLHttpRequest?.prototype, openOriginal = xhr?.open, sendOriginal = xhr?.send;\n const responses = new WeakMap<Response, State>(), requests = new WeakMap<XMLHttpRequest, State>();\n const active = new Set<State>(), xhrCleanups = new Set<() => void>();\n let stopped = false, insideFetch = false, pendingEmits = 0;\n /** Creates bounded request metadata and projects an already-provided JSON body immediately. */\n function state(url: string, method: string, body: unknown): State | null {\n const epoch = options.epoch();\n if (stopped || !epoch || active.size >= 128 || options.excluded(url)) return null;\n if (!/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(method)) return null;\n if (!/^(GET|HEAD|OPTIONS)$/i.test(method)) {\n // A concurrent server mutation makes a DOM-only outcome ambiguous and could otherwise double-count it.\n try { options.mutation?.(); } catch { options.dropped(); }\n }\n const result: State = { id: crypto.randomUUID(), epoch, method: method.toUpperCase(), url, route: routeFor(url), start: performance.now(),\n request: projectText(body), status: 0, bodySeen: false };\n active.add(result); return result;\n }\n /** Emits only within original permission/identity boundaries; evidence never includes raw body strings. */\n function emit(item: State, phase: string, outcome: string, response: Json | null = null): void {\n if (stopped || options.epoch() !== item.epoch) return;\n if (pendingEmits >= 128) { item.request = null; options.dropped(); return; }\n pendingEmits++;\n const elapsed = Math.max(0, performance.now() - item.start), time = Date.now();\n const request = phase === \"headers\" ? item.request : null;\n if (phase === \"headers\") item.request = null;\n void item.route.then(route => {\n if (!route || stopped || options.epoch() !== item.epoch) return;\n options.emit(\"network\", { request_id: item.id, method: item.method, route, route_version: 2,\n status: item.status, duration_ms: Math.round(elapsed), outcome, phase, projection_version: 2,\n ...(request ? { request } : {}), ...(response ? { response } : {}) }, item.epoch, time);\n }).catch(options.dropped).finally(() => { pendingEmits--; });\n }\n /** Returns the original fetch promise and Response; a side observer only attaches metadata. */\n function fetchObserved(this: unknown, ...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {\n let item: State | null = null;\n try {\n const input = args[0], init = args[1];\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n item = state(url, init?.method ?? (input instanceof Request ? input.method : \"GET\"), init?.body);\n } catch { options.dropped(); }\n let result: ReturnType<typeof fetch>;\n const previous = insideFetch;\n try { insideFetch = true; result = Reflect.apply(fetchOriginal, this, args); }\n catch (error) { if (item) { emit(item, \"headers\", \"error\"); active.delete(item); } throw error; }\n finally { insideFetch = previous; }\n const captured = item;\n if (captured) void result.then(response => {\n captured.status = response.status;\n emit(captured, \"headers\", \"completed\");\n if (!stopped && /(?:application|text)\\/(?:[a-z0-9.+-]*\\+)?json/i.test(response.headers.get(\"content-type\") ?? \"\")) responses.set(response, captured);\n active.delete(captured);\n }, () => { emit(captured, \"headers\", \"error\"); active.delete(captured); }).catch(options.dropped);\n return result;\n }\n /** Observes only the body consumption initiated by application code and preserves its promise. */\n function consume<T>(response: Response, original: (this: Response) => Promise<T>, isText: boolean): Promise<T> {\n const result = Reflect.apply(original, response, []), item = responses.get(response);\n if (item && !item.bodySeen) {\n item.bodySeen = true; responses.delete(response);\n void result.then(value => {\n if (stopped || options.epoch() !== item.epoch) return;\n try { if (item.status >= 200 && item.status < 300) options.products?.observe(value, item.url); const projected = isText ? projectText(value) : project(value); emit(item, \"body\", \"completed\", projected); }\n catch { options.dropped(); }\n }, () => {}).catch(options.dropped);\n }\n return result;\n }\n /** Wraps app-requested Response.text without starting any new body read. */\n function text(this: Response): Promise<string> { return consume(this, textOriginal!, true); }\n /** Wraps native browser Response.json; unlike RN it need not delegate to text(). */\n function json(this: Response): Promise<unknown> { return consume(this, jsonOriginal!, false); }\n /** Tracks XHR URL/method while preserving all original overload behavior. */\n function open(this: XMLHttpRequest, ...args: Parameters<XMLHttpRequest[\"open\"]>): void {\n const prior = requests.get(this);\n const result = Reflect.apply(openOriginal!, this, args);\n let url: string | null = null;\n try { url = String(args[1]); options.products?.track(this, url, args[0]); } catch { options.dropped(); }\n if (prior) { prior.cleanup?.(); active.delete(prior); requests.delete(this); }\n if (!insideFetch) {\n try { const item = url ? state(url, args[0], null) : null; if (item) requests.set(this, item); }\n catch { options.dropped(); }\n }\n return result;\n }\n /** Reads an already-completed text/JSON response; unsupported binary and streaming bodies stay unavailable. */\n function send(this: XMLHttpRequest, body?: Document | XMLHttpRequestBodyInit | null): void {\n const item = requests.get(this);\n if (!item || item.cleanup || stopped || options.epoch() !== item.epoch) return Reflect.apply(sendOriginal!, this, [body]);\n item.request = projectText(body);\n let outcome = \"completed\";\n /** Records transport outcome without interpreting business success. */\n const failed = (event: Event) => { outcome = event.type; };\n /** Removes this request's listeners and bounded bookkeeping. */\n const cleanup = () => {\n this.removeEventListener(\"loadend\", complete);\n for (const type of [\"error\", \"abort\", \"timeout\"]) this.removeEventListener(type, failed);\n active.delete(item); requests.delete(this); xhrCleanups.delete(cleanup); item.cleanup = undefined;\n };\n /** Projects only explicitly supported existing application response types. */\n const complete = () => {\n try {\n item.status = this.status;\n emit(item, \"headers\", outcome);\n if (outcome === \"completed\" && /(?:application|text)\\/(?:[a-z0-9.+-]*\\+)?json/i.test(this.getResponseHeader(\"content-type\") ?? \"\")) {\n if (item.status >= 200 && item.status < 300) options.products?.observe(this.responseType === \"json\" ? this.response : this.responseType === \"\" || this.responseType === \"text\" ? this.responseText : null, item.url);\n const response = this.responseType === \"json\" ? project(this.response)\n : this.responseType === \"\" || this.responseType === \"text\" ? projectText(this.responseText) : null;\n if (response) emit(item, \"body\", outcome, response);\n }\n } catch { options.dropped(); } finally { cleanup(); }\n };\n item.cleanup = cleanup; xhrCleanups.add(cleanup); this.addEventListener(\"loadend\", complete);\n for (const type of [\"error\", \"abort\", \"timeout\"]) this.addEventListener(type, failed);\n try { return Reflect.apply(sendOriginal!, this, [body]); } catch (error) { cleanup(); throw error; }\n }\n if (typeof fetchOriginal === \"function\") globalThis.fetch = fetchObserved;\n if (proto) proto.text = text;\n if (proto) proto.json = json;\n if (xhr) { xhr.open = open as typeof xhr.open; xhr.send = send; }\n /** Restores only wrappers still owned by this collector; later instrumentation remains intact. */\n return function stopNetwork(): void {\n stopped = true;\n for (const cleanup of [...xhrCleanups]) cleanup();\n active.clear();\n if (globalThis.fetch === fetchObserved) globalThis.fetch = fetchOriginal;\n if (proto?.text === text) proto.text = textOriginal!;\n if (proto?.json === json) proto.json = jsonOriginal!;\n if (xhr?.open === open) xhr.open = openOriginal!;\n if (xhr?.send === send) xhr.send = sendOriginal!;\n };\n}\n","import type { SagepilotSDKObservation } from \"@sagepilot-ai/sdk-installation-client\";\n\ntype ObservationKey = Pick<SagepilotSDKObservation, \"event_id\" | \"owner\">;\ntype JournalRecord<T> = { id: string; value: T; bytes: number; expires: number; purge?: string };\nexport type JournalDiagnostics = {\n storage: \"indexeddb\" | \"localStorage\" | \"memory\";\n pending_records: number;\n pending_bytes: number;\n memory_only_records: number;\n quota_evicted: number;\n expired_records: number;\n storage_failures: number;\n};\n\nexport const JOURNAL_TTL_MS = 24 * 60 * 60 * 1000;\nconst MAX_RECORDS = 8192, MAX_BYTES = 8 * 1024 * 1024;\nconst BACKUP_RECORDS = 256, BACKUP_BYTES = 512 * 1024;\n\n/** Opens a bounded journal with a small durable fallback for browsers that deny IndexedDB. */\nexport function createJournal<T extends ObservationKey>(scope: string) {\n const memory = new Map<string, JournalRecord<T>>();\n const backupSizes = new Map<string, number>();\n const prefix = `sagepilot:web-journal:${scope}:`, purgeKey = prefix + \"purged\";\n let db: IDBDatabase | null = null, backup: Storage | null = null;\n let pending = Promise.resolve(), opened: Promise<void> | null = null;\n let appends: { records: JournalRecord<T>[]; committed: Promise<void> } | null = null;\n let pendingBytes = 0, backupBytes = 0;\n let purge: string | null = null;\n let quotaEvicted = 0, expiredRecords = 0, storageFailures = 0;\n\n /** Rejects corrupt persisted entries before reading their owner or putting them on the wire. */\n function valid(record: JournalRecord<T>): boolean {\n return !!record && typeof record.id === \"string\" && record.id.length > 0 && record.id.length <= 128\n && Number.isSafeInteger(record.bytes) && record.bytes > 0 && record.bytes <= 32768 && Number.isFinite(record.expires)\n && record.value?.event_id === record.id && typeof record.value.owner?.session_id === \"string\"\n && (record.value.owner.customer_id === null || typeof record.value.owner.customer_id === \"string\");\n }\n\n /** Lists only this installation's fallback keys without reading other storage values. */\n function backupKeys(store: Storage): string[] {\n const keys: string[] = [];\n for (let index = 0; index < store.length; index++) {\n const key = store.key(index);\n if (key?.startsWith(prefix) && key !== purgeKey) keys.push(key);\n }\n return keys;\n }\n\n /** Restores sanitized records and the last consent purge marker before trying IndexedDB. */\n function readBackup(): JournalRecord<T>[] {\n const records: JournalRecord<T>[] = [];\n try {\n backup = globalThis.localStorage ?? null;\n if (!backup) return records;\n purge = backup.getItem(purgeKey);\n for (const key of backupKeys(backup)) {\n const raw = backup.getItem(key), size = (key.length + (raw?.length ?? 0)) * 2;\n let record: JournalRecord<T> | undefined;\n if (raw && size <= BACKUP_BYTES) {\n try { record = JSON.parse(raw) as JournalRecord<T>; } catch { /* Drop only the corrupt key. */ }\n }\n if (!record || !valid(record) || key !== prefix + record.id) { backup.removeItem(key); continue; }\n records.push(record);\n backupSizes.set(record.id, size); backupBytes += size;\n }\n } catch { backup = null; storageFailures++; }\n return records;\n }\n\n /** Stores one record per key so another tab's append cannot overwrite a saved batch. */\n function saveBackup(records: Iterable<JournalRecord<T>>): void {\n if (!backup) return;\n for (const record of records) {\n if (backupSizes.size >= BACKUP_RECORDS || backupBytes >= BACKUP_BYTES) break;\n if (backupSizes.has(record.id) || backupBytes + record.bytes > BACKUP_BYTES) continue;\n const key = prefix + record.id, raw = JSON.stringify(record), size = (key.length + raw.length) * 2;\n if (backupBytes + size > BACKUP_BYTES) continue;\n try { backup.setItem(key, raw); } catch { storageFailures++; break; }\n backupSizes.set(record.id, size); backupBytes += size;\n }\n }\n\n /** Deletes fallback copies after an acknowledgement, expiry or durable migration. */\n function removeBackup(ids: Iterable<string>): void {\n if (!backup) return;\n for (const id of ids) {\n const size = backupSizes.get(id);\n if (size === undefined) continue;\n try { backup.removeItem(prefix + id); } catch { storageFailures++; continue; }\n backupSizes.delete(id); backupBytes -= size;\n }\n }\n\n /** Preserves as much of the existing journal as the fallback budget can hold. */\n function fallback(): void {\n db?.close(); db = null; storageFailures++;\n saveBackup(memory.values());\n }\n\n /** Applies changes in one transaction and drops backup copies only after its commit. */\n async function persist(puts: JournalRecord<T>[], deletes: string[], clear = false): Promise<void> {\n removeBackup(deletes);\n if (db) {\n try {\n await new Promise<void>((resolve, reject) => {\n const tx = db!.transaction(\"events\", \"readwrite\"), store = tx.objectStore(\"events\");\n if (clear) store.clear();\n for (const id of deletes) store.delete(id);\n for (const record of puts) store.put(record);\n tx.oncomplete = () => resolve();\n tx.onabort = tx.onerror = () => reject(tx.error ?? new Error(\"Journal transaction failed\"));\n });\n removeBackup(puts.map(record => record.id));\n return;\n } catch { fallback(); }\n }\n saveBackup(deletes.length ? memory.values() : puts);\n }\n\n /** Restores the existing IndexedDB schema with a bounded wait for blocked browser storage. */\n function readIndexedDB(): Promise<JournalRecord<T>[]> {\n return new Promise((resolve, reject) => {\n let settled = false, connection: IDBDatabase | null = null;\n let timer = setTimeout(fail, 1500);\n\n /** Releases a late or unusable connection while allowing the fallback to take over. */\n function fail(): void {\n if (settled) return;\n settled = true; clearTimeout(timer); connection?.close();\n reject(new Error(\"IndexedDB journal is unavailable\"));\n }\n\n try {\n const request = indexedDB.open(\"sagepilot-web-events-\" + scope, 1);\n request.onupgradeneeded = () => { if (!request.result.objectStoreNames.contains(\"events\")) request.result.createObjectStore(\"events\", { keyPath: \"id\" }); };\n request.onerror = request.onblocked = fail;\n request.onsuccess = () => {\n if (settled) { request.result.close(); return; }\n connection = request.result;\n clearTimeout(timer); timer = setTimeout(fail, 5000);\n try {\n const tx = connection.transaction(\"events\", \"readonly\");\n const read = tx.objectStore(\"events\").getAll(undefined, MAX_RECORDS + 1);\n tx.onabort = tx.onerror = fail;\n tx.oncomplete = () => {\n if (settled) return;\n settled = true; clearTimeout(timer);\n db = connection; db!.onversionchange = fallback;\n resolve(read.result as JournalRecord<T>[]);\n };\n } catch { fail(); }\n };\n } catch { fail(); }\n });\n }\n\n /** Removes one entry and keeps hot-path byte accounting independent of journal size. */\n function remove(id: string): void {\n const record = memory.get(id);\n if (record) { memory.delete(id); pendingBytes -= record.bytes; }\n }\n\n /** Removes expired records and then evicts oldest records only if capacity is exhausted. */\n function prune(): string[] {\n const deleted: string[] = [], now = Date.now();\n for (const [id, record] of memory) {\n if (record.expires <= now) { remove(id); deleted.push(id); expiredRecords++; }\n }\n while (memory.size > MAX_RECORDS || pendingBytes > MAX_BYTES) {\n const id = memory.keys().next().value!;\n remove(id); deleted.push(id); quotaEvicted++;\n }\n return deleted;\n }\n\n /** Merges fallback and IndexedDB by occurrence ID without replacing another tab's records. */\n async function restore(): Promise<void> {\n const saved = readBackup();\n const primary = await readIndexedDB().catch(() => { storageFailures++; return []; });\n const corrupt: string[] = [];\n for (const record of [...saved, ...primary].filter(record => {\n if (valid(record) && (!purge || record.purge === purge)) return true;\n if (typeof record?.id === \"string\") corrupt.push(record.id);\n return false;\n }).sort((a, b) => a.expires - b.expires)) {\n remove(record.id); memory.set(record.id, record); pendingBytes += record.bytes;\n }\n const deleted = [...corrupt, ...prune()];\n const existing = new Set(primary.filter(valid).map(record => record.id));\n if (db) removeBackup(saved.filter(record => existing.has(record.id)).map(record => record.id));\n const migrate = db ? saved.filter(record => memory.has(record.id) && !existing.has(record.id)) : [];\n if (deleted.length || migrate.length) await persist(migrate, deleted);\n }\n\n /** Queues barriers after any earlier appends so consent purges and receipts retain their order. */\n function serial<R>(action: () => Promise<R>): Promise<R> {\n appends = null;\n const next = pending.then(async () => { await (opened ??= restore()); return action(); });\n pending = next.then(() => {}, () => { storageFailures++; });\n return next;\n }\n\n return {\n /** Coalesces queued captures into one disk transaction while preserving the capture order. */\n append(record: JournalRecord<T>): Promise<void> {\n if (appends) { appends.records.push(record); return appends.committed; }\n const records = [record];\n const committed = serial(async () => {\n if (appends?.records === records) appends = null;\n for (const item of records) {\n if (purge) item.purge = purge;\n remove(item.id); memory.set(item.id, item); pendingBytes += item.bytes;\n }\n const deleted = memory.size > MAX_RECORDS || pendingBytes > MAX_BYTES ? prune() : [];\n await persist(records.filter(item => memory.has(item.id)), deleted);\n });\n appends = { records, committed };\n return committed;\n },\n /** Selects a bounded upload batch without removing unacknowledged records. */\n batch(): Promise<T[]> {\n return serial(async () => {\n const deleted = prune();\n if (deleted.length) await persist([], deleted);\n const selected: T[] = [];\n let bytes = 0;\n for (const record of memory.values()) {\n if (selected.length >= 50 || bytes + record.bytes > 96 * 1024) break;\n selected.push(record.value); bytes += record.bytes;\n }\n return selected;\n });\n },\n /** Deletes only terminal receipt IDs from memory and any writable journal. */\n acknowledge(ids: Set<string>): Promise<void> {\n return serial(async () => { for (const id of ids) remove(id); await persist([], [...ids]); });\n },\n /** Purges evidence and fences the old generation if an inaccessible IndexedDB returns later. */\n clear(): Promise<void> {\n return serial(async () => {\n memory.clear(); pendingBytes = 0;\n purge = crypto.randomUUID();\n if (backup) {\n try {\n for (const key of backupKeys(backup)) backup.removeItem(key);\n backup.setItem(purgeKey, purge);\n } catch { storageFailures++; }\n }\n backupSizes.clear(); backupBytes = 0;\n await persist([], [], true);\n });\n },\n /** Reports known storage limits without exposing evidence or credentials. */\n diagnostics(): JournalDiagnostics {\n let volatile = 0;\n if (!db) for (const id of memory.keys()) if (!backupSizes.has(id)) volatile++;\n return { storage: db ? \"indexeddb\" : backup ? \"localStorage\" : \"memory\",\n pending_records: memory.size, pending_bytes: pendingBytes, memory_only_records: volatile,\n quota_evicted: quotaEvicted, expired_records: expiredRecords, storage_failures: storageFailures };\n },\n /** Closes browser handles after earlier writes settle. */\n async close(): Promise<void> { await pending; db?.close(); db = null; }\n };\n}\n","import type { SDKPopupBlock, SDKPopupDesign, SagepilotPopupConfig } from \"@sagepilot-ai/sdk-installation-client\";\n\nconst layouts = [\"centered\", \"image_left\", \"image_right\", \"bottom_sheet\"] as const;\nconst builtIns = new Set([\"logo\", \"title\", \"body\", \"hero\", \"form\"]);\nconst defaultBlocks: SDKPopupBlock[] = [{ kind: \"logo\" }, { kind: \"hero\" }, { kind: \"title\" }, { kind: \"body\" }, { kind: \"form\" }];\n\n/** Keeps public design assets to browser-safe HTTPS URLs before assigning any DOM property. */\nfunction asset(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length > 1000 || !value.startsWith(\"https://\") || /[\\s\\\\'\"<>]/.test(value)) return false;\n try {\n const url = new URL(value);\n return url.protocol === \"https:\" && !!url.hostname && url.port !== \"0\" && !url.username && !url.password && !url.hash;\n } catch { return false; }\n}\n\n/** Applies the server's design bounds defensively before creating merchant-controlled nodes. */\nexport function validPopupDesign(design: SDKPopupDesign | null | undefined): boolean {\n if (design == null) return true;\n const color = (v: unknown): boolean => typeof v === \"string\" && /^#[0-9a-f]{6}$/i.test(v);\n const integer = (v: number, min: number, max: number): boolean => Number.isInteger(v) && v >= min && v <= max;\n if (!layouts.includes(design.layout) ||\n ![design.background_color, design.text_color, design.button_text_color].every(color) ||\n !integer(design.border_radius, 0, 40) || !integer(design.padding, 12, 40) || !integer(design.width, 280, 760) ||\n (design.font_family !== null && (typeof design.font_family !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9 _-]{0,79}$/.test(design.font_family))) ||\n [design.font_url, design.image_url].some(url => url !== null && !asset(url)) ||\n typeof design.image_alt !== \"string\" || design.image_alt.length > 200) return false;\n if (design.blocks === null) return true;\n if (!Array.isArray(design.blocks) || design.blocks.length > 12) return false;\n const seen = new Set<string>();\n return design.blocks.every(block => {\n if (!block || typeof block !== \"object\") return false;\n if (builtIns.has(block.kind)) {\n if (seen.has(block.kind)) return false;\n seen.add(block.kind);\n return true;\n }\n if (block.kind === \"heading\" || block.kind === \"text\") return typeof block.text === \"string\" && block.text.length > 0 && block.text.length <= 600;\n if (block.kind === \"image\") return asset(block.url) && typeof block.alt === \"string\" && block.alt.length <= 200;\n if (block.kind === \"link\") return asset(block.url) && typeof block.text === \"string\" && block.text.length > 0 && block.text.length <= 120;\n return false;\n }) && seen.has(\"form\");\n}\n\n/** Creates a text-only popup element from the supported block set. */\nfunction node<K extends keyof HTMLElementTagNameMap>(tag: K, value?: string): HTMLElementTagNameMap[K] {\n const result = document.createElement(tag);\n if (value !== undefined) result.textContent = value;\n return result;\n}\n\n/** Applies presentation without letting imported content own any form behavior. */\nexport function renderPopupDesign(panel: HTMLElement, host: HTMLElement, config: SagepilotPopupConfig, form: HTMLFormElement): () => void {\n const design = config.design;\n const blocks = design?.blocks ?? defaultBlocks;\n const content = node(\"div\");\n content.className = \"content\";\n const hero = design?.image_url && blocks.some(block => block.kind === \"hero\") ? popupImage(design.image_url, design.image_alt, \"hero\") : null;\n const split = hero && (design?.layout === \"image_left\" || design?.layout === \"image_right\");\n if (split) {\n const side = node(\"div\");\n side.className = \"side-art\";\n side.append(hero);\n panel.append(side);\n }\n let heading = false;\n for (const block of blocks) {\n switch (block.kind) {\n case \"logo\": if (config.logo_url) content.append(popupImage(config.logo_url, \"\", \"logo\")); break;\n case \"hero\": if (hero && !split) content.append(hero); break;\n case \"title\": case \"heading\": {\n const title = node(heading ? \"h3\" : \"h2\", block.kind === \"heading\" ? block.text : config.title);\n if (!heading) { title.id = \"sage-popup-title\"; heading = true; }\n content.append(title);\n break;\n }\n case \"body\": content.append(node(\"p\", config.body)); break;\n case \"text\": content.append(node(\"p\", block.text)); break;\n case \"image\": content.append(popupImage(block.url, block.alt, \"block-image\")); break;\n case \"link\": {\n const link = node(\"a\", block.text); link.href = block.url; link.target = \"_blank\"; link.rel = \"noopener noreferrer\";\n content.append(link); break;\n }\n case \"form\": content.append(form); break;\n }\n }\n panel.append(content);\n if (heading) panel.setAttribute(\"aria-labelledby\", \"sage-popup-title\");\n else panel.setAttribute(\"aria-label\", config.title);\n if (!design) return () => {};\n panel.dataset.design = \"\";\n panel.dataset.layout = split ? design.layout : design.layout === \"bottom_sheet\" ? \"bottom_sheet\" : \"centered\";\n if (panel.dataset.layout === \"bottom_sheet\") {\n host.style.alignItems = \"end\";\n host.style.paddingBottom = \"0\";\n }\n for (const [key, value] of Object.entries({\n \"--popup-surface\": design.background_color, \"--popup-text\": design.text_color, \"--popup-button-text\": design.button_text_color,\n \"--popup-radius\": design.border_radius + \"px\", \"--popup-padding\": design.padding + \"px\", \"--popup-width\": design.width + \"px\",\n })) panel.style.setProperty(key, value);\n let face: FontFace | undefined;\n const fallback = design.font_family ? JSON.stringify(design.font_family) + \", system-ui, sans-serif\" : \"system-ui, sans-serif\";\n if (design.font_url && typeof FontFace === \"function\" && document.fonts) {\n try {\n face = new FontFace(\"sage-popup-\" + crypto.randomUUID(), \"url(\" + JSON.stringify(design.font_url) + \")\");\n document.fonts.add(face);\n panel.style.fontFamily = JSON.stringify(face.family) + \", \" + fallback;\n } catch { panel.style.fontFamily = fallback; }\n } else panel.style.fontFamily = fallback;\n return () => { if (face) document.fonts.delete(face); };\n}\n\n/** Assigns an inert image and omits the storefront referrer. */\nfunction popupImage(url: string, alt: string, className: string): HTMLImageElement {\n const image = node(\"img\");\n image.referrerPolicy = \"no-referrer\";\n image.alt = alt;\n image.className = className;\n image.src = url;\n return image;\n}\n\nexport const popupDesignStyles = [\n \".panel[data-design]{background:var(--popup-surface);color:var(--popup-text);border-radius:var(--popup-radius);width:min(var(--popup-width),calc(100vw - 40px));padding:0;overflow-wrap:anywhere}\",\n \".panel[data-design] .content{min-width:0;padding:var(--popup-padding)}\",\n \".panel[data-design] :is(p,a){color:inherit;white-space:pre-wrap}\",\n \".panel[data-design] input:not([type=checkbox]){color:inherit;background:transparent;border-color:currentColor}\",\n \".panel[data-design] button[type=submit]{color:var(--popup-button-text)}\",\n \".panel[data-design] :is(.hero,.block-image){display:block;max-width:100%;width:100%;max-height:240px;object-fit:cover;border-radius:calc(var(--popup-radius)/2)}\",\n \".panel[data-layout=bottom_sheet]{border-end-start-radius:0;border-end-end-radius:0}\",\n \".panel .side-art{position:relative;min-width:0;overflow:hidden}.panel .side-art>.hero{border-radius:0}.panel[data-design] .close{z-index:1}\",\n \"@media(min-width:600px){.panel:is([data-layout=image_left],[data-layout=image_right]){display:grid;grid-template-columns:minmax(0,2fr) minmax(0,3fr);align-items:stretch}.panel:is([data-layout=image_left],[data-layout=image_right]) .side-art>.hero{position:absolute;inset:0;height:100%;max-height:none}.panel[data-layout=image_right]{grid-template-columns:minmax(0,3fr) minmax(0,2fr)}.panel[data-layout=image_right]>.side-art{grid-row:1;grid-column:2}.panel[data-layout=image_right]>.content{grid-row:1;grid-column:1}}\",\n].join(\"\");\n","import type { SagepilotInstallationClient, SagepilotPopupConfig, SagepilotContactInput, SagepilotContactResult } from \"@sagepilot-ai/sdk-installation-client\";\nimport { popupDesignStyles, renderPopupDesign, validPopupDesign } from \"./popup-design\";\n\ntype PopupOptions = {\n client: SagepilotInstallationClient;\n storage: { getItem(key: string): string | null; setItem(key: string, value: string): void };\n emit(action: \"popup_shown\" | \"popup_submitted\" | \"popup_dismissed\"): void;\n submit(input: SagepilotContactInput): Promise<SagepilotContactResult>;\n identify(challenge: string, code: string): Promise<void>;\n report(error: unknown): void;\n};\n\n/** Shares completion state with the returning visitor bootstrap. */\nexport function popupCompletionKey(workspaceId: string, installationId: string): string {\n return `sagepilot:sdk-popup:${workspaceId}:${installationId}:completed`;\n}\n\n/** Rejects malformed public popup settings before creating DOM or loading a merchant image. */\nfunction valid(value: SagepilotPopupConfig): boolean {\n if (!value || !Number.isSafeInteger(value.revision) || value.revision < 1 || typeof value.enabled !== \"boolean\" ||\n !/^#[0-9a-f]{6}$/i.test(value.accent_color) || ![\"email\", \"none\"].includes(value.verification) ||\n ![value.title, value.body, value.button_text, value.success_text].every(item => typeof item === \"string\" && item.length <= 2000) ||\n !value.fields || ![value.fields.name, value.fields.email, value.fields.phone].every(item => typeof item === \"boolean\") ||\n !Array.isArray(value.required_fields) || value.required_fields.some(field => ![\"name\", \"email\", \"phone\"].includes(field) || !value.fields[field]) ||\n value.verification === \"email\" && !value.fields.email ||\n !Number.isFinite(value.frequency_hours) || value.frequency_hours < 1 || value.frequency_hours > 8760 ||\n !value.trigger || !Number.isFinite(value.trigger.delay_seconds) || value.trigger.delay_seconds < 0 || value.trigger.delay_seconds > 300 ||\n !Number.isFinite(value.trigger.scroll_percent) || value.trigger.scroll_percent < 0 || value.trigger.scroll_percent > 100 ||\n !Array.isArray(value.trigger.page_paths) || value.trigger.page_paths.length > 20 || value.trigger.page_paths.some(path => typeof path !== \"string\" || !path.startsWith(\"/\") || path.startsWith(\"//\") || /[?#\\\\]/.test(path) || path.length > 300)) return false;\n if (value.logo_url !== null) {\n try { const url = new URL(value.logo_url); if (url.protocol !== \"https:\" || url.username || url.password) return false; } catch { return false; }\n }\n return validPopupDesign(value.design);\n}\n\n/** Renders one accessible, text-only popup; contacts exist only in the explicit form submission. */\nexport function createPopup(options: PopupOptions): { configure(value: SagepilotPopupConfig | null | undefined): void; destroy(): void } {\n let config: SagepilotPopupConfig | null = null, host: HTMLElement | null = null;\n let timer: ReturnType<typeof setInterval> | null = null, entered = Date.now(), path = location.pathname, generation = 0;\n let previousFocus: Element | null = null, cleanup: (() => void) | null = null;\n const scope = `sagepilot:sdk-popup:${options.client.workspaceId}:${options.client.installationId}`;\n const shownKey = scope + \":shown\";\n const completedKey = popupCompletionKey(options.client.workspaceId, options.client.installationId);\n\n /** Removes the popup, its focus trap and observers without leaving host styles behind. */\n function remove(): void {\n generation++; cleanup?.(); cleanup = null; host?.remove(); host = null;\n if (previousFocus instanceof HTMLElement && previousFocus.isConnected) previousFocus.focus();\n previousFocus = null;\n }\n\n /** Evaluates targeting locally without transmitting a page path or its query parameters. */\n function eligible(): boolean {\n const session = options.client.session();\n if (!config?.enabled || host || !session || session.customer_id ||\n options.storage.getItem(completedKey) === session.anonymous_id) return false;\n if (path !== location.pathname) { path = location.pathname; entered = Date.now(); }\n if (config.trigger.page_paths.length && !config.trigger.page_paths.includes(path)) return false;\n if (Date.now() - entered < config.trigger.delay_seconds * 1000) return false;\n const height = Math.max(document.documentElement.scrollHeight - innerHeight, 1);\n if (config.trigger.scroll_percent > 0 && scrollY / height * 100 < config.trigger.scroll_percent) return false;\n const raw = options.storage.getItem(shownKey), last = Number(raw);\n return !raw || !Number.isFinite(last) || Date.now() - last >= config.frequency_hours * 3600000;\n }\n\n /** Creates typed DOM elements with textContent so merchant content cannot execute markup. */\n function element<K extends keyof HTMLElementTagNameMap>(tag: K, text?: string): HTMLElementTagNameMap[K] {\n const node = document.createElement(tag); if (text !== undefined) node.textContent = text; return node;\n }\n\n /** Displays the published template and retains no contact values in SDK diagnostics or events. */\n function show(): void {\n if (!eligible() || !config) return;\n const published = config, revision = ++generation;\n previousFocus = document.activeElement;\n host = element(\"div\"); host.setAttribute(\"data-sagepilot-popup\", \"\");\n host.style.cssText = \"position:fixed;inset:0;z-index:2147483000;display:grid;place-items:center;padding:20px;background:#10251d66\";\n const shadow = host.attachShadow({ mode: \"open\" });\n const style = element(\"style\");\n style.textContent = `:host{font-family:system-ui,sans-serif;color:#172c23;color-scheme:light}*{box-sizing:border-box}.panel{background:white;width:min(420px,calc(100vw - 40px));max-height:90dvh;overflow:auto;border-radius:18px;padding:28px;box-shadow:0 16px 80px #0003;position:relative}h2{margin:4px 28px 10px 0;font-size:25px}p{line-height:1.5;color:#52645a}label{display:block;margin-top:14px;font-size:14px}input{display:block;width:100%;padding:11px;border:1px solid #b6c7bd;border-radius:7px;margin-top:6px;font:inherit;background:white;color:#172c23}button{cursor:pointer;font:inherit;color:inherit}button[type=submit]{display:block;width:100%;border:0;border-radius:8px;background:${published.accent_color};color:white;padding:13px;margin-top:20px;font-weight:600}button:disabled{opacity:.6;cursor:wait}.close{position:absolute;right:15px;top:12px;border:0;background:transparent;font-size:25px}.status{min-height:1.3em;font-size:14px}.logo{max-width:160px;max-height:60px;object-fit:contain}input:focus-visible,button:focus-visible{outline:3px solid #729e82;outline-offset:3px}@media(max-width:480px){.panel{padding:22px}h2{font-size:22px}}`;\n style.textContent += popupDesignStyles;\n shadow.append(style);\n const panel = element(\"section\"); panel.className = \"panel\"; panel.setAttribute(\"role\", \"dialog\"); panel.setAttribute(\"aria-modal\", \"true\");\n const close = element(\"button\", \"×\"); close.type = \"button\"; close.className = \"close\"; close.setAttribute(\"aria-label\", \"Close form\");\n /** Closes the form and records only the explicit lifecycle action. */\n function dismiss(): void { options.emit(\"popup_dismissed\"); remove(); }\n close.addEventListener(\"click\", dismiss); panel.append(close);\n const form = element(\"form\"), status = element(\"p\"); status.className = \"status\"; status.setAttribute(\"role\", \"status\"); status.setAttribute(\"aria-live\", \"polite\");\n const inputs = new Map<string, HTMLInputElement>();\n const contactLabels: HTMLLabelElement[] = [];\n for (const field of [\"name\", \"email\", \"phone\"] as const) {\n if (!published.fields[field]) continue;\n const label = element(\"label\", field === \"phone\" ? \"Phone\" : field === \"email\" ? \"Email\" : \"Name\");\n const input = element(\"input\"); input.name = field; input.type = field === \"email\" ? \"email\" : field === \"phone\" ? \"tel\" : \"text\";\n input.autocomplete = field === \"phone\" ? \"tel\" : field; input.maxLength = field === \"phone\" ? 32 : field === \"email\" ? 254 : 100;\n input.required = published.required_fields.includes(field) || field === \"email\" && published.verification === \"email\";\n label.append(input); form.append(label); contactLabels.push(label); inputs.set(field, input);\n }\n const submit = element(\"button\", published.button_text); submit.type = \"submit\"; form.append(submit, status);\n const cleanupDesign = renderPopupDesign(panel, host, published, form);\n shadow.append(panel); document.body.append(host);\n options.storage.setItem(shownKey, String(Date.now())); options.emit(\"popup_shown\");\n const contactInputs = new Map(inputs);\n let submissionId = crypto.randomUUID(), challenge: string | null = null, busy = false;\n\n /** Sends an idempotent contact or challenge response while blocking duplicate form submissions. */\n async function submitForm(event: SubmitEvent): Promise<void> {\n event.preventDefault(); if (busy || revision !== generation) return;\n busy = true; submit.disabled = true; status.textContent = \"\";\n try {\n if (challenge) {\n await options.identify(challenge, inputs.get(\"code\")!.value);\n if (revision !== generation) return;\n form.replaceChildren(element(\"p\", published.success_text)); close.focus();\n } else {\n const contact: SagepilotContactInput = { submission_id: submissionId, popup_revision: published.revision, marketing_consent: true };\n for (const field of [\"name\", \"email\", \"phone\"] as const) { const value = inputs.get(field)?.value.trim(); if (value) contact[field] = value; }\n const result = await options.submit(contact);\n if (revision !== generation) return;\n options.emit(\"popup_submitted\");\n for (const input of inputs.values()) input.value = \"\";\n if (result.status === \"verification_required\") {\n challenge = result.challenge_id!; inputs.clear();\n const label = element(\"label\", \"Email verification code\"), code = element(\"input\");\n code.name = \"code\"; code.inputMode = \"numeric\"; code.autocomplete = \"one-time-code\"; code.pattern = \"[0-9]{6}\"; code.maxLength = 6; code.required = true;\n inputs.set(\"code\", code); label.append(code); submit.textContent = \"Verify email\";\n const restart = element(\"button\", \"Start again or use another email\"); restart.type = \"button\";\n /** Lets an expired challenge recover through a fresh explicit, rate-limited contact submission. */\n function restartForm(): void {\n if (busy) return;\n challenge = null; submissionId = crypto.randomUUID(); inputs.clear();\n for (const [key, value] of contactInputs) inputs.set(key, value);\n submit.textContent = published.button_text; status.textContent = \"\";\n form.replaceChildren(...contactLabels, submit, status);\n inputs.values().next().value?.focus();\n }\n restart.addEventListener(\"click\", restartForm);\n form.replaceChildren(label, submit, restart, status); status.textContent = \"Check your email for the six-digit code.\"; code.focus();\n } else { form.replaceChildren(element(\"p\", published.success_text)); close.focus(); }\n }\n } catch (error) {\n if (revision === generation) status.textContent = challenge ? \"Verification failed. Check the code and try again.\" : \"We couldn't save the form. Please try again.\";\n options.report(error);\n } finally { busy = false; submit.disabled = false; }\n }\n form.addEventListener(\"submit\", submitForm);\n /** Keeps keyboard focus within the active dialog and supports Escape dismissal. */\n function keydown(event: KeyboardEvent): void {\n if (event.key === \"Escape\") { event.preventDefault(); dismiss(); return; }\n if (event.key !== \"Tab\") return;\n const focusable = [...shadow.querySelectorAll<HTMLElement>(\"button:not(:disabled),input:not(:disabled),a[href]\")];\n const first = focusable[0], last = focusable[focusable.length - 1];\n if (event.shiftKey && shadow.activeElement === first) { event.preventDefault(); last?.focus(); }\n else if (!event.shiftKey && shadow.activeElement === last) { event.preventDefault(); first?.focus(); }\n }\n shadow.addEventListener(\"keydown\", keydown as EventListener);\n cleanup = () => { cleanupDesign(); form.removeEventListener(\"submit\", submitForm); shadow.removeEventListener(\"keydown\", keydown as EventListener); };\n (inputs.values().next().value ?? close).focus();\n }\n\n return {\n /** Applies only a validated published revision; disabling immediately removes an open form. */\n configure(value): void {\n if (value && !valid(value)) { options.report(new Error(\"Invalid published popup configuration.\")); value = null; }\n if (value?.revision === config?.revision && value?.enabled === config?.enabled) return;\n remove(); config = value ?? null; entered = Date.now(); path = location.pathname;\n if (timer) clearInterval(timer); timer = null;\n if (config?.enabled) { timer = setInterval(show, 1000); show(); }\n },\n /** Cancels rendering and listeners when the installation runtime is destroyed. */\n destroy(): void { if (timer) clearInterval(timer); timer = null; config = null; remove(); }\n };\n}\n","import { createSagepilotInstallationClient, SagepilotInstallationError, type SagepilotSDKObservation, type SagepilotContactInput, type SagepilotContactResult } from \"@sagepilot-ai/sdk-installation-client\";\nimport { name as SDK_NAME, version as SDK_VERSION } from \"../package.json\";\nimport { observePage } from \"./collectors\";\nimport { observeNetwork, type Capture } from \"./network\";\nimport { createJournal, JOURNAL_TTL_MS } from \"./storage\";\nimport { createPopup, popupCompletionKey } from \"./popup\";\nimport { createProductIndex } from \"./product\";\n\nexport type SagepilotWebEventsOptions = {\n key: string;\n /** HTTPS gateway origin; loopback origins are supported for local development. */\n apiHost?: string;\n /** Explicit website collection permission; capture is off by default. */\n collectionEnabled?: boolean;\n /** Optional custom transport for first-party requests and local integration fixtures. */\n fetch?: typeof fetch;\n onError?: (error: unknown) => void;\n};\nexport type SagepilotWebEvents = {\n start(): Promise<void>;\n setCollectionEnabled(enabled: boolean): Promise<void>;\n flush(): Promise<void>;\n submitContact(input: SagepilotContactInput): Promise<SagepilotContactResult>;\n verifyContact(challengeId: string, code: string): Promise<void>;\n logout(): Promise<void>;\n refreshConfig(): Promise<void>;\n diagnostics(): ReturnType<ReturnType<typeof createJournal>[\"diagnostics\"]> & {\n enabled: boolean; rejected_payloads: number; collector_dropped: number; anonymous_id_storage: \"cookie\" | \"localStorage\" | \"memory\";\n };\n destroy(): Promise<void>;\n};\nconst instances = new Map<string, SagepilotWebEvents>();\nconst VISITOR_KEY = \"sagepilot_anonymous_id\";\nconst VISITOR_ID = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** Creates or reuses one installation collector; no hooks or HTTP calls run until start(). */\nexport function createSagepilotWebEvents(options: SagepilotWebEventsOptions): SagepilotWebEvents {\n const scope = options.key.toLowerCase();\n const existing = instances.get(scope);\n if (existing) return existing;\n let anonymousStorage: \"cookie\" | \"localStorage\" | \"memory\" = \"memory\";\n let browserId: string | null = null;\n let cookieRequests: Promise<unknown> = Promise.resolve();\n let cookieSynced = false;\n const memory = new Map<string, string>();\n /** Shields the website from browser privacy-mode and quota storage failures. */\n const storage = {\n getItem(key: string): string | null { try { return localStorage.getItem(key) ?? memory.get(key) ?? null; } catch { return memory.get(key) ?? null; } },\n setItem(key: string, value: string): void { memory.set(key, value); try { localStorage.setItem(key, value); } catch { /* Scoped session remains in runtime memory. */ } },\n removeItem(key: string): void { memory.delete(key); try { localStorage.removeItem(key); } catch { /* Browser storage is unavailable. */ } }\n };\n const client = createSagepilotInstallationClient({\n key: options.key, apiHost: options.apiHost, platform: \"web\", fetch: options.fetch, storage,\n sdk: { name: SDK_NAME, version: SDK_VERSION },\n });\n const completedKey = popupCompletionKey(client.workspaceId, client.installationId);\n const cookieKey = `sagepilot:sdk-visitor-cookie:${scope}`;\n const journal = createJournal<SagepilotSDKObservation>(scope.replace(/:/g, \"_\"));\n let localPermission = options.collectionEnabled === true, started = false, destroyed = false, policyKnown = false;\n let identityChanging = false;\n let starting: Promise<void> | null = null, draining: Promise<void> | null = null;\n let generation = 0, epoch = \"\", failures = 0, rejected = 0, dropped = 0, lastRefresh = 0, capturePending = 0, captureBytes = 0, networkMutations = 0;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let policyTimer: ReturnType<typeof setInterval> | null = null;\n let stopPage: (() => void) | null = null, stopNetwork: (() => void) | null = null;\n let products: ReturnType<typeof createProductIndex> | null = null;\n /** Isolates host callbacks from instrumentation and transport behavior. */\n function report(error: unknown): void { try { options.onError?.(error); } catch { /* Host errors cannot break the SDK. */ } }\n\n /** Requires both dashboard policy and the browser's current analytics permission. */\n function canUseVisitorCookie(): boolean {\n const session = client.session();\n return !destroyed && localPermission && session?.collection_enabled === true && session.visitor_cookie_enabled === true;\n }\n\n /** Serializes cookie writes so a consent withdrawal clears any earlier completion update. */\n function syncVisitorCookie(anonymousId: string | null, allowed: boolean) {\n if (!allowed) cookieSynced = false;\n const operation = cookieRequests.then(async () => {\n if (allowed) {\n if (!canUseVisitorCookie()) return null;\n // A lost response can still set a cookie. Keep the marker so it can be cleared later.\n storage.setItem(cookieKey, \"1\");\n } else if (!storage.getItem(cookieKey)) return null;\n try {\n const visitor = await client.syncVisitorCookie(\n anonymousId, allowed, anonymousId !== null && storage.getItem(completedKey) === anonymousId,\n );\n if (visitor.anonymous_id === null) {\n cookieSynced = false;\n storage.removeItem(cookieKey);\n }\n return visitor;\n } catch (error) {\n if (!destroyed) report(error);\n return null;\n }\n });\n cookieRequests = operation;\n return operation;\n }\n\n /** Keeps the active ID in browser storage for use when the cookie route is unavailable. */\n function rememberBrowser(anonymousId: string, restored: boolean): void {\n memory.set(VISITOR_KEY, anonymousId);\n try {\n if (localStorage.getItem(VISITOR_KEY) !== anonymousId) localStorage.setItem(VISITOR_KEY, anonymousId);\n anonymousStorage = \"localStorage\";\n } catch { anonymousStorage = \"memory\"; }\n if (restored) anonymousStorage = \"cookie\";\n browserId = anonymousId;\n }\n\n /** Reconciles the storefront cookie before using the refreshed capture and popup policy. */\n async function syncCookiePolicy(revision: number): Promise<void> {\n if (destroyed || revision !== generation) return;\n const session = client.session();\n if (!session?.collection_enabled || session.visitor_cookie_enabled !== true) {\n await syncVisitorCookie(null, false);\n if (browserId && anonymousStorage === \"cookie\") rememberBrowser(browserId, false);\n return;\n }\n if (cookieSynced || !localPermission) return;\n const currentId = session.anonymous_id;\n const cookie = await syncVisitorCookie(currentId, true);\n const restoredId = cookie?.anonymous_id;\n if (!restoredId || revision !== generation || !canUseVisitorCookie() ||\n client.session()?.anonymous_id !== currentId) return;\n if (cookie.popup_completed) {\n storage.setItem(completedKey, restoredId);\n popup.configure(null);\n }\n rememberBrowser(restoredId, cookie.restored);\n if (restoredId !== currentId) {\n policyKnown = false;\n epoch = crypto.randomUUID();\n detach(true);\n popup.configure(null);\n client.destroy();\n await client.start(restoredId);\n }\n if (revision === generation && canUseVisitorCookie()) cookieSynced = true;\n }\n\n /** Bootstraps the installation policy before making any request to the optional cookie route. */\n async function startVisitor(revision: number): Promise<void> {\n const saved = browserId ?? storage.getItem(VISITOR_KEY);\n const anonymousId = saved && VISITOR_ID.test(saved) ? saved : crypto.randomUUID();\n rememberBrowser(anonymousId, false);\n await client.start(anonymousId);\n await syncCookiePolicy(revision);\n }\n\n /** Persists completion only after the server accepts the form or verifies the email. */\n async function completeVisitor(anonymousId: string | undefined): Promise<void> {\n if (!anonymousId || destroyed || client.session()?.anonymous_id !== anonymousId) return;\n storage.setItem(completedKey, anonymousId);\n if (canUseVisitorCookie()) await syncVisitorCookie(anonymousId, true);\n }\n\n /** Clears the optional cookie and the unsent observations on consent withdrawal. */\n async function clearCollection(): Promise<void> {\n await Promise.all([journal.clear(), syncVisitorCookie(null, false)]);\n }\n /** Keeps capture within both local consent and the last confirmed server permission lease. */\n function enabled(): boolean {\n if (destroyed || identityChanging || !started || !localPermission || !policyKnown) return false;\n const session = client.session();\n return session?.collection_enabled === true && Date.parse(session.expires_at) > Date.now();\n }\n /** Returns a capture fence only while this installation is allowed to observe. */\n function captureEpoch(): string | null { return enabled() ? epoch : null; }\n /** Excludes SDK bootstrap and its configured ingress before request data is observed. */\n function excluded(input: string): boolean {\n try {\n const url = new URL(input, location.href), session = client.session();\n return (url.origin === client.apiHost && url.pathname.startsWith(\"/platform-api/v1/sdk/\"))\n || url.origin === location.origin && url.pathname === client.visitorCookiePath\n || !!session && url.origin + url.pathname === session.ingestion_url;\n } catch { return true; }\n }\n /** Snapshots original ownership and appends sanitized records only within the capture fence. */\n const capture: Capture = (kind, data, capturedEpoch, time) => {\n const session = client.session();\n if (!session || !enabled() || epoch !== capturedEpoch) { dropped++; return; }\n const observation: SagepilotSDKObservation = {\n event_id: crypto.randomUUID(), kind, occurred_at: new Date(time).toISOString(),\n owner: { session_id: session.session_id, customer_id: session.customer_id, identity_epoch: capturedEpoch },\n workspace_id: session.workspace_id, installation_id: session.installation_id, platform: \"web\",\n sdk_name: SDK_NAME, sdk_version: SDK_VERSION, clock_quality: \"unverified\", clock_source: \"device_wall\", data\n };\n const bytes = new TextEncoder().encode(JSON.stringify(observation)).byteLength;\n if (bytes > 32768) { rejected++; return; }\n if (capturePending >= 128 || captureBytes + bytes > 512 * 1024) { dropped++; return; }\n capturePending++; captureBytes += bytes;\n void journal.append({ id: observation.event_id, value: observation, bytes, expires: Date.now() + JOURNAL_TTL_MS })\n .catch(report).finally(() => { capturePending--; captureBytes -= bytes; });\n };\n const popup = createPopup({ client, storage, report,\n emit(action) { if (enabled()) capture(\"lifecycle\", { action }, epoch, Date.now()); },\n submit(input) { return addon.submitContact(input); },\n identify(challenge, code) { return addon.verifyContact(challenge, code); }\n });\n /** Pauses collectors before proof/logout; old queued records retain original ownership and credentials. */\n async function changeIdentity(operation: () => Promise<unknown>): Promise<void> {\n if (!started || destroyed) throw new Error(\"Start the web-events installation first.\");\n if (identityChanging) throw new Error(\"An SDK identity operation is already running.\");\n identityChanging = true;\n generation++; epoch = crypto.randomUUID(); detach(true); client.cancelPending();\n try { await operation(); }\n finally {\n identityChanging = false;\n if (!destroyed) { epoch = crypto.randomUUID(); if (enabled()) attach(); else detach(); schedule(); }\n }\n }\n /** Refreshes capture permission and independently published popup settings on the existing session. */\n async function refreshConfig(): Promise<void> {\n if (identityChanging) return;\n const revision = generation;\n const previous = client.session();\n try {\n await client.refresh(true);\n await syncCookiePolicy(revision);\n }\n catch (error) {\n if (revision === generation && !destroyed) {\n popup.configure(null);\n const status = error instanceof SagepilotInstallationError ? error.status ?? 0 : 0;\n const temporary = error instanceof SagepilotInstallationError && (error.code === \"network_error\" ||\n status === 408 || status === 425 || status === 429 || status >= 500);\n if (!temporary) suspendCapture();\n }\n throw error;\n }\n if (revision !== generation || destroyed) return;\n if (previous?.session_id !== client.session()?.session_id || Date.parse(previous?.expires_at ?? \"\") <= Date.now()) {\n epoch = crypto.randomUUID();\n }\n lastRefresh = Date.now(); policyKnown = true;\n popup.configure(client.session()?.popup);\n if (!client.session()?.collection_enabled) { detach(); await journal.clear(); }\n else { attach(); schedule(); }\n }\n /** Fences capture after an authoritative failure and lets config renewal reestablish permission. */\n function suspendCapture(): void {\n policyKnown = false; lastRefresh = 0; epoch = crypto.randomUUID(); detach(); schedule();\n }\n /** Detaches all event sources before asynchronous permission or ownership work begins. */\n function detach(preserveProducts = false): void {\n stopPage?.(); stopPage = null; stopNetwork?.(); stopNetwork = null;\n if (preserveProducts) products?.pause(); else { products?.destroy(); products = null; }\n if (retryTimer) clearTimeout(retryTimer); retryTimer = null;\n }\n /** Installs the currently permitted collectors once. */\n function attach(): void {\n if (!enabled()) return;\n armNetwork(); products?.activate();\n if (!stopPage) stopPage = observePage({ epoch: captureEpoch, emit: capture, dropped: () => { dropped++; },\n networkVersion: () => networkMutations, productSnapshot: (root, price, currency, label) => products?.resolve(root, price, currency, label) });\n }\n /** Tracks only weak startup XHR metadata before authorization; ordinary capture stays gated. */\n function armNetwork(): void {\n if (destroyed || !localPermission || stopNetwork) return;\n products ??= createProductIndex({ epoch: captureEpoch });\n stopNetwork = observeNetwork({ epoch: captureEpoch, excluded, emit: capture, dropped: () => { dropped++; },\n mutation: () => { networkMutations++; }, products });\n }\n /** Maintains one retry timer; the collector never wakes repeatedly while disabled. */\n function schedule(): void {\n if (!started || destroyed || !localPermission || identityChanging || retryTimer) return;\n const delay = failures ? Math.min(60000, 2000 * 2 ** Math.min(failures, 5)) * (0.8 + Math.random() * 0.4) : 2000;\n retryTimer = setTimeout(() => { retryTimer = null; void flush().catch(report).finally(schedule); }, delay);\n }\n /** Refreshes server permission and uploads bounded same-owner batches; missing receipts retain records. */\n async function flush(): Promise<void> {\n if (draining) return draining;\n if (!started || destroyed || !localPermission || identityChanging) return;\n const revision = generation;\n draining = (async () => {\n try {\n if (!policyKnown || Date.now() - lastRefresh > 60000) await refreshConfig();\n if (revision !== generation || !enabled()) return;\n for (let pass = 0; pass < 4; pass++) {\n const queued = await journal.batch();\n const first = queued[0]?.owner;\n const batch = queued.filter(item => item.owner.session_id === first?.session_id && item.owner.customer_id === first?.customer_id);\n if (revision !== generation || !enabled()) return;\n if (!batch.length) { failures = 0; return; }\n if (!client.hasCaptureOwner(first!)) {\n // Credentials are bounded and logout revokes authority; report loss instead of blocking every newer owner.\n dropped += batch.length; await journal.acknowledge(new Set(batch.map(item => item.event_id))); continue;\n }\n const receipt = await client.upload(batch, first!);\n if (revision !== generation || !enabled()) return;\n const terminal = new Set(receipt.results.filter(item => item.status !== \"retryable\").map(item => item.event_id));\n dropped += receipt.results.filter(item => item.status === \"disabled\" || item.status === \"invalid\").length;\n await journal.acknowledge(terminal);\n if (terminal.size !== batch.length) { failures = Math.min(failures + 1, 6); return; }\n failures = 0;\n }\n } catch (error) {\n if (revision === generation && !destroyed) {\n failures = Math.min(failures + 1, 6);\n if (client.session()?.collection_enabled === false) { detach(); await journal.clear(); }\n else if (policyKnown && error instanceof SagepilotInstallationError && [401, 403, 404, 410].includes(error.status ?? 0)) suspendCapture();\n }\n throw error;\n }\n })().finally(() => { draining = null; });\n return draining;\n }\n /** Resumes flushing on connectivity restoration without reinitializing browser observers. */\n function online(): void { void flush().catch(report); }\n const addon: SagepilotWebEvents = {\n /** Bootstraps this browser owner without loading chat, showing a popup or collecting before consent. */\n async start(): Promise<void> {\n if (destroyed) throw new Error(\"This web-events collector was destroyed.\");\n if (starting) return starting;\n if (started) return;\n if (typeof window === \"undefined\" || !globalThis.crypto?.randomUUID) throw new Error(\"Web events require a browser on HTTPS or loopback.\");\n const revision = generation;\n starting = (async () => {\n armNetwork();\n await startVisitor(revision);\n if (destroyed || revision !== generation) return;\n started = true; policyKnown = true; epoch = crypto.randomUUID(); lastRefresh = Date.now();\n popup.configure(client.session()?.popup);\n window.addEventListener(\"online\", online);\n policyTimer = setInterval(() => { void refreshConfig().catch(report); }, 60000);\n if (!localPermission || !client.session()?.collection_enabled) detach();\n if (!client.session()?.collection_enabled) await journal.clear();\n attach(); schedule();\n })().catch(error => {\n if (revision !== generation || destroyed) return;\n detach();\n throw error;\n }).finally(() => { starting = null; });\n return starting;\n },\n /** Fences immediately; disabling aborts SDK requests and purges unuploaded evidence. */\n async setCollectionEnabled(next: boolean): Promise<void> {\n if (destroyed) throw new Error(\"This web-events collector was destroyed.\");\n if (typeof next !== \"boolean\") throw new Error(\"Collection permission must be boolean.\");\n if (localPermission === next && started) {\n if (!next) await clearCollection();\n return;\n }\n localPermission = next; generation++; epoch = crypto.randomUUID(); detach(); client.cancelPending();\n if (!next) { await clearCollection(); return; }\n if (starting) await starting;\n if (destroyed || !localPermission) return;\n if (!started) { await addon.start(); return; }\n const revision = generation; policyKnown = false;\n try {\n await client.refresh(true);\n await syncCookiePolicy(revision);\n if (revision !== generation || destroyed || !localPermission) return;\n lastRefresh = Date.now(); policyKnown = true;\n popup.configure(client.session()?.popup);\n if (!client.session()?.collection_enabled) await journal.clear();\n attach(); schedule();\n } catch (error) { if (revision === generation && !destroyed) { lastRefresh = 0; schedule(); } throw error; }\n },\n flush,\n /** Submits contact-only data through the explicit identity endpoint, never through autocapture. */\n async submitContact(input) {\n const anonymousId = client.session()?.anonymous_id;\n const result = await client.submitContact(input);\n if (result.status === \"recorded\") await completeVisitor(anonymousId);\n return result;\n },\n /** Verifies proof behind a capture fence; buffered anonymous observations remain anonymous. */\n async verifyContact(challengeId, code) {\n const anonymousId = client.session()?.anonymous_id;\n await changeIdentity(() => client.verifyContact(challengeId, code));\n await completeVisitor(anonymousId);\n },\n /** Applies an explicit logout boundary without relabeling earlier observations. */\n logout() {\n return changeIdentity(async () => {\n try { await client.logout(); }\n catch (error) {\n // The server may have revoked the old owner even when its response was lost.\n policyKnown = false; lastRefresh = 0;\n throw error;\n }\n });\n },\n refreshConfig,\n /** Reports bounded operational counters, never contact values, credentials or queued payloads. */\n diagnostics() { return { ...journal.diagnostics(), enabled: enabled(), rejected_payloads: rejected, collector_dropped: dropped, anonymous_id_storage: anonymousStorage }; },\n /** Stops the runtime and requests; consent revocation is the separate purge operation. */\n async destroy(): Promise<void> {\n destroyed = true; generation++; detach(); if (policyTimer) clearInterval(policyTimer); policyTimer = null; popup.destroy(); client.destroy();\n if (typeof window !== \"undefined\") window.removeEventListener(\"online\", online);\n await journal.close();\n if (instances.get(scope) === addon) instances.delete(scope);\n }\n };\n instances.set(scope, addon);\n return addon;\n}\n"],"mappings":";AACO,IAAM,6BAAN,cAAyC,MAAM;AAAA,EAIpD,YACW,MACT,SACA,UAAgD,CAAC,GACjD;AACA,UAAM,OAAO;AAJJ;AAKT,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ;AACtB,SAAK,QAAQ,QAAQ;AAAA,EACvB;AACF;AAmFA,IAAM,OAAO;AACb,IAAM,aAAa;AACnB,IAAM,WAAW,oBAAI,IAAI,CAAC,YAAY,aAAa,YAAY,WAAW,WAAW,CAAC;AAGtF,SAAS,QAAQ,OAAoB;AACnC,QAAM,MAAM,IAAI,IAAI,KAAK;AACzB,MAAI,IAAI,YAAY,IAAI,YAAY,IAAI,UAAU,IA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WAAW,WAAY,OAAM,gBAAgB,WAAW;AACnE,aAAO;AAAA,IACT;AAAA;AAAA,IAEA,MAAM,cAAc,aAAa,MAAM;AACrC,YAAM,cAAc,OAAO,QAAQ,GAAG;AACtC,YAAM,eAAe,MAAM,OAAO,cAAc,aAAa,IAAI,CAAC;AAClE,YAAM,gBAAgB,WAAW;AAAA,IACnC;AAAA;AAAA,IAEA,SAAS;AACP,aAAO,eAAe,YAAY;AAChC,YAAI;AAAE,gBAAM,OAAO,OAAO;AAAA,QAAG,SACtB,OAAO;AAEZ,wBAAc;AAAO,wBAAc;AACnC,gBAAM;AAAA,QACR;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IACA;AAAA;AAAA,IAEA,cAAc;AAAE,aAAO,EAAE,GAAG,QAAQ,YAAY,GAAG,SAAS,QAAQ,GAAG,mBAAmB,UAAU,mBAAmB,SAAS,sBAAsB,iBAAiB;AAAA,IAAG;AAAA;AAAA,IAE1K,MAAM,UAAyB;AAC7B,kBAAY;AAAM;AAAc,aAAO;AAAG,UAAI,YAAa,eAAc,WAAW;AAAG,oBAAc;AAAM,YAAM,QAAQ;AAAG,aAAO,QAAQ;AAC3I,UAAI,OAAO,WAAW,YAAa,QAAO,oBAAoB,UAAU,MAAM;AAC9E,YAAM,QAAQ,MAAM;AACpB,UAAI,UAAU,IAAI,KAAK,MAAM,MAAO,WAAU,OAAO,KAAK;AAAA,IAC5D;AAAA,EACF;AACA,YAAU,IAAI,OAAO,KAAK;AAC1B,SAAO;AACT;","names":["text","label","node","value","name","row","project","text","pending","form","nodes","price","node","name","node","label","text","valid","id","record","text","node","label","restartForm","VISITOR_ID","price","label"]}
1
+ {"version":3,"sources":["../../sdk-installation-client/src/index.ts","../package.json","../src/projection.ts","../src/product.ts","../src/dom.ts","../src/collectors.ts","../src/network.ts","../src/storage.ts","../src/popup-design.ts","../src/popup.ts","../src/index.ts"],"sourcesContent":["/** Distinguishes transport failures from HTTP rejections of an installation request. */\nexport class SagepilotInstallationError extends Error {\n readonly status?: number;\n readonly cause?: unknown;\n\n constructor(\n readonly code: \"invalid_response\" | \"network_error\",\n message: string,\n options: { status?: number; cause?: unknown } = {},\n ) {\n super(message);\n this.name = \"SagepilotInstallationError\";\n this.status = options.status;\n this.cause = options.cause;\n }\n}\n\ntype InstallationStorage = {\n getItem(key: string): string | null | Promise<string | null>;\n setItem(key: string, value: string): void | Promise<void>;\n removeItem(key: string): void | Promise<void>;\n};\n\nexport type SagepilotInstallationOwner = { session_id: string; customer_id: string | null };\nexport type SDKPopupBlock =\n | { kind: \"logo\" | \"title\" | \"body\" | \"hero\" | \"form\" }\n | { kind: \"heading\" | \"text\"; text: string }\n | { kind: \"image\"; url: string; alt: string }\n | { kind: \"link\"; url: string; text: string };\n\nexport type SDKPopupDesign = {\n layout: \"centered\" | \"image_left\" | \"image_right\" | \"bottom_sheet\";\n background_color: string;\n text_color: string;\n button_text_color: string;\n border_radius: number;\n padding: number;\n width: number;\n font_family: string | null;\n font_url: string | null;\n image_url: string | null;\n image_alt: string;\n blocks: SDKPopupBlock[] | null;\n};\n\nexport type SagepilotPopupConfig = {\n revision: number; enabled: boolean; title: string; body: string; button_text: string; success_text: string;\n logo_url: string | null; accent_color: string; fields: { name: boolean; email: boolean; phone: boolean };\n required_fields: Array<\"name\" | \"email\" | \"phone\">; consent: { required: boolean; label: string };\n trigger: { delay_seconds: number; scroll_percent: number; page_paths: string[] };\n frequency_hours: number; verification: \"email\" | \"none\";\n design?: SDKPopupDesign | null;\n};\nexport type SagepilotContactInput = {\n submission_id: string; popup_revision: number; name?: string; email?: string; phone?: string; marketing_consent: boolean;\n};\nexport type SagepilotContactResult = { status: \"verification_required\" | \"recorded\"; challenge_id?: string; expires_at?: string };\nexport type SagepilotSDKObservation = {\n event_id: string;\n kind: \"navigation\" | \"interaction\" | \"network\" | \"lifecycle\" | \"screen\";\n occurred_at: string;\n owner: SagepilotInstallationOwner & { identity_epoch: string };\n data: Record<string, unknown>;\n [key: string]: unknown;\n};\nexport type SagepilotInstallationReceipt = {\n results: Array<{ event_id: string; status: \"admitted\" | \"duplicate\" | \"disabled\" | \"invalid\" | \"retryable\" }>;\n};\nexport type SagepilotInstallationSession = SagepilotInstallationOwner & {\n workspace_id: string;\n installation_id: string;\n anonymous_id: string;\n platform: \"web\" | \"android\" | \"ios\";\n session_token: string;\n expires_at: string;\n collection_enabled: boolean;\n visitor_cookie_enabled?: boolean;\n revision: number;\n ingestion_url: string;\n popup?: SagepilotPopupConfig | null;\n};\ntype SagepilotBrowserVisitor = {\n anonymous_id: string | null;\n popup_completed: boolean;\n restored: boolean;\n};\nexport type SagepilotInstallationOptions = {\n key: string;\n /** Gateway origin; HTTPS is required except for loopback development. */\n apiHost?: string;\n platform: \"web\" | \"android\" | \"ios\";\n sdk: { name: string; version: string };\n appId?: string;\n fetch?: typeof fetch;\n /** Optional scoped session persistence; tokens never enter the observation journal. */\n storage?: InstallationStorage;\n};\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst VISITOR_ID = /^[A-Za-z0-9_-]{1,128}$/;\nconst TERMINAL = new Set([\"admitted\", \"duplicate\", \"disabled\", \"invalid\", \"retryable\"]);\n\n/** Restricts credential-bearing requests to HTTPS or an explicit loopback development endpoint. */\nfunction safeURL(value: string): URL {\n const url = new URL(value);\n if (url.username || url.password || url.search || url.hash ||\n (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\", \"10.0.2.2\"].includes(url.hostname)))) {\n throw new Error(\"SDK endpoints require HTTPS and cannot contain credentials, queries or fragments.\");\n }\n return url;\n}\n\n/** Checks receipt identity before any collector may discard a journal record. */\nexport function validateSagepilotInstallationReceipt(value: unknown, requestedIDs: string[]): SagepilotInstallationReceipt {\n const results = (value as SagepilotInstallationReceipt | null)?.results;\n if (!Array.isArray(results)) throw new Error(\"SDK admission receipt is missing.\");\n const requested = new Set(requestedIDs), seen = new Set<string>();\n if (requested.size !== requestedIDs.length) throw new Error(\"SDK batch contains duplicate observation IDs.\");\n for (const item of results) {\n if (!item || !requested.has(item.event_id) || seen.has(item.event_id) || !TERMINAL.has(item.status)) {\n throw new Error(\"SDK admission receipt does not match the requested observations.\");\n }\n seen.add(item.event_id);\n }\n return { results };\n}\n\n/** Installation-scoped anonymous sessions shared by browser and native event collectors. */\nexport class SagepilotInstallationClient {\n readonly workspaceId: string;\n readonly installationId: string;\n readonly apiHost: string;\n private readonly fetchImpl: typeof fetch;\n private readonly storageKey: string;\n private current: SagepilotInstallationSession | null = null;\n private anonymousId: string | null = null;\n private pending: Promise<SagepilotInstallationSession> | null = null;\n private startup: Promise<SagepilotInstallationSession> | null = null;\n private generation = 0;\n private uploadRevision = 0;\n private transitioning = false;\n private readonly owners = new Map<string, SagepilotInstallationSession>();\n private readonly requests = new Set<AbortController>();\n\n /** Validates the public installation binding without treating it as customer authentication. */\n constructor(private readonly options: SagepilotInstallationOptions) {\n const parts = options.key.split(\":\");\n if (parts.length !== 2 || !parts.every(value => UUID.test(value))) throw new Error(\"SDK key must be workspace_id:installation_id UUIDs.\");\n this.workspaceId = parts[0]!.toLowerCase(); this.installationId = parts[1]!.toLowerCase();\n const host = safeURL(options.apiHost ?? \"https://api.sagepilot.ai\");\n if (host.pathname !== \"/\") throw new Error(\"SDK apiHost must be a gateway origin.\");\n this.apiHost = host.origin;\n this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.storageKey = `sagepilot:sdk-session:${this.workspaceId}:${this.installationId}`;\n }\n\n /** Returns a copy of the active anonymous session without allowing mutation of capture ownership. */\n session(): SagepilotInstallationSession | null { return this.current ? { ...this.current } : null; }\n\n /** The merchant route owns the cookie path and forwards only the visitor cookie. */\n get visitorCookiePath(): string { return `/sagepilot/visitor/${this.workspaceId}/${this.installationId}`; }\n\n /** Resolves browser continuity on the storefront without sending an upload token or contact data. */\n async syncVisitorCookie(anonymousId: string | null, analyticsAllowed: boolean, popupCompleted: boolean): Promise<SagepilotBrowserVisitor> {\n if (this.options.platform !== \"web\" || typeof location === \"undefined\") throw new Error(\"Visitor cookies require a website.\");\n const endpoint = safeURL(location.origin + this.visitorCookiePath);\n const value = await this.request(endpoint.href, {\n method: \"POST\",\n mode: \"same-origin\",\n credentials: \"same-origin\",\n body: JSON.stringify({ analytics_allowed: analyticsAllowed, anonymous_id: anonymousId, popup_completed: popupCompleted }),\n }, 2500) as SagepilotBrowserVisitor;\n if (!value || (value.anonymous_id !== null && (typeof value.anonymous_id !== \"string\" || !VISITOR_ID.test(value.anonymous_id))) ||\n typeof value.popup_completed !== \"boolean\" || typeof value.restored !== \"boolean\") {\n throw new Error(\"Invalid SDK visitor cookie response.\");\n }\n return value;\n }\n\n /** Reports whether this runtime still holds matching capture authority for a queued owner. */\n hasCaptureOwner(owner: SagepilotInstallationOwner): boolean {\n const session = this.owners.get(owner.session_id) ?? this.current;\n return !!session && session.session_id === owner.session_id && session.customer_id === owner.customer_id;\n }\n\n /** Restores only the requested browser/device owner, then obtains a fresh server-authorized session. */\n async start(anonymousId: string): Promise<SagepilotInstallationSession> {\n if (!anonymousId.trim() || anonymousId.length > 128) throw new Error(\"SDK anonymous ID must contain 1–128 characters.\");\n if (this.anonymousId && this.anonymousId !== anonymousId) throw new Error(\"Destroy this SDK client before changing its anonymous owner.\");\n this.anonymousId = anonymousId;\n if (this.startup) return this.startup;\n const generation = this.generation;\n const startup = (async () => {\n if (!this.current && this.options.storage) {\n let restored: SagepilotInstallationSession | null = null;\n try {\n const raw = await this.options.storage.getItem(this.storageKey);\n if (raw && raw.length <= 16384) restored = this.validateSession(JSON.parse(raw));\n const previous = await this.options.storage.getItem(this.storageKey + \":owners\");\n if (previous && previous.length <= 65536) {\n const entries: unknown = JSON.parse(previous);\n if (Array.isArray(entries) && entries.length <= 4) for (const entry of entries) {\n const owner = this.validateSession(entry); this.owners.set(owner.session_id, owner);\n }\n }\n } catch { /* Corrupt or unavailable optional storage cannot select another owner. */ }\n if (generation !== this.generation) throw new Error(\"SDK session restoration was cancelled.\");\n this.current = restored;\n }\n if (generation !== this.generation) throw new Error(\"SDK session startup was cancelled.\");\n return this.refresh(true);\n })().finally(() => { if (this.startup === startup) this.startup = null; });\n this.startup = startup;\n return startup;\n }\n\n /** Renews the owner or, when allowed for web capture, starts fresh after an expired browser session. */\n async refresh(recoverAnonymous = false): Promise<SagepilotInstallationSession> {\n if (this.pending) return this.pending;\n if (!this.anonymousId) throw new Error(\"Start the installation client before renewing it.\");\n const generation = this.generation, prior = this.current;\n const pending = (async () => {\n let renewing = prior;\n let value: unknown;\n try { value = await this.requestSession(prior?.session_token); }\n catch (error) {\n if (!recoverAnonymous || !prior || this.options.platform !== \"web\" || generation !== this.generation ||\n !(error instanceof SagepilotInstallationError) || error.status !== 401) throw error;\n renewing = null;\n value = await this.requestSession();\n }\n const next = this.validateSession(value);\n if (generation !== this.generation) throw new Error(\"SDK session startup was cancelled.\");\n if (renewing && (next.session_id !== renewing.session_id || next.customer_id !== renewing.customer_id) ||\n !renewing && (next.customer_id !== null || next.session_id === prior?.session_id)) {\n throw new Error(\"SDK session renewal changed capture ownership.\");\n }\n if (prior && !renewing) this.owners.delete(prior.session_id);\n this.current = next;\n this.remember(next);\n try { await this.options.storage?.setItem(this.storageKey, JSON.stringify(next)); } catch { /* Event journals report their own storage gaps. */ }\n return { ...next };\n })().finally(() => { if (this.pending === pending) this.pending = null; });\n this.pending = pending;\n return pending;\n }\n\n /** Requests policy for this browser or device with the original token when renewing. */\n private requestSession(token?: string): Promise<unknown> {\n return this.request(`${this.apiHost}/platform-api/v1/sdk/sessions`, {\n method: \"POST\",\n headers: token ? { Authorization: `Bearer ${token}` } : {},\n body: JSON.stringify({ key: `${this.workspaceId}:${this.installationId}`, anonymous_id: this.anonymousId, platform: this.options.platform,\n ...(this.options.appId ? { app_id: this.options.appId } : {}) })\n });\n }\n\n /** Supplies a short-lived native upload authorization only for the original capture owner. */\n async authorize(owner: SagepilotInstallationOwner): Promise<{ url: string; headers: Record<string, string> }> {\n let session = this.owners.get(owner.session_id) ?? this.current;\n if (!session || owner.customer_id !== session.customer_id || owner.session_id !== session.session_id) throw new Error(\"SDK capture ownership changed.\");\n if (Date.parse(session.expires_at) - Date.now() < 60000) {\n if (session.session_id === this.current?.session_id) session = await this.refresh();\n else {\n const original = session;\n session = this.validateSession(await this.requestSession(session.session_token));\n if (session.session_id !== original.session_id || session.customer_id !== original.customer_id) throw new Error(\"Historical capture ownership changed.\");\n this.remember(session);\n }\n }\n if (!session.collection_enabled || owner.session_id !== session.session_id || owner.customer_id !== session.customer_id) throw new Error(\"SDK collection is disabled or its owner changed.\");\n return { url: session.ingestion_url, headers: { Authorization: `Bearer ${session.session_token}`,\n \"Content-Type\": \"application/json\", \"X-Sagepilot-Sdk-Name\": this.options.sdk.name, \"X-Sagepilot-Sdk-Version\": this.options.sdk.version } };\n }\n\n /** Posts one bounded immutable batch; collectors own backoff and retain missing/retryable receipts. */\n async upload(observations: SagepilotSDKObservation[], owner: SagepilotInstallationOwner): Promise<SagepilotInstallationReceipt> {\n if (!observations.length || observations.length > 100) throw new Error(\"SDK batches require 1–100 observations.\");\n for (const item of observations) {\n if (item.owner.session_id !== owner.session_id || item.owner.customer_id !== owner.customer_id) throw new Error(\"SDK batch mixes capture ownership.\");\n }\n const revision = this.uploadRevision;\n const auth = await this.authorize(owner);\n if (revision !== this.uploadRevision) throw new Error(\"SDK upload was cancelled.\");\n const body = JSON.stringify({ schema_version: 1, observations });\n if (new TextEncoder().encode(body).byteLength > 128 * 1024) throw new Error(\"SDK batch exceeds the upload limit.\");\n return validateSagepilotInstallationReceipt(await this.request(auth.url, { method: \"POST\", headers: auth.headers, body }), observations.map(item => item.event_id));\n }\n\n /** Submits explicit popup contacts independently from ordinary observation payloads. */\n async submitContact(input: SagepilotContactInput): Promise<SagepilotContactResult> {\n if (!UUID.test(input.submission_id) || !Number.isSafeInteger(input.popup_revision) || input.popup_revision < 1 || typeof input.marketing_consent !== \"boolean\") throw new Error(\"Invalid popup submission.\");\n const result = await this.authenticated(\"/contact\", input) as SagepilotContactResult;\n if (!result || ![\"recorded\", \"verification_required\"].includes(result.status) ||\n result.status === \"verification_required\" && (!result.challenge_id || !UUID.test(result.challenge_id) || !Number.isFinite(Date.parse(result.expires_at ?? \"\")))) throw new Error(\"Invalid popup submission response.\");\n return result;\n }\n\n /** Adopts customer authority only from the server's completed verification operation. */\n async verifyContact(challengeId: string, code: string): Promise<SagepilotInstallationSession> {\n if (!UUID.test(challengeId) || !/^\\d{6}$/.test(code)) throw new Error(\"Enter the six-digit verification code.\");\n return this.transition(\"/contact/verify\", { challenge_id: challengeId, code }, true);\n }\n\n /** Revokes the current identified grant and establishes a fresh anonymous capture owner. */\n async logout(): Promise<SagepilotInstallationSession> { return this.transition(\"/logout\", {}, false); }\n\n /** Keeps a bounded credential cache separate from observations so old anonymous batches retain their owner. */\n private remember(session: SagepilotInstallationSession): void {\n this.owners.set(session.session_id, { ...session });\n while (this.owners.size > 4) this.owners.delete(this.owners.keys().next().value!);\n try { void Promise.resolve(this.options.storage?.setItem(this.storageKey + \":owners\", JSON.stringify([...this.owners.values()]))).catch(() => {}); } catch { /* Optional credential storage may be unavailable. */ }\n }\n\n /** Uses the current scoped credential for identity operations without attaching it to event records. */\n private async authenticated(path: string, body: unknown): Promise<unknown> {\n const prior = this.current;\n if (!prior) throw new Error(\"Start the installation client first.\");\n if (Date.parse(prior.expires_at) - Date.now() < 60000) await this.refresh();\n if (this.current?.session_id !== prior.session_id) throw new Error(\"SDK identity session changed.\");\n return this.request(`${this.apiHost}/platform-api/v1/sdk${path}`, { method: \"POST\", headers: { Authorization: `Bearer ${this.current.session_token}` }, body: JSON.stringify(body) });\n }\n\n /** Serializes explicit ownership transitions and rejects unrelated or stale server responses. */\n private async transition(path: string, body: unknown, identified: boolean): Promise<SagepilotInstallationSession> {\n if (this.transitioning) throw new Error(\"An SDK identity operation is already running.\");\n this.transitioning = true;\n const generation = this.generation, prior = this.current;\n try {\n const next = this.validateSession(await this.authenticated(path, body));\n if (generation !== this.generation || !prior || next.session_id === prior.session_id || (identified ? next.customer_id === null : next.customer_id !== null)) throw new Error(\"Invalid SDK identity transition.\");\n this.generation++; this.cancelPending(); this.pending = null;\n if (path === \"/logout\") this.owners.delete(prior.session_id);\n else this.remember(prior);\n this.current = next; this.remember(next);\n try { await this.options.storage?.setItem(this.storageKey, JSON.stringify(next)); } catch { /* Optional session storage is isolated from capture. */ }\n return { ...next };\n } finally { this.transitioning = false; }\n }\n\n /** Cancels requests on permission/ownership boundaries while preserving the current session for safe renewal. */\n cancelPending(): void { this.uploadRevision++; for (const controller of this.requests) controller.abort(); }\n\n /** Fences in-flight session adoption and stops all outstanding requests. */\n destroy(): void { this.generation++; this.cancelPending(); this.current = null; this.anonymousId = null; this.pending = null; this.startup = null; this.owners.clear(); }\n\n /** Rejects foreign, identified or malformed session responses before credentials are used. */\n private validateSession(value: unknown): SagepilotInstallationSession {\n const session = value as SagepilotInstallationSession;\n if (!session || session.workspace_id !== this.workspaceId || session.installation_id !== this.installationId ||\n session.platform !== this.options.platform || session.anonymous_id !== this.anonymousId || (session.customer_id !== null && (typeof session.customer_id !== \"string\" || !UUID.test(session.customer_id))) ||\n !UUID.test(session.session_id) || typeof session.session_token !== \"string\" || session.session_token.length > 16384 || !session.session_token ||\n !Number.isFinite(Date.parse(session.expires_at)) || typeof session.collection_enabled !== \"boolean\" ||\n (session.visitor_cookie_enabled !== undefined && typeof session.visitor_cookie_enabled !== \"boolean\") ||\n !Number.isSafeInteger(session.revision)) {\n throw new Error(\"SDK session response has invalid scope or ownership.\");\n }\n const url = safeURL(session.ingestion_url);\n if (url.pathname !== \"/events/v1/sdk/observations\") throw new Error(\"SDK ingestion route is invalid.\");\n return { ...session };\n }\n\n /** Performs bounded SDK HTTP requests without retrying mutations or following credential redirects. */\n private async request(url: string, init: RequestInit, timeoutMs = 15000): Promise<unknown> {\n const controller = new AbortController(); this.requests.add(controller);\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const headers = new Headers(init.headers);\n headers.set(\"Content-Type\", \"application/json\");\n headers.set(\"X-Sagepilot-Sdk-Name\", this.options.sdk.name);\n headers.set(\"X-Sagepilot-Sdk-Version\", this.options.sdk.version);\n const response = await this.fetchImpl(url, { ...init, headers, signal: controller.signal, redirect: \"error\", credentials: init.credentials ?? \"omit\" });\n if (!response.ok) {\n void response.body?.cancel().catch(() => {});\n throw new SagepilotInstallationError(\"invalid_response\", `SDK request failed with HTTP ${response.status}.`, { status: response.status });\n }\n if (Number(response.headers.get(\"content-length\") ?? 0) > 65536) throw new Error(\"SDK response exceeds limit.\");\n let text = \"\";\n if (response.body?.getReader) {\n const reader = response.body.getReader(), decoder = new TextDecoder(); let bytes = 0;\n try {\n for (;;) {\n const part = await reader.read(); if (part.done) break;\n bytes += part.value.byteLength;\n if (bytes > 65536) { await reader.cancel(); throw new Error(\"SDK response exceeds limit.\"); }\n text += decoder.decode(part.value, { stream: true });\n }\n text += decoder.decode();\n } finally { reader.releaseLock(); }\n } else {\n text = await response.text();\n if (text.length > 65536) throw new Error(\"SDK response exceeds limit.\");\n }\n return JSON.parse(text);\n } catch (error) {\n if (controller.signal.aborted || error instanceof TypeError) {\n throw new SagepilotInstallationError(\"network_error\", \"SDK request could not reach the server.\", { cause: error });\n }\n throw error;\n } finally { clearTimeout(timeout); this.requests.delete(controller); }\n }\n}\n\n/** Creates the shared anonymous installation-session transport without initializing chat or channels. */\nexport function createSagepilotInstallationClient(options: SagepilotInstallationOptions): SagepilotInstallationClient {\n return new SagepilotInstallationClient(options);\n}\n","{\n \"name\": \"@sagepilot-ai/web-events-addon\",\n \"version\": \"0.2.3\",\n \"description\": \"Optional automatic browser observations for Sagepilot SDK installations\",\n \"license\": \"UNLICENSED\",\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n },\n \"./sagepilot-web-events.js\": \"./dist/sagepilot-web-events.global.js\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"sideEffects\": [\n \"./dist/sagepilot-web-events.global.js\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"typecheck\": \"tsc --noEmit\",\n \"prepublishOnly\": \"npm run typecheck && npm run build\"\n },\n \"devDependencies\": {\n \"@sagepilot-ai/sdk-installation-client\": \"0.0.0\",\n \"tsup\": \"^8.3.5\",\n \"typescript\": \"^5.7.2\"\n }\n}\n","export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };\ntype Projection = { fields: Json[]; structure: Json[]; limited: boolean };\nconst sensitive = /password|passwd|secret|token|authorization|cookie|session|email|phone|contact|address|card|payment|cvv|ssn|dob|birth|customer|user|account|person|profile|name|description|message|content|text|search|query/i;\nconst compact = /^[A-Za-z0-9_.:-]{1,128}$/;\nconst routes = new Map<string, Promise<string | null>>();\n\n/** Projects only bounded, typed, non-contact JSON facts; arbitrary strings are omitted. */\nexport function project(value: unknown): Projection {\n const output: Projection = { fields: [], structure: [], limited: false };\n let budget = 256;\n /** Visits plain JSON containers within shared depth, node and scalar limits. */\n function visit(input: unknown, path: string, depth: number): void {\n if (--budget < 0 || depth > 8 || output.fields.length >= 48) { output.limited = true; return; }\n if (input === null || typeof input === \"boolean\" || typeof input === \"number\") {\n if (typeof input === \"number\" && (!Number.isFinite(input) || Math.abs(input) > Number.MAX_SAFE_INTEGER)) return;\n output.fields.push({ path, type: input === null ? \"null\" : typeof input, value: input }); return;\n }\n if (typeof input === \"string\") {\n // Numeric product references retain precision; general phone-like strings and long credentials are omitted.\n const numericProductReference = /\\.(?:product_id|variant_id|sku)$/.test(path) && /^\\d{1,20}$/.test(input);\n if (numericProductReference || compact.test(input) && !/^\\+?\\d{7,}$/.test(input) && !/^[A-Za-z0-9_-]{32,}$/.test(input)) output.fields.push({ path, type: \"string\", value: input });\n else output.fields.push({ path, type: \"string\", omitted: \"privacy_or_size\" });\n return;\n }\n if (Array.isArray(input)) {\n output.structure.push({ path, type: \"array\" });\n for (let index = 0; index < Math.min(input.length, 10); index++) visit(input[index], `${path}[${index}]`, depth + 1);\n if (input.length > 10) output.limited = true;\n return;\n }\n if (!input || typeof input !== \"object\" || Object.getPrototypeOf(input) !== Object.prototype) return;\n output.structure.push({ path, type: \"object\" });\n const keys: string[] = [];\n for (const key in input) { if (Object.prototype.hasOwnProperty.call(input, key)) keys.push(key); if (keys.length > 32) break; }\n keys.sort();\n if (keys.length > 32) output.limited = true;\n for (const key of keys.slice(0, 32)) {\n if (!/^[A-Za-z_][A-Za-z0-9_]{0,47}$/.test(key) || sensitive.test(key)) continue;\n const descriptor = Object.getOwnPropertyDescriptor(input, key);\n if (descriptor && \"value\" in descriptor) visit(descriptor.value, `${path}.${key}`, depth + 1);\n }\n }\n visit(value, \"$\", 0);\n return output;\n}\n\n/** Parses only a bounded existing JSON string; it never reads an application stream. */\nexport function projectText(value: unknown): Projection | null {\n if (typeof value !== \"string\" || value.length > 65536 || !/^\\s*[\\[{]/.test(value.slice(0, 64))) return null;\n try { return project(JSON.parse(value)); } catch { return null; }\n}\n\n/** Produces bounded operation fingerprints without URL credentials, query, fragments or path values. */\nexport function routeFor(input: string): Promise<string | null> {\n if (input.length > 2048) return Promise.resolve(null);\n let url: URL;\n try { url = new URL(input, globalThis.location?.href); } catch { return Promise.resolve(null); }\n if (!/^https?:$/.test(url.protocol) || url.username || url.password) return Promise.resolve(null);\n const cacheKey = url.origin + url.pathname;\n const existing = routes.get(cacheKey);\n if (existing) return existing;\n /** Hashes alphabetic operation segments and masks likely dynamic identifiers. */\n const fingerprint = (async () => {\n if (!globalThis.crypto?.subtle) return null;\n const segments: string[] = [];\n for (const segment of url.pathname.split(\"/\").filter(Boolean).slice(0, 12)) {\n if (/^v\\d{1,2}$/i.test(segment)) { segments.push(segment.toLowerCase()); continue; }\n if (!/^[A-Za-z_-]{1,64}$/.test(segment)) { segments.push(\":id\"); continue; }\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(segment));\n segments.push(\":op_\" + Array.from(new Uint8Array(digest)).slice(0, 8).map(byte => byte.toString(16).padStart(2, \"0\")).join(\"\"));\n }\n return url.origin + \"/\" + segments.join(\"/\");\n })().catch(() => null);\n if (routes.size >= 128) routes.delete(routes.keys().next().value!);\n routes.set(cacheKey, fingerprint);\n return fingerprint;\n}\n","import type { Json } from \"./projection\";\n\nexport type ProductSnapshot = Record<string, Json> & { metadata: {\n resolution: \"resolved\" | \"unresolved\" | \"ambiguous\"; identifiers: Record<string, string>;\n variant_identifiers: Record<string, string>; attributes: Record<string, Json>;\n provenance: { source: string; source_ref: string; match: string }; limited: boolean;\n} };\nexport type ProductMatch = { snapshot: ProductSnapshot; product_ref: string };\ntype Entry = { snapshot: ProductSnapshot; ref: string; expires: number; images: string[]; rawImages?: string[]; url?: string; sku?: string; variant?: string; group?: { url?: string; name: string }; blocked?: boolean; ids?: string[] };\nconst privateKey = /pass|secret|token|auth|cookie|session|customer|buyer|user|account|profile|email|phone|mobile|contact|address|payment|credit|cvv|order|personal|customiz|monogram|option|review|message|comment|__proto__|constructor|prototype/i;\nconst identifier = /^(?:@?id|schema_product(?:ID|SKU)|productGroup(?:ID|SKU)|(?:product[_-]?)?sku|(?:product|catalog(?:ue)?|variant|item|article|part|model)[_-]?(?:id|code|number|ref)|mpn|gtin(?:8|12|13|14)?|upc|ean|isbn|reference|code)$/i;\nconst aliases = { product_id: /^(?:product[_-]?id|id)$/i, variant_id: /^(?:variant[_-]?id)$/i, sku: /^(?:product[_-]?)?sku$/i };\nconst publicField = /^(?:@type|@id|name|title|product_name|slug|id|productGroupID|product[_-]?(?:id|sku|url)|variant[_-]?id|sku|mpn|gtin\\d*|url|image|images|image_url|imageUrl|offers|variants|hasVariant|price|priceValue|sale_price|price[_-]?Currency|currency|currencyId|currencyFormat|brand|category|color|size|material|availability|stockRemaining|available|selected|selectedVariantId)$/i;\n/** Normalizes public labels for exact comparisons; no fuzzy title match can select an identity. */\nfunction normalized(value: unknown): string { return typeof value === \"string\" ? value.normalize(\"NFKC\").trim().toLowerCase().replace(/\\s+/g, \" \") : \"\"; }\n\n/** Removes only a terminal displayed price from an otherwise exact commerce action label. */\nexport function commerceAction(value: string): string {\n const label = value.normalize(\"NFKC\").trim();\n return label.replace(/\\s*[·|–—-]\\s*(?:₹|\\$|€|£|INR|USD|EUR|GBP)\\s*(?:\\d{1,8}|\\d{1,3}(?:,\\d{3}){1,2}|\\d{1,2}(?:,\\d{2}){1,2},\\d{3})(?:\\.\\d{1,2})?\\s*$/i, \"\").trim();\n}\n\n/** Compares an explicitly typed Shopify variant GID with its declared URL selector without inventing an ID. */\nfunction sameVariant(left: string | undefined | null, right: string | undefined | null): boolean {\n return !!left && !!right && (left === right || left.replace(/^gid:\\/\\/shopify\\/ProductVariant\\/(\\d+)$/, \"$1\") === right.replace(/^gid:\\/\\/shopify\\/ProductVariant\\/(\\d+)$/, \"$1\"));\n}\n\n/** Reads only native commerce identifier fields, never customer or general form values. */\nfunction nativeForms(): { form: Element; product?: string; variant: string }[] | null {\n const result: { form: Element; product?: string; variant: string }[] = [], forms = [...document.querySelectorAll(\"form[action]\")];\n if (forms.length > 32) return null;\n for (const form of forms) {\n const action = publicURL(form.getAttribute(\"action\"));\n if (!action || new URL(action).origin !== location.origin || !/\\/cart\\/add\\/?$/.test(new URL(action).pathname)) continue;\n const inputs = [...form.querySelectorAll('input[type=\"hidden\"][name=\"id\"]')], products = [...form.querySelectorAll('input[type=\"hidden\"][name=\"product-id\"]')];\n if (inputs.length !== 1 || products.length > 1) continue;\n const variant = id((inputs[0] as HTMLInputElement).value ?? inputs[0]!.getAttribute(\"value\"));\n const product = id(products.length ? (products[0] as HTMLInputElement).value ?? products[0]!.getAttribute(\"value\") : form.closest(\"[data-product-id]\")?.getAttribute(\"data-product-id\"));\n if (variant) result.push({ form, product, variant });\n }\n return result;\n}\n\n/** Reads one explicitly labeled public product identifier without copying arbitrary page text. */\nfunction labeledProductID(): string | undefined {\n const labels = [...document.querySelectorAll(\"span,dt,th,label\")], values: string[] = []; if (labels.length > 1024) return;\n for (const label of labels) {\n const value = label.nextElementSibling;\n if (label.childElementCount || normalized(label.textContent) !== \"product id:\" || !value || value.childElementCount || [label, value].some(node => node.closest('header,footer,form,dialog,[role=\"dialog\"],[hidden],[aria-hidden=\"true\"],[data-sagepilot-popup],[itemprop=\"review\"],[itemtype$=\"/Review\"],[data-review-id]'))) continue;\n const product = id(value.textContent?.trim()); if (product) values.push(product);\n }\n return values.length === 1 ? values[0] : undefined;\n}\n\n/** Accepts public product URLs without signed queries, credentials, fragments or script schemes. */\nfunction publicURL(value: unknown, base = location.href, image = false): string | undefined {\n if (typeof value !== \"string\" || value.length > 1024) return;\n try {\n const url = new URL(value, base);\n const keys = [...url.searchParams.keys()];\n if (url.username || url.password || /[<>\\x00-\\x1f\\x7f@]/.test(decodeURIComponent(url.href)) || new Set(keys).size !== keys.length || keys.some(key => /token|signature|auth|credential|password|secret|policy|expires|x-amz|^sig$|^key$/i.test(key))) return;\n if (image && /\\/_next\\/image$/.test(url.pathname) && keys.every(key => key === \"url\" || key === \"w\" && /^\\d{1,5}$/.test(url.searchParams.get(key)!) || key === \"q\" && /^\\d{1,3}$/.test(url.searchParams.get(key)!) && Number(url.searchParams.get(key)) <= 100)) return publicURL(url.searchParams.get(\"url\"), base, true);\n if (image && keys.length) {\n if (!/\\.(?:jpe?g|png|webp|avif|gif|svg)$/i.test(url.pathname) || !keys.every(key => {\n const value = url.searchParams.get(key)!;\n return /^(?:w|h|width|height)$/.test(key) ? /^\\d{1,5}$/.test(value) && Number(value) > 0\n : /^(?:q|quality)$/.test(key) ? /^\\d{1,3}$/.test(value) && Number(value) > 0 && Number(value) <= 100\n : key === \"v\" ? /^\\d{1,20}$/.test(value)\n : key === \"dpr\" ? /^(?:[1-7](?:\\.\\d{1,2})?|0\\.[1-9]\\d?|8)$/.test(value)\n : /^(?:f|format)$/.test(key) ? /^(?:jpe?g|png|webp|avif|gif|svg|xxs|xs|s|m|l|xl|xxl|u|xu)$/.test(value)\n : key === \"fit\" ? /^(?:cover|contain|fill|inside|outside|max|crop)$/.test(value)\n : key === \"auto\" ? /^(?:format|compress|format,compress|compress,format)$/.test(value)\n : key === \"crop\" && /^(?:center|faces|top|bottom|left|right)$/.test(value);\n })) return;\n url.search = \"\";\n }\n if (!image && keys.length && (keys.length > 1 || !keys.every(key => /^(?:variant|variant_id)$/.test(key) && !!id(url.searchParams.get(key))))) return;\n if (!image && /^(?:#content|#product|#variant)?$/.test(url.hash)) url.hash = \"\";\n if ((url.protocol === \"https:\" || url.protocol === \"http:\" && [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(url.hostname)) &&\n !url.username && !url.password && !url.hash && !/[<>\\x00-\\x1f\\x7f@]/.test(decodeURIComponent(url.href))) return url.href;\n } catch { /* Unusable source evidence stays unavailable. */ }\n}\n\n/** Removes only standard analytics attribution keys from document identity without retaining their values. */\nfunction documentURL(): string | undefined {\n try {\n const url = new URL(location.href);\n for (const key of [...url.searchParams.keys()]) if (/^utm_(?:source|medium|campaign|term|content|id|source_platform|creative_format|marketing_tactic)$/.test(key)) url.searchParams.delete(key);\n return publicURL(url.href);\n } catch { return; }\n}\n\n/** Excludes private account/order resources before product body access or projection. */\nfunction productSourceURL(value: string): string | undefined {\n const url = publicURL(value);\n return url && !/(?:^|[/_.-])(?:customers?|buyers?|users?|accounts?|profiles?|orders?|checkout|auth|login|sessions?|private|tokens?|contacts?|addresses|payments?)(?=[/_.-]|$)/i.test(decodeURIComponent(new URL(url).pathname)) ? url : undefined;\n}\n\n/** Screens product text before retaining it; catalog context does not authorize customer data. */\nfunction scalar(value: unknown): Json | undefined {\n if (value === null || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") return Number.isFinite(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER ? value : undefined;\n if (typeof value !== \"string\" || value.length > 256 || /[<>\\x00-\\x1f\\x7f]|@|https?:|\\+?\\d[\\d\\s().-]{5,}\\d|[A-Za-z0-9_-]{32,}|\\b(?:bearer|sk_live_|sk_test_|ghp_)|personalized|personalised|monogram|recommended for|your name/i.test(value.normalize(\"NFKC\"))) return;\n return value;\n}\n\n/** Preserves exact identifier strings and never claims rounded parsed numbers as original IDs. */\nfunction id(value: unknown): string | undefined {\n if (typeof value === \"number\") return Number.isSafeInteger(value) ? String(value) : undefined;\n return typeof value === \"string\" && /^[A-Za-z0-9_:/+=.-]{1,128}$/.test(value) && !/^(?:bearer|sk_live_|sk_test_|ghp_|eyJ[A-Za-z0-9_-]+\\.)/i.test(value) ? value : undefined;\n}\n\n/** Reads only declared public asset and SKU evidence for both accepted and rejected product rows. */\nfunction links(facts: Record<string, unknown>, base: string): Pick<Entry, \"url\" | \"images\" | \"rawImages\" | \"sku\"> {\n const image = facts.image_url ?? facts.imageUrl ?? facts.image ?? facts.images, offers = Array.isArray(facts.offers) ? facts.offers : [facts.offers];\n const assets = (Array.isArray(image) ? image : image === undefined ? [] : [image]), rawImages: string[] = []; let complete = assets.length <= 16;\n for (const value of assets.slice(0, 16)) {\n const uri = value && typeof value === \"object\" ? (value as Record<string, unknown>).url ?? (value as Record<string, unknown>).contentUrl : value;\n if (typeof uri === \"string\" && /^(?:https?:\\/\\/|\\/)/i.test(uri) && publicURL(uri, base, true)) rawImages.push(new URL(uri, base).href); else complete = false;\n }\n const urls = offers.map(value => value && typeof value === \"object\" ? publicURL((value as Record<string, unknown>).url, base) : undefined).filter(Boolean);\n return { rawImages: complete ? rawImages : undefined, url: publicURL(facts.url ?? facts.product_url ?? facts.productUrl ?? (typeof facts[\"@id\"] === \"string\" && /[/?]/.test(facts[\"@id\"]) ? facts[\"@id\"] : undefined), base) ?? (urls.length === offers.length && new Set(urls).size === 1 ? urls[0] : undefined), sku: id(facts.sku ?? facts.productSku ?? facts.product_sku),\n images: (Array.isArray(image) ? image.slice(0, 8) : [image]).map(value => {\n const uri = value && typeof value === \"object\" ? (value as Record<string, unknown>).url ?? (value as Record<string, unknown>).contentUrl : value;\n return typeof uri === \"string\" && /^(?:https?:\\/\\/|\\/)/i.test(uri) ? publicURL(uri, base, true) : undefined;\n }).filter((value): value is string => !!value) };\n}\n\n/** Parses only existing bounded JSON text, preserving identifier number lexemes when supported. */\nexport function parseProductJSON(value: string, limit = 262144): unknown {\n if (value.length > limit || new TextEncoder().encode(value).length > limit) return null;\n try {\n return JSON.parse(value, (key: string, item: unknown, context?: { source?: string }) => {\n if (identifier.test(key) && typeof item === \"number\") return context?.source && /^-?\\d+$/.test(context.source) ? context.source : id(item);\n return item;\n });\n } catch { return null; }\n}\n\n/** Parses framed public Flight JSON while skipping opaque/text payloads by their exact UTF-8 byte length. */\nfunction flightRows(value: string): unknown[] {\n // shortcut: public Flight framing is implementation-specific; unknown framing stays unresolved until a measured new format is supported.\n const bytes = new TextEncoder().encode(value), decoder = new TextDecoder(), rows: unknown[] = [];\n let offset = 0;\n while (offset < bytes.length) {\n if (bytes[offset] === 10) { offset++; continue; }\n const colon = bytes.indexOf(58, offset);\n if (colon < offset || colon - offset > 16 || !/^[\\da-f]*$/i.test(decoder.decode(bytes.subarray(offset, colon)))) return [];\n const start = colon + 1, comma = bytes.indexOf(44, start), tag = String.fromCharCode(bytes[start]!);\n if (/^[A-Za-z]$/.test(tag) && comma > start + 1 && comma - start < 16 && /^[\\da-f]+$/i.test(decoder.decode(bytes.subarray(start + 1, comma)))) {\n const size = parseInt(decoder.decode(bytes.subarray(start + 1, comma)), 16);\n if (comma + 1 + size > bytes.length) return []; offset = comma + 1 + size; continue;\n }\n const newline = bytes.indexOf(10, start), end = newline < 0 ? bytes.length : newline;\n if (bytes[start] === 91 || bytes[start] === 123) { const row = parseProductJSON(decoder.decode(bytes.subarray(start, end))); if (row === null) return []; rows.push(row); }\n offset = end + 1;\n }\n return rows;\n}\n\n/** Projects only independently bound product identifier records from inert indexed JSON; framework state is never restored. */\nfunction indexedProducts(graph: unknown, source: string, title: string, schemas: Record<string, unknown>[]): Record<string, unknown>[] {\n if (!Array.isArray(graph) || graph.length > 8192 || !Array.isArray(graph[0]) || graph[0][0] !== \"ShallowReactive\") return [];\n const values = graph;\n /** Reads one in-range integer reference without recursive graph expansion or framework revivers. */\n function ref(index: unknown): unknown { return typeof index === \"number\" && Number.isInteger(index) && index >= 0 && index < values.length ? values[index] : undefined; }\n const tail = new URL(source).pathname.split(\"/\").filter(Boolean).pop(), result: Record<string, unknown>[] = [];\n for (const row of graph) {\n if (!row || typeof row !== \"object\" || Array.isArray(row) || !Object.prototype.hasOwnProperty.call(row, \"productVariants\") || normalized(ref(row.name)) !== title) continue;\n const variants = ref(row.productVariants); if (!Array.isArray(variants) || variants.length > 16) return [];\n for (const index of variants) {\n const value = ref(index); if (!value || typeof value !== \"object\" || Array.isArray(value)) return []; const variant = value as Record<string, unknown>;\n const product_id = id(ref(row.id)), variant_id = id(ref(variant.id)), sku = id(ref(variant.sku)), name = ref(variant.name);\n if (!product_id || !variant_id || !sku || variant_id !== tail || normalized(name) !== title) continue;\n const matching = schemas.filter(value => {\n const offers = Array.isArray(value.offers) ? value.offers : [value.offers], declared = [value.url, value.product_url, value.productUrl, value[\"@id\"], ...offers.map(row => row && typeof row === \"object\" ? row.url : undefined)].filter(uri => uri !== undefined);\n return declared.every(uri => publicURL(uri, source) === source) && normalized(value.name) === title && [variant_id, sku].includes(String(value.sku));\n });\n if (matching.length !== 1) return [];\n result.push({ product_id, variant_id, sku, name, url: source, image: links(matching[0]!, source).images[0], schema_productSKU: String(matching[0]!.sku) });\n }\n }\n return result.length === 1 ? result : [];\n}\n\n/** Projects one confirmed product and optional selected variant into common fields plus safe metadata. */\nfunction project(row: Record<string, unknown>, source: string, source_ref: string, variant?: Record<string, unknown>): Entry | null {\n if (Array.isArray(row.offers) && row.offers.length > 16 || Array.isArray(variant?.offers) && variant.offers.length > 16) return null;\n const identifiers: Record<string, string> = {}, variant_identifiers: Record<string, string> = {}, attributes: Record<string, Json> = {};\n let limited = false;\n for (const [record, ids] of [[row, identifiers], ...(variant ? [[variant, variant_identifiers]] : [])] as [Record<string, unknown>, Record<string, string>][]) {\n const keys = Object.keys(record); if (keys.length > 48) limited = true;\n for (const key of keys.slice(0, 48)) {\n if (!/^[A-Za-z_@][A-Za-z0-9_@-]{0,63}$/.test(key) || privateKey.test(key) || [\"variants\", \"offers\", \"@type\", \"@context\"].includes(key) || source !== \"catalog_response\" && !identifier.test(key) && !publicField.test(key)) continue;\n if (record === row && variant && /^(?:image|images|image_url|imageUrl)$/.test(key) && links(variant, source_ref).images.length) continue;\n const value = record[key];\n if (identifier.test(key)) {\n const exact = id(value), target = record === row && /^variant[_-]?(?:id|code|number|ref)$/i.test(key) ? variant_identifiers : ids;\n if (exact !== undefined && Object.keys(target).length < 32) target[key] = exact;\n else if (exact !== undefined) limited = true;\n continue;\n }\n if (Object.keys(attributes).length >= 32) { limited = true; continue; }\n if (Array.isArray(value)) {\n if (value.length > 16) { limited = true; continue; }\n const projected = value.map(scalar); if (projected.every(item => item !== undefined)) attributes[key] = projected as Json[];\n } else { const projected = scalar(value); if (projected !== undefined) attributes[key] = projected; }\n }\n }\n const snapshot: ProductSnapshot = { metadata: { resolution: \"resolved\", identifiers, variant_identifiers, attributes,\n provenance: { source, source_ref, match: \"unresolved\" }, limited } };\n for (const [field, pattern] of Object.entries(aliases)) {\n const variantSKU = Object.keys(variant_identifiers).some(key => /^sku$/i.test(key));\n if (field === \"sku\" && variant && !variantSKU && variant_identifiers.id !== undefined && !Object.entries(identifiers).some(([key, value]) => aliases.sku.test(key) && value === variant_identifiers.id)) continue;\n const pool = field === \"product_id\" ? identifiers : field === \"sku\" ? variantSKU ? variant_identifiers : identifiers : { ...identifiers, ...variant_identifiers };\n const values = Object.keys(pool).filter(key => pattern.test(key)).map(key => pool[key]!);\n if (field === \"variant_id\" && !values.length && variant_identifiers.id !== undefined) values.push(variant_identifiers.id);\n const unique = [...new Set(values)]; if (unique.length > 1) return null;\n if (unique.length) snapshot[field] = unique[0]!;\n }\n const facts = { ...row, ...variant }, name = scalar(row.name ?? row.title ?? row.product_name ?? facts.name ?? facts.title), offer = facts.offers;\n const offers = (Array.isArray(offer) ? offer : [offer]).filter(value => value && typeof value === \"object\") as Record<string, unknown>[];\n if (offers.some(value => Array.isArray(value.priceSpecification) && value.priceSpecification.length > 16)) return null;\n if (typeof name === \"string\" && name.length <= 160) snapshot.name = name;\n const specifications = offers.map(value => {\n const specs = (Array.isArray(value.priceSpecification) ? value.priceSpecification : [value.priceSpecification]).filter(spec => spec && typeof spec === \"object\") as Record<string, unknown>[];\n return specs.filter(spec => !spec.priceType || /(?:^|\\/)SalePrice$/.test(String(spec.priceType)));\n });\n const prices = offers.map((value, n) => value.price ?? (value.lowPrice !== undefined && value.lowPrice === value.highPrice ? value.lowPrice : undefined) ?? (specifications[n]!.length && specifications[n]!.every(spec => spec.price === specifications[n]![0]!.price) ? specifications[n]![0]!.price : undefined));\n const money = facts.price && typeof facts.price === \"object\" && !Array.isArray(facts.price) ? facts.price as Record<string, unknown> : undefined;\n const amount = facts.sale_price ?? facts.priceValue ?? (money ? /^[A-Z]{3}$/.test(String(money.currencyCode)) ? money.amount : undefined : facts.price) ?? (prices.length && prices.every(value => value === prices[0]) ? prices[0] : undefined);\n if ((typeof amount === \"number\" || typeof amount === \"string\" && /^\\d{1,10}(?:\\.\\d{1,4})?$/.test(amount)) && Number.isFinite(Number(amount)) && Number(amount) >= 0 && Number(amount) <= Number.MAX_SAFE_INTEGER) snapshot.price = Number(amount);\n const currencies = offers.map((value, n) => value.priceCurrency ?? (specifications[n]!.length && specifications[n]!.every(spec => spec.priceCurrency === specifications[n]![0]!.priceCurrency) ? specifications[n]![0]!.priceCurrency : undefined)).filter(Boolean);\n const currency = facts.currency ?? facts.currencyId ?? facts.price_currency ?? facts.priceCurrency ?? money?.currencyCode ?? (new Set(currencies).size === 1 ? currencies[0] : undefined);\n if (typeof currency === \"string\" && /^[A-Z]{3}$/.test(currency)) snapshot.currency = currency;\n if (money && [facts.currency, facts.currencyId, facts.price_currency, facts.priceCurrency, ...currencies].some(value => value !== undefined && value !== money.currencyCode)) { delete snapshot.price; delete snapshot.currency; }\n const { url, images, rawImages } = links(facts, source_ref);\n if (url) snapshot.url = url; if (images.length) snapshot.image_url = images[0]!;\n if (!Object.keys(identifiers).length && !Object.keys(variant_identifiers).length || typeof name !== \"string\" || snapshot.price === undefined && !images.length) return null;\n if (new TextEncoder().encode(JSON.stringify(snapshot)).length > 8192) return null;\n return { snapshot, ref: crypto.randomUUID(), images, rawImages, url, sku: snapshot.sku as string | undefined, variant: snapshot.variant_id as string | undefined, expires: Date.now() + 900000 };\n}\n\n/** Identifies the same observed source record without retaining a raw response or changing its local correlation reference. */\nfunction entryKey(value: Entry): string {\n const identity = value.snapshot.metadata.provenance.source === \"public_hydration\" && value.snapshot.product_id ? [value.snapshot.product_id, value.snapshot.variant_id, value.snapshot.sku] : [Object.entries(value.snapshot.metadata.identifiers).sort(), Object.entries(value.snapshot.metadata.variant_identifiers).sort()];\n return JSON.stringify([identity, value.snapshot.metadata.provenance.source_ref, value.blocked && !Object.keys(value.snapshot.metadata.identifiers).length ? [value.sku, value.url, value.images, value.ids] : null]);\n}\n\n/** Builds a bounded per-runtime product index and a permission-gated startup XHR bridge. */\nexport function createProductIndex(options: { epoch: () => string | null }): {\n observe(value: unknown, source: string, kind?: string): void; track(xhr: XMLHttpRequest, url: string, method: string): void;\n activate(): void; resolve(root: Element, price?: number, currency?: string, label?: string): ProductMatch; pause(): void; destroy(): void;\n} {\n let records: Entry[] = [], limited = false, pageLimited = false, stopped = false, active: string | null = null, jsonPage = \"\", jsonPageTime = 0;\n const generations = new WeakMap<XMLHttpRequest, number>(), startup: { ref: WeakRef<XMLHttpRequest>; url: string; generation: number }[] = [];\n const listeners = new Set<() => void>();\n const timeout = setTimeout(() => { if (startup.length || listeners.size) limited = true; startup.length = 0; for (const stop of [...listeners]) stop(); listeners.clear(); }, 10000);\n /** Clears transient authorization-bound references while retaining only sanitized public product facts. */\n function pause(): void { active = null; startup.length = 0; for (const stop of [...listeners]) stop(); }\n /** Reads only confirmed product containers, without descending into customer or arbitrary item trees. */\n function observe(value: unknown, source: string, kind = \"catalog_response\"): void {\n const epoch = options.epoch(), source_ref = productSourceURL(source); if (!epoch || stopped || !source_ref) return;\n if (typeof value === \"string\") value = parseProductJSON(value);\n const filename = new URL(source_ref).pathname.split(\"/\").pop() ?? \"\";\n const queue: { value: unknown; product: boolean; depth: number; group?: Entry[\"group\"] }[] = [{ value, product: kind !== \"json_ld\" && /(?:^|[-_.])(?:products?|catalog)(?:[-_.]|$)/i.test(filename), depth: 0 }];\n let visited = 0;\n while (queue.length && visited++ < 512) {\n const item = queue.shift()!; if (item.depth > 5) { limited = true; continue; }\n if (Array.isArray(item.value)) { for (const child of item.value.slice(0, 128)) queue.push({ value: child, product: item.product, depth: item.depth + 1 }); if (item.value.length > 128) limited = true; continue; }\n if (!item.value || typeof item.value !== \"object\") continue;\n const row = item.value as Record<string, unknown>, types = Array.isArray(row[\"@type\"]) ? row[\"@type\"] : [row[\"@type\"]];\n if (types.includes(\"ProductGroup\") && Array.isArray(row.hasVariant)) {\n if (row.hasVariant.length > 16) { limited = true; continue; }\n const { id: groupID, productID: groupProductID, hasVariant, ...group } = row;\n const parent = Object.fromEntries(Object.entries(group).filter(([key]) => !aliases.product_id.test(key) && !aliases.sku.test(key) && !/^(?:url|@id|product[_-]?url)$/i.test(key)));\n for (const child of hasVariant) if (child && typeof child === \"object\") queue.push({ value: { ...parent, ...(child as object), url: links(child as Record<string, unknown>, source_ref).url, productGroupID: row.productGroupID ?? groupProductID ?? groupID, productGroupSKU: row.sku, \"@type\": \"Product\" }, product: true, depth: item.depth + 1, group: { url: links(row, source_ref).url, name: normalized(row.name) } });\n continue;\n }\n const product = types.some(type => [\"Product\", \"IndividualProduct\"].includes(String(type))) || item.product;\n if (product && Object.keys(row).some(key => identifier.test(key))) {\n const variants = Array.isArray(row.variants) ? row.variants : [undefined];\n if (variants.length > 16) { limited = true; continue; }\n if (variants.some(value => value !== undefined && (!value || typeof value !== \"object\" || Array.isArray(value)))) continue;\n for (const variant of variants.slice(0, 16)) {\n const selected = variant && typeof variant === \"object\" ? variant as Record<string, unknown> : undefined;\n let entry = project(row, kind, source_ref, selected);\n if (!entry) {\n const facts = { ...row, ...selected }, evidence = links(facts, source_ref);\n const ids = Object.keys(facts).filter(key => aliases.product_id.test(key)).map(key => id(facts[key])).filter((value): value is string => value !== undefined);\n if (!evidence.sku && !evidence.url && !evidence.images.length && !ids.length) continue;\n entry = { ...evidence, ids, variant: id(selected?.variant_id ?? selected?.variantId ?? selected?.id ?? row.variant_id ?? row.variantId), ref: crypto.randomUUID(), blocked: true, expires: Date.now() + 900000, snapshot: { metadata: { resolution: \"ambiguous\", identifiers: {}, variant_identifiers: {}, attributes: {}, provenance: { source: kind, source_ref, match: \"unresolved\" }, limited: false } } };\n }\n if (entry.snapshot.metadata.limited) limited = true;\n entry.group = item.group;\n const signature = entryKey(entry);\n const previous = records.find(existing => entryKey(existing) === signature);\n if ([\"json_ld\", \"public_hydration\"].includes(kind) && previous && !entry.blocked) {\n const conflict = previous.blocked || [\"price\", \"currency\", \"url\"].some(key => previous.snapshot[key] !== undefined && entry!.snapshot[key] !== undefined && previous.snapshot[key] !== entry!.snapshot[key]) || [\"identifiers\", \"variant_identifiers\"].some(key => Object.entries(previous.snapshot.metadata[key as \"identifiers\"]).some(([name, value]) => entry!.snapshot.metadata[key as \"identifiers\"][name] !== undefined && entry!.snapshot.metadata[key as \"identifiers\"][name] !== value));\n const strong = previous.url ? previous : entry, weak = strong === entry ? previous : entry;\n entry.snapshot = { ...weak.snapshot, ...strong.snapshot, metadata: { ...strong.snapshot.metadata, identifiers: { ...weak.snapshot.metadata.identifiers, ...strong.snapshot.metadata.identifiers }, variant_identifiers: { ...weak.snapshot.metadata.variant_identifiers, ...strong.snapshot.metadata.variant_identifiers }, attributes: { ...weak.snapshot.metadata.attributes, ...strong.snapshot.metadata.attributes } } };\n entry.url = strong.url ?? weak.url; entry.group = strong.group ?? weak.group;\n entry.images = [...new Set([...strong.images, ...weak.images])];\n entry.rawImages = strong.rawImages && weak.rawImages ? [...new Set([...strong.rawImages, ...weak.rawImages])] : undefined;\n if (entry.images.length > 16 || (entry.rawImages?.length ?? 0) > 16 || Object.keys(entry.snapshot.metadata.attributes).length > 32 || Object.keys(entry.snapshot.metadata.identifiers).length > 32 || Object.keys(entry.snapshot.metadata.variant_identifiers).length > 32) limited = true;\n if (conflict || limited) { entry.blocked = true; entry.snapshot.metadata.resolution = \"ambiguous\"; }\n }\n entry.ref = previous?.ref ?? entry.ref;\n records = records.filter(existing => entryKey(existing) !== signature && existing.expires > Date.now());\n if (records.length >= 128) { limited = true; continue; } records.push(entry);\n }\n }\n for (const key of [\"products\", \"product\", \"catalog\", \"data\", \"@graph\", \"items\", \"itemListElement\", \"item\", \"mainEntity\"]) if (row[key] !== undefined && (key !== \"items\" || product)) queue.push({ value: row[key], product: product || [\"products\", \"product\", \"catalog\"].includes(key), depth: item.depth + 1 });\n }\n if (queue.length) limited = true;\n }\n /** Reads JSON-only public document data, binding hydration candidates to independent current-page product evidence. */\n function readPage(): void {\n /** Refuses incomplete public sources on every access instead of caching a usable partial prefix. */\n function incomplete(): void { pageLimited = true; jsonPage = \"\"; }\n const currentDocument = documentURL(), source = currentDocument && productSourceURL(currentDocument), canonical = publicURL(document.querySelector('link[rel=\"canonical\"]')?.getAttribute(\"href\")) ?? source;\n if (!source || !canonical) return;\n const native = nativeForms(); if (!native) { incomplete(); return; }\n const scripts: HTMLScriptElement[] = []; let work = 0, hydrationWork = 0, schemaCount = 0, hydrationCount = 0, hydrationLimited = false, hash = 2166136261, second = 5381;\n for (const script of document.scripts) {\n if (script.src || script.type === \"application/json\" && privateKey.test(script.id)) continue;\n const text = script.textContent ?? \"\";\n if (script.type !== \"application/ld+json\" && script.type !== \"application/json\" && script.id !== \"__NEXT_DATA__\" && !text.slice(0, 128).includes(\"self.__next_f\")) continue;\n if (script.type === \"application/ld+json\") {\n if (++schemaCount > 256 || text.length > 262144 || (work += new TextEncoder().encode(text).length) > 1048576) { incomplete(); return; }\n } else if (++hydrationCount > 256 || hydrationLimited || text.length > 1048576 - hydrationWork || (hydrationWork += new TextEncoder().encode(text).length) > 1048576) { hydrationLimited = true; continue; }\n scripts.push(script);\n for (let n = 0; n < text.length; n++) { const code = text.charCodeAt(n); hash = Math.imul(hash ^ code, 16777619) >>> 0; second = (Math.imul(second, 33) ^ code) >>> 0; }\n }\n const signature = [source, canonical, document.querySelector(\"h1\")?.textContent, document.readyState, scripts.length, hydrationLimited, hash, second, JSON.stringify(native.map(({ product, variant }) => [product, variant]))].join(\":\");\n if (jsonPage === signature && Date.now() - jsonPageTime < 900000) return; pageLimited = false; jsonPage = signature; jsonPageTime = Date.now();\n const previousRefs = new Map(records.filter(entry => entry.expires > Date.now()).map(entry => [entryKey(entry), entry.ref]));\n records = records.filter(entry => ![\"json_ld\", \"public_hydration\"].includes(entry.snapshot.metadata.provenance.source) || entry.snapshot.metadata.provenance.source_ref !== source);\n const schemas: Record<string, unknown>[] = [], roots: unknown[] = [], chunks: string[] = [], variantSources: { rows: Record<string, unknown>[]; parent: string }[] = [];\n let bytes = 0, indexed: unknown, indexedCount = 0;\n for (const script of scripts) {\n const text = script.textContent ?? \"\";\n if (script.type === \"application/ld+json\") {\n if (new TextEncoder().encode(text).length > 262144) { incomplete(); return; }\n const pending: unknown[] = [parseProductJSON(text)];\n for (let n = 0; pending.length && n < 256; n++) {\n const value = pending.shift();\n if (Array.isArray(value)) { if (value.length > 64) { incomplete(); return; } pending.push(...value); continue; }\n if (!value || typeof value !== \"object\") continue;\n const row = value as Record<string, unknown>, types = Array.isArray(row[\"@type\"]) ? row[\"@type\"] : [row[\"@type\"]];\n if (types.some(type => [\"Product\", \"ProductGroup\", \"IndividualProduct\"].includes(String(type)))) schemas.push(row);\n for (const key of [\"@graph\", \"mainEntity\", \"itemListElement\", \"item\"]) if (row[key]) pending.push(row[key]);\n }\n if (pending.length) { incomplete(); return; }\n } else if (hydrationLimited) continue;\n else if (script.type === \"application/json\" && script.id === \"__NUXT_DATA__\") {\n bytes += new TextEncoder().encode(text).length; if (++indexedCount > 1) hydrationLimited = true;\n try { indexed = JSON.parse(text); } catch { hydrationLimited = true; }\n } else if (script.type === \"application/json\" && script.id !== \"__NEXT_DATA__\") {\n bytes += new TextEncoder().encode(text).length; const parsed = parseProductJSON(text), variants = Array.isArray(parsed) ? parsed : parsed && typeof parsed === \"object\" ? (parsed as Record<string, unknown>).variants : undefined;\n if (Array.isArray(variants) && variants.length <= 16 && variants.every(row => row && typeof row === \"object\" && !Array.isArray(row) && id(row.id))) {\n const root = parsed && !Array.isArray(parsed) && typeof parsed === \"object\" && (parsed as Record<string, unknown>).handle === new URL(canonical).pathname.split(\"/\").pop() ? parsed as Record<string, unknown> : undefined;\n const declared = root ? [...new Set(Object.entries(root).filter(([key]) => aliases.product_id.test(key)).map(([, value]) => id(value)).filter((value): value is string => value !== undefined))] : [];\n if (declared.length > 1) { pageLimited = true; continue; }\n const parentIDs = variants.map(row => id(row.featured_image?.product_id)), parent = root ? declared[0] : parentIDs.every(value => value && value === parentIDs[0]) ? parentIDs[0] : undefined;\n if (parent) variantSources.push({ rows: variants, parent });\n }\n } else if (script.id === \"__NEXT_DATA__\" && text.length <= 1048576) { bytes += new TextEncoder().encode(text).length; roots.push(parseProductJSON(text, 1048576)); }\n else if (text.includes(\"self.__next_f.push\")) for (const match of text.length <= 1048576 ? text.matchAll(/self\\.__next_f\\.push\\(\\[1\\s*,\\s*(\"(?:[^\"\\\\]|\\\\.)*\")\\s*\\]\\)/g) : []) {\n try { const chunk: unknown = JSON.parse(match[1]!); if (typeof chunk === \"string\") { bytes += new TextEncoder().encode(chunk).length; if (bytes <= 1048576) chunks.push(chunk); } } catch { /* Non-JSON/executable script syntax is never evaluated. */ }\n }\n }\n if (bytes > 1048576) hydrationLimited = true;\n if (!hydrationLimited) roots.push(...flightRows(chunks.join(\"\"))); else roots.length = 0;\n const title = normalized(document.querySelector(\"h1\")?.textContent), hydrated: { row: Record<string, unknown>; schema?: Record<string, unknown>; url?: string; structured: boolean }[] = [], typedVariants = new Map<string, Record<string, unknown>[]>();\n const anchors = [...document.querySelectorAll(\"a[href]\")].slice(0, 512).map(node => publicURL(node.getAttribute(\"href\"))).filter((value): value is string => !!value);\n const pending = roots.map(value => ({ value, product: false, depth: 0 })); let visited = 0;\n while (pending.length && visited++ < 8192) {\n const item = pending.shift()!;\n if (Array.isArray(item.value)) { if (item.value.length > 128) { hydrationLimited = true; continue; } for (const value of item.value) if (value && typeof value === \"object\") pending.push({ value, product: item.product, depth: item.depth + 1 }); continue; }\n if (!item.value || typeof item.value !== \"object\") continue;\n const original = item.value as Record<string, unknown>, core = original.product;\n const row = core && typeof core === \"object\" && !Array.isArray(core) && Array.isArray(original.variants) ? { ...core as Record<string, unknown>, variants: original.variants } : original, name = normalized(row.name ?? row.title ?? row.product_name);\n const typedID = id(row.id); if (typedID && /^gid:\\/\\/shopify\\/ProductVariant\\/\\d+$/.test(typedID)) typedVariants.set(typedID, [...typedVariants.get(typedID) ?? [], row]);\n const schema = schemas.filter(value => normalized(value.name) === name && (links(value, source).url === canonical || name === title));\n const segments = new URL(canonical).pathname.split(\"/\").filter(Boolean).map(decodeURIComponent);\n const slugValue = row.slug ?? row.handle ?? (schema.length === 1 && name === title ? row.url : undefined);\n const slug = typeof slugValue === \"string\" && /^[a-z0-9-]{1,160}$/.test(slugValue) && segments[segments.length - 1] === slugValue;\n const productLinks = typeof row.handle === \"string\" && /^[a-z0-9-]{1,160}$/.test(row.handle) && /^gid:\\/\\/shopify\\/Product\\/\\d+$/.test(typedID ?? \"\") ? [...new Set(anchors.filter(value => new URL(value).origin === location.origin && new URL(value).pathname.endsWith(\"/products/\" + row.handle)))] : [];\n const declaredID = Object.entries(row).some(([key, value]) => /^(?:id|product[_-]?id|sku)$/i.test(key) && id(value) !== undefined && segments.includes(id(value)!));\n const publicFacts = [row.price, row.priceValue, row.sale_price, row.image, row.image_url].some(value => value !== undefined) || Array.isArray(row.variants) && row.variants.length > 0;\n if (name && publicFacts && (slug && (row.handle === undefined || schema.length === 1) || productLinks.length === 1 || links(row, source).url === canonical || item.product && declaredID && schema.length === 1 && name === title) &&\n (Object.keys(row).some(key => identifier.test(key)) || Array.isArray(row.variants))) hydrated.push({ row, schema: schema.length === 1 ? schema[0] : undefined, url: productLinks.length === 1 ? productLinks[0] : undefined, structured: row !== original || /^gid:\\/\\/shopify\\/Product\\/\\d+$/.test(typedID ?? \"\") });\n for (const [key, value] of Object.entries(original)) if (!privateKey.test(key) && value && typeof value === \"object\") pending.push({ value, product: item.product || /product/i.test(key), depth: item.depth + 1 });\n }\n const consumed = new Set<Record<string, unknown>>();\n const schemaVariants = schemas.flatMap(row => Array.isArray(row.hasVariant) ? row.hasVariant : [row]).filter((row): row is Record<string, unknown> => !!row && typeof row === \"object\" && !Array.isArray(row));\n if (!pending.length && !hydrationLimited && bytes <= 1048576) for (const item of hydrated) {\n const variantID = id(item.row.variantId), concrete = variantID && /^gid:\\/\\/shopify\\/ProductVariant\\/\\d+$/.test(variantID) ? typedVariants.get(variantID) : undefined;\n const concreteFacts = concrete?.map(row => JSON.stringify([row.price, row.image, row.sku]));\n if (concreteFacts && new Set(concreteFacts).size !== 1) { pageLimited = true; continue; }\n const row = concrete?.length ? { ...item.row, variants: [concrete[0]] } : item.row;\n const safe = Object.fromEntries(Object.entries(row).filter(([key]) => (publicField.test(key) || identifier.test(key)) && !privateKey.test(key)));\n if (typeof safe.price === \"string\" && /^\\$[\\da-f]+:/i.test(safe.price)) delete safe.price;\n if (item.structured && (!safe.price || typeof safe.price !== \"object\")) delete safe.price;\n if (![...links(safe, source).images].length) { delete safe.image; delete safe.images; delete safe.image_url; delete safe.imageUrl; }\n if (Array.isArray(safe.variants)) safe.variants = safe.variants.map(value => {\n if (!value || typeof value !== \"object\") return null;\n const variant = Object.fromEntries(Object.entries(value).filter(([key]) => (publicField.test(key) || identifier.test(key)) && !privateKey.test(key))), money = variant.price as Record<string, unknown> | undefined;\n const facts = schemaVariants.filter(row => sameVariant(id(variant.id ?? variant.variantId), links(row, source).url && new URL(links(row, source).url!).searchParams.get(\"variant\"))).map(row => project(row, \"json_ld\", source)?.snapshot).filter(Boolean);\n if (item.structured && (!money || typeof money !== \"object\" || !/^[A-Z]{3}$/.test(String(money.currencyCode))) || money && typeof money === \"object\" && facts.some(fact => fact!.price !== undefined && Number(money.amount) !== fact!.price || fact!.currency !== undefined && money.currencyCode !== fact!.currency)) for (const key of [\"price\", \"currency\", \"priceCurrency\", \"price_currency\", \"offers\"]) variant[key] = undefined;\n return variant;\n });\n const schema = { ...item.schema };\n if (item.row.special_price !== undefined) {\n const declared = item.schema && project(item.schema, \"json_ld\", source)?.snapshot; delete safe.price;\n if (declared?.price !== undefined && declared.currency && Number(item.row.special_price) === declared.price) safe.sale_price = declared.price;\n else for (const key of [\"price\", \"offers\", \"currency\", \"currencyId\", \"priceCurrency\", \"price_currency\"]) { delete schema[key]; delete safe[key]; }\n }\n if (id(safe.id) && schema.productID !== undefined && id(schema.productID) !== id(safe.id)) { schema.schema_productID = schema.productID; delete schema.productID; }\n const combined = { ...schema, ...safe, \"@type\": \"Product\", name: safe.name ?? safe.title ?? safe.product_name, url: links(safe, source).url ?? item.url ?? canonical };\n observe({ products: [combined] }, source, \"public_hydration\"); if (item.schema) consumed.add(item.schema);\n }\n for (const row of schemas) if (!consumed.has(row)) observe(row, source, \"json_ld\");\n if (!hydrationLimited && source === canonical) for (const row of indexedProducts(indexed, source, title, schemas)) {\n observe({ products: [row] }, source, \"public_hydration\");\n records = records.filter(entry => entry.snapshot.metadata.provenance.source !== \"json_ld\" || entry.snapshot.metadata.provenance.source_ref !== source || entry.sku !== row.schema_productSKU || normalized(entry.snapshot.name) !== title || entry.url && entry.url !== source);\n }\n if (!pending.length && !hydrationLimited) for (const { rows: variants, parent: parentID } of variantSources) {\n const bindings = native.filter(form => form.product && variants.some(row => sameVariant(id(row.id), form.variant)));\n const parents = [...new Set(bindings.map(form => form.product!))]; if (!parents.length) continue;\n if (parents.length !== 1 || parents[0] !== parentID) { pageLimited = true; continue; }\n for (const entry of records.filter(value => [\"json_ld\", \"public_hydration\"].includes(value.snapshot.metadata.provenance.source) && value.snapshot.metadata.provenance.source_ref === source)) {\n const selector = entry.url && new URL(entry.url).searchParams.get(\"variant\"), matches = variants.filter(row => sameVariant(id(row.id), selector));\n if (!selector || matches.length !== 1 || !entry.url || new URL(entry.url).origin + new URL(entry.url).pathname !== new URL(canonical).origin + new URL(canonical).pathname) continue;\n const row = matches[0]!, image = row.featured_image as Record<string, unknown> | undefined, parent = id(image?.product_id);\n if (parent && parent !== parents[0] || row.sku !== undefined && id(row.sku) !== entry.sku || entry.snapshot.product_id && entry.snapshot.product_id !== parents[0]) { pageLimited = true; continue; }\n entry.snapshot.product_id = parents[0]!; entry.snapshot.variant_id = id(row.id)!; entry.variant = id(row.id);\n entry.snapshot.metadata.identifiers.product_id = parents[0]!; entry.snapshot.metadata.variant_identifiers.variant_id = id(row.id)!;\n entry.snapshot.metadata.provenance.source = \"public_hydration\";\n }\n }\n for (const entry of records) entry.ref = previousRefs.get(entryKey(entry)) ?? entry.ref;\n }\n /** Checks deferred and live XHR reads through the same current-permission and request-generation boundary. */\n function consume(candidate: typeof startup[number]): void {\n const xhr = candidate.ref.deref(); if (!xhr || stopped || !active || options.epoch() !== active || generations.get(xhr) !== candidate.generation) return;\n if (xhr.readyState !== 4) return;\n try { if (xhr.status >= 200 && xhr.status < 300 && publicURL(xhr.responseURL) === candidate.url && /json/i.test(xhr.getResponseHeader(\"content-type\") ?? \"\")) observe(xhr.responseType === \"json\" ? xhr.response : xhr.responseText, candidate.url); } catch { /* Detached/unsupported response types stay unavailable. */ }\n }\n return {\n observe,\n /** Stores only safe request metadata and weak references before server authorization. */\n track(xhr, input, method): void {\n const generation = (generations.get(xhr) ?? 0) + 1; generations.set(xhr, generation);\n const url = productSourceURL(input); if (active || stopped || !url || method.toUpperCase() !== \"GET\" || !/\\/(?:products?|catalog)\\.json$/i.test(new URL(url).pathname) || typeof WeakRef === \"undefined\") return;\n if (startup.length >= 32) { limited = true; return; }\n startup.push({ ref: new WeakRef(xhr), url, generation });\n },\n /** Activates after both gates, reading only still-live completed or subsequently completed XHRs. */\n activate(): void {\n const epoch = options.epoch(); if (!epoch || stopped || active) return; active = epoch;\n for (const candidate of startup.splice(0)) {\n const xhr = candidate.ref.deref(); if (!xhr) { limited = true; continue; }\n consume(candidate);\n if (xhr.readyState !== 4) {\n /** Releases one deferred listener after completion, timeout or permission revocation. */\n const stop = () => { candidate.ref.deref()?.removeEventListener(\"loadend\", complete); listeners.delete(stop); };\n /** Rechecks authorization before accessing the original completed response. */\n const complete = () => { consume(candidate); stop(); };\n listeners.add(stop); xhr.addEventListener(\"loadend\", complete, { once: true });\n }\n }\n },\n /** Resolves the actual target before considering current-page context; an off-page link never inherits its ancestor product. */\n resolve(root, observedPrice, observedCurrency, observedLabel): ProductMatch {\n const source_ref = location.origin + \"/\";\n const empty = (resolution: \"unresolved\" | \"ambiguous\"): ProductMatch => ({ product_ref: crypto.randomUUID(), snapshot: { metadata: { resolution, identifiers: {}, variant_identifiers: {}, attributes: {}, provenance: { source: \"dom\", source_ref, match: \"unresolved\" }, limited: limited || pageLimited } } });\n if (stopped || !options.epoch() || root.closest(\"header,footer,[data-sagepilot-popup]\")) return empty(\"unresolved\");\n readPage(); records = records.filter(entry => entry.expires > Date.now()); if (limited || pageLimited) return empty(\"ambiguous\");\n const anchor = root.closest(\"a[href]\"), targetURL = anchor ? publicURL(anchor.getAttribute(\"href\")) : undefined;\n if (anchor && !targetURL) return empty(\"unresolved\");\n const current = documentURL(), canonical = publicURL(document.querySelector('link[rel=\"canonical\"]')?.getAttribute(\"href\")) ?? current;\n if (!current) return empty(\"unresolved\");\n const samePage = current && canonical && new URL(current).origin + new URL(current).pathname === new URL(canonical).origin + new URL(canonical).pathname;\n const currentSelector = current ? new URL(current).searchParams.get(\"variant\") ?? new URL(current).searchParams.get(\"variant_id\") : undefined;\n const clickedImage = /^img$/i.test(root.tagName) && root.getClientRects().length ? publicURL((root as HTMLImageElement).currentSrc || root.getAttribute(\"src\"), location.href, true) : undefined;\n const literalImage = clickedImage ? new URL((root as HTMLImageElement).currentSrc || root.getAttribute(\"src\")!, location.href).href : undefined;\n const action = commerceAction(root.getAttribute(\"aria-label\") ?? (root as HTMLElement).innerText ?? root.textContent ?? \"\");\n const primary = /^h1$/i.test(root.tagName) || (root.matches(\"button,[role='button']\") && /^(?:add(?: to (?:cart|bag|basket))?|buy(?: now)?|rent(?: now)?)[.!]?$/i.test(action));\n if (!anchor && primary && !samePage) return empty(\"unresolved\");\n const form = (root as HTMLButtonElement).form ?? root.closest(\"form\"), privateForm = form && [...form.querySelectorAll(\"input:not([type='hidden']),textarea,select\")].some(node => node.tagName === \"TEXTAREA\" || !/^(?:quantity|qty|variant(?:_id)?|option(?:\\[.*\\])?|attribute_[A-Za-z0-9_]+)$/i.test(node.getAttribute(\"name\") ?? \"\"));\n if (privateForm) return empty(\"unresolved\");\n let pageContext = !anchor && primary && samePage && !privateForm && !root.closest(\"dialog,[role='dialog']\");\n const images = new Set<string>(), urls = new Set<string>(), skus = new Set<string>(), variants = new Set<string>(), ids = new Set<string>();\n const bound = records.filter(entry => entry.snapshot.metadata.provenance.source_ref === current && entry.url && new URL(entry.url).origin + new URL(entry.url).pathname === new URL(canonical!).origin + new URL(canonical!).pathname);\n const native = nativeForms(), owner = (root as HTMLButtonElement).form ?? root.closest(\"form\"); if (!native) return empty(\"ambiguous\");\n const own = native.find(value => value.form === owner);\n const ownerAction = owner && publicURL(owner.getAttribute(\"action\"));\n if (primary && ownerAction && new URL(ownerAction).origin === location.origin && /\\/cart\\/add\\/?$/.test(new URL(ownerAction).pathname) && !own) return empty(\"ambiguous\");\n const forms = native.filter(form => bound.some(entry => sameVariant(entry.variant, form.variant) || sameVariant(entry.url && new URL(entry.url).searchParams.get(\"variant\"), form.variant)));\n if (primary && own && !forms.includes(own)) return empty(\"unresolved\");\n const checked = [...document.querySelectorAll('input[type=\"radio\"]:checked')]; if (checked.length > 32) return empty(\"ambiguous\");\n const controls = checked.map(node => id((node as HTMLInputElement).value)).filter(value => value && bound.some(entry => entry.variant === value));\n const selections = [...new Set([...(own ? forms.filter(value => value === own) : forms).map(form => form.variant), ...controls])];\n const nativeConflict = selections.length && (selections.length !== 1 || currentSelector && !sameVariant(selections[0], currentSelector));\n const nativeVariant = samePage && selections.length === 1 && (!currentSelector || sameVariant(selections[0], currentSelector)) ? selections[0] : undefined;\n let exactVariant = id(root.getAttribute(\"data-variant-id\") ?? root.getAttribute(\"data-variant_id\") ?? anchor?.getAttribute(\"data-variant-id\"));\n const exactProduct = id(root.getAttribute(\"data-product-id\") ?? root.getAttribute(\"data-product_id\") ?? anchor?.getAttribute(\"data-product-id\"));\n const exactSKU = id(root.getAttribute(\"data-sku\") ?? anchor?.getAttribute(\"data-sku\"));\n let card: Element | null = root, direct: Element | null = null;\n for (let depth = 0; card && depth < 6 && card !== document.body; depth++, card = card.parentElement) {\n const nodes: Element[] = [card], walker = document.createTreeWalker(card, NodeFilter.SHOW_ELEMENT); let next: Node | null;\n while ((next = walker.nextNode()) && nodes.length <= 64) nodes.push(next as Element);\n if (nodes.length > 64) break;\n if (!direct && card.matches(\"[data-product-id],[data-variant-id],[data-product_id],[data-variant_id]\")) direct = card;\n for (const node of nodes) {\n const image = publicURL(node.getAttribute(\"src\") ?? undefined, location.href, true); if (image) images.add(image);\n for (const match of String(getComputedStyle(node).backgroundImage ?? \"\").matchAll(/url\\([\"']?([^\"')]+)[\"']?\\)/g)) { const value = publicURL(match[1], location.href, true); if (value) images.add(value); }\n const url = publicURL(node.getAttribute(\"href\") ?? undefined); if (url) urls.add(url);\n const sku = id(node.getAttribute(\"data-sku\") ?? (node.getAttribute(\"itemprop\") === \"sku\" ? node.getAttribute(\"content\") : null)); if (sku) skus.add(sku);\n const variant = id(node.getAttribute(\"data-variant-id\") ?? node.getAttribute(\"data-variant_id\")); if (variant) variants.add(variant);\n const product = id(node.getAttribute(\"data-product-id\") ?? node.getAttribute(\"data-product_id\") ?? (node.getAttribute(\"itemprop\") === \"productID\" ? node.getAttribute(\"content\") : null)); if (product) ids.add(product);\n }\n if (targetURL || images.size && urls.size) break;\n }\n const desired = targetURL ?? (urls.size === 1 ? [...urls][0] : undefined);\n if (primary && desired && new URL(desired).origin + new URL(desired).pathname !== new URL(canonical!).origin + new URL(canonical!).pathname) pageContext = false;\n if (pageContext && nativeConflict) return empty(\"ambiguous\"); exactVariant ??= pageContext ? nativeVariant : undefined;\n const labelCandidate = pageContext && current === canonical && records.some(entry => entry.snapshot.product_id === undefined && entry.snapshot.metadata.provenance.source === \"json_ld\" && entry.snapshot.metadata.provenance.source_ref === current && entry.url === current && entry.sku && new URL(current).pathname.split(\"/\").map(decodeURIComponent).includes(entry.sku));\n const labeled = labelCandidate ? labeledProductID() : undefined, productLabel = labeled && new URL(current).pathname.split(\"/\").map(decodeURIComponent).includes(labeled) ? labeled : undefined;\n if (exactVariant) { variants.clear(); variants.add(exactVariant); } if (exactProduct) { ids.clear(); ids.add(exactProduct); } if (exactSKU) { skus.clear(); skus.add(exactSKU); }\n const sharedImages = new Set([...images].filter(value => records.filter(entry => entry.images.includes(value)).length > 1));\n const pageSchema = records.filter(entry => entry.snapshot.metadata.provenance.source === \"json_ld\" && entry.snapshot.metadata.provenance.source_ref === current);\n const uniqueLiteral = literalImage && pageSchema.every(entry => entry.rawImages !== undefined) && pageSchema.filter(entry => entry.rawImages?.includes(literalImage)).length === 1;\n const matches: { entry: Entry; match: string; rank: number; image?: string }[] = [];\n for (const entry of records) {\n if (pageContext && [\"json_ld\", \"public_hydration\"].includes(entry.snapshot.metadata.provenance.source) && entry.snapshot.metadata.provenance.source_ref !== current) continue;\n const declaredVariantURL = entry.url ? new URL(entry.url).searchParams.get(\"variant\") ?? new URL(entry.url).searchParams.get(\"variant_id\") : undefined;\n const labelMatch = productLabel && entry.sku === productLabel && entry.url === current && entry.snapshot.metadata.provenance.source === \"json_ld\";\n if (labelMatch && entry.snapshot.product_id !== undefined && entry.snapshot.product_id !== productLabel) return empty(\"ambiguous\");\n if (exactVariant && !sameVariant(entry.variant ?? declaredVariantURL, exactVariant)) continue;\n const query = desired ? new URL(desired).searchParams : current ? new URL(current).searchParams : null;\n const selected = query?.get(\"variant\") ?? query?.get(\"variant_id\"), variantValues = Object.values(entry.snapshot.metadata.variant_identifiers);\n if (pageContext && currentSelector && ![entry.variant, entry.sku, declaredVariantURL, ...variantValues].some(value => sameVariant(value, currentSelector))) continue;\n const exactURL = !!desired && (entry.url === desired || !!selected && entry.url?.split(\"?\")[0] === desired.split(\"?\")[0] && [entry.variant, entry.sku, ...variantValues].some(value => sameVariant(value, selected)));\n const image = entry.images.find(value => images.has(value) && !sharedImages.has(value)), token = entry.sku && new RegExp(`(?:^|[^A-Za-z0-9])${entry.sku.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}(?:$|[^A-Za-z0-9])`);\n const skuImage = token ? [...images].find(value => !sharedImages.has(value) && token.test(new URL(value).pathname)) : undefined;\n const title = normalized(entry.snapshot.name), titleOnPage = [...document.querySelectorAll(\"h1\")].slice(0, 8).some(node => node.getClientRects().length && normalized(node.textContent) === title);\n const groupOnPage = entry.group?.url === canonical && samePage && entry.snapshot.metadata.provenance.source_ref === current && [...document.querySelectorAll(\"h1\")].slice(0, 8).some(node => node.getClientRects().length && normalized(node.textContent) === entry.group?.name);\n const directImage = uniqueLiteral && !targetURL && samePage && pageSchema.includes(entry) && entry.rawImages?.includes(literalImage!) && !sharedImages.has(clickedImage!) && (!entry.url || entry.url.split(\"?\")[0] === canonical!.split(\"?\")[0]) && (!currentSelector || [entry.variant, entry.sku, declaredVariantURL, ...variantValues].includes(currentSelector));\n const corroborated = title && title === normalized(observedLabel) && observedPrice !== undefined && entry.snapshot.price === observedPrice;\n let match = exactURL ? \"exact_url\" : !targetURL && (entry.variant && variants.has(entry.variant) || exactVariant && sameVariant(entry.variant ?? declaredVariantURL, exactVariant)) ? \"exact_variant\" : labelMatch || !targetURL && typeof entry.snapshot.product_id === \"string\" && ids.has(entry.snapshot.product_id) ? \"direct_id\"\n : !targetURL && entry.sku && skus.has(entry.sku) ? \"exact_sku\" : skuImage && (!targetURL || !entry.url) ? \"exact_sku\" : directImage || image && (corroborated || entry.blocked || entry.url === current && titleOnPage || groupOnPage) && (!targetURL || !entry.url) ? \"exact_image\" : null;\n if (!match && pageContext && titleOnPage && (entry.snapshot.metadata.provenance.source === \"catalog_response\" || entry.snapshot.metadata.provenance.source_ref === current) && (entry.url === current || entry.url === canonical) && (!selected || [entry.variant, entry.sku, ...variantValues].some(value => sameVariant(value, selected)))) match = \"exact_url\";\n if (match) matches.push({ entry, match, rank: exactURL ? 3 : match === \"exact_url\" ? 1 : 2, image: skuImage ?? image });\n }\n const rank = Math.max(0, ...matches.map(value => value.rank)), best = matches.filter(value => value.rank === rank);\n const directSelector = direct && id(direct.getAttribute(\"data-variant-id\") ?? direct.getAttribute(\"data-variant_id\") ?? direct.getAttribute(\"data-sku\"));\n if (!best.length && direct && (!anchor || direct === anchor) && !/^h1$/i.test(root.tagName) && (!primary || samePage && (!currentSelector || currentSelector === directSelector)) && !root.closest(\"dialog,[role='dialog']\")) {\n const identifiers: Record<string, string> = {}, variant_identifiers: Record<string, string> = {};\n const product = id(direct.getAttribute(\"data-product-id\") ?? direct.getAttribute(\"data-product_id\")), variant = id(direct.getAttribute(\"data-variant-id\") ?? direct.getAttribute(\"data-variant_id\"));\n if (product) identifiers.product_id = product; if (variant) variant_identifiers.variant_id = variant;\n if (product || variant) {\n const snapshot: ProductSnapshot = { ...(product ? { product_id: product } : {}), ...(variant ? { variant_id: variant } : {}), metadata: { resolution: \"resolved\", identifiers, variant_identifiers, attributes: {}, provenance: { source: \"dom_attribute\", source_ref, match: \"direct_id\" }, limited: false } };\n const price = direct.getAttribute(\"data-price\"), currency = direct.getAttribute(\"data-currency\");\n if (price && /^\\d{1,8}(?:\\.\\d{1,4})?$/.test(price)) snapshot.price = Number(price);\n if (currency && /^[A-Z]{3}$/.test(currency)) snapshot.currency = currency;\n const old = records.find(value => value.snapshot.product_id === product && value.snapshot.variant_id === variant && value.snapshot.metadata.provenance.source === \"dom_attribute\");\n const entry: Entry = old ?? { snapshot, ref: crypto.randomUUID(), images: [], expires: Date.now() + 900000 }; if (!old && records.length < 128) records.push(entry);\n return { snapshot, product_ref: entry.ref };\n }\n }\n if (best.length !== 1 || best[0]?.entry.blocked) return empty(best.length || sharedImages.size ? \"ambiguous\" : \"unresolved\");\n const result = JSON.parse(JSON.stringify(best[0]!.entry.snapshot)) as ProductSnapshot;\n if (productLabel && best[0]!.entry.sku === productLabel && best[0]!.entry.url === current && best[0]!.entry.snapshot.metadata.provenance.source === \"json_ld\") { result.product_id = productLabel; result.metadata.identifiers.product_id = productLabel; result.metadata.provenance.source = \"dom\"; }\n if (exactVariant && !result.variant_id) { result.variant_id = exactVariant; result.metadata.variant_identifiers.variant_id = exactVariant; }\n const chosen = best[0]!.entry, groupID = chosen.snapshot.metadata.identifiers.productGroupID;\n if (pageContext && groupID && chosen.group?.url === canonical && chosen.snapshot.metadata.provenance.source_ref === current) {\n const selected = chosen.url && (new URL(chosen.url).searchParams.get(\"variant\") ?? new URL(chosen.url).searchParams.get(\"variant_id\")), parents = [...new Set(forms.filter(form => form.product && sameVariant(form.variant, selected)).map(form => form.product!))];\n if (parents.length > 1 || parents[0] === groupID && result.product_id !== undefined && result.product_id !== parents[0]) return empty(\"ambiguous\");\n if (parents[0] === groupID && result.product_id === undefined) { result.product_id = parents[0]!; result.metadata.identifiers.product_id = parents[0]!; result.metadata.provenance.source = \"dom\"; }\n }\n if (typeof result.price === \"number\" && observedPrice !== undefined && Math.abs(result.price - observedPrice) > 1e-9 || result.currency && observedCurrency && result.currency !== observedCurrency) return empty(\"unresolved\");\n if (!result.image_url && best[0]!.image) result.image_url = best[0]!.image!;\n result.metadata.provenance.match = best[0]!.match;\n return new TextEncoder().encode(JSON.stringify(result)).length <= 8192 ? { snapshot: result, product_ref: best[0]!.entry.ref } : empty(\"unresolved\");\n },\n /** Clears every startup weak reference, deferred listener and retained product fact. */\n pause,\n destroy(): void { stopped = true; clearTimeout(timeout); pause(); records = []; }\n };\n}\n","import type { Capture } from \"./network\";\nimport type { Json } from \"./projection\";\nimport type { ProductMatch } from \"./product\";\nimport { commerceAction } from \"./product\";\n\ntype Product = { node: Element; label: string; price: number; currency?: string };\ntype Cart = { node: Element; ref: string; quantity: number };\ntype Pending = { label: string; epoch: string; trigger: string; before: Cart; changed: number; deadline: number; network: number; suppressed: boolean; product: Record<string, Json>; timer: ReturnType<typeof setTimeout> };\nconst imageSelector = \"img[alt],div[alt],[role='img'][aria-label]\";\nconst privateRegion = \"form,input,textarea,select,[contenteditable='true'],[data-sagepilot-popup],[hidden],[aria-hidden='true']\";\n\n/** Reads only a bounded subtree; an oversized or ambiguous region stays unavailable. */\nfunction nodes(root: Element, limit: number): Element[] | null {\n const result = [root], walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);\n let next: Node | null;\n while ((next = walker.nextNode())) { if (result.length >= limit) return null; result.push(next as Element); }\n return result;\n}\n\n/** Reads short displayed fragments without copying arbitrary parent text or input values. */\nfunction text(root: Element): string | null {\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n let result = \"\", next: Node | null, count = 0;\n while ((next = walker.nextNode())) {\n if (++count > 16 || (next.nodeValue?.length ?? 0) > 120) return null;\n const parent = next.parentElement;\n if (parent && (!parent.getClientRects().length || parent.closest(\"[aria-hidden='true']\") || getComputedStyle(parent).visibility === \"hidden\")) continue;\n result += next.nodeValue ?? \"\"; if (result.length > 120) return null;\n }\n return result.trim().replace(/\\s+/g, \" \");\n}\n\n/** Rejects contact-like and personalized labels before hashing; hashes do not make private text safe. */\nfunction label(value: string | null): string | null {\n value = value?.normalize(\"NFKC\") ?? null;\n if (!value || value.length < 3 || value.length > 80 || /\\d[\\d\\s().-]{5,}\\d|@|https?:|\\+\\d|[A-Za-z0-9_-]{24,}|\\b(?:your|my|account|profile|personalized|personalised|customized|customised|monogram|email|phone|address|password|token|customer|name)\\b/i.test(value)) return null;\n return value.trim().toLowerCase().replace(/\\s+/g, \" \");\n}\n\n/** Recognizes a displayed price, retaining currency only when an explicit ISO code is present. */\nfunction price(value: string | null): { price: number; currency?: string } | null {\n const match = value?.match(/^(?:rent at\\s+)?(?:(USD|EUR|GBP|INR|CAD|AUD|JPY)\\s*)?[$€£¥₹]?\\s*(\\d{1,8}(?:[.,]\\d{1,2})?|(?:\\d{1,3}(?:,\\d{3})+|\\d{1,3}(?:,\\d{2})*,\\d{3})(?:\\.\\d{1,2})?)\\s*(USD|EUR|GBP|INR|CAD|AUD|JPY)?(?:\\s*\\/\\s*(?:mo|month))?$/i);\n if (!match || !/[$€£¥₹]|\\b(?:USD|EUR|GBP|INR|CAD|AUD|JPY)\\b/i.test(value!)) return null;\n if (match[1] && match[3] && match[1].toUpperCase() !== match[3].toUpperCase()) return null;\n const amount = Number(/,\\d{3}(?:\\.|$)/.test(match[2]!) ? match[2]!.replace(/,/g, \"\") : match[2]!.replace(\",\", \".\")), currency = match[1] ?? match[3];\n return Number.isFinite(amount) && amount <= Number.MAX_SAFE_INTEGER ? { price: amount, ...(currency ? { currency: currency.toUpperCase() } : {}) } : null;\n}\n\n/** Finds a small unambiguous ordinary card for opaque context and DOM quantity proofs. */\nfunction productAt(target: Element): Product | null {\n let candidate: Element | null = target;\n for (let depth = 0; candidate && depth < 6 && candidate !== document.body; depth++, candidate = candidate.parentElement) {\n if (candidate.closest(privateRegion)) return null;\n const children = nodes(candidate, 64); if (!children) return null;\n if (children.some(node => node.matches(\"input,textarea,select,[contenteditable='true']\"))) return null;\n const images = children.filter(node => node.matches(imageSelector));\n if (images.length > 1) return null;\n if (images.length !== 1) continue;\n const name = label(images[0]!.getAttribute(\"alt\") ?? images[0]!.getAttribute(\"aria-label\"));\n if (!name || !children.some(node => node !== images[0] && !node.childElementCount && node.getClientRects().length &&\n getComputedStyle(node).visibility !== \"hidden\" && label(text(node)) === name)) continue;\n const amounts = children.filter(node => node.matches(\"p,span,[itemprop='price']\") && !node.closest(\"del,s\") && node.getClientRects().length &&\n getComputedStyle(node).visibility !== \"hidden\").map(node => price(text(node))).filter(Boolean);\n if (!amounts.length || new Set(amounts.map(amount => `${amount!.price}:${amount!.currency ?? \"\"}`)).size > 1) continue;\n const siblings = candidate.parentElement?.children;\n if (siblings && siblings.length > 64) return null;\n for (const sibling of siblings ? [...siblings] : []) {\n if (sibling === candidate) continue;\n const entries = nodes(sibling, 64); if (!entries) return null;\n if (entries.some(node => node.matches(imageSelector) && label(node.getAttribute(\"alt\") ?? node.getAttribute(\"aria-label\")) === name)) return null;\n }\n return { node: candidate, label: name, ...amounts[0]! };\n }\n return null;\n}\n\n/** Reads an explicit line quantity; unrelated digits, totals and input values cannot supply it. */\nfunction quantity(product: Product): number | null {\n const values = (nodes(product.node, 64) ?? []).filter(node => (!node.childElementCount || node.matches(\"p\")) &&\n node.getClientRects().length && getComputedStyle(node).visibility !== \"hidden\")\n .map(node => text(node)?.match(/^(?:.*\\s)?(?:quantity|qty)\\s*:\\s*(\\d{1,6})$/i)?.[1]).filter(value => value !== undefined);\n const unique = [...new Set(values)];\n return unique.length === 1 ? Number(unique[0]) : null;\n}\n\n/** Creates a private bounded observer for rendered cart changes; it never reads framework state. */\nexport function createDOMCart(options: { epoch: () => string | null; emit: Capture; networkVersion: () => number;\n productSnapshot?: (target: Element, price?: number, currency?: string, label?: string) => ProductMatch | undefined }): {\n click(target: Element, epoch: string, trigger: string): Record<string, Json> | Promise<Record<string, Json>>; destroy(): void;\n} {\n const regions = new WeakMap<Element, string>(), pending = new Map<string, Pending>();\n let stopped = false;\n /** Locates a positive Cart/Checkout region and counts only unique, fully readable product lines. */\n function cart(wanted: string): Cart | null {\n const markers: Element[] = [], possible = document.querySelectorAll(\"h1,h2,h3,h4,h5,h6,span,[aria-label],aside,[role='dialog']\");\n for (let index = 0; index < Math.min(possible.length, 128); index++) {\n const node = possible[index]!;\n if (!node.childElementCount && /^(?:shopping )?(?:cart|bag)$/i.test(text(node) ?? \"\")) markers.push(node);\n }\n const candidates = new Set<Element>();\n for (const marker of markers.slice(0, 8)) {\n let node = marker.parentElement;\n for (let depth = 0; node && node !== document.body && depth < 6; depth++, node = node.parentElement) {\n const children = nodes(node, 256); if (!children) break;\n if (children.some(child => child.getClientRects().length && getComputedStyle(child).visibility !== \"hidden\" &&\n (child.matches(\"[aria-busy='true'],[role='progressbar']\") || !child.childElementCount && /^(?:loading|updating)[.\\s…]*$/i.test(text(child) ?? \"\")))) break;\n const buttons = children.filter(child => child.matches(\"button,[role='button']\"));\n if (!buttons.some(button => /^(?:proceed to )?checkout$/i.test(text(button) ?? \"\"))) continue;\n if (buttons.some(button => /\\badd\\b.*\\bcart\\b/i.test(text(button) ?? \"\")) || node.closest(\"[hidden],[aria-hidden='true'],[aria-busy='true']\")) break;\n const style = getComputedStyle(node); if (style.display === \"none\" || style.visibility === \"hidden\") break;\n candidates.add(node); break;\n }\n }\n if (candidates.size !== 1) return null;\n const node = [...candidates][0]!, images = (nodes(node, 256) ?? []).filter(child => child.matches(imageSelector));\n if (images.length > 16) return null;\n if (!images.length && !(nodes(node, 256) ?? []).some(child => /^(?:(?:your|the|shopping)\\s+)?(?:cart|bag)\\s+(?:is\\s+)?empty[.!:]?$|^add some products (?:in|to) (?:the|your) (?:cart|bag)\\b/i.test(text(child) ?? \"\"))) return null;\n const seen = new Set<string>(); let count = 0;\n for (const image of images) {\n const product = productAt(image), amount = product ? quantity(product) : null;\n if (!product || !node.contains(product.node) || amount === null || seen.has(product.label)) return null;\n seen.add(product.label); if (product.label === wanted) count = amount;\n }\n let ref = regions.get(node); if (!ref) { ref = crypto.randomUUID(); regions.set(node, ref); }\n return { node, ref, quantity: count };\n }\n /** Disconnects observation whenever no bounded pending click remains. */\n function remove(key: string): void { const item = pending.get(key); if (item) clearTimeout(item.timer); pending.delete(key); if (!pending.size) observer.disconnect(); }\n /** Accepts one settled positive delta with the same region, permission and network snapshot. */\n function finish(key: string): void {\n const item = pending.get(key); if (!item) return;\n let after: Cart | null = null;\n try { after = cart(item.label); } catch { /* A detached or unreadable host DOM cannot establish success. */ }\n remove(key);\n if (stopped || item.suppressed || !item.product.product_ref || options.epoch() !== item.epoch || options.networkVersion() !== item.network ||\n performance.now() > item.deadline + 250 || performance.now() - item.changed < 300 ||\n !after || after.node !== item.before.node || after.quantity <= item.before.quantity) return;\n options.emit(\"interaction\", { action: \"cart_change\", confirmation: \"dom_cart_quantity_increase\", trigger_id: item.trigger,\n cart_region_ref: after.ref, before_quantity: item.before.quantity, after_quantity: after.quantity,\n product: { ...item.product, quantity: after.quantity - item.before.quantity } }, item.epoch, Date.now());\n }\n const observer = new MutationObserver(records => {\n for (const item of pending.values()) if (records.some(record => item.before.node.contains(record.target) || record.target.contains(item.before.node))) item.changed = performance.now();\n });\n return {\n /** Resolves the actual clicked product independently from the stricter cart-outcome reader. */\n click(target, epoch, trigger): Record<string, Json> | Promise<Record<string, Json>> {\n if (stopped) return {};\n const product = productAt(target), before = product ? cart(product.label) : null;\n const match = options.productSnapshot?.(target, before?.node.contains(target) ? undefined : product?.price, product?.currency, product?.label);\n const resolved = match?.snapshot.metadata.resolution === \"resolved\";\n if (!product && !resolved) return {};\n const action = commerceAction((target.getAttribute(\"aria-label\") ?? text(target) ?? \"\").slice(0, 256)).toLowerCase();\n const excluded = /\\b(?:wishlist|compare|address|tag|subscribe|contact)\\b/i.test(action + \" \" + (target.getAttribute(\"title\") ?? \"\").slice(0, 256));\n const add = !excluded && /\\badd\\b.*\\bcart\\b/.test(action), increment = /^(?:\\+|increase(?: quantity)?|increment(?: quantity)?)$/.test(action);\n const intent = resolved && !excluded && target.matches(\"button,[role='button']\") && !target.closest(\"dialog,[role='dialog']\") && /^(?:add|add to (?:cart|bag|basket))$/.test(action);\n const existing = product ? pending.get(product.label) : undefined;\n if (existing) existing.suppressed = true;\n const network = options.networkVersion();\n let watching: Pending | undefined;\n const sameProduct = !resolved || !product || typeof match?.snapshot.name !== \"string\" || label(match.snapshot.name) === product.label;\n if (product && sameProduct && before && !existing && pending.size < 3 && (add || increment && before.node.contains(target))) {\n watching = { label: product.label, epoch, trigger, before, network, changed: performance.now(), deadline: performance.now() + 2000, suppressed: false,\n product: {}, timer: setTimeout(() => finish(product.label), 2000) };\n pending.set(product.label, watching); observer.observe(document.body, { childList: true, characterData: true, subtree: true });\n }\n /** Keeps the same evidence and owner fence for synchronous source matches and legacy hashes. */\n const context = (product_ref: string): Record<string, Json> => {\n const snapshot = match?.snapshot, common = resolved ? snapshot : null;\n const evidence: Record<string, Json> = { product_ref, ...(!resolved && product ? { price: product.price, ...(product.currency ? { currency: product.currency } : {}) } : {}), ...(snapshot ? { snapshot } : {}) };\n for (const key of [\"product_id\", \"variant_id\", \"sku\", \"price\", \"currency\"]) if (common?.[key] !== undefined) evidence[key] = common[key]!;\n const amount = (add || intent) ? target.closest(\"[data-quantity]\")?.getAttribute(\"data-quantity\") : null;\n if (amount && /^\\d{1,8}(?:\\.\\d{1,4})?$/.test(amount)) evidence.quantity = Number(amount);\n if (watching && product && !stopped && options.epoch() === epoch && pending.get(product.label) === watching)\n watching.product = { product_ref, ...(add ? { price: product.price, ...(product.currency ? { currency: product.currency } : {}) } : {}), ...(snapshot ? { snapshot } : {}) };\n return { product: evidence, ...(intent ? { intent: \"add_to_cart\" } : {}) };\n };\n if (resolved) return context(match!.product_ref);\n return crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(location.origin + \"\\n\" + product!.label)).then(digest =>\n context(\"dom_\" + [...new Uint8Array(digest)].slice(0, 16).map(byte => byte.toString(16).padStart(2, \"0\")).join(\"\")));\n },\n /** Fences delayed observations and clears all retained transient product context. */\n destroy(): void { stopped = true; observer.disconnect(); for (const key of [...pending.keys()]) remove(key); }\n };\n}\n","import { routeFor, type Json } from \"./projection\";\nimport type { Capture } from \"./network\";\nimport { createDOMCart } from \"./dom\";\nimport type { ProductMatch } from \"./product\";\n\n/** Captures fingerprinted navigation, structural clicks and verified product-source context. */\nexport function observePage(options: { epoch: () => string | null; emit: Capture; dropped: () => void; networkVersion?: () => number;\n productSnapshot?: (target: Element, price?: number, currency?: string, label?: string) => ProductMatch | undefined }): () => void {\n const originalPush = history.pushState, originalReplace = history.replaceState;\n let stopped = false, previous = \"\", current = \"\", currentPage: string | null = null, pendingClicks = 0, pendingRoutes = 0;\n const roles = new Set([\"button\", \"link\", \"checkbox\", \"radio\", \"textbox\", \"combobox\", \"menuitem\", \"tab\", \"option\", \"switch\", \"listbox\", \"slider\"]);\n const dom = createDOMCart({ epoch: options.epoch, emit: options.emit, networkVersion: options.networkVersion ?? (() => 0), productSnapshot: options.productSnapshot });\n /** Emits a route observation only after a real URL change. */\n function navigation(): void {\n const epoch = options.epoch(), url = location.href;\n if (stopped || !epoch || url === current) return;\n const old = current; current = url; currentPage = null;\n if (pendingRoutes >= 128) { options.dropped(); return; }\n pendingRoutes++;\n const time = Date.now();\n void Promise.all([routeFor(url), old ? routeFor(old) : Promise.resolve(null)]).then(([page, from]) => {\n if (!page || stopped || options.epoch() !== epoch) return;\n if (current === url) currentPage = page;\n previous = from ?? \"\";\n let match: ProductMatch | undefined;\n try {\n const heading = current === url ? document.querySelector(\"main h1\") ?? document.querySelector(\"h1\") : null;\n match = heading ? options.productSnapshot?.(heading) : undefined;\n } catch { options.dropped(); }\n options.emit(\"navigation\", { action: \"page_view\", page, ...(previous ? { previous_page: previous } : {}),\n ...(match?.snapshot.metadata.resolution === \"resolved\" ? { product: { product_ref: match.product_ref, snapshot: match.snapshot } } : {}) }, epoch, time);\n }).catch(options.dropped).finally(() => { pendingRoutes--; });\n }\n /** Preserves History.pushState semantics and observes completed route changes. */\n function push(this: History, ...args: Parameters<History[\"pushState\"]>): void { Reflect.apply(originalPush, this, args); navigation(); }\n /** Preserves History.replaceState semantics and observes completed route changes. */\n function replace(this: History, ...args: Parameters<History[\"replaceState\"]>): void { Reflect.apply(originalReplace, this, args); navigation(); }\n /** Captures bounded ancestry/actions without merchant form values or arbitrary labels. */\n function click(event: MouseEvent): void {\n const epoch = options.epoch();\n if (stopped || !epoch || !(event.target instanceof Element) || event.composedPath().some(node => node instanceof Element && node.hasAttribute(\"data-sagepilot-popup\"))) return;\n if (pendingClicks >= 128) { options.dropped(); return; }\n try {\n const target = event.target.closest(\"button,a,input,select,textarea,[role='button']\") ?? event.target;\n const path: Json[] = [];\n let node: Element | null = target;\n for (let depth = 0; node && depth < 6; depth++, node = node.parentElement) {\n const role = node.getAttribute(\"role\"), type = node.getAttribute(\"type\"), parent: Element | null = node.parentElement;\n const sibling = parent && parent.children.length <= 64 ? Array.prototype.indexOf.call(parent.children, node) as number : -1;\n path.push({ tag: node.tagName.toLowerCase(), sibling_index: sibling, ...(role && roles.has(role) ? { role } : {}),\n ...(type && /^(button|submit|reset|checkbox|radio)$/.test(type) ? { type } : {}) });\n }\n const time = Date.now(), targetTag = target.tagName.toLowerCase();\n const evidence = semanticEvidence(target);\n let product: Record<string, Json> | Promise<Record<string, Json>> = {};\n try { product = dom.click(target, epoch, crypto.randomUUID()); } catch { options.dropped(); }\n /** Hands resolved source evidence to the journal before the merchant's navigation handler runs. */\n const emit = (ordinary: Record<string, Json>, page: string | null) => {\n if (!stopped && options.epoch() === epoch) options.emit(\"interaction\", { action: \"click\", target_tag: targetTag, target_path: path, ...evidence, ...ordinary, ...(page ? { page } : {}) }, epoch, time);\n };\n pendingClicks++;\n if (typeof (product as Promise<Record<string, Json>>).then !== \"function\") { try { emit(product as Record<string, Json>, current === location.href ? currentPage : null); } finally { queueMicrotask(() => { pendingClicks--; }); } }\n else void Promise.all([routeFor(location.href), Promise.resolve(product).catch(() => { options.dropped(); return {}; })]).then(([page, ordinary]) => emit(ordinary, page)).catch(options.dropped).finally(() => { pendingClicks--; });\n } catch { options.dropped(); }\n }\n history.pushState = push; history.replaceState = replace;\n document.addEventListener(\"click\", click, true);\n window.addEventListener(\"popstate\", navigation); window.addEventListener(\"hashchange\", navigation);\n navigation();\n /** Stops listeners without overwriting hooks installed by another library after ours. */\n return function stopPage(): void {\n stopped = true;\n dom.destroy();\n document.removeEventListener(\"click\", click, true);\n window.removeEventListener(\"popstate\", navigation); window.removeEventListener(\"hashchange\", navigation);\n if (history.pushState === push) history.pushState = originalPush;\n if (history.replaceState === replace) history.replaceState = originalReplace;\n };\n}\n\n/** Extracts an action vocabulary only; product identity is owned by the target-aware resolver. */\nfunction semanticEvidence(target: Element): Record<string, Json> {\n const hints = new Set([\"add\", \"cart\", \"remove\", \"checkout\", \"buy\", \"purchase\", \"wishlist\", \"product\", \"search\", \"subscribe\", \"submit\"]);\n const label = (target.getAttribute(\"aria-label\") ?? target.textContent ?? \"\").slice(0, 256).toLowerCase();\n const semanticTokens = [...new Set(label.split(/[^a-z]+/).filter(token => hints.has(token)))].sort();\n return { semantic_tokens: semanticTokens };\n}\n","import { project, projectText, routeFor, type Json } from \"./projection\";\nexport type Capture = (kind: \"network\" | \"navigation\" | \"interaction\" | \"lifecycle\", data: Record<string, Json>, epoch: string, time: number) => void;\ntype State = { id: string; epoch: string; method: string; url: string; route: Promise<string | null>; start: number; request: Json | null; status: number; bodySeen: boolean; cleanup?: () => void };\n\n/** Observes supported app-consumed bodies without cloning or initiating a read. */\nexport function observeNetwork(options: { epoch: () => string | null; excluded: (url: string) => boolean; emit: Capture; dropped: () => void; mutation?: () => void;\n products?: { observe(value: unknown, source: string): void; track(xhr: XMLHttpRequest, url: string, method: string): void } }): () => void {\n const fetchOriginal = globalThis.fetch, proto = globalThis.Response?.prototype;\n const textOriginal = proto?.text, jsonOriginal = proto?.json;\n const xhr = globalThis.XMLHttpRequest?.prototype, openOriginal = xhr?.open, sendOriginal = xhr?.send;\n const responses = new WeakMap<Response, State>(), requests = new WeakMap<XMLHttpRequest, State>();\n const active = new Set<State>(), xhrCleanups = new Set<() => void>();\n let stopped = false, insideFetch = false, pendingEmits = 0;\n /** Creates bounded request metadata and projects an already-provided JSON body immediately. */\n function state(url: string, method: string, body: unknown): State | null {\n const epoch = options.epoch();\n if (stopped || !epoch || active.size >= 128 || options.excluded(url)) return null;\n if (!/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i.test(method)) return null;\n if (!/^(GET|HEAD|OPTIONS)$/i.test(method)) {\n // A concurrent server mutation makes a DOM-only outcome ambiguous and could otherwise double-count it.\n try { options.mutation?.(); } catch { options.dropped(); }\n }\n const result: State = { id: crypto.randomUUID(), epoch, method: method.toUpperCase(), url, route: routeFor(url), start: performance.now(),\n request: projectText(body), status: 0, bodySeen: false };\n active.add(result); return result;\n }\n /** Emits only within original permission/identity boundaries; evidence never includes raw body strings. */\n function emit(item: State, phase: string, outcome: string, response: Json | null = null): void {\n if (stopped || options.epoch() !== item.epoch) return;\n if (pendingEmits >= 128) { item.request = null; options.dropped(); return; }\n pendingEmits++;\n const elapsed = Math.max(0, performance.now() - item.start), time = Date.now();\n const request = phase === \"headers\" ? item.request : null;\n if (phase === \"headers\") item.request = null;\n void item.route.then(route => {\n if (!route || stopped || options.epoch() !== item.epoch) return;\n options.emit(\"network\", { request_id: item.id, method: item.method, route, route_version: 2,\n status: item.status, duration_ms: Math.round(elapsed), outcome, phase, projection_version: 2,\n ...(request ? { request } : {}), ...(response ? { response } : {}) }, item.epoch, time);\n }).catch(options.dropped).finally(() => { pendingEmits--; });\n }\n /** Returns the original fetch promise and Response; a side observer only attaches metadata. */\n function fetchObserved(this: unknown, ...args: Parameters<typeof fetch>): ReturnType<typeof fetch> {\n let item: State | null = null;\n try {\n const input = args[0], init = args[1];\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.href : input.url;\n item = state(url, init?.method ?? (input instanceof Request ? input.method : \"GET\"), init?.body);\n } catch { options.dropped(); }\n let result: ReturnType<typeof fetch>;\n const previous = insideFetch;\n try { insideFetch = true; result = Reflect.apply(fetchOriginal, this, args); }\n catch (error) { if (item) { emit(item, \"headers\", \"error\"); active.delete(item); } throw error; }\n finally { insideFetch = previous; }\n const captured = item;\n if (captured) void result.then(response => {\n captured.status = response.status;\n emit(captured, \"headers\", \"completed\");\n if (!stopped && /(?:application|text)\\/(?:[a-z0-9.+-]*\\+)?json/i.test(response.headers.get(\"content-type\") ?? \"\")) responses.set(response, captured);\n active.delete(captured);\n }, () => { emit(captured, \"headers\", \"error\"); active.delete(captured); }).catch(options.dropped);\n return result;\n }\n /** Observes only the body consumption initiated by application code and preserves its promise. */\n function consume<T>(response: Response, original: (this: Response) => Promise<T>, isText: boolean): Promise<T> {\n const result = Reflect.apply(original, response, []), item = responses.get(response);\n if (item && !item.bodySeen) {\n item.bodySeen = true; responses.delete(response);\n void result.then(value => {\n if (stopped || options.epoch() !== item.epoch) return;\n try { if (item.status >= 200 && item.status < 300) options.products?.observe(value, item.url); const projected = isText ? projectText(value) : project(value); emit(item, \"body\", \"completed\", projected); }\n catch { options.dropped(); }\n }, () => {}).catch(options.dropped);\n }\n return result;\n }\n /** Wraps app-requested Response.text without starting any new body read. */\n function text(this: Response): Promise<string> { return consume(this, textOriginal!, true); }\n /** Wraps native browser Response.json; unlike RN it need not delegate to text(). */\n function json(this: Response): Promise<unknown> { return consume(this, jsonOriginal!, false); }\n /** Tracks XHR URL/method while preserving all original overload behavior. */\n function open(this: XMLHttpRequest, ...args: Parameters<XMLHttpRequest[\"open\"]>): void {\n const prior = requests.get(this);\n const result = Reflect.apply(openOriginal!, this, args);\n let url: string | null = null;\n try { url = String(args[1]); options.products?.track(this, url, args[0]); } catch { options.dropped(); }\n if (prior) { prior.cleanup?.(); active.delete(prior); requests.delete(this); }\n if (!insideFetch) {\n try { const item = url ? state(url, args[0], null) : null; if (item) requests.set(this, item); }\n catch { options.dropped(); }\n }\n return result;\n }\n /** Reads an already-completed text/JSON response; unsupported binary and streaming bodies stay unavailable. */\n function send(this: XMLHttpRequest, body?: Document | XMLHttpRequestBodyInit | null): void {\n const item = requests.get(this);\n if (!item || item.cleanup || stopped || options.epoch() !== item.epoch) return Reflect.apply(sendOriginal!, this, [body]);\n item.request = projectText(body);\n let outcome = \"completed\";\n /** Records transport outcome without interpreting business success. */\n const failed = (event: Event) => { outcome = event.type; };\n /** Removes this request's listeners and bounded bookkeeping. */\n const cleanup = () => {\n this.removeEventListener(\"loadend\", complete);\n for (const type of [\"error\", \"abort\", \"timeout\"]) this.removeEventListener(type, failed);\n active.delete(item); requests.delete(this); xhrCleanups.delete(cleanup); item.cleanup = undefined;\n };\n /** Projects only explicitly supported existing application response types. */\n const complete = () => {\n try {\n item.status = this.status;\n emit(item, \"headers\", outcome);\n if (outcome === \"completed\" && /(?:application|text)\\/(?:[a-z0-9.+-]*\\+)?json/i.test(this.getResponseHeader(\"content-type\") ?? \"\")) {\n if (item.status >= 200 && item.status < 300) options.products?.observe(this.responseType === \"json\" ? this.response : this.responseType === \"\" || this.responseType === \"text\" ? this.responseText : null, item.url);\n const response = this.responseType === \"json\" ? project(this.response)\n : this.responseType === \"\" || this.responseType === \"text\" ? projectText(this.responseText) : null;\n if (response) emit(item, \"body\", outcome, response);\n }\n } catch { options.dropped(); } finally { cleanup(); }\n };\n item.cleanup = cleanup; xhrCleanups.add(cleanup); this.addEventListener(\"loadend\", complete);\n for (const type of [\"error\", \"abort\", \"timeout\"]) this.addEventListener(type, failed);\n try { return Reflect.apply(sendOriginal!, this, [body]); } catch (error) { cleanup(); throw error; }\n }\n if (typeof fetchOriginal === \"function\") globalThis.fetch = fetchObserved;\n if (proto) proto.text = text;\n if (proto) proto.json = json;\n if (xhr) { xhr.open = open as typeof xhr.open; xhr.send = send; }\n /** Restores only wrappers still owned by this collector; later instrumentation remains intact. */\n return function stopNetwork(): void {\n stopped = true;\n for (const cleanup of [...xhrCleanups]) cleanup();\n active.clear();\n if (globalThis.fetch === fetchObserved) globalThis.fetch = fetchOriginal;\n if (proto?.text === text) proto.text = textOriginal!;\n if (proto?.json === json) proto.json = jsonOriginal!;\n if (xhr?.open === open) xhr.open = openOriginal!;\n if (xhr?.send === send) xhr.send = sendOriginal!;\n };\n}\n","import type { SagepilotSDKObservation } from \"@sagepilot-ai/sdk-installation-client\";\n\ntype ObservationKey = Pick<SagepilotSDKObservation, \"event_id\" | \"owner\">;\ntype JournalRecord<T> = { id: string; value: T; bytes: number; expires: number; purge?: string };\nexport type JournalDiagnostics = {\n storage: \"indexeddb\" | \"localStorage\" | \"memory\";\n pending_records: number;\n pending_bytes: number;\n memory_only_records: number;\n quota_evicted: number;\n expired_records: number;\n storage_failures: number;\n};\n\nexport const JOURNAL_TTL_MS = 24 * 60 * 60 * 1000;\nconst MAX_RECORDS = 8192, MAX_BYTES = 8 * 1024 * 1024;\nconst BACKUP_RECORDS = 256, BACKUP_BYTES = 512 * 1024;\n\n/** Opens a bounded journal with a small durable fallback for browsers that deny IndexedDB. */\nexport function createJournal<T extends ObservationKey>(scope: string) {\n const memory = new Map<string, JournalRecord<T>>();\n const backupSizes = new Map<string, number>();\n const prefix = `sagepilot:web-journal:${scope}:`, purgeKey = prefix + \"purged\";\n let db: IDBDatabase | null = null, backup: Storage | null = null;\n let pending = Promise.resolve(), opened: Promise<void> | null = null;\n let appends: { records: JournalRecord<T>[]; committed: Promise<void> } | null = null;\n let pendingBytes = 0, backupBytes = 0;\n let purge: string | null = null;\n let quotaEvicted = 0, expiredRecords = 0, storageFailures = 0;\n\n /** Rejects corrupt persisted entries before reading their owner or putting them on the wire. */\n function valid(record: JournalRecord<T>): boolean {\n return !!record && typeof record.id === \"string\" && record.id.length > 0 && record.id.length <= 128\n && Number.isSafeInteger(record.bytes) && record.bytes > 0 && record.bytes <= 32768 && Number.isFinite(record.expires)\n && record.value?.event_id === record.id && typeof record.value.owner?.session_id === \"string\"\n && (record.value.owner.customer_id === null || typeof record.value.owner.customer_id === \"string\");\n }\n\n /** Lists only this installation's fallback keys without reading other storage values. */\n function backupKeys(store: Storage): string[] {\n const keys: string[] = [];\n for (let index = 0; index < store.length; index++) {\n const key = store.key(index);\n if (key?.startsWith(prefix) && key !== purgeKey) keys.push(key);\n }\n return keys;\n }\n\n /** Restores sanitized records and the last consent purge marker before trying IndexedDB. */\n function readBackup(): JournalRecord<T>[] {\n const records: JournalRecord<T>[] = [];\n try {\n backup = globalThis.localStorage ?? null;\n if (!backup) return records;\n purge = backup.getItem(purgeKey);\n for (const key of backupKeys(backup)) {\n const raw = backup.getItem(key), size = (key.length + (raw?.length ?? 0)) * 2;\n let record: JournalRecord<T> | undefined;\n if (raw && size <= BACKUP_BYTES) {\n try { record = JSON.parse(raw) as JournalRecord<T>; } catch { /* Drop only the corrupt key. */ }\n }\n if (!record || !valid(record) || key !== prefix + record.id) { backup.removeItem(key); continue; }\n records.push(record);\n backupSizes.set(record.id, size); backupBytes += size;\n }\n } catch { backup = null; storageFailures++; }\n return records;\n }\n\n /** Stores one record per key so another tab's append cannot overwrite a saved batch. */\n function saveBackup(records: Iterable<JournalRecord<T>>): void {\n if (!backup) return;\n for (const record of records) {\n if (backupSizes.size >= BACKUP_RECORDS || backupBytes >= BACKUP_BYTES) break;\n if (backupSizes.has(record.id) || backupBytes + record.bytes > BACKUP_BYTES) continue;\n const key = prefix + record.id, raw = JSON.stringify(record), size = (key.length + raw.length) * 2;\n if (backupBytes + size > BACKUP_BYTES) continue;\n try { backup.setItem(key, raw); } catch { storageFailures++; break; }\n backupSizes.set(record.id, size); backupBytes += size;\n }\n }\n\n /** Deletes fallback copies after an acknowledgement, expiry or durable migration. */\n function removeBackup(ids: Iterable<string>): void {\n if (!backup) return;\n for (const id of ids) {\n const size = backupSizes.get(id);\n if (size === undefined) continue;\n try { backup.removeItem(prefix + id); } catch { storageFailures++; continue; }\n backupSizes.delete(id); backupBytes -= size;\n }\n }\n\n /** Preserves as much of the existing journal as the fallback budget can hold. */\n function fallback(): void {\n db?.close(); db = null; storageFailures++;\n saveBackup(memory.values());\n }\n\n /** Applies changes in one transaction and drops backup copies only after its commit. */\n async function persist(puts: JournalRecord<T>[], deletes: string[], clear = false): Promise<void> {\n removeBackup(deletes);\n if (db) {\n try {\n await new Promise<void>((resolve, reject) => {\n const tx = db!.transaction(\"events\", \"readwrite\"), store = tx.objectStore(\"events\");\n if (clear) store.clear();\n for (const id of deletes) store.delete(id);\n for (const record of puts) store.put(record);\n tx.oncomplete = () => resolve();\n tx.onabort = tx.onerror = () => reject(tx.error ?? new Error(\"Journal transaction failed\"));\n });\n removeBackup(puts.map(record => record.id));\n return;\n } catch { fallback(); }\n }\n saveBackup(deletes.length ? memory.values() : puts);\n }\n\n /** Restores the existing IndexedDB schema with a bounded wait for blocked browser storage. */\n function readIndexedDB(): Promise<JournalRecord<T>[]> {\n return new Promise((resolve, reject) => {\n let settled = false, connection: IDBDatabase | null = null;\n let timer = setTimeout(fail, 1500);\n\n /** Releases a late or unusable connection while allowing the fallback to take over. */\n function fail(): void {\n if (settled) return;\n settled = true; clearTimeout(timer); connection?.close();\n reject(new Error(\"IndexedDB journal is unavailable\"));\n }\n\n try {\n const request = indexedDB.open(\"sagepilot-web-events-\" + scope, 1);\n request.onupgradeneeded = () => { if (!request.result.objectStoreNames.contains(\"events\")) request.result.createObjectStore(\"events\", { keyPath: \"id\" }); };\n request.onerror = request.onblocked = fail;\n request.onsuccess = () => {\n if (settled) { request.result.close(); return; }\n connection = request.result;\n clearTimeout(timer); timer = setTimeout(fail, 5000);\n try {\n const tx = connection.transaction(\"events\", \"readonly\");\n const read = tx.objectStore(\"events\").getAll(undefined, MAX_RECORDS + 1);\n tx.onabort = tx.onerror = fail;\n tx.oncomplete = () => {\n if (settled) return;\n settled = true; clearTimeout(timer);\n db = connection; db!.onversionchange = fallback;\n resolve(read.result as JournalRecord<T>[]);\n };\n } catch { fail(); }\n };\n } catch { fail(); }\n });\n }\n\n /** Removes one entry and keeps hot-path byte accounting independent of journal size. */\n function remove(id: string): void {\n const record = memory.get(id);\n if (record) { memory.delete(id); pendingBytes -= record.bytes; }\n }\n\n /** Removes expired records and then evicts oldest records only if capacity is exhausted. */\n function prune(): string[] {\n const deleted: string[] = [], now = Date.now();\n for (const [id, record] of memory) {\n if (record.expires <= now) { remove(id); deleted.push(id); expiredRecords++; }\n }\n while (memory.size > MAX_RECORDS || pendingBytes > MAX_BYTES) {\n const id = memory.keys().next().value!;\n remove(id); deleted.push(id); quotaEvicted++;\n }\n return deleted;\n }\n\n /** Merges fallback and IndexedDB by occurrence ID without replacing another tab's records. */\n async function restore(): Promise<void> {\n const saved = readBackup();\n const primary = await readIndexedDB().catch(() => { storageFailures++; return []; });\n const corrupt: string[] = [];\n for (const record of [...saved, ...primary].filter(record => {\n if (valid(record) && (!purge || record.purge === purge)) return true;\n if (typeof record?.id === \"string\") corrupt.push(record.id);\n return false;\n }).sort((a, b) => a.expires - b.expires)) {\n remove(record.id); memory.set(record.id, record); pendingBytes += record.bytes;\n }\n const deleted = [...corrupt, ...prune()];\n const existing = new Set(primary.filter(valid).map(record => record.id));\n if (db) removeBackup(saved.filter(record => existing.has(record.id)).map(record => record.id));\n const migrate = db ? saved.filter(record => memory.has(record.id) && !existing.has(record.id)) : [];\n if (deleted.length || migrate.length) await persist(migrate, deleted);\n }\n\n /** Queues barriers after any earlier appends so consent purges and receipts retain their order. */\n function serial<R>(action: () => Promise<R>): Promise<R> {\n appends = null;\n const next = pending.then(async () => { await (opened ??= restore()); return action(); });\n pending = next.then(() => {}, () => { storageFailures++; });\n return next;\n }\n\n return {\n /** Coalesces queued captures into one disk transaction while preserving the capture order. */\n append(record: JournalRecord<T>): Promise<void> {\n if (appends) { appends.records.push(record); return appends.committed; }\n const records = [record];\n const committed = serial(async () => {\n if (appends?.records === records) appends = null;\n for (const item of records) {\n if (purge) item.purge = purge;\n remove(item.id); memory.set(item.id, item); pendingBytes += item.bytes;\n }\n const deleted = memory.size > MAX_RECORDS || pendingBytes > MAX_BYTES ? prune() : [];\n await persist(records.filter(item => memory.has(item.id)), deleted);\n });\n appends = { records, committed };\n return committed;\n },\n /** Selects a bounded upload batch without removing unacknowledged records. */\n batch(): Promise<T[]> {\n return serial(async () => {\n const deleted = prune();\n if (deleted.length) await persist([], deleted);\n const selected: T[] = [];\n let bytes = 0;\n for (const record of memory.values()) {\n if (selected.length >= 50 || bytes + record.bytes > 96 * 1024) break;\n selected.push(record.value); bytes += record.bytes;\n }\n return selected;\n });\n },\n /** Deletes only terminal receipt IDs from memory and any writable journal. */\n acknowledge(ids: Set<string>): Promise<void> {\n return serial(async () => { for (const id of ids) remove(id); await persist([], [...ids]); });\n },\n /** Purges evidence and fences the old generation if an inaccessible IndexedDB returns later. */\n clear(): Promise<void> {\n return serial(async () => {\n memory.clear(); pendingBytes = 0;\n purge = crypto.randomUUID();\n if (backup) {\n try {\n for (const key of backupKeys(backup)) backup.removeItem(key);\n backup.setItem(purgeKey, purge);\n } catch { storageFailures++; }\n }\n backupSizes.clear(); backupBytes = 0;\n await persist([], [], true);\n });\n },\n /** Reports known storage limits without exposing evidence or credentials. */\n diagnostics(): JournalDiagnostics {\n let volatile = 0;\n if (!db) for (const id of memory.keys()) if (!backupSizes.has(id)) volatile++;\n return { storage: db ? \"indexeddb\" : backup ? \"localStorage\" : \"memory\",\n pending_records: memory.size, pending_bytes: pendingBytes, memory_only_records: volatile,\n quota_evicted: quotaEvicted, expired_records: expiredRecords, storage_failures: storageFailures };\n },\n /** Closes browser handles after earlier writes settle. */\n async close(): Promise<void> { await pending; db?.close(); db = null; }\n };\n}\n","import type { SDKPopupBlock, SDKPopupDesign, SagepilotPopupConfig } from \"@sagepilot-ai/sdk-installation-client\";\n\nconst layouts = [\"centered\", \"image_left\", \"image_right\", \"bottom_sheet\"] as const;\nconst builtIns = new Set([\"logo\", \"title\", \"body\", \"hero\", \"form\"]);\nconst defaultBlocks: SDKPopupBlock[] = [{ kind: \"logo\" }, { kind: \"hero\" }, { kind: \"title\" }, { kind: \"body\" }, { kind: \"form\" }];\n\n/** Keeps public design assets to browser-safe HTTPS URLs before assigning any DOM property. */\nfunction asset(value: unknown): value is string {\n if (typeof value !== \"string\" || value.length > 1000 || !value.startsWith(\"https://\") || /[\\s\\\\'\"<>]/.test(value)) return false;\n try {\n const url = new URL(value);\n return url.protocol === \"https:\" && !!url.hostname && url.port !== \"0\" && !url.username && !url.password && !url.hash;\n } catch { return false; }\n}\n\n/** Applies the server's design bounds defensively before creating merchant-controlled nodes. */\nexport function validPopupDesign(design: SDKPopupDesign | null | undefined): boolean {\n if (design == null) return true;\n const color = (v: unknown): boolean => typeof v === \"string\" && /^#[0-9a-f]{6}$/i.test(v);\n const integer = (v: number, min: number, max: number): boolean => Number.isInteger(v) && v >= min && v <= max;\n if (!layouts.includes(design.layout) ||\n ![design.background_color, design.text_color, design.button_text_color].every(color) ||\n !integer(design.border_radius, 0, 40) || !integer(design.padding, 12, 40) || !integer(design.width, 280, 760) ||\n (design.font_family !== null && (typeof design.font_family !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9 _-]{0,79}$/.test(design.font_family))) ||\n [design.font_url, design.image_url].some(url => url !== null && !asset(url)) ||\n typeof design.image_alt !== \"string\" || design.image_alt.length > 200) return false;\n if (design.blocks === null) return true;\n if (!Array.isArray(design.blocks) || design.blocks.length > 12) return false;\n const seen = new Set<string>();\n return design.blocks.every(block => {\n if (!block || typeof block !== \"object\") return false;\n if (builtIns.has(block.kind)) {\n if (seen.has(block.kind)) return false;\n seen.add(block.kind);\n return true;\n }\n if (block.kind === \"heading\" || block.kind === \"text\") return typeof block.text === \"string\" && block.text.length > 0 && block.text.length <= 600;\n if (block.kind === \"image\") return asset(block.url) && typeof block.alt === \"string\" && block.alt.length <= 200;\n if (block.kind === \"link\") return asset(block.url) && typeof block.text === \"string\" && block.text.length > 0 && block.text.length <= 120;\n return false;\n }) && seen.has(\"form\");\n}\n\n/** Creates a text-only popup element from the supported block set. */\nfunction node<K extends keyof HTMLElementTagNameMap>(tag: K, value?: string): HTMLElementTagNameMap[K] {\n const result = document.createElement(tag);\n if (value !== undefined) result.textContent = value;\n return result;\n}\n\n/** Applies presentation without letting imported content own any form behavior. */\nexport function renderPopupDesign(panel: HTMLElement, host: HTMLElement, config: SagepilotPopupConfig, form: HTMLFormElement): () => void {\n const design = config.design;\n const blocks = design?.blocks ?? defaultBlocks;\n const content = node(\"div\");\n content.className = \"content\";\n const hero = design?.image_url && blocks.some(block => block.kind === \"hero\") ? popupImage(design.image_url, design.image_alt, \"hero\") : null;\n const split = hero && (design?.layout === \"image_left\" || design?.layout === \"image_right\");\n if (split) {\n const side = node(\"div\");\n side.className = \"side-art\";\n side.append(hero);\n panel.append(side);\n }\n let heading = false;\n for (const block of blocks) {\n switch (block.kind) {\n case \"logo\": if (config.logo_url) content.append(popupImage(config.logo_url, \"\", \"logo\")); break;\n case \"hero\": if (hero && !split) content.append(hero); break;\n case \"title\": case \"heading\": {\n const title = node(heading ? \"h3\" : \"h2\", block.kind === \"heading\" ? block.text : config.title);\n if (!heading) { title.id = \"sage-popup-title\"; heading = true; }\n content.append(title);\n break;\n }\n case \"body\": content.append(node(\"p\", config.body)); break;\n case \"text\": content.append(node(\"p\", block.text)); break;\n case \"image\": content.append(popupImage(block.url, block.alt, \"block-image\")); break;\n case \"link\": {\n const link = node(\"a\", block.text); link.href = block.url; link.target = \"_blank\"; link.rel = \"noopener noreferrer\";\n content.append(link); break;\n }\n case \"form\": content.append(form); break;\n }\n }\n panel.append(content);\n if (heading) panel.setAttribute(\"aria-labelledby\", \"sage-popup-title\");\n else panel.setAttribute(\"aria-label\", config.title);\n if (!design) return () => {};\n panel.dataset.design = \"\";\n panel.dataset.layout = split ? design.layout : design.layout === \"bottom_sheet\" ? \"bottom_sheet\" : \"centered\";\n if (panel.dataset.layout === \"bottom_sheet\") {\n host.style.alignItems = \"end\";\n host.style.paddingBottom = \"0\";\n }\n for (const [key, value] of Object.entries({\n \"--popup-surface\": design.background_color, \"--popup-text\": design.text_color, \"--popup-button-text\": design.button_text_color,\n \"--popup-radius\": design.border_radius + \"px\", \"--popup-padding\": design.padding + \"px\", \"--popup-width\": design.width + \"px\",\n })) panel.style.setProperty(key, value);\n let face: FontFace | undefined;\n const fallback = design.font_family ? JSON.stringify(design.font_family) + \", system-ui, sans-serif\" : \"system-ui, sans-serif\";\n if (design.font_url && typeof FontFace === \"function\" && document.fonts) {\n try {\n face = new FontFace(\"sage-popup-\" + crypto.randomUUID(), \"url(\" + JSON.stringify(design.font_url) + \")\");\n document.fonts.add(face);\n panel.style.fontFamily = JSON.stringify(face.family) + \", \" + fallback;\n } catch { panel.style.fontFamily = fallback; }\n } else panel.style.fontFamily = fallback;\n return () => { if (face) document.fonts.delete(face); };\n}\n\n/** Assigns an inert image and omits the storefront referrer. */\nfunction popupImage(url: string, alt: string, className: string): HTMLImageElement {\n const image = node(\"img\");\n image.referrerPolicy = \"no-referrer\";\n image.alt = alt;\n image.className = className;\n image.src = url;\n return image;\n}\n\nexport const popupDesignStyles = [\n \".panel[data-design]{background:var(--popup-surface);color:var(--popup-text);border-radius:var(--popup-radius);width:min(var(--popup-width),calc(100vw - 40px));padding:0;overflow-wrap:anywhere}\",\n \".panel[data-design] .content{min-width:0;padding:var(--popup-padding)}\",\n \".panel[data-design] :is(p,a){color:inherit;white-space:pre-wrap}\",\n \".panel[data-design] input:not([type=checkbox]){color:inherit;background:transparent;border-color:currentColor}\",\n \".panel[data-design] button[type=submit]{color:var(--popup-button-text)}\",\n \".panel[data-design] :is(.hero,.block-image){display:block;max-width:100%;width:100%;max-height:240px;object-fit:cover;border-radius:calc(var(--popup-radius)/2)}\",\n \".panel[data-layout=bottom_sheet]{border-end-start-radius:0;border-end-end-radius:0}\",\n \".panel .side-art{position:relative;min-width:0;overflow:hidden}.panel .side-art>.hero{border-radius:0}.panel[data-design] .close{z-index:1}\",\n \"@media(min-width:600px){.panel:is([data-layout=image_left],[data-layout=image_right]){display:grid;grid-template-columns:minmax(0,2fr) minmax(0,3fr);align-items:stretch}.panel:is([data-layout=image_left],[data-layout=image_right]) .side-art>.hero{position:absolute;inset:0;height:100%;max-height:none}.panel[data-layout=image_right]{grid-template-columns:minmax(0,3fr) minmax(0,2fr)}.panel[data-layout=image_right]>.side-art{grid-row:1;grid-column:2}.panel[data-layout=image_right]>.content{grid-row:1;grid-column:1}}\",\n].join(\"\");\n","import type { SagepilotInstallationClient, SagepilotPopupConfig, SagepilotContactInput, SagepilotContactResult } from \"@sagepilot-ai/sdk-installation-client\";\nimport { popupDesignStyles, renderPopupDesign, validPopupDesign } from \"./popup-design\";\n\nconst PHONE_FORMAT = /^\\+[1-9][0-9]{7,14}$/;\nconst PHONE_GUIDANCE = \"Start with + and your country code, e.g. +12025550123. No spaces or dashes.\";\n\ntype PopupOptions = {\n client: SagepilotInstallationClient;\n storage: { getItem(key: string): string | null; setItem(key: string, value: string): void };\n emit(action: \"popup_shown\" | \"popup_submitted\" | \"popup_dismissed\"): void;\n submit(input: SagepilotContactInput): Promise<SagepilotContactResult>;\n identify(challenge: string, code: string): Promise<void>;\n report(error: unknown): void;\n};\n\n/** Shares completion state with the returning visitor bootstrap. */\nexport function popupCompletionKey(workspaceId: string, installationId: string): string {\n return `sagepilot:sdk-popup:${workspaceId}:${installationId}:completed`;\n}\n\n/** Rejects malformed public popup settings before creating DOM or loading a merchant image. */\nfunction valid(value: SagepilotPopupConfig): boolean {\n if (!value || !Number.isSafeInteger(value.revision) || value.revision < 1 || typeof value.enabled !== \"boolean\" ||\n !/^#[0-9a-f]{6}$/i.test(value.accent_color) || ![\"email\", \"none\"].includes(value.verification) ||\n ![value.title, value.body, value.button_text, value.success_text].every(item => typeof item === \"string\" && item.length <= 2000) ||\n !value.fields || ![value.fields.name, value.fields.email, value.fields.phone].every(item => typeof item === \"boolean\") ||\n !Array.isArray(value.required_fields) || value.required_fields.some(field => ![\"name\", \"email\", \"phone\"].includes(field) || !value.fields[field]) ||\n value.verification === \"email\" && !value.fields.email ||\n !Number.isFinite(value.frequency_hours) || value.frequency_hours < 1 || value.frequency_hours > 8760 ||\n !value.trigger || !Number.isFinite(value.trigger.delay_seconds) || value.trigger.delay_seconds < 0 || value.trigger.delay_seconds > 300 ||\n !Number.isFinite(value.trigger.scroll_percent) || value.trigger.scroll_percent < 0 || value.trigger.scroll_percent > 100 ||\n !Array.isArray(value.trigger.page_paths) || value.trigger.page_paths.length > 20 || value.trigger.page_paths.some(path => typeof path !== \"string\" || !path.startsWith(\"/\") || path.startsWith(\"//\") || /[?#\\\\]/.test(path) || path.length > 300)) return false;\n if (value.logo_url !== null) {\n try { const url = new URL(value.logo_url); if (url.protocol !== \"https:\" || url.username || url.password) return false; } catch { return false; }\n }\n return validPopupDesign(value.design);\n}\n\n/** Renders one accessible, text-only popup; contacts exist only in the explicit form submission. */\nexport function createPopup(options: PopupOptions): { configure(value: SagepilotPopupConfig | null | undefined): void; destroy(): void } {\n let config: SagepilotPopupConfig | null = null, host: HTMLElement | null = null;\n let timer: ReturnType<typeof setInterval> | null = null, entered = Date.now(), path = location.pathname, generation = 0;\n let previousFocus: Element | null = null, cleanup: (() => void) | null = null;\n const scope = `sagepilot:sdk-popup:${options.client.workspaceId}:${options.client.installationId}`;\n const shownKey = scope + \":shown\";\n const completedKey = popupCompletionKey(options.client.workspaceId, options.client.installationId);\n\n /** Removes the popup, its focus trap and observers without leaving host styles behind. */\n function remove(): void {\n generation++; cleanup?.(); cleanup = null; host?.remove(); host = null;\n if (previousFocus instanceof HTMLElement && previousFocus.isConnected) previousFocus.focus();\n previousFocus = null;\n }\n\n /** Evaluates targeting locally without transmitting a page path or its query parameters. */\n function eligible(): boolean {\n const session = options.client.session();\n if (!config?.enabled || host || !session || session.customer_id ||\n options.storage.getItem(completedKey) === session.anonymous_id) return false;\n if (path !== location.pathname) { path = location.pathname; entered = Date.now(); }\n if (config.trigger.page_paths.length && !config.trigger.page_paths.includes(path)) return false;\n if (Date.now() - entered < config.trigger.delay_seconds * 1000) return false;\n const height = Math.max(document.documentElement.scrollHeight - innerHeight, 1);\n if (config.trigger.scroll_percent > 0 && scrollY / height * 100 < config.trigger.scroll_percent) return false;\n const raw = options.storage.getItem(shownKey), last = Number(raw);\n return !raw || !Number.isFinite(last) || Date.now() - last >= config.frequency_hours * 3600000;\n }\n\n /** Creates typed DOM elements with textContent so merchant content cannot execute markup. */\n function element<K extends keyof HTMLElementTagNameMap>(tag: K, text?: string): HTMLElementTagNameMap[K] {\n const node = document.createElement(tag); if (text !== undefined) node.textContent = text; return node;\n }\n\n /** Adds phone guidance and checks the trimmed value against the Platform API format. */\n function phoneField(label: HTMLLabelElement, input: HTMLInputElement): { group: HTMLElement; validate(): boolean } {\n const guidance = input.required ? PHONE_GUIDANCE : \"Optional. \" + PHONE_GUIDANCE;\n const hint = element(\"small\", guidance);\n hint.id = \"sage-popup-phone-hint\";\n hint.className = \"phone-hint\";\n hint.setAttribute(\"aria-live\", \"polite\");\n input.setAttribute(\"aria-describedby\", hint.id);\n\n /** Updates the inline message and allows an optional phone to be left blank. */\n function validate(): boolean {\n const value = input.value.trim();\n const invalid = (input.required || value.length > 0) && !PHONE_FORMAT.test(value);\n if (invalid === (input.getAttribute(\"aria-invalid\") === \"true\")) return !invalid;\n input.setAttribute(\"aria-invalid\", String(invalid));\n hint.classList.toggle(\"phone-error\", invalid);\n hint.textContent = invalid ? \"Check your phone number. \" + PHONE_GUIDANCE : guidance;\n return !invalid;\n }\n\n /** Clears the error once the visitor corrects or clears the number. */\n function updatePhoneError(): void {\n if (input.getAttribute(\"aria-invalid\") === \"true\") validate();\n }\n input.addEventListener(\"input\", updatePhoneError);\n const group = element(\"div\");\n group.append(label, hint);\n return { group, validate };\n }\n\n /** Displays the published template and retains no contact values in SDK diagnostics or events. */\n function show(): void {\n if (!eligible() || !config) return;\n const published = config, revision = ++generation;\n previousFocus = document.activeElement;\n host = element(\"div\"); host.setAttribute(\"data-sagepilot-popup\", \"\");\n host.style.cssText = \"position:fixed;inset:0;z-index:2147483000;display:grid;place-items:center;padding:20px;background:#10251d66\";\n const shadow = host.attachShadow({ mode: \"open\" });\n const style = element(\"style\");\n style.textContent = `:host{font-family:system-ui,sans-serif;color:#172c23;color-scheme:light}*{box-sizing:border-box}.panel{background:white;width:min(420px,calc(100vw - 40px));max-height:90dvh;overflow:auto;border-radius:18px;padding:28px;box-shadow:0 16px 80px #0003;position:relative}h2{margin:4px 28px 10px 0;font-size:25px}p{line-height:1.5;color:#52645a}label{display:block;margin-top:14px;font-size:14px}input{display:block;width:100%;padding:11px;border:1px solid #b6c7bd;border-radius:7px;margin-top:6px;font:inherit;background:white;color:#172c23}button{cursor:pointer;font:inherit;color:inherit}button[type=submit]{display:block;width:100%;border:0;border-radius:8px;background:${published.accent_color};color:white;padding:13px;margin-top:20px;font-weight:600}button:disabled{opacity:.6;cursor:wait}.close{position:absolute;right:15px;top:12px;border:0;background:transparent;font-size:25px}.status{min-height:1.3em;font-size:14px}.logo{max-width:160px;max-height:60px;object-fit:contain}input:focus-visible,button:focus-visible{outline:3px solid #729e82;outline-offset:3px}@media(max-width:480px){.panel{padding:22px}h2{font-size:22px}}`;\n style.textContent += \".phone-hint{display:block;margin-top:6px;line-height:1.4}.phone-error{font-weight:600}\";\n style.textContent += popupDesignStyles;\n shadow.append(style);\n const panel = element(\"section\"); panel.className = \"panel\"; panel.setAttribute(\"role\", \"dialog\"); panel.setAttribute(\"aria-modal\", \"true\");\n const close = element(\"button\", \"×\"); close.type = \"button\"; close.className = \"close\"; close.setAttribute(\"aria-label\", \"Close form\");\n /** Closes the form and records only the explicit lifecycle action. */\n function dismiss(): void { options.emit(\"popup_dismissed\"); remove(); }\n close.addEventListener(\"click\", dismiss); panel.append(close);\n const form = element(\"form\"), status = element(\"p\"); status.className = \"status\"; status.setAttribute(\"role\", \"status\"); status.setAttribute(\"aria-live\", \"polite\");\n const inputs = new Map<string, HTMLInputElement>();\n const contactFields: HTMLElement[] = [];\n let validatePhone: (() => boolean) | undefined;\n for (const field of [\"name\", \"email\", \"phone\"] as const) {\n if (!published.fields[field]) continue;\n const label = element(\"label\", field === \"phone\" ? \"Phone\" : field === \"email\" ? \"Email\" : \"Name\");\n const input = element(\"input\"); input.name = field; input.type = field === \"email\" ? \"email\" : field === \"phone\" ? \"tel\" : \"text\";\n input.autocomplete = field === \"phone\" ? \"tel\" : field; input.maxLength = field === \"phone\" ? 32 : field === \"email\" ? 254 : 100;\n input.required = published.required_fields.includes(field) || field === \"email\" && published.verification === \"email\";\n label.append(input);\n let control: HTMLElement = label;\n if (field === \"phone\") {\n const phone = phoneField(label, input);\n control = phone.group;\n validatePhone = phone.validate;\n }\n form.append(control); contactFields.push(control); inputs.set(field, input);\n }\n const submit = element(\"button\", published.button_text); submit.type = \"submit\"; form.append(submit, status);\n const cleanupDesign = renderPopupDesign(panel, host, published, form);\n shadow.append(panel); document.body.append(host);\n options.storage.setItem(shownKey, String(Date.now())); options.emit(\"popup_shown\");\n const contactInputs = new Map(inputs);\n let submissionId = crypto.randomUUID(), challenge: string | null = null, busy = false;\n\n /** Sends an idempotent contact or challenge response while blocking duplicate form submissions. */\n async function submitForm(event: SubmitEvent): Promise<void> {\n event.preventDefault(); if (busy || revision !== generation) return;\n if (!challenge && validatePhone?.() === false) {\n status.textContent = \"\";\n inputs.get(\"phone\")?.focus();\n return;\n }\n busy = true; submit.disabled = true; status.textContent = \"\";\n try {\n if (challenge) {\n await options.identify(challenge, inputs.get(\"code\")!.value);\n if (revision !== generation) return;\n form.replaceChildren(element(\"p\", published.success_text)); close.focus();\n } else {\n const contact: SagepilotContactInput = { submission_id: submissionId, popup_revision: published.revision, marketing_consent: true };\n for (const field of [\"name\", \"email\", \"phone\"] as const) { const value = inputs.get(field)?.value.trim(); if (value) contact[field] = value; }\n const result = await options.submit(contact);\n if (revision !== generation) return;\n options.emit(\"popup_submitted\");\n for (const input of inputs.values()) input.value = \"\";\n if (result.status === \"verification_required\") {\n challenge = result.challenge_id!; inputs.clear();\n const label = element(\"label\", \"Email verification code\"), code = element(\"input\");\n code.name = \"code\"; code.inputMode = \"numeric\"; code.autocomplete = \"one-time-code\"; code.pattern = \"[0-9]{6}\"; code.maxLength = 6; code.required = true;\n inputs.set(\"code\", code); label.append(code); submit.textContent = \"Verify email\";\n const restart = element(\"button\", \"Start again or use another email\"); restart.type = \"button\";\n /** Lets an expired challenge recover through a fresh explicit, rate-limited contact submission. */\n function restartForm(): void {\n if (busy) return;\n challenge = null; submissionId = crypto.randomUUID(); inputs.clear();\n for (const [key, value] of contactInputs) inputs.set(key, value);\n submit.textContent = published.button_text; status.textContent = \"\";\n form.replaceChildren(...contactFields, submit, status);\n inputs.values().next().value?.focus();\n }\n restart.addEventListener(\"click\", restartForm);\n form.replaceChildren(label, submit, restart, status); status.textContent = \"Check your email for the six-digit code.\"; code.focus();\n } else { form.replaceChildren(element(\"p\", published.success_text)); close.focus(); }\n }\n } catch (error) {\n if (revision === generation) status.textContent = challenge ? \"Verification failed. Check the code and try again.\" : \"We couldn't save the form. Please try again.\";\n options.report(error);\n } finally { busy = false; submit.disabled = false; }\n }\n form.addEventListener(\"submit\", submitForm);\n /** Keeps keyboard focus within the active dialog and supports Escape dismissal. */\n function keydown(event: KeyboardEvent): void {\n if (event.key === \"Escape\") { event.preventDefault(); dismiss(); return; }\n if (event.key !== \"Tab\") return;\n const focusable = [...shadow.querySelectorAll<HTMLElement>(\"button:not(:disabled),input:not(:disabled),a[href]\")];\n const first = focusable[0], last = focusable[focusable.length - 1];\n if (event.shiftKey && shadow.activeElement === first) { event.preventDefault(); last?.focus(); }\n else if (!event.shiftKey && shadow.activeElement === last) { event.preventDefault(); first?.focus(); }\n }\n shadow.addEventListener(\"keydown\", keydown as EventListener);\n cleanup = () => { cleanupDesign(); form.removeEventListener(\"submit\", submitForm); shadow.removeEventListener(\"keydown\", keydown as EventListener); };\n (inputs.values().next().value ?? close).focus();\n }\n\n return {\n /** Applies only a validated published revision; disabling immediately removes an open form. */\n configure(value): void {\n if (value && !valid(value)) { options.report(new Error(\"Invalid published popup configuration.\")); value = null; }\n if (value?.revision === config?.revision && value?.enabled === config?.enabled) return;\n remove(); config = value ?? null; entered = Date.now(); path = location.pathname;\n if (timer) clearInterval(timer); timer = null;\n if (config?.enabled) { timer = setInterval(show, 1000); show(); }\n },\n /** Cancels rendering and listeners when the installation runtime is destroyed. */\n destroy(): void { if (timer) clearInterval(timer); timer = null; config = null; remove(); }\n };\n}\n","import { createSagepilotInstallationClient, SagepilotInstallationError, type SagepilotSDKObservation, type SagepilotContactInput, type SagepilotContactResult } from \"@sagepilot-ai/sdk-installation-client\";\nimport { name as SDK_NAME, version as SDK_VERSION } from \"../package.json\";\nimport { observePage } from \"./collectors\";\nimport { observeNetwork, type Capture } from \"./network\";\nimport { createJournal, JOURNAL_TTL_MS } from \"./storage\";\nimport { createPopup, popupCompletionKey } from \"./popup\";\nimport { createProductIndex } from \"./product\";\n\nexport type SagepilotWebEventsOptions = {\n key: string;\n /** HTTPS gateway origin; loopback origins are supported for local development. */\n apiHost?: string;\n /** Explicit website collection permission; capture is off by default. */\n collectionEnabled?: boolean;\n /** Optional custom transport for first-party requests and local integration fixtures. */\n fetch?: typeof fetch;\n onError?: (error: unknown) => void;\n};\nexport type SagepilotWebEvents = {\n start(): Promise<void>;\n setCollectionEnabled(enabled: boolean): Promise<void>;\n flush(): Promise<void>;\n submitContact(input: SagepilotContactInput): Promise<SagepilotContactResult>;\n verifyContact(challengeId: string, code: string): Promise<void>;\n logout(): Promise<void>;\n refreshConfig(): Promise<void>;\n diagnostics(): ReturnType<ReturnType<typeof createJournal>[\"diagnostics\"]> & {\n enabled: boolean; rejected_payloads: number; collector_dropped: number; anonymous_id_storage: \"cookie\" | \"localStorage\" | \"memory\";\n };\n destroy(): Promise<void>;\n};\nconst instances = new Map<string, SagepilotWebEvents>();\nconst VISITOR_KEY = \"sagepilot_anonymous_id\";\nconst VISITOR_ID = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** Creates or reuses one installation collector; no hooks or HTTP calls run until start(). */\nexport function createSagepilotWebEvents(options: SagepilotWebEventsOptions): SagepilotWebEvents {\n const scope = options.key.toLowerCase();\n const existing = instances.get(scope);\n if (existing) return existing;\n let anonymousStorage: \"cookie\" | \"localStorage\" | \"memory\" = \"memory\";\n let browserId: string | null = null;\n let cookieRequests: Promise<unknown> = Promise.resolve();\n let cookieSynced = false;\n const memory = new Map<string, string>();\n /** Shields the website from browser privacy-mode and quota storage failures. */\n const storage = {\n getItem(key: string): string | null { try { return localStorage.getItem(key) ?? memory.get(key) ?? null; } catch { return memory.get(key) ?? null; } },\n setItem(key: string, value: string): void { memory.set(key, value); try { localStorage.setItem(key, value); } catch { /* Scoped session remains in runtime memory. */ } },\n removeItem(key: string): void { memory.delete(key); try { localStorage.removeItem(key); } catch { /* Browser storage is unavailable. */ } }\n };\n const client = createSagepilotInstallationClient({\n key: options.key, apiHost: options.apiHost, platform: \"web\", fetch: options.fetch, storage,\n sdk: { name: SDK_NAME, version: SDK_VERSION },\n });\n const completedKey = popupCompletionKey(client.workspaceId, client.installationId);\n const cookieKey = `sagepilot:sdk-visitor-cookie:${scope}`;\n const journal = createJournal<SagepilotSDKObservation>(scope.replace(/:/g, \"_\"));\n let localPermission = options.collectionEnabled === true, started = false, destroyed = false, policyKnown = false;\n let identityChanging = false;\n let starting: Promise<void> | null = null, draining: Promise<void> | null = null;\n let generation = 0, epoch = \"\", failures = 0, rejected = 0, dropped = 0, lastRefresh = 0, capturePending = 0, captureBytes = 0, networkMutations = 0;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let policyTimer: ReturnType<typeof setInterval> | null = null;\n let stopPage: (() => void) | null = null, stopNetwork: (() => void) | null = null;\n let products: ReturnType<typeof createProductIndex> | null = null;\n /** Isolates host callbacks from instrumentation and transport behavior. */\n function report(error: unknown): void { try { options.onError?.(error); } catch { /* Host errors cannot break the SDK. */ } }\n\n /** Requires both dashboard policy and the browser's current analytics permission. */\n function canUseVisitorCookie(): boolean {\n const session = client.session();\n return !destroyed && localPermission && session?.collection_enabled === true && session.visitor_cookie_enabled === true;\n }\n\n /** Serializes cookie writes so a consent withdrawal clears any earlier completion update. */\n function syncVisitorCookie(anonymousId: string | null, allowed: boolean) {\n if (!allowed) cookieSynced = false;\n const operation = cookieRequests.then(async () => {\n if (allowed) {\n if (!canUseVisitorCookie()) return null;\n // A lost response can still set a cookie. Keep the marker so it can be cleared later.\n storage.setItem(cookieKey, \"1\");\n } else if (!storage.getItem(cookieKey)) return null;\n try {\n const visitor = await client.syncVisitorCookie(\n anonymousId, allowed, anonymousId !== null && storage.getItem(completedKey) === anonymousId,\n );\n if (visitor.anonymous_id === null) {\n cookieSynced = false;\n storage.removeItem(cookieKey);\n }\n return visitor;\n } catch (error) {\n if (!destroyed) report(error);\n return null;\n }\n });\n cookieRequests = operation;\n return operation;\n }\n\n /** Keeps the active ID in browser storage for use when the cookie route is unavailable. */\n function rememberBrowser(anonymousId: string, restored: boolean): void {\n memory.set(VISITOR_KEY, anonymousId);\n try {\n if (localStorage.getItem(VISITOR_KEY) !== anonymousId) localStorage.setItem(VISITOR_KEY, anonymousId);\n anonymousStorage = \"localStorage\";\n } catch { anonymousStorage = \"memory\"; }\n if (restored) anonymousStorage = \"cookie\";\n browserId = anonymousId;\n }\n\n /** Reconciles the storefront cookie before using the refreshed capture and popup policy. */\n async function syncCookiePolicy(revision: number): Promise<void> {\n if (destroyed || revision !== generation) return;\n const session = client.session();\n if (!session?.collection_enabled || session.visitor_cookie_enabled !== true) {\n await syncVisitorCookie(null, false);\n if (browserId && anonymousStorage === \"cookie\") rememberBrowser(browserId, false);\n return;\n }\n if (cookieSynced || !localPermission) return;\n const currentId = session.anonymous_id;\n const cookie = await syncVisitorCookie(currentId, true);\n const restoredId = cookie?.anonymous_id;\n if (!restoredId || revision !== generation || !canUseVisitorCookie() ||\n client.session()?.anonymous_id !== currentId) return;\n if (cookie.popup_completed) {\n storage.setItem(completedKey, restoredId);\n popup.configure(null);\n }\n rememberBrowser(restoredId, cookie.restored);\n if (restoredId !== currentId) {\n policyKnown = false;\n epoch = crypto.randomUUID();\n detach(true);\n popup.configure(null);\n client.destroy();\n await client.start(restoredId);\n }\n if (revision === generation && canUseVisitorCookie()) cookieSynced = true;\n }\n\n /** Bootstraps the installation policy before making any request to the optional cookie route. */\n async function startVisitor(revision: number): Promise<void> {\n const saved = browserId ?? storage.getItem(VISITOR_KEY);\n const anonymousId = saved && VISITOR_ID.test(saved) ? saved : crypto.randomUUID();\n rememberBrowser(anonymousId, false);\n await client.start(anonymousId);\n await syncCookiePolicy(revision);\n }\n\n /** Persists completion only after the server accepts the form or verifies the email. */\n async function completeVisitor(anonymousId: string | undefined): Promise<void> {\n if (!anonymousId || destroyed || client.session()?.anonymous_id !== anonymousId) return;\n storage.setItem(completedKey, anonymousId);\n if (canUseVisitorCookie()) await syncVisitorCookie(anonymousId, true);\n }\n\n /** Clears the optional cookie and the unsent observations on consent withdrawal. */\n async function clearCollection(): Promise<void> {\n await Promise.all([journal.clear(), syncVisitorCookie(null, false)]);\n }\n /** Keeps capture within both local consent and the last confirmed server permission lease. */\n function enabled(): boolean {\n if (destroyed || identityChanging || !started || !localPermission || !policyKnown) return false;\n const session = client.session();\n return session?.collection_enabled === true && Date.parse(session.expires_at) > Date.now();\n }\n /** Returns a capture fence only while this installation is allowed to observe. */\n function captureEpoch(): string | null { return enabled() ? epoch : null; }\n /** Excludes SDK bootstrap and its configured ingress before request data is observed. */\n function excluded(input: string): boolean {\n try {\n const url = new URL(input, location.href), session = client.session();\n return (url.origin === client.apiHost && url.pathname.startsWith(\"/platform-api/v1/sdk/\"))\n || url.origin === location.origin && url.pathname === client.visitorCookiePath\n || !!session && url.origin + url.pathname === session.ingestion_url;\n } catch { return true; }\n }\n /** Snapshots original ownership and appends sanitized records only within the capture fence. */\n const capture: Capture = (kind, data, capturedEpoch, time) => {\n const session = client.session();\n if (!session || !enabled() || epoch !== capturedEpoch) { dropped++; return; }\n const observation: SagepilotSDKObservation = {\n event_id: crypto.randomUUID(), kind, occurred_at: new Date(time).toISOString(),\n owner: { session_id: session.session_id, customer_id: session.customer_id, identity_epoch: capturedEpoch },\n workspace_id: session.workspace_id, installation_id: session.installation_id, platform: \"web\",\n sdk_name: SDK_NAME, sdk_version: SDK_VERSION, clock_quality: \"unverified\", clock_source: \"device_wall\", data\n };\n const bytes = new TextEncoder().encode(JSON.stringify(observation)).byteLength;\n if (bytes > 32768) { rejected++; return; }\n if (capturePending >= 128 || captureBytes + bytes > 512 * 1024) { dropped++; return; }\n capturePending++; captureBytes += bytes;\n void journal.append({ id: observation.event_id, value: observation, bytes, expires: Date.now() + JOURNAL_TTL_MS })\n .catch(report).finally(() => { capturePending--; captureBytes -= bytes; });\n };\n const popup = createPopup({ client, storage, report,\n emit(action) { if (enabled()) capture(\"lifecycle\", { action }, epoch, Date.now()); },\n submit(input) { return addon.submitContact(input); },\n identify(challenge, code) { return addon.verifyContact(challenge, code); }\n });\n /** Pauses collectors before proof/logout; old queued records retain original ownership and credentials. */\n async function changeIdentity(operation: () => Promise<unknown>): Promise<void> {\n if (!started || destroyed) throw new Error(\"Start the web-events installation first.\");\n if (identityChanging) throw new Error(\"An SDK identity operation is already running.\");\n identityChanging = true;\n generation++; epoch = crypto.randomUUID(); detach(true); client.cancelPending();\n try { await operation(); }\n finally {\n identityChanging = false;\n if (!destroyed) { epoch = crypto.randomUUID(); if (enabled()) attach(); else detach(); schedule(); }\n }\n }\n /** Refreshes capture permission and independently published popup settings on the existing session. */\n async function refreshConfig(): Promise<void> {\n if (identityChanging) return;\n const revision = generation;\n const previous = client.session();\n try {\n await client.refresh(true);\n await syncCookiePolicy(revision);\n }\n catch (error) {\n if (revision === generation && !destroyed) {\n popup.configure(null);\n const status = error instanceof SagepilotInstallationError ? error.status ?? 0 : 0;\n const temporary = error instanceof SagepilotInstallationError && (error.code === \"network_error\" ||\n status === 408 || status === 425 || status === 429 || status >= 500);\n if (!temporary) suspendCapture();\n }\n throw error;\n }\n if (revision !== generation || destroyed) return;\n if (previous?.session_id !== client.session()?.session_id || Date.parse(previous?.expires_at ?? \"\") <= Date.now()) {\n epoch = crypto.randomUUID();\n }\n lastRefresh = Date.now(); policyKnown = true;\n popup.configure(client.session()?.popup);\n if (!client.session()?.collection_enabled) { detach(); await journal.clear(); }\n else { attach(); schedule(); }\n }\n /** Fences capture after an authoritative failure and lets config renewal reestablish permission. */\n function suspendCapture(): void {\n policyKnown = false; lastRefresh = 0; epoch = crypto.randomUUID(); detach(); schedule();\n }\n /** Detaches all event sources before asynchronous permission or ownership work begins. */\n function detach(preserveProducts = false): void {\n stopPage?.(); stopPage = null; stopNetwork?.(); stopNetwork = null;\n if (preserveProducts) products?.pause(); else { products?.destroy(); products = null; }\n if (retryTimer) clearTimeout(retryTimer); retryTimer = null;\n }\n /** Installs the currently permitted collectors once. */\n function attach(): void {\n if (!enabled()) return;\n armNetwork(); products?.activate();\n if (!stopPage) stopPage = observePage({ epoch: captureEpoch, emit: capture, dropped: () => { dropped++; },\n networkVersion: () => networkMutations, productSnapshot: (root, price, currency, label) => products?.resolve(root, price, currency, label) });\n }\n /** Tracks only weak startup XHR metadata before authorization; ordinary capture stays gated. */\n function armNetwork(): void {\n if (destroyed || !localPermission || stopNetwork) return;\n products ??= createProductIndex({ epoch: captureEpoch });\n stopNetwork = observeNetwork({ epoch: captureEpoch, excluded, emit: capture, dropped: () => { dropped++; },\n mutation: () => { networkMutations++; }, products });\n }\n /** Maintains one retry timer; the collector never wakes repeatedly while disabled. */\n function schedule(): void {\n if (!started || destroyed || !localPermission || identityChanging || retryTimer) return;\n const delay = failures ? Math.min(60000, 2000 * 2 ** Math.min(failures, 5)) * (0.8 + Math.random() * 0.4) : 2000;\n retryTimer = setTimeout(() => { retryTimer = null; void flush().catch(report).finally(schedule); }, delay);\n }\n /** Refreshes server permission and uploads bounded same-owner batches; missing receipts retain records. */\n async function flush(): Promise<void> {\n if (draining) return draining;\n if (!started || destroyed || !localPermission || identityChanging) return;\n const revision = generation;\n draining = (async () => {\n try {\n if (!policyKnown || Date.now() - lastRefresh > 60000) await refreshConfig();\n if (revision !== generation || !enabled()) return;\n for (let pass = 0; pass < 4; pass++) {\n const queued = await journal.batch();\n const first = queued[0]?.owner;\n const batch = queued.filter(item => item.owner.session_id === first?.session_id && item.owner.customer_id === first?.customer_id);\n if (revision !== generation || !enabled()) return;\n if (!batch.length) { failures = 0; return; }\n if (!client.hasCaptureOwner(first!)) {\n // Credentials are bounded and logout revokes authority; report loss instead of blocking every newer owner.\n dropped += batch.length; await journal.acknowledge(new Set(batch.map(item => item.event_id))); continue;\n }\n const receipt = await client.upload(batch, first!);\n if (revision !== generation || !enabled()) return;\n const terminal = new Set(receipt.results.filter(item => item.status !== \"retryable\").map(item => item.event_id));\n dropped += receipt.results.filter(item => item.status === \"disabled\" || item.status === \"invalid\").length;\n await journal.acknowledge(terminal);\n if (terminal.size !== batch.length) { failures = Math.min(failures + 1, 6); return; }\n failures = 0;\n }\n } catch (error) {\n if (revision === generation && !destroyed) {\n failures = Math.min(failures + 1, 6);\n if (client.session()?.collection_enabled === false) { detach(); await journal.clear(); }\n else if (policyKnown && error instanceof SagepilotInstallationError && [401, 403, 404, 410].includes(error.status ?? 0)) suspendCapture();\n }\n throw error;\n }\n })().finally(() => { draining = null; });\n return draining;\n }\n /** Resumes flushing on connectivity restoration without reinitializing browser observers. */\n function online(): void { void flush().catch(report); }\n const addon: SagepilotWebEvents = {\n /** Bootstraps this browser owner without loading chat, showing a popup or collecting before consent. */\n async start(): Promise<void> {\n if (destroyed) throw new Error(\"This web-events collector was destroyed.\");\n if (starting) return starting;\n if (started) return;\n if (typeof window === \"undefined\" || !globalThis.crypto?.randomUUID) throw new Error(\"Web events require a browser on HTTPS or loopback.\");\n const revision = generation;\n starting = (async () => {\n armNetwork();\n await startVisitor(revision);\n if (destroyed || revision !== generation) return;\n started = true; policyKnown = true; epoch = crypto.randomUUID(); lastRefresh = Date.now();\n popup.configure(client.session()?.popup);\n window.addEventListener(\"online\", online);\n policyTimer = setInterval(() => { void refreshConfig().catch(report); }, 60000);\n if (!localPermission || !client.session()?.collection_enabled) detach();\n if (!client.session()?.collection_enabled) await journal.clear();\n attach(); schedule();\n })().catch(error => {\n if (revision !== generation || destroyed) return;\n detach();\n throw error;\n }).finally(() => { starting = null; });\n return starting;\n },\n /** Fences immediately; disabling aborts SDK requests and purges unuploaded evidence. */\n async setCollectionEnabled(next: boolean): Promise<void> {\n if (destroyed) throw new Error(\"This web-events collector was destroyed.\");\n if (typeof next !== \"boolean\") throw new Error(\"Collection permission must be boolean.\");\n if (localPermission === next && started) {\n if (!next) await clearCollection();\n return;\n }\n localPermission = next; generation++; epoch = crypto.randomUUID(); detach(); client.cancelPending();\n if (!next) { await clearCollection(); return; }\n if (starting) await starting;\n if (destroyed || !localPermission) return;\n if (!started) { await addon.start(); return; }\n const revision = generation; policyKnown = false;\n try {\n await client.refresh(true);\n await syncCookiePolicy(revision);\n if (revision !== generation || destroyed || !localPermission) return;\n lastRefresh = Date.now(); policyKnown = true;\n popup.configure(client.session()?.popup);\n if (!client.session()?.collection_enabled) await journal.clear();\n attach(); schedule();\n } catch (error) { if (revision === generation && !destroyed) { lastRefresh = 0; schedule(); } throw error; }\n },\n flush,\n /** Submits contact-only data through the explicit identity endpoint, never through autocapture. */\n async submitContact(input) {\n const anonymousId = client.session()?.anonymous_id;\n const result = await client.submitContact(input);\n if (result.status === \"recorded\") await completeVisitor(anonymousId);\n return result;\n },\n /** Verifies proof behind a capture fence; buffered anonymous observations remain anonymous. */\n async verifyContact(challengeId, code) {\n const anonymousId = client.session()?.anonymous_id;\n await changeIdentity(() => client.verifyContact(challengeId, code));\n await completeVisitor(anonymousId);\n },\n /** Applies an explicit logout boundary without relabeling earlier observations. */\n logout() {\n return changeIdentity(async () => {\n try { await client.logout(); }\n catch (error) {\n // The server may have revoked the old owner even when its response was lost.\n policyKnown = false; lastRefresh = 0;\n throw error;\n }\n });\n },\n refreshConfig,\n /** Reports bounded operational counters, never contact values, credentials or queued payloads. */\n diagnostics() { return { ...journal.diagnostics(), enabled: enabled(), rejected_payloads: rejected, collector_dropped: dropped, anonymous_id_storage: anonymousStorage }; },\n /** Stops the runtime and requests; consent revocation is the separate purge operation. */\n async destroy(): Promise<void> {\n destroyed = true; generation++; detach(); if (policyTimer) clearInterval(policyTimer); policyTimer = null; popup.destroy(); client.destroy();\n if (typeof window !== \"undefined\") window.removeEventListener(\"online\", online);\n await journal.close();\n if (instances.get(scope) === addon) instances.delete(scope);\n }\n };\n instances.set(scope, addon);\n return addon;\n}\n"],"mappings":";AACO,IAAM,6BAAN,cAAyC,MAAM;AAAA,EAIpD,YACW,MACT,SACA,UAAgD,CAAC,GACjD;AACA,UAAM,OAAO;AAJJ;AAKT,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ;AACtB,SAAK,QAAQ,QAAQ;AAAA,EACvB;AACF;AAmFA,IAAM,OAAO;AACb,IAAM,aAAa;AACnB,IAAM,WAAW,oBAAI,IAAI,CAAC,YAAY,aAAa,YAAY,WAAW,WAAW,CAAC;AAGtF,SAAS,QAAQ,OAAoB;AACnC,QAAM,MAAM,IAAI,IAAI,KAAK;AACzB,MAAI,IAAI,YAAY,IAAI,YAAY,IAAI,UAAU,IAAI,QACjD,IAAI,aAAa,YAAY,EAAE,IAAI,aAAa,WAAW,CAAC,aAAa,aAAa,SAAS,UAAU,EAAE,SAAS,IAAI,QAAQ,IAAK;AACxI,UAAM,IAAI,MAAM,mFAAmF;AAAA,EACrG;AACA,SAAO;AACT;AAGO,SAAS,qCAAqC,OAAgB,cAAsD;AACzH,QAAM,UAAW,OAA+C;AAChE,MAAI,CAAC,MAAM,QAAQ,OAAO,EAAG,OAAM,IAAI,MAAM,mCAAmC;AAChF,QAAM,YAAY,IAAI,IAAI,YAAY,GAAG,OAAO,oBAAI,IAAY;AAChE,MAAI,UAAU,SAAS,aAAa,OAAQ,OAAM,IAAI,MAAM,+CAA+C;AAC3G,aAAW,QAAQ,SAAS;AAC1B,QAAI,CAAC,QAAQ,CA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B,kBAAY;AAAM;AAAc,aAAO;AAAG,UAAI,YAAa,eAAc,WAAW;AAAG,oBAAc;AAAM,YAAM,QAAQ;AAAG,aAAO,QAAQ;AAC3I,UAAI,OAAO,WAAW,YAAa,QAAO,oBAAoB,UAAU,MAAM;AAC9E,YAAM,QAAQ,MAAM;AACpB,UAAI,UAAU,IAAI,KAAK,MAAM,MAAO,WAAU,OAAO,KAAK;AAAA,IAC5D;AAAA,EACF;AACA,YAAU,IAAI,OAAO,KAAK;AAC1B,SAAO;AACT;","names":["text","label","node","value","name","row","project","text","pending","form","nodes","price","node","name","node","label","text","valid","id","record","text","node","label","restartForm","VISITOR_ID","price","label"]}