@sentientui/core 0.41.2 → 0.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -3
- package/dist/chunk-5VIREVXA.mjs +2 -0
- package/dist/chunk-5VIREVXA.mjs.map +1 -0
- package/dist/chunk-BGZLWZUG.mjs +2 -0
- package/dist/chunk-BGZLWZUG.mjs.map +1 -0
- package/dist/chunk-JNQY3XNF.mjs +2 -0
- package/dist/chunk-JNQY3XNF.mjs.map +1 -0
- package/dist/chunk-LCYGZNFI.mjs +2 -0
- package/dist/chunk-LCYGZNFI.mjs.map +1 -0
- package/dist/chunk-WUFFNQHQ.mjs +2 -0
- package/dist/{chunk-J5EL7HKC.mjs.map → chunk-WUFFNQHQ.mjs.map} +1 -1
- package/dist/{index-DlJDNOWu.d.cts → index-CWHTKETi.d.cts} +34 -5
- package/dist/index-consent.js +1 -1
- package/dist/index-consent.js.map +1 -1
- package/dist/index-consent.mjs +1 -1
- package/dist/index-consent.mjs.map +1 -1
- package/dist/{index-C--aVpoo.d.ts → index-cqfRT6LZ.d.ts} +34 -5
- package/dist/index-engagement.js +1 -1
- package/dist/index-engagement.js.map +1 -1
- package/dist/index-engagement.mjs +1 -1
- package/dist/index-engagement.mjs.map +1 -1
- package/dist/index-graph.d.cts +2 -2
- package/dist/index-graph.d.ts +2 -2
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.js.map +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index-graph.mjs.map +1 -1
- package/dist/index-internal-traffic.d.cts +37 -0
- package/dist/index-internal-traffic.d.ts +37 -0
- package/dist/index-internal-traffic.js +2 -0
- package/dist/index-internal-traffic.js.map +1 -0
- package/dist/index-internal-traffic.mjs +2 -0
- package/dist/index-internal-traffic.mjs.map +1 -0
- package/dist/index-local.d.cts +1 -1
- package/dist/index-local.d.ts +1 -1
- package/dist/index-region.mjs +1 -1
- package/dist/index-server.d.cts +25 -1
- package/dist/index-server.d.ts +25 -1
- package/dist/index-server.js +1 -1
- package/dist/index-server.js.map +1 -1
- package/dist/index-server.mjs +1 -1
- package/dist/index-server.mjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/llms.txt +2 -1
- package/package.json +7 -2
- package/dist/chunk-FPOHOWJP.mjs +0 -2
- package/dist/chunk-FPOHOWJP.mjs.map +0 -1
- package/dist/chunk-J5EL7HKC.mjs +0 -2
- package/dist/chunk-KXA3X6T3.mjs +0 -2
- package/dist/chunk-KXA3X6T3.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index-consent.ts","../src/consent-sources.ts","../src/storage-key.ts","../src/snapshot.ts","../src/queue.ts","../src/goal-queue.ts","../src/cookie-domain.ts","../src/forget.ts"],"sourcesContent":["/** `@sentientui/core/consent`: read a visitor's consent from the site's\n * consent platform (Cookiebot, OneTrust, CookieYes, IAB TCF v2.2, Google\n * Consent Mode v2, or a cookie/check of your own). Its own entry so installs\n * that never configure `consentFrom` don't download it. */\nexport {\n consentWatcher,\n consentFromCookies,\n consentModeGranted,\n tcStringConsents,\n TCF_DEFAULT_PURPOSES,\n tcStringPurposes,\n cookiebotCookieGrants,\n onetrustCookieGrants,\n cookieyesCookieGrants,\n} from './consent-sources.js';\nexport type { ConsentSource, ConsentPreset, ConsentWatcher } from './consent-sources.js';\nexport { forgetVisitor } from './forget.js';\n","// Consent sources: where the SDK reads a visitor's consent decision from, so a\n// site keeps its own consent manager (CMP) and we only OBSERVE it. Shared by\n// React (`consentFrom`), Next.js `AdaptiveRoot` (server read of the CMP's own\n// cookie → SSR for visitors who already consented) and the snippet.\n//\n// Presets encode each platform's documented API, verified 2026-09-24:\n// - Cookiebot: `Cookiebot.consent.{preferences,statistics,marketing}`; window\n// events CookiebotOnAccept / CookiebotOnDecline (both also fire on load for a\n// returning visitor) / CookiebotOnConsentReady; cookie `CookieConsent` =\n// `{stamp:'…',necessary:true,preferences:…,statistics:…,marketing:…,…}`,\n// \"0\" = declined, \"-1\" = consent not required in the visitor's region.\n// - OneTrust: `OnetrustActiveGroups` (\",C0001,C0002,\"), window event\n// OneTrustGroupsUpdated; cookie `OptanonConsent` with `groups=C0001:1,C0002:0`.\n// C0002 = Performance.\n// - CookieYes: `getCkyConsent().categories.{functional,analytics,performance,\n// advertisement}` (only after the banner loads); `cookieyes_consent_update`\n// dispatched on DOCUMENT; cookie `cookieyes-consent` observed as\n// `consentid:…,consent:yes,…,analytics:yes,…` (not officially documented —\n// used server-side only, and an unrecognised value is \"unknown\", not \"no\").\n// - IAB TCF v2.2: `__tcfapi('addEventListener', 2, cb)`; granted when GDPR\n// doesn't apply or every required purpose is satisfied (consent; or, for a\n// purpose the policy lets rest on it, legitimate interest) and — when a\n// `vendorId` is configured — the vendor has consent. Server: the TC string\n// in `euconsent-v2` (the de-facto cookie; not every CMP writes it).\n// - Google Consent Mode v2: the latest `consent default|update` command in\n// `dataLayer` for the storage type. Most CMPs (Cookiebot, OneTrust,\n// CookieYes, Usercentrics, Didomi…) drive it, so it is a universal adapter.\n// `default` may carry `region: ['ES', 'US-CA']`: region-scoped defaults beat\n// the global one for visitors in those regions (most specific wins); an\n// `update` applies everywhere.\n// - Shopify Customer Privacy API (shopify.dev/docs/api/customer-privacy):\n// `Shopify.customerPrivacy.analyticsProcessingAllowed()` — already combines\n// the merchant's region settings, the visitor's location and their choice;\n// loaded via `Shopify.loadFeatures([{name:'consent-tracking-api'}])`;\n// `visitorConsentCollected` on DOCUMENT when consent changes. Shopify's own\n// banner and every Shopify CMP app are required to report into it.\n//\n// Every read is re-done from the source on each signal — an event payload is\n// never trusted — and a revocation reads false, which the callers turn into a\n// teardown. Unknown ≠ granted: a source that can't be read gates.\n\nexport type ConsentPreset = 'cookiebot' | 'onetrust' | 'cookieyes' | 'tcf' | 'google-consent-mode' | 'shopify';\n\n/** TCF purposes the SDK's processing needs: 1 store/access on a device,\n * 5 build a personalised-content profile, 6 select personalised content from\n * it, 8 measure content performance. The old default was purpose 1 alone —\n * storage consent, which says nothing about profiling or measurement. */\nexport const TCF_DEFAULT_PURPOSES: readonly number[] = [1, 5, 6, 8];\n\nexport type ConsentSource =\n | ConsentPreset\n | { cmp: 'cookiebot'; category?: 'preferences' | 'statistics' | 'marketing' }\n | { cmp: 'onetrust'; group?: string }\n | { cmp: 'cookieyes'; category?: 'functional' | 'analytics' | 'performance' | 'advertisement' }\n | {\n cmp: 'tcf';\n /** Purposes that must be satisfied. @default TCF_DEFAULT_PURPOSES (1, 5, 6, 8) */\n purposes?: number[];\n /** Also require consent for this Global Vendor List id. SentientUI is a\n * processor for your site and has no GVL id of its own; set this only if\n * your CMP lists a vendor entry you map it to. */\n vendorId?: number;\n }\n | {\n cmp: 'google-consent-mode';\n type?: 'analytics_storage' | 'ad_storage' | 'personalization_storage' | 'functionality_storage';\n dataLayer?: string;\n /** The visitor's region (ISO 3166-1 alpha-2, optionally `-` ISO 3166-2\n * subdivision: 'ES', 'US-CA'), e.g. from your CDN's country header.\n * Resolves region-scoped `consent default` commands exactly. Without it\n * a region-scoped denial can't be ruled out, so it reads as denied. */\n region?: string;\n }\n | {\n cmp: 'shopify';\n /** Which Customer Privacy purpose to require. @default 'analytics' */\n category?: 'analytics' | 'marketing' | 'preferences';\n }\n | {\n cmp?: undefined;\n /** Cookie to read. Granted when its value equals `value`. */\n cookie?: string;\n /** Cookie value that means granted. @default 'accepted' */\n value?: string;\n /** Predicate for CMPs with a JS API. Takes precedence over `cookie`. */\n check?: () => boolean;\n /** Event that signals a decision (listened on window AND document). */\n event?: string;\n /** With `check`: true when the visitor has actually REFUSED (not merely\n * not answered yet). A predicate can't say why it returned false, so\n * without this a `check` source only pauses tracking and never forgets. */\n refused?: () => boolean;\n };\n\nexport type ConsentWatcher = {\n /** The decision right now: true/false, or null when the source can't tell\n * yet (CMP not loaded, no decision stored). Callers treat null as \"keep\n * whatever you knew\" — e.g. the server's read — and never as granted. */\n read(): boolean | null;\n /** True only when the source records an actual refusal — a \"no\" that\n * justifies deleting what the SDK stored (forget-me), not merely gating.\n * False while the platform is loading, while its banner is up (TCF\n * `cmpuishown`), for a region-conservative Consent Mode read, and for\n * `check()` sources (a predicate can't say why it returned false). */\n refused(): boolean;\n /** Call `onChange` whenever the decision may have changed. */\n subscribe(onChange: () => void): () => void;\n};\n\ntype AnyWin = Window & Record<string, unknown>;\n\nconst decode = (v: string): string => {\n try {\n return decodeURIComponent(v);\n } catch {\n return v;\n }\n};\n\nfunction docCookie(doc: Document | undefined, name: string): string | undefined {\n if (!doc) return undefined;\n for (const part of doc.cookie.split(';')) {\n const i = part.indexOf('=');\n if (i > 0 && part.slice(0, i).trim() === name) return part.slice(i + 1).trim();\n }\n return undefined;\n}\n\n/** Listen to `names` on both window and document (CMPs use either). */\nfunction listen(win: Window, names: string[], cb: () => void): () => void {\n const targets: EventTarget[] = [win, ...(win.document ? [win.document] : [])];\n for (const t of targets) for (const n of names) t.addEventListener(n, cb);\n return () => {\n for (const t of targets) for (const n of names) t.removeEventListener(n, cb);\n };\n}\n\n// ── Cookie parsers (also used server-side) ────────────────────────────────\n\n/** Cookiebot `CookieConsent`: true/false for `category`, null when unknown. */\nexport function cookiebotCookieGrants(raw: string | undefined, category = 'statistics'): boolean | null {\n if (raw == null || raw === '') return null;\n const v = decode(raw).trim();\n if (v === '-1') return true; // consent not required in this region\n if (v === '0') return false;\n const m = new RegExp(`[{,]\\\\s*${category}\\\\s*:\\\\s*(true|false)`).exec(v);\n return m ? m[1] === 'true' : null;\n}\n\n/** OneTrust `OptanonConsent`: is `group` active? null when unknown. Pass the\n * raw cookie value, not a decoded one (see {@link consentFromCookies}). */\nexport function onetrustCookieGrants(raw: string | undefined, group = 'C0002'): boolean | null {\n if (raw == null || raw === '') return null;\n // Split on the RAW `&` first, then decode only the groups value: decoding\n // the whole cookie first let an encoded `&groups=C0002:1` inside\n // `landingPath` (the landing URL, before any answer) read as consent\n // (grader N7-1). The LAST `groups` field counts: a caller whose cookie jar\n // already decoded the value (Next's cookies() does) hands us that injected\n // field as a real one, and landingPath is written before OneTrust's own\n // `groups` (grader R8 NEW-1).\n let groups: string | undefined;\n for (const field of raw.split('&')) {\n if (field.startsWith('groups=')) groups = decode(field.slice('groups='.length));\n }\n if (groups == null) return null;\n for (const pair of groups.split(',')) {\n const [g, on] = pair.split(':');\n if (g === group) return on === '1';\n }\n return null;\n}\n\n/** CookieYes `cookieyes-consent`: `category:yes|no`, null when unrecognised. */\nexport function cookieyesCookieGrants(raw: string | undefined, category = 'analytics'): boolean | null {\n if (raw == null || raw === '') return null;\n const m = new RegExp(`(?:^|,)${category}:(yes|no)(?:,|$)`).exec(decode(raw));\n return m ? m[1] === 'yes' : null;\n}\n\nexport type TcConsents = {\n purposes: Set<number>;\n legitimateInterests: Set<number>;\n /** Vendor ids with consent; null when the vendor section is truncated. */\n vendors: Set<number> | null;\n /** The publisher segment (type 3): the site's own purposes. Empty sets when\n * the string carries none. */\n publisherPurposes: Set<number>;\n publisherLegitimateInterests: Set<number>;\n /** PurposeOneTreatment (bit 200): purpose 1 is not collected. */\n purposeOneTreatment: boolean;\n};\n\n/**\n * Decode an IAB TCF v2 TC string's core segment. Bit layout (TCF v2.2 spec):\n * Version 6 · Created 36 · LastUpdated 36 · CmpId 12 · CmpVersion 12 ·\n * ConsentScreen 6 · ConsentLanguage 12 · VendorListVersion 12 ·\n * TcfPolicyVersion 6 · IsServiceSpecific 1 · UseNonStandardTexts 1 ·\n * SpecialFeatureOptIns 12 · PurposesConsent 24 (bit 152) ·\n * PurposesLITransparency 24 (bit 176) · PurposeOneTreatment 1 · PublisherCC 12\n * · then the vendor-consent section at bit 213: MaxVendorId 16 ·\n * IsRangeEncoding 1 · a MaxVendorId-bit field, or NumEntries 12 and entries\n * of IsARange 1 · Start 16 · [End 16]. Null for anything that isn't v2.\n */\nconst B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\nconst toBits = (seg: string): string => {\n let bits = '';\n for (const ch of seg) bits += B64URL.indexOf(ch).toString(2).padStart(6, '0');\n return bits;\n};\n\nexport function tcStringConsents(tc: string | undefined): TcConsents | null {\n if (!tc) return null;\n const segments = tc.split('.');\n const core = segments[0]!;\n if (!/^[A-Za-z0-9_-]+$/.test(core)) return null;\n const bits = toBits(core);\n if (bits.length < 200 || parseInt(bits.slice(0, 6), 2) !== 2) return null;\n const int = (at: number, len: number): number | null => (at + len <= bits.length ? parseInt(bits.slice(at, at + len), 2) : null);\n const purposes = new Set<number>();\n const legitimateInterests = new Set<number>();\n for (let p = 1; p <= 24; p++) {\n if (bits[151 + p] === '1') purposes.add(p);\n if (bits[175 + p] === '1') legitimateInterests.add(p);\n }\n let vendors: Set<number> | null = null;\n const max = int(213, 16);\n const isRange = int(229, 1);\n if (max !== null && isRange === 0) {\n if (230 + max <= bits.length) {\n vendors = new Set();\n for (let v = 1; v <= max; v++) if (bits[229 + v] === '1') vendors.add(v);\n }\n } else if (max !== null && isRange === 1) {\n const n = int(230, 12);\n let at = 242;\n const out = new Set<number>();\n let ok = n !== null;\n for (let i = 0; ok && i < (n ?? 0); i++) {\n const range = int(at, 1);\n const start = int(at + 1, 16);\n if (range === null || start === null) ok = false;\n else if (range === 1) {\n const end = int(at + 17, 16);\n if (end === null || end < start || end - start > 65535) ok = false;\n else for (let v = start; v <= end; v++) out.add(v);\n at += 33;\n } else {\n out.add(start);\n at += 17;\n }\n }\n if (ok) vendors = out;\n }\n // Publisher TC segment: SegmentType 3 · PubPurposesConsent 24 ·\n // PubPurposesLITransparency 24 (then custom purposes, unused here).\n const publisherPurposes = new Set<number>();\n const publisherLegitimateInterests = new Set<number>();\n for (const seg of segments.slice(1)) {\n if (!/^[A-Za-z0-9_-]+$/.test(seg)) continue;\n const pb = toBits(seg);\n if (pb.length < 51 || parseInt(pb.slice(0, 3), 2) !== 3) continue;\n for (let p = 1; p <= 24; p++) {\n if (pb[2 + p] === '1') publisherPurposes.add(p);\n if (pb[26 + p] === '1') publisherLegitimateInterests.add(p);\n }\n }\n return { purposes, legitimateInterests, vendors, publisherPurposes, publisherLegitimateInterests, purposeOneTreatment: bits[200] === '1' };\n}\n\n/** Purpose consents only — kept for callers of the pre-vendor parser. */\nexport function tcStringPurposes(tc: string | undefined): Set<number> | null {\n return tcStringConsents(tc)?.purposes ?? null;\n}\n\n// TCF policy: purposes 1, 3, 4, 5 and 6 need consent; the rest may rest on a\n// legitimate interest the visitor didn't object to.\nconst TCF_CONSENT_ONLY = new Set([1, 3, 4, 5, 6]);\n\nfunction tcfSatisfied(\n n: { purposes: readonly number[]; vendorId?: number },\n consent: (p: number) => boolean,\n li: (p: number) => boolean,\n vendor: (v: number) => boolean | null,\n): boolean | null {\n const purposesOk = n.purposes.every((p) => consent(p) || (!TCF_CONSENT_ONLY.has(p) && li(p)));\n if (!purposesOk) return false;\n if (n.vendorId === undefined) return true;\n return vendor(n.vendorId);\n}\n\n// ── Normalisation ─────────────────────────────────────────────────────────\n\ntype Norm =\n | { cmp: 'cookiebot'; category: string }\n | { cmp: 'onetrust'; group: string }\n | { cmp: 'cookieyes'; category: string }\n | { cmp: 'tcf'; purposes: readonly number[]; vendorId?: number }\n | { cmp: 'google-consent-mode'; type: string; dataLayer: string; region?: string }\n | { cmp: 'shopify'; category: 'analytics' | 'marketing' | 'preferences' }\n | { cmp: 'custom'; cookie?: string; value: string; check?: () => boolean; event?: string; refused?: () => boolean };\n\nfunction normalize(input: ConsentSource): Norm {\n const src = (typeof input === 'string' ? { cmp: input } : input) as Exclude<ConsentSource, string>;\n switch (src.cmp) {\n case 'cookiebot':\n return { cmp: 'cookiebot', category: src.category ?? 'statistics' };\n case 'onetrust':\n return { cmp: 'onetrust', group: src.group ?? 'C0002' };\n case 'cookieyes':\n return { cmp: 'cookieyes', category: src.category ?? 'analytics' };\n case 'tcf':\n return {\n cmp: 'tcf',\n purposes: src.purposes && src.purposes.length > 0 ? src.purposes : TCF_DEFAULT_PURPOSES,\n vendorId: typeof src.vendorId === 'number' && src.vendorId > 0 ? src.vendorId : undefined,\n };\n case 'google-consent-mode':\n return {\n cmp: 'google-consent-mode',\n type: src.type ?? 'analytics_storage',\n dataLayer: src.dataLayer ?? 'dataLayer',\n region: typeof src.region === 'string' && src.region.trim() !== '' ? src.region.trim().toUpperCase() : undefined,\n };\n case 'shopify':\n return { cmp: 'shopify', category: src.category ?? 'analytics' };\n default:\n return { cmp: 'custom', cookie: src.cookie, value: src.value ?? 'accepted', check: src.check, event: src.event, refused: src.refused };\n }\n}\n\n/**\n * Server-side read from the request's cookies (Next.js `AdaptiveRoot`).\n * true/false when the CMP's cookie decides it, null when it can't be known on\n * the server (no cookie yet, a JS-only source) — the caller then gates the\n * first paint and lets the browser decide.\n *\n * `getCookie` must return the value exactly as sent in the Cookie header,\n * NOT decoded: most server cookie jars (Next's cookies(), Express\n * cookie-parser) decode values, and a decoded OneTrust cookie lets a crafted\n * landing URL inject a `groups=` field that reads as consent.\n */\nexport function consentFromCookies(src: ConsentSource, getCookie: (name: string) => string | undefined): boolean | null {\n const n = normalize(src);\n switch (n.cmp) {\n case 'cookiebot':\n return cookiebotCookieGrants(getCookie('CookieConsent'), n.category);\n case 'onetrust':\n return onetrustCookieGrants(getCookie('OptanonConsent'), n.group);\n case 'cookieyes':\n return cookieyesCookieGrants(getCookie('cookieyes-consent'), n.category);\n case 'tcf': {\n const c = tcStringConsents(getCookie('euconsent-v2'));\n if (!c) return null;\n return tcfSatisfied(\n c.purposeOneTreatment ? { ...n, purposes: n.purposes.filter((p) => p !== 1) } : n,\n (p) => c.purposes.has(p) || c.publisherPurposes.has(p),\n (p) => c.legitimateInterests.has(p) || c.publisherLegitimateInterests.has(p),\n (v) => (c.vendors ? c.vendors.has(v) : null),\n );\n }\n case 'google-consent-mode':\n return null;\n case 'shopify':\n // `_tracking_consent` is undocumented; the browser API decides.\n return null;\n case 'custom':\n if (!n.cookie || n.check) return null;\n return getCookie(n.cookie) === n.value;\n }\n}\n\n/** Consent Mode state folded from dataLayer commands, one storage type. */\ntype ConsentModeState = {\n /** Latest `update` — applies in every region and beats any default. */\n update: boolean | null;\n /** Latest region-less `default`. */\n global: boolean | null;\n /** Latest region-scoped `default`, per upper-cased region code. */\n regions: Map<string, boolean>;\n};\n\nconst emptyConsentModeState = (): ConsentModeState => ({ update: null, global: null, regions: new Map() });\n\nfunction foldConsentMode(state: ConsentModeState, item: unknown, type: string): void {\n // gtag() pushes `arguments` objects; GTM templates push arrays.\n const args = item && typeof item === 'object' && 'length' in (item as object) ? Array.prototype.slice.call(item) : null;\n if (!args || args[0] !== 'consent' || (args[1] !== 'default' && args[1] !== 'update')) return;\n const params = args[2] as Record<string, unknown> | undefined;\n const raw = params?.[type];\n const v = raw === 'granted' ? true : raw === 'denied' ? false : null;\n if (v === null) return;\n if (args[1] === 'update') {\n state.update = v;\n return;\n }\n const region = params?.region;\n const list = Array.isArray(region) ? region : typeof region === 'string' ? [region] : [];\n const codes = list.filter((r): r is string => typeof r === 'string' && r.trim() !== '').map((r) => r.trim().toUpperCase());\n if (codes.length === 0) state.global = v;\n else for (const c of codes) state.regions.set(c, v);\n}\n\n/** A recorded \"denied\" is an `update` only. A `default` is the site's\n * starting state, pushed on every page before the CMP answers (Google's own\n * recommended setup) — treating `default: denied` as a refusal forgot every\n * consented visitor whose CMP pushed its `update` a moment after we read. */\nfunction consentModeRefused(state: ConsentModeState): boolean {\n return state.update === false;\n}\n\nfunction resolveConsentMode(state: ConsentModeState, region: string | undefined): boolean | null {\n if (state.update !== null) return state.update;\n if (region) {\n // Most specific wins: 'US-CA' over 'US' over the global default.\n const exact = state.regions.get(region);\n if (exact !== undefined) return exact;\n const country = region.split('-')[0]!;\n const byCountry = state.regions.get(country);\n if (byCountry !== undefined) return byCountry;\n // Country only ('US', the usual CDN header) but a subdivision-scoped\n // denial ('US-CA'): the visitor may be in it, so it reads as denied.\n if (region === country) {\n for (const [r, v] of state.regions) if (v === false && r.startsWith(`${country}-`)) return false;\n }\n return state.global;\n }\n // Region unknown: a region-scoped denial may be this visitor's. The old\n // reader ignored `region` entirely, so the common EU setup — global\n // granted, `region: [EU…]` denied — read as granted for EU visitors.\n for (const v of state.regions.values()) if (v === false) return false;\n if (state.global !== null) return state.global;\n // Only region-scoped grants: this visitor may be outside all of them.\n return state.regions.size > 0 ? false : null;\n}\n\n/**\n * The Consent Mode state for `type` in `dataLayer`, or null when no command\n * has decided it. `region` (e.g. 'ES', 'US-CA') resolves region-scoped\n * `consent default` commands; without it, any region-scoped denial reads as\n * denied until an `update` settles it.\n */\nexport function consentModeGranted(dataLayer: unknown, type = 'analytics_storage', region?: string): boolean | null {\n if (!Array.isArray(dataLayer)) return null;\n const state = emptyConsentModeState();\n for (const item of dataLayer) foldConsentMode(state, item, type);\n return resolveConsentMode(state, region?.trim().toUpperCase() || undefined);\n}\n\n// ── Browser watcher ───────────────────────────────────────────────────────\n\nexport function consentWatcher(src: ConsentSource, win: Window = window): ConsentWatcher {\n const n = normalize(src);\n const w = win as AnyWin;\n const doc = win.document;\n switch (n.cmp) {\n case 'cookiebot':\n return {\n read: () => {\n const cb = w.Cookiebot as { consent?: Record<string, unknown>; hasResponse?: unknown } | undefined;\n const cookie = cookiebotCookieGrants(docCookie(doc, 'CookieConsent'), n.category);\n // The stored answer wins until Cookiebot says it has one in memory:\n // a `consent` object read before uc.js finishes initialising can hold\n // defaults (all false), and reading those for a returning visitor\n // gated them — or, with refused(), forgot them (grader N-D).\n if (cb?.consent && typeof cb.consent[n.category] === 'boolean' && (cb.hasResponse === true || cookie === null)) {\n return cb.consent[n.category] === true;\n }\n return cookie;\n },\n subscribe: (cb) => listen(win, ['CookiebotOnAccept', 'CookiebotOnDecline', 'CookiebotOnConsentReady', 'CookiebotOnLoad'], cb),\n // Only once the visitor has answered: `consent.statistics` is also\n // false while the banner is pending. The cookie is written on answer.\n refused() {\n const cb = w.Cookiebot as { hasResponse?: unknown } | undefined;\n const answered = cb?.hasResponse === true || docCookie(doc, 'CookieConsent') !== undefined;\n return answered && this.read() === false;\n },\n };\n case 'onetrust':\n return {\n read: () => {\n const groups = w.OnetrustActiveGroups;\n if (typeof groups === 'string') return `,${groups},`.includes(`,${n.group},`);\n return onetrustCookieGrants(docCookie(doc, 'OptanonConsent'), n.group);\n },\n subscribe: (cb) => listen(win, ['OneTrustGroupsUpdated'], cb),\n // OneTrust writes OptanonAlertBoxClosed when the visitor answers; before\n // that, an opt-in region's active groups are just the defaults.\n refused() {\n return docCookie(doc, 'OptanonAlertBoxClosed') !== undefined && this.read() === false;\n },\n };\n case 'cookieyes':\n return {\n read: () => {\n const get = w.getCkyConsent as (() => { categories?: Record<string, unknown> }) | undefined;\n if (typeof get === 'function') {\n try {\n const cats = get()?.categories;\n if (cats && typeof cats[n.category] === 'boolean') return cats[n.category] === true;\n } catch {\n /* banner not ready — fall through to the cookie */\n }\n }\n return cookieyesCookieGrants(docCookie(doc, 'cookieyes-consent'), n.category);\n },\n subscribe: (cb) => listen(win, ['cookieyes_consent_update', 'cookieyes_banner_load', 'cookieyes_banner_loaded'], cb),\n // Answered = the API says the user acted, or the cookie records\n // `action:yes`; the categories read false while the banner is pending.\n refused() {\n let answered = /(?:^|,)action:yes(?:,|$)/.test(decode(docCookie(doc, 'cookieyes-consent') ?? ''));\n const get = w.getCkyConsent as (() => { isUserActionCompleted?: unknown }) | undefined;\n if (!answered && typeof get === 'function') {\n try {\n answered = get()?.isUserActionCompleted === true;\n } catch {\n /* not ready */\n }\n }\n return answered && this.read() === false;\n },\n };\n case 'tcf': {\n let granted: boolean | null = null;\n // The banner being up is \"no decision yet\" (or a re-prompt), never a refusal.\n let bannerUp = false;\n // Forget-me needs storage itself refused (purpose 1). A decision that\n // grants storage but lacks 5/6/8 or the vendor only gates: many CMPs never\n // OFFER those purposes, and \"not offered\" is indistinguishable from \"no\"\n // in the TC data — forgetting on it wiped every accepting visitor on each\n // page of such sites (review #6).\n let storageRefused = false;\n return {\n read: () => granted,\n refused: () => granted === false && !bannerUp && storageRefused,\n subscribe: (cb) => {\n type TcData = {\n gdprApplies?: boolean;\n eventStatus?: string;\n listenerId?: number;\n purpose?: { consents?: Record<string, boolean>; legitimateInterests?: Record<string, boolean> };\n vendor?: { consents?: Record<string, boolean> };\n publisher?: { consents?: Record<string, boolean>; legitimateInterests?: Record<string, boolean> };\n purposeOneTreatment?: boolean;\n };\n type TcfApi = (cmd: string, v: number, cb: (d: TcData, ok: boolean) => void, param?: unknown) => void;\n let listenerId: number | undefined;\n let stopped = false;\n let everDecided = false;\n const onData = (d: TcData, ok: boolean): void => {\n if (!ok || stopped) return;\n if (typeof d.listenerId === 'number') listenerId = d.listenerId;\n // cmpuishown = the banner is up: no decision yet.\n bannerUp = d.eventStatus === 'cmpuishown';\n // Only a completed decision: some CMPs emit early/empty tcData\n // (cmpStatus 'loading') with ok=true — not a refusal (review #9).\n // purposeOneTreatment: purpose 1 isn't collected in this\n // jurisdiction, so its absence is not a refusal.\n storageRefused =\n (d.eventStatus === 'tcloaded' || d.eventStatus === 'useractioncomplete') &&\n d.purposeOneTreatment !== true &&\n d.gdprApplies !== false &&\n d.purpose?.consents?.[1] !== true &&\n d.publisher?.consents?.[1] !== true;\n const decided = d.eventStatus === 'tcloaded' || d.eventStatus === 'useractioncomplete';\n if (decided) everDecided = true;\n if (bannerUp) granted = false;\n // A loading/empty callback is \"not known yet\" (null), never false:\n // reading it as false disposed a server-granted client on load\n // and re-sent its decides (grader N7-5). After a decision it\n // changes nothing: the SDKs now read null-after-an-answer as a\n // pause, so a stray one paused a consented visitor (review R11 #2).\n else if (!decided && d.gdprApplies !== false) {\n if (!everDecided) granted = null;\n }\n else\n granted =\n d.gdprApplies === false ||\n tcfSatisfied(\n // Purpose 1 isn't collected under purposeOneTreatment: not\n // required then, or those visitors could never be granted\n // (N7-8).\n d.purposeOneTreatment === true ? { ...n, purposes: n.purposes.filter((p) => p !== 1) } : n,\n // Publisher consent counts too: SentientUI processes for the\n // site, and some CMPs record the site's own purposes only in\n // the publisher segment.\n (p) => d.purpose?.consents?.[p] === true || d.publisher?.consents?.[p] === true,\n (p) => d.purpose?.legitimateInterests?.[p] === true || d.publisher?.legitimateInterests?.[p] === true,\n (v) => d.vendor?.consents?.[v] === true,\n ) === true;\n cb();\n };\n // CMPs install the IAB stub early, but a late one needs a moment.\n let tries = 0;\n const attach = (): void => {\n if (stopped) return;\n const api = w.__tcfapi as TcfApi | undefined;\n if (typeof api === 'function') api('addEventListener', 2, onData);\n else if (tries++ < 40) window.setTimeout(attach, 250);\n };\n attach();\n return () => {\n stopped = true;\n const api = w.__tcfapi as TcfApi | undefined;\n if (typeof api === 'function' && listenerId !== undefined) api('removeEventListener', 2, () => undefined, listenerId);\n };\n },\n };\n }\n case 'google-consent-mode': {\n // Folded incrementally: each read scans only entries pushed since the\n // last one (the old reader rescanned the whole dataLayer every second —\n // GTM sites push hundreds of entries). A replaced or shrunk array\n // restarts the fold.\n let seen: unknown[] | null = null;\n let upTo = 0;\n let state = emptyConsentModeState();\n const read = (): boolean | null => {\n const dl = w[n.dataLayer];\n if (!Array.isArray(dl)) return null;\n if (dl !== seen || dl.length < upTo) {\n seen = dl;\n upTo = 0;\n state = emptyConsentModeState();\n }\n for (; upTo < dl.length; upTo++) foldConsentMode(state, dl[upTo], n.type);\n return resolveConsentMode(state, n.region);\n };\n return {\n read,\n refused: () => read() === false && consentModeRefused(state),\n subscribe: (cb) => {\n // Wrap push ONCE per array, and never re-wrap: gtag.js and GTM\n // replace dataLayer.push with a function that chains to the previous\n // one (ours), so wrapping theirs again made the two call each other\n // forever (caught by the real-gtag.js e2e, 2026-09-25). A\n // replacement that doesn't chain is covered by the poll, which is\n // O(1) — it compares lengths and calls `cb` only when entries arrived\n // (the old poll called it every second, forever, re-scanning all).\n const wrappedArrays = new WeakSet<object>();\n let stopped = false;\n const unwrap: Array<() => void> = [];\n let lastLen = -1;\n const attach = (): void => {\n const dl = (w[n.dataLayer] ??= []) as unknown[] & { push: (...a: unknown[]) => number };\n if (!wrappedArrays.has(dl)) {\n wrappedArrays.add(dl);\n const original = dl.push;\n const wrapped = function (this: unknown, ...a: unknown[]): number {\n const r = original.apply(dl, a);\n lastLen = dl.length;\n // gtag/GTM chain onto this wrapper, so it can't always be\n // unhooked on unsubscribe; a stopped one must go quiet.\n if (!stopped) cb();\n return r;\n };\n dl.push = wrapped;\n unwrap.push(() => {\n if (dl.push === wrapped) dl.push = original;\n });\n }\n if (dl.length !== lastLen) {\n lastLen = dl.length;\n cb();\n }\n };\n attach();\n const timer = window.setInterval(attach, 1000);\n return () => {\n stopped = true;\n window.clearInterval(timer);\n for (const u of unwrap) u();\n };\n },\n };\n }\n case 'shopify': {\n type CustomerPrivacy = Partial<Record<'analyticsProcessingAllowed' | 'marketingAllowed' | 'preferencesProcessingAllowed', () => unknown>>;\n type ShopifyGlobal = {\n customerPrivacy?: CustomerPrivacy;\n loadFeatures?: (features: Array<{ name: string; version: string }>, cb: (err?: unknown) => void) => void;\n };\n const method =\n n.category === 'marketing' ? 'marketingAllowed' : n.category === 'preferences' ? 'preferencesProcessingAllowed' : 'analyticsProcessingAllowed';\n return {\n read: () => {\n const fn = (w.Shopify as ShopifyGlobal | undefined)?.customerPrivacy?.[method];\n if (typeof fn !== 'function') return null; // API not loaded yet\n try {\n const v = fn();\n return typeof v === 'boolean' ? v : null;\n } catch {\n return null;\n }\n },\n // analyticsProcessingAllowed() is also false before the visitor has\n // answered in a consent region; only an explicit 'no' is a refusal.\n refused() {\n const priv = (w.Shopify as { customerPrivacy?: { currentVisitorConsent?: () => Record<string, unknown> } } | undefined)?.customerPrivacy;\n if (typeof priv?.currentVisitorConsent !== 'function') return false;\n try {\n return priv.currentVisitorConsent()?.[n.category] === 'no';\n } catch {\n return false;\n }\n },\n subscribe: (cb) => {\n const stopListen = listen(win, ['visitorConsentCollected'], cb);\n // The API is not on the page until something loads it; a theme's\n // own banner usually does, but nothing guarantees it.\n let stopped = false;\n let tries = 0;\n const load = (): void => {\n if (stopped) return;\n const shop = w.Shopify as ShopifyGlobal | undefined;\n if (shop?.customerPrivacy) {\n cb();\n return;\n }\n if (typeof shop?.loadFeatures === 'function') {\n try {\n shop.loadFeatures([{ name: 'consent-tracking-api', version: '0.1' }], (err) => {\n if (!stopped && !err) cb();\n });\n } catch {\n /* a broken storefront API never breaks the site */\n }\n return;\n }\n if (tries++ < 40) window.setTimeout(load, 250);\n };\n load();\n return () => {\n stopped = true;\n stopListen();\n };\n },\n };\n }\n case 'custom':\n return {\n read: () => {\n if (n.check) {\n try {\n return n.check() === true;\n } catch {\n return false;\n }\n }\n if (!n.cookie) return null;\n const v = docCookie(doc, n.cookie);\n // No cookie yet = no decision yet; any other value = not granted.\n return v === undefined ? null : v === n.value;\n },\n // A cookie holding another value is an answer; a predicate isn't —\n // unless the site says so through `refused` (grader F4).\n refused: () => {\n if (n.check) {\n try {\n return n.refused?.() === true;\n } catch {\n return false;\n }\n }\n return !!n.cookie && docCookie(doc, n.cookie) !== undefined && docCookie(doc, n.cookie) !== n.value;\n },\n subscribe: (cb) => (n.event ? listen(win, [n.event], cb) : () => undefined),\n };\n }\n}\n","/**\n * Per-project browser-storage namespace suffix, derived from the public apiKey.\n *\n * Multiple SentientUI projects (different `pk_` keys) can run on the same exact\n * origin. Storage keyed only by name (`_snt_uid`, `_snt_asgn_*`,\n * `_snt_graph_nodes`) would then collide across projects — the visitor id in\n * particular, whose session row is keyed globally server-side, would let one\n * project's traffic land on another's session. Suffixing every browser key with\n * the apiKey prefix isolates projects, matching the queue's existing\n * `_snt_retry_${apiKey.slice(0,12)}` convention.\n *\n * Returns `''` when no apiKey is available (local mode) so keys stay stable\n * there.\n */\nexport function storageSuffix(apiKey?: string): string {\n return apiKey ? `_${apiKey.slice(0, 12)}` : '';\n}\n\n/**\n * The bare, pre-namespacing session cookie name. Still read as a FALLBACK\n * everywhere the suffixed name is read, so visitors who got their identity\n * before per-project namespacing keep it instead of being minted a fresh one.\n */\nexport const LEGACY_SESSION_COOKIE_NAME = '_snt_uid';\n\n/**\n * The one place the session cookie's name is decided. The writer (session.ts)\n * and every reader (core/server.ts SSR helper, graph sync, react devtools) must\n * call THIS — when namespacing landed, the writer moved to the suffixed name\n * while three readers kept the bare `_snt_uid`, so every SSR request for a\n * returning visitor missed the cookie and minted a fresh orphan session (quota\n * inflation, broken sticky assignments and persona continuity), and graph sync\n * sent `sessionId: undefined`. Deriving both sides from one function makes that\n * drift impossible, and index.test.ts pins the reader against the writer.\n */\nexport function sessionCookieName(apiKey?: string): string {\n return `${LEGACY_SESSION_COOKIE_NAME}${storageSuffix(apiKey)}`;\n}\n\n// Forget-me generation per project, on window so every bundle on the page\n// sees it (the snippet and its lazy chunks each carry their own copy of these\n// modules). Every client and queue captures it when created and persists only\n// while it is unchanged: a forget can never be undone by a later grant — the\n// old boolean marker was cleared by the next tracking client, and a paused\n// client's in-flight decide then wrote the forgotten visitor back (grader\n// NEW-1), as could its queues' failed final flush (F8).\nconst GENS = '__sntForgetGen';\ntype GenMap = Record<string, number>;\nconst genMap = (): GenMap | undefined => {\n try {\n return (window as unknown as Record<string, GenMap | undefined>)[GENS];\n } catch {\n return undefined;\n }\n};\nexport function markForgotten(apiKey: string): void {\n try {\n const w = window as unknown as Record<string, GenMap>;\n const m = (w[GENS] ??= {});\n m[apiKey] = (m[apiKey] ?? 0) + 1;\n } catch {\n /* no window */\n }\n}\n/** Bumped by every forget-me for this project in this page. */\nexport function forgetGeneration(apiKey: string): number {\n return genMap()?.[apiKey] ?? 0;\n}\n","/**\n * Decision snapshot: the SPA / return-visit pre-paint source. Written after\n * every successful decide; read by the inline pre-paint script (before any\n * framework code runs) and by init() to seed slot/persona state.\n */\nimport type { ServedEdits } from './region-skeleton.js';\nimport type { SlotResult } from './slots.js';\nimport type { BlockNode, SitePalette } from './blocks.js';\n\nexport const SNAPSHOT_STORAGE_KEY_PREFIX = '_snt_snap:';\n/** A snapshot older than this is ignored (the inline pre-paint's 2592e6). */\nexport const SNAPSHOT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** Versioned compound locator: resolve id → dataAttr → selector, then verify\n * against fingerprint. Lets a slot survive DOM/markup drift. */\nexport type CompoundLocator = {\n v?: number;\n id?: string;\n dataAttr?: { name: string; value: string };\n selector?: string;\n urlMatch?: string;\n /** Where the element is expected to exist — see page-scope.ts. Health only, never serving. */\n page?: string;\n fingerprint?: { tag?: string; text?: string };\n semanticId?: string;\n};\n\n/** Bounded, declarative operations a registry arm may apply to its element.\n * The style set is a fixed whitelist (validated server-side); no arbitrary CSS,\n * HTML, or JS ever. `text` is applied via textContent; https-only URLs.\n * moveBefore/moveAfter (exactly one) reposition the element relative to a\n * uniquely-resolving sibling anchor — post-decide only, never pre-paint. */\nexport type SlotOps = {\n text?: string;\n style?: Record<string, string>;\n hidden?: boolean;\n href?: string;\n imageSrc?: string;\n imageAlt?: string;\n moveBefore?: CompoundLocator;\n moveAfter?: CompoundLocator;\n};\n\n/** Registry-mode apply info per slot: where to apply and what to set. Stored so\n * a returning visitor's pre-paint can reapply it. `target` is the Phase-2 bare\n * selector; `locator` (Phase 3) is the compound locator, preferred when present. */\nexport type SlotConfigEntry = {\n kind: 'tokens' | 'arms';\n target?: string;\n locator?: CompoundLocator;\n content?: string;\n ops?: SlotOps;\n /** Composition Blocks per arm — ALL arms, not just the served one, because\n * Option-B rendering pre-paints every arm hidden and reveals the served one\n * (spec §6). Holdout sessions receive the baseline arm's tree only, so the\n * control group's DOM stays meaningful. Absent for non-composition slots. */\n blocks?: Record<string, BlockNode>;\n /** The served Rewrite arm (spec 2026-09-23 §4.3): per-node edits plus the\n * skeleton fingerprint and leaf map they were written against. */\n edits?: ServedEdits;\n /** The server has no skeleton for this region — capture and report one. */\n needsSkeleton?: true;\n /** Redesign arms per arm id — ALL arms, same Option-B reason as `blocks`.\n * Served only to pages that declared RenderCaps.compose. */\n compose?: Record<string, import('./style-vocabulary.js').ComposeArm>;\n /** A hybrid <Adaptive> held back: its id still has un-migrated variant\n * history, so the page renders its original until the operator migrates. */\n blocked?: 'variant_history';\n};\n\nexport type DecisionSnapshot = {\n v: 1;\n persona: string;\n band: 'low' | 'medium' | 'high';\n slots: Record<string, SlotResult>;\n layoutOrder: string[] | null;\n savedAt: number;\n // Additive (kept at v:1 so existing snapshots stay valid — bumping the version\n // would flush every returning visitor's snapshot and flash the baseline once).\n // Present only for registry-mode (no-code) installs.\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Derived site palette for Composition Block rendering — cached so the\n * pre-paint render already looks native (a palette that pops in post-decide\n * would be its own flash). */\n palette?: SitePalette;\n /** The site-style entries the served compose arms reference — cached so the\n * pre-paint render already borrows the site's classes. Additive (v stays 1). */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n /** The `data-sentient-stage` value last decided — already coarsened, and\n * present only for a `stageAttributes` install (additive, v stays 1). */\n stage?: string;\n};\n\nconst BANDS = ['low', 'medium', 'high'];\n\n/** Returns null on missing, corrupt, or wrong-version data — never throws. */\nexport function readSnapshot(apiKey: string): DecisionSnapshot | null {\n try {\n const raw = localStorage.getItem(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey);\n if (!raw) return null;\n const p = JSON.parse(raw) as Partial<DecisionSnapshot> | null;\n if (\n !p ||\n typeof p !== 'object' ||\n p.v !== 1 ||\n typeof p.persona !== 'string' ||\n typeof p.band !== 'string' ||\n !BANDS.includes(p.band) ||\n typeof p.slots !== 'object' ||\n p.slots === null ||\n Array.isArray(p.slots) ||\n !(p.layoutOrder === null || Array.isArray(p.layoutOrder)) ||\n typeof p.savedAt !== 'number' ||\n // The documented 30-day life, the same bound the inline pre-paint script\n // applies: an older decision is ignored everywhere (grader NEW-5).\n !(Date.now() - p.savedAt < SNAPSHOT_MAX_AGE_MS) ||\n // slotConfig is optional; when present it must be a plain object.\n !(p.slotConfig === undefined || (typeof p.slotConfig === 'object' && p.slotConfig !== null && !Array.isArray(p.slotConfig)))\n ) {\n return null;\n }\n // A malformed cached vocabulary degrades to palette styling, never throws.\n const v = p.vocabulary as { entries?: unknown; images?: unknown } | undefined;\n if (v !== undefined && (typeof v !== 'object' || v === null || !Array.isArray(v.entries) || !Array.isArray(v.images))) {\n delete p.vocabulary;\n }\n // Same for the stage: a non-string never reaches setAttribute.\n if (p.stage !== undefined && typeof p.stage !== 'string') delete p.stage;\n return p as DecisionSnapshot;\n } catch {\n return null;\n }\n}\n\n/** Best-effort persist — storage failures are swallowed. */\nexport function writeSnapshot(apiKey: string, snap: DecisionSnapshot): void {\n try {\n localStorage.setItem(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey, JSON.stringify(snap));\n } catch {\n /* private mode / quota — the snapshot is an optimization, never a requirement */\n }\n}\n\n/**\n * Inline pre-paint script (Rung 1a): reads the snapshot and sets\n * `data-sentient-persona` / `data-sentient-confidence` on <html> before\n * first paint. Single-writer: it never overwrites attributes already set.\n *\n * Safety properties (pinned by tests):\n * - apiKey goes through JSON.stringify, then '<' is escaped to <, so a\n * hostile key can neither break the JS string nor terminate the <script>.\n * - Built by string concatenation and contains no backticks, so the output\n * survives being embedded in template-literal-based renderers.\n */\nexport function renderPrePaintScript(apiKey: string, opts?: { stage?: boolean }): string {\n const key = JSON.stringify(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey).replace(/</g, '\\\\u003c');\n return (\n '(function(){try{' +\n // DNT/GPC: the SDK never reads what it stored for an opted-out browser\n // (grader F3 — this fallback had no gate at all).\n // Every signal isDoNotTrackEnabled reads, not just the standard one.\n 'var N=navigator,W=window;if(N.doNotTrack==\"1\"||N.doNotTrack==\"yes\"||W.doNotTrack==\"1\"||N.msDoNotTrack==\"1\"||N.globalPrivacyControl)return;' +\n 'var r=localStorage.getItem(' + key + ');if(!r)return;' +\n 'var s=JSON.parse(r);' +\n 'if(!s||s.v!==1||typeof s.persona!==\"string\"||typeof s.band!==\"string\")return;' +\n // The same 30-day life readSnapshot enforces.\n 'if(!(' + SNAPSHOT_MAX_AGE_MS + '>Date.now()-s.savedAt))return;' +\n 'var d=document.documentElement;' +\n // Opt-in stage attribute (`stageAttributes`): the snapshot holds only the\n // already-coarsened value, so this copies it as-is. Before the persona\n // single-writer return below — an SSR persona must not stop it — but with\n // its own single-writer check, so an SSR-written stage wins. Absent from\n // the output entirely without the option (the default bytes are pinned).\n (opts?.stage\n ? 'if(typeof s.stage==\"string\"&&!d.hasAttribute(\"data-sentient-stage\"))d.setAttribute(\"data-sentient-stage\",s.stage);'\n : '') +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",s.persona);' +\n 'd.setAttribute(\"data-sentient-confidence\",s.band);' +\n '}catch(e){}})();'\n );\n}\n","/** Batched event queue with reliable transport (fetch + keepalive, localStorage retry). */\n\nimport { forgetGeneration } from './storage-key.js';\nimport { QUEUE_TIMEOUT_MS, timeoutSignal } from './timeout.js';\nimport { backoffDelayMs, classifyResponse, drainBucket, purgeBucket, writeBucket } from './durable.js';\n\nexport type EventType =\n | 'variant_assigned'\n | 'goal_achieved'\n | 'scroll_depth'\n | 'dwell'\n | 'cursor_signal'\n | 'component_visible'\n | 'component_exited'\n | 'micro_signal'\n // A funnel DECLARATION, not telemetry: the server upserts the funnel entity\n // and never stores it in raw_events. Listed here so callers can express it\n // without casting through the track() signature.\n | 'funnel_declared'\n // A goal DECLARATION (React `useGoal`, the snippet's `primaryGoal`): the\n // server creates the goal so it shows at 0 before it first fires, and with\n // `primary: true` makes it the main goal. Never stored in raw_events.\n | 'goal_declared'\n // One per page load and per SPA route change, so a visit's journey through the\n // site is reconstructable. Carries `path` and nothing else.\n | 'pageview'\n // Session-level interaction aggregates for the browser-agent axis (one\n // cumulative snapshot per bank point on the `__session__` sentinel). Read by\n // the bot scorer only; never attributed to a component, never a reward.\n | 'interaction_stats';\n\nexport type SentientEvent = {\n id: string;\n sessionId: string;\n projectId: string;\n componentId: string;\n variantId?: string;\n eventType: EventType;\n goalType?: string;\n /**\n * Page path the event happened on, e.g. `/pricing`. Set automatically from\n * `location.pathname` — deliberately NOT `location.href`, so query strings\n * (which routinely carry emails, reset tokens and order ids) never leave the\n * browser. The server re-strips them anyway; this is the first of two gates.\n * Undefined outside a browser (SSR), where there is no page to name.\n */\n path?: string;\n payload: Record<string, unknown>;\n timestamp: number;\n timeInSession: number;\n};\n\nexport type QueueConfig = {\n ingestUrl: string;\n apiKey: string;\n flushIntervalMs?: number;\n maxBatchSize?: number;\n maxRetrySize?: number;\n};\n\nexport type EventQueue = {\n push(event: SentientEvent): void;\n flush(): void;\n /** Stop the queue with a final flush. `forget`: the visitor asked to be\n * forgotten — a failed final delivery must NOT be persisted for retry\n * (it re-created the retry bucket after forget-me removed it). */\n destroy(opts?: { forget?: boolean }): void;\n};\n\nconst MAX_SENT_IDS = 500;\n// 64 KB is the per-origin keepalive budget on every modern browser. We split unload\n// flushes into chunks below this to avoid the whole batch being dropped.\nconst KEEPALIVE_BUDGET_BYTES = 56 * 1024;\n\n/**\n * Persisted retry-bucket key, namespaced by apiKey prefix so multiple projects\n * on the same origin each get their own bucket. Exported so the client's\n * forget-me teardown can remove it.\n */\nexport function retryStorageKey(apiKey: string): string {\n return `_snt_retry_${apiKey.slice(0, 12)}`;\n}\n\nconst SSR_QUEUE: EventQueue = {\n push: () => undefined,\n flush: () => undefined,\n destroy: () => undefined,\n};\n\n/**\n * Creates a batched event queue with periodic and lifecycle-triggered flushes.\n */\nexport function createEventQueue(config: QueueConfig): EventQueue {\n if (typeof window === 'undefined') {\n return SSR_QUEUE;\n }\n\n const flushIntervalMs = config.flushIntervalMs ?? 5000;\n const maxBatchSize = config.maxBatchSize ?? 20;\n const maxRetrySize = config.maxRetrySize ?? 100;\n const ingestUrl = config.ingestUrl;\n const apiKey = config.apiKey;\n const RETRY_KEY = retryStorageKey(apiKey);\n // Set by destroy({ forget: true }); see the type's doc.\n let forgotten = false;\n const createdGen = forgetGeneration(apiKey);\n const persistBucket: typeof writeBucket = (...a) => {\n if (!forgotten && forgetGeneration(apiKey) === createdGen) writeBucket(...a);\n };\n\n const queue: SentientEvent[] = [];\n const sentIds = new Set<string>();\n const sentIdOrder: string[] = [];\n\n const markSent = (ids: string[]): void => {\n for (const id of ids) {\n queuedIds.delete(id); // free the in-flight slot\n if (sentIds.has(id)) continue;\n sentIds.add(id);\n sentIdOrder.push(id);\n }\n while (sentIdOrder.length > MAX_SENT_IDS) {\n const oldest = sentIdOrder.shift();\n if (oldest) sentIds.delete(oldest);\n }\n // A batch that previously 5xx'd was persisted to the cross-reload retry\n // backstop. Now that it's acknowledged (delivered, or 4xx-dropped as\n // unretryable), drop those ids from localStorage too — otherwise the next\n // page load would replay an already-handled event. `sentIds` is in-memory\n // only, so it can't suppress that cross-reload duplicate on its own.\n purgeBucket(ids, RETRY_KEY);\n };\n\n // Tracks IDs currently in `queue` or in flight (handed to transportBatch\n // but not yet confirmed). Entries are removed on markSent or when an event\n // is dropped, so the set stays bounded by in-flight + queued size.\n const queuedIds = new Set<string>();\n\n // Bound the in-memory queue at the same cap as the persisted retry bucket\n // (maxRetrySize). During a sustained outage flush() keeps re-enqueueing every\n // failed batch while the page keeps producing events, and only the\n // localStorage bucket was capped — so a multi-hour outage on a long-lived\n // SPA tab grew this array without limit. Drop-oldest, matching writeBucket's\n // slice(-max) shed policy: the newest events are the ones a recovering\n // server can still use.\n const capQueue = (): void => {\n while (queue.length > maxRetrySize) {\n const dropped = queue.shift();\n if (dropped) queuedIds.delete(dropped.id);\n }\n };\n\n const enqueue = (event: SentientEvent): void => {\n if (sentIds.has(event.id) || queuedIds.has(event.id)) return;\n queuedIds.add(event.id);\n queue.push(event);\n capQueue();\n };\n\n // A retryable failure hands the batch back to the in-memory queue so the\n // backoff-gated interval flush retries it in-session (localStorage is only the\n // cross-reload backstop). The ids are still tracked in queuedIds — they were\n // pulled from `queue` on flush but never markSent — so we re-add them WITHOUT\n // going through enqueue (which would skip them as already-queued) and without\n // deleting/re-adding queuedIds. Already-sent events are never re-queued, and a\n // single event stays a single copy: `queue` is fully drained each flush.\n const requeueFailed = (batch: SentientEvent[]): void => {\n for (const event of batch) {\n if (sentIds.has(event.id)) continue;\n queuedIds.add(event.id); // idempotent — keeps id-tracking consistent\n queue.push(event);\n }\n // Failed batches count against the same bound as fresh pushes — this path\n // is exactly the one that grew unbounded during an outage (see capQueue).\n capQueue();\n };\n\n const retryEvents = drainBucket<SentientEvent>(RETRY_KEY, maxRetrySize);\n for (const event of retryEvents) {\n enqueue(event);\n }\n\n // Pause flushing until backoff expires.\n let backoffUntil = 0;\n let consecutiveFailures = 0;\n\n // Authenticated transport. keepalive: true gives unload-survival; we still await\n // the response so 5xx/429 actually surface and we can retry.\n const transportBatch = (batch: SentientEvent[], salvage = true): void => {\n if (batch.length === 0) return;\n const body = JSON.stringify(batch);\n const ids = batch.map((e) => e.id);\n\n let pending: Promise<Response> | Response;\n const queueTimer = timeoutSignal(QUEUE_TIMEOUT_MS);\n try {\n // Bounded (QUEUE_TIMEOUT_MS): a hung POST never settles, which held this\n // batch in flight forever. An abort is a retry; ids dedupe server-side.\n pending = fetch(ingestUrl, {\n method: 'POST',\n keepalive: true,\n signal: queueTimer.signal,\n body,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n });\n } catch {\n // Synchronous throw (typically jsdom in tests, or extreme browser failure).\n persistBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n return;\n }\n\n Promise.resolve(pending).then(queueTimer.clear, queueTimer.clear);\n // fetch can sometimes return a value directly (tests using stubGlobal). Handle both.\n const handleResponse = (res: Response): void => {\n if (classifyResponse(res) !== 'retry') {\n // An API older than migration 108 400s the whole batch over the unknown\n // 'pageview' type, and a 4xx is terminal — which silently dropped the\n // co-batched exposures and goals too. Re-send once without the\n // pageviews (valid on the old API); the pageviews themselves are\n // unsendable there and are dropped as delivered.\n if (!res.ok && salvage) {\n const rest = batch.filter((e) => e.eventType !== 'pageview');\n if (rest.length > 0 && rest.length < batch.length) {\n markSent(batch.filter((e) => e.eventType === 'pageview').map((e) => e.id));\n transportBatch(rest, false);\n return;\n }\n }\n // 2xx = success. 4xx (except 429) will never succeed — drop them rather than loop.\n markSent(ids);\n consecutiveFailures = 0;\n backoffUntil = 0;\n return;\n }\n // 5xx / 429 → retry with backoff.\n persistBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n };\n\n // Thenable, not instanceof: another realm's Promise failed it (N11-4).\n if (pending && typeof (pending as PromiseLike<unknown>).then === 'function') {\n pending.then(handleResponse).catch(() => {\n persistBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n });\n } else {\n handleResponse(pending as unknown as Response); // test stubs return a plain value\n }\n };\n\n // Pack events into a batch that stays under the keepalive byte budget AND the\n // configured event-count cap. Returns the prefix of `pool` that fits.\n // Uses UTF-8 byte length (not char count) — emoji/CJK payloads can be 3–4×\n // larger as bytes and would otherwise blow the keepalive budget.\n const encoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null;\n const byteLength = (s: string): number =>\n encoder ? encoder.encode(s).length : s.length;\n const packBatch = (pool: SentientEvent[]): SentientEvent[] => {\n const out: SentientEvent[] = [];\n let bytes = 2; // for the surrounding []\n for (const e of pool) {\n const size = byteLength(JSON.stringify(e)) + 1; // +1 for comma\n if (out.length > 0 && bytes + size > KEEPALIVE_BUDGET_BYTES) break;\n if (out.length >= maxBatchSize) break;\n out.push(e);\n bytes += size;\n }\n return out;\n };\n\n const flush = (): void => {\n try {\n if (Date.now() < backoffUntil) return;\n while (queue.length > 0) {\n // Re-check inside the loop: transportBatch can set backoffUntil\n // synchronously (a sync throw or a same-tick Response) and re-enqueue the\n // failed batch, so a mid-drain backoff must stop further chunks this tick\n // (otherwise the just-re-enqueued batch would immediately retry-loop).\n if (Date.now() < backoffUntil) break;\n const pending = queue.filter((e) => !sentIds.has(e.id));\n queue.length = 0;\n if (pending.length === 0) break;\n const batch = packBatch(pending);\n if (batch.length === 0) break;\n // Put anything we didn't pack back on the queue for the next tick.\n if (batch.length < pending.length) {\n queue.push(...pending.slice(batch.length));\n }\n transportBatch(batch);\n }\n } catch {\n /* never throw */\n }\n };\n\n let flushTimerActive = true;\n let intervalId: ReturnType<typeof setInterval> | null = null;\n\n intervalId = setInterval(() => {\n if (!flushTimerActive) return;\n flush();\n }, flushIntervalMs);\n\n const onVisibilityChange = (): void => {\n if (document.visibilityState === 'hidden') {\n flush();\n }\n };\n\n // `pagehide` (not `beforeunload`): a `beforeunload` listener can disqualify a\n // page from the back/forward cache. `pagehide` fires on real unloads AND on\n // bfcache eviction, and `visibilitychange:hidden` already covers most leaves,\n // so flush-on-leave stays covered without inhibiting bfcache.\n const onPageHide = (): void => {\n flush();\n };\n\n document.addEventListener('visibilitychange', onVisibilityChange);\n window.addEventListener('pagehide', onPageHide);\n\n return {\n push(event: SentientEvent): void {\n enqueue(event);\n if (queue.length >= maxBatchSize) {\n flush();\n }\n },\n flush,\n destroy(opts?: { forget?: boolean }): void {\n if (opts?.forget) forgotten = true;\n flushTimerActive = false;\n if (intervalId !== null) {\n clearInterval(intervalId);\n intervalId = null;\n }\n document.removeEventListener('visibilitychange', onVisibilityChange);\n window.removeEventListener('pagehide', onPageHide);\n flush();\n },\n };\n}\n","/**\n * Durable transport for `POST /v1/goals`.\n *\n * A conversion is the single most valuable event the SDK emits, and it used to\n * be the least reliable one: `goal()` fired a bare `fetch(...).catch(() => {})`,\n * which only observes network-layer failures. A 429 (the per-IP limit is 100\n * req/min, and shared egress — corporate NAT, carriers, storefront proxies —\n * hits it routinely), a 5xx, or a 400 all RESOLVE, so the catch never ran and\n * the response was discarded unread. The conversion was gone with no retry and\n * nothing surfaced to the developer.\n *\n * This gives goals the same guarantees the event queue has always had: retry\n * with backoff in-session, a localStorage bucket that survives reload, and\n * dedupe by id. Retry is safe because `goalId` is a client-generated UUID that\n * the server dedupes on (`ON CONFLICT DO NOTHING`) — the safety was already\n * there, it just wasn't used.\n *\n * Unlike events, `/v1/goals` takes ONE goal per request, so this is a serial\n * sender rather than a batcher, and a flush sends at most `maxPerFlush` so a\n * backlog drains at a pace the rate limiter tolerates instead of re-triggering\n * the 429 that created it.\n */\n\nimport { forgetGeneration } from './storage-key.js';\nimport { QUEUE_TIMEOUT_MS, timeoutSignal } from './timeout.js';\nimport { backoffDelayMs, classifyResponse, drainBucket, purgeBucket, writeBucket } from './durable.js';\n\n/** One queued conversion. `id` is the goalId — the server's dedupe key. */\nexport type PendingGoal = {\n id: string;\n /** Pre-serialized request body, so a persisted goal replays byte-identically. */\n body: string;\n};\n\nexport type GoalQueueConfig = {\n /** Absolute URL of the goals endpoint. */\n url: string;\n apiKey: string;\n headers: Record<string, string>;\n flushIntervalMs?: number;\n maxRetrySize?: number;\n maxPerFlush?: number;\n /** Called when a goal is permanently dropped (non-retryable status), so the\n * client can warn in debug mode. Never called for retryable failures. */\n onDrop?: (goal: PendingGoal, status: number) => void;\n};\n\nexport type GoalQueue = {\n /** Sends immediately; on a retryable failure the goal is queued and retried. */\n send(goal: PendingGoal): void;\n flush(): void;\n /** Stop the queue with a final flush. `forget`: the visitor asked to be\n * forgotten — a failed final delivery must NOT be persisted for retry\n * (it re-created the retry bucket after forget-me removed it). */\n destroy(opts?: { forget?: boolean }): void;\n};\n\nconst MAX_SENT_IDS = 200;\n\n/**\n * Persisted goal-retry bucket key, namespaced by apiKey prefix so multiple\n * projects on one origin keep separate buckets. Exported so the client's\n * forget-me teardown can remove it.\n */\nexport function goalRetryStorageKey(apiKey: string): string {\n return `_snt_goal_retry_${apiKey.slice(0, 12)}`;\n}\n\nconst SSR_GOAL_QUEUE: GoalQueue = {\n send: () => undefined,\n flush: () => undefined,\n destroy: () => undefined,\n};\n\nexport function createGoalQueue(config: GoalQueueConfig): GoalQueue {\n if (typeof window === 'undefined') return SSR_GOAL_QUEUE;\n\n const flushIntervalMs = config.flushIntervalMs ?? 5000;\n const maxRetrySize = config.maxRetrySize ?? 100;\n const maxPerFlush = config.maxPerFlush ?? 5;\n const RETRY_KEY = goalRetryStorageKey(config.apiKey);\n // Set by destroy({ forget: true }); see the type's doc.\n let forgotten = false;\n const createdGen = forgetGeneration(config.apiKey);\n const persistBucket: typeof writeBucket = (...a) => {\n if (!forgotten && forgetGeneration(config.apiKey) === createdGen) writeBucket(...a);\n };\n\n const pending: PendingGoal[] = [];\n const pendingIds = new Set<string>();\n const sentIds = new Set<string>();\n const sentIdOrder: string[] = [];\n\n let backoffUntil = 0;\n let consecutiveFailures = 0;\n let disposed = false;\n\n const markSent = (goal: PendingGoal): void => {\n pendingIds.delete(goal.id);\n if (!sentIds.has(goal.id)) {\n sentIds.add(goal.id);\n sentIdOrder.push(goal.id);\n }\n while (sentIdOrder.length > MAX_SENT_IDS) {\n const oldest = sentIdOrder.shift();\n if (oldest) sentIds.delete(oldest);\n }\n // Acknowledged (delivered, or dropped as unretryable) — clear it from the\n // cross-reload bucket so the next page load doesn't replay it.\n purgeBucket([goal.id], RETRY_KEY);\n };\n\n const markFailed = (goal: PendingGoal): void => {\n persistBucket([goal], maxRetrySize, RETRY_KEY);\n if (!sentIds.has(goal.id) && !pendingIds.has(goal.id)) {\n pendingIds.add(goal.id);\n pending.push(goal);\n }\n // One failed ROUND counts once, however many goals were in flight. flush()\n // launches up to maxPerFlush transports synchronously, so counting per goal\n // turned a single bad tick into consecutiveFailures=5 and a 32s backoff\n // where the first failure warrants 2s. queue.ts counts per batch; match it.\n if (Date.now() >= backoffUntil) {\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n }\n };\n\n const transport = (goal: PendingGoal): void => {\n let res: Promise<Response> | Response;\n const queueTimer = timeoutSignal(QUEUE_TIMEOUT_MS);\n try {\n // Bounded like the event queue: an abort retries, the goalId dedupes.\n res = fetch(config.url, {\n method: 'POST',\n keepalive: true,\n signal: queueTimer.signal,\n body: goal.body,\n headers: config.headers,\n });\n } catch {\n // Synchronous throw (jsdom in tests, or extreme browser failure).\n markFailed(goal);\n return;\n }\n\n const handle = (r: Response): void => {\n const outcome = classifyResponse(r);\n if (outcome === 'retry') {\n markFailed(goal);\n return;\n }\n // Terminal either way, but a drop is a wiring bug the developer can fix —\n // a 400 \"session not found\", a 401 from a misconfigured origin allowlist —\n // and used to be swallowed entirely. Say so instead of failing silently.\n if (outcome === 'dropped') config.onDrop?.(goal, r.status);\n markSent(goal);\n consecutiveFailures = 0;\n backoffUntil = 0;\n };\n\n Promise.resolve(res).then(queueTimer.clear, queueTimer.clear);\n // fetch can return a plain value under test stubs. Handle both.\n // A thenable check, not instanceof: a fetch wrapper returning another\n // realm's Promise was handled as a Response and retried (grader N11-4).\n if (res && typeof (res as PromiseLike<unknown>).then === 'function') (res as Promise<Response>).then(handle).catch(() => markFailed(goal));\n else handle(res as unknown as Response); // test stubs return a plain value\n };\n\n const flush = (): void => {\n try {\n if (disposed) return;\n if (Date.now() < backoffUntil) return;\n let sentThisTick = 0;\n while (pending.length > 0 && sentThisTick < maxPerFlush) {\n if (Date.now() < backoffUntil) break; // a same-tick failure re-armed backoff\n const goal = pending.shift()!;\n pendingIds.delete(goal.id);\n if (sentIds.has(goal.id)) continue;\n sentThisTick++;\n transport(goal);\n }\n } catch {\n /* never throw from a lifecycle handler */\n }\n };\n\n // Replay anything a previous page load failed to deliver. Left for the first\n // interval tick rather than sent now, so a page that reloads under an ongoing\n // outage doesn't stampede the endpoint during init.\n const restored = drainBucket<PendingGoal>(RETRY_KEY, maxRetrySize);\n for (const goal of restored) {\n if (!pendingIds.has(goal.id)) {\n pendingIds.add(goal.id);\n pending.push(goal);\n }\n }\n // drainBucket CLEARS storage as it reads, but only maxPerFlush goals leave per\n // tick — so a 40-goal backlog moved to memory and the visitor navigating two\n // seconds later lost the 35 that hadn't been sent yet. Put them straight back;\n // markSent purges each id individually once it is actually acknowledged.\n if (restored.length > 0) writeBucket(restored, maxRetrySize, RETRY_KEY);\n\n const intervalId = setInterval(flush, flushIntervalMs);\n const onVisibilityChange = (): void => {\n if (document.visibilityState === 'hidden') flush();\n };\n const onPageHide = (): void => flush();\n document.addEventListener('visibilitychange', onVisibilityChange);\n window.addEventListener('pagehide', onPageHide);\n\n return {\n send(goal: PendingGoal): void {\n if (disposed) {\n // A goal fired before a pause, still waiting on the first session\n // upsert, arrives after dispose(): banked for the next page's queue\n // instead of dropped unreported (grader R9-3, CONTRACTS §7). Never\n // after a forget — persistBucket checks that.\n if (!sentIds.has(goal.id)) persistBucket([goal], maxRetrySize, RETRY_KEY);\n return;\n }\n if (sentIds.has(goal.id) || pendingIds.has(goal.id)) return;\n // A conversion goes out now — it is often the last thing that happens\n // before a redirect to a thank-you page. Only a failure makes it queued.\n if (Date.now() < backoffUntil) {\n // Persist BEFORE parking it in memory. A goal only ever reached the\n // cross-reload bucket via markFailed — i.e. only after a failed attempt\n // — so a conversion queued during someone else's backoff lived in memory\n // alone, and flush() early-returns while backoff is armed, so pagehide\n // could not rescue it either. A purchase firing 300ms after a rate-limited\n // add_to_cart was lost on the checkout redirect: exactly the outage this\n // queue exists to survive.\n persistBucket([goal], maxRetrySize, RETRY_KEY);\n pendingIds.add(goal.id);\n pending.push(goal);\n return;\n }\n transport(goal);\n },\n flush,\n destroy(opts?: { forget?: boolean }): void {\n if (opts?.forget) forgotten = true;\n clearInterval(intervalId);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n window.removeEventListener('pagehide', onPageHide);\n flush();\n disposed = true;\n },\n };\n}\n","/**\n * Candidate domains for the shared visitor cookie. The visitor id lives on the\n * site's registrable domain (`example.com` for `app.example.com`), so a marketing\n * site and its app subdomain see ONE visitor: host-only cookies gave each host\n * its own id, and a journey that started on the landing page and converted in\n * the app (or the app's backend) could never be joined to the decisions that\n * earned it.\n *\n * Detection (session.ts `detectCookieDomain`) works the way analytics.js and\n * GA's `cookieDomain: 'auto'` do: try the shortest parent first and keep the\n * first one the browser accepts. The browser refuses public suffixes\n * (`co.uk`, `vercel.app`, `herokuapp.com`), so no suffix list ships in the\n * bundle — those fall through to the next candidate, and a host with no\n * acceptable parent stays host-only.\n */\n\n/** `false` = host-only (the pre-sharing behaviour); a string = that domain. */\nexport type CookieDomainOption = string | false | undefined;\n\n/**\n * Domains to try for `hostname`, shortest first, ENDING WITH THE HOST ITSELF.\n * The host is a candidate because the site's own bare domain is the common\n * case: a landing page on `example.com` must write `Domain=example.com` to share\n * with `app.example.com` — without it the bare domain stayed host-only while\n * its subdomains shared, so the landing-to-app journey was still two\n * visitors, and forget-me there left the shared copy behind.\n */\nexport function parentDomains(hostname: string | undefined): string[] {\n // `|| ''`: a stubbed or embedded `location` without a hostname must cost\n // the visitor cookie sharing, never crash init().\n const host = (hostname || '').toLowerCase();\n // localhost, a bare intranet name, an IP literal: nothing to share across.\n if (!host.includes('.') || /^[\\d.]+$|:/.test(host)) return [];\n const labels = host.split('.');\n const out: string[] = [];\n for (let i = labels.length - 2; i >= 0; i--) out.push(labels.slice(i).join('.'));\n return out;\n}\n","import { sessionCookieName, storageSuffix, LEGACY_SESSION_COOKIE_NAME, markForgotten } from './storage-key.js';\nimport { SNAPSHOT_STORAGE_KEY_PREFIX } from './snapshot.js';\nimport { retryStorageKey } from './queue.js';\nimport { goalRetryStorageKey } from './goal-queue.js';\nimport { parentDomains } from './cookie-domain.js';\n\n/**\n * Forget-me WITHOUT a client: delete everything the SDK stores for `apiKey`'s\n * visitor. `client.destroy()` does this for a live tracking client, which only\n * exists when consent was granted in this page view — so a visitor who said\n * \"no\" somewhere the SDK wasn't watching (a CMP settings page, checkout)\n * kept the 365-day id, the decision snapshot and the retry buckets for good,\n * and the pre-paint script kept personalizing from that snapshot (audit N2).\n * Callers run this when the consent source reports a refusal at boot.\n *\n * Writes nothing unless something was stored: the legacy tombstone (which\n * stops this project re-adopting the shared bare `_snt_uid`) is only written\n * when there is a bare id to block. Returns whether anything was removed.\n */\nexport function forgetVisitor(apiKey: string): boolean {\n if (typeof window === 'undefined' || !apiKey) return false;\n markForgotten(apiKey);\n let removed = false;\n const name = sessionCookieName(apiKey);\n try {\n if (new RegExp(`(?:^|; )${name}=`).test(document.cookie)) {\n const secure = location.protocol === 'https:' ? '; Secure' : '';\n // The visitor cookie may be shared on a parent domain (cookie-domain.ts),\n // and a host-only delete leaves that copy for every sibling host to\n // re-adopt. Which domain was configured is not known here, so every\n // parent is cleared — deleting a cookie that isn't there is a no-op.\n for (const d of ['', ...parentDomains(location.hostname)]) {\n document.cookie = `${name}=; max-age=0; SameSite=lax; path=/${d ? `; domain=${d}` : ''}${secure}`;\n }\n removed = true;\n }\n } catch {\n /* cookies unavailable */\n }\n const suffix = storageSuffix(apiKey);\n const exact = [\n name,\n // Written by builds before 2026; current SDKs only ever delete it.\n '_snt_graph_edges',\n SNAPSHOT_STORAGE_KEY_PREFIX + apiKey,\n retryStorageKey(apiKey),\n goalRetryStorageKey(apiKey),\n `_snt_graph_nodes${suffix}`,\n ];\n const prefixes = [`_snt_asgn${suffix}_`];\n for (const store of ['localStorage', 'sessionStorage'] as const) {\n try {\n const s = window[store];\n for (const k of exact) {\n if (s.getItem(k) !== null) {\n s.removeItem(k);\n removed = true;\n }\n }\n for (let i = s.length - 1; i >= 0; i--) {\n const k = s.key(i);\n if (k && prefixes.some((p) => k.startsWith(p))) {\n s.removeItem(k);\n removed = true;\n }\n }\n } catch {\n /* storage unavailable */\n }\n }\n try {\n // Every layer session.ts's legacy read adopts from, sessionStorage too.\n const bare =\n new RegExp(`(?:^|; )${LEGACY_SESSION_COOKIE_NAME}=[^;]`).test(document.cookie) ||\n localStorage.getItem(LEGACY_SESSION_COOKIE_NAME) !== null ||\n sessionStorage.getItem(LEGACY_SESSION_COOKIE_NAME) !== null;\n if (bare) localStorage.setItem(`${LEGACY_SESSION_COOKIE_NAME}_tomb${suffix}`, '1');\n } catch {\n /* storage unavailable */\n }\n return removed;\n}\n"],"mappings":"kxBAAA,I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EACvC,QAAWO,IAAS,CAAC,eAAgB,gBAAgB,EACnD,GAAI,CACF,IAAMC,EAAI,OAAOD,CAAK,EACtB,QAAWE,KAAKP,EACVM,EAAE,QAAQC,CAAC,IAAM,OACnBD,EAAE,WAAWC,CAAC,EACdhB,EAAU,IAGd,QAASiB,EAAIF,EAAE,OAAS,EAAGE,GAAK,EAAGA,IAAK,CACtC,IAAMD,EAAID,EAAE,IAAIE,CAAC,EACbD,GAAKH,EAAS,KAAMK,GAAMF,EAAE,WAAWE,CAAC,CAAC,IAC3CH,EAAE,WAAWC,CAAC,EACdhB,EAAU,GAEd,CACF,OAAQM,EAAA,CAER,CAEF,GAAI,EAGA,IAAI,OAAO,WAAWa,CAA0B,OAAO,EAAE,KAAK,SAAS,MAAM,GAC7E,aAAa,QAAQA,CAA0B,IAAM,MACrD,eAAe,QAAQA,CAA0B,IAAM,OAC/C,aAAa,QAAQ,GAAGA,CAA0B,QAAQZ,CAAM,GAAI,GAAG,CACnF,OAAQD,EAAA,CAER,CACA,OAAON,CACT","names":["index_consent_exports","__export","TCF_DEFAULT_PURPOSES","consentFromCookies","consentModeGranted","consentWatcher","cookiebotCookieGrants","cookieyesCookieGrants","forgetVisitor","onetrustCookieGrants","tcStringConsents","tcStringPurposes","__toCommonJS","TCF_DEFAULT_PURPOSES","decode","v","e","docCookie","doc","name","part","i","listen","win","names","cb","targets","t","n","cookiebotCookieGrants","raw","category","m","onetrustCookieGrants","group","groups","field","pair","g","on","cookieyesCookieGrants","B64URL","toBits","seg","bits","ch","tcStringConsents","tc","segments","core","int","at","len","purposes","legitimateInterests","p","vendors","max","isRange","out","ok","range","start","end","publisherPurposes","publisherLegitimateInterests","pb","tcStringPurposes","_a","_b","TCF_CONSENT_ONLY","tcfSatisfied","consent","li","vendor","normalize","input","_c","_d","_e","_f","_g","src","consentFromCookies","getCookie","c","__spreadProps","__spreadValues","emptyConsentModeState","foldConsentMode","state","item","type","args","params","region","codes","r","consentModeRefused","resolveConsentMode","exact","country","byCountry","consentModeGranted","dataLayer","consentWatcher","w","cookie","get","cats","answered","granted","bannerUp","storageRefused","listenerId","stopped","everDecided","onData","d","decided","tries","attach","api","seen","upTo","read","dl","wrappedArrays","unwrap","lastLen","original","wrapped","a","timer","u","method","fn","priv","stopListen","load","shop","err","storageSuffix","apiKey","LEGACY_SESSION_COOKIE_NAME","sessionCookieName","GENS","markForgotten","apiKey","_a","_b","w","m","GENS","e","SNAPSHOT_STORAGE_KEY_PREFIX","KEEPALIVE_BUDGET_BYTES","retryStorageKey","apiKey","goalRetryStorageKey","apiKey","parentDomains","hostname","host","labels","out","i","forgetVisitor","apiKey","markForgotten","removed","name","sessionCookieName","secure","d","parentDomains","e","suffix","storageSuffix","exact","SNAPSHOT_STORAGE_KEY_PREFIX","retryStorageKey","goalRetryStorageKey","prefixes","store","s","k","i","p","LEGACY_SESSION_COOKIE_NAME"]}
|
|
1
|
+
{"version":3,"sources":["../src/index-consent.ts","../src/consent-sources.ts","../src/storage-key.ts","../src/snapshot.ts","../src/queue.ts","../src/goal-queue.ts","../src/cookie-domain.ts","../src/forget.ts"],"sourcesContent":["/** `@sentientui/core/consent`: read a visitor's consent from the site's\n * consent platform (Cookiebot, OneTrust, CookieYes, IAB TCF v2.2, Google\n * Consent Mode v2, or a cookie/check of your own). Its own entry so installs\n * that never configure `consentFrom` don't download it. */\nexport {\n consentWatcher,\n consentFromCookies,\n consentModeGranted,\n tcStringConsents,\n TCF_DEFAULT_PURPOSES,\n tcStringPurposes,\n cookiebotCookieGrants,\n onetrustCookieGrants,\n cookieyesCookieGrants,\n} from './consent-sources.js';\nexport type { ConsentSource, ConsentPreset, ConsentWatcher } from './consent-sources.js';\nexport { forgetVisitor } from './forget.js';\n","// Consent sources: where the SDK reads a visitor's consent decision from, so a\n// site keeps its own consent manager (CMP) and we only OBSERVE it. Shared by\n// React (`consentFrom`), Next.js `AdaptiveRoot` (server read of the CMP's own\n// cookie → SSR for visitors who already consented) and the snippet.\n//\n// Presets encode each platform's documented API, verified 2026-09-24:\n// - Cookiebot: `Cookiebot.consent.{preferences,statistics,marketing}`; window\n// events CookiebotOnAccept / CookiebotOnDecline (both also fire on load for a\n// returning visitor) / CookiebotOnConsentReady; cookie `CookieConsent` =\n// `{stamp:'…',necessary:true,preferences:…,statistics:…,marketing:…,…}`,\n// \"0\" = declined, \"-1\" = consent not required in the visitor's region.\n// - OneTrust: `OnetrustActiveGroups` (\",C0001,C0002,\"), window event\n// OneTrustGroupsUpdated; cookie `OptanonConsent` with `groups=C0001:1,C0002:0`.\n// C0002 = Performance.\n// - CookieYes: `getCkyConsent().categories.{functional,analytics,performance,\n// advertisement}` (only after the banner loads); `cookieyes_consent_update`\n// dispatched on DOCUMENT; cookie `cookieyes-consent` observed as\n// `consentid:…,consent:yes,…,analytics:yes,…` (not officially documented —\n// used server-side only, and an unrecognised value is \"unknown\", not \"no\").\n// - IAB TCF v2.2: `__tcfapi('addEventListener', 2, cb)`; granted when GDPR\n// doesn't apply or every required purpose is satisfied (consent; or, for a\n// purpose the policy lets rest on it, legitimate interest) and — when a\n// `vendorId` is configured — the vendor has consent. Server: the TC string\n// in `euconsent-v2` (the de-facto cookie; not every CMP writes it).\n// - Google Consent Mode v2: the latest `consent default|update` command in\n// `dataLayer` for the storage type. Most CMPs (Cookiebot, OneTrust,\n// CookieYes, Usercentrics, Didomi…) drive it, so it is a universal adapter.\n// `default` may carry `region: ['ES', 'US-CA']`: region-scoped defaults beat\n// the global one for visitors in those regions (most specific wins); an\n// `update` applies everywhere.\n// - Shopify Customer Privacy API (shopify.dev/docs/api/customer-privacy):\n// `Shopify.customerPrivacy.analyticsProcessingAllowed()` — already combines\n// the merchant's region settings, the visitor's location and their choice;\n// loaded via `Shopify.loadFeatures([{name:'consent-tracking-api'}])`;\n// `visitorConsentCollected` on DOCUMENT when consent changes. Shopify's own\n// banner and every Shopify CMP app are required to report into it.\n//\n// Every read is re-done from the source on each signal — an event payload is\n// never trusted — and a revocation reads false, which the callers turn into a\n// teardown. Unknown ≠ granted: a source that can't be read gates.\n\nexport type ConsentPreset = 'cookiebot' | 'onetrust' | 'cookieyes' | 'tcf' | 'google-consent-mode' | 'shopify';\n\n/** TCF purposes the SDK's processing needs: 1 store/access on a device,\n * 5 build a personalised-content profile, 6 select personalised content from\n * it, 8 measure content performance. The old default was purpose 1 alone —\n * storage consent, which says nothing about profiling or measurement. */\nexport const TCF_DEFAULT_PURPOSES: readonly number[] = [1, 5, 6, 8];\n\nexport type ConsentSource =\n | ConsentPreset\n | { cmp: 'cookiebot'; category?: 'preferences' | 'statistics' | 'marketing' }\n | { cmp: 'onetrust'; group?: string }\n | { cmp: 'cookieyes'; category?: 'functional' | 'analytics' | 'performance' | 'advertisement' }\n | {\n cmp: 'tcf';\n /** Purposes that must be satisfied. @default TCF_DEFAULT_PURPOSES (1, 5, 6, 8) */\n purposes?: number[];\n /** Also require consent for this Global Vendor List id. SentientUI is a\n * processor for your site and has no GVL id of its own; set this only if\n * your CMP lists a vendor entry you map it to. */\n vendorId?: number;\n }\n | {\n cmp: 'google-consent-mode';\n type?: 'analytics_storage' | 'ad_storage' | 'personalization_storage' | 'functionality_storage';\n dataLayer?: string;\n /** The visitor's region (ISO 3166-1 alpha-2, optionally `-` ISO 3166-2\n * subdivision: 'ES', 'US-CA'), e.g. from your CDN's country header.\n * Resolves region-scoped `consent default` commands exactly. Without it\n * a region-scoped denial can't be ruled out, so it reads as denied. */\n region?: string;\n }\n | {\n cmp: 'shopify';\n /** Which Customer Privacy purpose to require. @default 'analytics' */\n category?: 'analytics' | 'marketing' | 'preferences';\n }\n | {\n cmp?: undefined;\n /** Cookie to read. Granted when its value equals `value`. */\n cookie?: string;\n /** Cookie value that means granted. @default 'accepted' */\n value?: string;\n /** Predicate for CMPs with a JS API. Takes precedence over `cookie`. */\n check?: () => boolean;\n /** Event that signals a decision (listened on window AND document). */\n event?: string;\n /** With `check`: true when the visitor has actually REFUSED (not merely\n * not answered yet). A predicate can't say why it returned false, so\n * without this a `check` source only pauses tracking and never forgets. */\n refused?: () => boolean;\n };\n\nexport type ConsentWatcher = {\n /** The decision right now: true/false, or null when the source can't tell\n * yet (CMP not loaded, no decision stored). Callers treat null as \"keep\n * whatever you knew\" — e.g. the server's read — and never as granted. */\n read(): boolean | null;\n /** True only when the source records an actual refusal — a \"no\" that\n * justifies deleting what the SDK stored (forget-me), not merely gating.\n * False while the platform is loading, while its banner is up (TCF\n * `cmpuishown`), for a region-conservative Consent Mode read, and for\n * `check()` sources (a predicate can't say why it returned false). */\n refused(): boolean;\n /** Call `onChange` whenever the decision may have changed. */\n subscribe(onChange: () => void): () => void;\n};\n\ntype AnyWin = Window & Record<string, unknown>;\n\nconst decode = (v: string): string => {\n try {\n return decodeURIComponent(v);\n } catch {\n return v;\n }\n};\n\nfunction docCookie(doc: Document | undefined, name: string): string | undefined {\n if (!doc) return undefined;\n for (const part of doc.cookie.split(';')) {\n const i = part.indexOf('=');\n if (i > 0 && part.slice(0, i).trim() === name) return part.slice(i + 1).trim();\n }\n return undefined;\n}\n\n/** Listen to `names` on both window and document (CMPs use either). */\nfunction listen(win: Window, names: string[], cb: () => void): () => void {\n const targets: EventTarget[] = [win, ...(win.document ? [win.document] : [])];\n for (const t of targets) for (const n of names) t.addEventListener(n, cb);\n return () => {\n for (const t of targets) for (const n of names) t.removeEventListener(n, cb);\n };\n}\n\n// ── Cookie parsers (also used server-side) ────────────────────────────────\n\n/** Cookiebot `CookieConsent`: true/false for `category`, null when unknown. */\nexport function cookiebotCookieGrants(raw: string | undefined, category = 'statistics'): boolean | null {\n if (raw == null || raw === '') return null;\n const v = decode(raw).trim();\n if (v === '-1') return true; // consent not required in this region\n if (v === '0') return false;\n const m = new RegExp(`[{,]\\\\s*${category}\\\\s*:\\\\s*(true|false)`).exec(v);\n return m ? m[1] === 'true' : null;\n}\n\n/** OneTrust `OptanonConsent`: is `group` active? null when unknown. Pass the\n * raw cookie value, not a decoded one (see {@link consentFromCookies}). */\nexport function onetrustCookieGrants(raw: string | undefined, group = 'C0002'): boolean | null {\n if (raw == null || raw === '') return null;\n // Split on the RAW `&` first, then decode only the groups value: decoding\n // the whole cookie first let an encoded `&groups=C0002:1` inside\n // `landingPath` (the landing URL, before any answer) read as consent\n // (grader N7-1). The LAST `groups` field counts: a caller whose cookie jar\n // already decoded the value (Next's cookies() does) hands us that injected\n // field as a real one, and landingPath is written before OneTrust's own\n // `groups` (grader R8 NEW-1).\n let groups: string | undefined;\n for (const field of raw.split('&')) {\n if (field.startsWith('groups=')) groups = decode(field.slice('groups='.length));\n }\n if (groups == null) return null;\n for (const pair of groups.split(',')) {\n const [g, on] = pair.split(':');\n if (g === group) return on === '1';\n }\n return null;\n}\n\n/** CookieYes `cookieyes-consent`: `category:yes|no`, null when unrecognised. */\nexport function cookieyesCookieGrants(raw: string | undefined, category = 'analytics'): boolean | null {\n if (raw == null || raw === '') return null;\n const m = new RegExp(`(?:^|,)${category}:(yes|no)(?:,|$)`).exec(decode(raw));\n return m ? m[1] === 'yes' : null;\n}\n\nexport type TcConsents = {\n purposes: Set<number>;\n legitimateInterests: Set<number>;\n /** Vendor ids with consent; null when the vendor section is truncated. */\n vendors: Set<number> | null;\n /** The publisher segment (type 3): the site's own purposes. Empty sets when\n * the string carries none. */\n publisherPurposes: Set<number>;\n publisherLegitimateInterests: Set<number>;\n /** PurposeOneTreatment (bit 200): purpose 1 is not collected. */\n purposeOneTreatment: boolean;\n};\n\n/**\n * Decode an IAB TCF v2 TC string's core segment. Bit layout (TCF v2.2 spec):\n * Version 6 · Created 36 · LastUpdated 36 · CmpId 12 · CmpVersion 12 ·\n * ConsentScreen 6 · ConsentLanguage 12 · VendorListVersion 12 ·\n * TcfPolicyVersion 6 · IsServiceSpecific 1 · UseNonStandardTexts 1 ·\n * SpecialFeatureOptIns 12 · PurposesConsent 24 (bit 152) ·\n * PurposesLITransparency 24 (bit 176) · PurposeOneTreatment 1 · PublisherCC 12\n * · then the vendor-consent section at bit 213: MaxVendorId 16 ·\n * IsRangeEncoding 1 · a MaxVendorId-bit field, or NumEntries 12 and entries\n * of IsARange 1 · Start 16 · [End 16]. Null for anything that isn't v2.\n */\nconst B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\nconst toBits = (seg: string): string => {\n let bits = '';\n for (const ch of seg) bits += B64URL.indexOf(ch).toString(2).padStart(6, '0');\n return bits;\n};\n\nexport function tcStringConsents(tc: string | undefined): TcConsents | null {\n if (!tc) return null;\n const segments = tc.split('.');\n const core = segments[0]!;\n if (!/^[A-Za-z0-9_-]+$/.test(core)) return null;\n const bits = toBits(core);\n if (bits.length < 200 || parseInt(bits.slice(0, 6), 2) !== 2) return null;\n const int = (at: number, len: number): number | null => (at + len <= bits.length ? parseInt(bits.slice(at, at + len), 2) : null);\n const purposes = new Set<number>();\n const legitimateInterests = new Set<number>();\n for (let p = 1; p <= 24; p++) {\n if (bits[151 + p] === '1') purposes.add(p);\n if (bits[175 + p] === '1') legitimateInterests.add(p);\n }\n let vendors: Set<number> | null = null;\n const max = int(213, 16);\n const isRange = int(229, 1);\n if (max !== null && isRange === 0) {\n if (230 + max <= bits.length) {\n vendors = new Set();\n for (let v = 1; v <= max; v++) if (bits[229 + v] === '1') vendors.add(v);\n }\n } else if (max !== null && isRange === 1) {\n const n = int(230, 12);\n let at = 242;\n const out = new Set<number>();\n let ok = n !== null;\n for (let i = 0; ok && i < (n ?? 0); i++) {\n const range = int(at, 1);\n const start = int(at + 1, 16);\n if (range === null || start === null) ok = false;\n else if (range === 1) {\n const end = int(at + 17, 16);\n if (end === null || end < start || end - start > 65535) ok = false;\n else for (let v = start; v <= end; v++) out.add(v);\n at += 33;\n } else {\n out.add(start);\n at += 17;\n }\n }\n if (ok) vendors = out;\n }\n // Publisher TC segment: SegmentType 3 · PubPurposesConsent 24 ·\n // PubPurposesLITransparency 24 (then custom purposes, unused here).\n const publisherPurposes = new Set<number>();\n const publisherLegitimateInterests = new Set<number>();\n for (const seg of segments.slice(1)) {\n if (!/^[A-Za-z0-9_-]+$/.test(seg)) continue;\n const pb = toBits(seg);\n if (pb.length < 51 || parseInt(pb.slice(0, 3), 2) !== 3) continue;\n for (let p = 1; p <= 24; p++) {\n if (pb[2 + p] === '1') publisherPurposes.add(p);\n if (pb[26 + p] === '1') publisherLegitimateInterests.add(p);\n }\n }\n return { purposes, legitimateInterests, vendors, publisherPurposes, publisherLegitimateInterests, purposeOneTreatment: bits[200] === '1' };\n}\n\n/** Purpose consents only — kept for callers of the pre-vendor parser. */\nexport function tcStringPurposes(tc: string | undefined): Set<number> | null {\n return tcStringConsents(tc)?.purposes ?? null;\n}\n\n// TCF policy: purposes 1, 3, 4, 5 and 6 need consent; the rest may rest on a\n// legitimate interest the visitor didn't object to.\nconst TCF_CONSENT_ONLY = new Set([1, 3, 4, 5, 6]);\n\nfunction tcfSatisfied(\n n: { purposes: readonly number[]; vendorId?: number },\n consent: (p: number) => boolean,\n li: (p: number) => boolean,\n vendor: (v: number) => boolean | null,\n): boolean | null {\n const purposesOk = n.purposes.every((p) => consent(p) || (!TCF_CONSENT_ONLY.has(p) && li(p)));\n if (!purposesOk) return false;\n if (n.vendorId === undefined) return true;\n return vendor(n.vendorId);\n}\n\n// ── Normalisation ─────────────────────────────────────────────────────────\n\ntype Norm =\n | { cmp: 'cookiebot'; category: string }\n | { cmp: 'onetrust'; group: string }\n | { cmp: 'cookieyes'; category: string }\n | { cmp: 'tcf'; purposes: readonly number[]; vendorId?: number }\n | { cmp: 'google-consent-mode'; type: string; dataLayer: string; region?: string }\n | { cmp: 'shopify'; category: 'analytics' | 'marketing' | 'preferences' }\n | { cmp: 'custom'; cookie?: string; value: string; check?: () => boolean; event?: string; refused?: () => boolean };\n\nfunction normalize(input: ConsentSource): Norm {\n const src = (typeof input === 'string' ? { cmp: input } : input) as Exclude<ConsentSource, string>;\n switch (src.cmp) {\n case 'cookiebot':\n return { cmp: 'cookiebot', category: src.category ?? 'statistics' };\n case 'onetrust':\n return { cmp: 'onetrust', group: src.group ?? 'C0002' };\n case 'cookieyes':\n return { cmp: 'cookieyes', category: src.category ?? 'analytics' };\n case 'tcf':\n return {\n cmp: 'tcf',\n purposes: src.purposes && src.purposes.length > 0 ? src.purposes : TCF_DEFAULT_PURPOSES,\n vendorId: typeof src.vendorId === 'number' && src.vendorId > 0 ? src.vendorId : undefined,\n };\n case 'google-consent-mode':\n return {\n cmp: 'google-consent-mode',\n type: src.type ?? 'analytics_storage',\n dataLayer: src.dataLayer ?? 'dataLayer',\n region: typeof src.region === 'string' && src.region.trim() !== '' ? src.region.trim().toUpperCase() : undefined,\n };\n case 'shopify':\n return { cmp: 'shopify', category: src.category ?? 'analytics' };\n default:\n return { cmp: 'custom', cookie: src.cookie, value: src.value ?? 'accepted', check: src.check, event: src.event, refused: src.refused };\n }\n}\n\n/**\n * Server-side read from the request's cookies (Next.js `AdaptiveRoot`).\n * true/false when the CMP's cookie decides it, null when it can't be known on\n * the server (no cookie yet, a JS-only source) — the caller then gates the\n * first paint and lets the browser decide.\n *\n * `getCookie` must return the value exactly as sent in the Cookie header,\n * NOT decoded: most server cookie jars (Next's cookies(), Express\n * cookie-parser) decode values, and a decoded OneTrust cookie lets a crafted\n * landing URL inject a `groups=` field that reads as consent.\n */\nexport function consentFromCookies(src: ConsentSource, getCookie: (name: string) => string | undefined): boolean | null {\n const n = normalize(src);\n switch (n.cmp) {\n case 'cookiebot':\n return cookiebotCookieGrants(getCookie('CookieConsent'), n.category);\n case 'onetrust':\n return onetrustCookieGrants(getCookie('OptanonConsent'), n.group);\n case 'cookieyes':\n return cookieyesCookieGrants(getCookie('cookieyes-consent'), n.category);\n case 'tcf': {\n const c = tcStringConsents(getCookie('euconsent-v2'));\n if (!c) return null;\n return tcfSatisfied(\n c.purposeOneTreatment ? { ...n, purposes: n.purposes.filter((p) => p !== 1) } : n,\n (p) => c.purposes.has(p) || c.publisherPurposes.has(p),\n (p) => c.legitimateInterests.has(p) || c.publisherLegitimateInterests.has(p),\n (v) => (c.vendors ? c.vendors.has(v) : null),\n );\n }\n case 'google-consent-mode':\n return null;\n case 'shopify':\n // `_tracking_consent` is undocumented; the browser API decides.\n return null;\n case 'custom':\n if (!n.cookie || n.check) return null;\n return getCookie(n.cookie) === n.value;\n }\n}\n\n/** Consent Mode state folded from dataLayer commands, one storage type. */\ntype ConsentModeState = {\n /** Latest `update` — applies in every region and beats any default. */\n update: boolean | null;\n /** Latest region-less `default`. */\n global: boolean | null;\n /** Latest region-scoped `default`, per upper-cased region code. */\n regions: Map<string, boolean>;\n};\n\nconst emptyConsentModeState = (): ConsentModeState => ({ update: null, global: null, regions: new Map() });\n\nfunction foldConsentMode(state: ConsentModeState, item: unknown, type: string): void {\n // gtag() pushes `arguments` objects; GTM templates push arrays.\n const args = item && typeof item === 'object' && 'length' in (item as object) ? Array.prototype.slice.call(item) : null;\n if (!args || args[0] !== 'consent' || (args[1] !== 'default' && args[1] !== 'update')) return;\n const params = args[2] as Record<string, unknown> | undefined;\n const raw = params?.[type];\n const v = raw === 'granted' ? true : raw === 'denied' ? false : null;\n if (v === null) return;\n if (args[1] === 'update') {\n state.update = v;\n return;\n }\n const region = params?.region;\n const list = Array.isArray(region) ? region : typeof region === 'string' ? [region] : [];\n const codes = list.filter((r): r is string => typeof r === 'string' && r.trim() !== '').map((r) => r.trim().toUpperCase());\n if (codes.length === 0) state.global = v;\n else for (const c of codes) state.regions.set(c, v);\n}\n\n/** A recorded \"denied\" is an `update` only. A `default` is the site's\n * starting state, pushed on every page before the CMP answers (Google's own\n * recommended setup) — treating `default: denied` as a refusal forgot every\n * consented visitor whose CMP pushed its `update` a moment after we read. */\nfunction consentModeRefused(state: ConsentModeState): boolean {\n return state.update === false;\n}\n\nfunction resolveConsentMode(state: ConsentModeState, region: string | undefined): boolean | null {\n if (state.update !== null) return state.update;\n if (region) {\n // Most specific wins: 'US-CA' over 'US' over the global default.\n const exact = state.regions.get(region);\n if (exact !== undefined) return exact;\n const country = region.split('-')[0]!;\n const byCountry = state.regions.get(country);\n if (byCountry !== undefined) return byCountry;\n // Country only ('US', the usual CDN header) but a subdivision-scoped\n // denial ('US-CA'): the visitor may be in it, so it reads as denied.\n if (region === country) {\n for (const [r, v] of state.regions) if (v === false && r.startsWith(`${country}-`)) return false;\n }\n return state.global;\n }\n // Region unknown: a region-scoped denial may be this visitor's. The old\n // reader ignored `region` entirely, so the common EU setup — global\n // granted, `region: [EU…]` denied — read as granted for EU visitors.\n for (const v of state.regions.values()) if (v === false) return false;\n if (state.global !== null) return state.global;\n // Only region-scoped grants: this visitor may be outside all of them.\n return state.regions.size > 0 ? false : null;\n}\n\n/**\n * The Consent Mode state for `type` in `dataLayer`, or null when no command\n * has decided it. `region` (e.g. 'ES', 'US-CA') resolves region-scoped\n * `consent default` commands; without it, any region-scoped denial reads as\n * denied until an `update` settles it.\n */\nexport function consentModeGranted(dataLayer: unknown, type = 'analytics_storage', region?: string): boolean | null {\n if (!Array.isArray(dataLayer)) return null;\n const state = emptyConsentModeState();\n for (const item of dataLayer) foldConsentMode(state, item, type);\n return resolveConsentMode(state, region?.trim().toUpperCase() || undefined);\n}\n\n// ── Browser watcher ───────────────────────────────────────────────────────\n\nexport function consentWatcher(src: ConsentSource, win: Window = window): ConsentWatcher {\n const n = normalize(src);\n const w = win as AnyWin;\n const doc = win.document;\n switch (n.cmp) {\n case 'cookiebot':\n return {\n read: () => {\n const cb = w.Cookiebot as { consent?: Record<string, unknown>; hasResponse?: unknown } | undefined;\n const cookie = cookiebotCookieGrants(docCookie(doc, 'CookieConsent'), n.category);\n // The stored answer wins until Cookiebot says it has one in memory:\n // a `consent` object read before uc.js finishes initialising can hold\n // defaults (all false), and reading those for a returning visitor\n // gated them — or, with refused(), forgot them (grader N-D).\n if (cb?.consent && typeof cb.consent[n.category] === 'boolean' && (cb.hasResponse === true || cookie === null)) {\n return cb.consent[n.category] === true;\n }\n return cookie;\n },\n subscribe: (cb) => listen(win, ['CookiebotOnAccept', 'CookiebotOnDecline', 'CookiebotOnConsentReady', 'CookiebotOnLoad'], cb),\n // Only once the visitor has answered: `consent.statistics` is also\n // false while the banner is pending. The cookie is written on answer.\n refused() {\n const cb = w.Cookiebot as { hasResponse?: unknown } | undefined;\n const answered = cb?.hasResponse === true || docCookie(doc, 'CookieConsent') !== undefined;\n return answered && this.read() === false;\n },\n };\n case 'onetrust':\n return {\n read: () => {\n const groups = w.OnetrustActiveGroups;\n if (typeof groups === 'string') return `,${groups},`.includes(`,${n.group},`);\n return onetrustCookieGrants(docCookie(doc, 'OptanonConsent'), n.group);\n },\n subscribe: (cb) => listen(win, ['OneTrustGroupsUpdated'], cb),\n // OneTrust writes OptanonAlertBoxClosed when the visitor answers; before\n // that, an opt-in region's active groups are just the defaults.\n refused() {\n return docCookie(doc, 'OptanonAlertBoxClosed') !== undefined && this.read() === false;\n },\n };\n case 'cookieyes':\n return {\n read: () => {\n const get = w.getCkyConsent as (() => { categories?: Record<string, unknown> }) | undefined;\n if (typeof get === 'function') {\n try {\n const cats = get()?.categories;\n if (cats && typeof cats[n.category] === 'boolean') return cats[n.category] === true;\n } catch {\n /* banner not ready — fall through to the cookie */\n }\n }\n return cookieyesCookieGrants(docCookie(doc, 'cookieyes-consent'), n.category);\n },\n subscribe: (cb) => listen(win, ['cookieyes_consent_update', 'cookieyes_banner_load', 'cookieyes_banner_loaded'], cb),\n // Answered = the API says the user acted, or the cookie records\n // `action:yes`; the categories read false while the banner is pending.\n refused() {\n let answered = /(?:^|,)action:yes(?:,|$)/.test(decode(docCookie(doc, 'cookieyes-consent') ?? ''));\n const get = w.getCkyConsent as (() => { isUserActionCompleted?: unknown }) | undefined;\n if (!answered && typeof get === 'function') {\n try {\n answered = get()?.isUserActionCompleted === true;\n } catch {\n /* not ready */\n }\n }\n return answered && this.read() === false;\n },\n };\n case 'tcf': {\n let granted: boolean | null = null;\n // The banner being up is \"no decision yet\" (or a re-prompt), never a refusal.\n let bannerUp = false;\n // Forget-me needs storage itself refused (purpose 1). A decision that\n // grants storage but lacks 5/6/8 or the vendor only gates: many CMPs never\n // OFFER those purposes, and \"not offered\" is indistinguishable from \"no\"\n // in the TC data — forgetting on it wiped every accepting visitor on each\n // page of such sites (review #6).\n let storageRefused = false;\n return {\n read: () => granted,\n refused: () => granted === false && !bannerUp && storageRefused,\n subscribe: (cb) => {\n type TcData = {\n gdprApplies?: boolean;\n eventStatus?: string;\n listenerId?: number;\n purpose?: { consents?: Record<string, boolean>; legitimateInterests?: Record<string, boolean> };\n vendor?: { consents?: Record<string, boolean> };\n publisher?: { consents?: Record<string, boolean>; legitimateInterests?: Record<string, boolean> };\n purposeOneTreatment?: boolean;\n };\n type TcfApi = (cmd: string, v: number, cb: (d: TcData, ok: boolean) => void, param?: unknown) => void;\n let listenerId: number | undefined;\n let stopped = false;\n let everDecided = false;\n const onData = (d: TcData, ok: boolean): void => {\n if (!ok || stopped) return;\n if (typeof d.listenerId === 'number') listenerId = d.listenerId;\n // cmpuishown = the banner is up: no decision yet.\n bannerUp = d.eventStatus === 'cmpuishown';\n // Only a completed decision: some CMPs emit early/empty tcData\n // (cmpStatus 'loading') with ok=true — not a refusal (review #9).\n // purposeOneTreatment: purpose 1 isn't collected in this\n // jurisdiction, so its absence is not a refusal.\n storageRefused =\n (d.eventStatus === 'tcloaded' || d.eventStatus === 'useractioncomplete') &&\n d.purposeOneTreatment !== true &&\n d.gdprApplies !== false &&\n d.purpose?.consents?.[1] !== true &&\n d.publisher?.consents?.[1] !== true;\n const decided = d.eventStatus === 'tcloaded' || d.eventStatus === 'useractioncomplete';\n if (decided) everDecided = true;\n if (bannerUp) granted = false;\n // A loading/empty callback is \"not known yet\" (null), never false:\n // reading it as false disposed a server-granted client on load\n // and re-sent its decides (grader N7-5). After a decision it\n // changes nothing: the SDKs now read null-after-an-answer as a\n // pause, so a stray one paused a consented visitor (review R11 #2).\n else if (!decided && d.gdprApplies !== false) {\n if (!everDecided) granted = null;\n }\n else\n granted =\n d.gdprApplies === false ||\n tcfSatisfied(\n // Purpose 1 isn't collected under purposeOneTreatment: not\n // required then, or those visitors could never be granted\n // (N7-8).\n d.purposeOneTreatment === true ? { ...n, purposes: n.purposes.filter((p) => p !== 1) } : n,\n // Publisher consent counts too: SentientUI processes for the\n // site, and some CMPs record the site's own purposes only in\n // the publisher segment.\n (p) => d.purpose?.consents?.[p] === true || d.publisher?.consents?.[p] === true,\n (p) => d.purpose?.legitimateInterests?.[p] === true || d.publisher?.legitimateInterests?.[p] === true,\n (v) => d.vendor?.consents?.[v] === true,\n ) === true;\n cb();\n };\n // CMPs install the IAB stub early, but a late one needs a moment.\n let tries = 0;\n const attach = (): void => {\n if (stopped) return;\n const api = w.__tcfapi as TcfApi | undefined;\n if (typeof api === 'function') api('addEventListener', 2, onData);\n else if (tries++ < 40) window.setTimeout(attach, 250);\n };\n attach();\n return () => {\n stopped = true;\n const api = w.__tcfapi as TcfApi | undefined;\n if (typeof api === 'function' && listenerId !== undefined) api('removeEventListener', 2, () => undefined, listenerId);\n };\n },\n };\n }\n case 'google-consent-mode': {\n // Folded incrementally: each read scans only entries pushed since the\n // last one (the old reader rescanned the whole dataLayer every second —\n // GTM sites push hundreds of entries). A replaced or shrunk array\n // restarts the fold.\n let seen: unknown[] | null = null;\n let upTo = 0;\n let state = emptyConsentModeState();\n const read = (): boolean | null => {\n const dl = w[n.dataLayer];\n if (!Array.isArray(dl)) return null;\n if (dl !== seen || dl.length < upTo) {\n seen = dl;\n upTo = 0;\n state = emptyConsentModeState();\n }\n for (; upTo < dl.length; upTo++) foldConsentMode(state, dl[upTo], n.type);\n return resolveConsentMode(state, n.region);\n };\n return {\n read,\n refused: () => read() === false && consentModeRefused(state),\n subscribe: (cb) => {\n // Wrap push ONCE per array, and never re-wrap: gtag.js and GTM\n // replace dataLayer.push with a function that chains to the previous\n // one (ours), so wrapping theirs again made the two call each other\n // forever (caught by the real-gtag.js e2e, 2026-09-25). A\n // replacement that doesn't chain is covered by the poll, which is\n // O(1) — it compares lengths and calls `cb` only when entries arrived\n // (the old poll called it every second, forever, re-scanning all).\n const wrappedArrays = new WeakSet<object>();\n let stopped = false;\n const unwrap: Array<() => void> = [];\n let lastLen = -1;\n const attach = (): void => {\n const dl = (w[n.dataLayer] ??= []) as unknown[] & { push: (...a: unknown[]) => number };\n if (!wrappedArrays.has(dl)) {\n wrappedArrays.add(dl);\n const original = dl.push;\n const wrapped = function (this: unknown, ...a: unknown[]): number {\n const r = original.apply(dl, a);\n lastLen = dl.length;\n // gtag/GTM chain onto this wrapper, so it can't always be\n // unhooked on unsubscribe; a stopped one must go quiet.\n if (!stopped) cb();\n return r;\n };\n dl.push = wrapped;\n unwrap.push(() => {\n if (dl.push === wrapped) dl.push = original;\n });\n }\n if (dl.length !== lastLen) {\n lastLen = dl.length;\n cb();\n }\n };\n attach();\n const timer = window.setInterval(attach, 1000);\n return () => {\n stopped = true;\n window.clearInterval(timer);\n for (const u of unwrap) u();\n };\n },\n };\n }\n case 'shopify': {\n type CustomerPrivacy = Partial<Record<'analyticsProcessingAllowed' | 'marketingAllowed' | 'preferencesProcessingAllowed', () => unknown>>;\n type ShopifyGlobal = {\n customerPrivacy?: CustomerPrivacy;\n loadFeatures?: (features: Array<{ name: string; version: string }>, cb: (err?: unknown) => void) => void;\n };\n const method =\n n.category === 'marketing' ? 'marketingAllowed' : n.category === 'preferences' ? 'preferencesProcessingAllowed' : 'analyticsProcessingAllowed';\n return {\n read: () => {\n const fn = (w.Shopify as ShopifyGlobal | undefined)?.customerPrivacy?.[method];\n if (typeof fn !== 'function') return null; // API not loaded yet\n try {\n const v = fn();\n return typeof v === 'boolean' ? v : null;\n } catch {\n return null;\n }\n },\n // analyticsProcessingAllowed() is also false before the visitor has\n // answered in a consent region; only an explicit 'no' is a refusal.\n refused() {\n const priv = (w.Shopify as { customerPrivacy?: { currentVisitorConsent?: () => Record<string, unknown> } } | undefined)?.customerPrivacy;\n if (typeof priv?.currentVisitorConsent !== 'function') return false;\n try {\n return priv.currentVisitorConsent()?.[n.category] === 'no';\n } catch {\n return false;\n }\n },\n subscribe: (cb) => {\n const stopListen = listen(win, ['visitorConsentCollected'], cb);\n // The API is not on the page until something loads it; a theme's\n // own banner usually does, but nothing guarantees it.\n let stopped = false;\n let tries = 0;\n const load = (): void => {\n if (stopped) return;\n const shop = w.Shopify as ShopifyGlobal | undefined;\n if (shop?.customerPrivacy) {\n cb();\n return;\n }\n if (typeof shop?.loadFeatures === 'function') {\n try {\n shop.loadFeatures([{ name: 'consent-tracking-api', version: '0.1' }], (err) => {\n if (!stopped && !err) cb();\n });\n } catch {\n /* a broken storefront API never breaks the site */\n }\n return;\n }\n if (tries++ < 40) window.setTimeout(load, 250);\n };\n load();\n return () => {\n stopped = true;\n stopListen();\n };\n },\n };\n }\n case 'custom':\n return {\n read: () => {\n if (n.check) {\n try {\n return n.check() === true;\n } catch {\n return false;\n }\n }\n if (!n.cookie) return null;\n const v = docCookie(doc, n.cookie);\n // No cookie yet = no decision yet; any other value = not granted.\n return v === undefined ? null : v === n.value;\n },\n // A cookie holding another value is an answer; a predicate isn't —\n // unless the site says so through `refused` (grader F4).\n refused: () => {\n if (n.check) {\n try {\n return n.refused?.() === true;\n } catch {\n return false;\n }\n }\n return !!n.cookie && docCookie(doc, n.cookie) !== undefined && docCookie(doc, n.cookie) !== n.value;\n },\n subscribe: (cb) => (n.event ? listen(win, [n.event], cb) : () => undefined),\n };\n }\n}\n","/**\n * Per-project browser-storage namespace suffix, derived from the public apiKey.\n *\n * Multiple SentientUI projects (different `pk_` keys) can run on the same exact\n * origin. Storage keyed only by name (`_snt_uid`, `_snt_asgn_*`,\n * `_snt_graph_nodes`) would then collide across projects — the visitor id in\n * particular, whose session row is keyed globally server-side, would let one\n * project's traffic land on another's session. Suffixing every browser key with\n * the apiKey prefix isolates projects, matching the queue's existing\n * `_snt_retry_${apiKey.slice(0,12)}` convention.\n *\n * Returns `''` when no apiKey is available (local mode) so keys stay stable\n * there.\n */\nexport function storageSuffix(apiKey?: string): string {\n return apiKey ? `_${apiKey.slice(0, 12)}` : '';\n}\n\n/**\n * The bare, pre-namespacing session cookie name. Still read as a FALLBACK\n * everywhere the suffixed name is read, so visitors who got their identity\n * before per-project namespacing keep it instead of being minted a fresh one.\n */\nexport const LEGACY_SESSION_COOKIE_NAME = '_snt_uid';\n\n/**\n * The one place the session cookie's name is decided. The writer (session.ts)\n * and every reader (core/server.ts SSR helper, graph sync, react devtools) must\n * call THIS — when namespacing landed, the writer moved to the suffixed name\n * while three readers kept the bare `_snt_uid`, so every SSR request for a\n * returning visitor missed the cookie and minted a fresh orphan session (quota\n * inflation, broken sticky assignments and persona continuity), and graph sync\n * sent `sessionId: undefined`. Deriving both sides from one function makes that\n * drift impossible, and index.test.ts pins the reader against the writer.\n */\nexport function sessionCookieName(apiKey?: string): string {\n return `${LEGACY_SESSION_COOKIE_NAME}${storageSuffix(apiKey)}`;\n}\n\n// Forget-me generation per project, on window so every bundle on the page\n// sees it (the snippet and its lazy chunks each carry their own copy of these\n// modules). Every client and queue captures it when created and persists only\n// while it is unchanged: a forget can never be undone by a later grant — the\n// old boolean marker was cleared by the next tracking client, and a paused\n// client's in-flight decide then wrote the forgotten visitor back (grader\n// NEW-1), as could its queues' failed final flush (F8).\nconst GENS = '__sntForgetGen';\ntype GenMap = Record<string, number>;\nconst genMap = (): GenMap | undefined => {\n try {\n return (window as unknown as Record<string, GenMap | undefined>)[GENS];\n } catch {\n return undefined;\n }\n};\nexport function markForgotten(apiKey: string): void {\n try {\n const w = window as unknown as Record<string, GenMap>;\n const m = (w[GENS] ??= {});\n m[apiKey] = (m[apiKey] ?? 0) + 1;\n } catch {\n /* no window */\n }\n}\n/** Bumped by every forget-me for this project in this page. */\nexport function forgetGeneration(apiKey: string): number {\n return genMap()?.[apiKey] ?? 0;\n}\n\n/**\n * The \"mark this browser internal\" cookie (internal-traffic plan, Interfaces).\n * One name for the browser writer (internal.ts) and the SSR reader\n * (@sentientui/react/server) — the same drift the session cookie name had\n * (writer renamed, readers not) would silently stop SSR upserts carrying the\n * token, so server-rendered first requests from a team browser would count.\n * Not namespaced per project: the value is the project-bound token itself,\n * and the server ignores a token that is not this project's.\n */\nexport const INTERNAL_COOKIE = 'sentient_internal';\n","/**\n * Decision snapshot: the SPA / return-visit pre-paint source. Written after\n * every successful decide; read by the inline pre-paint script (before any\n * framework code runs) and by init() to seed slot/persona state.\n */\nimport type { ServedEdits } from './region-skeleton.js';\nimport type { SlotResult } from './slots.js';\nimport type { BlockNode, SitePalette } from './blocks.js';\n\nexport const SNAPSHOT_STORAGE_KEY_PREFIX = '_snt_snap:';\n/** A snapshot older than this is ignored (the inline pre-paint's 2592e6). */\nexport const SNAPSHOT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** Versioned compound locator: resolve id → dataAttr → selector, then verify\n * against fingerprint. Lets a slot survive DOM/markup drift. */\nexport type CompoundLocator = {\n v?: number;\n id?: string;\n dataAttr?: { name: string; value: string };\n selector?: string;\n urlMatch?: string;\n /** Where the element is expected to exist — see page-scope.ts. Health only, never serving. */\n page?: string;\n fingerprint?: { tag?: string; text?: string };\n semanticId?: string;\n};\n\n/** Bounded, declarative operations a registry arm may apply to its element.\n * The style set is a fixed whitelist (validated server-side); no arbitrary CSS,\n * HTML, or JS ever. `text` is applied via textContent; https-only URLs.\n * moveBefore/moveAfter (exactly one) reposition the element relative to a\n * uniquely-resolving sibling anchor — post-decide only, never pre-paint. */\nexport type SlotOps = {\n text?: string;\n style?: Record<string, string>;\n hidden?: boolean;\n href?: string;\n imageSrc?: string;\n imageAlt?: string;\n moveBefore?: CompoundLocator;\n moveAfter?: CompoundLocator;\n};\n\n/** Registry-mode apply info per slot: where to apply and what to set. Stored so\n * a returning visitor's pre-paint can reapply it. `target` is the Phase-2 bare\n * selector; `locator` (Phase 3) is the compound locator, preferred when present. */\nexport type SlotConfigEntry = {\n kind: 'tokens' | 'arms';\n target?: string;\n locator?: CompoundLocator;\n content?: string;\n ops?: SlotOps;\n /** Composition Blocks per arm — ALL arms, not just the served one, because\n * Option-B rendering pre-paints every arm hidden and reveals the served one\n * (spec §6). Holdout sessions receive the baseline arm's tree only, so the\n * control group's DOM stays meaningful. Absent for non-composition slots. */\n blocks?: Record<string, BlockNode>;\n /** The served Rewrite arm (spec 2026-09-23 §4.3): per-node edits plus the\n * skeleton fingerprint and leaf map they were written against. */\n edits?: ServedEdits;\n /** The server has no skeleton for this region — capture and report one. */\n needsSkeleton?: true;\n /** Redesign arms per arm id — ALL arms, same Option-B reason as `blocks`.\n * Served only to pages that declared RenderCaps.compose. */\n compose?: Record<string, import('./style-vocabulary.js').ComposeArm>;\n /** A hybrid <Adaptive> held back: its id still has un-migrated variant\n * history, so the page renders its original until the operator migrates. */\n blocked?: 'variant_history';\n};\n\nexport type DecisionSnapshot = {\n v: 1;\n persona: string;\n band: 'low' | 'medium' | 'high';\n slots: Record<string, SlotResult>;\n layoutOrder: string[] | null;\n savedAt: number;\n // Additive (kept at v:1 so existing snapshots stay valid — bumping the version\n // would flush every returning visitor's snapshot and flash the baseline once).\n // Present only for registry-mode (no-code) installs.\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Derived site palette for Composition Block rendering — cached so the\n * pre-paint render already looks native (a palette that pops in post-decide\n * would be its own flash). */\n palette?: SitePalette;\n /** The site-style entries the served compose arms reference — cached so the\n * pre-paint render already borrows the site's classes. Additive (v stays 1). */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n /** The `data-sentient-stage` value last decided — already coarsened, and\n * present only for a `stageAttributes` install (additive, v stays 1). */\n stage?: string;\n};\n\nconst BANDS = ['low', 'medium', 'high'];\n\n/** Returns null on missing, corrupt, or wrong-version data — never throws. */\nexport function readSnapshot(apiKey: string): DecisionSnapshot | null {\n try {\n const raw = localStorage.getItem(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey);\n if (!raw) return null;\n const p = JSON.parse(raw) as Partial<DecisionSnapshot> | null;\n if (\n !p ||\n typeof p !== 'object' ||\n p.v !== 1 ||\n typeof p.persona !== 'string' ||\n typeof p.band !== 'string' ||\n !BANDS.includes(p.band) ||\n typeof p.slots !== 'object' ||\n p.slots === null ||\n Array.isArray(p.slots) ||\n !(p.layoutOrder === null || Array.isArray(p.layoutOrder)) ||\n typeof p.savedAt !== 'number' ||\n // The documented 30-day life, the same bound the inline pre-paint script\n // applies: an older decision is ignored everywhere (grader NEW-5).\n !(Date.now() - p.savedAt < SNAPSHOT_MAX_AGE_MS) ||\n // slotConfig is optional; when present it must be a plain object.\n !(p.slotConfig === undefined || (typeof p.slotConfig === 'object' && p.slotConfig !== null && !Array.isArray(p.slotConfig)))\n ) {\n return null;\n }\n // A malformed cached vocabulary degrades to palette styling, never throws.\n const v = p.vocabulary as { entries?: unknown; images?: unknown } | undefined;\n if (v !== undefined && (typeof v !== 'object' || v === null || !Array.isArray(v.entries) || !Array.isArray(v.images))) {\n delete p.vocabulary;\n }\n // Same for the stage: a non-string never reaches setAttribute.\n if (p.stage !== undefined && typeof p.stage !== 'string') delete p.stage;\n return p as DecisionSnapshot;\n } catch {\n return null;\n }\n}\n\n/** Best-effort persist — storage failures are swallowed. */\nexport function writeSnapshot(apiKey: string, snap: DecisionSnapshot): void {\n try {\n localStorage.setItem(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey, JSON.stringify(snap));\n } catch {\n /* private mode / quota — the snapshot is an optimization, never a requirement */\n }\n}\n\n/**\n * Inline pre-paint script (Rung 1a): reads the snapshot and sets\n * `data-sentient-persona` / `data-sentient-confidence` on <html> before\n * first paint. Single-writer: it never overwrites attributes already set.\n *\n * Safety properties (pinned by tests):\n * - apiKey goes through JSON.stringify, then '<' is escaped to <, so a\n * hostile key can neither break the JS string nor terminate the <script>.\n * - Built by string concatenation and contains no backticks, so the output\n * survives being embedded in template-literal-based renderers.\n */\nexport function renderPrePaintScript(apiKey: string, opts?: { stage?: boolean }): string {\n const key = JSON.stringify(SNAPSHOT_STORAGE_KEY_PREFIX + apiKey).replace(/</g, '\\\\u003c');\n return (\n '(function(){try{' +\n // DNT/GPC: the SDK never reads what it stored for an opted-out browser\n // (grader F3 — this fallback had no gate at all).\n // Every signal isDoNotTrackEnabled reads, not just the standard one.\n 'var N=navigator,W=window;if(N.doNotTrack==\"1\"||N.doNotTrack==\"yes\"||W.doNotTrack==\"1\"||N.msDoNotTrack==\"1\"||N.globalPrivacyControl)return;' +\n 'var r=localStorage.getItem(' + key + ');if(!r)return;' +\n 'var s=JSON.parse(r);' +\n 'if(!s||s.v!==1||typeof s.persona!==\"string\"||typeof s.band!==\"string\")return;' +\n // The same 30-day life readSnapshot enforces.\n 'if(!(' + SNAPSHOT_MAX_AGE_MS + '>Date.now()-s.savedAt))return;' +\n 'var d=document.documentElement;' +\n // Opt-in stage attribute (`stageAttributes`): the snapshot holds only the\n // already-coarsened value, so this copies it as-is. Before the persona\n // single-writer return below — an SSR persona must not stop it — but with\n // its own single-writer check, so an SSR-written stage wins. Absent from\n // the output entirely without the option (the default bytes are pinned).\n (opts?.stage\n ? 'if(typeof s.stage==\"string\"&&!d.hasAttribute(\"data-sentient-stage\"))d.setAttribute(\"data-sentient-stage\",s.stage);'\n : '') +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",s.persona);' +\n 'd.setAttribute(\"data-sentient-confidence\",s.band);' +\n '}catch(e){}})();'\n );\n}\n","/** Batched event queue with reliable transport (fetch + keepalive, localStorage retry). */\n\nimport { forgetGeneration } from './storage-key.js';\nimport { QUEUE_TIMEOUT_MS, timeoutSignal } from './timeout.js';\nimport { backoffDelayMs, classifyResponse, drainBucket, purgeBucket, writeBucket } from './durable.js';\n\nexport type EventType =\n | 'variant_assigned'\n | 'goal_achieved'\n | 'scroll_depth'\n | 'dwell'\n | 'cursor_signal'\n | 'component_visible'\n | 'component_exited'\n | 'micro_signal'\n // A funnel DECLARATION, not telemetry: the server upserts the funnel entity\n // and never stores it in raw_events. Listed here so callers can express it\n // without casting through the track() signature.\n | 'funnel_declared'\n // A goal DECLARATION (React `useGoal`, the snippet's `primaryGoal`): the\n // server creates the goal so it shows at 0 before it first fires, and with\n // `primary: true` makes it the main goal. Never stored in raw_events.\n | 'goal_declared'\n // One per page load and per SPA route change, so a visit's journey through the\n // site is reconstructable. Carries `path` and nothing else.\n | 'pageview'\n // Session-level interaction aggregates for the browser-agent axis (one\n // cumulative snapshot per bank point on the `__session__` sentinel). Read by\n // the bot scorer only; never attributed to a component, never a reward.\n | 'interaction_stats';\n\nexport type SentientEvent = {\n id: string;\n sessionId: string;\n projectId: string;\n componentId: string;\n variantId?: string;\n eventType: EventType;\n goalType?: string;\n /**\n * Page path the event happened on, e.g. `/pricing`. Set automatically from\n * `location.pathname` — deliberately NOT `location.href`, so query strings\n * (which routinely carry emails, reset tokens and order ids) never leave the\n * browser. The server re-strips them anyway; this is the first of two gates.\n * Undefined outside a browser (SSR), where there is no page to name.\n */\n path?: string;\n payload: Record<string, unknown>;\n timestamp: number;\n timeInSession: number;\n};\n\nexport type QueueConfig = {\n ingestUrl: string;\n apiKey: string;\n flushIntervalMs?: number;\n maxBatchSize?: number;\n maxRetrySize?: number;\n};\n\nexport type EventQueue = {\n push(event: SentientEvent): void;\n flush(): void;\n /** Stop the queue with a final flush. `forget`: the visitor asked to be\n * forgotten — a failed final delivery must NOT be persisted for retry\n * (it re-created the retry bucket after forget-me removed it). */\n destroy(opts?: { forget?: boolean }): void;\n};\n\nconst MAX_SENT_IDS = 500;\n// 64 KB is the per-origin keepalive budget on every modern browser. We split unload\n// flushes into chunks below this to avoid the whole batch being dropped.\nconst KEEPALIVE_BUDGET_BYTES = 56 * 1024;\n\n/**\n * Persisted retry-bucket key, namespaced by apiKey prefix so multiple projects\n * on the same origin each get their own bucket. Exported so the client's\n * forget-me teardown can remove it.\n */\nexport function retryStorageKey(apiKey: string): string {\n return `_snt_retry_${apiKey.slice(0, 12)}`;\n}\n\nconst SSR_QUEUE: EventQueue = {\n push: () => undefined,\n flush: () => undefined,\n destroy: () => undefined,\n};\n\n/**\n * Creates a batched event queue with periodic and lifecycle-triggered flushes.\n */\nexport function createEventQueue(config: QueueConfig): EventQueue {\n if (typeof window === 'undefined') {\n return SSR_QUEUE;\n }\n\n const flushIntervalMs = config.flushIntervalMs ?? 5000;\n const maxBatchSize = config.maxBatchSize ?? 20;\n const maxRetrySize = config.maxRetrySize ?? 100;\n const ingestUrl = config.ingestUrl;\n const apiKey = config.apiKey;\n const RETRY_KEY = retryStorageKey(apiKey);\n // Set by destroy({ forget: true }); see the type's doc.\n let forgotten = false;\n const createdGen = forgetGeneration(apiKey);\n const persistBucket: typeof writeBucket = (...a) => {\n if (!forgotten && forgetGeneration(apiKey) === createdGen) writeBucket(...a);\n };\n\n const queue: SentientEvent[] = [];\n const sentIds = new Set<string>();\n const sentIdOrder: string[] = [];\n\n const markSent = (ids: string[]): void => {\n for (const id of ids) {\n queuedIds.delete(id); // free the in-flight slot\n if (sentIds.has(id)) continue;\n sentIds.add(id);\n sentIdOrder.push(id);\n }\n while (sentIdOrder.length > MAX_SENT_IDS) {\n const oldest = sentIdOrder.shift();\n if (oldest) sentIds.delete(oldest);\n }\n // A batch that previously 5xx'd was persisted to the cross-reload retry\n // backstop. Now that it's acknowledged (delivered, or 4xx-dropped as\n // unretryable), drop those ids from localStorage too — otherwise the next\n // page load would replay an already-handled event. `sentIds` is in-memory\n // only, so it can't suppress that cross-reload duplicate on its own.\n purgeBucket(ids, RETRY_KEY);\n };\n\n // Tracks IDs currently in `queue` or in flight (handed to transportBatch\n // but not yet confirmed). Entries are removed on markSent or when an event\n // is dropped, so the set stays bounded by in-flight + queued size.\n const queuedIds = new Set<string>();\n\n // Bound the in-memory queue at the same cap as the persisted retry bucket\n // (maxRetrySize). During a sustained outage flush() keeps re-enqueueing every\n // failed batch while the page keeps producing events, and only the\n // localStorage bucket was capped — so a multi-hour outage on a long-lived\n // SPA tab grew this array without limit. Drop-oldest, matching writeBucket's\n // slice(-max) shed policy: the newest events are the ones a recovering\n // server can still use.\n const capQueue = (): void => {\n while (queue.length > maxRetrySize) {\n const dropped = queue.shift();\n if (dropped) queuedIds.delete(dropped.id);\n }\n };\n\n const enqueue = (event: SentientEvent): void => {\n if (sentIds.has(event.id) || queuedIds.has(event.id)) return;\n queuedIds.add(event.id);\n queue.push(event);\n capQueue();\n };\n\n // A retryable failure hands the batch back to the in-memory queue so the\n // backoff-gated interval flush retries it in-session (localStorage is only the\n // cross-reload backstop). The ids are still tracked in queuedIds — they were\n // pulled from `queue` on flush but never markSent — so we re-add them WITHOUT\n // going through enqueue (which would skip them as already-queued) and without\n // deleting/re-adding queuedIds. Already-sent events are never re-queued, and a\n // single event stays a single copy: `queue` is fully drained each flush.\n const requeueFailed = (batch: SentientEvent[]): void => {\n for (const event of batch) {\n if (sentIds.has(event.id)) continue;\n queuedIds.add(event.id); // idempotent — keeps id-tracking consistent\n queue.push(event);\n }\n // Failed batches count against the same bound as fresh pushes — this path\n // is exactly the one that grew unbounded during an outage (see capQueue).\n capQueue();\n };\n\n const retryEvents = drainBucket<SentientEvent>(RETRY_KEY, maxRetrySize);\n for (const event of retryEvents) {\n enqueue(event);\n }\n\n // Pause flushing until backoff expires.\n let backoffUntil = 0;\n let consecutiveFailures = 0;\n\n // Authenticated transport. keepalive: true gives unload-survival; we still await\n // the response so 5xx/429 actually surface and we can retry.\n const transportBatch = (batch: SentientEvent[], salvage = true): void => {\n if (batch.length === 0) return;\n const body = JSON.stringify(batch);\n const ids = batch.map((e) => e.id);\n\n let pending: Promise<Response> | Response;\n const queueTimer = timeoutSignal(QUEUE_TIMEOUT_MS);\n try {\n // Bounded (QUEUE_TIMEOUT_MS): a hung POST never settles, which held this\n // batch in flight forever. An abort is a retry; ids dedupe server-side.\n pending = fetch(ingestUrl, {\n method: 'POST',\n keepalive: true,\n signal: queueTimer.signal,\n body,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n });\n } catch {\n // Synchronous throw (typically jsdom in tests, or extreme browser failure).\n persistBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n return;\n }\n\n Promise.resolve(pending).then(queueTimer.clear, queueTimer.clear);\n // fetch can sometimes return a value directly (tests using stubGlobal). Handle both.\n const handleResponse = (res: Response): void => {\n if (classifyResponse(res) !== 'retry') {\n // An API older than migration 108 400s the whole batch over the unknown\n // 'pageview' type, and a 4xx is terminal — which silently dropped the\n // co-batched exposures and goals too. Re-send once without the\n // pageviews (valid on the old API); the pageviews themselves are\n // unsendable there and are dropped as delivered.\n if (!res.ok && salvage) {\n const rest = batch.filter((e) => e.eventType !== 'pageview');\n if (rest.length > 0 && rest.length < batch.length) {\n markSent(batch.filter((e) => e.eventType === 'pageview').map((e) => e.id));\n transportBatch(rest, false);\n return;\n }\n }\n // 2xx = success. 4xx (except 429) will never succeed — drop them rather than loop.\n markSent(ids);\n consecutiveFailures = 0;\n backoffUntil = 0;\n return;\n }\n // 5xx / 429 → retry with backoff.\n persistBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n };\n\n // Thenable, not instanceof: another realm's Promise failed it (N11-4).\n if (pending && typeof (pending as PromiseLike<unknown>).then === 'function') {\n pending.then(handleResponse).catch(() => {\n persistBucket(batch, maxRetrySize, RETRY_KEY);\n requeueFailed(batch);\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n });\n } else {\n handleResponse(pending as unknown as Response); // test stubs return a plain value\n }\n };\n\n // Pack events into a batch that stays under the keepalive byte budget AND the\n // configured event-count cap. Returns the prefix of `pool` that fits.\n // Uses UTF-8 byte length (not char count) — emoji/CJK payloads can be 3–4×\n // larger as bytes and would otherwise blow the keepalive budget.\n const encoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null;\n const byteLength = (s: string): number =>\n encoder ? encoder.encode(s).length : s.length;\n const packBatch = (pool: SentientEvent[]): SentientEvent[] => {\n const out: SentientEvent[] = [];\n let bytes = 2; // for the surrounding []\n for (const e of pool) {\n const size = byteLength(JSON.stringify(e)) + 1; // +1 for comma\n if (out.length > 0 && bytes + size > KEEPALIVE_BUDGET_BYTES) break;\n if (out.length >= maxBatchSize) break;\n out.push(e);\n bytes += size;\n }\n return out;\n };\n\n const flush = (): void => {\n try {\n if (Date.now() < backoffUntil) return;\n while (queue.length > 0) {\n // Re-check inside the loop: transportBatch can set backoffUntil\n // synchronously (a sync throw or a same-tick Response) and re-enqueue the\n // failed batch, so a mid-drain backoff must stop further chunks this tick\n // (otherwise the just-re-enqueued batch would immediately retry-loop).\n if (Date.now() < backoffUntil) break;\n const pending = queue.filter((e) => !sentIds.has(e.id));\n queue.length = 0;\n if (pending.length === 0) break;\n const batch = packBatch(pending);\n if (batch.length === 0) break;\n // Put anything we didn't pack back on the queue for the next tick.\n if (batch.length < pending.length) {\n queue.push(...pending.slice(batch.length));\n }\n transportBatch(batch);\n }\n } catch {\n /* never throw */\n }\n };\n\n let flushTimerActive = true;\n let intervalId: ReturnType<typeof setInterval> | null = null;\n\n intervalId = setInterval(() => {\n if (!flushTimerActive) return;\n flush();\n }, flushIntervalMs);\n\n const onVisibilityChange = (): void => {\n if (document.visibilityState === 'hidden') {\n flush();\n }\n };\n\n // `pagehide` (not `beforeunload`): a `beforeunload` listener can disqualify a\n // page from the back/forward cache. `pagehide` fires on real unloads AND on\n // bfcache eviction, and `visibilitychange:hidden` already covers most leaves,\n // so flush-on-leave stays covered without inhibiting bfcache.\n const onPageHide = (): void => {\n flush();\n };\n\n document.addEventListener('visibilitychange', onVisibilityChange);\n window.addEventListener('pagehide', onPageHide);\n\n return {\n push(event: SentientEvent): void {\n enqueue(event);\n if (queue.length >= maxBatchSize) {\n flush();\n }\n },\n flush,\n destroy(opts?: { forget?: boolean }): void {\n if (opts?.forget) forgotten = true;\n flushTimerActive = false;\n if (intervalId !== null) {\n clearInterval(intervalId);\n intervalId = null;\n }\n document.removeEventListener('visibilitychange', onVisibilityChange);\n window.removeEventListener('pagehide', onPageHide);\n flush();\n },\n };\n}\n","/**\n * Durable transport for `POST /v1/goals`.\n *\n * A conversion is the single most valuable event the SDK emits, and it used to\n * be the least reliable one: `goal()` fired a bare `fetch(...).catch(() => {})`,\n * which only observes network-layer failures. A 429 (the per-IP limit is 100\n * req/min, and shared egress — corporate NAT, carriers, storefront proxies —\n * hits it routinely), a 5xx, or a 400 all RESOLVE, so the catch never ran and\n * the response was discarded unread. The conversion was gone with no retry and\n * nothing surfaced to the developer.\n *\n * This gives goals the same guarantees the event queue has always had: retry\n * with backoff in-session, a localStorage bucket that survives reload, and\n * dedupe by id. Retry is safe because `goalId` is a client-generated UUID that\n * the server dedupes on (`ON CONFLICT DO NOTHING`) — the safety was already\n * there, it just wasn't used.\n *\n * Unlike events, `/v1/goals` takes ONE goal per request, so this is a serial\n * sender rather than a batcher, and a flush sends at most `maxPerFlush` so a\n * backlog drains at a pace the rate limiter tolerates instead of re-triggering\n * the 429 that created it.\n */\n\nimport { forgetGeneration } from './storage-key.js';\nimport { QUEUE_TIMEOUT_MS, timeoutSignal } from './timeout.js';\nimport { backoffDelayMs, classifyResponse, drainBucket, purgeBucket, writeBucket } from './durable.js';\n\n/** One queued conversion. `id` is the goalId — the server's dedupe key. */\nexport type PendingGoal = {\n id: string;\n /** Pre-serialized request body, so a persisted goal replays byte-identically. */\n body: string;\n};\n\nexport type GoalQueueConfig = {\n /** Absolute URL of the goals endpoint. */\n url: string;\n apiKey: string;\n headers: Record<string, string>;\n flushIntervalMs?: number;\n maxRetrySize?: number;\n maxPerFlush?: number;\n /** Called when a goal is permanently dropped (non-retryable status), so the\n * client can warn in debug mode. Never called for retryable failures. */\n onDrop?: (goal: PendingGoal, status: number) => void;\n};\n\nexport type GoalQueue = {\n /** Sends immediately; on a retryable failure the goal is queued and retried. */\n send(goal: PendingGoal): void;\n flush(): void;\n /** Stop the queue with a final flush. `forget`: the visitor asked to be\n * forgotten — a failed final delivery must NOT be persisted for retry\n * (it re-created the retry bucket after forget-me removed it). */\n destroy(opts?: { forget?: boolean }): void;\n};\n\nconst MAX_SENT_IDS = 200;\n\n/**\n * Persisted goal-retry bucket key, namespaced by apiKey prefix so multiple\n * projects on one origin keep separate buckets. Exported so the client's\n * forget-me teardown can remove it.\n */\nexport function goalRetryStorageKey(apiKey: string): string {\n return `_snt_goal_retry_${apiKey.slice(0, 12)}`;\n}\n\nconst SSR_GOAL_QUEUE: GoalQueue = {\n send: () => undefined,\n flush: () => undefined,\n destroy: () => undefined,\n};\n\nexport function createGoalQueue(config: GoalQueueConfig): GoalQueue {\n if (typeof window === 'undefined') return SSR_GOAL_QUEUE;\n\n const flushIntervalMs = config.flushIntervalMs ?? 5000;\n const maxRetrySize = config.maxRetrySize ?? 100;\n const maxPerFlush = config.maxPerFlush ?? 5;\n const RETRY_KEY = goalRetryStorageKey(config.apiKey);\n // Set by destroy({ forget: true }); see the type's doc.\n let forgotten = false;\n const createdGen = forgetGeneration(config.apiKey);\n const persistBucket: typeof writeBucket = (...a) => {\n if (!forgotten && forgetGeneration(config.apiKey) === createdGen) writeBucket(...a);\n };\n\n const pending: PendingGoal[] = [];\n const pendingIds = new Set<string>();\n const sentIds = new Set<string>();\n const sentIdOrder: string[] = [];\n\n let backoffUntil = 0;\n let consecutiveFailures = 0;\n let disposed = false;\n\n const markSent = (goal: PendingGoal): void => {\n pendingIds.delete(goal.id);\n if (!sentIds.has(goal.id)) {\n sentIds.add(goal.id);\n sentIdOrder.push(goal.id);\n }\n while (sentIdOrder.length > MAX_SENT_IDS) {\n const oldest = sentIdOrder.shift();\n if (oldest) sentIds.delete(oldest);\n }\n // Acknowledged (delivered, or dropped as unretryable) — clear it from the\n // cross-reload bucket so the next page load doesn't replay it.\n purgeBucket([goal.id], RETRY_KEY);\n };\n\n const markFailed = (goal: PendingGoal): void => {\n persistBucket([goal], maxRetrySize, RETRY_KEY);\n if (!sentIds.has(goal.id) && !pendingIds.has(goal.id)) {\n pendingIds.add(goal.id);\n pending.push(goal);\n }\n // One failed ROUND counts once, however many goals were in flight. flush()\n // launches up to maxPerFlush transports synchronously, so counting per goal\n // turned a single bad tick into consecutiveFailures=5 and a 32s backoff\n // where the first failure warrants 2s. queue.ts counts per batch; match it.\n if (Date.now() >= backoffUntil) {\n consecutiveFailures++;\n backoffUntil = Date.now() + backoffDelayMs(consecutiveFailures);\n }\n };\n\n const transport = (goal: PendingGoal): void => {\n let res: Promise<Response> | Response;\n const queueTimer = timeoutSignal(QUEUE_TIMEOUT_MS);\n try {\n // Bounded like the event queue: an abort retries, the goalId dedupes.\n res = fetch(config.url, {\n method: 'POST',\n keepalive: true,\n signal: queueTimer.signal,\n body: goal.body,\n headers: config.headers,\n });\n } catch {\n // Synchronous throw (jsdom in tests, or extreme browser failure).\n markFailed(goal);\n return;\n }\n\n const handle = (r: Response): void => {\n const outcome = classifyResponse(r);\n if (outcome === 'retry') {\n markFailed(goal);\n return;\n }\n // Terminal either way, but a drop is a wiring bug the developer can fix —\n // a 400 \"session not found\", a 401 from a misconfigured origin allowlist —\n // and used to be swallowed entirely. Say so instead of failing silently.\n if (outcome === 'dropped') config.onDrop?.(goal, r.status);\n markSent(goal);\n consecutiveFailures = 0;\n backoffUntil = 0;\n };\n\n Promise.resolve(res).then(queueTimer.clear, queueTimer.clear);\n // fetch can return a plain value under test stubs. Handle both.\n // A thenable check, not instanceof: a fetch wrapper returning another\n // realm's Promise was handled as a Response and retried (grader N11-4).\n if (res && typeof (res as PromiseLike<unknown>).then === 'function') (res as Promise<Response>).then(handle).catch(() => markFailed(goal));\n else handle(res as unknown as Response); // test stubs return a plain value\n };\n\n const flush = (): void => {\n try {\n if (disposed) return;\n if (Date.now() < backoffUntil) return;\n let sentThisTick = 0;\n while (pending.length > 0 && sentThisTick < maxPerFlush) {\n if (Date.now() < backoffUntil) break; // a same-tick failure re-armed backoff\n const goal = pending.shift()!;\n pendingIds.delete(goal.id);\n if (sentIds.has(goal.id)) continue;\n sentThisTick++;\n transport(goal);\n }\n } catch {\n /* never throw from a lifecycle handler */\n }\n };\n\n // Replay anything a previous page load failed to deliver. Left for the first\n // interval tick rather than sent now, so a page that reloads under an ongoing\n // outage doesn't stampede the endpoint during init.\n const restored = drainBucket<PendingGoal>(RETRY_KEY, maxRetrySize);\n for (const goal of restored) {\n if (!pendingIds.has(goal.id)) {\n pendingIds.add(goal.id);\n pending.push(goal);\n }\n }\n // drainBucket CLEARS storage as it reads, but only maxPerFlush goals leave per\n // tick — so a 40-goal backlog moved to memory and the visitor navigating two\n // seconds later lost the 35 that hadn't been sent yet. Put them straight back;\n // markSent purges each id individually once it is actually acknowledged.\n if (restored.length > 0) writeBucket(restored, maxRetrySize, RETRY_KEY);\n\n const intervalId = setInterval(flush, flushIntervalMs);\n const onVisibilityChange = (): void => {\n if (document.visibilityState === 'hidden') flush();\n };\n const onPageHide = (): void => flush();\n document.addEventListener('visibilitychange', onVisibilityChange);\n window.addEventListener('pagehide', onPageHide);\n\n return {\n send(goal: PendingGoal): void {\n if (disposed) {\n // A goal fired before a pause, still waiting on the first session\n // upsert, arrives after dispose(): banked for the next page's queue\n // instead of dropped unreported (grader R9-3, CONTRACTS §7). Never\n // after a forget — persistBucket checks that.\n if (!sentIds.has(goal.id)) persistBucket([goal], maxRetrySize, RETRY_KEY);\n return;\n }\n if (sentIds.has(goal.id) || pendingIds.has(goal.id)) return;\n // A conversion goes out now — it is often the last thing that happens\n // before a redirect to a thank-you page. Only a failure makes it queued.\n if (Date.now() < backoffUntil) {\n // Persist BEFORE parking it in memory. A goal only ever reached the\n // cross-reload bucket via markFailed — i.e. only after a failed attempt\n // — so a conversion queued during someone else's backoff lived in memory\n // alone, and flush() early-returns while backoff is armed, so pagehide\n // could not rescue it either. A purchase firing 300ms after a rate-limited\n // add_to_cart was lost on the checkout redirect: exactly the outage this\n // queue exists to survive.\n persistBucket([goal], maxRetrySize, RETRY_KEY);\n pendingIds.add(goal.id);\n pending.push(goal);\n return;\n }\n transport(goal);\n },\n flush,\n destroy(opts?: { forget?: boolean }): void {\n if (opts?.forget) forgotten = true;\n clearInterval(intervalId);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n window.removeEventListener('pagehide', onPageHide);\n flush();\n disposed = true;\n },\n };\n}\n","/**\n * Candidate domains for the shared visitor cookie. The visitor id lives on the\n * site's registrable domain (`example.com` for `app.example.com`), so a marketing\n * site and its app subdomain see ONE visitor: host-only cookies gave each host\n * its own id, and a journey that started on the landing page and converted in\n * the app (or the app's backend) could never be joined to the decisions that\n * earned it.\n *\n * Detection (session.ts `detectCookieDomain`) works the way analytics.js and\n * GA's `cookieDomain: 'auto'` do: try the shortest parent first and keep the\n * first one the browser accepts. The browser refuses public suffixes\n * (`co.uk`, `vercel.app`, `herokuapp.com`), so no suffix list ships in the\n * bundle — those fall through to the next candidate, and a host with no\n * acceptable parent stays host-only.\n */\n\n/** `false` = host-only (the pre-sharing behaviour); a string = that domain. */\nexport type CookieDomainOption = string | false | undefined;\n\n/**\n * Domains to try for `hostname`, shortest first, ENDING WITH THE HOST ITSELF.\n * The host is a candidate because the site's own bare domain is the common\n * case: a landing page on `example.com` must write `Domain=example.com` to share\n * with `app.example.com` — without it the bare domain stayed host-only while\n * its subdomains shared, so the landing-to-app journey was still two\n * visitors, and forget-me there left the shared copy behind.\n */\nexport function parentDomains(hostname: string | undefined): string[] {\n // `|| ''`: a stubbed or embedded `location` without a hostname must cost\n // the visitor cookie sharing, never crash init().\n const host = (hostname || '').toLowerCase();\n // localhost, a bare intranet name, an IP literal: nothing to share across.\n if (!host.includes('.') || /^[\\d.]+$|:/.test(host)) return [];\n const labels = host.split('.');\n const out: string[] = [];\n for (let i = labels.length - 2; i >= 0; i--) out.push(labels.slice(i).join('.'));\n return out;\n}\n","import { sessionCookieName, storageSuffix, LEGACY_SESSION_COOKIE_NAME, markForgotten } from './storage-key.js';\nimport { SNAPSHOT_STORAGE_KEY_PREFIX } from './snapshot.js';\nimport { retryStorageKey } from './queue.js';\nimport { goalRetryStorageKey } from './goal-queue.js';\nimport { parentDomains } from './cookie-domain.js';\n\n/**\n * Forget-me WITHOUT a client: delete everything the SDK stores for `apiKey`'s\n * visitor. `client.destroy()` does this for a live tracking client, which only\n * exists when consent was granted in this page view — so a visitor who said\n * \"no\" somewhere the SDK wasn't watching (a CMP settings page, checkout)\n * kept the 365-day id, the decision snapshot and the retry buckets for good,\n * and the pre-paint script kept personalizing from that snapshot (audit N2).\n * Callers run this when the consent source reports a refusal at boot.\n *\n * Writes nothing unless something was stored: the legacy tombstone (which\n * stops this project re-adopting the shared bare `_snt_uid`) is only written\n * when there is a bare id to block. Returns whether anything was removed.\n */\nexport function forgetVisitor(apiKey: string): boolean {\n if (typeof window === 'undefined' || !apiKey) return false;\n markForgotten(apiKey);\n let removed = false;\n const name = sessionCookieName(apiKey);\n try {\n if (new RegExp(`(?:^|; )${name}=`).test(document.cookie)) {\n const secure = location.protocol === 'https:' ? '; Secure' : '';\n // The visitor cookie may be shared on a parent domain (cookie-domain.ts),\n // and a host-only delete leaves that copy for every sibling host to\n // re-adopt. Which domain was configured is not known here, so every\n // parent is cleared — deleting a cookie that isn't there is a no-op.\n for (const d of ['', ...parentDomains(location.hostname)]) {\n document.cookie = `${name}=; max-age=0; SameSite=lax; path=/${d ? `; domain=${d}` : ''}${secure}`;\n }\n removed = true;\n }\n } catch {\n /* cookies unavailable */\n }\n const suffix = storageSuffix(apiKey);\n const exact = [\n name,\n // Written by builds before 2026; current SDKs only ever delete it.\n '_snt_graph_edges',\n SNAPSHOT_STORAGE_KEY_PREFIX + apiKey,\n retryStorageKey(apiKey),\n goalRetryStorageKey(apiKey),\n `_snt_graph_nodes${suffix}`,\n ];\n const prefixes = [`_snt_asgn${suffix}_`];\n for (const store of ['localStorage', 'sessionStorage'] as const) {\n try {\n const s = window[store];\n for (const k of exact) {\n if (s.getItem(k) !== null) {\n s.removeItem(k);\n removed = true;\n }\n }\n for (let i = s.length - 1; i >= 0; i--) {\n const k = s.key(i);\n if (k && prefixes.some((p) => k.startsWith(p))) {\n s.removeItem(k);\n removed = true;\n }\n }\n } catch {\n /* storage unavailable */\n }\n }\n try {\n // Every layer session.ts's legacy read adopts from, sessionStorage too.\n const bare =\n new RegExp(`(?:^|; )${LEGACY_SESSION_COOKIE_NAME}=[^;]`).test(document.cookie) ||\n localStorage.getItem(LEGACY_SESSION_COOKIE_NAME) !== null ||\n sessionStorage.getItem(LEGACY_SESSION_COOKIE_NAME) !== null;\n if (bare) localStorage.setItem(`${LEGACY_SESSION_COOKIE_NAME}_tomb${suffix}`, '1');\n } catch {\n /* storage unavailable */\n }\n return removed;\n}\n"],"mappings":"kxBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,0BAAAE,EAAA,uBAAAC,EAAA,uBAAAC,EAAA,mBAAAC,EAAA,0BAAAC,EAAA,0BAAAC,EAAA,kBAAAC,GAAA,yBAAAC,EAAA,qBAAAC,EAAA,qBAAAC,IAAA,eAAAC,GAAAZ,IC+CO,IAAMa,EAA0C,CAAC,EAAG,EAAG,EAAG,CAAC,EAgE5DC,EAAUC,GAAsB,CACpC,GAAI,CACF,OAAO,mBAAmBA,CAAC,CAC7B,OAAQC,EAAA,CACN,OAAOD,CACT,CACF,EAEA,SAASE,EAAUC,EAA2BC,EAAkC,CAC9E,GAAKD,EACL,QAAWE,KAAQF,EAAI,OAAO,MAAM,GAAG,EAAG,CACxC,IAAMG,EAAID,EAAK,QAAQ,GAAG,EAC1B,GAAIC,EAAI,GAAKD,EAAK,MAAM,EAAGC,CAAC,EAAE,KAAK,IAAMF,EAAM,OAAOC,EAAK,MAAMC,EAAI,CAAC,EAAE,KAAK,CAC/E,CAEF,CAGA,SAASC,EAAOC,EAAaC,EAAiBC,EAA4B,CACxE,IAAMC,EAAyB,CAACH,EAAK,GAAIA,EAAI,SAAW,CAACA,EAAI,QAAQ,EAAI,CAAC,CAAE,EAC5E,QAAWI,KAAKD,EAAS,QAAWE,KAAKJ,EAAOG,EAAE,iBAAiBC,EAAGH,CAAE,EACxE,MAAO,IAAM,CACX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,QAAWC,IAAK,CAAC,GAAI,GAAGC,GAAc,SAAS,QAAQ,CAAC,EACtD,SAAS,OAAS,GAAGJ,CAAI,qCAAqCG,EAAI,YAAYA,CAAC,GAAK,EAAE,GAAGD,CAAM,GAEjGH,EAAU,EACZ,CACF,OAAQM,EAAA,CAER,CACA,IAAMC,EAASC,EAAcV,CAAM,EAC7BW,EAAQ,CACZR,EAEA,mBACAS,GAA8BZ,EAC9Ba,GAAgBb,CAAM,EACtBc,GAAoBd,CAAM,EAC1B,mBAAmBS,CAAM,EAC3B,EACMM,EAAW,CAAC,YAAYN,CAAM,GAAG,EACvC,QAAWO,IAAS,CAAC,eAAgB,gBAAgB,EACnD,GAAI,CACF,IAAMC,EAAI,OAAOD,CAAK,EACtB,QAAWE,KAAKP,EACVM,EAAE,QAAQC,CAAC,IAAM,OACnBD,EAAE,WAAWC,CAAC,EACdhB,EAAU,IAGd,QAASiB,EAAIF,EAAE,OAAS,EAAGE,GAAK,EAAGA,IAAK,CACtC,IAAMD,EAAID,EAAE,IAAIE,CAAC,EACbD,GAAKH,EAAS,KAAMK,GAAMF,EAAE,WAAWE,CAAC,CAAC,IAC3CH,EAAE,WAAWC,CAAC,EACdhB,EAAU,GAEd,CACF,OAAQM,EAAA,CAER,CAEF,GAAI,EAGA,IAAI,OAAO,WAAWa,CAA0B,OAAO,EAAE,KAAK,SAAS,MAAM,GAC7E,aAAa,QAAQA,CAA0B,IAAM,MACrD,eAAe,QAAQA,CAA0B,IAAM,OAC/C,aAAa,QAAQ,GAAGA,CAA0B,QAAQZ,CAAM,GAAI,GAAG,CACnF,OAAQD,EAAA,CAER,CACA,OAAON,CACT","names":["index_consent_exports","__export","TCF_DEFAULT_PURPOSES","consentFromCookies","consentModeGranted","consentWatcher","cookiebotCookieGrants","cookieyesCookieGrants","forgetVisitor","onetrustCookieGrants","tcStringConsents","tcStringPurposes","__toCommonJS","TCF_DEFAULT_PURPOSES","decode","v","e","docCookie","doc","name","part","i","listen","win","names","cb","targets","t","n","cookiebotCookieGrants","raw","category","m","onetrustCookieGrants","group","groups","field","pair","g","on","cookieyesCookieGrants","B64URL","toBits","seg","bits","ch","tcStringConsents","tc","segments","core","int","at","len","purposes","legitimateInterests","p","vendors","max","isRange","out","ok","range","start","end","publisherPurposes","publisherLegitimateInterests","pb","tcStringPurposes","_a","_b","TCF_CONSENT_ONLY","tcfSatisfied","consent","li","vendor","normalize","input","_c","_d","_e","_f","_g","src","consentFromCookies","getCookie","c","__spreadProps","__spreadValues","emptyConsentModeState","foldConsentMode","state","item","type","args","params","region","codes","r","consentModeRefused","resolveConsentMode","exact","country","byCountry","consentModeGranted","dataLayer","consentWatcher","w","cookie","get","cats","answered","granted","bannerUp","storageRefused","listenerId","stopped","everDecided","onData","d","decided","tries","attach","api","seen","upTo","read","dl","wrappedArrays","unwrap","lastLen","original","wrapped","a","timer","u","method","fn","priv","stopListen","load","shop","err","storageSuffix","apiKey","LEGACY_SESSION_COOKIE_NAME","sessionCookieName","GENS","markForgotten","apiKey","_a","_b","w","m","GENS","e","SNAPSHOT_STORAGE_KEY_PREFIX","KEEPALIVE_BUDGET_BYTES","retryStorageKey","apiKey","goalRetryStorageKey","apiKey","parentDomains","hostname","host","labels","out","i","forgetVisitor","apiKey","markForgotten","removed","name","sessionCookieName","secure","d","parentDomains","e","suffix","storageSuffix","exact","SNAPSHOT_STORAGE_KEY_PREFIX","retryStorageKey","goalRetryStorageKey","prefixes","store","s","k","i","p","LEGACY_SESSION_COOKIE_NAME"]}
|
package/dist/index-consent.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as j}from"./chunk-FPOHOWJP.mjs";import"./chunk-J5EL7HKC.mjs";import{a as _,b as O}from"./chunk-TMCGHANO.mjs";var F=[1,5,6,8],P=r=>{try{return decodeURIComponent(r)}catch(n){return r}};function C(r,n){if(r)for(let e of r.cookie.split(";")){let t=e.indexOf("=");if(t>0&&e.slice(0,t).trim()===n)return e.slice(t+1).trim()}}function R(r,n,e){let t=[r,...r.document?[r.document]:[]];for(let s of t)for(let o of n)s.addEventListener(o,e);return()=>{for(let s of t)for(let o of n)s.removeEventListener(o,e)}}function E(r,n="statistics"){if(r==null||r==="")return null;let e=P(r).trim();if(e==="-1")return!0;if(e==="0")return!1;let t=new RegExp(`[{,]\\s*${n}\\s*:\\s*(true|false)`).exec(e);return t?t[1]==="true":null}function G(r,n="C0002"){if(r==null||r==="")return null;let e;for(let t of r.split("&"))t.startsWith("groups=")&&(e=P(t.slice(7)));if(e==null)return null;for(let t of e.split(",")){let[s,o]=t.split(":");if(s===n)return o==="1"}return null}function M(r,n="analytics"){if(r==null||r==="")return null;let e=new RegExp(`(?:^|,)${n}:(yes|no)(?:,|$)`).exec(P(r));return e?e[1]==="yes":null}var V="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",W=r=>{let n="";for(let e of r)n+=V.indexOf(e).toString(2).padStart(6,"0");return n};function U(r){if(!r)return null;let n=r.split("."),e=n[0];if(!/^[A-Za-z0-9_-]+$/.test(e))return null;let t=W(e);if(t.length<200||parseInt(t.slice(0,6),2)!==2)return null;let s=(a,p)=>a+p<=t.length?parseInt(t.slice(a,a+p),2):null,o=new Set,i=new Set;for(let a=1;a<=24;a++)t[151+a]==="1"&&o.add(a),t[175+a]==="1"&&i.add(a);let u=null,f=s(213,16),l=s(229,1);if(f!==null&&l===0){if(230+f<=t.length){u=new Set;for(let a=1;a<=f;a++)t[229+a]==="1"&&u.add(a)}}else if(f!==null&&l===1){let a=s(230,12),p=242,m=new Set,c=a!==null;for(let g=0;c&&g<(a!=null?a:0);g++){let S=s(p,1),b=s(p+1,16);if(S===null||b===null)c=!1;else if(S===1){let h=s(p+17,16);if(h===null||h<b||h-b>65535)c=!1;else for(let v=b;v<=h;v++)m.add(v);p+=33}else m.add(b),p+=17}c&&(u=m)}let d=new Set,y=new Set;for(let a of n.slice(1)){if(!/^[A-Za-z0-9_-]+$/.test(a))continue;let p=W(a);if(!(p.length<51||parseInt(p.slice(0,3),2)!==3))for(let m=1;m<=24;m++)p[2+m]==="1"&&d.add(m),p[26+m]==="1"&&y.add(m)}return{purposes:o,legitimateInterests:i,vendors:u,publisherPurposes:d,publisherLegitimateInterests:y,purposeOneTreatment:t[200]==="1"}}function B(r){var n,e;return(e=(n=U(r))==null?void 0:n.purposes)!=null?e:null}var Z=new Set([1,3,4,5,6]);function D(r,n,e,t){return r.purposes.every(o=>n(o)||!Z.has(o)&&e(o))?r.vendorId===void 0?!0:t(r.vendorId):!1}function $(r){var e,t,s,o,i,u,f;let n=typeof r=="string"?{cmp:r}:r;switch(n.cmp){case"cookiebot":return{cmp:"cookiebot",category:(e=n.category)!=null?e:"statistics"};case"onetrust":return{cmp:"onetrust",group:(t=n.group)!=null?t:"C0002"};case"cookieyes":return{cmp:"cookieyes",category:(s=n.category)!=null?s:"analytics"};case"tcf":return{cmp:"tcf",purposes:n.purposes&&n.purposes.length>0?n.purposes:F,vendorId:typeof n.vendorId=="number"&&n.vendorId>0?n.vendorId:void 0};case"google-consent-mode":return{cmp:"google-consent-mode",type:(o=n.type)!=null?o:"analytics_storage",dataLayer:(i=n.dataLayer)!=null?i:"dataLayer",region:typeof n.region=="string"&&n.region.trim()!==""?n.region.trim().toUpperCase():void 0};case"shopify":return{cmp:"shopify",category:(u=n.category)!=null?u:"analytics"};default:return{cmp:"custom",cookie:n.cookie,value:(f=n.value)!=null?f:"accepted",check:n.check,event:n.event,refused:n.refused}}}function Y(r,n){let e=$(r);switch(e.cmp){case"cookiebot":return E(n("CookieConsent"),e.category);case"onetrust":return G(n("OptanonConsent"),e.group);case"cookieyes":return M(n("cookieyes-consent"),e.category);case"tcf":{let t=U(n("euconsent-v2"));return t?D(t.purposeOneTreatment?O(_({},e),{purposes:e.purposes.filter(s=>s!==1)}):e,s=>t.purposes.has(s)||t.publisherPurposes.has(s),s=>t.legitimateInterests.has(s)||t.publisherLegitimateInterests.has(s),s=>t.vendors?t.vendors.has(s):null):null}case"google-consent-mode":return null;case"shopify":return null;case"custom":return!e.cookie||e.check?null:n(e.cookie)===e.value}}var L=()=>({update:null,global:null,regions:new Map});function z(r,n,e){let t=n&&typeof n=="object"&&"length"in n?Array.prototype.slice.call(n):null;if(!t||t[0]!=="consent"||t[1]!=="default"&&t[1]!=="update")return;let s=t[2],o=s==null?void 0:s[e],i=o==="granted"?!0:o==="denied"?!1:null;if(i===null)return;if(t[1]==="update"){r.update=i;return}let u=s==null?void 0:s.region,l=(Array.isArray(u)?u:typeof u=="string"?[u]:[]).filter(d=>typeof d=="string"&&d.trim()!=="").map(d=>d.trim().toUpperCase());if(l.length===0)r.global=i;else for(let d of l)r.regions.set(d,i)}function q(r){return r.update===!1}function N(r,n){if(r.update!==null)return r.update;if(n){let e=r.regions.get(n);if(e!==void 0)return e;let t=n.split("-")[0],s=r.regions.get(t);if(s!==void 0)return s;if(n===t){for(let[o,i]of r.regions)if(i===!1&&o.startsWith(`${t}-`))return!1}return r.global}for(let e of r.regions.values())if(e===!1)return!1;return r.global!==null?r.global:r.regions.size>0?!1:null}function H(r,n="analytics_storage",e){if(!Array.isArray(r))return null;let t=L();for(let s of r)z(t,s,n);return N(t,(e==null?void 0:e.trim().toUpperCase())||void 0)}function J(r,n=window){let e=$(r),t=n,s=n.document;switch(e.cmp){case"cookiebot":return{read:()=>{let o=t.Cookiebot,i=E(C(s,"CookieConsent"),e.category);return o!=null&&o.consent&&typeof o.consent[e.category]=="boolean"&&(o.hasResponse===!0||i===null)?o.consent[e.category]===!0:i},subscribe:o=>R(n,["CookiebotOnAccept","CookiebotOnDecline","CookiebotOnConsentReady","CookiebotOnLoad"],o),refused(){let o=t.Cookiebot;return((o==null?void 0:o.hasResponse)===!0||C(s,"CookieConsent")!==void 0)&&this.read()===!1}};case"onetrust":return{read:()=>{let o=t.OnetrustActiveGroups;return typeof o=="string"?`,${o},`.includes(`,${e.group},`):G(C(s,"OptanonConsent"),e.group)},subscribe:o=>R(n,["OneTrustGroupsUpdated"],o),refused(){return C(s,"OptanonAlertBoxClosed")!==void 0&&this.read()===!1}};case"cookieyes":return{read:()=>{var i;let o=t.getCkyConsent;if(typeof o=="function")try{let u=(i=o())==null?void 0:i.categories;if(u&&typeof u[e.category]=="boolean")return u[e.category]===!0}catch(u){}return M(C(s,"cookieyes-consent"),e.category)},subscribe:o=>R(n,["cookieyes_consent_update","cookieyes_banner_load","cookieyes_banner_loaded"],o),refused(){var u,f;let o=/(?:^|,)action:yes(?:,|$)/.test(P((u=C(s,"cookieyes-consent"))!=null?u:"")),i=t.getCkyConsent;if(!o&&typeof i=="function")try{o=((f=i())==null?void 0:f.isUserActionCompleted)===!0}catch(l){}return o&&this.read()===!1}};case"tcf":{let o=null,i=!1,u=!1;return{read:()=>o,refused:()=>o===!1&&!i&&u,subscribe:f=>{let l,d=!1,y=!1,a=(c,g)=>{var b,h,v,T;if(!g||d)return;typeof c.listenerId=="number"&&(l=c.listenerId),i=c.eventStatus==="cmpuishown",u=(c.eventStatus==="tcloaded"||c.eventStatus==="useractioncomplete")&&c.purposeOneTreatment!==!0&&c.gdprApplies!==!1&&((h=(b=c.purpose)==null?void 0:b.consents)==null?void 0:h[1])!==!0&&((T=(v=c.publisher)==null?void 0:v.consents)==null?void 0:T[1])!==!0;let S=c.eventStatus==="tcloaded"||c.eventStatus==="useractioncomplete";S&&(y=!0),i?o=!1:!S&&c.gdprApplies!==!1?y||(o=null):o=c.gdprApplies===!1||D(c.purposeOneTreatment===!0?O(_({},e),{purposes:e.purposes.filter(k=>k!==1)}):e,k=>{var w,A,I,x;return((A=(w=c.purpose)==null?void 0:w.consents)==null?void 0:A[k])===!0||((x=(I=c.publisher)==null?void 0:I.consents)==null?void 0:x[k])===!0},k=>{var w,A,I,x;return((A=(w=c.purpose)==null?void 0:w.legitimateInterests)==null?void 0:A[k])===!0||((x=(I=c.publisher)==null?void 0:I.legitimateInterests)==null?void 0:x[k])===!0},k=>{var w,A;return((A=(w=c.vendor)==null?void 0:w.consents)==null?void 0:A[k])===!0})===!0,f()},p=0,m=()=>{if(d)return;let c=t.__tcfapi;typeof c=="function"?c("addEventListener",2,a):p++<40&&window.setTimeout(m,250)};return m(),()=>{d=!0;let c=t.__tcfapi;typeof c=="function"&&l!==void 0&&c("removeEventListener",2,()=>{},l)}}}}case"google-consent-mode":{let o=null,i=0,u=L(),f=()=>{let l=t[e.dataLayer];if(!Array.isArray(l))return null;for((l!==o||l.length<i)&&(o=l,i=0,u=L());i<l.length;i++)z(u,l[i],e.type);return N(u,e.region)};return{read:f,refused:()=>f()===!1&&q(u),subscribe:l=>{let d=new WeakSet,y=!1,a=[],p=-1,m=()=>{var S,b;let g=(b=t[S=e.dataLayer])!=null?b:t[S]=[];if(!d.has(g)){d.add(g);let h=g.push,v=function(...T){let k=h.apply(g,T);return p=g.length,y||l(),k};g.push=v,a.push(()=>{g.push===v&&(g.push=h)})}g.length!==p&&(p=g.length,l())};m();let c=window.setInterval(m,1e3);return()=>{y=!0,window.clearInterval(c);for(let g of a)g()}}}}case"shopify":{let o=e.category==="marketing"?"marketingAllowed":e.category==="preferences"?"preferencesProcessingAllowed":"analyticsProcessingAllowed";return{read:()=>{var u,f;let i=(f=(u=t.Shopify)==null?void 0:u.customerPrivacy)==null?void 0:f[o];if(typeof i!="function")return null;try{let l=i();return typeof l=="boolean"?l:null}catch(l){return null}},refused(){var u,f;let i=(u=t.Shopify)==null?void 0:u.customerPrivacy;if(typeof(i==null?void 0:i.currentVisitorConsent)!="function")return!1;try{return((f=i.currentVisitorConsent())==null?void 0:f[e.category])==="no"}catch(l){return!1}},subscribe:i=>{let u=R(n,["visitorConsentCollected"],i),f=!1,l=0,d=()=>{if(f)return;let y=t.Shopify;if(y!=null&&y.customerPrivacy){i();return}if(typeof(y==null?void 0:y.loadFeatures)=="function"){try{y.loadFeatures([{name:"consent-tracking-api",version:"0.1"}],a=>{!f&&!a&&i()})}catch(a){}return}l++<40&&window.setTimeout(d,250)};return d(),()=>{f=!0,u()}}}}case"custom":return{read:()=>{if(e.check)try{return e.check()===!0}catch(i){return!1}if(!e.cookie)return null;let o=C(s,e.cookie);return o===void 0?null:o===e.value},refused:()=>{var o;if(e.check)try{return((o=e.refused)==null?void 0:o.call(e))===!0}catch(i){return!1}return!!e.cookie&&C(s,e.cookie)!==void 0&&C(s,e.cookie)!==e.value},subscribe:o=>e.event?R(n,[e.event],o):()=>{}}}}export{F as TCF_DEFAULT_PURPOSES,Y as consentFromCookies,H as consentModeGranted,J as consentWatcher,E as cookiebotCookieGrants,M as cookieyesCookieGrants,j as forgetVisitor,G as onetrustCookieGrants,U as tcStringConsents,B as tcStringPurposes};
|
|
1
|
+
import{m as j}from"./chunk-JNQY3XNF.mjs";import"./chunk-BGZLWZUG.mjs";import"./chunk-WUFFNQHQ.mjs";import{a as _,b as O}from"./chunk-TMCGHANO.mjs";var F=[1,5,6,8],P=r=>{try{return decodeURIComponent(r)}catch(n){return r}};function C(r,n){if(r)for(let e of r.cookie.split(";")){let t=e.indexOf("=");if(t>0&&e.slice(0,t).trim()===n)return e.slice(t+1).trim()}}function R(r,n,e){let t=[r,...r.document?[r.document]:[]];for(let s of t)for(let o of n)s.addEventListener(o,e);return()=>{for(let s of t)for(let o of n)s.removeEventListener(o,e)}}function E(r,n="statistics"){if(r==null||r==="")return null;let e=P(r).trim();if(e==="-1")return!0;if(e==="0")return!1;let t=new RegExp(`[{,]\\s*${n}\\s*:\\s*(true|false)`).exec(e);return t?t[1]==="true":null}function G(r,n="C0002"){if(r==null||r==="")return null;let e;for(let t of r.split("&"))t.startsWith("groups=")&&(e=P(t.slice(7)));if(e==null)return null;for(let t of e.split(",")){let[s,o]=t.split(":");if(s===n)return o==="1"}return null}function M(r,n="analytics"){if(r==null||r==="")return null;let e=new RegExp(`(?:^|,)${n}:(yes|no)(?:,|$)`).exec(P(r));return e?e[1]==="yes":null}var V="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",W=r=>{let n="";for(let e of r)n+=V.indexOf(e).toString(2).padStart(6,"0");return n};function U(r){if(!r)return null;let n=r.split("."),e=n[0];if(!/^[A-Za-z0-9_-]+$/.test(e))return null;let t=W(e);if(t.length<200||parseInt(t.slice(0,6),2)!==2)return null;let s=(a,p)=>a+p<=t.length?parseInt(t.slice(a,a+p),2):null,o=new Set,i=new Set;for(let a=1;a<=24;a++)t[151+a]==="1"&&o.add(a),t[175+a]==="1"&&i.add(a);let u=null,f=s(213,16),l=s(229,1);if(f!==null&&l===0){if(230+f<=t.length){u=new Set;for(let a=1;a<=f;a++)t[229+a]==="1"&&u.add(a)}}else if(f!==null&&l===1){let a=s(230,12),p=242,m=new Set,c=a!==null;for(let g=0;c&&g<(a!=null?a:0);g++){let S=s(p,1),b=s(p+1,16);if(S===null||b===null)c=!1;else if(S===1){let h=s(p+17,16);if(h===null||h<b||h-b>65535)c=!1;else for(let v=b;v<=h;v++)m.add(v);p+=33}else m.add(b),p+=17}c&&(u=m)}let d=new Set,y=new Set;for(let a of n.slice(1)){if(!/^[A-Za-z0-9_-]+$/.test(a))continue;let p=W(a);if(!(p.length<51||parseInt(p.slice(0,3),2)!==3))for(let m=1;m<=24;m++)p[2+m]==="1"&&d.add(m),p[26+m]==="1"&&y.add(m)}return{purposes:o,legitimateInterests:i,vendors:u,publisherPurposes:d,publisherLegitimateInterests:y,purposeOneTreatment:t[200]==="1"}}function B(r){var n,e;return(e=(n=U(r))==null?void 0:n.purposes)!=null?e:null}var Z=new Set([1,3,4,5,6]);function D(r,n,e,t){return r.purposes.every(o=>n(o)||!Z.has(o)&&e(o))?r.vendorId===void 0?!0:t(r.vendorId):!1}function $(r){var e,t,s,o,i,u,f;let n=typeof r=="string"?{cmp:r}:r;switch(n.cmp){case"cookiebot":return{cmp:"cookiebot",category:(e=n.category)!=null?e:"statistics"};case"onetrust":return{cmp:"onetrust",group:(t=n.group)!=null?t:"C0002"};case"cookieyes":return{cmp:"cookieyes",category:(s=n.category)!=null?s:"analytics"};case"tcf":return{cmp:"tcf",purposes:n.purposes&&n.purposes.length>0?n.purposes:F,vendorId:typeof n.vendorId=="number"&&n.vendorId>0?n.vendorId:void 0};case"google-consent-mode":return{cmp:"google-consent-mode",type:(o=n.type)!=null?o:"analytics_storage",dataLayer:(i=n.dataLayer)!=null?i:"dataLayer",region:typeof n.region=="string"&&n.region.trim()!==""?n.region.trim().toUpperCase():void 0};case"shopify":return{cmp:"shopify",category:(u=n.category)!=null?u:"analytics"};default:return{cmp:"custom",cookie:n.cookie,value:(f=n.value)!=null?f:"accepted",check:n.check,event:n.event,refused:n.refused}}}function Y(r,n){let e=$(r);switch(e.cmp){case"cookiebot":return E(n("CookieConsent"),e.category);case"onetrust":return G(n("OptanonConsent"),e.group);case"cookieyes":return M(n("cookieyes-consent"),e.category);case"tcf":{let t=U(n("euconsent-v2"));return t?D(t.purposeOneTreatment?O(_({},e),{purposes:e.purposes.filter(s=>s!==1)}):e,s=>t.purposes.has(s)||t.publisherPurposes.has(s),s=>t.legitimateInterests.has(s)||t.publisherLegitimateInterests.has(s),s=>t.vendors?t.vendors.has(s):null):null}case"google-consent-mode":return null;case"shopify":return null;case"custom":return!e.cookie||e.check?null:n(e.cookie)===e.value}}var L=()=>({update:null,global:null,regions:new Map});function z(r,n,e){let t=n&&typeof n=="object"&&"length"in n?Array.prototype.slice.call(n):null;if(!t||t[0]!=="consent"||t[1]!=="default"&&t[1]!=="update")return;let s=t[2],o=s==null?void 0:s[e],i=o==="granted"?!0:o==="denied"?!1:null;if(i===null)return;if(t[1]==="update"){r.update=i;return}let u=s==null?void 0:s.region,l=(Array.isArray(u)?u:typeof u=="string"?[u]:[]).filter(d=>typeof d=="string"&&d.trim()!=="").map(d=>d.trim().toUpperCase());if(l.length===0)r.global=i;else for(let d of l)r.regions.set(d,i)}function q(r){return r.update===!1}function N(r,n){if(r.update!==null)return r.update;if(n){let e=r.regions.get(n);if(e!==void 0)return e;let t=n.split("-")[0],s=r.regions.get(t);if(s!==void 0)return s;if(n===t){for(let[o,i]of r.regions)if(i===!1&&o.startsWith(`${t}-`))return!1}return r.global}for(let e of r.regions.values())if(e===!1)return!1;return r.global!==null?r.global:r.regions.size>0?!1:null}function H(r,n="analytics_storage",e){if(!Array.isArray(r))return null;let t=L();for(let s of r)z(t,s,n);return N(t,(e==null?void 0:e.trim().toUpperCase())||void 0)}function J(r,n=window){let e=$(r),t=n,s=n.document;switch(e.cmp){case"cookiebot":return{read:()=>{let o=t.Cookiebot,i=E(C(s,"CookieConsent"),e.category);return o!=null&&o.consent&&typeof o.consent[e.category]=="boolean"&&(o.hasResponse===!0||i===null)?o.consent[e.category]===!0:i},subscribe:o=>R(n,["CookiebotOnAccept","CookiebotOnDecline","CookiebotOnConsentReady","CookiebotOnLoad"],o),refused(){let o=t.Cookiebot;return((o==null?void 0:o.hasResponse)===!0||C(s,"CookieConsent")!==void 0)&&this.read()===!1}};case"onetrust":return{read:()=>{let o=t.OnetrustActiveGroups;return typeof o=="string"?`,${o},`.includes(`,${e.group},`):G(C(s,"OptanonConsent"),e.group)},subscribe:o=>R(n,["OneTrustGroupsUpdated"],o),refused(){return C(s,"OptanonAlertBoxClosed")!==void 0&&this.read()===!1}};case"cookieyes":return{read:()=>{var i;let o=t.getCkyConsent;if(typeof o=="function")try{let u=(i=o())==null?void 0:i.categories;if(u&&typeof u[e.category]=="boolean")return u[e.category]===!0}catch(u){}return M(C(s,"cookieyes-consent"),e.category)},subscribe:o=>R(n,["cookieyes_consent_update","cookieyes_banner_load","cookieyes_banner_loaded"],o),refused(){var u,f;let o=/(?:^|,)action:yes(?:,|$)/.test(P((u=C(s,"cookieyes-consent"))!=null?u:"")),i=t.getCkyConsent;if(!o&&typeof i=="function")try{o=((f=i())==null?void 0:f.isUserActionCompleted)===!0}catch(l){}return o&&this.read()===!1}};case"tcf":{let o=null,i=!1,u=!1;return{read:()=>o,refused:()=>o===!1&&!i&&u,subscribe:f=>{let l,d=!1,y=!1,a=(c,g)=>{var b,h,v,T;if(!g||d)return;typeof c.listenerId=="number"&&(l=c.listenerId),i=c.eventStatus==="cmpuishown",u=(c.eventStatus==="tcloaded"||c.eventStatus==="useractioncomplete")&&c.purposeOneTreatment!==!0&&c.gdprApplies!==!1&&((h=(b=c.purpose)==null?void 0:b.consents)==null?void 0:h[1])!==!0&&((T=(v=c.publisher)==null?void 0:v.consents)==null?void 0:T[1])!==!0;let S=c.eventStatus==="tcloaded"||c.eventStatus==="useractioncomplete";S&&(y=!0),i?o=!1:!S&&c.gdprApplies!==!1?y||(o=null):o=c.gdprApplies===!1||D(c.purposeOneTreatment===!0?O(_({},e),{purposes:e.purposes.filter(k=>k!==1)}):e,k=>{var w,A,I,x;return((A=(w=c.purpose)==null?void 0:w.consents)==null?void 0:A[k])===!0||((x=(I=c.publisher)==null?void 0:I.consents)==null?void 0:x[k])===!0},k=>{var w,A,I,x;return((A=(w=c.purpose)==null?void 0:w.legitimateInterests)==null?void 0:A[k])===!0||((x=(I=c.publisher)==null?void 0:I.legitimateInterests)==null?void 0:x[k])===!0},k=>{var w,A;return((A=(w=c.vendor)==null?void 0:w.consents)==null?void 0:A[k])===!0})===!0,f()},p=0,m=()=>{if(d)return;let c=t.__tcfapi;typeof c=="function"?c("addEventListener",2,a):p++<40&&window.setTimeout(m,250)};return m(),()=>{d=!0;let c=t.__tcfapi;typeof c=="function"&&l!==void 0&&c("removeEventListener",2,()=>{},l)}}}}case"google-consent-mode":{let o=null,i=0,u=L(),f=()=>{let l=t[e.dataLayer];if(!Array.isArray(l))return null;for((l!==o||l.length<i)&&(o=l,i=0,u=L());i<l.length;i++)z(u,l[i],e.type);return N(u,e.region)};return{read:f,refused:()=>f()===!1&&q(u),subscribe:l=>{let d=new WeakSet,y=!1,a=[],p=-1,m=()=>{var S,b;let g=(b=t[S=e.dataLayer])!=null?b:t[S]=[];if(!d.has(g)){d.add(g);let h=g.push,v=function(...T){let k=h.apply(g,T);return p=g.length,y||l(),k};g.push=v,a.push(()=>{g.push===v&&(g.push=h)})}g.length!==p&&(p=g.length,l())};m();let c=window.setInterval(m,1e3);return()=>{y=!0,window.clearInterval(c);for(let g of a)g()}}}}case"shopify":{let o=e.category==="marketing"?"marketingAllowed":e.category==="preferences"?"preferencesProcessingAllowed":"analyticsProcessingAllowed";return{read:()=>{var u,f;let i=(f=(u=t.Shopify)==null?void 0:u.customerPrivacy)==null?void 0:f[o];if(typeof i!="function")return null;try{let l=i();return typeof l=="boolean"?l:null}catch(l){return null}},refused(){var u,f;let i=(u=t.Shopify)==null?void 0:u.customerPrivacy;if(typeof(i==null?void 0:i.currentVisitorConsent)!="function")return!1;try{return((f=i.currentVisitorConsent())==null?void 0:f[e.category])==="no"}catch(l){return!1}},subscribe:i=>{let u=R(n,["visitorConsentCollected"],i),f=!1,l=0,d=()=>{if(f)return;let y=t.Shopify;if(y!=null&&y.customerPrivacy){i();return}if(typeof(y==null?void 0:y.loadFeatures)=="function"){try{y.loadFeatures([{name:"consent-tracking-api",version:"0.1"}],a=>{!f&&!a&&i()})}catch(a){}return}l++<40&&window.setTimeout(d,250)};return d(),()=>{f=!0,u()}}}}case"custom":return{read:()=>{if(e.check)try{return e.check()===!0}catch(i){return!1}if(!e.cookie)return null;let o=C(s,e.cookie);return o===void 0?null:o===e.value},refused:()=>{var o;if(e.check)try{return((o=e.refused)==null?void 0:o.call(e))===!0}catch(i){return!1}return!!e.cookie&&C(s,e.cookie)!==void 0&&C(s,e.cookie)!==e.value},subscribe:o=>e.event?R(n,[e.event],o):()=>{}}}}export{F as TCF_DEFAULT_PURPOSES,Y as consentFromCookies,H as consentModeGranted,J as consentWatcher,E as cookiebotCookieGrants,M as cookieyesCookieGrants,j as forgetVisitor,G as onetrustCookieGrants,U as tcStringConsents,B as tcStringPurposes};
|
|
2
2
|
//# sourceMappingURL=index-consent.mjs.map
|