@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.
Files changed (54) hide show
  1. package/README.md +32 -3
  2. package/dist/chunk-5VIREVXA.mjs +2 -0
  3. package/dist/chunk-5VIREVXA.mjs.map +1 -0
  4. package/dist/chunk-BGZLWZUG.mjs +2 -0
  5. package/dist/chunk-BGZLWZUG.mjs.map +1 -0
  6. package/dist/chunk-JNQY3XNF.mjs +2 -0
  7. package/dist/chunk-JNQY3XNF.mjs.map +1 -0
  8. package/dist/chunk-LCYGZNFI.mjs +2 -0
  9. package/dist/chunk-LCYGZNFI.mjs.map +1 -0
  10. package/dist/chunk-WUFFNQHQ.mjs +2 -0
  11. package/dist/{chunk-J5EL7HKC.mjs.map → chunk-WUFFNQHQ.mjs.map} +1 -1
  12. package/dist/{index-DlJDNOWu.d.cts → index-CWHTKETi.d.cts} +34 -5
  13. package/dist/index-consent.js +1 -1
  14. package/dist/index-consent.js.map +1 -1
  15. package/dist/index-consent.mjs +1 -1
  16. package/dist/index-consent.mjs.map +1 -1
  17. package/dist/{index-C--aVpoo.d.ts → index-cqfRT6LZ.d.ts} +34 -5
  18. package/dist/index-engagement.js +1 -1
  19. package/dist/index-engagement.js.map +1 -1
  20. package/dist/index-engagement.mjs +1 -1
  21. package/dist/index-engagement.mjs.map +1 -1
  22. package/dist/index-graph.d.cts +2 -2
  23. package/dist/index-graph.d.ts +2 -2
  24. package/dist/index-graph.js +1 -1
  25. package/dist/index-graph.js.map +1 -1
  26. package/dist/index-graph.mjs +1 -1
  27. package/dist/index-graph.mjs.map +1 -1
  28. package/dist/index-internal-traffic.d.cts +37 -0
  29. package/dist/index-internal-traffic.d.ts +37 -0
  30. package/dist/index-internal-traffic.js +2 -0
  31. package/dist/index-internal-traffic.js.map +1 -0
  32. package/dist/index-internal-traffic.mjs +2 -0
  33. package/dist/index-internal-traffic.mjs.map +1 -0
  34. package/dist/index-local.d.cts +1 -1
  35. package/dist/index-local.d.ts +1 -1
  36. package/dist/index-region.mjs +1 -1
  37. package/dist/index-server.d.cts +25 -1
  38. package/dist/index-server.d.ts +25 -1
  39. package/dist/index-server.js +1 -1
  40. package/dist/index-server.js.map +1 -1
  41. package/dist/index-server.mjs +1 -1
  42. package/dist/index-server.mjs.map +1 -1
  43. package/dist/index.d.cts +1 -1
  44. package/dist/index.d.ts +1 -1
  45. package/dist/index.js +1 -1
  46. package/dist/index.js.map +1 -1
  47. package/dist/index.mjs +1 -1
  48. package/llms.txt +2 -1
  49. package/package.json +7 -2
  50. package/dist/chunk-FPOHOWJP.mjs +0 -2
  51. package/dist/chunk-FPOHOWJP.mjs.map +0 -1
  52. package/dist/chunk-J5EL7HKC.mjs +0 -2
  53. package/dist/chunk-KXA3X6T3.mjs +0 -2
  54. package/dist/chunk-KXA3X6T3.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/snapshot.ts","../src/timeout.ts","../src/durable.ts","../src/queue.ts","../src/goal-queue.ts","../src/forget.ts"],"sourcesContent":["/**\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","// Browser request ceilings (audit S8). No browser fetch had a timeout, so a\n// stalled connection — captive portal, dropped mobile radio, an overloaded\n// edge — held a decide or an assign open indefinitely while the page sat on\n// its baseline, and a hung ingest POST wedged a queue's in-flight slot.\n\n/** Read-only calls (winner, weights) and each session upsert. */\nexport const REQUEST_TIMEOUT_MS = 5000;\n/** A SENT decide or assign. The server records them whether or not we read\n * the answer (decide's slot_decisions rows are trials; assign logs the\n * exposure at draw time) — so neither is ever cut short on latency (a slow answer is still applied late, which is\n * what makes the trial real). This ceiling only frees a dead connection. */\nexport const DECIDE_TIMEOUT_MS = 30000;\n/** Durable queue POSTs. Retried on abort, and deduplicated server-side by\n * event id / goal id, so a timeout never double-counts. */\nexport const QUEUE_TIMEOUT_MS = 15000;\n/** How long decide/assign wait for the session upsert before giving up\n * WITHOUT sending: the session retry chain can run ~14 s under 429s, and a\n * decision that is never requested writes no trial (a late decide would —\n * close-out books every slot_decisions row, CONTRACTS §2 \"Which decisions\n * exist\"). The page keeps its baseline; the next page view decides. */\nexport const SESSION_WAIT_MS = 2500;\n\n/** An AbortSignal that fires after `ms`, and a `clear` for when the request\n * settles. No-op where AbortController is missing (the signal is optional). */\nexport function timeoutSignal(ms: number): { signal?: AbortSignal; clear: () => void } {\n if (typeof AbortController !== 'function') return { clear: () => undefined };\n const ctl = new AbortController();\n const t = setTimeout(() => ctl.abort(), ms);\n return { signal: ctl.signal, clear: () => clearTimeout(t) };\n}\n\n/** Resolves true when `p` settles within `ms`, false otherwise. */\nexport function settlesWithin(p: Promise<unknown>, ms: number): Promise<boolean> {\n return new Promise((resolve) => {\n const t = setTimeout(() => resolve(false), ms);\n const done = (): void => {\n clearTimeout(t);\n resolve(true);\n };\n p.then(done, done);\n });\n}\n","/**\n * Reliability primitives shared by every outbound SDK transport.\n *\n * Extracted from queue.ts so the goal sender cannot drift from the event\n * queue on the three decisions that decide whether data survives: which\n * responses are worth retrying, how long to wait, and how the cross-reload\n * bucket is read and written. Behaviour is byte-identical to the versions\n * these replace.\n */\n\nconst MAX_BACKOFF_MS = 60_000;\n/** 2^6 s = 64 s, already past MAX_BACKOFF_MS — the cap that stops the shift overflowing. */\nconst BACKOFF_EXPONENT_CAP = 6;\n\n/** Delay before the next attempt after `consecutiveFailures` failed ones (1-based). */\nexport function backoffDelayMs(consecutiveFailures: number): number {\n return Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.min(consecutiveFailures, BACKOFF_EXPONENT_CAP));\n}\n\n/** What one delivery attempt achieved. `dropped` is terminal but unsuccessful. */\nexport type DeliveryOutcome = 'delivered' | 'dropped' | 'retry';\n\n/**\n * Classifies a response into the three outcomes that matter to a transport.\n *\n * 2xx delivered. A 4xx other than 429 will never succeed however many times we\n * try it (bad key, rejected body, unknown session), so retrying it loops\n * forever and starves real data out of the bucket — drop it, but distinctly,\n * so callers can tell the developer. 429 and 5xx are transient.\n *\n * `ok` is consulted before `status` deliberately: it is the semantic check, and\n * it keeps stubs that set only `ok` (used throughout the SDK test suite)\n * behaving as they did before this was extracted. An unrecognizable response\n * with neither is treated as retryable, matching the original queue.\n */\nexport function classifyResponse(res: { ok?: boolean; status?: number }): DeliveryOutcome {\n if (res.ok === true) return 'delivered';\n const { status } = res;\n if (typeof status !== 'number') return 'retry';\n if (status >= 200 && status < 300) return 'delivered';\n if (status >= 400 && status < 500 && status !== 429) return 'dropped';\n return 'retry';\n}\n\n/** Anything a persisted bucket can hold: it needs a stable server-side dedupe id. */\nexport type Identified = { id: string };\n\n/**\n * Reads a persisted bucket AND clears it — the caller takes ownership of the\n * items and is responsible for re-persisting any that fail again. Returns the\n * newest `max` entries; a corrupt or absent bucket reads as empty.\n */\nexport function drainBucket<T extends Identified>(storageKey: string, max: number): T[] {\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return [];\n const parsed = JSON.parse(raw) as T[];\n if (!Array.isArray(parsed)) return [];\n localStorage.removeItem(storageKey);\n return parsed.slice(-max);\n } catch {\n return [];\n }\n}\n\n/**\n * Merges `items` into the persisted bucket, de-duped by id (last write wins)\n * before the size cap. The dedupe matters: a batch that 5xx's repeatedly\n * in-session hands the same ids back on every retry, and without it each retry\n * appends another copy and `slice(-max)` evicts other distinct failed items to\n * make room for the duplicates.\n */\nexport function writeBucket<T extends Identified>(items: T[], max: number, storageKey: string): void {\n try {\n const existing = (() => {\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return [] as T[];\n const parsed = JSON.parse(raw) as T[];\n return Array.isArray(parsed) ? parsed : ([] as T[]);\n } catch {\n return [] as T[];\n }\n })();\n const byId = new Map<string, T>();\n for (const e of existing) byId.set(e.id, e);\n for (const e of items) byId.set(e.id, e);\n localStorage.setItem(storageKey, JSON.stringify([...byId.values()].slice(-max)));\n } catch {\n /* storage unavailable — the in-memory retry path still applies */\n }\n}\n\n/**\n * Removes the given ids from the persisted bucket. Called once an item is\n * acknowledged so a transient failure that was written to localStorage isn't\n * replayed on the next page load after the in-session retry succeeded.\n */\nexport function purgeBucket(ids: string[], storageKey: string): void {\n try {\n const raw = localStorage.getItem(storageKey);\n if (!raw) return;\n const parsed = JSON.parse(raw) as Identified[];\n if (!Array.isArray(parsed)) return;\n const drop = new Set(ids);\n const remaining = parsed.filter((e) => !drop.has(e.id));\n if (remaining.length === parsed.length) return; // nothing to remove\n if (remaining.length === 0) localStorage.removeItem(storageKey);\n else localStorage.setItem(storageKey, JSON.stringify(remaining));\n } catch {\n /* ignore */\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","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":"kHASO,IAAMA,EAA8B,aAoF3C,IAAMC,GAAQ,CAAC,MAAO,SAAU,MAAM,EAG/B,SAASC,GAAaC,EAAyC,CACpE,GAAI,CACF,IAAMC,EAAM,aAAa,QAAQC,EAA8BF,CAAM,EACrE,GAAI,CAACC,EAAK,OAAO,KACjB,IAAME,EAAI,KAAK,MAAMF,CAAG,EACxB,GACE,CAACE,GACD,OAAOA,GAAM,UACbA,EAAE,IAAM,GACR,OAAOA,EAAE,SAAY,UACrB,OAAOA,EAAE,MAAS,UACl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T","names":["SNAPSHOT_STORAGE_KEY_PREFIX","BANDS","readSnapshot","apiKey","raw","SNAPSHOT_STORAGE_KEY_PREFIX","p","v","e","writeSnapshot","snap","renderPrePaintScript","opts","timeoutSignal","ms","ctl","t","settlesWithin","p","resolve","done","backoffDelayMs","consecutiveFailures","classifyResponse","res","status","drainBucket","storageKey","max","raw","parsed","writeBucket","items","existing","e","byId","purgeBucket","ids","drop","remaining","MAX_SENT_IDS","KEEPALIVE_BUDGET_BYTES","retryStorageKey","apiKey","SSR_QUEUE","createEventQueue","config","_a","_b","_c","flushIntervalMs","maxBatchSize","maxRetrySize","ingestUrl","RETRY_KEY","forgotten","createdGen","forgetGeneration","persistBucket","a","writeBucket","queue","sentIds","sentIdOrder","markSent","ids","id","queuedIds","oldest","purgeBucket","capQueue","dropped","enqueue","event","requeueFailed","batch","retryEvents","drainBucket","backoffUntil","consecutiveFailures","transportBatch","salvage","body","e","pending","queueTimer","timeoutSignal","backoffDelayMs","handleResponse","res","classifyResponse","rest","encoder","byteLength","s","packBatch","pool","out","bytes","size","flush","flushTimerActive","intervalId","onVisibilityChange","onPageHide","opts","MAX_SENT_IDS","goalRetryStorageKey","apiKey","SSR_GOAL_QUEUE","createGoalQueue","config","_a","_b","_c","flushIntervalMs","maxRetrySize","maxPerFlush","RETRY_KEY","forgotten","createdGen","forgetGeneration","persistBucket","a","writeBucket","pending","pendingIds","sentIds","sentIdOrder","backoffUntil","consecutiveFailures","disposed","markSent","goal","oldest","purgeBucket","markFailed","backoffDelayMs","transport","res","queueTimer","timeoutSignal","e","handle","r","outcome","classifyResponse","flush","sentThisTick","restored","drainBucket","intervalId","onVisibilityChange","onPageHide","opts","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"]}
@@ -0,0 +1,2 @@
1
+ import{a as O}from"./chunk-BGZLWZUG.mjs";import{a as T,c as E}from"./chunk-WUFFNQHQ.mjs";function b(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let t=new Uint8Array(16);crypto.getRandomValues(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e="";for(let n=0;n<16;n++)e+=t[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(e+="-");return e}}catch(t){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}var L="_snt_uid",M=365,l="_snt_uid";function V(){return b()}function u(t){try{let e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch(e){return null}}function A(){try{return location.protocol==="https:"?"; Secure":""}catch(t){return""}}function d(t,e,n,o){try{document.cookie=`${t}=${encodeURIComponent(e)}; max-age=${n}; SameSite=lax; path=/${o?`; domain=${o}`:""}${A()}`}catch(x){}}function c(t){try{return localStorage.getItem(t)}catch(e){return null}}function U(t,e){try{return localStorage.setItem(t,e),!0}catch(n){return!1}}function y(t){try{return sessionStorage.getItem(t)}catch(e){return null}}function F(t,e){try{return sessionStorage.setItem(t,e),!0}catch(n){return!1}}function G(t){try{sessionStorage.removeItem(t)}catch(e){}}function Y(t){try{return document.cookie=`${t}_probe=1; max-age=1; SameSite=lax; path=/${A()}`,document.cookie.indexOf(`${t}_probe=1`)!==-1}catch(e){return!1}}function W(t){try{localStorage.removeItem(t)}catch(e){}}function m(t,e){d(t,"",0,e)}var j={getSessionId:()=>null,isEphemeral:()=>!1,domain:null,destroy:()=>{}};function q(t,e){if(t===!1)return null;if(typeof t=="string")return t.replace(/^\./,"");for(let n of O(location.hostname))if(d(e,"1",10,n),u(e)==="1")return m(e,n),n;return null}function Q(t){var k,h,f,I,C,D,_;if(typeof window=="undefined")return j;let e=T(t==null?void 0:t.apiKey),n=(k=t==null?void 0:t.cookieName)!=null?k:E(t==null?void 0:t.apiKey),o=`${l}${e}`,x=`${l}_tomb${e}`,S=((h=t==null?void 0:t.cookieTTLDays)!=null?h:M)*24*60*60,r=a=>a&&a.length>0?a:null,w=()=>{var a,$;return e&&!(t!=null&&t.cookieName)&&c(x)===null?($=(a=r(u(L)))!=null?a:r(c(l)))!=null?$:r(y(l)):null},i=q(t==null?void 0:t.cookieDomain,`${n}_dom`),K=r(u(n)),p=i?(m(n),r(u(n))):null,s=(_=(D=(C=(I=(f=p!=null?p:K)!=null?f:r(c(o)))!=null?I:r(y(o)))!=null?C:w())!=null?D:r(t==null?void 0:t.ssrSessionId))!=null?_:V();d(n,s,S,i),i&&u(n)!==s&&(i=null,d(n,s,S));let g=U(o,s),N=Y(n),R=g?!1:F(o,s),v=!g&&!N&&!R;return{getSessionId:()=>s,isEphemeral:()=>v,domain:i,destroy:()=>{s=null,m(n),m(n,i),W(o),G(o),e&&!(t!=null&&t.cookieName)&&(u(L)!==null||c(l)!==null||y(l)!==null)&&U(x,"1")}}}export{b as a,u as b,d as c,m as d,Q as e};
2
+ //# sourceMappingURL=chunk-LCYGZNFI.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/uuid.ts","../src/session.ts"],"sourcesContent":["/** Shared RFC 4122 v4 UUID generator. */\n\n/**\n * Returns a random RFC 4122 v4 UUID.\n *\n * Resolution order, each falling through only on absence/throw:\n * 1. `crypto.randomUUID()` — requires a **secure context** (HTTPS/localhost),\n * so it is absent on plain `http://` (non-localhost) pages.\n * 2. `crypto.getRandomValues()` — a CSPRNG that, unlike `randomUUID`, *is*\n * available in insecure contexts, so ids stay cryptographically random\n * exactly where step 1 is unavailable.\n * 3. `Math.random()` — last resort only when no Web Crypto exists at all.\n * These ids are anonymous analytics session/event keys (not secrets or\n * authenticators), so a well-formed value the Postgres `uuid` column accepts\n * matters more than PRNG quality here — and the generator must never throw\n * (a missing/malformed id would break session creation and the host page).\n */\nexport function randomUuidV4(): string {\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n } catch {\n /* fall through to getRandomValues */\n }\n try {\n if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {\n const buf = new Uint8Array(16);\n crypto.getRandomValues(buf);\n buf[6] = (buf[6]! & 0x0f) | 0x40; // version 4\n buf[8] = (buf[8]! & 0x3f) | 0x80; // variant 10\n let out = '';\n for (let i = 0; i < 16; i++) {\n out += buf[i]!.toString(16).padStart(2, '0');\n if (i === 3 || i === 5 || i === 7 || i === 9) out += '-';\n }\n return out;\n }\n } catch {\n /* fall through to the Math.random() builder */\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n","/** Manages anonymous session identity with cookie + localStorage layers. */\n\nimport { randomUuidV4 } from './uuid.js';\nimport { sessionCookieName, storageSuffix } from './storage-key.js';\nimport { parentDomains, type CookieDomainOption } from './cookie-domain.js';\n\nexport type SessionConfig = {\n cookieName?: string;\n cookieTTLDays?: number;\n /**\n * Public apiKey — namespaces the `_snt_uid` cookie + storage per project, so\n * two projects on the same exact origin don't share a visitor id (which would\n * cross-contaminate sessions server-side). Omit in local mode.\n */\n apiKey?: string;\n /**\n * Session ID generated during SSR (e.g. from `loadAdaptiveAssignments`).\n * Used as the fallback when no existing cookie or localStorage entry is found,\n * so the client adopts the same session the server used for variant assignment\n * on first visit rather than generating a new, orphaned ID.\n */\n ssrSessionId?: string;\n /**\n * Where the visitor cookie lives. Default (undefined): the site's\n * registrable domain, auto-detected, so `example.com` and `app.example.com`\n * share one visitor. `false`: this host only. A string: that domain.\n */\n cookieDomain?: CookieDomainOption;\n};\n\nexport type SessionManager = {\n getSessionId(): string | null;\n /** True when neither cookie nor localStorage could be written — id is in-memory only. */\n isEphemeral(): boolean;\n /** The domain the visitor cookie is shared on (null = this host only) —\n * also the site's extent for referrer classification. */\n domain: string | null;\n destroy(): void;\n};\n\nconst DEFAULT_COOKIE_NAME = '_snt_uid';\nconst DEFAULT_COOKIE_TTL_DAYS = 365;\nconst STORAGE_KEY = '_snt_uid';\n\n/**\n * Generates a unique session identifier. Always an RFC 4122 v4 UUID — the id is\n * stored server-side in a Postgres `uuid` column, so the insecure-context\n * fallback must not emit a malformed value (see `randomUuidV4`).\n */\nfunction generateSessionId(): string {\n return randomUuidV4();\n}\n\nexport function readCookie(name: string): string | null {\n try {\n const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return match ? decodeURIComponent(match[1]) : null;\n } catch {\n return null;\n }\n}\n\n// `Secure` on https pages (audit S21): without it the identity cookie also\n// rode any plain-http request to the same host. Never on http (localhost dev),\n// where the browser would refuse to store it at all.\nfunction secureAttr(): string {\n try {\n return location.protocol === 'https:' ? '; Secure' : '';\n } catch {\n return '';\n }\n}\n\n// SameSite=Lax, not Strict (grader N-B): a Strict cookie is withheld on\n// cross-site top-level navigations — a click from Google, an ad, an email — so\n// AdaptiveRoot's SSR read missed a returning visitor on exactly their landing\n// page and minted an orphan session whose slot trials never saw the visit's\n// conversions (the browser kept its own id). Lax still never rides cross-site\n// subresource or POST requests, and the cookie is first-party only.\nexport function writeCookie(name: string, value: string, maxAgeSeconds: number, domain?: string | null): void {\n try {\n document.cookie = `${name}=${encodeURIComponent(value)}; max-age=${maxAgeSeconds}; SameSite=lax; path=/${domain ? `; domain=${domain}` : ''}${secureAttr()}`;\n } catch {\n /* ignore */\n }\n}\n\nfunction readLocalStorage(key: string): string | null {\n try {\n return localStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\nfunction writeLocalStorage(key: string, value: string): boolean {\n try {\n localStorage.setItem(key, value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction readSessionStorage(key: string): string | null {\n try {\n return sessionStorage.getItem(key);\n } catch {\n return null;\n }\n}\n\nfunction writeSessionStorage(key: string, value: string): boolean {\n try {\n sessionStorage.setItem(key, value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction removeSessionStorage(key: string): void {\n try {\n sessionStorage.removeItem(key);\n } catch {\n /* ignore */\n }\n}\n\nfunction probeCookieWritable(name: string): boolean {\n try {\n document.cookie = `${name}_probe=1; max-age=1; SameSite=lax; path=/${secureAttr()}`;\n return document.cookie.indexOf(`${name}_probe=1`) !== -1;\n } catch {\n return false;\n }\n}\n\nfunction removeLocalStorage(key: string): void {\n try {\n localStorage.removeItem(key);\n } catch {\n /* ignore */\n }\n}\n\nexport function clearCookie(name: string, domain?: string | null): void {\n writeCookie(name, '', 0, domain); // writeCookie already swallows a throw\n}\n\nconst SSR_MANAGER: SessionManager = {\n getSessionId: () => null,\n isEphemeral: () => false,\n domain: null,\n destroy: () => undefined,\n};\n\n/**\n * The domain to share the visitor cookie on (cookie-domain.ts), or null for\n * host-only. undefined → the shortest parent the browser accepts a probe\n * cookie on; false → host-only; a string → that domain (one that does not\n * cover this host is refused by the browser, and initSession then falls back\n * to host-only — see the write check there).\n */\nfunction detectCookieDomain(option: CookieDomainOption, probe: string): string | null {\n if (option === false) return null;\n if (typeof option === 'string') return option.replace(/^\\./, '');\n for (const d of parentDomains(location.hostname)) {\n writeCookie(probe, '1', 10, d);\n if (readCookie(probe) === '1') {\n clearCookie(probe, d);\n return d;\n }\n }\n return null;\n}\n\n/**\n * Initializes session management. Returns a no-op manager in SSR environments.\n */\nexport function initSession(config?: SessionConfig): SessionManager {\n if (typeof window === 'undefined') {\n return SSR_MANAGER;\n }\n\n // Namespace the visitor-id keys per project so multiple keys on one origin\n // don't share a `_snt_uid` (see storage-key.ts). An explicit cookieName still\n // wins for callers that manage their own naming. sessionCookieName is the\n // shared writer/reader name — the SSR reader and graph sync derive the same\n // string from it, so they can't drift back to the bare name.\n const suffix = storageSuffix(config?.apiKey);\n const cookieName = config?.cookieName ?? sessionCookieName(config?.apiKey);\n const storageKey = `${STORAGE_KEY}${suffix}`;\n // Forget-me tombstone for the legacy fallback below. destroy() deletes only\n // this project's SUFFIXED keys — deleting the bare pre-namespacing ones\n // would reset every other project on a shared origin — so without a marker\n // the next init()'s readLegacy() re-adopted the exact identity the visitor\n // had just asked to forget. The marker carries the same per-project suffix,\n // so other projects keep adopting the bare id exactly as before.\n const legacyTombstoneKey = `${STORAGE_KEY}_tomb${suffix}`;\n const cookieTTLDays = config?.cookieTTLDays ?? DEFAULT_COOKIE_TTL_DAYS;\n const maxAgeSeconds = cookieTTLDays * 24 * 60 * 60;\n\n // Treat an empty string from any layer as absent. A `_snt_uid=` cookie with no\n // value (or an empty localStorage/sessionStorage entry) decodes to '', which is\n // not nullish — a plain `??` chain would keep it and persist it for a year,\n // leaving getSessionId() falsy so every track/goal/upsert bails out and the\n // visitor is permanently muted with no way to regenerate. Coercing '' to null\n // lets the chain fall through to a real id (or a freshly generated one).\n const nonEmpty = (value: string | null | undefined): string | null =>\n value && value.length > 0 ? value : null;\n\n // Legacy fallback: visitors identified BEFORE per-project namespacing carry\n // their id under the bare `_snt_uid` names. Without this read, the rollout of\n // the suffixed names reset every existing visitor's identity — a fresh session\n // row per visitor, broken sticky assignments, persona continuity lost. The id\n // is adopted (re-written under the suffixed names below) but the legacy keys\n // are left in place: deleting them would reset the OTHER projects on a shared\n // origin that haven't migrated it yet. Skipped when the caller manages its own\n // cookieName — the bare `_snt_uid` was never theirs — and when there is no\n // suffix (local mode still uses the bare names directly).\n // The tombstone (written by destroy()) blocks this fallback for THIS project\n // only — a forgotten visitor must come back a stranger, not resurrected from\n // the bare keys that other projects still legitimately share.\n const readLegacy = (): string | null =>\n suffix && !config?.cookieName && readLocalStorage(legacyTombstoneKey) === null\n ? nonEmpty(readCookie(DEFAULT_COOKIE_NAME)) ??\n nonEmpty(readLocalStorage(STORAGE_KEY)) ??\n nonEmpty(readSessionStorage(STORAGE_KEY))\n : null;\n\n // Shared visitor cookie (cookie-domain.ts). JS cannot tell a host-only\n // cookie from a domain cookie of the same name — document.cookie lists both\n // as `name=value` — so this host's own copy is deleted and the cookie read\n // again: whatever survives is the SHARED id, and it wins. That is what\n // aligns two hosts that each minted an id before sharing existed (and after\n // Safari's 7-day cap expires the shared one): the first host to write the\n // shared cookie decides, the other adopts it on its next page.\n let domain = detectCookieDomain(config?.cookieDomain, `${cookieName}_dom`);\n const ownCopy = nonEmpty(readCookie(cookieName));\n const shared = domain ? (clearCookie(cookieName), nonEmpty(readCookie(cookieName))) : null;\n\n let sessionId: string | null =\n shared ??\n ownCopy ??\n nonEmpty(readLocalStorage(storageKey)) ??\n nonEmpty(readSessionStorage(storageKey)) ??\n readLegacy() ??\n nonEmpty(config?.ssrSessionId) ??\n generateSessionId();\n\n writeCookie(cookieName, sessionId, maxAgeSeconds, domain);\n // A domain the probe accepted but this write did not (a cookie-policy\n // extension, a jar at capacity) must not leave the visitor with no cookie:\n // the host-only copy was deleted above.\n if (domain && readCookie(cookieName) !== sessionId) {\n domain = null;\n writeCookie(cookieName, sessionId, maxAgeSeconds);\n }\n const lsOk = writeLocalStorage(storageKey, sessionId);\n const cookieOk = probeCookieWritable(cookieName);\n // Always write sessionStorage when localStorage fails — it covers same-tab\n // navigation even in strict storage environments.\n const ssOk = !lsOk ? writeSessionStorage(storageKey, sessionId) : false;\n const ephemeral = !lsOk && !cookieOk && !ssOk;\n\n return {\n getSessionId: () => sessionId,\n isEphemeral: () => ephemeral,\n domain,\n destroy: () => {\n sessionId = null;\n clearCookie(cookieName);\n clearCookie(cookieName, domain); // the shared copy (a repeat no-op when host-only)\n removeLocalStorage(storageKey);\n removeSessionStorage(storageKey);\n // See legacyTombstoneKey: the bare `_snt_uid` keys stay for the other\n // projects on this origin, but this project's next init() must not\n // re-adopt them — that quietly undid the forget-me it just performed.\n // Only when a bare id exists to block: an unconditional marker was a\n // storage write on every forget-me, for visitors with nothing to hide.\n if (\n suffix &&\n !config?.cookieName &&\n (readCookie(DEFAULT_COOKIE_NAME) !== null || readLocalStorage(STORAGE_KEY) !== null || readSessionStorage(STORAGE_KEY) !== null)\n ) {\n writeLocalStorage(legacyTombstoneKey, '1');\n }\n },\n };\n}\n"],"mappings":"yFAiBO,SAASA,GAAuB,CACrC,GAAI,CACF,GAAI,OAAO,QAAW,aAAe,OAAO,OAAO,YAAe,WAChE,OAAO,OAAO,WAAW,CAE7B,OAAQC,EAAA,CAER,CACA,GAAI,CACF,GAAI,OAAO,QAAW,aAAe,OAAO,OAAO,iBAAoB,WAAY,CACjF,IAAMC,EAAM,IAAI,WAAW,EAAE,EAC7B,OAAO,gBAAgBA,CAAG,EAC1BA,EAAI,CAAC,EAAKA,EAAI,CAAC,EAAK,GAAQ,GAC5BA,EAAI,CAAC,EAAKA,EAAI,CAAC,EAAK,GAAQ,IAC5B,IAAIC,EAAM,GACV,QAASC,EAAI,EAAGA,EAAI,GAAIA,IACtBD,GAAOD,EAAIE,CAAC,EAAG,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,GACvCA,IAAM,GAAKA,IAAM,GAAKA,IAAM,GAAKA,IAAM,KAAGD,GAAO,KAEvD,OAAOA,CACT,CACF,OAAQF,EAAA,CAER,CACA,MAAO,uCAAuC,QAAQ,QAAUI,GAAM,CACpE,IAAMC,EAAK,KAAK,OAAO,EAAI,GAAM,EACjC,OAAQD,IAAM,IAAMC,EAAKA,EAAI,EAAO,GAAK,SAAS,EAAE,CACtD,CAAC,CACH,CCLA,IAAMC,EAAsB,WACtBC,EAA0B,IAC1BC,EAAc,WAOpB,SAASC,GAA4B,CACnC,OAAOC,EAAa,CACtB,CAEO,SAASC,EAAWC,EAA6B,CACtD,GAAI,CACF,IAAMC,EAAQ,SAAS,OAAO,MAAM,IAAI,OAAO,WAAWD,CAAI,UAAU,CAAC,EACzE,OAAOC,EAAQ,mBAAmBA,EAAM,CAAC,CAAC,EAAI,IAChD,OAAQ,GACN,OAAO,IACT,CACF,CAKA,SAASC,GAAqB,CAC5B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,EAAUF,EAASvC,EAAWmC,CAAU,CAAC,EACzCO,EAASlC,GAAUS,EAAYkB,CAAU,EAAGI,EAASvC,EAAWmC,CAAU,CAAC,GAAK,KAElFQ,GACFX,GAAAD,GAAAD,GAAAD,GAAAD,EAAAc,GAAA,KAAAA,EACAD,IADA,KAAAb,EAEAW,EAAS9B,EAAiB4B,CAAU,CAAC,IAFrC,KAAAR,EAGAU,EAAS3B,EAAmByB,CAAU,CAAC,IAHvC,KAAAP,EAIAU,EAAW,IAJX,KAAAT,EAKAQ,EAASd,GAAA,YAAAA,EAAQ,YAAY,IAL7B,KAAAO,EAMAlC,EAAkB,EAEpBO,EAAY8B,EAAYQ,EAAWpC,EAAeC,CAAM,EAIpDA,GAAUR,EAAWmC,CAAU,IAAMQ,IACvCnC,EAAS,KACTH,EAAY8B,EAAYQ,EAAWpC,CAAa,GAElD,IAAMqC,EAAOjC,EAAkB0B,EAAYM,CAAS,EAC9CE,EAAW9B,EAAoBoB,CAAU,EAGzCW,EAAQF,EAAoD,GAA7C/B,EAAoBwB,EAAYM,CAAS,EACxDI,EAAY,CAACH,GAAQ,CAACC,GAAY,CAACC,EAEzC,MAAO,CACL,aAAc,IAAMH,EACpB,YAAa,IAAMI,EACnB,OAAAvC,EACA,QAAS,IAAM,CACbmC,EAAY,KACZ1B,EAAYkB,CAAU,EACtBlB,EAAYkB,EAAY3B,CAAM,EAC9BQ,EAAmBqB,CAAU,EAC7BvB,EAAqBuB,CAAU,EAO7BJ,GACA,EAACR,GAAA,MAAAA,EAAQ,cACRzB,EAAWL,CAAmB,IAAM,MAAQc,EAAiBZ,CAAW,IAAM,MAAQe,EAAmBf,CAAW,IAAM,OAE3Hc,EAAkB2B,EAAoB,GAAG,CAE7C,CACF,CACF","names":["randomUuidV4","e","buf","out","i","c","r","DEFAULT_COOKIE_NAME","DEFAULT_COOKIE_TTL_DAYS","STORAGE_KEY","generateSessionId","randomUuidV4","readCookie","name","match","secureAttr","e","writeCookie","value","maxAgeSeconds","domain","readLocalStorage","key","writeLocalStorage","readSessionStorage","writeSessionStorage","removeSessionStorage","probeCookieWritable","removeLocalStorage","clearCookie","SSR_MANAGER","detectCookieDomain","option","probe","d","parentDomains","initSession","config","_a","_b","_c","_d","_e","_f","_g","suffix","storageSuffix","cookieName","sessionCookieName","storageKey","legacyTombstoneKey","nonEmpty","readLegacy","ownCopy","shared","sessionId","lsOk","cookieOk","ssOk","ephemeral"]}
@@ -0,0 +1,2 @@
1
+ function i(n){return n?`_${n.slice(0,12)}`:""}var c="_snt_uid";function a(n){return`${c}${i(n)}`}var o="__sntForgetGen",u=()=>{try{return window[o]}catch(n){return}};function g(n){var t,e;try{let r=window,s=(t=r[o])!=null?t:r[o]={};s[n]=((e=s[n])!=null?e:0)+1}catch(r){}}function d(n){var t,e;return(e=(t=u())==null?void 0:t[n])!=null?e:0}var f="sentient_internal";export{i as a,c as b,a as c,g as d,d as e,f};
2
+ //# sourceMappingURL=chunk-WUFFNQHQ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/storage-key.ts"],"sourcesContent":["/**\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"],"mappings":"AAcO,SAASA,EAAcC,EAAyB,CACrD,OAAOA,EAAS,IAAIA,EAAO,MAAM,EAAG,EAAE,CAAC,GAAK,EAC9C,CAOO,IAAMC,EAA6B,WAYnC,SAASC,EAAkBF,EAAyB,CACzD,MAAO,GAAGC,CAA0B,GAAGF,EAAcC,CAAM,CAAC,EAC9D,CASA,IAAMG,EAAO,iBAEPC,EAAS,IAA0B,CACvC,GAAI,CACF,OAAQ,OAAyDD,CAAI,CACvE,OAAQE,EAAA,CACN,MACF,CACF,EACO,SAASC,EAAcN,EAAsB,CAvDpD,IAAAO,EAAAC,EAwDE,GAAI,CACF,IAAMC,EAAI,OACJC,GAAKH,EAAAE,EAAAN,KAAA,KAAAI,EAAAE,EAAAN,GAAY,CAAC,EACxBO,EAAEV,CAAM,IAAKQ,EAAAE,EAAEV,CAAM,IAAR,KAAAQ,EAAa,GAAK,CACjC,OAAQ,GAER,CACF,CAEO,SAASG,EAAiBX,EAAwB,CAjEzD,IAAAO,EAAAC,EAkEE,OAAOA,GAAAD,EAAAH,EAAO,IAAP,YAAAG,EAAWP,KAAX,KAAAQ,EAAsB,CAC/B","names":["storageSuffix","apiKey","LEGACY_SESSION_COOKIE_NAME","sessionCookieName","GENS","genMap","e","markForgotten","_a","_b","w","m","forgetGeneration"]}
1
+ {"version":3,"sources":["../src/storage-key.ts"],"sourcesContent":["/**\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"],"mappings":"AAcO,SAASA,EAAcC,EAAyB,CACrD,OAAOA,EAAS,IAAIA,EAAO,MAAM,EAAG,EAAE,CAAC,GAAK,EAC9C,CAOO,IAAMC,EAA6B,WAYnC,SAASC,EAAkBF,EAAyB,CACzD,MAAO,GAAGC,CAA0B,GAAGF,EAAcC,CAAM,CAAC,EAC9D,CASA,IAAMG,EAAO,iBAEPC,EAAS,IAA0B,CACvC,GAAI,CACF,OAAQ,OAAyDD,CAAI,CACvE,OAAQE,EAAA,CACN,MACF,CACF,EACO,SAASC,EAAcN,EAAsB,CAvDpD,IAAAO,EAAAC,EAwDE,GAAI,CACF,IAAMC,EAAI,OACJC,GAAKH,EAAAE,EAAAN,KAAA,KAAAI,EAAAE,EAAAN,GAAY,CAAC,EACxBO,EAAEV,CAAM,IAAKQ,EAAAE,EAAEV,CAAM,IAAR,KAAAQ,EAAa,GAAK,CACjC,OAAQH,EAAA,CAER,CACF,CAEO,SAASM,EAAiBX,EAAwB,CAjEzD,IAAAO,EAAAC,EAkEE,OAAOA,GAAAD,EAAAH,EAAO,IAAP,YAAAG,EAAWP,KAAX,KAAAQ,EAAsB,CAC/B,CAWO,IAAMI,EAAkB","names":["storageSuffix","apiKey","LEGACY_SESSION_COOKIE_NAME","sessionCookieName","GENS","genMap","e","markForgotten","_a","_b","w","m","forgetGeneration","INTERNAL_COOKIE"]}
@@ -374,11 +374,29 @@ type SentientConfig = {
374
374
  * will not upgrade it. Set `false` to make your own consent gate authoritative.
375
375
  */
376
376
  respectDoNotTrack?: boolean;
377
+ /**
378
+ * Your own id for this visitor, when the page already knows it at start-up
379
+ * (a signed-in user). Same effect as calling `identify(userId)` after init:
380
+ * it links their devices and lets a person who already reached your main
381
+ * goal be recognised as such. Never an email address.
382
+ */
377
383
  userId?: string;
384
+ /** `signUserId(userId, secretKey)` from your server, making `userId` a VERIFIED identify. */
385
+ userHash?: string;
386
+ /**
387
+ * Marks this visit as your own team's or a test site's, so it is left out of
388
+ * every report and out of learning (it is still served versions, so QA keeps
389
+ * working). Typically `user.email.endsWith('@example.com')` evaluated in
390
+ * your code: the email itself never leaves the site, only `internal: true`.
391
+ * A function is called once, at init. Sticky server-side: `false` never
392
+ * un-marks a visit. Needs a SentientUI API that knows internal traffic;
393
+ * older ones ignore it.
394
+ */
395
+ internal?: boolean | (() => boolean);
378
396
  /**
379
397
  * Declared persona — the role your app already knows for this visitor
380
398
  * (e.g. 'admin', 'evaluator'). Must be a key in the project's persona
381
- * vocabulary (dashboard → Settings → Personas); unrecognized values are
399
+ * vocabulary (dashboard → Audiences); unrecognized values are
382
400
  * ignored server-side and surfaced in the dashboard so you can add them.
383
401
  * Declared personas are served at full confidence, overriding the inferred
384
402
  * one. Keep it a low-cardinality role label — never a user id or email.
@@ -584,6 +602,19 @@ type ComponentGoalOptions = GoalOptions & {
584
602
  /** Reward credited to the served variant (0–1). Defaults to 1. */
585
603
  reward?: number;
586
604
  };
605
+ /** identify()'s options. */
606
+ type IdentifyOptions = {
607
+ /** `signUserId(userId, secretKey)` from your server — a VERIFIED identify. */
608
+ userHash?: string;
609
+ /**
610
+ * The user's email, for the project's "team emails & domains" rules. It is
611
+ * normalized (trimmed, lowercased) and SHA-256 hashed on the device; only
612
+ * the hash and the domain (`example.com`) are sent, never the address. On a
613
+ * non-secure (http:) page, where the browser offers no hashing, only the
614
+ * domain is sent.
615
+ */
616
+ email?: string;
617
+ };
587
618
  type SentientClient = {
588
619
  track(event: Omit<SentientEvent, 'id' | 'sessionId' | 'timestamp' | 'timeInSession'>): void;
589
620
  goal(name: string, options?: GoalOptions): void;
@@ -604,9 +635,7 @@ type SentientClient = {
604
635
  * project signs its identifies, only verified links receive server goals by
605
636
  * `userId` and carry the user's profile across devices.
606
637
  */
607
- identify(userId: string, opts?: {
608
- userHash?: string;
609
- }): void;
638
+ identify(userId: string, opts?: IdentifyOptions): void;
610
639
  /**
611
640
  * The visitor id (session id) for carrying a conversion to your server
612
641
  * later: store it with the order/sign-up, then pass it to `trackServerGoal`.
@@ -784,4 +813,4 @@ declare function routeKey(): string;
784
813
  */
785
814
  declare function init(config: SentientConfig): SentientClient;
786
815
 
787
- export { setStageAttribute as $, type AssignOptions as A, cspNonce as B, type ComponentGoalOptions as C, type DecideInput as D, type EventQueue as E, exposedStage as F, type GoalDefinition as G, forgetGeneration as H, grantConsent as I, init as J, isDoNotTrackEnabled as K, LEGACY_SESSION_COOKIE_NAME as L, type MicroSignalEmitter as M, normalizeUrlPattern as N, pageScopeMatches as O, PAGE_SCOPE_RE as P, type QueueConfig as Q, REVEAL_MS as R, STAGE_ATTRIBUTE as S, resetRevealStyles as T, reveal as U, routeKey as V, type WeightEntry as W, sanitizePageUrl as X, sessionCookieName as Y, setCspNonce as Z, _registerConsentUpgradeInit as _, type AssignResult as a, urlMatches as a0, type Assignment as b, type AssignmentCache as c, type AuthoredArmReport as d, type ComponentWeightEntry as e, type DecideOutcome as f, type EventType as g, type GoalOptions as h, type GraphClient as i, type GraphConfig as j, type GraphSnapshot as k, LOCAL_MODE_BANNER as l, type MicroSignalType as m, PROD_KEYLESS_ERROR as n, type PageNode as o, type RevealOptions as p, type SectionMapEntry as q, type SentientClient as r, type SentientConfig as s, type SentientEvent as t, type SessionConfig as u, type SessionManager as v, type SkeletonReport as w, type StageAttributes as x, applyNonce as y, attachMicroSignalDetectors as z };
816
+ export { setCspNonce as $, type AssignOptions as A, cspNonce as B, type ComponentGoalOptions as C, type DecideInput as D, type EventQueue as E, exposedStage as F, type GoalDefinition as G, forgetGeneration as H, type IdentifyOptions as I, grantConsent as J, init as K, LEGACY_SESSION_COOKIE_NAME as L, type MicroSignalEmitter as M, isDoNotTrackEnabled as N, normalizeUrlPattern as O, PAGE_SCOPE_RE as P, type QueueConfig as Q, REVEAL_MS as R, STAGE_ATTRIBUTE as S, pageScopeMatches as T, resetRevealStyles as U, reveal as V, type WeightEntry as W, routeKey as X, sanitizePageUrl as Y, sessionCookieName as Z, _registerConsentUpgradeInit as _, type AssignResult as a, setStageAttribute as a0, urlMatches as a1, type Assignment as b, type AssignmentCache as c, type AuthoredArmReport as d, type ComponentWeightEntry as e, type DecideOutcome as f, type EventType as g, type GoalOptions as h, type GraphClient as i, type GraphConfig as j, type GraphSnapshot as k, LOCAL_MODE_BANNER as l, type MicroSignalType as m, PROD_KEYLESS_ERROR as n, type PageNode as o, type RevealOptions as p, type SectionMapEntry as q, type SentientClient as r, type SentientConfig as s, type SentientEvent as t, type SessionConfig as u, type SessionManager as v, type SkeletonReport as w, type StageAttributes as x, applyNonce as y, attachMicroSignalDetectors as z };
@@ -1,2 +1,2 @@
1
- "use strict";var T=Object.defineProperty,ae=Object.defineProperties,ue=Object.getOwnPropertyDescriptor,ce=Object.getOwnPropertyDescriptors,le=Object.getOwnPropertyNames,Q=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,de=Object.prototype.propertyIsEnumerable;var j=(n,t,e)=>t in n?T(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,D=(n,t)=>{for(var e in t||(t={}))z.call(t,e)&&j(n,e,t[e]);if(Q)for(var e of Q(t))de.call(t,e)&&j(n,e,t[e]);return n},N=(n,t)=>ae(n,ce(t));var fe=(n,t)=>{for(var e in t)T(n,e,{get:t[e],enumerable:!0})},pe=(n,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of le(t))!z.call(n,s)&&s!==e&&T(n,s,{get:()=>t[s],enumerable:!(o=ue(t,s))||o.enumerable});return n};var ge=n=>pe(T({},"__esModule",{value:!0}),n);var ve={};fe(ve,{TCF_DEFAULT_PURPOSES:()=>B,consentFromCookies:()=>H,consentModeGranted:()=>J,consentWatcher:()=>Z,cookiebotCookieGrants:()=>O,cookieyesCookieGrants:()=>M,forgetVisitor:()=>ie,onetrustCookieGrants:()=>G,tcStringConsents:()=>L,tcStringPurposes:()=>K});module.exports=ge(ve);var B=[1,5,6,8],P=n=>{try{return decodeURIComponent(n)}catch(t){return n}};function k(n,t){if(n)for(let e of n.cookie.split(";")){let o=e.indexOf("=");if(o>0&&e.slice(0,o).trim()===t)return e.slice(o+1).trim()}}function I(n,t,e){let o=[n,...n.document?[n.document]:[]];for(let s of o)for(let r of t)s.addEventListener(r,e);return()=>{for(let s of o)for(let r of t)s.removeEventListener(r,e)}}function O(n,t="statistics"){if(n==null||n==="")return null;let e=P(n).trim();if(e==="-1")return!0;if(e==="0")return!1;let o=new RegExp(`[{,]\\s*${t}\\s*:\\s*(true|false)`).exec(e);return o?o[1]==="true":null}function G(n,t="C0002"){if(n==null||n==="")return null;let e;for(let o of n.split("&"))o.startsWith("groups=")&&(e=P(o.slice(7)));if(e==null)return null;for(let o of e.split(",")){let[s,r]=o.split(":");if(s===t)return r==="1"}return null}function M(n,t="analytics"){if(n==null||n==="")return null;let e=new RegExp(`(?:^|,)${t}:(yes|no)(?:,|$)`).exec(P(n));return e?e[1]==="yes":null}var me="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",W=n=>{let t="";for(let e of n)t+=me.indexOf(e).toString(2).padStart(6,"0");return t};function L(n){if(!n)return null;let t=n.split("."),e=t[0];if(!/^[A-Za-z0-9_-]+$/.test(e))return null;let o=W(e);if(o.length<200||parseInt(o.slice(0,6),2)!==2)return null;let s=(d,p)=>d+p<=o.length?parseInt(o.slice(d,d+p),2):null,r=new Set,i=new Set;for(let d=1;d<=24;d++)o[151+d]==="1"&&r.add(d),o[175+d]==="1"&&i.add(d);let a=null,u=s(213,16),l=s(229,1);if(u!==null&&l===0){if(230+u<=o.length){a=new Set;for(let d=1;d<=u;d++)o[229+d]==="1"&&a.add(d)}}else if(u!==null&&l===1){let d=s(230,12),p=242,y=new Set,c=d!==null;for(let g=0;c&&g<(d!=null?d:0);g++){let w=s(p,1),h=s(p+1,16);if(w===null||h===null)c=!1;else if(w===1){let b=s(p+17,16);if(b===null||b<h||b-h>65535)c=!1;else for(let S=h;S<=b;S++)y.add(S);p+=33}else y.add(h),p+=17}c&&(a=y)}let f=new Set,m=new Set;for(let d of t.slice(1)){if(!/^[A-Za-z0-9_-]+$/.test(d))continue;let p=W(d);if(!(p.length<51||parseInt(p.slice(0,3),2)!==3))for(let y=1;y<=24;y++)p[2+y]==="1"&&f.add(y),p[26+y]==="1"&&m.add(y)}return{purposes:r,legitimateInterests:i,vendors:a,publisherPurposes:f,publisherLegitimateInterests:m,purposeOneTreatment:o[200]==="1"}}function K(n){var t,e;return(e=(t=L(n))==null?void 0:t.purposes)!=null?e:null}var ye=new Set([1,3,4,5,6]);function Y(n,t,e,o){return n.purposes.every(r=>t(r)||!ye.has(r)&&e(r))?n.vendorId===void 0?!0:o(n.vendorId):!1}function V(n){var e,o,s,r,i,a,u;let t=typeof n=="string"?{cmp:n}:n;switch(t.cmp){case"cookiebot":return{cmp:"cookiebot",category:(e=t.category)!=null?e:"statistics"};case"onetrust":return{cmp:"onetrust",group:(o=t.group)!=null?o:"C0002"};case"cookieyes":return{cmp:"cookieyes",category:(s=t.category)!=null?s:"analytics"};case"tcf":return{cmp:"tcf",purposes:t.purposes&&t.purposes.length>0?t.purposes:B,vendorId:typeof t.vendorId=="number"&&t.vendorId>0?t.vendorId:void 0};case"google-consent-mode":return{cmp:"google-consent-mode",type:(r=t.type)!=null?r:"analytics_storage",dataLayer:(i=t.dataLayer)!=null?i:"dataLayer",region:typeof t.region=="string"&&t.region.trim()!==""?t.region.trim().toUpperCase():void 0};case"shopify":return{cmp:"shopify",category:(a=t.category)!=null?a:"analytics"};default:return{cmp:"custom",cookie:t.cookie,value:(u=t.value)!=null?u:"accepted",check:t.check,event:t.event,refused:t.refused}}}function H(n,t){let e=V(n);switch(e.cmp){case"cookiebot":return O(t("CookieConsent"),e.category);case"onetrust":return G(t("OptanonConsent"),e.group);case"cookieyes":return M(t("cookieyes-consent"),e.category);case"tcf":{let o=L(t("euconsent-v2"));return o?Y(o.purposeOneTreatment?N(D({},e),{purposes:e.purposes.filter(s=>s!==1)}):e,s=>o.purposes.has(s)||o.publisherPurposes.has(s),s=>o.legitimateInterests.has(s)||o.publisherLegitimateInterests.has(s),s=>o.vendors?o.vendors.has(s):null):null}case"google-consent-mode":return null;case"shopify":return null;case"custom":return!e.cookie||e.check?null:t(e.cookie)===e.value}}var U=()=>({update:null,global:null,regions:new Map});function X(n,t,e){let o=t&&typeof t=="object"&&"length"in t?Array.prototype.slice.call(t):null;if(!o||o[0]!=="consent"||o[1]!=="default"&&o[1]!=="update")return;let s=o[2],r=s==null?void 0:s[e],i=r==="granted"?!0:r==="denied"?!1:null;if(i===null)return;if(o[1]==="update"){n.update=i;return}let a=s==null?void 0:s.region,l=(Array.isArray(a)?a:typeof a=="string"?[a]:[]).filter(f=>typeof f=="string"&&f.trim()!=="").map(f=>f.trim().toUpperCase());if(l.length===0)n.global=i;else for(let f of l)n.regions.set(f,i)}function he(n){return n.update===!1}function q(n,t){if(n.update!==null)return n.update;if(t){let e=n.regions.get(t);if(e!==void 0)return e;let o=t.split("-")[0],s=n.regions.get(o);if(s!==void 0)return s;if(t===o){for(let[r,i]of n.regions)if(i===!1&&r.startsWith(`${o}-`))return!1}return n.global}for(let e of n.regions.values())if(e===!1)return!1;return n.global!==null?n.global:n.regions.size>0?!1:null}function J(n,t="analytics_storage",e){if(!Array.isArray(n))return null;let o=U();for(let s of n)X(o,s,t);return q(o,(e==null?void 0:e.trim().toUpperCase())||void 0)}function Z(n,t=window){let e=V(n),o=t,s=t.document;switch(e.cmp){case"cookiebot":return{read:()=>{let r=o.Cookiebot,i=O(k(s,"CookieConsent"),e.category);return r!=null&&r.consent&&typeof r.consent[e.category]=="boolean"&&(r.hasResponse===!0||i===null)?r.consent[e.category]===!0:i},subscribe:r=>I(t,["CookiebotOnAccept","CookiebotOnDecline","CookiebotOnConsentReady","CookiebotOnLoad"],r),refused(){let r=o.Cookiebot;return((r==null?void 0:r.hasResponse)===!0||k(s,"CookieConsent")!==void 0)&&this.read()===!1}};case"onetrust":return{read:()=>{let r=o.OnetrustActiveGroups;return typeof r=="string"?`,${r},`.includes(`,${e.group},`):G(k(s,"OptanonConsent"),e.group)},subscribe:r=>I(t,["OneTrustGroupsUpdated"],r),refused(){return k(s,"OptanonAlertBoxClosed")!==void 0&&this.read()===!1}};case"cookieyes":return{read:()=>{var i;let r=o.getCkyConsent;if(typeof r=="function")try{let a=(i=r())==null?void 0:i.categories;if(a&&typeof a[e.category]=="boolean")return a[e.category]===!0}catch(a){}return M(k(s,"cookieyes-consent"),e.category)},subscribe:r=>I(t,["cookieyes_consent_update","cookieyes_banner_load","cookieyes_banner_loaded"],r),refused(){var a,u;let r=/(?:^|,)action:yes(?:,|$)/.test(P((a=k(s,"cookieyes-consent"))!=null?a:"")),i=o.getCkyConsent;if(!r&&typeof i=="function")try{r=((u=i())==null?void 0:u.isUserActionCompleted)===!0}catch(l){}return r&&this.read()===!1}};case"tcf":{let r=null,i=!1,a=!1;return{read:()=>r,refused:()=>r===!1&&!i&&a,subscribe:u=>{let l,f=!1,m=!1,d=(c,g)=>{var h,b,S,R;if(!g||f)return;typeof c.listenerId=="number"&&(l=c.listenerId),i=c.eventStatus==="cmpuishown",a=(c.eventStatus==="tcloaded"||c.eventStatus==="useractioncomplete")&&c.purposeOneTreatment!==!0&&c.gdprApplies!==!1&&((b=(h=c.purpose)==null?void 0:h.consents)==null?void 0:b[1])!==!0&&((R=(S=c.publisher)==null?void 0:S.consents)==null?void 0:R[1])!==!0;let w=c.eventStatus==="tcloaded"||c.eventStatus==="useractioncomplete";w&&(m=!0),i?r=!1:!w&&c.gdprApplies!==!1?m||(r=null):r=c.gdprApplies===!1||Y(c.purposeOneTreatment===!0?N(D({},e),{purposes:e.purposes.filter(v=>v!==1)}):e,v=>{var C,_,A,x;return((_=(C=c.purpose)==null?void 0:C.consents)==null?void 0:_[v])===!0||((x=(A=c.publisher)==null?void 0:A.consents)==null?void 0:x[v])===!0},v=>{var C,_,A,x;return((_=(C=c.purpose)==null?void 0:C.legitimateInterests)==null?void 0:_[v])===!0||((x=(A=c.publisher)==null?void 0:A.legitimateInterests)==null?void 0:x[v])===!0},v=>{var C,_;return((_=(C=c.vendor)==null?void 0:C.consents)==null?void 0:_[v])===!0})===!0,u()},p=0,y=()=>{if(f)return;let c=o.__tcfapi;typeof c=="function"?c("addEventListener",2,d):p++<40&&window.setTimeout(y,250)};return y(),()=>{f=!0;let c=o.__tcfapi;typeof c=="function"&&l!==void 0&&c("removeEventListener",2,()=>{},l)}}}}case"google-consent-mode":{let r=null,i=0,a=U(),u=()=>{let l=o[e.dataLayer];if(!Array.isArray(l))return null;for((l!==r||l.length<i)&&(r=l,i=0,a=U());i<l.length;i++)X(a,l[i],e.type);return q(a,e.region)};return{read:u,refused:()=>u()===!1&&he(a),subscribe:l=>{let f=new WeakSet,m=!1,d=[],p=-1,y=()=>{var w,h;let g=(h=o[w=e.dataLayer])!=null?h:o[w]=[];if(!f.has(g)){f.add(g);let b=g.push,S=function(...R){let v=b.apply(g,R);return p=g.length,m||l(),v};g.push=S,d.push(()=>{g.push===S&&(g.push=b)})}g.length!==p&&(p=g.length,l())};y();let c=window.setInterval(y,1e3);return()=>{m=!0,window.clearInterval(c);for(let g of d)g()}}}}case"shopify":{let r=e.category==="marketing"?"marketingAllowed":e.category==="preferences"?"preferencesProcessingAllowed":"analyticsProcessingAllowed";return{read:()=>{var a,u;let i=(u=(a=o.Shopify)==null?void 0:a.customerPrivacy)==null?void 0:u[r];if(typeof i!="function")return null;try{let l=i();return typeof l=="boolean"?l:null}catch(l){return null}},refused(){var a,u;let i=(a=o.Shopify)==null?void 0:a.customerPrivacy;if(typeof(i==null?void 0:i.currentVisitorConsent)!="function")return!1;try{return((u=i.currentVisitorConsent())==null?void 0:u[e.category])==="no"}catch(l){return!1}},subscribe:i=>{let a=I(t,["visitorConsentCollected"],i),u=!1,l=0,f=()=>{if(u)return;let m=o.Shopify;if(m!=null&&m.customerPrivacy){i();return}if(typeof(m==null?void 0:m.loadFeatures)=="function"){try{m.loadFeatures([{name:"consent-tracking-api",version:"0.1"}],d=>{!u&&!d&&i()})}catch(d){}return}l++<40&&window.setTimeout(f,250)};return f(),()=>{u=!0,a()}}}}case"custom":return{read:()=>{if(e.check)try{return e.check()===!0}catch(i){return!1}if(!e.cookie)return null;let r=k(s,e.cookie);return r===void 0?null:r===e.value},refused:()=>{var r;if(e.check)try{return((r=e.refused)==null?void 0:r.call(e))===!0}catch(i){return!1}return!!e.cookie&&k(s,e.cookie)!==void 0&&k(s,e.cookie)!==e.value},subscribe:r=>e.event?I(t,[e.event],r):()=>{}}}}function F(n){return n?`_${n.slice(0,12)}`:""}var E="_snt_uid";function ee(n){return`${E}${F(n)}`}var $="__sntForgetGen";function te(n){var t,e;try{let o=window,s=(t=o[$])!=null?t:o[$]={};s[n]=((e=s[n])!=null?e:0)+1}catch(o){}}var ne="_snt_snap:";var _e=56*1024;function oe(n){return`_snt_retry_${n.slice(0,12)}`}function re(n){return`_snt_goal_retry_${n.slice(0,12)}`}function se(n){let t=(n||"").toLowerCase();if(!t.includes(".")||/^[\d.]+$|:/.test(t))return[];let e=t.split("."),o=[];for(let s=e.length-2;s>=0;s--)o.push(e.slice(s).join("."));return o}function ie(n){if(typeof window=="undefined"||!n)return!1;te(n);let t=!1,e=ee(n);try{if(new RegExp(`(?:^|; )${e}=`).test(document.cookie)){let i=location.protocol==="https:"?"; Secure":"";for(let a of["",...se(location.hostname)])document.cookie=`${e}=; max-age=0; SameSite=lax; path=/${a?`; domain=${a}`:""}${i}`;t=!0}}catch(i){}let o=F(n),s=[e,"_snt_graph_edges",ne+n,oe(n),re(n),`_snt_graph_nodes${o}`],r=[`_snt_asgn${o}_`];for(let i of["localStorage","sessionStorage"])try{let a=window[i];for(let u of s)a.getItem(u)!==null&&(a.removeItem(u),t=!0);for(let u=a.length-1;u>=0;u--){let l=a.key(u);l&&r.some(f=>l.startsWith(f))&&(a.removeItem(l),t=!0)}}catch(a){}try{(new RegExp(`(?:^|; )${E}=[^;]`).test(document.cookie)||localStorage.getItem(E)!==null||sessionStorage.getItem(E)!==null)&&localStorage.setItem(`${E}_tomb${o}`,"1")}catch(i){}return t}0&&(module.exports={TCF_DEFAULT_PURPOSES,consentFromCookies,consentModeGranted,consentWatcher,cookiebotCookieGrants,cookieyesCookieGrants,forgetVisitor,onetrustCookieGrants,tcStringConsents,tcStringPurposes});
1
+ "use strict";var T=Object.defineProperty,ae=Object.defineProperties,ue=Object.getOwnPropertyDescriptor,ce=Object.getOwnPropertyDescriptors,le=Object.getOwnPropertyNames,Q=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,de=Object.prototype.propertyIsEnumerable;var j=(n,t,e)=>t in n?T(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e,D=(n,t)=>{for(var e in t||(t={}))z.call(t,e)&&j(n,e,t[e]);if(Q)for(var e of Q(t))de.call(t,e)&&j(n,e,t[e]);return n},N=(n,t)=>ae(n,ce(t));var fe=(n,t)=>{for(var e in t)T(n,e,{get:t[e],enumerable:!0})},pe=(n,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of le(t))!z.call(n,s)&&s!==e&&T(n,s,{get:()=>t[s],enumerable:!(o=ue(t,s))||o.enumerable});return n};var ge=n=>pe(T({},"__esModule",{value:!0}),n);var ve={};fe(ve,{TCF_DEFAULT_PURPOSES:()=>B,consentFromCookies:()=>H,consentModeGranted:()=>J,consentWatcher:()=>Z,cookiebotCookieGrants:()=>O,cookieyesCookieGrants:()=>L,forgetVisitor:()=>ie,onetrustCookieGrants:()=>G,tcStringConsents:()=>M,tcStringPurposes:()=>K});module.exports=ge(ve);var B=[1,5,6,8],P=n=>{try{return decodeURIComponent(n)}catch(t){return n}};function k(n,t){if(n)for(let e of n.cookie.split(";")){let o=e.indexOf("=");if(o>0&&e.slice(0,o).trim()===t)return e.slice(o+1).trim()}}function I(n,t,e){let o=[n,...n.document?[n.document]:[]];for(let s of o)for(let r of t)s.addEventListener(r,e);return()=>{for(let s of o)for(let r of t)s.removeEventListener(r,e)}}function O(n,t="statistics"){if(n==null||n==="")return null;let e=P(n).trim();if(e==="-1")return!0;if(e==="0")return!1;let o=new RegExp(`[{,]\\s*${t}\\s*:\\s*(true|false)`).exec(e);return o?o[1]==="true":null}function G(n,t="C0002"){if(n==null||n==="")return null;let e;for(let o of n.split("&"))o.startsWith("groups=")&&(e=P(o.slice(7)));if(e==null)return null;for(let o of e.split(",")){let[s,r]=o.split(":");if(s===t)return r==="1"}return null}function L(n,t="analytics"){if(n==null||n==="")return null;let e=new RegExp(`(?:^|,)${t}:(yes|no)(?:,|$)`).exec(P(n));return e?e[1]==="yes":null}var me="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",W=n=>{let t="";for(let e of n)t+=me.indexOf(e).toString(2).padStart(6,"0");return t};function M(n){if(!n)return null;let t=n.split("."),e=t[0];if(!/^[A-Za-z0-9_-]+$/.test(e))return null;let o=W(e);if(o.length<200||parseInt(o.slice(0,6),2)!==2)return null;let s=(d,p)=>d+p<=o.length?parseInt(o.slice(d,d+p),2):null,r=new Set,i=new Set;for(let d=1;d<=24;d++)o[151+d]==="1"&&r.add(d),o[175+d]==="1"&&i.add(d);let a=null,u=s(213,16),l=s(229,1);if(u!==null&&l===0){if(230+u<=o.length){a=new Set;for(let d=1;d<=u;d++)o[229+d]==="1"&&a.add(d)}}else if(u!==null&&l===1){let d=s(230,12),p=242,y=new Set,c=d!==null;for(let g=0;c&&g<(d!=null?d:0);g++){let w=s(p,1),h=s(p+1,16);if(w===null||h===null)c=!1;else if(w===1){let b=s(p+17,16);if(b===null||b<h||b-h>65535)c=!1;else for(let S=h;S<=b;S++)y.add(S);p+=33}else y.add(h),p+=17}c&&(a=y)}let f=new Set,m=new Set;for(let d of t.slice(1)){if(!/^[A-Za-z0-9_-]+$/.test(d))continue;let p=W(d);if(!(p.length<51||parseInt(p.slice(0,3),2)!==3))for(let y=1;y<=24;y++)p[2+y]==="1"&&f.add(y),p[26+y]==="1"&&m.add(y)}return{purposes:r,legitimateInterests:i,vendors:a,publisherPurposes:f,publisherLegitimateInterests:m,purposeOneTreatment:o[200]==="1"}}function K(n){var t,e;return(e=(t=M(n))==null?void 0:t.purposes)!=null?e:null}var ye=new Set([1,3,4,5,6]);function Y(n,t,e,o){return n.purposes.every(r=>t(r)||!ye.has(r)&&e(r))?n.vendorId===void 0?!0:o(n.vendorId):!1}function V(n){var e,o,s,r,i,a,u;let t=typeof n=="string"?{cmp:n}:n;switch(t.cmp){case"cookiebot":return{cmp:"cookiebot",category:(e=t.category)!=null?e:"statistics"};case"onetrust":return{cmp:"onetrust",group:(o=t.group)!=null?o:"C0002"};case"cookieyes":return{cmp:"cookieyes",category:(s=t.category)!=null?s:"analytics"};case"tcf":return{cmp:"tcf",purposes:t.purposes&&t.purposes.length>0?t.purposes:B,vendorId:typeof t.vendorId=="number"&&t.vendorId>0?t.vendorId:void 0};case"google-consent-mode":return{cmp:"google-consent-mode",type:(r=t.type)!=null?r:"analytics_storage",dataLayer:(i=t.dataLayer)!=null?i:"dataLayer",region:typeof t.region=="string"&&t.region.trim()!==""?t.region.trim().toUpperCase():void 0};case"shopify":return{cmp:"shopify",category:(a=t.category)!=null?a:"analytics"};default:return{cmp:"custom",cookie:t.cookie,value:(u=t.value)!=null?u:"accepted",check:t.check,event:t.event,refused:t.refused}}}function H(n,t){let e=V(n);switch(e.cmp){case"cookiebot":return O(t("CookieConsent"),e.category);case"onetrust":return G(t("OptanonConsent"),e.group);case"cookieyes":return L(t("cookieyes-consent"),e.category);case"tcf":{let o=M(t("euconsent-v2"));return o?Y(o.purposeOneTreatment?N(D({},e),{purposes:e.purposes.filter(s=>s!==1)}):e,s=>o.purposes.has(s)||o.publisherPurposes.has(s),s=>o.legitimateInterests.has(s)||o.publisherLegitimateInterests.has(s),s=>o.vendors?o.vendors.has(s):null):null}case"google-consent-mode":return null;case"shopify":return null;case"custom":return!e.cookie||e.check?null:t(e.cookie)===e.value}}var U=()=>({update:null,global:null,regions:new Map});function X(n,t,e){let o=t&&typeof t=="object"&&"length"in t?Array.prototype.slice.call(t):null;if(!o||o[0]!=="consent"||o[1]!=="default"&&o[1]!=="update")return;let s=o[2],r=s==null?void 0:s[e],i=r==="granted"?!0:r==="denied"?!1:null;if(i===null)return;if(o[1]==="update"){n.update=i;return}let a=s==null?void 0:s.region,l=(Array.isArray(a)?a:typeof a=="string"?[a]:[]).filter(f=>typeof f=="string"&&f.trim()!=="").map(f=>f.trim().toUpperCase());if(l.length===0)n.global=i;else for(let f of l)n.regions.set(f,i)}function he(n){return n.update===!1}function q(n,t){if(n.update!==null)return n.update;if(t){let e=n.regions.get(t);if(e!==void 0)return e;let o=t.split("-")[0],s=n.regions.get(o);if(s!==void 0)return s;if(t===o){for(let[r,i]of n.regions)if(i===!1&&r.startsWith(`${o}-`))return!1}return n.global}for(let e of n.regions.values())if(e===!1)return!1;return n.global!==null?n.global:n.regions.size>0?!1:null}function J(n,t="analytics_storage",e){if(!Array.isArray(n))return null;let o=U();for(let s of n)X(o,s,t);return q(o,(e==null?void 0:e.trim().toUpperCase())||void 0)}function Z(n,t=window){let e=V(n),o=t,s=t.document;switch(e.cmp){case"cookiebot":return{read:()=>{let r=o.Cookiebot,i=O(k(s,"CookieConsent"),e.category);return r!=null&&r.consent&&typeof r.consent[e.category]=="boolean"&&(r.hasResponse===!0||i===null)?r.consent[e.category]===!0:i},subscribe:r=>I(t,["CookiebotOnAccept","CookiebotOnDecline","CookiebotOnConsentReady","CookiebotOnLoad"],r),refused(){let r=o.Cookiebot;return((r==null?void 0:r.hasResponse)===!0||k(s,"CookieConsent")!==void 0)&&this.read()===!1}};case"onetrust":return{read:()=>{let r=o.OnetrustActiveGroups;return typeof r=="string"?`,${r},`.includes(`,${e.group},`):G(k(s,"OptanonConsent"),e.group)},subscribe:r=>I(t,["OneTrustGroupsUpdated"],r),refused(){return k(s,"OptanonAlertBoxClosed")!==void 0&&this.read()===!1}};case"cookieyes":return{read:()=>{var i;let r=o.getCkyConsent;if(typeof r=="function")try{let a=(i=r())==null?void 0:i.categories;if(a&&typeof a[e.category]=="boolean")return a[e.category]===!0}catch(a){}return L(k(s,"cookieyes-consent"),e.category)},subscribe:r=>I(t,["cookieyes_consent_update","cookieyes_banner_load","cookieyes_banner_loaded"],r),refused(){var a,u;let r=/(?:^|,)action:yes(?:,|$)/.test(P((a=k(s,"cookieyes-consent"))!=null?a:"")),i=o.getCkyConsent;if(!r&&typeof i=="function")try{r=((u=i())==null?void 0:u.isUserActionCompleted)===!0}catch(l){}return r&&this.read()===!1}};case"tcf":{let r=null,i=!1,a=!1;return{read:()=>r,refused:()=>r===!1&&!i&&a,subscribe:u=>{let l,f=!1,m=!1,d=(c,g)=>{var h,b,S,R;if(!g||f)return;typeof c.listenerId=="number"&&(l=c.listenerId),i=c.eventStatus==="cmpuishown",a=(c.eventStatus==="tcloaded"||c.eventStatus==="useractioncomplete")&&c.purposeOneTreatment!==!0&&c.gdprApplies!==!1&&((b=(h=c.purpose)==null?void 0:h.consents)==null?void 0:b[1])!==!0&&((R=(S=c.publisher)==null?void 0:S.consents)==null?void 0:R[1])!==!0;let w=c.eventStatus==="tcloaded"||c.eventStatus==="useractioncomplete";w&&(m=!0),i?r=!1:!w&&c.gdprApplies!==!1?m||(r=null):r=c.gdprApplies===!1||Y(c.purposeOneTreatment===!0?N(D({},e),{purposes:e.purposes.filter(v=>v!==1)}):e,v=>{var C,_,A,x;return((_=(C=c.purpose)==null?void 0:C.consents)==null?void 0:_[v])===!0||((x=(A=c.publisher)==null?void 0:A.consents)==null?void 0:x[v])===!0},v=>{var C,_,A,x;return((_=(C=c.purpose)==null?void 0:C.legitimateInterests)==null?void 0:_[v])===!0||((x=(A=c.publisher)==null?void 0:A.legitimateInterests)==null?void 0:x[v])===!0},v=>{var C,_;return((_=(C=c.vendor)==null?void 0:C.consents)==null?void 0:_[v])===!0})===!0,u()},p=0,y=()=>{if(f)return;let c=o.__tcfapi;typeof c=="function"?c("addEventListener",2,d):p++<40&&window.setTimeout(y,250)};return y(),()=>{f=!0;let c=o.__tcfapi;typeof c=="function"&&l!==void 0&&c("removeEventListener",2,()=>{},l)}}}}case"google-consent-mode":{let r=null,i=0,a=U(),u=()=>{let l=o[e.dataLayer];if(!Array.isArray(l))return null;for((l!==r||l.length<i)&&(r=l,i=0,a=U());i<l.length;i++)X(a,l[i],e.type);return q(a,e.region)};return{read:u,refused:()=>u()===!1&&he(a),subscribe:l=>{let f=new WeakSet,m=!1,d=[],p=-1,y=()=>{var w,h;let g=(h=o[w=e.dataLayer])!=null?h:o[w]=[];if(!f.has(g)){f.add(g);let b=g.push,S=function(...R){let v=b.apply(g,R);return p=g.length,m||l(),v};g.push=S,d.push(()=>{g.push===S&&(g.push=b)})}g.length!==p&&(p=g.length,l())};y();let c=window.setInterval(y,1e3);return()=>{m=!0,window.clearInterval(c);for(let g of d)g()}}}}case"shopify":{let r=e.category==="marketing"?"marketingAllowed":e.category==="preferences"?"preferencesProcessingAllowed":"analyticsProcessingAllowed";return{read:()=>{var a,u;let i=(u=(a=o.Shopify)==null?void 0:a.customerPrivacy)==null?void 0:u[r];if(typeof i!="function")return null;try{let l=i();return typeof l=="boolean"?l:null}catch(l){return null}},refused(){var a,u;let i=(a=o.Shopify)==null?void 0:a.customerPrivacy;if(typeof(i==null?void 0:i.currentVisitorConsent)!="function")return!1;try{return((u=i.currentVisitorConsent())==null?void 0:u[e.category])==="no"}catch(l){return!1}},subscribe:i=>{let a=I(t,["visitorConsentCollected"],i),u=!1,l=0,f=()=>{if(u)return;let m=o.Shopify;if(m!=null&&m.customerPrivacy){i();return}if(typeof(m==null?void 0:m.loadFeatures)=="function"){try{m.loadFeatures([{name:"consent-tracking-api",version:"0.1"}],d=>{!u&&!d&&i()})}catch(d){}return}l++<40&&window.setTimeout(f,250)};return f(),()=>{u=!0,a()}}}}case"custom":return{read:()=>{if(e.check)try{return e.check()===!0}catch(i){return!1}if(!e.cookie)return null;let r=k(s,e.cookie);return r===void 0?null:r===e.value},refused:()=>{var r;if(e.check)try{return((r=e.refused)==null?void 0:r.call(e))===!0}catch(i){return!1}return!!e.cookie&&k(s,e.cookie)!==void 0&&k(s,e.cookie)!==e.value},subscribe:r=>e.event?I(t,[e.event],r):()=>{}}}}function F(n){return n?`_${n.slice(0,12)}`:""}var E="_snt_uid";function ee(n){return`${E}${F(n)}`}var $="__sntForgetGen";function te(n){var t,e;try{let o=window,s=(t=o[$])!=null?t:o[$]={};s[n]=((e=s[n])!=null?e:0)+1}catch(o){}}var ne="_snt_snap:";var _e=56*1024;function oe(n){return`_snt_retry_${n.slice(0,12)}`}function re(n){return`_snt_goal_retry_${n.slice(0,12)}`}function se(n){let t=(n||"").toLowerCase();if(!t.includes(".")||/^[\d.]+$|:/.test(t))return[];let e=t.split("."),o=[];for(let s=e.length-2;s>=0;s--)o.push(e.slice(s).join("."));return o}function ie(n){if(typeof window=="undefined"||!n)return!1;te(n);let t=!1,e=ee(n);try{if(new RegExp(`(?:^|; )${e}=`).test(document.cookie)){let i=location.protocol==="https:"?"; Secure":"";for(let a of["",...se(location.hostname)])document.cookie=`${e}=; max-age=0; SameSite=lax; path=/${a?`; domain=${a}`:""}${i}`;t=!0}}catch(i){}let o=F(n),s=[e,"_snt_graph_edges",ne+n,oe(n),re(n),`_snt_graph_nodes${o}`],r=[`_snt_asgn${o}_`];for(let i of["localStorage","sessionStorage"])try{let a=window[i];for(let u of s)a.getItem(u)!==null&&(a.removeItem(u),t=!0);for(let u=a.length-1;u>=0;u--){let l=a.key(u);l&&r.some(f=>l.startsWith(f))&&(a.removeItem(l),t=!0)}}catch(a){}try{(new RegExp(`(?:^|; )${E}=[^;]`).test(document.cookie)||localStorage.getItem(E)!==null||sessionStorage.getItem(E)!==null)&&localStorage.setItem(`${E}_tomb${o}`,"1")}catch(i){}return t}0&&(module.exports={TCF_DEFAULT_PURPOSES,consentFromCookies,consentModeGranted,consentWatcher,cookiebotCookieGrants,cookieyesCookieGrants,forgetVisitor,onetrustCookieGrants,tcStringConsents,tcStringPurposes});
2
2
  //# sourceMappingURL=index-consent.js.map