@sentientui/core 0.37.0 → 0.38.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 (37) hide show
  1. package/dist/chunk-VLFWHJNJ.mjs +2 -0
  2. package/dist/chunk-VLFWHJNJ.mjs.map +1 -0
  3. package/dist/chunk-XZRKD2GS.mjs +2 -0
  4. package/dist/chunk-XZRKD2GS.mjs.map +1 -0
  5. package/dist/{index-C-meVCmm.d.cts → index-BdpO3Qlm.d.cts} +32 -2
  6. package/dist/{index-DbpGK3Dj.d.ts → index-DzGhQhSK.d.ts} +32 -2
  7. package/dist/index-consent.js.map +1 -1
  8. package/dist/index-consent.mjs +1 -1
  9. package/dist/index-engagement.js +1 -1
  10. package/dist/index-engagement.js.map +1 -1
  11. package/dist/index-engagement.mjs +1 -1
  12. package/dist/index-graph.d.cts +4 -4
  13. package/dist/index-graph.d.ts +4 -4
  14. package/dist/index-graph.js +1 -1
  15. package/dist/index-graph.js.map +1 -1
  16. package/dist/index-graph.mjs +1 -1
  17. package/dist/index-graph.mjs.map +1 -1
  18. package/dist/index-local.d.cts +2 -2
  19. package/dist/index-local.d.ts +2 -2
  20. package/dist/index-server.d.cts +7 -2
  21. package/dist/index-server.d.ts +7 -2
  22. package/dist/index-server.js +1 -1
  23. package/dist/index-server.js.map +1 -1
  24. package/dist/index-server.mjs +1 -1
  25. package/dist/index-server.mjs.map +1 -1
  26. package/dist/index.d.cts +2 -2
  27. package/dist/index.d.ts +2 -2
  28. package/dist/index.js +1 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/index.mjs +1 -1
  31. package/dist/{session-meta-DlCp0tyi.d.ts → session-meta-CvEwPQCX.d.ts} +6 -1
  32. package/dist/{session-meta-CJ-QAskZ.d.cts → session-meta-USVMwvsR.d.cts} +6 -1
  33. package/package.json +1 -1
  34. package/dist/chunk-5CCBWT6H.mjs +0 -2
  35. package/dist/chunk-5CCBWT6H.mjs.map +0 -1
  36. package/dist/chunk-DU3AXQHR.mjs +0 -2
  37. package/dist/chunk-DU3AXQHR.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index-engagement.ts","../src/engagement/classify.ts","../src/engagement/capture.ts","../src/index.ts","../src/micro-signals.ts","../src/locator-from-dom.ts","../src/engagement/interaction-stats.ts"],"sourcesContent":["// Lazy engagement entry — loaded on demand (mirrors ./graph) so the lean\n// bundle never carries the section classifier or IntersectionObserver logic.\nexport {\n startEngagementCapture,\n INTERACTION_STATS_COMPONENT,\n type EngagementCaptureOptions,\n type InteractionStats,\n} from './engagement/capture';\nexport {\n classifyFeatures,\n classifySection,\n featuresFromElement,\n SEMANTIC_TYPES,\n type SectionFeatures,\n type SemanticType,\n} from './engagement/classify';\n","// Semantic section classification for no-code section capture (Phase 3 §2.4).\n// Pure heuristic: element → one of the graph_nodes semantic_type enum. Mirrors\n// the SDK graph scanner's vocabulary so the persona × section matrix consumes\n// snippet-captured sections unchanged.\n//\n// SPLIT (Phase 2b, spec 2026-09-04). This module is the BROWSER-SAFE core:\n// structural rules, the small parent-level keyword table, and the fallbacks.\n// The rich ~40-topic vocabulary lives in ./topics.ts, which only the server\n// imports — shipping it here cost 1.5 KB gzip in every bundle (7% of the\n// always-on snippet) for a layer the browser never reads, since classifySection\n// returns only the parent.\n//\n// Both paths share structuralTopicOf/fallbackTopicOf, so the three fixes below\n// apply identically on client and server; only vocabulary richness differs.\n//\n// Fixes, each reproduced against the shipped classifier before being changed:\n// 1. structural before the converter fallback — `<div class=\"navbar\">` used\n// to become `cta`, because `navigation` was reachable only via tag\n// nav/footer.\n// 2. hero before the converter fallback — the cta rule sat above both hero\n// rules, so a `<header>` with a button and <200 chars could never be hero.\n// 3. tightened pricing/social keywords — `plans?` and `customers?` fired on\n// unrelated copy AND were `strong`, so they auto-applied at confidence 0.9\n// and were never sent to the LLM fallback.\n\nexport type SemanticType =\n | 'pricing' | 'hero' | 'social_proof' | 'cta' | 'features'\n | 'faq' | 'comparison' | 'trust' | 'navigation' | 'generic';\n\nexport type SectionRole = 'converter' | 'persuader' | 'structural';\n\n/** Canonical vocabulary — mirrors the graph_nodes semantic_type CHECK enum. */\nexport const SEMANTIC_TYPES: readonly SemanticType[] = [\n 'pricing', 'hero', 'social_proof', 'cta', 'features',\n 'faq', 'comparison', 'trust', 'navigation', 'generic',\n] as const;\n\nexport type TopicRule = { topic: string; parent: SemanticType; role: SectionRole };\n\n/** Environment-agnostic section features — buildable from a browser Element or\n * a server-parsed node (node-html-parser). */\nexport type SectionFeatures = {\n tag: string; // lowercase tag name\n idClass: string; // `${id} ${className}`\n headingText: string;\n bodyText: string; // normalized text content, first 2000 chars\n actionCount: number;\n textLength: number;\n /** ARIA landmark role, when the element declares one. Optional so every\n * existing caller keeps compiling; a page that uses landmarks gives a\n * high-precision signal for free, which the old classifier ignored — it\n * tested membership of SEMANTIC_TYPES, so only role=\"navigation\" ever hit\n * and role=\"banner\"/\"contentinfo\" were discarded. */\n ariaRole?: string;\n /** schema.org `@type` values found in `<script type=\"application/ld+json\">`\n * INSIDE this section. Highest-precision signal available and free to\n * collect — the crawler already has the HTML. Type-only here; the\n * `@type` → topic table is server-side in ./topics.ts, since the browser\n * never reads the topic layer and the snippet has ~200 bytes of margin. */\n structuredTypes?: string[];\n};\n\n// ARIA landmark → topic. Structural facts, not guesses.\nconst ARIA_TOPIC: Record<string, string> = {\n banner: 'hero',\n navigation: 'navigation',\n contentinfo: 'footer',\n};\n\n/**\n * Structural identification, shared by the browser and server classifiers.\n * Returns a topic name, or null when the section is not structural furniture.\n * Everything matched here is definitive (tag or authored marker), so callers\n * treat it as `strong`.\n */\nexport function structuralTopicOf(f: SectionFeatures): string | null {\n const aria = f.ariaRole ? ARIA_TOPIC[f.ariaRole.toLowerCase()] : undefined;\n if (aria) return aria;\n if (f.tag === 'nav') return 'navigation';\n if (f.tag === 'footer') return 'footer';\n // A page-level <header> IS the banner landmark (HTML-AAM maps it to\n // role=\"banner\", which this function already treats as hero), so it is a\n // structural fact rather than a keyword guess. Without this, a header whose\n // headline happens to contain a content word loses to the keyword table:\n // \"We build brands that move\" scored social_proof and \"Winter collection\"\n // scored features, purely on words inside the hero copy.\n //\n // …EXCEPT when the header IS the site's navigation. The hold-out corpus\n // (2026-09-05, six real unseen sites) showed most real pages wrap their nav\n // in <header> — mega-menus with 10–114 links and almost no prose — and\n // hero-typing those cost the classifier a 0.11 hero precision. A hero header\n // carries a headline and one or two calls to action; a nav header is\n // link-dominated, so the action count is the discriminator. Measured on the\n // hold-out: nav headers had 10+ actions (one at 4), authored hero headers\n // have 0–2.\n if (f.tag === 'header') return f.actionCount >= 5 ? 'navigation' : 'hero';\n const hay = `${f.idClass} ${f.headingText}`.toLowerCase();\n if (/\\b(navbar|nav-bar|navigation|site-nav|main-nav|topbar|footer)\\b/.test(hay)) {\n return /footer/.test(hay) ? 'footer' : 'navigation';\n }\n // Explicit authoring marker beats any inferred keyword, and is matched on\n // idClass ONLY: a `<header class=\"hero\">` headlined \"Expert Car Repair\" is a\n // hero, not a services section — but matching \"hero\" in heading text would\n // also catch \"Hero of the story\".\n if (/\\b(hero|masthead|jumbotron)\\b/i.test(f.idClass)) return 'hero';\n return null;\n}\n\n/**\n * Last-resort classification once no keyword or content evidence matched.\n * Hero is checked BEFORE the converter fallback — fix 2 above.\n */\nexport function fallbackTopicOf(f: SectionFeatures): string {\n // `tag === 'header'` is handled in structuralTopicOf, which runs first.\n if (f.actionCount >= 1 && f.textLength > 0 && f.textLength < 200) return 'cta';\n return 'generic';\n}\n\n// Parent-level keyword table for the BROWSER path. Deliberately close to the\n// original size — the rich topic vocabulary is in ./topics.ts. `plans?` now\n// requires adjacent pricing context, and bare `customers?` is gone (it fired on\n// navigation furniture like a \"Customer Service\" footer block).\nconst KEYWORDS: Array<[SemanticType, RegExp]> = [\n ['pricing', /\\b(pricing|price list|per month|\\/mo|subscriptions?)\\b|\\bplans?\\b(?=[^.]{0,40}(from|start|month|year|[$€£]))/i],\n ['faq', /\\bfaq\\b|frequently asked|common questions?/i],\n ['comparison', /\\b(compare|comparison|versus)\\b|\\bvs\\./i],\n ['social_proof', /\\b(reviews?|ratings?|testimonial|brands?|galler(y|ies)|logos)\\b|trusted by|loved by|case stud|what our customers say/i],\n ['trust', /\\b(insurance|warrant(y|ies)|guarantees?|certifi|accredit|security|privacy|compliance|gdpr|encrypt)\\b|why choose|about us|our team/i],\n ['cta', /\\b(book|booking|reserve|appointments?|newsletter|subscribe)\\b|contact us|get in touch|opening hours/i],\n ['features', /\\b(features?|benefits?|capabilit|services?|repairs?|menus?|products?)\\b|how it works|our process|what we (do|offer)|what you get/i],\n];\n\n// Content-evidence patterns — run against bodyText when the heading gave us\n// nothing. Deliberately conservative: pricing needs per-period/plan context next\n// to money so an article mentioning \"$5 million\" stays generic.\nexport const CONTENT_PATTERNS: Array<[SemanticType, RegExp]> = [\n ['pricing', /(?:[$€£]\\s?\\d[\\d,.]*\\s*(?:\\/|per\\s)\\s*(?:mo|month|yr|year|seat|user))|(?:\\b(?:starter|basic|pro|growth|premium|enterprise)\\b[^.]{0,60}[$€£]\\s?\\d)/i],\n ['social_proof', /(?:★{2,})|(?:\\b\\d(?:\\.\\d)?\\s*(?:out of|\\/)\\s*5\\b)|(?:\\brated\\b)|(?:[\"“][^\"”]{20,160}[\"”]\\s*[—–-]\\s*[A-Z][a-z]+)/],\n ['trust', /\\b(?:money[- ]back guarantee|free returns?|returns? within|refund(?:s)? within|encrypted|soc ?2|iso ?27001|gdpr[- ]compliant|cancel anytime)\\b/i],\n ['comparison', /\\b(?:vs|versus)\\b\\.?[^.!?]{0,80}\\b(?:compare|comparison|plans?|features?|alternative)\\b|\\bhow (?:we|it) compares?\\b/i],\n];\n\n/** Parent for the handful of topics the shared structural/fallback helpers\n * emit. The server maps the full vocabulary via CLASSIFIER_TOPICS instead. */\nconst SHARED_TOPIC_PARENT: Record<string, SemanticType> = {\n navigation: 'navigation',\n footer: 'navigation',\n hero: 'hero',\n cta: 'cta',\n generic: 'generic',\n};\n\nfunction headingText(el: Element): string {\n const h = el.querySelector('h1, h2, h3');\n return (h?.textContent ?? '').slice(0, 160);\n}\n\n/**\n * Pure classification over extracted features. `strong` = keyword, content, or\n * structural evidence (trustable enough to auto-apply); `weak` = a fallback\n * guess (hero/cta/generic — capture-worthy but not persona evidence).\n */\nexport function classifyFeatures(f: SectionFeatures): { type: SemanticType; strength: 'strong' | 'weak' } {\n const structural = structuralTopicOf(f);\n if (structural) return { type: SHARED_TOPIC_PARENT[structural] ?? 'generic', strength: 'strong' };\n\n const hay = `${f.idClass} ${f.headingText}`.toLowerCase();\n for (const [type, re] of KEYWORDS) if (re.test(hay)) return { type, strength: 'strong' };\n for (const [type, re] of CONTENT_PATTERNS) if (re.test(f.bodyText)) return { type, strength: 'strong' };\n\n const fb = fallbackTopicOf(f);\n return { type: SHARED_TOPIC_PARENT[fb] ?? 'generic', strength: 'weak' };\n}\n\n/** Feature extraction from a live DOM element (browser paths). */\nexport function featuresFromElement(el: Element): SectionFeatures {\n const text = (el.textContent ?? '').replace(/\\s+/g, ' ').trim();\n const role = el.getAttribute('role');\n return {\n tag: el.tagName.toLowerCase(),\n idClass: `${el.id} ${String(el.className ?? '')}`,\n headingText: headingText(el),\n bodyText: text.slice(0, 2000),\n actionCount: el.querySelectorAll('a, button, [role=\"button\"]').length,\n textLength: text.length,\n ...(role ? { ariaRole: role } : {}),\n };\n}\n\n/** Classify a page section into a semantic type (never null — falls back to\n * 'generic' so the caller can still capture attention on it). */\nexport function classifySection(el: Element): SemanticType {\n return classifyFeatures(featuresFromElement(el)).type;\n}\n","import {\n classifyFeatures,\n featuresFromElement,\n CONTENT_PATTERNS,\n SEMANTIC_TYPES,\n type SemanticType,\n} from './classify';\nimport { fnv1a } from '@sentientui/policy';\nimport { isDoNotTrackEnabled } from '../index.js';\nimport { attachMicroSignalDetectors } from '../micro-signals.js';\nimport { locatorFromElement } from '../locator-from-dom.js';\nimport { startInteractionCollector, type InteractionStats } from './interaction-stats.js';\n\n// Shared engagement capture (spec 2026-07-22-persona-signal-capture). Detects\n// semantic sections, registers them via /v1/section-map, and records per-section\n// dwell/scroll via IntersectionObserver — emitting the same 'dwell' events the\n// persona pipeline consumes. Used by the React provider (default on) and the\n// no-code snippet. Defense-in-depth: checks DNT internally even though callers\n// gate on consent/DNT too; a missing IntersectionObserver → no-op.\n\ntype CaptureClient = {\n track(event: { projectId: string; componentId: string; eventType: string; payload: Record<string, unknown> }): void;\n /** Drain the event queue now. Optional so an embedder can pass a bare\n * tracker, but every first-party client has it — see the leave-path flush\n * in `emit`, which is what makes a short visit deliverable at all. */\n flush?(): void;\n};\n\nexport type EngagementCaptureOptions = {\n apiKey: string;\n /** API base, no trailing slash. Defaults to the hosted API. */\n apiBase?: string;\n doc?: Document;\n /**\n * Also attach per-section micro-signal detectors (rage click, text copy,\n * scroll hesitation, tab loss), attributed to the section's per-element `nc-*`\n * component. For the no-code snippet, whose pages have no `<Adaptive>`\n * components carrying their own detectors. Default false — the React SDK\n * keeps its per-component detectors and must not double-attach.\n */\n microSignals?: boolean;\n /**\n * Section types declared in code, keyed by `data-sentient-id`. The highest\n * precedence — the same map the graph scanner receives, so capture and the\n * graph never disagree on what a declared section is.\n */\n sectionTypes?: Readonly<Partial<Record<string, string>>>;\n /**\n * Server-served section-map lookup (persona-coverage auto-classification):\n * consulted after declared types and legacy `data-sentient-type` markup,\n * before the local heuristic. Return null when the element has no served label.\n */\n typeOf?: (el: Element) => SemanticType | null;\n};\n\nconst SECTION_SELECTOR = 'section, header, footer, nav, main > div, [data-sentient-section]';\n\n/** Bank cadence for visible dwell. Dwell used to leave the page only on\n * visibilitychange/pagehide, and in production that path delivered for ~5-8%\n * of sessions (Bodyshop audit 2026-08-30): a visitor who reads and closes the\n * tab races the unload pipeline, and mobile browsers can kill a page with no\n * lifecycle event at all. The heartbeat caps the loss at one interval. */\nconst HEARTBEAT_MS = 20_000;\n\n/** Sentinel component for the session-level interaction snapshot — same\n * pattern as pageview's `__page__`: not a component, never attributed to one.\n * Every report producer filters `raw_events` by event_type, so the sentinel\n * cannot leak into a component table. */\nexport const INTERACTION_STATS_COMPONENT = '__session__';\nexport type { InteractionStats };\n\n/**\n * Pick the elements to observe. Two rules, in order:\n * 1. A candidate that CONTAINS two or more other candidates is a layout\n * wrapper, not a section — drop it. Pages built from bare divs match\n * `main > div` with their page-wide content wrapper; keeping that outer\n * match swallowed every real <section> inside it, collapsing the whole page\n * into one nc-generic component whose intersectionRatio could never exceed\n * viewport-height / page-height (a constant ~0.05 scroll_depth on the\n * audited site). A candidate with exactly one nested candidate (header >\n * nav) is NOT a wrapper — rule 2 keeps the outer one, as before.\n * 2. Of what remains, skip a section nested inside another kept section\n * (avoid double count).\n */\nfunction selectSections(doc: Document): Element[] {\n const candidates = Array.from(doc.querySelectorAll(SECTION_SELECTOR));\n const kept = candidates.filter(\n (el) => candidates.filter((c) => c !== el && el.contains(c)).length < 2,\n );\n return kept.filter((el) => !kept.some((k) => k !== el && k.contains(el)));\n}\n\n/** Client-sensor observation riding each section-map entry (spec 2026-09-04\n * §2): structure, headings, and which CONTENT_PATTERNS matched — never body\n * text, so nothing beyond headings leaves the page. Lets the server's richer\n * topic classifier label pages the crawler cannot fetch (CSR, auth-walled). */\ntype SectionObservation = {\n tag: string;\n idClass: string;\n headingText: string;\n textLength: number;\n actionCount: number;\n ariaRole?: string;\n patternFlags?: SemanticType[];\n};\n\nfunction registerSections(\n apiKey: string,\n apiBase: string,\n pageUrl: string,\n sections: Array<{\n componentId: string;\n semanticType: SemanticType;\n source: 'markup' | 'auto';\n locator?: unknown;\n observation?: SectionObservation;\n }>,\n): void {\n try {\n void fetch(`${apiBase}/v1/section-map`, {\n method: 'POST',\n keepalive: true,\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify({ pageUrl, sections }),\n }).catch(() => undefined);\n } catch {\n /* fail-safe */\n }\n}\n\nconst NOOP = (): void => undefined;\n\nexport function startEngagementCapture(\n client: CaptureClient,\n opts: EngagementCaptureOptions,\n): () => void {\n const doc = opts.doc ?? (typeof document !== 'undefined' ? document : undefined);\n if (!doc || typeof IntersectionObserver === 'undefined') return NOOP;\n if (isDoNotTrackEnabled()) return NOOP;\n // Keyless zero-network contract: capture exists to feed the hosted persona\n // pipeline — with no api key there is nothing to feed, and the section-map\n // registration fetch must never fire. Same validity rule as init() and the\n // graph entry: this used to check truthiness only, so an invalid non-`pk_`\n // (typo'd) key still fired /v1/section-map registration and dwell events\n // into a client that discards everything.\n if (!opts.apiKey || !opts.apiKey.startsWith('pk_')) return NOOP;\n // Normalize so both a ROOT base (`https://api.sentient-ui.com`) and a\n // `/v1`-suffixed base resolve to exactly one `/v1/section-map` — some callers\n // pass the versioned base, which would otherwise produce `/v1/v1/section-map`\n // (a silent 404). Strip trailing slashes, then a single trailing `/v1`.\n const apiBase = (opts.apiBase ?? 'https://api.sentient-ui.com')\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '');\n\n const els = selectSections(doc);\n if (els.length === 0) return NOOP;\n\n // One component per ELEMENT (nc-* retirement, 2026-09-05): the id carries a\n // short locator hash — `nc-<type>-<hash>` — so two same-typed bands no longer\n // collapse into one row with summed dwell, which is what made \"which features\n // band holds attention?\" unanswerable. The hash is over the locator's\n // identity fields (the same subset section_key hashes server-side), so the id\n // is stable across visits. An element with no resolvable locator falls back\n // to the collapsed `nc-<type>` — no identity means no better name exists.\n // The type-level matrix is unaffected (it aggregates via graph_nodes\n // semantic_type); pre-change dwell history stays keyed to collapsed ids and\n // ages out of the reporting windows.\n // Per-element precedence: declared sectionTypes (by data-sentient-id) →\n // legacy data-sentient-type markup → served section map (opts.typeOf) →\n // local heuristic. Declared and markup types both report source 'markup':\n // they are author-asserted, not inferred.\n const componentOf = new Map<Element, string>();\n const entries: Array<{\n componentId: string;\n semanticType: SemanticType;\n source: 'markup' | 'auto';\n locator?: unknown;\n observation?: SectionObservation;\n }> = [];\n for (const el of els) {\n const markup = [\n opts.sectionTypes?.[el.getAttribute('data-sentient-id') ?? ''],\n el.getAttribute('data-sentient-type'),\n ].find((t): t is SemanticType => (SEMANTIC_TYPES as readonly unknown[]).includes(t)) ?? null;\n const f = featuresFromElement(el);\n const type = markup ?? opts.typeOf?.(el) ?? classifyFeatures(f).type;\n const locator = locatorFromElement(el, doc) as\n | { id?: string; dataAttr?: unknown; selector?: string }\n | null;\n const componentId = locator\n ? `nc-${type}-${fnv1a(\n JSON.stringify({ id: locator.id ?? null, dataAttr: locator.dataAttr ?? null, selector: locator.selector ?? null }),\n ).toString(36)}`\n : `nc-${type}`;\n componentOf.set(el, componentId);\n // Client-sensor observation: which shipped CONTENT_PATTERNS matched the\n // body text (booleans — the text itself never leaves the page), plus the\n // structural features the server classifier keys on.\n const patternFlags = CONTENT_PATTERNS.filter(([, re]) => re.test(f.bodyText)).map(([t]) => t);\n entries.push({\n componentId,\n semanticType: type,\n // `source` is per ELEMENT: with one row per section the server records\n // each section's real provenance, not the most-confident of its siblings'.\n source: markup ? 'markup' : 'auto',\n ...(locator ? { locator } : {}),\n observation: {\n tag: f.tag,\n idClass: f.idClass.slice(0, 200),\n headingText: f.headingText,\n textLength: f.textLength,\n actionCount: f.actionCount,\n ...(f.ariaRole ? { ariaRole: f.ariaRole } : {}),\n ...(patternFlags.length > 0 ? { patternFlags } : {}),\n },\n });\n }\n\n const pageUrl = (doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined))?.location?.pathname ?? '/';\n registerSections(opts.apiKey, apiBase, pageUrl, entries);\n\n // Browser-agent axis (spec 2026-09-22 §4.1): passive interaction aggregates,\n // emitted at the same bank points as dwell. Same DNT/key gate — we are past\n // both checks here — and the collector itself never touches the network.\n const interaction = startInteractionCollector(doc);\n // EVERY visit reports, however short. There used to be an 8 s floor here, on\n // the reasoning that a bounce has too few events for an aggregate to mean\n // anything. True of the aggregate, wrong as a place to act on it: a 2 s read\n // on a phone is a real visit, and suppressing it left the scorer unable to\n // tell that visitor from a JS-less crawler — the population that already\n // makes up 83% of the \"human\" sessions on the busiest prod project. Whether\n // a snapshot is thin enough to ignore is a SCORING question, and it now\n // lives with the scorer (a snapshot that fires no positive reason keeps\n // `client_js_present`), where the threshold can move without an SDK release.\n const emitInteraction = (): void => {\n let snap: InteractionStats;\n try { snap = interaction.snapshot(); } catch { return; }\n try {\n client.track({\n projectId: opts.apiKey,\n componentId: INTERACTION_STATS_COMPONENT,\n eventType: 'interaction_stats',\n payload: snap as unknown as Record<string, unknown>,\n });\n } catch {\n /* fail-safe */\n }\n };\n\n // Accumulate visible dwell (ms) + max scroll ratio per component. `intersecting`\n // tracks in-viewport state independently of `enterAt` (the running clock) so a\n // tab-hide can pause the clock and a tab-show can resume it for still-visible\n // sections — IntersectionObserver does not re-fire on visibilitychange.\n const state = new Map<string, { ms: number; scroll: number; enterAt: number | null; intersecting: boolean }>();\n const get = (id: string) => {\n let s = state.get(id);\n if (!s) { s = { ms: 0, scroll: 0, enterAt: null, intersecting: false }; state.set(id, s); }\n return s;\n };\n\n const observer = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n const id = componentOf.get(entry.target);\n if (!id) continue;\n const s = get(id);\n if (entry.isIntersecting) {\n s.intersecting = true;\n s.enterAt = Date.now();\n if (entry.intersectionRatio > s.scroll) s.scroll = entry.intersectionRatio;\n } else {\n s.intersecting = false;\n if (s.enterAt != null) { s.ms += Date.now() - s.enterAt; s.enterAt = null; }\n }\n }\n }, { threshold: [0, 0.25, 0.5, 0.75, 1] });\n for (const el of componentOf.keys()) observer.observe(el);\n\n // Bank accumulated dwell and RESET the accumulators (so a later emit can't\n // double-count) WITHOUT disconnecting — a visitor who hides/re-shows the tab\n // or tab-switches keeps being measured. Pauses the running clock; the tab-show\n // handler restarts it for still-visible sections so hidden time isn't counted.\n // `leaving` marks the paths where the page may not exist a tick from now.\n // The queue installed its OWN pagehide/visibilitychange flush when the\n // client was constructed — before this module was imported — so on those\n // events it drains first and everything banked below is enqueued after the\n // drain has already happened. With a 5 s queue timer and a 20 s heartbeat,\n // a visit shorter than either delivered nothing: measured at ~5-8% on the\n // leave path (Bodyshop audit 2026-08-30). Flushing here, after the bank,\n // is what closes that. Not on the heartbeat: the page is alive, the queue's\n // own timer covers it, and flushing every 20 s would double the requests.\n const emit = (leaving = false): void => {\n const now = Date.now();\n for (const [id, s] of state) {\n if (s.enterAt != null) { s.ms += now - s.enterAt; s.enterAt = null; }\n if (s.ms <= 0) continue;\n try {\n client.track({\n projectId: opts.apiKey, // SDK convention: server derives the real project from the key\n componentId: id,\n eventType: 'dwell',\n payload: { dwell_time: Math.round(s.ms), scroll_depth: Number(s.scroll.toFixed(2)) },\n });\n } catch {\n /* fail-safe */\n }\n s.ms = 0;\n }\n emitInteraction();\n if (leaving) {\n try { client.flush?.(); } catch { /* fail-safe */ }\n }\n };\n\n const onVisibility = (): void => {\n if (doc.hidden) {\n emit(true); // bank + pause + drain: on mobile this IS the leave path\n } else {\n const now = Date.now(); // resume the clock for sections still on screen\n for (const s of state.values()) if (s.intersecting) s.enterAt = now;\n }\n };\n // A page can be FROZEN into the bfcache rather than torn down. Timers keep\n // firing on restore, and `intersecting` still holds whatever it held at\n // pagehide — so without this the heartbeat kept banking dwell for sections the\n // visitor had scrolled far past, forever, while the observer that could have\n // corrected them had been disconnected. Freeze the clocks instead, and only\n // tear down for real when the page is genuinely going away.\n let frozen = false;\n const onPageHide = (event?: { persisted?: boolean }): void => {\n emit(true); // bank whatever is measured either way, then drain\n if (event?.persisted) {\n frozen = true; // bfcache: keep the observer, stop counting\n return;\n }\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n const onPageShow = (event?: { persisted?: boolean }): void => {\n if (!event?.persisted || !frozen) return;\n frozen = false;\n // The observer stayed connected, so it will correct `intersecting` for\n // anything that moved. Restart clocks only for what is on screen NOW.\n const now = Date.now();\n for (const s of state.values()) s.enterAt = s.intersecting && !doc.hidden ? now : null;\n };\n doc.addEventListener('visibilitychange', onVisibility);\n const win = doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined);\n win?.addEventListener('pagehide', onPageHide);\n win?.addEventListener('pageshow', onPageShow);\n\n // See HEARTBEAT_MS: bank visible dwell periodically so a hard close (or a\n // mobile page kill) loses at most one interval instead of the whole visit.\n // Hidden tabs skip the emit — their clock is already paused, and an empty\n // state map makes emit a no-op anyway.\n const heartbeat = setInterval(() => {\n if (doc.hidden || frozen) return;\n emit();\n // emit() pauses every running clock and only the tab-show handler restarts\n // them — here the page never went hidden, so restart the clock ourselves\n // or accumulation silently stops after the first heartbeat.\n const now = Date.now();\n for (const s of state.values()) if (s.intersecting) s.enterAt = now;\n }, HEARTBEAT_MS);\n\n // Per-section micro-signal detectors (opt-in; see EngagementCaptureOptions).\n // Attributed to the section's per-element nc-* id with no variant — they feed the\n // persona attention fallback and auto-discovery, never rewards.\n const detectorCleanups: Array<() => void> = [];\n if (opts.microSignals) {\n // tab_loss is a single document-level `visibilitychange` signal, so enabling\n // it on every section detector would emit one tab_loss per section\n // on a single tab-hide — attributing one page-level exit to every section\n // (audit M5). Enable it on only the first section so the exit is recorded\n // once, mirroring the per-option path in slot-signals.ts ({ tabLoss: index === 0 }).\n [...componentOf.entries()].forEach(([el, componentId], i) => {\n detectorCleanups.push(\n attachMicroSignalDetectors((signalType, extra = {}) => {\n try {\n client.track({\n projectId: opts.apiKey,\n componentId,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n } catch {\n /* fail-safe */\n }\n }, el, undefined, { tabLoss: i === 0 }),\n );\n });\n }\n\n // Cleanup: bank any remaining dwell, then detach everything (provider unmount\n // / consent re-init must not leak observers or listeners).\n return () => {\n emit(true);\n clearInterval(heartbeat);\n interaction.stop();\n doc.removeEventListener('visibilitychange', onVisibility);\n win?.removeEventListener('pagehide', onPageHide);\n win?.removeEventListener('pageshow', onPageShow);\n for (const c of detectorCleanups) c();\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n}\n","import { DECIDE_TIMEOUT_MS, REQUEST_TIMEOUT_MS, SESSION_WAIT_MS, settlesWithin, timeoutSignal } from './timeout.js';\nimport { setCspNonce } from './csp-nonce.js';\nimport { forgetVisitor } from './forget.js';\nimport { forgetGeneration, markForgotten, storageSuffix } from './storage-key.js';\nimport { initSession, type SessionConfig, type SessionManager } from './session';\nimport {\n createEventQueue,\n retryStorageKey,\n type EventQueue,\n type EventType,\n type QueueConfig,\n type SentientEvent,\n} from './queue';\nimport {\n createGoalQueue,\n goalRetryStorageKey,\n type GoalQueue,\n} from './goal-queue';\nimport {\n createAssignmentCache,\n type Assignment,\n} from './cache';\nimport type {\n GraphConfig,\n GraphSnapshot,\n} from './graph';\nimport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n extractTrackedParams,\n referrerDomainFromReferer,\n uaTokenMatch,\n} from './session-meta.js';\nimport {\n toWireSlot,\n baselineResultFor,\n armOfResult,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\nimport { readSnapshot, writeSnapshot, SNAPSHOT_STORAGE_KEY_PREFIX, type SlotConfigEntry, type CompoundLocator } from './snapshot.js';\nimport type { RegionSkeleton, RenderCaps } from './region-skeleton.js';\n\n/** A captured skeleton, or why none could be captured. */\nexport type SkeletonReport = RegionSkeleton | { status: 'too_large' | 'empty' | 'unaddressable' };\n/** One authored arm of a hybrid <Adaptive>, as it rendered. */\nexport type AuthoredArmReport = { key: string; text?: string; skeleton?: RegionSkeleton };\nimport { confidenceBand } from '@sentientui/policy';\nimport { createLocalModeClient } from './local-mode.js';\nimport { randomUuidV4 } from './uuid.js';\nimport { backoffDelayMs, classifyResponse } from './durable.js';\n\n// Never `process?.env` — optional chaining still throws ReferenceError on an\n// undeclared global, and browsers without a bundler shim (raw esbuild, vanilla\n// script tags) have no `process`. Same declaration @sentientui/react carries.\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\n/** True unless NODE_ENV is 'production' — gates integrator-facing dev warnings. */\nfunction isDevBuild(): boolean {\n return typeof process === 'undefined' || process.env?.NODE_ENV !== 'production';\n}\n\nexport { PROD_KEYLESS_ERROR, LOCAL_MODE_BANNER } from './local-mode.js';\n\n// The one source of truth for the session cookie's name — every out-of-package\n// reader (react devtools, integrator SSR code) must derive the name from this\n// instead of hard-coding `_snt_uid`, which is only the pre-namespacing fallback.\nexport { sessionCookieName, LEGACY_SESSION_COOKIE_NAME } from './storage-key.js';\n\nexport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n deriveSessionSegment,\n extractTrackedParams,\n CLICK_ID_KEYS,\n referrerDomainFromReferer,\n uaTokenMatch,\n matchedAgentToken,\n agentUaList,\n agentIntent,\n classifiedAgents,\n AGENT_INTENTS,\n} from './session-meta.js';\nexport type { AgentIntent } from './session-meta.js';\n\nconst DEFAULT_INGEST_URL = 'https://api.sentient-ui.com/v1/events';\n\n// Keyed by apiKey so multiple init() calls (HMR, multi-project) don't collide.\nconst _clients = new Map<string, {\n config: SentientConfig;\n upgrade: ((c: SentientClient) => void) | null;\n // Why grantConsent() cannot upgrade this entry (keyless/local mode, invalid\n // key). grantConsent() warns with this instead of silently no-oping — a CMP\n // callback wired to it otherwise LOOKED like it worked while nothing ever\n // started tracking. Absent for entries where the silent no-op IS the\n // documented contract (DNT-blocked, already upgraded).\n upgradeBlockedReason?: string;\n // Set by an alternate entry point (the /graph entry) whose gated init\n // deferred extra resources: grantConsent() must re-run THAT entry's init —\n // upgrading through the lean init() produced a post-consent client that\n // never mounted the DOM scanner, silently losing graph capture.\n reinit?: (c: SentientConfig) => SentientClient;\n // Teardown for the live client bound to this key (stops its queue interval +\n // unload listeners). Present only for the full tracking client; the no-op /\n // pre-consent / local entries have nothing to tear down. Called before a\n // re-init for the same key replaces it, so timers/listeners can't leak.\n dispose?: () => void;\n}>();\nlet _lastApiKey: string | null = null;\n\n/**\n * @internal Wires an alternate entry point's init as grantConsent()'s upgrade\n * path for `apiKey`. The /graph entry calls this when its init is gated on\n * consent: without it, grantConsent() upgraded through the LEAN init, so a\n * graph-configured page granted consent but never mounted the scanner (the\n * graph resources exist only in the /graph entry). No-op unless the entry is\n * actually upgradeable — DNT-blocked and local entries register no hook.\n */\nexport function _registerConsentUpgradeInit(\n apiKey: string,\n reinit: (config: SentientConfig) => SentientClient,\n): void {\n const entry = _clients.get(apiKey);\n if (entry && entry.upgrade) entry.reinit = reinit;\n}\n\nexport type SentientConfig = {\n apiKey: string;\n /**\n * @deprecated Unused — the project's type is set in the dashboard. Safe to omit.\n * Still accepted so existing installs keep type-checking; nothing reads it.\n */\n context?: 'landing' | 'ecommerce' | 'saas' | 'marketplace';\n /** @internal — not exposed to users; defaults to the hosted SentientUI API. */\n ingestUrl?: string;\n debug?: boolean;\n /**\n * Pre-seeded assignments from `preloadAssignments()` (SSR).\n * Seeds the local cache so `assign()` returns without a network call for\n * listed code variants, guaranteeing server and client render the same\n * variant on first paint. Managed-text components (assign with no\n * variantIds) still fetch once when the seed carries no content.\n */\n initialAssignments?: Record<string, string>;\n /**\n * Segment used for SSR preload (`device:source`). When set with `initialAssignments`,\n * seeds the assignment cache under this key so hydration matches the server bandit row.\n */\n sessionSegment?: string;\n /**\n * Consent gate. When `false`, returns a no-op client and performs no tracking.\n * Defaults to `true`. Re-call `init()` (via `AdaptiveProvider` consent prop) when\n * the user grants or revokes consent mid-session.\n */\n consent?: boolean;\n /**\n * Behavior before consent is granted. `'statistical_winner'` fetches the\n * best-performing variant via `GET /v1/winner` — no session or tracking data\n * is stored. `'control'` (default) shows `variantIds[0]` with no API call.\n * Applies when tracking is gated off — either `consent: false` or an active\n * Do Not Track signal.\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Whether to honor the browser's Do Not Track (DNT) signal. Defaults to `true`.\n * When `true` and the visitor has DNT enabled, the SDK sets no cookies and\n * sends no tracking data — behaving exactly as `consent: false` (still serving\n * the read-only `preConsentBehavior` winner if configured), and `grantConsent()`\n * will not upgrade it. Set `false` to make your own consent gate authoritative.\n */\n respectDoNotTrack?: boolean;\n userId?: string;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. 'admin', 'evaluator'). Must be a key in the project's persona\n * vocabulary (dashboard → Settings → Personas); unrecognized values are\n * ignored server-side and surfaced in the dashboard so you can add them.\n * Declared personas are served at full confidence, overriding the inferred\n * one. Keep it a low-cardinality role label — never a user id or email.\n */\n persona?: string;\n /**\n * Session ID generated server-side (from `loadAdaptiveAssignments` / `loadAdaptiveDecision`).\n * When provided, the client adopts this ID on first visit instead of generating a new one,\n * ensuring events and goals are attributed to the same session the server used for assignment.\n */\n ssrSessionId?: string;\n /**\n * ISO 3166-1 alpha-2 country code for the visitor. When provided (e.g. from\n * the `CF-IPCountry` header in a Next.js server component), it is included in\n * the session upsert so country-based segmentation works without client-side\n * geo lookup.\n */\n country?: string;\n /**\n * Pre-seeded slot results from `preloadDecisions()` / `loadAdaptiveDecision()`\n * (SSR). Seeds the local slot state so `getSlotResult()` agrees with the\n * server-rendered markup on first paint.\n */\n initialSlots?: Record<string, SlotResult>;\n /**\n * Registry slot config decided outside the browser (SSR). Seeds\n * `getSlotConfig()` so server-rendered block/content arms survive hydration.\n */\n initialSlotConfig?: Record<string, SlotConfigEntry>;\n /** Site palette decided outside the browser (SSR). Seeds `getSitePalette()`. */\n initialPalette?: import('./blocks.js').SitePalette;\n /** Site styles the SSR decision's Redesign arms borrow. Seeds `getStyleVocabulary()`. */\n initialVocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n /**\n * Persona decided during SSR. Takes priority over the html-attribute\n * adoption and the local snapshot.\n */\n initialPersona?: { persona: string; confidence: number };\n /**\n * Keyless local mode. 'auto' (default) simulates decisions on-device when no\n * valid API key is configured — but only in development builds (the\n * `development` export condition); production bundles physically exclude the\n * engine. `true` forces the local engine regardless of key (escape hatch);\n * `false` restores the silent keyless no-op.\n */\n localMode?: 'auto' | boolean;\n /**\n * Which integration surface is driving this client, and its released build\n * version — `{ name: 'react', version: '0.27.0' }`. Set by the wrapper\n * package (@sentientui/react, @sentientui/snippet), never by application\n * code: core is a dependency of both, so its own version says nothing about\n * what the customer installed.\n *\n * Rides the session upsert (the one call EVERY integration makes, unlike\n * decide, which only the slot paths use) so the dashboard can tell a project\n * its SDK is behind. Additive and best-effort: older API deployments ignore\n * the fields, and omitting it changes nothing.\n */\n sdk?: { name: string; version: string };\n /**\n * CSP nonce for the <style> elements the SDK injects (the adaptation\n * reveal). Without one the page's CSP needs `style-src 'unsafe-inline'`.\n * Defaults to the nonce of a script already on the page.\n */\n nonce?: string;\n};\n\nexport type AssignResult = { variantId: string; assignmentTtlMs: number; content?: string };\n\nexport type { SlotDeclInput, SlotResult };\nexport { armOfResult, baselineResultFor, baselineSlots, toWireSlot } from './slots.js';\n\nexport {\n SNAPSHOT_STORAGE_KEY_PREFIX,\n readSnapshot,\n writeSnapshot,\n renderPrePaintScript,\n} from './snapshot.js';\nexport type { DecisionSnapshot, SlotConfigEntry, SlotOps, CompoundLocator } from './snapshot.js';\nexport { pageScopeMatches, PAGE_SCOPE_RE } from './page-scope.js';\nexport * from './blocks.js';\nexport * from './region-skeleton.js';\n// Types only: the vocabulary's runtime constants (roles, id pattern, caps) are\n// server/editor concerns and live on `@sentientui/core/style-sample`, so the\n// lean bundle every visitor downloads doesn't carry them.\nexport type { StyleRole, StyleEntry, SiteImage, StyleVocabulary, ComposeArm } from './style-vocabulary.js';\n// Consent sources: the runtime is `@sentientui/core/consent` (loaded only by\n// installs that configure a consent platform); the types live here.\nexport type { ConsentSource, ConsentPreset, ConsentWatcher } from './consent-sources.js';\n\n/** An editor-defined goal delivered with a registry-mode decision, for the\n * snippet to install delegated listeners from. */\nexport type GoalDefinition = {\n goalId: string;\n event: 'click' | 'form_submit' | 'url_reached' | 'scroll_depth';\n locator?: CompoundLocator;\n urlPattern?: string;\n slotId?: string;\n /** scroll_depth only: fraction of the page (0–1] that counts as read. */\n threshold?: number;\n};\n\n/** One served section-classification row (registry mode): where it is on the\n * page (url match + compound locator) and its semantic type. The snippet\n * resolves the locator to build capture's `typeOf` hook. */\nexport type SectionMapEntry = {\n urlMatch: string;\n locator: CompoundLocator;\n type: string;\n};\n\nexport type DecideOutcome = {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n // Registry mode only: where/what to apply for server-defined slots.\n slotConfig?: Record<string, SlotConfigEntry>;\n // Registry mode only: editor-defined goals to wire up.\n goals?: GoalDefinition[];\n // Registry mode only: served section-classification map the snippet turns\n // into capture's `typeOf` hook.\n sectionMap?: SectionMapEntry[];\n // Registry mode only: derived site palette for Composition Block rendering.\n palette?: import('./blocks.js').SitePalette;\n // Registry mode only: the site styles served Redesign arms borrow.\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n};\n\nexport type DecideInput = {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n // 'registry' → serve the project's published slot_definitions in addition to\n // any declared slots (registry wins on id collision). Default 'request'.\n slotsFrom?: 'request' | 'registry';\n /** Registry mode only: decide just these published slot ids (1–50) instead\n * of every published slot — see `requestSlots`. */\n registrySlotIds?: string[];\n /** Registry mode only: `false` omits the snippet bootstrap data (editor goals,\n * section map) the React SDK never reads — two queries per page saved. */\n bootstrap?: false;\n /** Registry mode only: what the page can render per mounted slot. The\n * server narrows each slot's arm space to it before drawing (CONTRACTS §2\n * — an arm the page would refuse still books a trial). */\n render?: Record<string, RenderCaps>;\n /**\n * Caller's build version (e.g. the snippet's `__SNIPPET_VERSION__`), sent\n * as `v` on the wire. Additive/best-effort: the server persists it for\n * version-skew reporting (see apps/api decide route) and ignores it\n * entirely on older deployments. Omit if the caller has no version to report.\n */\n v?: string;\n /**\n * Snippet only: which inline pre-paint contract the install carries\n * (`window.__sntPP.v`), or 0 for the two-tag install with no inline script.\n * Sent as `pp` alongside `v`; the server persists it for the dashboard's\n * install-health nudge and no serving behaviour depends on it. Additive —\n * older deployments ignore it entirely.\n */\n pp?: number;\n};\n\nexport type WeightEntry = { variantId: string; pulls: number; avgReward: number | null };\nexport type ComponentWeightEntry = { componentId: string; updatedAt: number; variants: WeightEntry[] };\n\n/** Options accepted by goal() (and inherited by componentGoal / the React\n * hooks / the snippet) — one shape everywhere (spec §5). */\nexport type GoalOptions = {\n /** Revenue of this conversion, in the project currency. */\n value?: number;\n /** ISO-4217 code, only when it differs from the project currency. */\n currency?: string;\n /** Merchant order/transaction id — dedupes retries, enables refunds later. */\n externalId?: string;\n /** Extra fields merged into the event payload / goal metadata. */\n metadata?: Record<string, unknown>;\n /** Advanced: partial-credit weight in [0,1] (composite steps). */\n weight?: number;\n /** Advanced: funnel step index (0-based). */\n stepIndex?: number;\n};\n\n/** goal()'s second arg is the options object iff it carries a reserved key;\n * anything else keeps the legacy bare-metadata interpretation. Reserved keys\n * inside legacy metadata were inert on the server, so reinterpretation is the\n * upgrade the sender wanted (spec §5). */\nfunction isGoalOptions(v: Record<string, unknown>): boolean {\n return 'value' in v || 'currency' in v || 'externalId' in v || 'metadata' in v || 'weight' in v || 'stepIndex' in v;\n}\n\nexport type ComponentGoalOptions = GoalOptions & {\n /** Reward credited to the served variant (0–1). Defaults to 1. */\n reward?: number;\n};\n\nexport type SentientClient = {\n track(\n event: Omit<SentientEvent, 'id' | 'sessionId' | 'timestamp' | 'timeInSession'>,\n ): void;\n goal(name: string, options?: GoalOptions): void;\n /** @deprecated positional form — prefer goal(name, options). */\n goal(name: string, metadata?: Record<string, unknown>, weight?: number, stepIndex?: number): void;\n /**\n * Records a conversion attributed to the variant currently served for\n * `componentId`, so it feeds the per-variant CVR funnel. Resolves the served\n * variant from the local assignment cache — no need to pass variantId or\n * projectId. No-ops if the component has not been assigned yet (render its\n * `<Adaptive>`/call `assign()` first). Prefer this over bare `goal()` for\n * variant experiments; `goal()` is session-level only (no component attribution).\n */\n componentGoal(componentId: string, goalType: string, opts?: ComponentGoalOptions): void;\n identify(userId: string): void;\n getAssignment(componentId: string, segment: string): Assignment | null;\n /** Server-side variant assignment. Caches the result locally per (component, segment). */\n assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): Promise<AssignResult | null>;\n /**\n * Single-roundtrip decision for layout sections, component variants, and\n * adaptive slots. Awaits the session upsert (like `assign`) so the server\n * never decides for a session row that doesn't exist yet. A response\n * without a `slots` field means the server predates slots — every declared\n * slot resolves to its baseline and no retry is made.\n */\n decide(input: DecideInput): Promise<DecideOutcome | null>;\n /** Slot result served this session (decide result, SSR seed, snapshot, or failure baseline). Null when unknown. */\n getSlotResult(slotId: string): SlotResult | null;\n /** Registry slot config served this session (content/ops/blocks for the slot).\n * Null until a registry-mode decide, SSR seed, or snapshot provides it. */\n getSlotConfig(slotId: string): SlotConfigEntry | null;\n /** Report mounted AdaptiveSlot ids the server has no config for, so they\n * auto-register as draft slots. Fire-and-forget, batched, deduped per\n * client — never blocks rendering and never throws. `baselineTexts` maps a\n * slot id to its rendered baseline text (what the region says today), so\n * generation can ground its versions in what they replace — sent only on\n * the first report of an id, capped, and the server keeps it only at\n * first registration. */\n reportSlots(\n slotIds: string[],\n baselineTexts?: Record<string, string>,\n baselineSkeletons?: Record<string, SkeletonReport>,\n /** A hybrid <Adaptive>'s authored arms seen on screen (spec 2026-09-23\n * §7.4): recorded for the dashboard and to ground generation. Sent once\n * per (slot, key) per client. */\n authoredArms?: Record<string, AuthoredArmReport[]>,\n ): void;\n /** Report a skeleton for a PUBLISHED slot the server flagged `needsSkeleton`\n * (registered before skeletons existed). Once per id per client; the server\n * stores it only while the slot has none. Optional for hand-rolled clients. */\n reportSkeleton?(slotId: string, skeleton: SkeletonReport): void;\n /** A served Rewrite arm could not be applied because the region's markup no\n * longer matches the skeleton it was written for. Batched, deduped per\n * (slot, fingerprint), never throws. Enough distinct visitors reporting the\n * same drift suspend that skeleton's arms. Optional for hand-rolled clients. */\n reportDrift?(slotId: string, expectedFp: string, observedFp: string | null, reason: 'fp_mismatch' | 'unaddressable' | 'forms'): void;\n /**\n * Ask the server for the registry config of these MOUNTED slots. Batches a\n * tick's mounts into one decide scoped to exactly those ids, once per id per\n * client; ids the server has nothing published for are passed on to\n * `reportSlots` (with their baseline text) so they register as drafts.\n * Listeners from `onSlotsChanged` fire when the answer lands. Optional so\n * hand-rolled/test clients keep type-checking.\n */\n requestSlots?(\n slotIds: string[],\n baselineTexts?: Record<string, string>,\n extras?: { render?: Record<string, RenderCaps>; skeletons?: Record<string, SkeletonReport> },\n ): void;\n /**\n * Decide these MOUNTED request-declared slots (useAdaptiveTokens,\n * AdaptiveGroup) that nothing preloaded: a tick's mounts batch into one\n * `decide({ slots })`, once per id per client. Listeners from\n * `onSlotsChanged` fire when it lands. Optional for hand-rolled clients.\n */\n decideSlots?(decls: SlotDeclInput[]): void;\n /**\n * Withdraw slots from a `requestSlots`/`decideSlots` batch that has not\n * been sent yet (the hooks call this from their unmount cleanup). A slot\n * that mounted and unmounted inside one tick — a redirecting route, a\n * StrictMode probe — is not on the page, so it must not become a trial.\n * In-flight requests are unaffected. Optional for hand-rolled clients.\n */\n cancelSlots?(slotIds: string[]): void;\n /** Subscribe to slot result/config changes. Returns the unsubscribe. */\n onSlotsChanged?(listener: () => void): () => void;\n /**\n * Whether the result `getSlotResult` returns for this slot was DECIDED for\n * this session — an SSR seed or a decide response — as opposed to a\n * snapshot from an earlier visit or the baseline written when a decide\n * failed. Only a decided arm has a `slot_decisions` row, so only a decided\n * arm may be exposed: recording an impression for a seeded one trains an\n * arm the server never served this session. Optional for hand-rolled\n * clients (absent reads as decided).\n */\n isSlotDecided?(slotId: string): boolean;\n /** Site palette served with registry block decisions. Null when absent. */\n getSitePalette(): import('./blocks.js').SitePalette | null;\n /** Site styles the served Redesign (compose) arms borrow; null when none.\n * Optional so hand-rolled clients keep type-checking. */\n getStyleVocabulary?(): import('./style-vocabulary.js').StyleVocabulary | null;\n /** Current persona estimate. Band is always `confidenceBand(confidence)`. Null when nothing is known yet. */\n getPersona(): { persona: string; confidence: number; band: 'low' | 'medium' | 'high' } | null;\n /** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */\n fetchWeights(): Promise<ComponentWeightEntry[]>;\n getGraph(): GraphSnapshot;\n /**\n * Routine teardown: stops timers/listeners and flushes pending events, but\n * KEEPS the visitor identity, decision snapshot, and retry bucket. Use for\n * component unmount / re-init (framework providers call this on cleanup).\n */\n /**\n * Drain the event queue now, without tearing anything down.\n *\n * The queue flushes on its own timer and on its own pagehide /\n * visibilitychange listeners, both registered when this client is built. The\n * engagement capture is imported later and banks dwell and the interaction\n * snapshot INSIDE those same lifecycle events — i.e. after the queue has\n * already drained — so on the leave path its events sat in the queue while\n * the page went away. Delivery on that path measured ~5-8% (Bodyshop audit\n * 2026-08-30); a visit shorter than the 5 s tick delivered nothing at all.\n * Anything that banks late in a lifecycle handler must call this after.\n */\n flush(): void;\n dispose(): void;\n /**\n * Consent-revocation / forget-me teardown: everything `dispose()` does,\n * plus deletion of the visitor identity (`_snt_uid`), the decision\n * snapshot, and the persisted retry bucket. The next visit starts as a\n * brand-new visitor.\n */\n destroy(): void;\n /** True when this client is the keyless local-mode client (dev only). */\n readonly isLocal?: boolean;\n /** True while this is a consent-gated client not yet upgraded in place:\n * goals and events are held until then, and a decide is held (or dropped\n * if the page changed). A released one still reads true but can't be\n * upgraded — check `released`. Absent on a tracking client. */\n readonly gated?: boolean;\n /** @internal True once a gated client was disposed/destroyed before any\n * upgrade: its decides resolve null without being sent. */\n readonly released?: boolean;\n /** @internal The gated client's held goal() calls, removed from it. */\n takeHeld?(): Array<(c: SentientClient) => void>;\n};\n\n// SSR preload helpers moved to the `@sentientui/core/server` entry in 0.6.0 so\n// ~200 lines of Node-only fetch logic stop shipping in the browser bundle.\n\nexport { REVEAL_MS, reveal, resetRevealStyles } from './reveal.js';\nexport { setCspNonce, cspNonce, applyNonce } from './csp-nonce.js';\nexport { forgetVisitor } from './forget.js';\nexport { forgetGeneration } from './storage-key.js';\nexport type { RevealOptions } from './reveal.js';\nexport { attachMicroSignalDetectors } from './micro-signals.js';\nexport type { MicroSignalEmitter, MicroSignalType } from './micro-signals.js';\n\nexport type {\n SessionConfig,\n SessionManager,\n EventType,\n SentientEvent,\n QueueConfig,\n Assignment,\n GraphSnapshot,\n GraphConfig,\n};\n\n/** Attempts after the first for the session upsert — see upsertSession. */\nconst SESSION_UPSERT_RETRIES = 3;\n\nfunction generateEventId(): string {\n return randomUuidV4();\n}\n\n/**\n * The page an event happened on.\n *\n * `location.pathname` ONLY — never `href` or `search`. Query strings on real\n * sites carry emails, reset tokens, order ids and session ids, and none of that\n * should leave the browser for analytics. The server strips them again\n * (domain/page-path.ts) because a hand-rolled integration can post whatever it\n * likes; this is the first of the two gates, and the one that means the data\n * never travels at all.\n *\n * Undefined outside a browser: during SSR there is no page to name, and an\n * invented one would be wrong for every reader.\n */\nfunction currentPath(): string | undefined {\n if (typeof window === 'undefined') return undefined;\n return window.location?.pathname || undefined;\n}\n\n/**\n * Decides whether a goal() call belongs to a user action already recorded.\n *\n * This used to be a clock: a latch cleared on the next macrotask, so anything\n * inside that window counted as \"the same action\". A clock cannot tell the two\n * cases apart, and it got the expensive one wrong. The window can be JUMPED —\n * a macrotask scheduled to close it runs after any timer already armed, which\n * every real page and every sibling test in a worker has — so a genuinely\n * separate conversion landed in a window that should have shut, and was\n * swallowed rather than queued: gone, with no retry able to rescue it because\n * nothing was ever handed to the queue.\n *\n * So ask the question the clock was approximating. Two nested components\n * reacting to one click are, exactly, two listeners in one event DISPATCH, and\n * the platform already hands us that identity: `window.event` is the same Event\n * object for every listener of one dispatch, a different object for the next\n * click, and undefined outside dispatch entirely. Keying on the event object\n * makes \"one action\" a fact rather than a deadline — no timer to lose a race\n * with, no fake-timer or background-throttle hazard, and no way for a second\n * click to be mistaken for the first however long the page stalls between them.\n *\n * Goals fired outside any dispatch (an effect on mount, a page goal) have no\n * event to key on, and fall back to one SYNCHRONOUS flush — closed on a\n * microtask. That is exact too, and for the same reason the old macrotask\n * window was not: microtasks always drain before the next macrotask, so no\n * pending timer can jump this window. A user cannot perform two actions inside\n * one synchronous block, so anything sharing it is a double-fire, not a repeat.\n *\n * A microtask is deliberately NOT used for the dispatch case: the HTML spec\n * runs a microtask checkpoint between listeners once the JS stack empties, so\n * it would split one click into two and double-count the revenue this collapse\n * exists to protect. That is why the dispatch case keys on the event instead,\n * and why a host without `window.event` keeps the old macrotask window — too\n * loose, but erring toward the old behaviour rather than toward double-counting.\n */\nfunction createActionLatch(): { firedBefore(actionKey: string, valueKey: string | null): boolean } {\n // Per window, per action key: the set of value identities already recorded.\n // An entry with an empty set means a VALUELESS fire was recorded. The split\n // exists because value cannot simply live inside one flat key: an inner\n // component declaring `value: 50` nested in an outer wrapper with the same\n // goal but NO value produced two distinct keys — two rows for one click.\n // Within a window, a valueless fire is absorbed by ANY record of the same\n // action (the valued row already carries the order, and a valueless\n // duplicate would inflate Hits), while a valued fire is collapsed only by an\n // IDENTICAL (value, currency) record — $50 and $70 stay two orders\n // (CONTRACTS §1). A valued fire landing AFTER a valueless one still records:\n // the valueless row has already been handed to the queue (often already on\n // the wire) and cannot be retracted, and losing the money would be the worse\n // error — server-side credit clamps the extra valueless hit at min(1, MAX\n // weight), so the cost is one inflated Hit, not corrupted revenue. Listener\n // order makes the benign ordering the common one: the inner (valued)\n // component's listener runs before the wrapper's in a bubbling dispatch.\n const byEvent = new WeakMap<object, Map<string, Set<string>>>();\n const byFlush = new Map<string, Set<string>>();\n let flushOpen = false;\n\n const alreadyRecorded = (map: Map<string, Set<string>>, actionKey: string, valueKey: string | null): boolean => {\n const values = map.get(actionKey);\n if (valueKey === null) {\n if (values) return true;\n map.set(actionKey, new Set());\n return false;\n }\n if (!values) {\n map.set(actionKey, new Set([valueKey]));\n return false;\n }\n if (values.has(valueKey)) return true;\n values.add(valueKey);\n return false;\n };\n\n // Standardised as Window.event and present in every current browser, but a\n // capability check keeps exotic hosts on the path they have always had.\n const hasWindowEvent = typeof window !== 'undefined' && 'event' in window;\n\n const currentEvent = (): object | undefined => {\n if (!hasWindowEvent) return undefined;\n const ev = (window as unknown as { event?: unknown }).event;\n // Must be a real same-realm Event, not merely an object. Window.event is\n // [Replaceable]: a classic script doing `event = {...}` at top level (an\n // implicit or sloppy global on plenty of host pages) permanently shadows\n // the accessor with a data property. Accepting any object then returned\n // that SAME object forever — its WeakMap entry never died, so every later\n // conversion looked like a re-fire of the first action and ALL repeat\n // conversions were silently dropped for the session. `instanceof Event`\n // cannot be true for such a literal; a cross-realm Event (iframe) fails it\n // too and merely falls back to the flush window, which is safe.\n // (typeof guard: a host with `window` but no Event constructor must fall\n // back, not throw a ReferenceError from inside goal().)\n return typeof Event === 'function' && ev instanceof Event ? ev : undefined;\n };\n\n const closeFlushWindow = (): void => {\n if (hasWindowEvent) {\n // A promise microtask, not queueMicrotask: fake-timer setups can replace\n // queueMicrotask, and this window closing is what keeps repeat\n // conversions from being swallowed.\n void Promise.resolve().then(() => {\n flushOpen = false;\n byFlush.clear();\n });\n return;\n }\n let done = false;\n const clear = (): void => {\n if (done) return;\n done = true;\n flushOpen = false;\n byFlush.clear();\n };\n setTimeout(clear, 0);\n if (typeof MessageChannel === 'function') {\n const ch = new MessageChannel();\n ch.port1.onmessage = () => {\n ch.port1.close();\n ch.port2.close();\n clear();\n };\n ch.port2.postMessage(0);\n }\n };\n\n return {\n firedBefore(actionKey: string, valueKey: string | null): boolean {\n const ev = currentEvent();\n if (ev) {\n let keys = byEvent.get(ev);\n if (!keys) {\n keys = new Map<string, Set<string>>();\n // Keyed weakly: the Map dies with the Event object, so a long session\n // of clicks accumulates nothing.\n byEvent.set(ev, keys);\n }\n return alreadyRecorded(keys, actionKey, valueKey);\n }\n const collapsed = alreadyRecorded(byFlush, actionKey, valueKey);\n if (!collapsed && !flushOpen) {\n flushOpen = true;\n closeFlushWindow();\n }\n return collapsed;\n },\n };\n}\n\n/**\n * Emits one `pageview` per page load and per SPA route change.\n *\n * Patches pushState/replaceState rather than polling: a route change is a\n * discrete event, and polling would either miss fast back-to-back navigations or\n * burn a timer on every page for the entire session. popstate covers\n * back/forward, which history patching does not see.\n *\n * Deduplicates on pathname, because frameworks routinely replaceState several\n * times for one navigation (query/hash updates, scroll restoration) and each\n * would otherwise look like another page in the visitor's journey.\n */\n/** Pages already recorded this page lifetime, keyed project:path. dispose()\n * flushes, so without this a consent-change or StrictMode re-init delivered a\n * second landing pageview for a page the previous client already sent. */\nconst emittedPages = new Set<string>();\n\nfunction startPageviewTracking(\n client: SentientClient,\n projectId: string,\n // Called with the page key after emitting; the caller marks emittedPages only\n // once the event reached a LIVE queue. Marking at emit time instead turned\n // StrictMode's mount→dispose→mount into zero delivered landings: the first\n // mount's event dies in the destroyed queue, and the mark suppressed the\n // second mount's — the one that actually ships.\n markDelivered: (key: string) => void,\n): () => void {\n const h = typeof window === 'undefined' ? null : window.history;\n if (!h) return () => undefined;\n\n // The stop handle exists because init() runs again on every consent change,\n // StrictMode double-invoke and HMR: without it each init wrapped history\n // again and the old wrapper kept emitting through the DISPOSED client, so one\n // navigation produced one pageview per init that ever happened.\n let stopped = false;\n let last: string | undefined;\n const emit = (): void => {\n if (stopped) return;\n const path = currentPath();\n if (!path || path === last) return;\n last = path;\n // '__page__' is a sentinel componentId: the ingest schema requires one, and\n // every component reader filters on variant_id IS NOT NULL or a specific\n // event_type, so it never surfaces as a component.\n client.track({ projectId, componentId: '__page__', eventType: 'pageview', payload: {} });\n markDelivered(`${projectId}:${path}`);\n };\n\n const installed: Array<['pushState' | 'replaceState', History['pushState'], History['pushState']]> = [];\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = h[name];\n const wrapper = function (this: History, ...a: unknown[]) {\n const r = (orig as (...x: unknown[]) => unknown).apply(this, a);\n emit();\n return r;\n } as History[typeof name];\n h[name] = wrapper;\n installed.push([name, orig, wrapper]);\n }\n window.addEventListener('popstate', emit);\n\n // The landing page itself — once per (project, path) per page lifetime. When\n // it was already sent, `last` is still primed so the next real navigation\n // emits exactly once.\n const landing = currentPath();\n if (landing && emittedPages.has(`${projectId}:${landing}`)) last = landing;\n else emit();\n\n return () => {\n if (stopped) return;\n stopped = true;\n window.removeEventListener('popstate', emit);\n for (const [name, orig, wrapper] of installed) {\n // Restore only while ours is still on top; if something wrapped over it,\n // unhooking would sever their chain — the stopped flag already makes ours\n // a passthrough.\n if (h[name] === wrapper) h[name] = orig;\n }\n };\n}\n\nconst SSR_CLIENT: SentientClient = {\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n getAssignment: () => null,\n assign: () => Promise.resolve(null),\n decide: () => Promise.resolve(null),\n getSlotResult: () => null,\n getSlotConfig: () => null,\n getSitePalette: () => null,\n reportSlots: () => undefined,\n getPersona: () => null,\n fetchWeights: () => Promise.resolve([]),\n getGraph: () => ({ pageNodes: [], capturedAt: 0 }),\n flush: () => undefined,\n dispose: () => undefined,\n destroy: () => undefined,\n};\n\nfunction readTrackedParams(): {\n utmParams: Record<string, string>;\n clickIds: Record<string, string>;\n} {\n try {\n return extractTrackedParams(window.location.search);\n } catch {\n return { utmParams: {}, clickIds: {} };\n }\n}\n\nfunction deriveBaseUrl(ingestUrl: string): string {\n return ingestUrl.replace(/\\/events\\/?$/, '');\n}\n\n/**\n * Detects whether the visitor has signalled a tracking opt-out. Honors Global\n * Privacy Control (`navigator.globalPrivacyControl`) — the legally-enforceable\n * CCPA/CPRA signal — as well as Do Not Track (`navigator.doNotTrack`, the legacy\n * `window.doNotTrack` on older Firefox, and `navigator.msDoNotTrack` on old\n * IE/Edge). GPC is a boolean; DNT is opt-out only when explicitly `'1'`/`'yes'`.\n */\nexport function isDoNotTrackEnabled(): boolean {\n // GPC is a boolean flag, checked separately from the DNT string signals.\n if (\n typeof navigator !== 'undefined' &&\n (navigator as unknown as { globalPrivacyControl?: boolean }).globalPrivacyControl === true\n ) {\n return true;\n }\n const signals = [\n typeof navigator !== 'undefined' ? navigator.doNotTrack : undefined,\n typeof window !== 'undefined'\n ? (window as unknown as { doNotTrack?: string | null }).doNotTrack\n : undefined,\n typeof navigator !== 'undefined'\n ? (navigator as unknown as { msDoNotTrack?: string | null }).msDoNotTrack\n : undefined,\n ];\n return signals.some((v) => v === '1' || v === 'yes');\n}\n\n/**\n * Upgrades a pre-consent client (any client created with `consent: false`, in\n * either `preConsentBehavior` mode) to a fully-tracking client, in place and\n * with no page reload. Call this from your consent management platform callback.\n * For React apps, prefer updating the `consent` prop on `<AdaptiveProvider>`.\n * Pass `apiKey` to target a specific project; omit to upgrade the most-recently-initialized client.\n */\nexport function grantConsent(apiKey?: string): void {\n if (typeof window === 'undefined') return;\n\n const key = apiKey ?? _lastApiKey;\n if (!key) {\n console.warn('[sentient] grantConsent() called before init()');\n return;\n }\n\n const entry = _clients.get(key);\n if (!entry) {\n console.warn('[sentient] grantConsent() called before init()');\n return;\n }\n\n const { config, upgrade, reinit } = entry;\n if (!upgrade) {\n // Keyless/local and invalid-key clients register no upgrade hook — there\n // is no hosted client to swap in. This used to return SILENTLY, so a CMP\n // callback wired to grantConsent() looked like it worked while nothing\n // ever started tracking. DNT-blocked and already-upgraded entries carry no\n // reason and stay quiet: for them the no-op is the documented contract.\n if (entry.upgradeBlockedReason) console.warn(entry.upgradeBlockedReason);\n return;\n }\n\n // Honor an active Do Not Track signal — consent cannot override a global opt-out.\n if (config.respectDoNotTrack !== false && isDoNotTrackEnabled()) return;\n\n // Upgrade through the entry point that ran the gated init when one\n // registered itself (see _registerConsentUpgradeInit) — the lean init knows\n // nothing about that entry's extra resources (the /graph scanner).\n const fullClient = (reinit ?? init)({ ...config, consent: true });\n upgrade(fullClient);\n // init() just registered the full client (with its dispose) under `key`.\n // Preserve that dispose so a later re-init/teardown can still tear it down —\n // we only need to clear the upgrade hook now that consent is granted.\n const disposed = _clients.get(key)?.dispose;\n _clients.set(key, { config: { ...config, consent: true }, upgrade: null, dispose: disposed });\n}\n\nfunction createPreConsentProxy(config: SentientConfig, neverUpgrades: boolean): { proxy: SentientClient; setInner: (c: SentientClient) => void } {\n // 'control' (the default) must reach the network zero times before consent.\n // The proxy still exists so grantConsent() has something to upgrade in place\n // — without it, a site wanting no pre-consent traffic could only start\n // tracking by reloading the page.\n const servesWinner = config.preConsentBehavior === 'statistical_winner';\n const baseUrl = deriveBaseUrl(config.ingestUrl ?? DEFAULT_INGEST_URL);\n const authHeaders = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n } as const;\n\n // Pre-consent winners are read-only and render-driven: every mounted\n // component re-calls assign() on every render, and without a result cache or\n // in-flight coalescing each call refired GET /v1/winner — the full client\n // has inflightAssigns for exactly this. Successful winners are cached for\n // the pre-consent phase (the winner is stable, and a flip mid-visit would be\n // a variant flash anyway); failure fallbacks are NOT cached, so a recovering\n // server gets asked again. Both maps die with the proxy on upgrade.\n const winnerCache = new Map<string, AssignResult>();\n const inflightWinners = new Map<string, Promise<AssignResult | null>>();\n\n let inner: SentientClient = {\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n getAssignment: () => null,\n fetchWeights: () => Promise.resolve([]),\n assign(componentId, variantIds, _agentData?) {\n // Control mode: no request. Callers fall back to variantIds[0] through\n // ssrFallback, exactly as they did against the old no-op client.\n if (!servesWinner) return Promise.resolve(null);\n const cached = winnerCache.get(componentId);\n if (cached) return Promise.resolve(cached);\n return coalesce(inflightWinners, componentId, async (): Promise<AssignResult | null> => {\n try {\n const params = new URLSearchParams({ componentId });\n for (const v of variantIds ?? []) params.append('variantIds[]', v);\n const t = timeoutSignal(REQUEST_TIMEOUT_MS);\n let body: { variantId: string };\n try {\n const res = await fetch(`${baseUrl}/winner?${params.toString()}`, {\n headers: authHeaders,\n signal: t.signal,\n });\n if (!res.ok) return variantIds?.[0] ? { variantId: variantIds[0], assignmentTtlMs: 0 } : null;\n body = (await res.json()) as { variantId: string };\n } finally {\n t.clear();\n }\n const result: AssignResult = { variantId: body.variantId, assignmentTtlMs: 0 };\n winnerCache.set(componentId, result);\n return result;\n } catch {\n return variantIds?.[0] ? { variantId: variantIds[0], assignmentTtlMs: 0 } : null;\n }\n });\n },\n decide: () => Promise.resolve(null),\n getSlotResult: () => null,\n getSlotConfig: () => null,\n getSitePalette: () => null,\n reportSlots: () => undefined,\n getPersona: () => null,\n getGraph: () => ({ pageNodes: [], capturedAt: 0 }),\n flush: () => undefined,\n dispose: () => undefined,\n destroy: () => undefined,\n };\n\n let upgraded = false;\n const slotListeners = new Set<() => void>();\n // Every argument is queued and forwarded: the render caps and skeletons\n // (native generation) ride the third one, and dropping them made a\n // consent-gated page read as a legacy SDK — never drawn a Rewrite arm.\n const queuedSlots: Array<[string[], Parameters<NonNullable<SentientClient['requestSlots']>>[1], Parameters<NonNullable<SentientClient['requestSlots']>>[2]]> = [];\n let queuedDecls: SlotDeclInput[] = [];\n // decide() while gated: held and replayed on upgrade (audit N1). The pre-\n // consent client answered null and nothing asked again, so a visitor whose\n // consent arrived a moment later — every consentFrom snippet page view, now\n // that the presets load lazily — got no decision for the whole page view.\n // Keyed by path: a decide replayed after an SPA navigation would book trials\n // for slots that are no longer on the page (CONTRACTS §2), so it resolves null.\n const queuedDecides: Array<[Parameters<SentientClient['decide']>[0], string, (o: DecideOutcome | null) => void]> = [];\n\n const releaseDecides = (): void => {\n for (const [, , done] of queuedDecides.splice(0)) done(null);\n heldCalls.length = 0;\n };\n // Session-level conversions (goal()) recorded while consent is still\n // unknown — every consentFrom snippet page boots gated while the presets\n // chunk loads, so a consented visitor's order-confirmation goal() used to\n // vanish (grader NEW-1; CONTRACTS §7: never swallowed). Held in memory only\n // — nothing is stored or sent — and replayed if consent arrives in this\n // page view, dropped on dispose/destroy/refusal. Never held under DNT/GPC\n // (no upgrade). NOT componentGoal/track: those attribute to a variant, and\n // pre-consent the visitor saw the baseline — replayed after the grant they\n // credited whatever the tracking client then held (review #4).\n const heldCalls: Array<(c: SentientClient) => void> = [];\n // Set by dispose()/destroy() before an upgrade: a released gated client\n // holds nothing more (goals fired after a refusal were held again and sent\n // on a later accept — grader N7-3) and answers any decide with null at once\n // (a held decide on it could never settle — review #3). `released` tells a\n // caller that a null came from this, not from a failed request.\n let released = false;\n // A released proxy also leaves the grantConsent() registry: a later global\n // grant upgraded it in place, reviving a client its owner had let go of\n // (review R8 #6). Only our own hook — a newer init under the key keeps its.\n const release = (): void => {\n if (upgraded) return;\n released = true;\n const entry = _clients.get(config.apiKey);\n if (entry?.upgrade === setInner) {\n _clients.set(config.apiKey, {\n config,\n upgrade: null,\n upgradeBlockedReason:\n '[sentient] grantConsent(): client released before consent; call init() again',\n });\n }\n };\n // Held calls replay one per task after the upgrade (see setInner); a goal\n // fired meanwhile joins the back of that line, or it was sent before the\n // conversions that happened first (grader N11-3).\n const replay: Array<(c: SentientClient) => void> = [];\n const pumpReplay = (): void =>\n void setTimeout(() => {\n try {\n replay.shift()?.(inner);\n } catch {\n /* one bad call never blocks the rest */\n }\n if (replay.length) pumpReplay();\n });\n const hold = (call: (c: SentientClient) => void): void => {\n if (upgraded) {\n if (replay.length) replay.push(call);\n else call(inner);\n } else if (!neverUpgrades && !released && heldCalls.length < 100) heldCalls.push(call);\n // Visible in debug: a goal after a refusal is dropped on purpose, and a\n // silent drop read as a broken integration (grader N10-2).\n else if (released && config.debug) console.warn('[sentient] goal dropped: client released');\n };\n const proxy: SentientClient = {\n get gated() {\n return !upgraded && !neverUpgrades;\n },\n get released() {\n return released && !upgraded;\n },\n /** @internal Hand the held conversions to another client (React re-inits\n * on a grant instead of upgrading in place) and clear them. */\n takeHeld: () => heldCalls.splice(0),\n track: (e) => inner.track(e),\n // Cast: a single arrow can't structurally satisfy the overloaded member;\n // the passthrough forwards both call shapes untouched.\n goal: ((n: string, m?: Record<string, unknown>, w?: number, s?: number) => hold((c) => c.goal(n, m, w, s))) as SentientClient['goal'],\n componentGoal: (c, g, o) => inner.componentGoal(c, g, o),\n identify: (u) => inner.identify(u),\n getAssignment: (c, s) => inner.getAssignment(c, s),\n assign: (c, v, a, av) => inner.assign(c, v, a, av),\n decide: (i) =>\n upgraded\n ? inner.decide(i)\n : released\n ? Promise.resolve(null)\n : // DNT/GPC can never be upgraded: held, it would never resolve, and a\n // core-direct `await client.decide()` hung for every GPC browser (F1).\n neverUpgrades\n ? Promise.resolve(null)\n : new Promise<DecideOutcome | null>((done) => queuedDecides.push([i, routeKey(), done])),\n getSlotResult: (s) => inner.getSlotResult(s),\n isSlotDecided: (s) => inner.isSlotDecided?.(s) ?? true,\n getSlotConfig: (s) => inner.getSlotConfig(s),\n getSitePalette: () => inner.getSitePalette(),\n getStyleVocabulary: () => inner.getStyleVocabulary?.() ?? null,\n reportSlots: (ids, texts, skels, authored) => inner.reportSlots(ids, texts, skels, authored),\n reportSkeleton: (id, sk) => inner.reportSkeleton?.(id, sk),\n reportDrift: (id, e, o, r) => inner.reportDrift?.(id, e, o, r),\n // Pre-consent: queue mounted slots and hold listeners, then hand both to\n // the real client on upgrade. A grantConsent() upgrade swaps the client in\n // place without remounting, so a slot that asked while gated would\n // otherwise never be decided.\n requestSlots: (ids, texts, extras) => (upgraded ? inner.requestSlots?.(ids, texts, extras) : queuedSlots.push([ids, texts, extras])),\n decideSlots: (d) => (upgraded ? inner.decideSlots?.(d) : queuedDecls.push(...d)),\n // Pre-consent, an unmounted slot leaves the queue too: consent may be\n // granted minutes later on a different route, and the slots the visitor\n // mounted before navigating away are not on the page then.\n cancelSlots: (ids) => {\n if (upgraded) return inner.cancelSlots?.(ids);\n const gone = new Set(ids);\n for (const q of queuedSlots) q[0] = q[0].filter((id) => !gone.has(id));\n queuedDecls = queuedDecls.filter((d) => !gone.has(d.id));\n },\n onSlotsChanged: (l) => (slotListeners.add(l), () => void slotListeners.delete(l)),\n getPersona: () => inner.getPersona(),\n fetchWeights: () => inner.fetchWeights(),\n getGraph: () => inner.getGraph(),\n flush: () => inner.flush(),\n dispose: () => (release(), releaseDecides(), inner.dispose()),\n // Before consent there is no tracking client to destroy, but a returning\n // visitor may still have an id, snapshot and buckets from an earlier\n // consented visit: forget-me deletes them all the same (grader F2 — a\n // \"Reject\" on a manual gate used to delete nothing).\n destroy: () => (release(), releaseDecides(), upgraded ? inner.destroy() : forgetVisitor(config.apiKey)),\n };\n\n function setInner(fullClient: SentientClient) {\n inner = fullClient;\n upgraded = true;\n // Each in its own task: replayed in one go they shared one latch window\n // (createActionLatch), so two held add_to_cart clicks became one (NEW-3).\n // In order, one per task (see pumpReplay).\n if (heldCalls.length) {\n replay.push(...heldCalls.splice(0));\n pumpReplay();\n }\n const path = routeKey();\n for (const [input, at, done] of queuedDecides.splice(0)) {\n if (at !== path) done(null);\n else fullClient.decide(input).then(done, () => done(null));\n }\n fullClient.onSlotsChanged?.(() => slotListeners.forEach((l) => l()));\n for (const [ids, texts, extras] of queuedSlots.splice(0)) if (ids.length > 0) fullClient.requestSlots?.(ids, texts, extras);\n if (queuedDecls.length > 0) fullClient.decideSlots?.(queuedDecls.splice(0));\n }\n\n return { proxy, setInner };\n}\n\n/**\n * The page a decision belongs to: the pathname plus a route-shaped fragment.\n * Hash routers (`#/pricing`) navigate without changing the pathname; an\n * in-page anchor (`#faq`) is not a route. Shared by the held-decide drop rule\n * and the snippet's re-decide check, which must agree (grader NEW-2).\n */\nexport function routeKey(): string {\n return typeof location === 'undefined' ? '' : location.pathname + (/^#!?\\//.test(location.hash) ? location.hash : '');\n}\n\n/**\n * Shares one promise among concurrent calls with the same key — assign() and\n * decide() both use this so N same-tick requests (several mounted slots\n * sharing a component id; per-slot lazy decides) cost one roundtrip. The map\n * entry lives exactly as long as the request is in flight: a settled result\n * must NOT serve later calls (a sequential re-request is a fresh decision —\n * caching lives elsewhere), and a failed one must not wedge the key. No\n * `.finally()` — that's ES2018 and this file ships in the es2017 snippet\n * bundle (the SNIP-5 lesson).\n */\nfunction coalesce<T>(inflight: Map<string, Promise<T>>, key: string, run: () => Promise<T>): Promise<T> {\n const hit = inflight.get(key);\n if (hit) return hit;\n const request = (async (): Promise<T> => {\n try {\n return await run();\n } finally {\n inflight.delete(key);\n }\n })();\n inflight.set(key, request);\n return request;\n}\n\n/**\n * Initializes the Sentient client. Returns a no-op client during SSR.\n */\nexport function init(config: SentientConfig): SentientClient {\n if (typeof window === 'undefined') {\n return SSR_CLIENT;\n }\n\n if (config.nonce) setCspNonce(config.nonce);\n\n // `|| 'local'`: keyless clients register under the 'local' fallback key\n // below, and `_lastApiKey = ''` is falsy — so a no-arg grantConsent() after\n // a keyless init() warned \"called before init()\" even though init() DID run,\n // instead of resolving that entry (and its blocked-upgrade explanation).\n _lastApiKey = config.apiKey || 'local';\n\n // A re-init for the same key (HMR, consent toggle, provider remount) supersedes\n // the prior client. Dispose it first so its queue's setInterval and\n // visibilitychange/pagehide listeners don't leak — the map only ever held its\n // config, so without this the old client kept flushing forever.\n const prevEntry = _clients.get(config.apiKey || 'local');\n if (prevEntry?.dispose) {\n try {\n prevEntry.dispose();\n } catch {\n /* teardown must never throw on re-init */\n }\n }\n\n // DNT/GPC (a global opt-out) or an explicit `consent: false` must be evaluated\n // BEFORE the local-mode branch: createLocalModeClient() calls initSession()\n // unconditionally, so a gated visitor would otherwise be issued the 365-day\n // `_snt_uid` identity cookie in keyless/local mode (audit P2). DNT/GPC also\n // gates tracking off even when the site passes `consent: true`, and blocks\n // `grantConsent()` from upgrading.\n const dntBlocked = config.respectDoNotTrack !== false && isDoNotTrackEnabled();\n const gated = config.consent === false || dntBlocked;\n\n // Keyless local mode. `localMode: true` forces the local engine (documented\n // escape hatch); 'auto' (default) engages it only when no valid key is\n // present. In production builds `@sentientui/core/local` resolves to a stub\n // and this degrades to a no-op client + one console.error per page load\n // (createLocalModeClient handles that), so no NODE_ENV check is needed here.\n const keyValid = typeof config.apiKey === 'string' && config.apiKey.startsWith('pk_');\n if (config.localMode === true || (!keyValid && config.localMode !== false)) {\n // One registration for both arms (they used to duplicate this set call).\n // upgrade stays null — there is no hosted client to swap in — but the\n // reason lets grantConsent() explain that instead of no-oping silently.\n _clients.set(config.apiKey || 'local', {\n config,\n upgrade: null,\n upgradeBlockedReason:\n '[sentient] grantConsent(): this client is keyless/local — there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking.',\n });\n // A gated visitor must never get the identity cookie. Local mode has no\n // server to serve a statistical winner from, so return a plain no-op.\n if (gated) return SSR_CLIENT;\n return createLocalModeClient(config);\n }\n\n if (gated) {\n if (!config.apiKey || !config.apiKey.startsWith('pk_')) {\n if (config.preConsentBehavior === 'statistical_winner') {\n console.warn('[sentient] init() called with an invalid apiKey — expected a pk_ public key. SDK disabled.');\n }\n // Registered under the same 'local' fallback key the local branch uses:\n // `config.apiKey` here can be '', and a ''-keyed entry was unreachable\n // by a no-arg grantConsent() (falsy `_lastApiKey`), which then wrongly\n // warned \"called before init()\".\n _clients.set(config.apiKey || 'local', {\n config,\n upgrade: null,\n upgradeBlockedReason:\n '[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) — consent cannot enable tracking.',\n });\n return SSR_CLIENT;\n }\n // Every gated client gets an upgradeable proxy, not just the winner-serving\n // one — otherwise grantConsent() is silently dead for the 'control' default\n // and the site has to reload to start tracking. Control mode still makes no\n // request; the proxy only exists so consent can swap the inner client.\n const { proxy, setInner } = createPreConsentProxy(config, dntBlocked);\n // Under DNT the read-only winner still serves, but consent can never\n // upgrade it to tracking — so drop the upgrade hook.\n _clients.set(config.apiKey, { config, upgrade: dntBlocked ? null : setInner });\n return proxy;\n }\n\n if (!config.apiKey || !config.apiKey.startsWith('pk_')) {\n console.warn('[sentient] init() called with an invalid apiKey — expected a pk_ public key. SDK disabled.');\n return SSR_CLIENT;\n }\n\n if (config.ingestUrl === '') {\n console.warn('[sentient] init() called with an empty ingestUrl. SDK disabled.');\n return SSR_CLIENT;\n }\n\n const resolvedIngestUrl = config.ingestUrl ?? DEFAULT_INGEST_URL;\n\n const sessionStart = Date.now();\n const session = initSession({ ssrSessionId: config.ssrSessionId, apiKey: config.apiKey });\n const rawCache = createAssignmentCache(undefined, config.apiKey);\n // Set by this client's destroy(). The window marker covers other bundles'\n // forget-me, but a new grant clears it — and this client's own in-flight\n // answer must never write a forgotten visitor back after that either.\n let forgottenHere = false;\n const createdGen = forgetGeneration(config.apiKey);\n const mayPersist = (): boolean => !forgottenHere && forgetGeneration(config.apiKey) === createdGen;\n // Same rule as the snapshot write: nothing is cached for a forgotten visitor.\n const assignmentCache: typeof rawCache = {\n ...rawCache,\n set: (...a) => {\n if (mayPersist()) rawCache.set(...a);\n },\n };\n const eventQueue = createEventQueue({ ingestUrl: resolvedIngestUrl, apiKey: config.apiKey });\n const baseUrl = deriveBaseUrl(resolvedIngestUrl);\n\n const authHeaders = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n } as const;\n\n // Conversions get the same durable transport the event queue has always had:\n // retry with backoff, a cross-reload bucket, dedupe on the server's goalId.\n // One warning per distinct drop status per page load (see onDrop below).\n const warnedDropStatuses = new Set<number>();\n const goalQueue: GoalQueue = createGoalQueue({\n url: `${baseUrl}/goals`,\n apiKey: config.apiKey,\n headers: authHeaders,\n onDrop: (goal, status) => {\n // NOT debug-gated. CONTRACTS §7 says a dropped goal is reported to the\n // developer and never swallowed, but this returned early unless debug was\n // on — so in production a rate-limited or misconfigured project lost every\n // conversion with no signal anywhere. Warn once per (status, page load):\n // enough to be discoverable in a console or an error reporter, quiet\n // enough that a broken integration cannot flood the page.\n if (!config.debug) {\n if (warnedDropStatuses.has(status)) return;\n warnedDropStatuses.add(status);\n }\n console.warn(\n `[sentient] goal dropped (HTTP ${status}) — this will not be retried. ` +\n (status === 400\n ? 'The session was not found: call init() and let the session upsert complete before firing goals.'\n : status === 401 || status === 403\n ? 'Check the API key and that this origin is on the project allowlist.'\n : 'See the response status for the cause.'),\n goal,\n );\n },\n });\n\n const deviceClass = detectDeviceClass(navigator.userAgent ?? '');\n // No window guard here: init() already returned SSR_CLIENT at the top when\n // window is undefined, so the old `typeof window` ternary was dead code.\n const appOrigin = window.location.origin;\n const trafficSource = detectTrafficSource(document.referrer ?? '', appOrigin);\n const sessionSegment =\n config.sessionSegment ?? `${deviceClass}:${trafficSource}`;\n const inflightAssigns = new Map<string, Promise<AssignResult | null>>();\n // Mirrors inflightAssigns for decide(): per-slot lazy-decide patterns (see\n // local-mode's merge comment — one decide({ slots: [decl] }) per mounted\n // slot, all in the same tick) otherwise issue N roundtrips and N snapshot\n // rewrites for one page. Keyed by the full request payload, never just \"a\n // decide is running\": coalescing {slots:[a]} with {slots:[b]} would hand\n // slot b's caller an outcome that never decided b.\n const inflightDecides = new Map<string, Promise<DecideOutcome | null>>();\n\n // --- Adaptive-slot state (decide) ---\n // Results served for this session, keyed by slot id. Written by decide();\n // read by getSlotResult() (Task 3.3) and componentGoal's slot fallback.\n const slotStore = new Map<string, SlotResult>();\n // Ids whose slotStore entry the server decided for THIS session (SSR seed or\n // a decide response). Snapshot seeds and failure baselines are deliberately\n // absent: they render (pre-paint parity, \"always resolve to something\") but\n // have no slot_decisions row, so the React exposure gates must not record an\n // impression for them — a failed 30-declaration batch used to yield up to\n // 30 phantom baseline exposures, and a snapshot arm was exposed and then a\n // second, different arm exposed again when the real decide landed.\n const decidedSlotIds = new Set<string>();\n // Registry slot config (content/ops/blocks) served this session. Written by\n // decide() and the SSR/snapshot seeds below; read by getSlotConfig() so SDK\n // surfaces (AdaptiveSlot) can render server-authored arms — previously the\n // snippet was the only consumer and this never left the decide outcome.\n const slotConfigStore = new Map<string, SlotConfigEntry>();\n let sitePalette: import('./blocks.js').SitePalette | null = null;\n let styleVocabulary: import('./style-vocabulary.js').StyleVocabulary | null = null;\n let personaState: { persona: string; confidence: number } | null = null;\n // First-seen slot registration (reportSlots): once per id per client.\n const reportedSlotIds = new Set<string>();\n const pendingSlotReports = new Set<string>();\n // Baseline text captured with the first report of an id. Bounded by the\n // once-per-id dedupe above, normalized + capped before it leaves the page.\n const pendingBaselineTexts = new Map<string, string>();\n const pendingBaselineSkeletons = new Map<string, SkeletonReport>();\n const reportedSkeletonIds = new Set<string>();\n // Drift: once per (slot, expected fp) per client.\n const reportedDrift = new Set<string>();\n const reportedAuthored = new Set<string>();\n let slotReportTimer: ReturnType<typeof setTimeout> | null = null;\n // Mirror of the server's slot-id rule (apps/api/src/routes/slots-observed.ts):\n // the server 400s the WHOLE batch when any one id fails it, and every\n // co-batched valid id is already in reportedSlotIds by then — so a single\n // `hero.cta` on the page would silently unregister every other new slot for\n // the client lifetime. Invalid ids are refused at the door instead.\n const SLOT_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/;\n const warnedInvalidSlotIds = new Set<string>();\n // requestSlots: mounted-slot decides, once per id per client.\n const slotListeners = new Set<() => void>();\n const requestedSlotIds = new Set<string>();\n const pendingSlotTexts = new Map<string, { text?: string; render?: RenderCaps; skeleton?: SkeletonReport }>();\n let slotRequestTimer: ReturnType<typeof setTimeout> | null = null;\n // decideSlots: mounted request-declared slots, once per id per client.\n const decidedDeclIds = new Set<string>();\n const pendingDecls = new Map<string, SlotDeclInput>();\n let declTimer: ReturnType<typeof setTimeout> | null = null;\n // \"Once per id per client\" was keyed on the ASK, not the answer: a decide\n // that failed (5xx, offline, tab suspended mid-flight) left its ids marked\n // as requested, so the slots served their baseline/snapshot — unexposed,\n // untrained — for the rest of the client lifetime, and a SPA visitor never\n // got a decision for that page again. Failed ids are released so a remount\n // re-asks, and each batch gets a bounded automatic retry with backoff so a\n // blip during the initial render still resolves without user action.\n // Bounded per id per client, not per mount: a server that is really down\n // must not turn every route change into a retry storm.\n const SLOT_DECIDE_AUTO_RETRIES = 2;\n const slotDecideFailures = new Map<string, number>();\n let slotDecideTornDown = false;\n // Releases every id in the failed batch, then schedules `resend` (after the\n // backoff for the worst-off id) with the subset still under the retry cap.\n const retryFailedSlots = (ids: string[], requested: Set<string>, resend: (retry: Set<string>) => void): void => {\n const retry = new Set<string>();\n let worst = 1;\n for (const id of ids) {\n requested.delete(id);\n const n = (slotDecideFailures.get(id) ?? 0) + 1;\n slotDecideFailures.set(id, n);\n if (n <= SLOT_DECIDE_AUTO_RETRIES) {\n retry.add(id);\n if (n > worst) worst = n;\n }\n }\n if (retry.size > 0) {\n setTimeout(() => {\n if (!slotDecideTornDown) resend(retry);\n }, backoffDelayMs(worst));\n }\n };\n\n // On decide failure every declared slot must still resolve — to its baseline.\n // Never overwrite a previously served result.\n const seedSlotBaselines = (decls: SlotDeclInput[]): void => {\n for (const d of decls) {\n if (!slotStore.has(d.id)) slotStore.set(d.id, baselineResultFor(d));\n }\n };\n\n // Seed slot/persona state. Priority: explicit SSR seeds → snapshot.\n if (config.initialSlots) {\n for (const [slotId, result] of Object.entries(config.initialSlots)) {\n slotStore.set(slotId, result);\n // The SSR preload decided these against this very session id.\n decidedSlotIds.add(slotId);\n }\n }\n if (config.initialSlotConfig) {\n for (const [slotId, entry] of Object.entries(config.initialSlotConfig)) {\n slotConfigStore.set(slotId, entry);\n }\n }\n if (config.initialPalette) sitePalette = config.initialPalette;\n if (config.initialVocabulary) styleVocabulary = config.initialVocabulary;\n const seedSnapshot = readSnapshot(config.apiKey);\n if (seedSnapshot) {\n for (const [slotId, result] of Object.entries(seedSnapshot.slots)) {\n if (!slotStore.has(slotId)) slotStore.set(slotId, result);\n }\n for (const [slotId, entry] of Object.entries(seedSnapshot.slotConfig ?? {})) {\n if (!slotConfigStore.has(slotId)) slotConfigStore.set(slotId, entry);\n }\n if (!sitePalette && seedSnapshot.palette) sitePalette = seedSnapshot.palette;\n if (!styleVocabulary && seedSnapshot.vocabulary) styleVocabulary = seedSnapshot.vocabulary;\n }\n\n // Band-only persona sources (html attrs, snapshot) become a band-consistent\n // numeric confidence so confidenceBand(confidence) always equals the band.\n const BAND_CONFIDENCE: Record<string, number> = { low: 0.15, medium: 0.5, high: 0.85 };\n if (config.initialPersona) {\n personaState = { ...config.initialPersona };\n } else {\n // Single-writer rule: the inline pre-paint script owns the <html>\n // attributes. The client ADOPTS them as truth and never rewrites them\n // mid-session (next visit's script picks up the new snapshot instead).\n const ds = document.documentElement.dataset;\n if (ds.sentientPersona) {\n personaState = {\n persona: ds.sentientPersona,\n confidence: BAND_CONFIDENCE[ds.sentientConfidence ?? 'low'] ?? 0.15,\n };\n } else if (seedSnapshot) {\n personaState = {\n persona: seedSnapshot.persona,\n confidence: BAND_CONFIDENCE[seedSnapshot.band] ?? 0.15,\n };\n }\n }\n\n // Seed SSR-preloaded assignments into the local cache so assign() finds a\n // cache hit immediately — no network call, no variant flash on hydration.\n if (config.initialAssignments) {\n for (const [componentId, variantId] of Object.entries(config.initialAssignments)) {\n assignmentCache.set(componentId, sessionSegment, {\n variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n });\n }\n }\n\n // Upsert session metadata once on init. assign() awaits this promise so\n // the server isn't asked to assign for a session row that doesn't exist yet.\n let sessionReady: Promise<void> = Promise.resolve();\n\n const sessionId = session.getSessionId();\n if (sessionId) {\n const referrerDomain = referrerDomainFromReferer(document.referrer ?? '');\n const { utmParams, clickIds } = readTrackedParams();\n const sessionBody = {\n sessionId,\n deviceClass,\n trafficSource,\n referrerDomain,\n utmParams,\n // Ad-platform click IDs (gclid & co). Captured separately from utmParams\n // because Google Ads auto-tagging appends ONLY gclid — without this,\n // paid search with no manual UTM template reported as organic.\n clickIds,\n // The landing page's PATH (never its query string) — it is what tells a\n // paid click to a product page or a Shopify /discount/ link apart from\n // any other arrival (server-side arrival classification).\n landingPath: typeof location !== 'undefined' ? location.pathname : undefined,\n timeOfDay: detectTimeOfDay(new Date()),\n dayOfWeek: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][new Date().getDay()],\n ephemeral: session.isEphemeral(),\n // Likely-automation hint: navigator.webdriver (set under automation\n // control) or a known agent token in the UA. Probabilistic — used for\n // metrics + bandit exclusion server-side, never to change what's served.\n automation:\n (typeof navigator !== 'undefined' && navigator.webdriver === true) ||\n uaTokenMatch(navigator.userAgent ?? ''),\n ...(config.userId ? { userId: config.userId } : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n ...(config.country ? { country: config.country } : {}),\n // Version-skew reporting. Only a wrapper that knows its own released\n // version sets this — a dev-sentinel version is dropped by the caller,\n // not smuggled through, or the dashboard would read it as \"behind\"\n // forever (the same trap the snippet's decide reporting documents).\n ...(config.sdk ? { sdk: config.sdk.name, sdkVersion: config.sdk.version } : {}),\n };\n // The session row is a PRECONDITION for every conversion: /v1/goals answers\n // 400 session_not_found without it, and the durable queue classifies a 4xx\n // as terminal — so a session upsert that fails silently turns every later\n // conversion into a permanent drop. That is not hypothetical: /v1/sessions\n // carries the same per-IP limiter as /v1/goals, so under shared egress\n // (offices, mobile carriers, corporate NAT) the SESSION call 429s first and\n // the goals that follow are dropped for good. Retry it, so a transient\n // failure costs a moment rather than the visit's whole conversion history.\n const upsertSession = async (): Promise<undefined> => {\n for (let attempt = 0; ; attempt++) {\n // Stop retrying once this client is torn down or the visitor was\n // forgotten: the retries POSTed the forgotten id again (N7-6).\n if (slotDecideTornDown || !mayPersist()) return undefined;\n const t = timeoutSignal(REQUEST_TIMEOUT_MS);\n try {\n const res = await fetch(`${baseUrl}/sessions`, {\n method: 'POST',\n keepalive: true,\n body: JSON.stringify(sessionBody),\n headers: authHeaders,\n signal: t.signal,\n });\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n return undefined; // terminal: retrying a quota will not clear it\n }\n if (res.ok || classifyResponse(res) === 'dropped') return undefined;\n } catch {\n /* network failure or timeout — same retry path as a 5xx (the\n upsert is idempotent, so a timed-out attempt that did land is\n harmless to repeat) */\n } finally {\n t.clear();\n }\n if (attempt >= SESSION_UPSERT_RETRIES) {\n // Say so once: from here every conversion this visit will 400, and\n // that used to be entirely silent.\n console.warn(\n '[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.',\n );\n return undefined;\n }\n await new Promise((r) => setTimeout(r, backoffDelayMs(attempt + 1)));\n }\n };\n try {\n sessionReady = upsertSession();\n } catch {\n /* never throw on init */\n }\n }\n\n if (config.debug) {\n console.log('[sentient] initialized', { context: config.context });\n (\n window as unknown as {\n __sentient?: {\n client: SentientClient;\n queue: EventQueue;\n };\n }\n ).__sentient = {\n client: null as unknown as SentientClient,\n queue: eventQueue,\n };\n }\n\n // One user action must record ONE session-level conversion per goal name.\n // Nested components each fire their declared goal on the same click (every\n // <Adaptive>/hook path calls componentGoal() AND goal()), so a hero nested\n // inside a CTA wrapper wrote two goal_events rows for one click: harmless for\n // a weight-1.0 goal (close-out clamps at 1) but a 0.3-weight step summed to\n // 0.6, and the Goals page counts Hits as COUNT(*) either way.\n //\n // The scope is one event dispatch, not one session and no longer one task:\n // see createActionLatch. A session-wide latch would swallow genuine repeat\n // conversions (two purchases in one visit are two conversions), and a\n // time-boxed one did exactly that whenever the box outlived the action.\n // Calls carrying distinct externalIds are never collapsed — those are, by\n // definition, distinct orders.\n const firedThisAction = createActionLatch();\n\n // Set once tracking starts; dispose() and destroy() call it so a replaced\n // client stops watching history instead of emitting forever. The flag records\n // teardown for the delivery-marking below, which runs on a later microtask.\n let stopPageviews: (() => void) | null = null;\n let pageviewsTornDown = false;\n\n const client: SentientClient = {\n goal(name: string, metadataOrOpts: Record<string, unknown> = {}, weight = 1.0, stepIndex = 0) {\n const sid = session.getSessionId();\n // Nothing is sent by a client that was disposed (a pause) or forgotten.\n if (!sid || slotDecideTornDown || !mayPersist()) return;\n const opts: GoalOptions = isGoalOptions(metadataOrOpts)\n ? (metadataOrOpts as GoalOptions)\n : { metadata: metadataOrOpts };\n // stepIndex and weight are part of the key: funnel steps share a goal\n // name and differ by stepIndex, so collapsing on name alone dropped a\n // step fired in the same handler. Only IDENTICAL calls are one action.\n //\n // value and currency key the payload SEPARATELY (the latch's valueKey),\n // not as more segments of the flat key, and for a costlier reason: they\n // are the money. Flattened out of the key entirely, a $50 order and a\n // $70 order landing in one window collapsed into a single $50 record —\n // the client half of CONTRACTS §1 \"two orders are worth two orders\",\n // which the server already honours (migration 119 records the repeat if\n // it arrives; this is what stopped it arriving). But flattened INTO the\n // key, a valued inner component nested in a valueless wrapper made two\n // keys out of one click — two rows for one order. So the latch compares\n // values only between valued fires ($50 vs $70 stays two records) and\n // lets a valued record absorb a valueless re-fire of the same action\n // (see createActionLatch for the one asymmetric case).\n //\n // NOT metadata: every nested <Adaptive>/hook path stamps its own\n // componentId and variantId in there, so keying on it would make the\n // duplicate this latch exists to collapse look distinct again.\n const actionKey = [\n name,\n opts.externalId ?? '',\n opts.stepIndex ?? stepIndex,\n opts.weight ?? weight,\n ].join('\\0');\n const valueKey = opts.value !== undefined ? `${opts.value}\\0${opts.currency ?? ''}` : null;\n if (firedThisAction.firedBefore(actionKey, valueKey)) {\n if (config.debug) {\n console.log(`[sentient] goal(\"${name}\") already recorded for this action — not sent twice`);\n }\n return;\n }\n const goalId = generateEventId();\n // undefined values vanish at JSON.stringify time, so optional fields\n // need no conditional assembly.\n const body = {\n sessionId: sid,\n name,\n metadata: opts.metadata ?? {},\n weight: opts.weight ?? weight,\n stepIndex: opts.stepIndex ?? stepIndex,\n goalId,\n value: opts.value,\n currency: opts.currency,\n externalId: opts.externalId,\n };\n if (config.debug) {\n console.log('[sentient] goal', body);\n }\n // Serialize once, here: the queued copy must replay byte-identically\n // (same goalId) so a retry dedupes server-side instead of double-counting.\n const payload = { id: goalId, body: JSON.stringify(body) };\n sessionReady.then(() => goalQueue.send(payload));\n },\n\n componentGoal(componentId, goalType, opts) {\n const sid = session.getSessionId();\n // Same gate as goal(): a paused or forgotten client's component\n // conversion was still queued and sent (review R8 #3).\n if (!sid || slotDecideTornDown || !mayPersist()) return;\n // Variant experiments resolve from the assignment cache; adaptive slots\n // (useAdaptiveTokens / AdaptiveGroup) resolve from the slot state, using\n // the canonical arm string as the attributed variantId.\n const assignment = assignmentCache.get(componentId, sessionSegment);\n const slotResult = assignment ? null : slotStore.get(componentId) ?? null;\n if (!assignment && slotResult === null) {\n if (config.debug) {\n console.warn(\n `[sentient] componentGoal(\"${componentId}\"): no assignment or slot decision yet — render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`,\n );\n }\n return;\n }\n // A slot result the core only HOLDS (pre-paint snapshot, failure\n // baseline) has no slot_decisions row this session, so a goal attributed\n // to its arm would be a conversion with no trial behind it. The React\n // hooks gate this on `source === 'seeded'`; this is the same rule at the\n // transport, so a hand-rolled integration cannot bypass it.\n if (!assignment && !decidedSlotIds.has(componentId)) {\n if (config.debug) console.warn(`[sentient] componentGoal(\"${componentId}\"): slot not decided this session — not attributed`);\n return;\n }\n const attributedVariantId = assignment ? assignment.variantId : armOfResult(slotResult!);\n const fullEvent: SentientEvent = {\n id: generateEventId(),\n sessionId: sid,\n projectId: config.apiKey,\n componentId,\n variantId: attributedVariantId,\n eventType: 'goal_achieved',\n goalType,\n // undefined goalValue/currency vanish at JSON.stringify time.\n payload: {\n reward: opts?.reward ?? 1,\n goalValue: opts?.value,\n currency: opts?.currency,\n ...(opts?.metadata ?? {}),\n },\n timestamp: Date.now(),\n timeInSession: Date.now() - sessionStart,\n path: currentPath(),\n };\n if (config.debug) {\n console.log('[sentient] componentGoal', fullEvent);\n }\n sessionReady.then(() => {\n if (!slotDecideTornDown && mayPersist()) eventQueue.push(fullEvent);\n });\n },\n\n identify(userId) {\n const sid = session.getSessionId();\n if (!sid || slotDecideTornDown || !mayPersist()) return;\n sessionReady.then(() => {\n fetch(`${baseUrl}/sessions`, {\n method: 'POST',\n keepalive: true,\n body: JSON.stringify({ sessionId: sid, userId, ephemeral: session.isEphemeral() }),\n headers: authHeaders,\n }).catch(() => undefined);\n });\n },\n\n track(event) {\n const sessionId = session.getSessionId();\n if (!sessionId || slotDecideTornDown || !mayPersist()) return;\n // Same rule as componentGoal: an impression for a slot arm the core holds\n // without a decision this session (snapshot, failure baseline) trains an\n // arm the server never served. Only ids the core knows AS SLOTS are\n // gated — variant components never enter slotStore and pass through.\n if (\n event.eventType === 'variant_assigned' &&\n slotStore.get(event.componentId) !== undefined &&\n !decidedSlotIds.has(event.componentId) &&\n !assignmentCache.get(event.componentId, sessionSegment)\n ) return;\n\n const fullEvent: SentientEvent = {\n // `path` first so an explicit event.path from the caller wins over the\n // ambient one — a server-side or replayed event knows its page better\n // than location does.\n path: currentPath(),\n ...event,\n id: generateEventId(),\n sessionId,\n timestamp: Date.now(),\n timeInSession: Date.now() - sessionStart,\n };\n\n if (config.debug) {\n console.log('[sentient] track', fullEvent);\n }\n\n sessionReady.then(() => eventQueue.push(fullEvent));\n },\n\n getAssignment(componentId, segment) {\n return assignmentCache.get(componentId, segment);\n },\n\n async assign(componentId, variantIds, agentData?, agentDataByVariant?) {\n const sid = session.getSessionId();\n if (!sid) return null;\n\n const cached = assignmentCache.get(componentId, sessionSegment);\n // When variantIds are provided (A/B code variant), a cache hit is always final.\n // When variantIds are absent (managed text component), only hit the cache if content\n // is present — a seed from initialAssignments has no content and must still fetch.\n if (cached && (variantIds?.length || cached.content !== undefined)) {\n // Surface the entry's remaining TTL (server-provided when set) instead of\n // a hardcoded 0, so callers can reason about when a re-assign is due.\n const remainingTtlMs =\n cached.ttlMs && cached.ttlMs > 0\n ? Math.max(0, cached.assignedAt + cached.ttlMs - Date.now())\n : 0;\n return { variantId: cached.variantId, assignmentTtlMs: remainingTtlMs, content: cached.content };\n }\n\n // Coalesce concurrent assigns for the same component (e.g. several\n // mounted slots sharing one id) into a single network request.\n return coalesce(inflightAssigns, componentId, async () => {\n // Bounded: see SESSION_WAIT_MS. null = the caller keeps its fallback.\n if (!(await settlesWithin(sessionReady, SESSION_WAIT_MS))) return null;\n // Torn down or forgotten while waiting for the session: never send —\n // a sent assign books an exposure the page will not show (NEW-2).\n if (slotDecideTornDown || !mayPersist()) return null;\n const t = timeoutSignal(DECIDE_TIMEOUT_MS);\n try {\n const body: Record<string, unknown> = { sessionId: sid, componentId, variantIds };\n if (agentDataByVariant !== undefined) body.agentDataByVariant = agentDataByVariant;\n else if (agentData !== undefined) body.agentData = agentData;\n // Sent = booked: /v1/assign records the exposure at draw time, so\n // like decide it is never cut short on latency (DECIDE_TIMEOUT_MS\n // frees a dead connection only; a slow answer is still applied).\n const res = await fetch(`${baseUrl}/assign`, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: authHeaders,\n signal: t.signal,\n });\n if (!res.ok) return null;\n const result = (await res.json()) as AssignResult;\n assignmentCache.set(componentId, sessionSegment, {\n variantId: result.variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n content: result.content,\n // Honor the server's TTL as this entry's expiry; omit when absent/0\n // so the cache falls back to its default (DEFAULT_TTL_MS).\n ...(result.assignmentTtlMs && result.assignmentTtlMs > 0\n ? { ttlMs: result.assignmentTtlMs }\n : {}),\n });\n return result;\n } catch {\n return null;\n } finally {\n t.clear();\n }\n });\n },\n\n async decide(input) {\n const sid = session.getSessionId();\n if (!sid) return null;\n const declared = input.slots ?? [];\n\n const body: Record<string, unknown> = { sessionId: sid };\n if (input.sections && input.sections.length > 0) {\n body.sections = input.sections.map((id) => ({ id }));\n }\n body.components = input.components ?? [];\n if (declared.length > 0) body.slots = declared.map(toWireSlot);\n if (input.slotsFrom === 'registry') {\n body.slotsFrom = 'registry';\n if (input.registrySlotIds) body.registrySlotIds = input.registrySlotIds;\n if (input.bootstrap === false) body.bootstrap = false;\n if (input.render && Object.keys(input.render).length > 0) body.render = input.render;\n }\n if (input.v) body.v = input.v;\n // 0 is meaningful here (a two-tag snippet install with no inline pre-paint\n // script), so this is a presence check, not a truthiness one.\n if (typeof input.pp === 'number') body.pp = input.pp;\n // Declared persona rides on decide too: SSR-first flows can race the\n // session upsert, and the decide-body value wins for this decision.\n if (config.persona) body.persona = config.persona;\n\n // Coalesce concurrent IDENTICAL decides into one request + one snapshot\n // write, keyed by the serialized wire payload (also reused as the fetch\n // body). Never key on just \"a decide is running\": coalescing {slots:[a]}\n // with {slots:[b]} would hand slot b's caller an outcome that never\n // decided b. The wire projection is a safe key even though toWireSlot\n // strips SDK-only decl fields — the baselines synthesized for omitted\n // slots below go through baselineResultFor, which projects with the\n // same toWireSlot, so identical payloads imply identical outcomes.\n const decideKey = JSON.stringify(body);\n return coalesce(inflightDecides, decideKey, async () => {\n // Bounded: a decide never sent writes no trial (SESSION_WAIT_MS).\n if (!(await settlesWithin(sessionReady, SESSION_WAIT_MS)) || slotDecideTornDown || !mayPersist()) {\n // Not sent: the session never came, or the visitor withdrew\n // (dispose/destroy/forget) while we waited — a decide sent now\n // would book trials for a page that will not show them (NEW-2).\n seedSlotBaselines(declared);\n return null;\n }\n // Once sent, the server writes the decision whether or not we read\n // the answer, so this is NOT a latency ceiling (see DECIDE_TIMEOUT_MS):\n // an abort leaves a trial for an arm the page never showed.\n const t = timeoutSignal(DECIDE_TIMEOUT_MS);\n try {\n const res = await fetch(`${baseUrl}/decide`, {\n method: 'POST',\n body: decideKey,\n headers: authHeaders,\n signal: t.signal,\n });\n if (!res.ok) {\n seedSlotBaselines(declared);\n return null;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[] | null;\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n goals?: GoalDefinition[];\n sectionMap?: SectionMapEntry[];\n palette?: import('./blocks.js').SitePalette;\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declared) {\n // `data.slots === undefined` means the server predates the slots\n // contract: serve the declared baseline everywhere, do NOT retry.\n // (Distinct from `slots: {}`, which also falls back per-slot.)\n const served = data.slots?.[d.id];\n if (served !== undefined) {\n slots[d.id] = served;\n slotStore.set(d.id, served);\n decidedSlotIds.add(d.id);\n continue;\n }\n // Slot omitted from the response → synthesize a baseline for the\n // RETURN value, but apply the same never-overwrite rule the failure\n // path (seedSlotBaselines) has always had. This success path used\n // to write unconditionally, so a partial response — or a pre-slots\n // server — clobbered SSR-seeded and previously-served results with\n // synthetic baselines.\n const prior = slotStore.get(d.id);\n if (prior !== undefined) {\n slots[d.id] = prior;\n } else {\n const baseline = baselineResultFor(d);\n slots[d.id] = baseline;\n slotStore.set(d.id, baseline);\n }\n }\n // Registry mode: the server returns slots the request never declared.\n // Take them verbatim (classic mode returns only declared slots, so this\n // union is a no-op there — back-compatible). These are real served\n // results, so they may overwrite the store, unlike the baselines above.\n if (data.slots) {\n for (const [slotId, result] of Object.entries(data.slots)) {\n if (!(slotId in slots)) {\n slots[slotId] = result;\n slotStore.set(slotId, result);\n decidedSlotIds.add(slotId);\n }\n }\n }\n // Only overwrite persona when the response actually carries one, and\n // never downgrade a known persona to 'unknown' — a decide that omits\n // persona (or returns 'unknown') must not clobber a good SSR/snapshot/\n // initialPersona value, and must not persist that regression below.\n const known = personaState != null && personaState.persona !== 'unknown';\n if (data.persona && !(data.persona === 'unknown' && known)) {\n personaState = { persona: data.persona, confidence: data.confidence ?? 0 };\n } else if (!personaState) {\n personaState = { persona: 'unknown', confidence: 0 };\n }\n\n // Seed component assignments so <Adaptive>/assign() agree with this\n // decide (same shape as the initialAssignments seed above).\n for (const [componentId, variantId] of Object.entries(data.assignments ?? {})) {\n assignmentCache.set(componentId, sessionSegment, {\n variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n });\n }\n\n // Registry slot config accumulates like slotStore does: a later\n // decide that omits slotConfig (classic mode, partial response) must\n // not evict entries an earlier registry decide served.\n if (data.slotConfig) {\n for (const [slotId, entry] of Object.entries(data.slotConfig)) {\n slotConfigStore.set(slotId, entry);\n }\n }\n if (data.palette) sitePalette = data.palette;\n // Served wins; an absent one leaves the cached copy (same rule as palette).\n if (data.vocabulary) styleVocabulary = data.vocabulary;\n // A scoped registry decide is authoritative for the ids it asked\n // about: one with no config has nothing published NOW. Drop what an\n // earlier visit's snapshot seeded — before the snapshot is rewritten\n // below — or an unpublished/archived slot keeps rendering its old\n // version from localStorage on every visit.\n for (const id of input.registrySlotIds ?? []) {\n if (data.slotConfig?.[id]) continue;\n slotConfigStore.delete(id);\n slotStore.delete(id);\n decidedSlotIds.delete(id);\n }\n\n // Persist for the next visit's pre-paint (SPA cache-first pattern).\n // A decide that landed after forget-me must not write the visitor back\n // (grader NEW-3: destroy() ran while it was in flight).\n if (mayPersist()) writeSnapshot(config.apiKey, {\n v: 1,\n persona: personaState.persona,\n band: confidenceBand(personaState.confidence),\n slots: Object.fromEntries(slotStore),\n layoutOrder: data.layoutOrder ?? null,\n savedAt: Date.now(),\n ...(slotConfigStore.size > 0 ? { slotConfig: Object.fromEntries(slotConfigStore) } : {}),\n ...(sitePalette ? { palette: sitePalette } : {}),\n ...(styleVocabulary ? { vocabulary: styleVocabulary } : {}),\n });\n\n return {\n layoutOrder: data.layoutOrder ?? null,\n assignments: data.assignments ?? {},\n slots,\n persona: personaState.persona,\n confidence: personaState.confidence,\n ...(data.slotConfig ? { slotConfig: data.slotConfig } : {}),\n ...(data.goals ? { goals: data.goals } : {}),\n ...(data.sectionMap ? { sectionMap: data.sectionMap } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n ...(data.vocabulary ? { vocabulary: data.vocabulary } : {}),\n };\n } catch {\n seedSlotBaselines(declared);\n return null;\n } finally {\n t.clear();\n }\n });\n },\n\n getSlotResult(slotId) {\n return slotStore.get(slotId) ?? null;\n },\n\n isSlotDecided(slotId) {\n return decidedSlotIds.has(slotId);\n },\n\n getSlotConfig(slotId) {\n return slotConfigStore.get(slotId) ?? null;\n },\n\n reportSlots(slotIds, baselineTexts, baselineSkeletons, authoredArms) {\n // Authored arms go straight out, deduped per (slot, key): unlike the\n // first-seen id registration below, a hybrid's arms are seen one at a\n // time as the visitor is served them.\n const authored: Record<string, AuthoredArmReport[]> = {};\n for (const [id, list] of Object.entries(authoredArms ?? {})) {\n for (const a of list) {\n const k = `${id}|${a.key}`;\n if (!SLOT_ID_RE.test(id) || reportedAuthored.has(k)) continue;\n reportedAuthored.add(k);\n // Sent as given: the server normalizes and caps the text (the same\n // rule as baselineText), so the lean bundle doesn't carry it twice.\n (authored[id] ??= []).push(a);\n }\n }\n if (Object.keys(authored).length > 0) {\n void fetch(`${baseUrl}/slots/observed`, {\n method: 'POST',\n headers: authHeaders,\n body: JSON.stringify({ slotIds: Object.keys(authored), authoredArms: authored }),\n }).catch(() => undefined);\n }\n // Batch a tick's worth of AdaptiveSlot mounts into one request, once per\n // id per client lifetime — a page of N slots must not fire N registrations\n // on every navigation.\n for (const id of slotIds) {\n if (typeof id !== 'string' || id.length === 0) continue;\n if (!SLOT_ID_RE.test(id)) {\n // Warn once per id, dev builds only — the fetch error the server\n // batch rejection produced was swallowed, so an invalid id was\n // completely silent AND poisoned its whole batch.\n if (isDevBuild() && !warnedInvalidSlotIds.has(id)) {\n warnedInvalidSlotIds.add(id);\n console.warn(\n `[sentient] reportSlots: slot id ${JSON.stringify(id)} will not register — ids must start ` +\n `with a letter or digit and contain only letters, digits, '_' or '-' (max 128 chars): ` +\n `/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.`,\n );\n }\n continue;\n }\n if (!reportedSlotIds.has(id)) {\n reportedSlotIds.add(id);\n pendingSlotReports.add(id);\n // Normalize before it leaves the page: whitespace collapsed, hard\n // 400-char cap. Only the region the developer explicitly wrapped\n // for replacement is read — never the page around it.\n const raw = baselineTexts?.[id];\n if (typeof raw === 'string') {\n const text = raw.replace(/\\s+/g, ' ').trim().slice(0, 400);\n if (text !== '') pendingBaselineTexts.set(id, text);\n }\n const sk = baselineSkeletons?.[id];\n if (sk !== undefined) pendingBaselineSkeletons.set(id, sk);\n }\n }\n if (pendingSlotReports.size === 0 || slotReportTimer != null) return;\n slotReportTimer = setTimeout(() => {\n slotReportTimer = null;\n const all = [...pendingSlotReports];\n pendingSlotReports.clear();\n // Chunks of 20 — the server's MAX_BATCH. This used to slice(0, 20) and\n // clear(), so ids 21+ were dropped permanently: already marked as\n // reported, never sent, never retried. Sequential fire-and-forget keeps\n // the send path as cheap as the single-batch one.\n for (let i = 0; i < all.length; i += 20) {\n const chunk = all.slice(i, i + 20);\n const texts: Record<string, string> = {};\n const skels: Record<string, SkeletonReport> = {};\n for (const id of chunk) {\n const t = pendingBaselineTexts.get(id);\n if (t !== undefined) {\n texts[id] = t;\n pendingBaselineTexts.delete(id);\n }\n const sk = pendingBaselineSkeletons.get(id);\n if (sk !== undefined) {\n skels[id] = sk;\n pendingBaselineSkeletons.delete(id);\n }\n }\n void fetch(`${baseUrl}/slots/observed`, {\n method: 'POST',\n headers: authHeaders,\n body: JSON.stringify({\n slotIds: chunk,\n ...(Object.keys(texts).length > 0 ? { baselineTexts: texts } : {}),\n ...(Object.keys(skels).length > 0 ? { baselineSkeletons: skels } : {}),\n // Where these regions live: a Redesign brief reads that page's text.\n pagePaths: Object.fromEntries(chunk.map((id) => [id, location.pathname])),\n // A baseline-text vote counts only once this session is scored\n // human with events (server C8); without it the vote never\n // promotes, so the text would wait for owner confirmation.\n ...(Object.keys(texts).length > 0 && session.getSessionId() ? { sessionId: session.getSessionId() } : {}),\n }),\n }).catch(() => undefined);\n }\n }, 1000);\n },\n\n reportSkeleton(slotId, skeleton) {\n if (!SLOT_ID_RE.test(slotId) || reportedSkeletonIds.has(slotId)) return;\n reportedSkeletonIds.add(slotId);\n // Same endpoint as first registration: the slot exists, so the insert is\n // a no-op and the server's fill-once UPDATE stores the skeleton.\n void fetch(`${baseUrl}/slots/observed`, {\n method: 'POST',\n headers: authHeaders,\n body: JSON.stringify({ slotIds: [slotId], baselineSkeletons: { [slotId]: skeleton } }),\n }).catch(() => undefined);\n },\n\n reportDrift(slotId, expectedFp, observedFp, reason) {\n // Once per (slot, fingerprint) per client — that dedupe bounds volume,\n // so no batching timer. The server applies the visitors-and-rate rule.\n const key = `${slotId}|${expectedFp}`;\n const sid = session.getSessionId();\n if (!sid || reportedDrift.has(key)) return;\n reportedDrift.add(key);\n void fetch(`${baseUrl}/slots/drift`, {\n method: 'POST',\n headers: authHeaders,\n body: JSON.stringify({ sessionId: sid, reports: [{ slotId, expectedFp, observedFp, reason }] }),\n }).catch(() => undefined);\n },\n\n requestSlots(slotIds, baselineTexts, extras) {\n for (const id of slotIds) {\n if (requestedSlotIds.has(id)) continue;\n requestedSlotIds.add(id);\n // An invalid id would 400 the whole scoped decide; reportSlots owns\n // the dev warning for it and refuses it there.\n if (SLOT_ID_RE.test(id)) {\n pendingSlotTexts.set(id, {\n text: baselineTexts?.[id],\n render: extras?.render?.[id],\n skeleton: extras?.skeletons?.[id],\n });\n } else client.reportSlots([id]);\n }\n if (pendingSlotTexts.size === 0 || slotRequestTimer != null) return;\n // 0ms: every AdaptiveSlot mounted in the same commit lands in one request.\n slotRequestTimer = setTimeout(() => {\n slotRequestTimer = null;\n const all = [...pendingSlotTexts];\n pendingSlotTexts.clear();\n for (let i = 0; i < all.length; i += 50) {\n const chunk = all.slice(i, i + 50);\n const render: Record<string, RenderCaps> = {};\n for (const [id, p] of chunk) if (p.render) render[id] = p.render;\n void client\n .decide({ slotsFrom: 'registry', registrySlotIds: chunk.map(([id]) => id), bootstrap: false, render })\n .then((out) => {\n // A failed decide registers nothing: \"the network blipped\" must not\n // read as \"this slot has nothing published\".\n if (out) {\n const texts: Record<string, string> = {};\n const skels: Record<string, SkeletonReport> = {};\n const missing: string[] = [];\n for (const [id, p] of chunk) {\n const cfg = out.slotConfig?.[id];\n if (cfg) {\n // Published but never captured: fill it from this page.\n if (cfg.needsSkeleton && p.skeleton) client.reportSkeleton?.(id, p.skeleton);\n continue;\n }\n missing.push(id);\n if (p.text) texts[id] = p.text;\n if (p.skeleton) skels[id] = p.skeleton;\n }\n if (missing.length > 0) client.reportSlots(missing, texts, skels);\n } else {\n // Release the ids (a remount re-asks) and retry this batch with\n // backoff — see retryFailedSlots.\n retryFailedSlots(chunk.map(([id]) => id), requestedSlotIds, (retry) => {\n const texts: Record<string, string> = {};\n const retryRender: Record<string, RenderCaps> = {};\n const skels: Record<string, SkeletonReport> = {};\n for (const [id, p] of chunk) {\n if (!retry.has(id)) continue;\n if (p.text) texts[id] = p.text;\n if (p.render) retryRender[id] = p.render;\n if (p.skeleton) skels[id] = p.skeleton;\n }\n client.requestSlots?.([...retry], texts, { render: retryRender, skeletons: skels });\n });\n }\n slotListeners.forEach((l) => l());\n });\n }\n }, 0);\n },\n\n decideSlots(decls) {\n for (const d of decls) {\n if (decidedDeclIds.has(d.id)) continue;\n decidedDeclIds.add(d.id);\n pendingDecls.set(d.id, d);\n }\n if (pendingDecls.size === 0 || declTimer != null) return;\n declTimer = setTimeout(() => {\n declTimer = null;\n const all = [...pendingDecls.values()];\n pendingDecls.clear();\n // 30 per request: the server's decide `slots` cap.\n for (let i = 0; i < all.length; i += 30) {\n const batch = all.slice(i, i + 30);\n void client.decide({ slots: batch }).then((out) => {\n // The failure path already seeded every declared slot's baseline\n // into slotStore (unexposed — isSlotDecided stays false); release\n // the ids and retry with backoff so the slot gets a real decision.\n if (!out) {\n retryFailedSlots(batch.map((d) => d.id), decidedDeclIds, (retry) =>\n client.decideSlots?.(batch.filter((d) => retry.has(d.id))));\n }\n slotListeners.forEach((l) => l());\n });\n }\n }, 0);\n },\n\n cancelSlots(slotIds) {\n for (const id of slotIds) {\n // Only a still-pending ask is withdrawn; once sent, the id stays\n // marked so the in-flight answer is not duplicated by a remount.\n if (pendingSlotTexts.delete(id)) requestedSlotIds.delete(id);\n if (pendingDecls.delete(id)) decidedDeclIds.delete(id);\n }\n },\n\n onSlotsChanged(listener) {\n slotListeners.add(listener);\n return () => void slotListeners.delete(listener);\n },\n\n getStyleVocabulary() {\n return styleVocabulary;\n },\n\n getSitePalette() {\n return sitePalette;\n },\n\n getPersona() {\n if (!personaState) return null;\n return {\n persona: personaState.persona,\n confidence: personaState.confidence,\n band: confidenceBand(personaState.confidence),\n };\n },\n\n async fetchWeights() {\n const t = timeoutSignal(REQUEST_TIMEOUT_MS);\n try {\n const res = await fetch(`${baseUrl}/weights`, { headers: authHeaders, signal: t.signal });\n if (!res.ok) return [];\n const data = (await res.json()) as { components: ComponentWeightEntry[] };\n return data.components ?? [];\n } catch {\n return [];\n } finally {\n t.clear();\n }\n },\n\n getGraph() {\n return { pageNodes: [], capturedAt: 0 };\n },\n\n flush() {\n // Both queues: a goal banked late in a lifecycle handler races the same\n // unload pipeline the event queue does.\n eventQueue.flush();\n goalQueue.flush();\n },\n\n dispose() {\n // Stops the flush timer and unload listeners (with a final flush) but\n // leaves identity, snapshot, and retry buckets for the next client.\n stopPageviews?.();\n pageviewsTornDown = true;\n slotDecideTornDown = true;\n eventQueue.destroy();\n goalQueue.destroy();\n // Drop the registry entry so a later re-init doesn't try to dispose an\n // already-torn-down client (and so the map doesn't pin this closure).\n if (_clients.get(config.apiKey)?.dispose === client.dispose) {\n _clients.delete(config.apiKey);\n }\n if (config.debug) {\n console.log('[sentient] disposed');\n }\n },\n\n destroy() {\n stopPageviews?.();\n pageviewsTornDown = true;\n slotDecideTornDown = true;\n // Before anything else: in-flight decides/assigns check these.\n forgottenHere = true;\n markForgotten(config.apiKey);\n eventQueue.destroy({ forget: true });\n goalQueue.destroy({ forget: true });\n session.destroy();\n // The assignment cache persists in localStorage (`_snt_asgn_*`) with a\n // 30-minute default TTL — left in place, a revoked visitor returning\n // within that window was handed their previous personalized variants\n // back, so forget-me wasn't total.\n assignmentCache.clear();\n if (_clients.get(config.apiKey)?.dispose === client.dispose) {\n _clients.delete(config.apiKey);\n }\n // Forget-me must be total: a surviving decision snapshot would\n // re-personalize the next visit via the pre-paint script, and a\n // persisted retry bucket would re-send events for the deleted identity.\n try {\n localStorage.removeItem(SNAPSHOT_STORAGE_KEY_PREFIX + config.apiKey);\n localStorage.removeItem(retryStorageKey(config.apiKey));\n localStorage.removeItem(goalRetryStorageKey(config.apiKey));\n // The graph caches too (the graph entry also clears them): forget-me\n // on a lean client left them (review #9).\n localStorage.removeItem(`_snt_graph_nodes${storageSuffix(config.apiKey)}`);\n localStorage.removeItem('_snt_graph_edges');\n } catch {\n /* storage unavailable — nothing persisted to remove */\n }\n if (config.debug) {\n console.log('[sentient] destroyed');\n }\n },\n };\n\n _clients.set(config.apiKey, { config, upgrade: null, dispose: client.dispose });\n\n stopPageviews = startPageviewTracking(client, config.apiKey, (key) => {\n // track() defers its enqueue on sessionReady; chaining after it means this\n // runs once the push has happened. If the client was torn down first, the\n // event went into a destroyed queue and never ships — leave the page\n // unmarked so the replacement client's emit is the one that counts.\n void sessionReady.then(() => {\n if (!pageviewsTornDown) emittedPages.add(key);\n });\n });\n\n if (config.debug) {\n const win = window as unknown as { __sentient?: { client: SentientClient } };\n if (win.__sentient) {\n win.__sentient.client = client;\n }\n }\n\n return client;\n}\n","export type MicroSignalEmitter = (\n signalType: 'rage_click' | 'text_copy' | 'scroll_hesitation' | 'tab_loss',\n extra?: Record<string, unknown>,\n) => void;\n\nexport type MicroSignalType = Parameters<MicroSignalEmitter>[0];\n\n/**\n * Attaches passive behavioral detectors to `node`. Calls `emit` when a signal\n * fires. Each signal type fires at most once per call to this function.\n * Returns a cleanup function that removes all listeners.\n */\nexport function attachMicroSignalDetectors(\n emit: MicroSignalEmitter,\n node: Element,\n variantAssignedAt?: number,\n options?: { tabLoss?: boolean },\n): () => void {\n const cleanups: Array<() => void> = [];\n\n // --- Rage click: 3+ clicks within 500ms ---\n {\n const WINDOW_MS = 500;\n const THRESHOLD = 3;\n let firedOnce = false;\n const timestamps: number[] = [];\n\n const onClick = (): void => {\n if (firedOnce) return;\n const now = Date.now();\n timestamps.push(now);\n while (timestamps.length > 0 && now - timestamps[0]! > WINDOW_MS) {\n timestamps.shift();\n }\n if (timestamps.length >= THRESHOLD) {\n firedOnce = true;\n emit('rage_click');\n }\n };\n\n node.addEventListener('click', onClick);\n cleanups.push(() => node.removeEventListener('click', onClick));\n }\n\n // --- Text copy: copy event within node ---\n {\n let firedOnce = false;\n\n const onCopy = (e: Event): void => {\n if (firedOnce) return;\n if (!(e.target instanceof Node)) return;\n if (!node.contains(e.target) && node !== e.target) return;\n firedOnce = true;\n const sel = typeof window !== 'undefined' ? window.getSelection() : null;\n const selectionLength = sel ? sel.toString().length : 0;\n emit('text_copy', { selectionLength });\n };\n\n document.addEventListener('copy', onCopy);\n cleanups.push(() => document.removeEventListener('copy', onCopy));\n }\n\n // --- Scroll hesitation: scroll stops 3s while component visible ---\n {\n let firedOnce = false;\n let isVisible = false;\n let hesitationTimer: ReturnType<typeof setTimeout> | null = null;\n\n const clearHesitation = (): void => {\n if (hesitationTimer !== null) {\n clearTimeout(hesitationTimer);\n hesitationTimer = null;\n }\n };\n\n const startHesitation = (): void => {\n if (firedOnce || !isVisible) return;\n clearHesitation();\n hesitationTimer = setTimeout(() => {\n if (!firedOnce && isVisible) {\n firedOnce = true;\n emit('scroll_hesitation');\n }\n }, 3000);\n };\n\n const onScroll = (): void => {\n clearHesitation();\n startHesitation();\n };\n\n const ioCallback = (entries: IntersectionObserverEntry[]): void => {\n for (const entry of entries) {\n isVisible = entry.intersectionRatio > 0.3;\n if (!isVisible) clearHesitation();\n else startHesitation();\n }\n };\n const io = new IntersectionObserver(ioCallback, { threshold: [0.3] });\n io.observe(node);\n window.addEventListener('scroll', onScroll, { passive: true });\n\n cleanups.push(() => {\n io.disconnect();\n window.removeEventListener('scroll', onScroll);\n clearHesitation();\n });\n }\n\n // --- Tab loss: tab hidden within 15s of variant_assigned ---\n // Document-level (not node-scoped), so callers that attach detectors to many\n // nodes at once (e.g. the snippet's per-option slot signals) can opt out on all\n // but one node to avoid emitting a duplicate tab_loss per node (audit M5).\n if (options?.tabLoss !== false) {\n let firedOnce = false;\n const assignedAt = variantAssignedAt ?? Date.now();\n\n const onVisibility = (): void => {\n if (firedOnce) return;\n if (document.visibilityState !== 'hidden') return;\n const elapsed = Date.now() - assignedAt;\n if (elapsed < 15_000) {\n firedOnce = true;\n emit('tab_loss', { timeOnPage: elapsed });\n }\n };\n\n document.addEventListener('visibilitychange', onVisibility);\n cleanups.push(() => document.removeEventListener('visibilitychange', onVisibility));\n }\n\n return () => {\n for (const c of cleanups) c();\n };\n}\n","import type { CompoundLocator } from './snapshot.js';\n\n// Live-DOM twin of apps/api/src/domain/locator-from-html.ts. The two MUST stay\n// in step: section_key is a hash of this object, so any divergence silently\n// splits one physical section into two identities — a crawl-derived one and a\n// client-derived one — and every per-section number downstream halves.\n// Cross-implementation parity is locked by apps/api/src/domain/locator-parity.test.ts.\n// data-sentient-id FIRST (added 2026-09-05, both generators together): it is\n// the one attribute a site authors specifically to name a section for us, and\n// it is exactly what hydration and redesigns do NOT rewrite. Elements with a\n// unique `id` are unaffected (id outranks data attrs); for the rest the change\n// moves section_key once — ingest-time fingerprint reconciliation\n// (section-key-reconcile.ts) writes the alias, and no offline backfill is\n// possible because pre-change locators never captured the attribute.\nconst STABLE_DATA_ATTRS = ['data-sentient-id', 'data-testid', 'data-test', 'data-id', 'data-name', 'data-cy'];\nconst FINGERPRINT_TEXT_MAX = 40;\n\nfunction normalizedText(el: Element): string {\n return (el.textContent ?? '').replace(/\\s+/g, ' ').trim();\n}\n\nfunction fingerprintOf(el: Element): { tag: string; text: string } {\n return {\n tag: el.tagName.toLowerCase(),\n text: normalizedText(el).slice(0, FINGERPRINT_TEXT_MAX),\n };\n}\n\nfunction cssEscape(v: string): string {\n return v.replace(/[\"\\\\\\]]/g, '\\\\$&');\n}\n\nfunction unique(root: ParentNode, selector: string): boolean {\n try {\n return root.querySelectorAll(selector).length === 1;\n } catch {\n return false;\n }\n}\n\n/** Shortest unique selector: tag, tag.class, then parent-qualified, then nth-of-type chain. */\nfunction uniqueSelector(el: Element, root: ParentNode): string | null {\n const tag = el.tagName.toLowerCase();\n if (!tag) return null;\n const classes = (el.getAttribute('class') ?? '').split(/\\s+/).filter((c) => /^[a-zA-Z][\\w-]*$/.test(c));\n const candidates = [tag, ...classes.map((c) => `${tag}.${c}`)];\n for (const c of candidates) if (unique(root, c)) return c;\n const parent = el.parentElement;\n if (parent && (parent as ParentNode) !== root) {\n const parentSel = uniqueSelector(parent, root);\n if (parentSel) {\n for (const c of candidates) {\n const combined = `${parentSel} > ${c}`;\n if (unique(root, combined)) return combined;\n }\n // Element-only children: matches the server's rawTagName filter over\n // childNodes, which excludes text nodes.\n const siblings = Array.from(parent.children).filter((n) => n.tagName.toLowerCase() === tag);\n const idx = siblings.indexOf(el);\n // An nth-of-type selector is only trustworthy when it pairs with a\n // fingerprint that could actually catch drift: if every same-tag sibling\n // has identical text, the node is a true duplicate and the {tag, text}\n // check can never distinguish \"still the right one\" from \"DOM reordered,\n // now pointing at the wrong duplicate\". Refuse it rather than return a\n // false sense of precision.\n const distinguishable = siblings.some((s) => s !== el && normalizedText(s) !== normalizedText(el));\n if (idx >= 0 && distinguishable) {\n const nth = `${parentSel} > ${tag}:nth-of-type(${idx + 1})`;\n if (unique(root, nth)) return nth;\n }\n }\n }\n return null;\n}\n\n/** Build a compound locator for a live DOM element. Returns null when nothing\n * resolves uniquely — the runtime never guesses an identity. */\nexport function locatorFromElement(el: Element, root: ParentNode): CompoundLocator | null {\n const fingerprint = fingerprintOf(el);\n const id = el.getAttribute('id');\n if (id && unique(root, `#${cssEscape(id)}`)) return { v: 1, id, fingerprint };\n for (const name of STABLE_DATA_ATTRS) {\n const value = el.getAttribute(name);\n if (value && unique(root, `[${name}=\"${cssEscape(value)}\"]`)) {\n return { v: 1, dataAttr: { name, value }, fingerprint };\n }\n }\n const selector = uniqueSelector(el, root);\n if (selector) return { v: 1, selector, fingerprint };\n return null;\n}\n","//\n// Session-scoped interaction AGGREGATES for the browser-agent axis (spec\n// 2026-09-22-agent-axis-human-verified-numbers-design.md §4.1). Counts, means\n// and variances only: no per-event timestamps, no coordinates, no text. A\n// raw trace is arguably a biometric; these statistics are not, and the whole\n// privacy posture of the feature rests on that line staying where it is.\n//\n// The collector knows nothing about the network. It exposes a snapshot; the\n// engagement capture decides when to emit it, under its own DNT/consent gate.\n\nexport type InteractionStats = {\n v: 1;\n active_ms: number;\n mm: number;\n /** Mousemoves per VISIBLE second, 2 dp. The count alone does not separate:\n * a driver dispatches one mousemove per click, so `mm === 0` is false for\n * the commonest automation stack (measured: Playwright emits 3 over a\n * 6-action script). The rate does — humans emit tens per second, drivers\n * around one. Carried alongside `mm` so a future threshold can use either. */\n mm_rate: number;\n touches: number;\n clicks: number;\n /** How many mousedown→mouseup pairs `hold_mean`/`hold_std` rest on. Without\n * it a zero-variance hold (a driver pressing and releasing in one tick) is\n * indistinguishable from never having measured one at all, and the scorer\n * would condemn the second case on the evidence of the first. */\n hold_n: number;\n hold_mean: number;\n hold_std: number;\n teleport: number;\n wheel: number;\n scroll_px: number;\n keydowns: number;\n input_chars: number;\n ik_cv: number;\n backspaces: number;\n gaps: [number, number, number, number, number, number];\n reduced_motion: boolean;\n kb_nav: number;\n renderer: 'sw' | 'hw' | 'unknown';\n vp: [number, number];\n dpr: number;\n};\n\nexport type InteractionCollector = { snapshot(): InteractionStats; stop(): void };\n\n/** Log-spaced action-gap edges (ms). Six buckets: <100, <300, <1000, <3000,\n * <10000, >=10000. LLM agents pile into the two ends (instant bursts after\n * model latency); humans sit in the middle. */\nexport const GAP_EDGES_MS: readonly number[] = [100, 300, 1000, 3000, 10000];\n\nconst TELEPORT_WINDOW_MS = 250;\nconst TOUCH_RECENT_MS = 1000;\nconst NAV_KEYS = new Set(['Tab', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']);\n\n/** Welford running mean/variance — one object per measured quantity, so the\n * std of click hold and the CV of inter-key intervals cost 3 numbers each. */\ntype Welford = { n: number; mean: number; m2: number };\nfunction push(w: Welford, x: number): void {\n w.n++;\n const d = x - w.mean;\n w.mean += d / w.n;\n w.m2 += d * (x - w.mean);\n}\nconst std = (w: Welford): number => (w.n > 1 ? Math.sqrt(w.m2 / w.n) : 0);\n\nfunction rendererClass(doc: Document): InteractionStats['renderer'] {\n try {\n const canvas = doc.createElement('canvas');\n const gl = (canvas.getContext('webgl') || canvas.getContext('experimental-webgl')) as\n | (WebGLRenderingContext & { getExtension(name: string): { UNMASKED_RENDERER_WEBGL: number } | null })\n | null;\n if (!gl) return 'unknown';\n const ext = gl.getExtension('WEBGL_debug_renderer_info');\n const name = ext ? String(gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) ?? '') : '';\n if (!name) return 'unknown';\n // Software rasterisers are what headless Chromium ships without a GPU.\n // Corroboration only — stealth tooling patches this string first — so the\n // scorer weights it low (spec §4.2).\n return /swiftshader|llvmpipe|softpipe|software|mesa offscreen/i.test(name) ? 'sw' : 'hw';\n } catch {\n return 'unknown';\n }\n}\n\nexport function startInteractionCollector(doc: Document, now: () => number = Date.now): InteractionCollector {\n const win = doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined);\n const hold: Welford = { n: 0, mean: 0, m2: 0 };\n const interkey: Welford = { n: 0, mean: 0, m2: 0 };\n const gaps: InteractionStats['gaps'] = [0, 0, 0, 0, 0, 0];\n let mm = 0, touches = 0, clicks = 0, teleport = 0, wheel = 0, scrollPx = 0;\n let keydowns = 0, inputChars = 0, backspaces = 0, kbNav = 0;\n let lastMoveAt = -Infinity, lastTouchAt = -Infinity, downAt: number | null = null;\n let lastKeyAt: number | null = null, lastActionAt: number | null = null;\n let lastScrollY = win?.scrollY ?? 0;\n // Visible wall-clock: banked on hide, resumed on show. A hidden tab must not\n // accrue \"activity\", or a background tab left open all day reads as a\n // deeply engaged visitor with no mouse — the assistive-technology signature.\n let banked = 0;\n let visibleSince: number | null = doc.hidden ? null : now();\n\n const action = (): void => {\n const t = now();\n if (lastActionAt != null) {\n const g = t - lastActionAt;\n let i = 0;\n while (i < GAP_EDGES_MS.length && g >= GAP_EDGES_MS[i]!) i++;\n gaps[i as 0 | 1 | 2 | 3 | 4 | 5]++;\n }\n lastActionAt = t;\n };\n\n const onMove = (): void => { mm++; lastMoveAt = now(); };\n const onTouch = (): void => { touches++; lastTouchAt = now(); };\n const onDown = (): void => { downAt = now(); };\n const onUp = (): void => { if (downAt != null) { push(hold, now() - downAt); downAt = null; } };\n const onClick = (): void => {\n const t = now();\n clicks++;\n // A click with no pointer travel before it was placed at computed\n // coordinates — unless it was a tap, which never moves a mouse.\n if (t - lastMoveAt > TELEPORT_WINDOW_MS && t - lastTouchAt > TOUCH_RECENT_MS) teleport++;\n action();\n };\n const onWheel = (): void => { wheel++; };\n const onScroll = (): void => {\n const y = win?.scrollY ?? 0;\n scrollPx += Math.abs(y - lastScrollY);\n lastScrollY = y;\n // A scroll IS an action for gap purposes. Without this a session that\n // reads by scrolling contributes almost nothing to the gap histogram —\n // measured 3 gaps across a six-action script, far below what any shape\n // test can read.\n action();\n };\n const onKey = (e: KeyboardEvent): void => {\n const t = now();\n keydowns++;\n if (e.key === 'Backspace' || e.key === 'Delete') backspaces++;\n if (NAV_KEYS.has(e.key)) kbNav++;\n if (lastKeyAt != null) push(interkey, t - lastKeyAt);\n lastKeyAt = t;\n action();\n };\n const onInput = (e: Event): void => {\n const data = (e as InputEvent).data;\n if (typeof data === 'string') inputChars += data.length;\n action();\n };\n const onVisibility = (): void => {\n const t = now();\n if (doc.hidden) { if (visibleSince != null) { banked += t - visibleSince; visibleSince = null; } }\n else if (visibleSince == null) visibleSince = t;\n };\n\n const opts: AddEventListenerOptions = { passive: true, capture: true };\n doc.addEventListener('mousemove', onMove, opts);\n doc.addEventListener('touchstart', onTouch, opts);\n doc.addEventListener('touchmove', onWheel, opts);\n doc.addEventListener('mousedown', onDown, opts);\n doc.addEventListener('mouseup', onUp, opts);\n doc.addEventListener('click', onClick, opts);\n doc.addEventListener('wheel', onWheel, opts);\n doc.addEventListener('keydown', onKey as EventListener, opts);\n doc.addEventListener('input', onInput, opts);\n doc.addEventListener('visibilitychange', onVisibility);\n win?.addEventListener('scroll', onScroll, opts);\n\n const renderer = rendererClass(doc);\n const reducedMotion = ((): boolean => {\n try { return win?.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true; } catch { return false; }\n })();\n\n return {\n snapshot(): InteractionStats {\n const t = now();\n const active = banked + (visibleSince != null ? t - visibleSince : 0);\n return {\n v: 1,\n active_ms: Math.round(active),\n mm,\n mm_rate: active > 0 ? Number(((mm * 1000) / active).toFixed(2)) : 0,\n touches, clicks,\n hold_n: hold.n,\n hold_mean: Math.round(hold.mean),\n hold_std: Math.round(std(hold)),\n teleport, wheel,\n scroll_px: Math.round(scrollPx),\n keydowns,\n input_chars: inputChars,\n ik_cv: interkey.mean > 0 ? Number((std(interkey) / interkey.mean).toFixed(2)) : 0,\n backspaces,\n gaps: [...gaps] as InteractionStats['gaps'],\n reduced_motion: reducedMotion,\n kb_nav: kbNav,\n renderer,\n vp: [win?.innerWidth ?? 0, win?.innerHeight ?? 0],\n dpr: win?.devicePixelRatio || 1,\n };\n },\n stop(): void {\n doc.removeEventListener('mousemove', onMove, opts);\n doc.removeEventListener('touchstart', onTouch, opts);\n doc.removeEventListener('touchmove', onWheel, opts);\n doc.removeEventListener('mousedown', onDown, opts);\n doc.removeEventListener('mouseup', onUp, opts);\n doc.removeEventListener('click', onClick, opts);\n doc.removeEventListener('wheel', onWheel, opts);\n doc.removeEventListener('keydown', onKey as EventListener, opts);\n doc.removeEventListener('input', onInput, opts);\n doc.removeEventListener('visibilitychange', onVisibility);\n win?.removeEventListener('scroll', onScroll, opts);\n },\n };\n}\n"],"mappings":"2xBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,iCAAAE,GAAA,mBAAAC,EAAA,qBAAAC,EAAA,oBAAAC,GAAA,wBAAAC,EAAA,2BAAAC,KAAA,eAAAC,GAAAR,ICgCO,IAAMS,EAA0C,CACrD,UAAW,OAAQ,eAAgB,MAAO,WAC1C,MAAO,aAAc,QAAS,aAAc,SAC9C,EA4BMC,GAAqC,CACzC,OAAQ,OACR,WAAY,aACZ,YAAa,QACf,EAQO,SAASC,GAAkBC,EAAmC,CACnE,IAAMC,EAAOD,EAAE,SAAWF,GAAWE,EAAE,SAAS,YAAY,CAAC,EAAI,OACjE,GAAIC,EAAM,OAAOA,EACjB,GAAID,EAAE,MAAQ,MAAO,MAAO,aAC5B,GAAIA,EAAE,MAAQ,SAAU,MAAO,SAgB/B,GAAIA,EAAE,MAAQ,SAAU,OAAOA,EAAE,aAAe,EAAI,aAAe,OACnE,IAAME,EAAM,GAAGF,EAAE,OAAO,IAAIA,EAAE,WAAW,GAAG,YAAY,EACxD,MAAI,kEAAkE,KAAKE,CAAG,EACrE,SAAS,KAAKA,CAAG,EAAI,SAAW,aAMrC,iCAAiC,KAAKF,EAAE,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ACT,cAAcS,CAAS,EACvBnB,EAAY,KAAK,EACjBlD,EAAI,oBAAoB,mBAAoB+D,CAAY,EACxDK,GAAA,MAAAA,EAAK,oBAAoB,WAAYH,GACrCG,GAAA,MAAAA,EAAK,oBAAoB,WAAYD,GACrC,QAAW/D,KAAKkE,EAAkBlE,EAAE,EACpC,GAAI,CAAEsD,EAAS,WAAW,CAAG,OAAQ/C,EAAA,CAAe,CACtD,CACF","names":["index_engagement_exports","__export","INTERACTION_STATS_COMPONENT","SEMANTIC_TYPES","classifyFeatures","classifySection","featuresFromElement","startEngagementCapture","__toCommonJS","SEMANTIC_TYPES","ARIA_TOPIC","structuralTopicOf","f","aria","hay","fallbackTopicOf","KEYWORDS","CONTENT_PATTERNS","SHARED_TOPIC_PARENT","headingText","el","_a","h","classifyFeatures","_b","structural","type","re","fb","featuresFromElement","text","role","__spreadValues","classifySection","import_policy","import_policy","attachMicroSignalDetectors","emit","node","variantAssignedAt","options","cleanups","firedOnce","timestamps","onClick","now","onCopy","e","sel","selectionLength","isVisible","hesitationTimer","clearHesitation","startHesitation","onScroll","ioCallback","entries","entry","io","assignedAt","onVisibility","elapsed","c","isDoNotTrackEnabled","v","STABLE_DATA_ATTRS","normalizedText","el","_a","fingerprintOf","cssEscape","v","unique","root","selector","e","uniqueSelector","tag","classes","c","candidates","parent","parentSel","combined","siblings","n","idx","distinguishable","s","nth","locatorFromElement","fingerprint","id","name","STABLE_DATA_ATTRS","value","GAP_EDGES_MS","TELEPORT_WINDOW_MS","TOUCH_RECENT_MS","NAV_KEYS","push","w","x","d","std","rendererClass","doc","_a","canvas","gl","ext","name","e","startInteractionCollector","now","_b","win","hold","interkey","gaps","mm","touches","clicks","teleport","wheel","scrollPx","keydowns","inputChars","backspaces","kbNav","lastMoveAt","lastTouchAt","downAt","lastKeyAt","lastActionAt","lastScrollY","banked","visibleSince","action","t","g","i","onMove","onTouch","onDown","onUp","onClick","onWheel","onScroll","y","onKey","onInput","data","onVisibility","opts","renderer","reducedMotion","active","SECTION_SELECTOR","HEARTBEAT_MS","INTERACTION_STATS_COMPONENT","selectSections","doc","candidates","kept","el","c","k","registerSections","apiKey","apiBase","pageUrl","sections","e","NOOP","startEngagementCapture","client","opts","_a","_b","_c","_d","_e","_f","_g","_h","_i","_j","_k","_l","_m","_n","_o","isDoNotTrackEnabled","els","componentOf","entries","markup","t","SEMANTIC_TYPES","f","featuresFromElement","type","classifyFeatures","locator","locatorFromElement","componentId","patternFlags","CONTENT_PATTERNS","re","__spreadProps","__spreadValues","interaction","startInteractionCollector","emitInteraction","snap","state","get","id","s","observer","entry","emit","leaving","now","onVisibility","frozen","onPageHide","event","onPageShow","win","heartbeat","detectorCleanups","i","attachMicroSignalDetectors","signalType","extra"]}
1
+ {"version":3,"sources":["../src/index-engagement.ts","../src/engagement/classify.ts","../src/engagement/capture.ts","../src/index.ts","../src/micro-signals.ts","../src/locator-from-dom.ts","../src/engagement/interaction-stats.ts"],"sourcesContent":["// Lazy engagement entry — loaded on demand (mirrors ./graph) so the lean\n// bundle never carries the section classifier or IntersectionObserver logic.\nexport {\n startEngagementCapture,\n INTERACTION_STATS_COMPONENT,\n type EngagementCaptureOptions,\n type InteractionStats,\n} from './engagement/capture';\nexport {\n classifyFeatures,\n classifySection,\n featuresFromElement,\n SEMANTIC_TYPES,\n type SectionFeatures,\n type SemanticType,\n} from './engagement/classify';\n","// Semantic section classification for no-code section capture (Phase 3 §2.4).\n// Pure heuristic: element → one of the graph_nodes semantic_type enum. Mirrors\n// the SDK graph scanner's vocabulary so the persona × section matrix consumes\n// snippet-captured sections unchanged.\n//\n// SPLIT (Phase 2b, spec 2026-09-04). This module is the BROWSER-SAFE core:\n// structural rules, the small parent-level keyword table, and the fallbacks.\n// The rich ~40-topic vocabulary lives in ./topics.ts, which only the server\n// imports — shipping it here cost 1.5 KB gzip in every bundle (7% of the\n// always-on snippet) for a layer the browser never reads, since classifySection\n// returns only the parent.\n//\n// Both paths share structuralTopicOf/fallbackTopicOf, so the three fixes below\n// apply identically on client and server; only vocabulary richness differs.\n//\n// Fixes, each reproduced against the shipped classifier before being changed:\n// 1. structural before the converter fallback — `<div class=\"navbar\">` used\n// to become `cta`, because `navigation` was reachable only via tag\n// nav/footer.\n// 2. hero before the converter fallback — the cta rule sat above both hero\n// rules, so a `<header>` with a button and <200 chars could never be hero.\n// 3. tightened pricing/social keywords — `plans?` and `customers?` fired on\n// unrelated copy AND were `strong`, so they auto-applied at confidence 0.9\n// and were never sent to the LLM fallback.\n\nexport type SemanticType =\n | 'pricing' | 'hero' | 'social_proof' | 'cta' | 'features'\n | 'faq' | 'comparison' | 'trust' | 'navigation' | 'generic';\n\nexport type SectionRole = 'converter' | 'persuader' | 'structural';\n\n/** Canonical vocabulary — mirrors the graph_nodes semantic_type CHECK enum. */\nexport const SEMANTIC_TYPES: readonly SemanticType[] = [\n 'pricing', 'hero', 'social_proof', 'cta', 'features',\n 'faq', 'comparison', 'trust', 'navigation', 'generic',\n] as const;\n\nexport type TopicRule = { topic: string; parent: SemanticType; role: SectionRole };\n\n/** Environment-agnostic section features — buildable from a browser Element or\n * a server-parsed node (node-html-parser). */\nexport type SectionFeatures = {\n tag: string; // lowercase tag name\n idClass: string; // `${id} ${className}`\n headingText: string;\n bodyText: string; // normalized text content, first 2000 chars\n actionCount: number;\n textLength: number;\n /** ARIA landmark role, when the element declares one. Optional so every\n * existing caller keeps compiling; a page that uses landmarks gives a\n * high-precision signal for free, which the old classifier ignored — it\n * tested membership of SEMANTIC_TYPES, so only role=\"navigation\" ever hit\n * and role=\"banner\"/\"contentinfo\" were discarded. */\n ariaRole?: string;\n /** schema.org `@type` values found in `<script type=\"application/ld+json\">`\n * INSIDE this section. Highest-precision signal available and free to\n * collect — the crawler already has the HTML. Type-only here; the\n * `@type` → topic table is server-side in ./topics.ts, since the browser\n * never reads the topic layer and the snippet has ~200 bytes of margin. */\n structuredTypes?: string[];\n};\n\n// ARIA landmark → topic. Structural facts, not guesses.\nconst ARIA_TOPIC: Record<string, string> = {\n banner: 'hero',\n navigation: 'navigation',\n contentinfo: 'footer',\n};\n\n/**\n * Structural identification, shared by the browser and server classifiers.\n * Returns a topic name, or null when the section is not structural furniture.\n * Everything matched here is definitive (tag or authored marker), so callers\n * treat it as `strong`.\n */\nexport function structuralTopicOf(f: SectionFeatures): string | null {\n const aria = f.ariaRole ? ARIA_TOPIC[f.ariaRole.toLowerCase()] : undefined;\n if (aria) return aria;\n if (f.tag === 'nav') return 'navigation';\n if (f.tag === 'footer') return 'footer';\n // A page-level <header> IS the banner landmark (HTML-AAM maps it to\n // role=\"banner\", which this function already treats as hero), so it is a\n // structural fact rather than a keyword guess. Without this, a header whose\n // headline happens to contain a content word loses to the keyword table:\n // \"We build brands that move\" scored social_proof and \"Winter collection\"\n // scored features, purely on words inside the hero copy.\n //\n // …EXCEPT when the header IS the site's navigation. The hold-out corpus\n // (2026-09-05, six real unseen sites) showed most real pages wrap their nav\n // in <header> — mega-menus with 10–114 links and almost no prose — and\n // hero-typing those cost the classifier a 0.11 hero precision. A hero header\n // carries a headline and one or two calls to action; a nav header is\n // link-dominated, so the action count is the discriminator. Measured on the\n // hold-out: nav headers had 10+ actions (one at 4), authored hero headers\n // have 0–2.\n if (f.tag === 'header') return f.actionCount >= 5 ? 'navigation' : 'hero';\n const hay = `${f.idClass} ${f.headingText}`.toLowerCase();\n if (/\\b(navbar|nav-bar|navigation|site-nav|main-nav|topbar|footer)\\b/.test(hay)) {\n return /footer/.test(hay) ? 'footer' : 'navigation';\n }\n // Explicit authoring marker beats any inferred keyword, and is matched on\n // idClass ONLY: a `<header class=\"hero\">` headlined \"Expert Car Repair\" is a\n // hero, not a services section — but matching \"hero\" in heading text would\n // also catch \"Hero of the story\".\n if (/\\b(hero|masthead|jumbotron)\\b/i.test(f.idClass)) return 'hero';\n return null;\n}\n\n/**\n * Last-resort classification once no keyword or content evidence matched.\n * Hero is checked BEFORE the converter fallback — fix 2 above.\n */\nexport function fallbackTopicOf(f: SectionFeatures): string {\n // `tag === 'header'` is handled in structuralTopicOf, which runs first.\n if (f.actionCount >= 1 && f.textLength > 0 && f.textLength < 200) return 'cta';\n return 'generic';\n}\n\n// Parent-level keyword table for the BROWSER path. Deliberately close to the\n// original size — the rich topic vocabulary is in ./topics.ts. `plans?` now\n// requires adjacent pricing context, and bare `customers?` is gone (it fired on\n// navigation furniture like a \"Customer Service\" footer block).\nconst KEYWORDS: Array<[SemanticType, RegExp]> = [\n ['pricing', /\\b(pricing|price list|per month|\\/mo|subscriptions?)\\b|\\bplans?\\b(?=[^.]{0,40}(from|start|month|year|[$€£]))/i],\n ['faq', /\\bfaq\\b|frequently asked|common questions?/i],\n ['comparison', /\\b(compare|comparison|versus)\\b|\\bvs\\./i],\n ['social_proof', /\\b(reviews?|ratings?|testimonial|brands?|galler(y|ies)|logos)\\b|trusted by|loved by|case stud|what our customers say/i],\n ['trust', /\\b(insurance|warrant(y|ies)|guarantees?|certifi|accredit|security|privacy|compliance|gdpr|encrypt)\\b|why choose|about us|our team/i],\n ['cta', /\\b(book|booking|reserve|appointments?|newsletter|subscribe)\\b|contact us|get in touch|opening hours/i],\n ['features', /\\b(features?|benefits?|capabilit|services?|repairs?|menus?|products?)\\b|how it works|our process|what we (do|offer)|what you get/i],\n];\n\n// Content-evidence patterns — run against bodyText when the heading gave us\n// nothing. Deliberately conservative: pricing needs per-period/plan context next\n// to money so an article mentioning \"$5 million\" stays generic.\nexport const CONTENT_PATTERNS: Array<[SemanticType, RegExp]> = [\n ['pricing', /(?:[$€£]\\s?\\d[\\d,.]*\\s*(?:\\/|per\\s)\\s*(?:mo|month|yr|year|seat|user))|(?:\\b(?:starter|basic|pro|growth|premium|enterprise)\\b[^.]{0,60}[$€£]\\s?\\d)/i],\n ['social_proof', /(?:★{2,})|(?:\\b\\d(?:\\.\\d)?\\s*(?:out of|\\/)\\s*5\\b)|(?:\\brated\\b)|(?:[\"“][^\"”]{20,160}[\"”]\\s*[—–-]\\s*[A-Z][a-z]+)/],\n ['trust', /\\b(?:money[- ]back guarantee|free returns?|returns? within|refund(?:s)? within|encrypted|soc ?2|iso ?27001|gdpr[- ]compliant|cancel anytime)\\b/i],\n ['comparison', /\\b(?:vs|versus)\\b\\.?[^.!?]{0,80}\\b(?:compare|comparison|plans?|features?|alternative)\\b|\\bhow (?:we|it) compares?\\b/i],\n];\n\n/** Parent for the handful of topics the shared structural/fallback helpers\n * emit. The server maps the full vocabulary via CLASSIFIER_TOPICS instead. */\nconst SHARED_TOPIC_PARENT: Record<string, SemanticType> = {\n navigation: 'navigation',\n footer: 'navigation',\n hero: 'hero',\n cta: 'cta',\n generic: 'generic',\n};\n\nfunction headingText(el: Element): string {\n const h = el.querySelector('h1, h2, h3');\n return (h?.textContent ?? '').slice(0, 160);\n}\n\n/**\n * Pure classification over extracted features. `strong` = keyword, content, or\n * structural evidence (trustable enough to auto-apply); `weak` = a fallback\n * guess (hero/cta/generic — capture-worthy but not persona evidence).\n */\nexport function classifyFeatures(f: SectionFeatures): { type: SemanticType; strength: 'strong' | 'weak' } {\n const structural = structuralTopicOf(f);\n if (structural) return { type: SHARED_TOPIC_PARENT[structural] ?? 'generic', strength: 'strong' };\n\n const hay = `${f.idClass} ${f.headingText}`.toLowerCase();\n for (const [type, re] of KEYWORDS) if (re.test(hay)) return { type, strength: 'strong' };\n for (const [type, re] of CONTENT_PATTERNS) if (re.test(f.bodyText)) return { type, strength: 'strong' };\n\n const fb = fallbackTopicOf(f);\n return { type: SHARED_TOPIC_PARENT[fb] ?? 'generic', strength: 'weak' };\n}\n\n/** Feature extraction from a live DOM element (browser paths). */\nexport function featuresFromElement(el: Element): SectionFeatures {\n const text = (el.textContent ?? '').replace(/\\s+/g, ' ').trim();\n const role = el.getAttribute('role');\n return {\n tag: el.tagName.toLowerCase(),\n idClass: `${el.id} ${String(el.className ?? '')}`,\n headingText: headingText(el),\n bodyText: text.slice(0, 2000),\n actionCount: el.querySelectorAll('a, button, [role=\"button\"]').length,\n textLength: text.length,\n ...(role ? { ariaRole: role } : {}),\n };\n}\n\n/** Classify a page section into a semantic type (never null — falls back to\n * 'generic' so the caller can still capture attention on it). */\nexport function classifySection(el: Element): SemanticType {\n return classifyFeatures(featuresFromElement(el)).type;\n}\n","import {\n classifyFeatures,\n featuresFromElement,\n CONTENT_PATTERNS,\n SEMANTIC_TYPES,\n type SemanticType,\n} from './classify';\nimport { fnv1a } from '@sentientui/policy';\nimport { isDoNotTrackEnabled } from '../index.js';\nimport { attachMicroSignalDetectors } from '../micro-signals.js';\nimport { locatorFromElement } from '../locator-from-dom.js';\nimport { startInteractionCollector, type InteractionStats } from './interaction-stats.js';\n\n// Shared engagement capture (spec 2026-07-22-persona-signal-capture). Detects\n// semantic sections, registers them via /v1/section-map, and records per-section\n// dwell/scroll via IntersectionObserver — emitting the same 'dwell' events the\n// persona pipeline consumes. Used by the React provider (default on) and the\n// no-code snippet. Defense-in-depth: checks DNT internally even though callers\n// gate on consent/DNT too; a missing IntersectionObserver → no-op.\n\ntype CaptureClient = {\n track(event: { projectId: string; componentId: string; eventType: string; payload: Record<string, unknown> }): void;\n /** Drain the event queue now. Optional so an embedder can pass a bare\n * tracker, but every first-party client has it — see the leave-path flush\n * in `emit`, which is what makes a short visit deliverable at all. */\n flush?(): void;\n};\n\nexport type EngagementCaptureOptions = {\n apiKey: string;\n /** API base, no trailing slash. Defaults to the hosted API. */\n apiBase?: string;\n doc?: Document;\n /**\n * Also attach per-section micro-signal detectors (rage click, text copy,\n * scroll hesitation, tab loss), attributed to the section's per-element `nc-*`\n * component. For the no-code snippet, whose pages have no `<Adaptive>`\n * components carrying their own detectors. Default false — the React SDK\n * keeps its per-component detectors and must not double-attach.\n */\n microSignals?: boolean;\n /**\n * Section types declared in code, keyed by `data-sentient-id`. The highest\n * precedence — the same map the graph scanner receives, so capture and the\n * graph never disagree on what a declared section is.\n */\n sectionTypes?: Readonly<Partial<Record<string, string>>>;\n /**\n * Server-served section-map lookup (persona-coverage auto-classification):\n * consulted after declared types and legacy `data-sentient-type` markup,\n * before the local heuristic. Return null when the element has no served label.\n */\n typeOf?: (el: Element) => SemanticType | null;\n};\n\nconst SECTION_SELECTOR = 'section, header, footer, nav, main > div, [data-sentient-section]';\n\n/** Bank cadence for visible dwell. Dwell used to leave the page only on\n * visibilitychange/pagehide, and in production that path delivered for ~5-8%\n * of sessions (Bodyshop audit 2026-08-30): a visitor who reads and closes the\n * tab races the unload pipeline, and mobile browsers can kill a page with no\n * lifecycle event at all. The heartbeat caps the loss at one interval. */\nconst HEARTBEAT_MS = 20_000;\n\n/** Sentinel component for the session-level interaction snapshot — same\n * pattern as pageview's `__page__`: not a component, never attributed to one.\n * Every report producer filters `raw_events` by event_type, so the sentinel\n * cannot leak into a component table. */\nexport const INTERACTION_STATS_COMPONENT = '__session__';\nexport type { InteractionStats };\n\n/**\n * Pick the elements to observe. Two rules, in order:\n * 1. A candidate that CONTAINS two or more other candidates is a layout\n * wrapper, not a section — drop it. Pages built from bare divs match\n * `main > div` with their page-wide content wrapper; keeping that outer\n * match swallowed every real <section> inside it, collapsing the whole page\n * into one nc-generic component whose intersectionRatio could never exceed\n * viewport-height / page-height (a constant ~0.05 scroll_depth on the\n * audited site). A candidate with exactly one nested candidate (header >\n * nav) is NOT a wrapper — rule 2 keeps the outer one, as before.\n * 2. Of what remains, skip a section nested inside another kept section\n * (avoid double count).\n */\nfunction selectSections(doc: Document): Element[] {\n const candidates = Array.from(doc.querySelectorAll(SECTION_SELECTOR));\n const kept = candidates.filter(\n (el) => candidates.filter((c) => c !== el && el.contains(c)).length < 2,\n );\n return kept.filter((el) => !kept.some((k) => k !== el && k.contains(el)));\n}\n\n/** Client-sensor observation riding each section-map entry (spec 2026-09-04\n * §2): structure, headings, and which CONTENT_PATTERNS matched — never body\n * text, so nothing beyond headings leaves the page. Lets the server's richer\n * topic classifier label pages the crawler cannot fetch (CSR, auth-walled). */\ntype SectionObservation = {\n tag: string;\n idClass: string;\n headingText: string;\n textLength: number;\n actionCount: number;\n ariaRole?: string;\n patternFlags?: SemanticType[];\n};\n\nfunction registerSections(\n apiKey: string,\n apiBase: string,\n pageUrl: string,\n sections: Array<{\n componentId: string;\n semanticType: SemanticType;\n source: 'markup' | 'auto';\n locator?: unknown;\n observation?: SectionObservation;\n }>,\n): void {\n try {\n void fetch(`${apiBase}/v1/section-map`, {\n method: 'POST',\n keepalive: true,\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify({ pageUrl, sections }),\n }).catch(() => undefined);\n } catch {\n /* fail-safe */\n }\n}\n\nconst NOOP = (): void => undefined;\n\nexport function startEngagementCapture(\n client: CaptureClient,\n opts: EngagementCaptureOptions,\n): () => void {\n const doc = opts.doc ?? (typeof document !== 'undefined' ? document : undefined);\n if (!doc || typeof IntersectionObserver === 'undefined') return NOOP;\n if (isDoNotTrackEnabled()) return NOOP;\n // Keyless zero-network contract: capture exists to feed the hosted persona\n // pipeline — with no api key there is nothing to feed, and the section-map\n // registration fetch must never fire. Same validity rule as init() and the\n // graph entry: this used to check truthiness only, so an invalid non-`pk_`\n // (typo'd) key still fired /v1/section-map registration and dwell events\n // into a client that discards everything.\n if (!opts.apiKey || !opts.apiKey.startsWith('pk_')) return NOOP;\n // Normalize so both a ROOT base (`https://api.sentient-ui.com`) and a\n // `/v1`-suffixed base resolve to exactly one `/v1/section-map` — some callers\n // pass the versioned base, which would otherwise produce `/v1/v1/section-map`\n // (a silent 404). Strip trailing slashes, then a single trailing `/v1`.\n const apiBase = (opts.apiBase ?? 'https://api.sentient-ui.com')\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '');\n\n const els = selectSections(doc);\n if (els.length === 0) return NOOP;\n\n // One component per ELEMENT (nc-* retirement, 2026-09-05): the id carries a\n // short locator hash — `nc-<type>-<hash>` — so two same-typed bands no longer\n // collapse into one row with summed dwell, which is what made \"which features\n // band holds attention?\" unanswerable. The hash is over the locator's\n // identity fields (the same subset section_key hashes server-side), so the id\n // is stable across visits. An element with no resolvable locator falls back\n // to the collapsed `nc-<type>` — no identity means no better name exists.\n // The type-level matrix is unaffected (it aggregates via graph_nodes\n // semantic_type); pre-change dwell history stays keyed to collapsed ids and\n // ages out of the reporting windows.\n // Per-element precedence: declared sectionTypes (by data-sentient-id) →\n // legacy data-sentient-type markup → served section map (opts.typeOf) →\n // local heuristic. Declared and markup types both report source 'markup':\n // they are author-asserted, not inferred.\n const componentOf = new Map<Element, string>();\n const entries: Array<{\n componentId: string;\n semanticType: SemanticType;\n source: 'markup' | 'auto';\n locator?: unknown;\n observation?: SectionObservation;\n }> = [];\n for (const el of els) {\n const markup = [\n opts.sectionTypes?.[el.getAttribute('data-sentient-id') ?? ''],\n el.getAttribute('data-sentient-type'),\n ].find((t): t is SemanticType => (SEMANTIC_TYPES as readonly unknown[]).includes(t)) ?? null;\n const f = featuresFromElement(el);\n const type = markup ?? opts.typeOf?.(el) ?? classifyFeatures(f).type;\n const locator = locatorFromElement(el, doc) as\n | { id?: string; dataAttr?: unknown; selector?: string }\n | null;\n const componentId = locator\n ? `nc-${type}-${fnv1a(\n JSON.stringify({ id: locator.id ?? null, dataAttr: locator.dataAttr ?? null, selector: locator.selector ?? null }),\n ).toString(36)}`\n : `nc-${type}`;\n componentOf.set(el, componentId);\n // Client-sensor observation: which shipped CONTENT_PATTERNS matched the\n // body text (booleans — the text itself never leaves the page), plus the\n // structural features the server classifier keys on.\n const patternFlags = CONTENT_PATTERNS.filter(([, re]) => re.test(f.bodyText)).map(([t]) => t);\n entries.push({\n componentId,\n semanticType: type,\n // `source` is per ELEMENT: with one row per section the server records\n // each section's real provenance, not the most-confident of its siblings'.\n source: markup ? 'markup' : 'auto',\n ...(locator ? { locator } : {}),\n observation: {\n tag: f.tag,\n idClass: f.idClass.slice(0, 200),\n headingText: f.headingText,\n textLength: f.textLength,\n actionCount: f.actionCount,\n ...(f.ariaRole ? { ariaRole: f.ariaRole } : {}),\n ...(patternFlags.length > 0 ? { patternFlags } : {}),\n },\n });\n }\n\n const pageUrl = (doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined))?.location?.pathname ?? '/';\n registerSections(opts.apiKey, apiBase, pageUrl, entries);\n\n // Browser-agent axis (spec 2026-09-22 §4.1): passive interaction aggregates,\n // emitted at the same bank points as dwell. Same DNT/key gate — we are past\n // both checks here — and the collector itself never touches the network.\n const interaction = startInteractionCollector(doc);\n // EVERY visit reports, however short. There used to be an 8 s floor here, on\n // the reasoning that a bounce has too few events for an aggregate to mean\n // anything. True of the aggregate, wrong as a place to act on it: a 2 s read\n // on a phone is a real visit, and suppressing it left the scorer unable to\n // tell that visitor from a JS-less crawler — the population that already\n // makes up 83% of the \"human\" sessions on the busiest prod project. Whether\n // a snapshot is thin enough to ignore is a SCORING question, and it now\n // lives with the scorer (a snapshot that fires no positive reason keeps\n // `client_js_present`), where the threshold can move without an SDK release.\n const emitInteraction = (): void => {\n let snap: InteractionStats;\n try { snap = interaction.snapshot(); } catch { return; }\n try {\n client.track({\n projectId: opts.apiKey,\n componentId: INTERACTION_STATS_COMPONENT,\n eventType: 'interaction_stats',\n payload: snap as unknown as Record<string, unknown>,\n });\n } catch {\n /* fail-safe */\n }\n };\n\n // Accumulate visible dwell (ms) + max scroll ratio per component. `intersecting`\n // tracks in-viewport state independently of `enterAt` (the running clock) so a\n // tab-hide can pause the clock and a tab-show can resume it for still-visible\n // sections — IntersectionObserver does not re-fire on visibilitychange.\n const state = new Map<string, { ms: number; scroll: number; enterAt: number | null; intersecting: boolean }>();\n const get = (id: string) => {\n let s = state.get(id);\n if (!s) { s = { ms: 0, scroll: 0, enterAt: null, intersecting: false }; state.set(id, s); }\n return s;\n };\n\n const observer = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n const id = componentOf.get(entry.target);\n if (!id) continue;\n const s = get(id);\n if (entry.isIntersecting) {\n s.intersecting = true;\n s.enterAt = Date.now();\n if (entry.intersectionRatio > s.scroll) s.scroll = entry.intersectionRatio;\n } else {\n s.intersecting = false;\n if (s.enterAt != null) { s.ms += Date.now() - s.enterAt; s.enterAt = null; }\n }\n }\n }, { threshold: [0, 0.25, 0.5, 0.75, 1] });\n for (const el of componentOf.keys()) observer.observe(el);\n\n // Bank accumulated dwell and RESET the accumulators (so a later emit can't\n // double-count) WITHOUT disconnecting — a visitor who hides/re-shows the tab\n // or tab-switches keeps being measured. Pauses the running clock; the tab-show\n // handler restarts it for still-visible sections so hidden time isn't counted.\n // `leaving` marks the paths where the page may not exist a tick from now.\n // The queue installed its OWN pagehide/visibilitychange flush when the\n // client was constructed — before this module was imported — so on those\n // events it drains first and everything banked below is enqueued after the\n // drain has already happened. With a 5 s queue timer and a 20 s heartbeat,\n // a visit shorter than either delivered nothing: measured at ~5-8% on the\n // leave path (Bodyshop audit 2026-08-30). Flushing here, after the bank,\n // is what closes that. Not on the heartbeat: the page is alive, the queue's\n // own timer covers it, and flushing every 20 s would double the requests.\n const emit = (leaving = false): void => {\n const now = Date.now();\n for (const [id, s] of state) {\n if (s.enterAt != null) { s.ms += now - s.enterAt; s.enterAt = null; }\n if (s.ms <= 0) continue;\n try {\n client.track({\n projectId: opts.apiKey, // SDK convention: server derives the real project from the key\n componentId: id,\n eventType: 'dwell',\n payload: { dwell_time: Math.round(s.ms), scroll_depth: Number(s.scroll.toFixed(2)) },\n });\n } catch {\n /* fail-safe */\n }\n s.ms = 0;\n }\n emitInteraction();\n if (leaving) {\n try { client.flush?.(); } catch { /* fail-safe */ }\n }\n };\n\n const onVisibility = (): void => {\n if (doc.hidden) {\n emit(true); // bank + pause + drain: on mobile this IS the leave path\n } else {\n const now = Date.now(); // resume the clock for sections still on screen\n for (const s of state.values()) if (s.intersecting) s.enterAt = now;\n }\n };\n // A page can be FROZEN into the bfcache rather than torn down. Timers keep\n // firing on restore, and `intersecting` still holds whatever it held at\n // pagehide — so without this the heartbeat kept banking dwell for sections the\n // visitor had scrolled far past, forever, while the observer that could have\n // corrected them had been disconnected. Freeze the clocks instead, and only\n // tear down for real when the page is genuinely going away.\n let frozen = false;\n const onPageHide = (event?: { persisted?: boolean }): void => {\n emit(true); // bank whatever is measured either way, then drain\n if (event?.persisted) {\n frozen = true; // bfcache: keep the observer, stop counting\n return;\n }\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n const onPageShow = (event?: { persisted?: boolean }): void => {\n if (!event?.persisted || !frozen) return;\n frozen = false;\n // The observer stayed connected, so it will correct `intersecting` for\n // anything that moved. Restart clocks only for what is on screen NOW.\n const now = Date.now();\n for (const s of state.values()) s.enterAt = s.intersecting && !doc.hidden ? now : null;\n };\n doc.addEventListener('visibilitychange', onVisibility);\n const win = doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined);\n win?.addEventListener('pagehide', onPageHide);\n win?.addEventListener('pageshow', onPageShow);\n\n // See HEARTBEAT_MS: bank visible dwell periodically so a hard close (or a\n // mobile page kill) loses at most one interval instead of the whole visit.\n // Hidden tabs skip the emit — their clock is already paused, and an empty\n // state map makes emit a no-op anyway.\n const heartbeat = setInterval(() => {\n if (doc.hidden || frozen) return;\n emit();\n // emit() pauses every running clock and only the tab-show handler restarts\n // them — here the page never went hidden, so restart the clock ourselves\n // or accumulation silently stops after the first heartbeat.\n const now = Date.now();\n for (const s of state.values()) if (s.intersecting) s.enterAt = now;\n }, HEARTBEAT_MS);\n\n // Per-section micro-signal detectors (opt-in; see EngagementCaptureOptions).\n // Attributed to the section's per-element nc-* id with no variant — they feed the\n // persona attention fallback and auto-discovery, never rewards.\n const detectorCleanups: Array<() => void> = [];\n if (opts.microSignals) {\n // tab_loss is a single document-level `visibilitychange` signal, so enabling\n // it on every section detector would emit one tab_loss per section\n // on a single tab-hide — attributing one page-level exit to every section\n // (audit M5). Enable it on only the first section so the exit is recorded\n // once, mirroring the per-option path in slot-signals.ts ({ tabLoss: index === 0 }).\n [...componentOf.entries()].forEach(([el, componentId], i) => {\n detectorCleanups.push(\n attachMicroSignalDetectors((signalType, extra = {}) => {\n try {\n client.track({\n projectId: opts.apiKey,\n componentId,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n } catch {\n /* fail-safe */\n }\n }, el, undefined, { tabLoss: i === 0 }),\n );\n });\n }\n\n // Cleanup: bank any remaining dwell, then detach everything (provider unmount\n // / consent re-init must not leak observers or listeners).\n return () => {\n emit(true);\n clearInterval(heartbeat);\n interaction.stop();\n doc.removeEventListener('visibilitychange', onVisibility);\n win?.removeEventListener('pagehide', onPageHide);\n win?.removeEventListener('pageshow', onPageShow);\n for (const c of detectorCleanups) c();\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n}\n","import { DECIDE_TIMEOUT_MS, REQUEST_TIMEOUT_MS, SESSION_WAIT_MS, settlesWithin, timeoutSignal } from './timeout.js';\nimport { setCspNonce } from './csp-nonce.js';\nimport { forgetVisitor } from './forget.js';\nimport { forgetGeneration, markForgotten, storageSuffix } from './storage-key.js';\nimport { initSession, type SessionConfig, type SessionManager } from './session';\nimport {\n createEventQueue,\n retryStorageKey,\n type EventQueue,\n type EventType,\n type QueueConfig,\n type SentientEvent,\n} from './queue';\nimport {\n createGoalQueue,\n goalRetryStorageKey,\n type GoalQueue,\n} from './goal-queue';\nimport {\n createAssignmentCache,\n type Assignment,\n} from './cache';\nimport type {\n GraphConfig,\n GraphSnapshot,\n} from './graph';\nimport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n extractTrackedParams,\n referrerDomainFromReferer,\n uaTokenMatch,\n} from './session-meta.js';\nimport {\n toWireSlot,\n baselineResultFor,\n armOfResult,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\nimport { readSnapshot, writeSnapshot, SNAPSHOT_STORAGE_KEY_PREFIX, type SlotConfigEntry, type CompoundLocator } from './snapshot.js';\nimport { exposedStage, setStageAttribute, type StageAttributes } from './stage-attribute.js';\nimport type { RegionSkeleton, RenderCaps } from './region-skeleton.js';\n\n/** A captured skeleton, or why none could be captured. */\nexport type SkeletonReport = RegionSkeleton | { status: 'too_large' | 'empty' | 'unaddressable' };\n/** One authored arm of a hybrid <Adaptive>, as it rendered. */\nexport type AuthoredArmReport = { key: string; text?: string; skeleton?: RegionSkeleton };\nimport { confidenceBand } from '@sentientui/policy';\nimport { createLocalModeClient } from './local-mode.js';\nimport { randomUuidV4 } from './uuid.js';\nimport { backoffDelayMs, classifyResponse } from './durable.js';\n\n// Never `process?.env` — optional chaining still throws ReferenceError on an\n// undeclared global, and browsers without a bundler shim (raw esbuild, vanilla\n// script tags) have no `process`. Same declaration @sentientui/react carries.\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\n/** True unless NODE_ENV is 'production' — gates integrator-facing dev warnings. */\nfunction isDevBuild(): boolean {\n return typeof process === 'undefined' || process.env?.NODE_ENV !== 'production';\n}\n\nexport { PROD_KEYLESS_ERROR, LOCAL_MODE_BANNER } from './local-mode.js';\n\n// The one source of truth for the session cookie's name — every out-of-package\n// reader (react devtools, integrator SSR code) must derive the name from this\n// instead of hard-coding `_snt_uid`, which is only the pre-namespacing fallback.\nexport { sessionCookieName, LEGACY_SESSION_COOKIE_NAME } from './storage-key.js';\n\nexport {\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n deriveSessionSegment,\n extractTrackedParams,\n CLICK_ID_KEYS,\n referrerDomainFromReferer,\n uaTokenMatch,\n matchedAgentToken,\n agentUaList,\n agentIntent,\n classifiedAgents,\n AGENT_INTENTS,\n} from './session-meta.js';\nexport type { AgentIntent } from './session-meta.js';\n\nconst DEFAULT_INGEST_URL = 'https://api.sentient-ui.com/v1/events';\n\n// Keyed by apiKey so multiple init() calls (HMR, multi-project) don't collide.\nconst _clients = new Map<string, {\n config: SentientConfig;\n upgrade: ((c: SentientClient) => void) | null;\n // Why grantConsent() cannot upgrade this entry (keyless/local mode, invalid\n // key). grantConsent() warns with this instead of silently no-oping — a CMP\n // callback wired to it otherwise LOOKED like it worked while nothing ever\n // started tracking. Absent for entries where the silent no-op IS the\n // documented contract (DNT-blocked, already upgraded).\n upgradeBlockedReason?: string;\n // Set by an alternate entry point (the /graph entry) whose gated init\n // deferred extra resources: grantConsent() must re-run THAT entry's init —\n // upgrading through the lean init() produced a post-consent client that\n // never mounted the DOM scanner, silently losing graph capture.\n reinit?: (c: SentientConfig) => SentientClient;\n // Teardown for the live client bound to this key (stops its queue interval +\n // unload listeners). Present only for the full tracking client; the no-op /\n // pre-consent / local entries have nothing to tear down. Called before a\n // re-init for the same key replaces it, so timers/listeners can't leak.\n dispose?: () => void;\n}>();\nlet _lastApiKey: string | null = null;\n\n/**\n * @internal Wires an alternate entry point's init as grantConsent()'s upgrade\n * path for `apiKey`. The /graph entry calls this when its init is gated on\n * consent: without it, grantConsent() upgraded through the LEAN init, so a\n * graph-configured page granted consent but never mounted the scanner (the\n * graph resources exist only in the /graph entry). No-op unless the entry is\n * actually upgradeable — DNT-blocked and local entries register no hook.\n */\nexport function _registerConsentUpgradeInit(\n apiKey: string,\n reinit: (config: SentientConfig) => SentientClient,\n): void {\n const entry = _clients.get(apiKey);\n if (entry && entry.upgrade) entry.reinit = reinit;\n}\n\nexport type SentientConfig = {\n apiKey: string;\n /**\n * @deprecated Unused — the project's type is set in the dashboard. Safe to omit.\n * Still accepted so existing installs keep type-checking; nothing reads it.\n */\n context?: 'landing' | 'ecommerce' | 'saas' | 'marketplace';\n /** @internal — not exposed to users; defaults to the hosted SentientUI API. */\n ingestUrl?: string;\n debug?: boolean;\n /**\n * Pre-seeded assignments from `preloadAssignments()` (SSR).\n * Seeds the local cache so `assign()` returns without a network call for\n * listed code variants, guaranteeing server and client render the same\n * variant on first paint. Managed-text components (assign with no\n * variantIds) still fetch once when the seed carries no content.\n */\n initialAssignments?: Record<string, string>;\n /**\n * Segment used for SSR preload (`device:source`). When set with `initialAssignments`,\n * seeds the assignment cache under this key so hydration matches the server bandit row.\n */\n sessionSegment?: string;\n /**\n * Consent gate. When `false`, returns a no-op client and performs no tracking.\n * Defaults to `true`. Re-call `init()` (via `AdaptiveProvider` consent prop) when\n * the user grants or revokes consent mid-session.\n */\n consent?: boolean;\n /**\n * Behavior before consent is granted. `'statistical_winner'` fetches the\n * best-performing variant via `GET /v1/winner` — no session or tracking data\n * is stored. `'control'` (default) shows `variantIds[0]` with no API call.\n * Applies when tracking is gated off — either `consent: false` or an active\n * Do Not Track signal.\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Whether to honor the browser's Do Not Track (DNT) signal. Defaults to `true`.\n * When `true` and the visitor has DNT enabled, the SDK sets no cookies and\n * sends no tracking data — behaving exactly as `consent: false` (still serving\n * the read-only `preConsentBehavior` winner if configured), and `grantConsent()`\n * will not upgrade it. Set `false` to make your own consent gate authoritative.\n */\n respectDoNotTrack?: boolean;\n userId?: string;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. 'admin', 'evaluator'). Must be a key in the project's persona\n * vocabulary (dashboard → Settings → Personas); unrecognized values are\n * ignored server-side and surfaced in the dashboard so you can add them.\n * Declared personas are served at full confidence, overriding the inferred\n * one. Keep it a low-cardinality role label — never a user id or email.\n */\n persona?: string;\n /**\n * Session ID generated server-side (from `loadAdaptiveAssignments` / `loadAdaptiveDecision`).\n * When provided, the client adopts this ID on first visit instead of generating a new one,\n * ensuring events and goals are attributed to the same session the server used for assignment.\n */\n ssrSessionId?: string;\n /**\n * ISO 3166-1 alpha-2 country code for the visitor. When provided (e.g. from\n * the `CF-IPCountry` header in a Next.js server component), it is included in\n * the session upsert so country-based segmentation works without client-side\n * geo lookup.\n */\n country?: string;\n /**\n * Pre-seeded slot results from `preloadDecisions()` / `loadAdaptiveDecision()`\n * (SSR). Seeds the local slot state so `getSlotResult()` agrees with the\n * server-rendered markup on first paint.\n */\n initialSlots?: Record<string, SlotResult>;\n /**\n * Registry slot config decided outside the browser (SSR). Seeds\n * `getSlotConfig()` so server-rendered block/content arms survive hydration.\n */\n initialSlotConfig?: Record<string, SlotConfigEntry>;\n /** Site palette decided outside the browser (SSR). Seeds `getSitePalette()`. */\n initialPalette?: import('./blocks.js').SitePalette;\n /** Site styles the SSR decision's Redesign arms borrow. Seeds `getStyleVocabulary()`. */\n initialVocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n /**\n * Persona decided during SSR. Takes priority over the html-attribute\n * adoption and the local snapshot.\n */\n initialPersona?: { persona: string; confidence: number };\n /**\n * Keyless local mode. 'auto' (default) simulates decisions on-device when no\n * valid API key is configured — but only in development builds (the\n * `development` export condition); production bundles physically exclude the\n * engine. `true` forces the local engine regardless of key (escape hatch);\n * `false` restores the silent keyless no-op.\n */\n localMode?: 'auto' | boolean;\n /**\n * Which integration surface is driving this client, and its released build\n * version — `{ name: 'react', version: '0.27.0' }`. Set by the wrapper\n * package (@sentientui/react, @sentientui/snippet), never by application\n * code: core is a dependency of both, so its own version says nothing about\n * what the customer installed.\n *\n * Rides the session upsert (the one call EVERY integration makes, unlike\n * decide, which only the slot paths use) so the dashboard can tell a project\n * its SDK is behind. Additive and best-effort: older API deployments ignore\n * the fields, and omitting it changes nothing.\n */\n sdk?: { name: string; version: string };\n /**\n * CSP nonce for the <style> elements the SDK injects (the adaptation\n * reveal). Without one the page's CSP needs `style-src 'unsafe-inline'`.\n * Defaults to the nonce of a script already on the page.\n */\n nonce?: string;\n /**\n * Opt-in: write the visitor's funnel stage to `<html data-sentient-stage>`\n * after each decide (and remember it for the next visit's pre-paint script),\n * so a theme can make deterministic CSS changes per stage. Only projects\n * with stages turned on send one. `true` exposes `new`, `browsing`, `carted`\n * and `returning` (has bought here — `customer`/`lapsed` collapsed, since any\n * script on the page can read it); `'detailed'` exposes `customer` and\n * `lapsed` as they are. How the visitor arrived is never written.\n */\n stageAttributes?: StageAttributes;\n};\n\nexport type AssignResult = { variantId: string; assignmentTtlMs: number; content?: string };\n\nexport type { SlotDeclInput, SlotResult };\nexport { armOfResult, baselineResultFor, baselineSlots, toWireSlot } from './slots.js';\n\nexport {\n SNAPSHOT_STORAGE_KEY_PREFIX,\n readSnapshot,\n writeSnapshot,\n renderPrePaintScript,\n} from './snapshot.js';\nexport type { DecisionSnapshot, SlotConfigEntry, SlotOps, CompoundLocator } from './snapshot.js';\nexport { pageScopeMatches, PAGE_SCOPE_RE } from './page-scope.js';\nexport { exposedStage, setStageAttribute, STAGE_ATTRIBUTE } from './stage-attribute.js';\nexport type { StageAttributes } from './stage-attribute.js';\nexport * from './blocks.js';\nexport * from './region-skeleton.js';\n// Types only: the vocabulary's runtime constants (roles, id pattern, caps) are\n// server/editor concerns and live on `@sentientui/core/style-sample`, so the\n// lean bundle every visitor downloads doesn't carry them.\nexport type { StyleRole, StyleEntry, SiteImage, StyleVocabulary, ComposeArm } from './style-vocabulary.js';\n// Consent sources: the runtime is `@sentientui/core/consent` (loaded only by\n// installs that configure a consent platform); the types live here.\nexport type { ConsentSource, ConsentPreset, ConsentWatcher } from './consent-sources.js';\n\n/** An editor-defined goal delivered with a registry-mode decision, for the\n * snippet to install delegated listeners from. */\nexport type GoalDefinition = {\n goalId: string;\n event: 'click' | 'form_submit' | 'url_reached' | 'scroll_depth';\n locator?: CompoundLocator;\n urlPattern?: string;\n slotId?: string;\n /** scroll_depth only: fraction of the page (0–1] that counts as read. */\n threshold?: number;\n};\n\n/** One served section-classification row (registry mode): where it is on the\n * page (url match + compound locator) and its semantic type. The snippet\n * resolves the locator to build capture's `typeOf` hook. */\nexport type SectionMapEntry = {\n urlMatch: string;\n locator: CompoundLocator;\n type: string;\n};\n\nexport type DecideOutcome = {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n // Registry mode only: where/what to apply for server-defined slots.\n slotConfig?: Record<string, SlotConfigEntry>;\n // Registry mode only: editor-defined goals to wire up.\n goals?: GoalDefinition[];\n // Registry mode only: served section-classification map the snippet turns\n // into capture's `typeOf` hook.\n sectionMap?: SectionMapEntry[];\n // Registry mode only: derived site palette for Composition Block rendering.\n palette?: import('./blocks.js').SitePalette;\n // Registry mode only: the site styles served Redesign arms borrow.\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n /** The visit's funnel stage — only for projects with stages on, never for\n * the control group. Raw: see `stageAttributes` for what reaches the page. */\n stage?: string;\n /** The visit's serving context (an arrival class or the stage). Never\n * written to the page or the snapshot. */\n context?: string;\n};\n\nexport type DecideInput = {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n // 'registry' → serve the project's published slot_definitions in addition to\n // any declared slots (registry wins on id collision). Default 'request'.\n slotsFrom?: 'request' | 'registry';\n /** Registry mode only: decide just these published slot ids (1–50) instead\n * of every published slot — see `requestSlots`. */\n registrySlotIds?: string[];\n /** Registry mode only: `false` omits the snippet bootstrap data (editor goals,\n * section map) the React SDK never reads — two queries per page saved. */\n bootstrap?: false;\n /** Registry mode only: what the page can render per mounted slot. The\n * server narrows each slot's arm space to it before drawing (CONTRACTS §2\n * — an arm the page would refuse still books a trial). */\n render?: Record<string, RenderCaps>;\n /**\n * Caller's build version (e.g. the snippet's `__SNIPPET_VERSION__`), sent\n * as `v` on the wire. Additive/best-effort: the server persists it for\n * version-skew reporting (see apps/api decide route) and ignores it\n * entirely on older deployments. Omit if the caller has no version to report.\n */\n v?: string;\n /**\n * Snippet only: which inline pre-paint contract the install carries\n * (`window.__sntPP.v`), or 0 for the two-tag install with no inline script.\n * Sent as `pp` alongside `v`; the server persists it for the dashboard's\n * install-health nudge and no serving behaviour depends on it. Additive —\n * older deployments ignore it entirely.\n */\n pp?: number;\n};\n\nexport type WeightEntry = { variantId: string; pulls: number; avgReward: number | null };\nexport type ComponentWeightEntry = { componentId: string; updatedAt: number; variants: WeightEntry[] };\n\n/** Options accepted by goal() (and inherited by componentGoal / the React\n * hooks / the snippet) — one shape everywhere (spec §5). */\nexport type GoalOptions = {\n /** Revenue of this conversion, in the project currency. */\n value?: number;\n /** ISO-4217 code, only when it differs from the project currency. */\n currency?: string;\n /** Merchant order/transaction id — dedupes retries, enables refunds later. */\n externalId?: string;\n /** Extra fields merged into the event payload / goal metadata. */\n metadata?: Record<string, unknown>;\n /** Advanced: partial-credit weight in [0,1] (composite steps). */\n weight?: number;\n /** Advanced: funnel step index (0-based). */\n stepIndex?: number;\n};\n\n/** goal()'s second arg is the options object iff it carries a reserved key;\n * anything else keeps the legacy bare-metadata interpretation. Reserved keys\n * inside legacy metadata were inert on the server, so reinterpretation is the\n * upgrade the sender wanted (spec §5). */\nfunction isGoalOptions(v: Record<string, unknown>): boolean {\n return 'value' in v || 'currency' in v || 'externalId' in v || 'metadata' in v || 'weight' in v || 'stepIndex' in v;\n}\n\nexport type ComponentGoalOptions = GoalOptions & {\n /** Reward credited to the served variant (0–1). Defaults to 1. */\n reward?: number;\n};\n\nexport type SentientClient = {\n track(\n event: Omit<SentientEvent, 'id' | 'sessionId' | 'timestamp' | 'timeInSession'>,\n ): void;\n goal(name: string, options?: GoalOptions): void;\n /** @deprecated positional form — prefer goal(name, options). */\n goal(name: string, metadata?: Record<string, unknown>, weight?: number, stepIndex?: number): void;\n /**\n * Records a conversion attributed to the variant currently served for\n * `componentId`, so it feeds the per-variant CVR funnel. Resolves the served\n * variant from the local assignment cache — no need to pass variantId or\n * projectId. No-ops if the component has not been assigned yet (render its\n * `<Adaptive>`/call `assign()` first). Prefer this over bare `goal()` for\n * variant experiments; `goal()` is session-level only (no component attribution).\n */\n componentGoal(componentId: string, goalType: string, opts?: ComponentGoalOptions): void;\n identify(userId: string): void;\n getAssignment(componentId: string, segment: string): Assignment | null;\n /** Server-side variant assignment. Caches the result locally per (component, segment). */\n assign(componentId: string, variantIds?: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): Promise<AssignResult | null>;\n /**\n * Single-roundtrip decision for layout sections, component variants, and\n * adaptive slots. Awaits the session upsert (like `assign`) so the server\n * never decides for a session row that doesn't exist yet. A response\n * without a `slots` field means the server predates slots — every declared\n * slot resolves to its baseline and no retry is made.\n */\n decide(input: DecideInput): Promise<DecideOutcome | null>;\n /** Slot result served this session (decide result, SSR seed, snapshot, or failure baseline). Null when unknown. */\n getSlotResult(slotId: string): SlotResult | null;\n /** Registry slot config served this session (content/ops/blocks for the slot).\n * Null until a registry-mode decide, SSR seed, or snapshot provides it. */\n getSlotConfig(slotId: string): SlotConfigEntry | null;\n /** Report mounted AdaptiveSlot ids the server has no config for, so they\n * auto-register as draft slots. Fire-and-forget, batched, deduped per\n * client — never blocks rendering and never throws. `baselineTexts` maps a\n * slot id to its rendered baseline text (what the region says today), so\n * generation can ground its versions in what they replace — sent only on\n * the first report of an id, capped, and the server keeps it only at\n * first registration. */\n reportSlots(\n slotIds: string[],\n baselineTexts?: Record<string, string>,\n baselineSkeletons?: Record<string, SkeletonReport>,\n /** A hybrid <Adaptive>'s authored arms seen on screen (spec 2026-09-23\n * §7.4): recorded for the dashboard and to ground generation. Sent once\n * per (slot, key) per client. */\n authoredArms?: Record<string, AuthoredArmReport[]>,\n ): void;\n /** Report a skeleton for a PUBLISHED slot the server flagged `needsSkeleton`\n * (registered before skeletons existed). Once per id per client; the server\n * stores it only while the slot has none. Optional for hand-rolled clients. */\n reportSkeleton?(slotId: string, skeleton: SkeletonReport): void;\n /** A served Rewrite arm could not be applied because the region's markup no\n * longer matches the skeleton it was written for. Batched, deduped per\n * (slot, fingerprint), never throws. Enough distinct visitors reporting the\n * same drift suspend that skeleton's arms. Optional for hand-rolled clients. */\n reportDrift?(slotId: string, expectedFp: string, observedFp: string | null, reason: 'fp_mismatch' | 'unaddressable' | 'forms'): void;\n /**\n * Ask the server for the registry config of these MOUNTED slots. Batches a\n * tick's mounts into one decide scoped to exactly those ids, once per id per\n * client; ids the server has nothing published for are passed on to\n * `reportSlots` (with their baseline text) so they register as drafts.\n * Listeners from `onSlotsChanged` fire when the answer lands. Optional so\n * hand-rolled/test clients keep type-checking.\n */\n requestSlots?(\n slotIds: string[],\n baselineTexts?: Record<string, string>,\n extras?: { render?: Record<string, RenderCaps>; skeletons?: Record<string, SkeletonReport> },\n ): void;\n /**\n * Decide these MOUNTED request-declared slots (useAdaptiveTokens,\n * AdaptiveGroup) that nothing preloaded: a tick's mounts batch into one\n * `decide({ slots })`, once per id per client. Listeners from\n * `onSlotsChanged` fire when it lands. Optional for hand-rolled clients.\n */\n decideSlots?(decls: SlotDeclInput[]): void;\n /**\n * Withdraw slots from a `requestSlots`/`decideSlots` batch that has not\n * been sent yet (the hooks call this from their unmount cleanup). A slot\n * that mounted and unmounted inside one tick — a redirecting route, a\n * StrictMode probe — is not on the page, so it must not become a trial.\n * In-flight requests are unaffected. Optional for hand-rolled clients.\n */\n cancelSlots?(slotIds: string[]): void;\n /** Subscribe to slot result/config changes. Returns the unsubscribe. */\n onSlotsChanged?(listener: () => void): () => void;\n /**\n * Whether the result `getSlotResult` returns for this slot was DECIDED for\n * this session — an SSR seed or a decide response — as opposed to a\n * snapshot from an earlier visit or the baseline written when a decide\n * failed. Only a decided arm has a `slot_decisions` row, so only a decided\n * arm may be exposed: recording an impression for a seeded one trains an\n * arm the server never served this session. Optional for hand-rolled\n * clients (absent reads as decided).\n */\n isSlotDecided?(slotId: string): boolean;\n /** Site palette served with registry block decisions. Null when absent. */\n getSitePalette(): import('./blocks.js').SitePalette | null;\n /** Site styles the served Redesign (compose) arms borrow; null when none.\n * Optional so hand-rolled clients keep type-checking. */\n getStyleVocabulary?(): import('./style-vocabulary.js').StyleVocabulary | null;\n /** Current persona estimate. Band is always `confidenceBand(confidence)`. Null when nothing is known yet. */\n getPersona(): { persona: string; confidence: number; band: 'low' | 'medium' | 'high' } | null;\n /** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */\n fetchWeights(): Promise<ComponentWeightEntry[]>;\n getGraph(): GraphSnapshot;\n /**\n * Routine teardown: stops timers/listeners and flushes pending events, but\n * KEEPS the visitor identity, decision snapshot, and retry bucket. Use for\n * component unmount / re-init (framework providers call this on cleanup).\n */\n /**\n * Drain the event queue now, without tearing anything down.\n *\n * The queue flushes on its own timer and on its own pagehide /\n * visibilitychange listeners, both registered when this client is built. The\n * engagement capture is imported later and banks dwell and the interaction\n * snapshot INSIDE those same lifecycle events — i.e. after the queue has\n * already drained — so on the leave path its events sat in the queue while\n * the page went away. Delivery on that path measured ~5-8% (Bodyshop audit\n * 2026-08-30); a visit shorter than the 5 s tick delivered nothing at all.\n * Anything that banks late in a lifecycle handler must call this after.\n */\n flush(): void;\n dispose(): void;\n /**\n * Consent-revocation / forget-me teardown: everything `dispose()` does,\n * plus deletion of the visitor identity (`_snt_uid`), the decision\n * snapshot, and the persisted retry bucket. The next visit starts as a\n * brand-new visitor.\n */\n destroy(): void;\n /** True when this client is the keyless local-mode client (dev only). */\n readonly isLocal?: boolean;\n /** True while this is a consent-gated client not yet upgraded in place:\n * goals and events are held until then, and a decide is held (or dropped\n * if the page changed). A released one still reads true but can't be\n * upgraded — check `released`. Absent on a tracking client. */\n readonly gated?: boolean;\n /** @internal True once a gated client was disposed/destroyed before any\n * upgrade: its decides resolve null without being sent. */\n readonly released?: boolean;\n /** @internal The gated client's held goal() calls, removed from it. */\n takeHeld?(): Array<(c: SentientClient) => void>;\n};\n\n// SSR preload helpers moved to the `@sentientui/core/server` entry in 0.6.0 so\n// ~200 lines of Node-only fetch logic stop shipping in the browser bundle.\n\nexport { REVEAL_MS, reveal, resetRevealStyles } from './reveal.js';\nexport { setCspNonce, cspNonce, applyNonce } from './csp-nonce.js';\nexport { forgetVisitor } from './forget.js';\nexport { forgetGeneration } from './storage-key.js';\nexport type { RevealOptions } from './reveal.js';\nexport { attachMicroSignalDetectors } from './micro-signals.js';\nexport type { MicroSignalEmitter, MicroSignalType } from './micro-signals.js';\n\nexport type {\n SessionConfig,\n SessionManager,\n EventType,\n SentientEvent,\n QueueConfig,\n Assignment,\n GraphSnapshot,\n GraphConfig,\n};\n\n/** Attempts after the first for the session upsert — see upsertSession. */\nconst SESSION_UPSERT_RETRIES = 3;\n\nfunction generateEventId(): string {\n return randomUuidV4();\n}\n\n/**\n * The page an event happened on.\n *\n * `location.pathname` ONLY — never `href` or `search`. Query strings on real\n * sites carry emails, reset tokens, order ids and session ids, and none of that\n * should leave the browser for analytics. The server strips them again\n * (domain/page-path.ts) because a hand-rolled integration can post whatever it\n * likes; this is the first of the two gates, and the one that means the data\n * never travels at all.\n *\n * Undefined outside a browser: during SSR there is no page to name, and an\n * invented one would be wrong for every reader.\n */\nfunction currentPath(): string | undefined {\n if (typeof window === 'undefined') return undefined;\n return window.location?.pathname || undefined;\n}\n\n/**\n * Decides whether a goal() call belongs to a user action already recorded.\n *\n * This used to be a clock: a latch cleared on the next macrotask, so anything\n * inside that window counted as \"the same action\". A clock cannot tell the two\n * cases apart, and it got the expensive one wrong. The window can be JUMPED —\n * a macrotask scheduled to close it runs after any timer already armed, which\n * every real page and every sibling test in a worker has — so a genuinely\n * separate conversion landed in a window that should have shut, and was\n * swallowed rather than queued: gone, with no retry able to rescue it because\n * nothing was ever handed to the queue.\n *\n * So ask the question the clock was approximating. Two nested components\n * reacting to one click are, exactly, two listeners in one event DISPATCH, and\n * the platform already hands us that identity: `window.event` is the same Event\n * object for every listener of one dispatch, a different object for the next\n * click, and undefined outside dispatch entirely. Keying on the event object\n * makes \"one action\" a fact rather than a deadline — no timer to lose a race\n * with, no fake-timer or background-throttle hazard, and no way for a second\n * click to be mistaken for the first however long the page stalls between them.\n *\n * Goals fired outside any dispatch (an effect on mount, a page goal) have no\n * event to key on, and fall back to one SYNCHRONOUS flush — closed on a\n * microtask. That is exact too, and for the same reason the old macrotask\n * window was not: microtasks always drain before the next macrotask, so no\n * pending timer can jump this window. A user cannot perform two actions inside\n * one synchronous block, so anything sharing it is a double-fire, not a repeat.\n *\n * A microtask is deliberately NOT used for the dispatch case: the HTML spec\n * runs a microtask checkpoint between listeners once the JS stack empties, so\n * it would split one click into two and double-count the revenue this collapse\n * exists to protect. That is why the dispatch case keys on the event instead,\n * and why a host without `window.event` keeps the old macrotask window — too\n * loose, but erring toward the old behaviour rather than toward double-counting.\n */\nfunction createActionLatch(): { firedBefore(actionKey: string, valueKey: string | null): boolean } {\n // Per window, per action key: the set of value identities already recorded.\n // An entry with an empty set means a VALUELESS fire was recorded. The split\n // exists because value cannot simply live inside one flat key: an inner\n // component declaring `value: 50` nested in an outer wrapper with the same\n // goal but NO value produced two distinct keys — two rows for one click.\n // Within a window, a valueless fire is absorbed by ANY record of the same\n // action (the valued row already carries the order, and a valueless\n // duplicate would inflate Hits), while a valued fire is collapsed only by an\n // IDENTICAL (value, currency) record — $50 and $70 stay two orders\n // (CONTRACTS §1). A valued fire landing AFTER a valueless one still records:\n // the valueless row has already been handed to the queue (often already on\n // the wire) and cannot be retracted, and losing the money would be the worse\n // error — server-side credit clamps the extra valueless hit at min(1, MAX\n // weight), so the cost is one inflated Hit, not corrupted revenue. Listener\n // order makes the benign ordering the common one: the inner (valued)\n // component's listener runs before the wrapper's in a bubbling dispatch.\n const byEvent = new WeakMap<object, Map<string, Set<string>>>();\n const byFlush = new Map<string, Set<string>>();\n let flushOpen = false;\n\n const alreadyRecorded = (map: Map<string, Set<string>>, actionKey: string, valueKey: string | null): boolean => {\n const values = map.get(actionKey);\n if (valueKey === null) {\n if (values) return true;\n map.set(actionKey, new Set());\n return false;\n }\n if (!values) {\n map.set(actionKey, new Set([valueKey]));\n return false;\n }\n if (values.has(valueKey)) return true;\n values.add(valueKey);\n return false;\n };\n\n // Standardised as Window.event and present in every current browser, but a\n // capability check keeps exotic hosts on the path they have always had.\n const hasWindowEvent = typeof window !== 'undefined' && 'event' in window;\n\n const currentEvent = (): object | undefined => {\n if (!hasWindowEvent) return undefined;\n const ev = (window as unknown as { event?: unknown }).event;\n // Must be a real same-realm Event, not merely an object. Window.event is\n // [Replaceable]: a classic script doing `event = {...}` at top level (an\n // implicit or sloppy global on plenty of host pages) permanently shadows\n // the accessor with a data property. Accepting any object then returned\n // that SAME object forever — its WeakMap entry never died, so every later\n // conversion looked like a re-fire of the first action and ALL repeat\n // conversions were silently dropped for the session. `instanceof Event`\n // cannot be true for such a literal; a cross-realm Event (iframe) fails it\n // too and merely falls back to the flush window, which is safe.\n // (typeof guard: a host with `window` but no Event constructor must fall\n // back, not throw a ReferenceError from inside goal().)\n return typeof Event === 'function' && ev instanceof Event ? ev : undefined;\n };\n\n const closeFlushWindow = (): void => {\n if (hasWindowEvent) {\n // A promise microtask, not queueMicrotask: fake-timer setups can replace\n // queueMicrotask, and this window closing is what keeps repeat\n // conversions from being swallowed.\n void Promise.resolve().then(() => {\n flushOpen = false;\n byFlush.clear();\n });\n return;\n }\n let done = false;\n const clear = (): void => {\n if (done) return;\n done = true;\n flushOpen = false;\n byFlush.clear();\n };\n setTimeout(clear, 0);\n if (typeof MessageChannel === 'function') {\n const ch = new MessageChannel();\n ch.port1.onmessage = () => {\n ch.port1.close();\n ch.port2.close();\n clear();\n };\n ch.port2.postMessage(0);\n }\n };\n\n return {\n firedBefore(actionKey: string, valueKey: string | null): boolean {\n const ev = currentEvent();\n if (ev) {\n let keys = byEvent.get(ev);\n if (!keys) {\n keys = new Map<string, Set<string>>();\n // Keyed weakly: the Map dies with the Event object, so a long session\n // of clicks accumulates nothing.\n byEvent.set(ev, keys);\n }\n return alreadyRecorded(keys, actionKey, valueKey);\n }\n const collapsed = alreadyRecorded(byFlush, actionKey, valueKey);\n if (!collapsed && !flushOpen) {\n flushOpen = true;\n closeFlushWindow();\n }\n return collapsed;\n },\n };\n}\n\n/**\n * Emits one `pageview` per page load and per SPA route change.\n *\n * Patches pushState/replaceState rather than polling: a route change is a\n * discrete event, and polling would either miss fast back-to-back navigations or\n * burn a timer on every page for the entire session. popstate covers\n * back/forward, which history patching does not see.\n *\n * Deduplicates on pathname, because frameworks routinely replaceState several\n * times for one navigation (query/hash updates, scroll restoration) and each\n * would otherwise look like another page in the visitor's journey.\n */\n/** Pages already recorded this page lifetime, keyed project:path. dispose()\n * flushes, so without this a consent-change or StrictMode re-init delivered a\n * second landing pageview for a page the previous client already sent. */\nconst emittedPages = new Set<string>();\n\nfunction startPageviewTracking(\n client: SentientClient,\n projectId: string,\n // Called with the page key after emitting; the caller marks emittedPages only\n // once the event reached a LIVE queue. Marking at emit time instead turned\n // StrictMode's mount→dispose→mount into zero delivered landings: the first\n // mount's event dies in the destroyed queue, and the mark suppressed the\n // second mount's — the one that actually ships.\n markDelivered: (key: string) => void,\n): () => void {\n const h = typeof window === 'undefined' ? null : window.history;\n if (!h) return () => undefined;\n\n // The stop handle exists because init() runs again on every consent change,\n // StrictMode double-invoke and HMR: without it each init wrapped history\n // again and the old wrapper kept emitting through the DISPOSED client, so one\n // navigation produced one pageview per init that ever happened.\n let stopped = false;\n let last: string | undefined;\n const emit = (): void => {\n if (stopped) return;\n const path = currentPath();\n if (!path || path === last) return;\n last = path;\n // '__page__' is a sentinel componentId: the ingest schema requires one, and\n // every component reader filters on variant_id IS NOT NULL or a specific\n // event_type, so it never surfaces as a component.\n client.track({ projectId, componentId: '__page__', eventType: 'pageview', payload: {} });\n markDelivered(`${projectId}:${path}`);\n };\n\n const installed: Array<['pushState' | 'replaceState', History['pushState'], History['pushState']]> = [];\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = h[name];\n const wrapper = function (this: History, ...a: unknown[]) {\n const r = (orig as (...x: unknown[]) => unknown).apply(this, a);\n emit();\n return r;\n } as History[typeof name];\n h[name] = wrapper;\n installed.push([name, orig, wrapper]);\n }\n window.addEventListener('popstate', emit);\n\n // The landing page itself — once per (project, path) per page lifetime. When\n // it was already sent, `last` is still primed so the next real navigation\n // emits exactly once.\n const landing = currentPath();\n if (landing && emittedPages.has(`${projectId}:${landing}`)) last = landing;\n else emit();\n\n return () => {\n if (stopped) return;\n stopped = true;\n window.removeEventListener('popstate', emit);\n for (const [name, orig, wrapper] of installed) {\n // Restore only while ours is still on top; if something wrapped over it,\n // unhooking would sever their chain — the stopped flag already makes ours\n // a passthrough.\n if (h[name] === wrapper) h[name] = orig;\n }\n };\n}\n\nconst SSR_CLIENT: SentientClient = {\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n getAssignment: () => null,\n assign: () => Promise.resolve(null),\n decide: () => Promise.resolve(null),\n getSlotResult: () => null,\n getSlotConfig: () => null,\n getSitePalette: () => null,\n reportSlots: () => undefined,\n getPersona: () => null,\n fetchWeights: () => Promise.resolve([]),\n getGraph: () => ({ pageNodes: [], capturedAt: 0 }),\n flush: () => undefined,\n dispose: () => undefined,\n destroy: () => undefined,\n};\n\nfunction readTrackedParams(): {\n utmParams: Record<string, string>;\n clickIds: Record<string, string>;\n} {\n try {\n return extractTrackedParams(window.location.search);\n } catch {\n return { utmParams: {}, clickIds: {} };\n }\n}\n\nfunction deriveBaseUrl(ingestUrl: string): string {\n return ingestUrl.replace(/\\/events\\/?$/, '');\n}\n\n/**\n * Detects whether the visitor has signalled a tracking opt-out. Honors Global\n * Privacy Control (`navigator.globalPrivacyControl`) — the legally-enforceable\n * CCPA/CPRA signal — as well as Do Not Track (`navigator.doNotTrack`, the legacy\n * `window.doNotTrack` on older Firefox, and `navigator.msDoNotTrack` on old\n * IE/Edge). GPC is a boolean; DNT is opt-out only when explicitly `'1'`/`'yes'`.\n */\nexport function isDoNotTrackEnabled(): boolean {\n // GPC is a boolean flag, checked separately from the DNT string signals.\n if (\n typeof navigator !== 'undefined' &&\n (navigator as unknown as { globalPrivacyControl?: boolean }).globalPrivacyControl === true\n ) {\n return true;\n }\n const signals = [\n typeof navigator !== 'undefined' ? navigator.doNotTrack : undefined,\n typeof window !== 'undefined'\n ? (window as unknown as { doNotTrack?: string | null }).doNotTrack\n : undefined,\n typeof navigator !== 'undefined'\n ? (navigator as unknown as { msDoNotTrack?: string | null }).msDoNotTrack\n : undefined,\n ];\n return signals.some((v) => v === '1' || v === 'yes');\n}\n\n/**\n * Upgrades a pre-consent client (any client created with `consent: false`, in\n * either `preConsentBehavior` mode) to a fully-tracking client, in place and\n * with no page reload. Call this from your consent management platform callback.\n * For React apps, prefer updating the `consent` prop on `<AdaptiveProvider>`.\n * Pass `apiKey` to target a specific project; omit to upgrade the most-recently-initialized client.\n */\nexport function grantConsent(apiKey?: string): void {\n if (typeof window === 'undefined') return;\n\n const key = apiKey ?? _lastApiKey;\n if (!key) {\n console.warn('[sentient] grantConsent() called before init()');\n return;\n }\n\n const entry = _clients.get(key);\n if (!entry) {\n console.warn('[sentient] grantConsent() called before init()');\n return;\n }\n\n const { config, upgrade, reinit } = entry;\n if (!upgrade) {\n // Keyless/local and invalid-key clients register no upgrade hook — there\n // is no hosted client to swap in. This used to return SILENTLY, so a CMP\n // callback wired to grantConsent() looked like it worked while nothing\n // ever started tracking. DNT-blocked and already-upgraded entries carry no\n // reason and stay quiet: for them the no-op is the documented contract.\n if (entry.upgradeBlockedReason) console.warn(entry.upgradeBlockedReason);\n return;\n }\n\n // Honor an active Do Not Track signal — consent cannot override a global opt-out.\n if (config.respectDoNotTrack !== false && isDoNotTrackEnabled()) return;\n\n // Upgrade through the entry point that ran the gated init when one\n // registered itself (see _registerConsentUpgradeInit) — the lean init knows\n // nothing about that entry's extra resources (the /graph scanner).\n const fullClient = (reinit ?? init)({ ...config, consent: true });\n upgrade(fullClient);\n // init() just registered the full client (with its dispose) under `key`.\n // Preserve that dispose so a later re-init/teardown can still tear it down —\n // we only need to clear the upgrade hook now that consent is granted.\n const disposed = _clients.get(key)?.dispose;\n _clients.set(key, { config: { ...config, consent: true }, upgrade: null, dispose: disposed });\n}\n\nfunction createPreConsentProxy(config: SentientConfig, neverUpgrades: boolean): { proxy: SentientClient; setInner: (c: SentientClient) => void } {\n // 'control' (the default) must reach the network zero times before consent.\n // The proxy still exists so grantConsent() has something to upgrade in place\n // — without it, a site wanting no pre-consent traffic could only start\n // tracking by reloading the page.\n const servesWinner = config.preConsentBehavior === 'statistical_winner';\n const baseUrl = deriveBaseUrl(config.ingestUrl ?? DEFAULT_INGEST_URL);\n const authHeaders = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n } as const;\n\n // Pre-consent winners are read-only and render-driven: every mounted\n // component re-calls assign() on every render, and without a result cache or\n // in-flight coalescing each call refired GET /v1/winner — the full client\n // has inflightAssigns for exactly this. Successful winners are cached for\n // the pre-consent phase (the winner is stable, and a flip mid-visit would be\n // a variant flash anyway); failure fallbacks are NOT cached, so a recovering\n // server gets asked again. Both maps die with the proxy on upgrade.\n const winnerCache = new Map<string, AssignResult>();\n const inflightWinners = new Map<string, Promise<AssignResult | null>>();\n\n let inner: SentientClient = {\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n getAssignment: () => null,\n fetchWeights: () => Promise.resolve([]),\n assign(componentId, variantIds, _agentData?) {\n // Control mode: no request. Callers fall back to variantIds[0] through\n // ssrFallback, exactly as they did against the old no-op client.\n if (!servesWinner) return Promise.resolve(null);\n const cached = winnerCache.get(componentId);\n if (cached) return Promise.resolve(cached);\n return coalesce(inflightWinners, componentId, async (): Promise<AssignResult | null> => {\n try {\n const params = new URLSearchParams({ componentId });\n for (const v of variantIds ?? []) params.append('variantIds[]', v);\n const t = timeoutSignal(REQUEST_TIMEOUT_MS);\n let body: { variantId: string };\n try {\n const res = await fetch(`${baseUrl}/winner?${params.toString()}`, {\n headers: authHeaders,\n signal: t.signal,\n });\n if (!res.ok) return variantIds?.[0] ? { variantId: variantIds[0], assignmentTtlMs: 0 } : null;\n body = (await res.json()) as { variantId: string };\n } finally {\n t.clear();\n }\n const result: AssignResult = { variantId: body.variantId, assignmentTtlMs: 0 };\n winnerCache.set(componentId, result);\n return result;\n } catch {\n return variantIds?.[0] ? { variantId: variantIds[0], assignmentTtlMs: 0 } : null;\n }\n });\n },\n decide: () => Promise.resolve(null),\n getSlotResult: () => null,\n getSlotConfig: () => null,\n getSitePalette: () => null,\n reportSlots: () => undefined,\n getPersona: () => null,\n getGraph: () => ({ pageNodes: [], capturedAt: 0 }),\n flush: () => undefined,\n dispose: () => undefined,\n destroy: () => undefined,\n };\n\n let upgraded = false;\n const slotListeners = new Set<() => void>();\n // Every argument is queued and forwarded: the render caps and skeletons\n // (native generation) ride the third one, and dropping them made a\n // consent-gated page read as a legacy SDK — never drawn a Rewrite arm.\n const queuedSlots: Array<[string[], Parameters<NonNullable<SentientClient['requestSlots']>>[1], Parameters<NonNullable<SentientClient['requestSlots']>>[2]]> = [];\n let queuedDecls: SlotDeclInput[] = [];\n // decide() while gated: held and replayed on upgrade (audit N1). The pre-\n // consent client answered null and nothing asked again, so a visitor whose\n // consent arrived a moment later — every consentFrom snippet page view, now\n // that the presets load lazily — got no decision for the whole page view.\n // Keyed by path: a decide replayed after an SPA navigation would book trials\n // for slots that are no longer on the page (CONTRACTS §2), so it resolves null.\n const queuedDecides: Array<[Parameters<SentientClient['decide']>[0], string, (o: DecideOutcome | null) => void]> = [];\n\n const releaseDecides = (): void => {\n for (const [, , done] of queuedDecides.splice(0)) done(null);\n heldCalls.length = 0;\n };\n // Session-level conversions (goal()) recorded while consent is still\n // unknown — every consentFrom snippet page boots gated while the presets\n // chunk loads, so a consented visitor's order-confirmation goal() used to\n // vanish (grader NEW-1; CONTRACTS §7: never swallowed). Held in memory only\n // — nothing is stored or sent — and replayed if consent arrives in this\n // page view, dropped on dispose/destroy/refusal. Never held under DNT/GPC\n // (no upgrade). NOT componentGoal/track: those attribute to a variant, and\n // pre-consent the visitor saw the baseline — replayed after the grant they\n // credited whatever the tracking client then held (review #4).\n const heldCalls: Array<(c: SentientClient) => void> = [];\n // Set by dispose()/destroy() before an upgrade: a released gated client\n // holds nothing more (goals fired after a refusal were held again and sent\n // on a later accept — grader N7-3) and answers any decide with null at once\n // (a held decide on it could never settle — review #3). `released` tells a\n // caller that a null came from this, not from a failed request.\n let released = false;\n // A released proxy also leaves the grantConsent() registry: a later global\n // grant upgraded it in place, reviving a client its owner had let go of\n // (review R8 #6). Only our own hook — a newer init under the key keeps its.\n const release = (): void => {\n if (upgraded) return;\n released = true;\n const entry = _clients.get(config.apiKey);\n if (entry?.upgrade === setInner) {\n _clients.set(config.apiKey, {\n config,\n upgrade: null,\n upgradeBlockedReason:\n '[sentient] grantConsent(): client released before consent; call init() again',\n });\n }\n };\n // Held calls replay one per task after the upgrade (see setInner); a goal\n // fired meanwhile joins the back of that line, or it was sent before the\n // conversions that happened first (grader N11-3).\n const replay: Array<(c: SentientClient) => void> = [];\n const pumpReplay = (): void =>\n void setTimeout(() => {\n try {\n replay.shift()?.(inner);\n } catch {\n /* one bad call never blocks the rest */\n }\n if (replay.length) pumpReplay();\n });\n const hold = (call: (c: SentientClient) => void): void => {\n if (upgraded) {\n if (replay.length) replay.push(call);\n else call(inner);\n } else if (!neverUpgrades && !released && heldCalls.length < 100) heldCalls.push(call);\n // Visible in debug: a goal after a refusal is dropped on purpose, and a\n // silent drop read as a broken integration (grader N10-2).\n else if (released && config.debug) console.warn('[sentient] goal dropped: client released');\n };\n const proxy: SentientClient = {\n get gated() {\n return !upgraded && !neverUpgrades;\n },\n get released() {\n return released && !upgraded;\n },\n /** @internal Hand the held conversions to another client (React re-inits\n * on a grant instead of upgrading in place) and clear them. */\n takeHeld: () => heldCalls.splice(0),\n track: (e) => inner.track(e),\n // Cast: a single arrow can't structurally satisfy the overloaded member;\n // the passthrough forwards both call shapes untouched.\n goal: ((n: string, m?: Record<string, unknown>, w?: number, s?: number) => hold((c) => c.goal(n, m, w, s))) as SentientClient['goal'],\n componentGoal: (c, g, o) => inner.componentGoal(c, g, o),\n identify: (u) => inner.identify(u),\n getAssignment: (c, s) => inner.getAssignment(c, s),\n assign: (c, v, a, av) => inner.assign(c, v, a, av),\n decide: (i) =>\n upgraded\n ? inner.decide(i)\n : released\n ? Promise.resolve(null)\n : // DNT/GPC can never be upgraded: held, it would never resolve, and a\n // core-direct `await client.decide()` hung for every GPC browser (F1).\n neverUpgrades\n ? Promise.resolve(null)\n : new Promise<DecideOutcome | null>((done) => queuedDecides.push([i, routeKey(), done])),\n getSlotResult: (s) => inner.getSlotResult(s),\n isSlotDecided: (s) => inner.isSlotDecided?.(s) ?? true,\n getSlotConfig: (s) => inner.getSlotConfig(s),\n getSitePalette: () => inner.getSitePalette(),\n getStyleVocabulary: () => inner.getStyleVocabulary?.() ?? null,\n reportSlots: (ids, texts, skels, authored) => inner.reportSlots(ids, texts, skels, authored),\n reportSkeleton: (id, sk) => inner.reportSkeleton?.(id, sk),\n reportDrift: (id, e, o, r) => inner.reportDrift?.(id, e, o, r),\n // Pre-consent: queue mounted slots and hold listeners, then hand both to\n // the real client on upgrade. A grantConsent() upgrade swaps the client in\n // place without remounting, so a slot that asked while gated would\n // otherwise never be decided.\n requestSlots: (ids, texts, extras) => (upgraded ? inner.requestSlots?.(ids, texts, extras) : queuedSlots.push([ids, texts, extras])),\n decideSlots: (d) => (upgraded ? inner.decideSlots?.(d) : queuedDecls.push(...d)),\n // Pre-consent, an unmounted slot leaves the queue too: consent may be\n // granted minutes later on a different route, and the slots the visitor\n // mounted before navigating away are not on the page then.\n cancelSlots: (ids) => {\n if (upgraded) return inner.cancelSlots?.(ids);\n const gone = new Set(ids);\n for (const q of queuedSlots) q[0] = q[0].filter((id) => !gone.has(id));\n queuedDecls = queuedDecls.filter((d) => !gone.has(d.id));\n },\n onSlotsChanged: (l) => (slotListeners.add(l), () => void slotListeners.delete(l)),\n getPersona: () => inner.getPersona(),\n fetchWeights: () => inner.fetchWeights(),\n getGraph: () => inner.getGraph(),\n flush: () => inner.flush(),\n dispose: () => (release(), releaseDecides(), inner.dispose()),\n // Before consent there is no tracking client to destroy, but a returning\n // visitor may still have an id, snapshot and buckets from an earlier\n // consented visit: forget-me deletes them all the same (grader F2 — a\n // \"Reject\" on a manual gate used to delete nothing).\n destroy: () => (release(), releaseDecides(), upgraded ? inner.destroy() : forgetVisitor(config.apiKey)),\n };\n\n function setInner(fullClient: SentientClient) {\n inner = fullClient;\n upgraded = true;\n // Each in its own task: replayed in one go they shared one latch window\n // (createActionLatch), so two held add_to_cart clicks became one (NEW-3).\n // In order, one per task (see pumpReplay).\n if (heldCalls.length) {\n replay.push(...heldCalls.splice(0));\n pumpReplay();\n }\n const path = routeKey();\n for (const [input, at, done] of queuedDecides.splice(0)) {\n if (at !== path) done(null);\n else fullClient.decide(input).then(done, () => done(null));\n }\n fullClient.onSlotsChanged?.(() => slotListeners.forEach((l) => l()));\n for (const [ids, texts, extras] of queuedSlots.splice(0)) if (ids.length > 0) fullClient.requestSlots?.(ids, texts, extras);\n if (queuedDecls.length > 0) fullClient.decideSlots?.(queuedDecls.splice(0));\n }\n\n return { proxy, setInner };\n}\n\n/**\n * The page a decision belongs to: the pathname plus a route-shaped fragment.\n * Hash routers (`#/pricing`) navigate without changing the pathname; an\n * in-page anchor (`#faq`) is not a route. Shared by the held-decide drop rule\n * and the snippet's re-decide check, which must agree (grader NEW-2).\n */\nexport function routeKey(): string {\n return typeof location === 'undefined' ? '' : location.pathname + (/^#!?\\//.test(location.hash) ? location.hash : '');\n}\n\n/**\n * Shares one promise among concurrent calls with the same key — assign() and\n * decide() both use this so N same-tick requests (several mounted slots\n * sharing a component id; per-slot lazy decides) cost one roundtrip. The map\n * entry lives exactly as long as the request is in flight: a settled result\n * must NOT serve later calls (a sequential re-request is a fresh decision —\n * caching lives elsewhere), and a failed one must not wedge the key. No\n * `.finally()` — that's ES2018 and this file ships in the es2017 snippet\n * bundle (the SNIP-5 lesson).\n */\nfunction coalesce<T>(inflight: Map<string, Promise<T>>, key: string, run: () => Promise<T>): Promise<T> {\n const hit = inflight.get(key);\n if (hit) return hit;\n const request = (async (): Promise<T> => {\n try {\n return await run();\n } finally {\n inflight.delete(key);\n }\n })();\n inflight.set(key, request);\n return request;\n}\n\n/**\n * Initializes the Sentient client. Returns a no-op client during SSR.\n */\nexport function init(config: SentientConfig): SentientClient {\n if (typeof window === 'undefined') {\n return SSR_CLIENT;\n }\n\n if (config.nonce) setCspNonce(config.nonce);\n\n // `|| 'local'`: keyless clients register under the 'local' fallback key\n // below, and `_lastApiKey = ''` is falsy — so a no-arg grantConsent() after\n // a keyless init() warned \"called before init()\" even though init() DID run,\n // instead of resolving that entry (and its blocked-upgrade explanation).\n _lastApiKey = config.apiKey || 'local';\n\n // A re-init for the same key (HMR, consent toggle, provider remount) supersedes\n // the prior client. Dispose it first so its queue's setInterval and\n // visibilitychange/pagehide listeners don't leak — the map only ever held its\n // config, so without this the old client kept flushing forever.\n const prevEntry = _clients.get(config.apiKey || 'local');\n if (prevEntry?.dispose) {\n try {\n prevEntry.dispose();\n } catch {\n /* teardown must never throw on re-init */\n }\n }\n\n // DNT/GPC (a global opt-out) or an explicit `consent: false` must be evaluated\n // BEFORE the local-mode branch: createLocalModeClient() calls initSession()\n // unconditionally, so a gated visitor would otherwise be issued the 365-day\n // `_snt_uid` identity cookie in keyless/local mode (audit P2). DNT/GPC also\n // gates tracking off even when the site passes `consent: true`, and blocks\n // `grantConsent()` from upgrading.\n const dntBlocked = config.respectDoNotTrack !== false && isDoNotTrackEnabled();\n const gated = config.consent === false || dntBlocked;\n\n // Keyless local mode. `localMode: true` forces the local engine (documented\n // escape hatch); 'auto' (default) engages it only when no valid key is\n // present. In production builds `@sentientui/core/local` resolves to a stub\n // and this degrades to a no-op client + one console.error per page load\n // (createLocalModeClient handles that), so no NODE_ENV check is needed here.\n const keyValid = typeof config.apiKey === 'string' && config.apiKey.startsWith('pk_');\n if (config.localMode === true || (!keyValid && config.localMode !== false)) {\n // One registration for both arms (they used to duplicate this set call).\n // upgrade stays null — there is no hosted client to swap in — but the\n // reason lets grantConsent() explain that instead of no-oping silently.\n _clients.set(config.apiKey || 'local', {\n config,\n upgrade: null,\n upgradeBlockedReason:\n '[sentient] grantConsent(): this client is keyless/local — there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking.',\n });\n // A gated visitor must never get the identity cookie. Local mode has no\n // server to serve a statistical winner from, so return a plain no-op.\n if (gated) return SSR_CLIENT;\n return createLocalModeClient(config);\n }\n\n if (gated) {\n if (!config.apiKey || !config.apiKey.startsWith('pk_')) {\n if (config.preConsentBehavior === 'statistical_winner') {\n console.warn('[sentient] init() called with an invalid apiKey — expected a pk_ public key. SDK disabled.');\n }\n // Registered under the same 'local' fallback key the local branch uses:\n // `config.apiKey` here can be '', and a ''-keyed entry was unreachable\n // by a no-arg grantConsent() (falsy `_lastApiKey`), which then wrongly\n // warned \"called before init()\".\n _clients.set(config.apiKey || 'local', {\n config,\n upgrade: null,\n upgradeBlockedReason:\n '[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) — consent cannot enable tracking.',\n });\n return SSR_CLIENT;\n }\n // Every gated client gets an upgradeable proxy, not just the winner-serving\n // one — otherwise grantConsent() is silently dead for the 'control' default\n // and the site has to reload to start tracking. Control mode still makes no\n // request; the proxy only exists so consent can swap the inner client.\n const { proxy, setInner } = createPreConsentProxy(config, dntBlocked);\n // Under DNT the read-only winner still serves, but consent can never\n // upgrade it to tracking — so drop the upgrade hook.\n _clients.set(config.apiKey, { config, upgrade: dntBlocked ? null : setInner });\n return proxy;\n }\n\n if (!config.apiKey || !config.apiKey.startsWith('pk_')) {\n console.warn('[sentient] init() called with an invalid apiKey — expected a pk_ public key. SDK disabled.');\n return SSR_CLIENT;\n }\n\n if (config.ingestUrl === '') {\n console.warn('[sentient] init() called with an empty ingestUrl. SDK disabled.');\n return SSR_CLIENT;\n }\n\n const resolvedIngestUrl = config.ingestUrl ?? DEFAULT_INGEST_URL;\n\n const sessionStart = Date.now();\n const session = initSession({ ssrSessionId: config.ssrSessionId, apiKey: config.apiKey });\n const rawCache = createAssignmentCache(undefined, config.apiKey);\n // Set by this client's destroy(). The window marker covers other bundles'\n // forget-me, but a new grant clears it — and this client's own in-flight\n // answer must never write a forgotten visitor back after that either.\n let forgottenHere = false;\n const createdGen = forgetGeneration(config.apiKey);\n const mayPersist = (): boolean => !forgottenHere && forgetGeneration(config.apiKey) === createdGen;\n // Same rule as the snapshot write: nothing is cached for a forgotten visitor.\n const assignmentCache: typeof rawCache = {\n ...rawCache,\n set: (...a) => {\n if (mayPersist()) rawCache.set(...a);\n },\n };\n const eventQueue = createEventQueue({ ingestUrl: resolvedIngestUrl, apiKey: config.apiKey });\n const baseUrl = deriveBaseUrl(resolvedIngestUrl);\n\n const authHeaders = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n } as const;\n\n // Conversions get the same durable transport the event queue has always had:\n // retry with backoff, a cross-reload bucket, dedupe on the server's goalId.\n // One warning per distinct drop status per page load (see onDrop below).\n const warnedDropStatuses = new Set<number>();\n const goalQueue: GoalQueue = createGoalQueue({\n url: `${baseUrl}/goals`,\n apiKey: config.apiKey,\n headers: authHeaders,\n onDrop: (goal, status) => {\n // NOT debug-gated. CONTRACTS §7 says a dropped goal is reported to the\n // developer and never swallowed, but this returned early unless debug was\n // on — so in production a rate-limited or misconfigured project lost every\n // conversion with no signal anywhere. Warn once per (status, page load):\n // enough to be discoverable in a console or an error reporter, quiet\n // enough that a broken integration cannot flood the page.\n if (!config.debug) {\n if (warnedDropStatuses.has(status)) return;\n warnedDropStatuses.add(status);\n }\n console.warn(\n `[sentient] goal dropped (HTTP ${status}) — this will not be retried. ` +\n (status === 400\n ? 'The session was not found: call init() and let the session upsert complete before firing goals.'\n : status === 401 || status === 403\n ? 'Check the API key and that this origin is on the project allowlist.'\n : 'See the response status for the cause.'),\n goal,\n );\n },\n });\n\n const deviceClass = detectDeviceClass(navigator.userAgent ?? '');\n // No window guard here: init() already returned SSR_CLIENT at the top when\n // window is undefined, so the old `typeof window` ternary was dead code.\n const appOrigin = window.location.origin;\n const trafficSource = detectTrafficSource(document.referrer ?? '', appOrigin);\n const sessionSegment =\n config.sessionSegment ?? `${deviceClass}:${trafficSource}`;\n const inflightAssigns = new Map<string, Promise<AssignResult | null>>();\n // Mirrors inflightAssigns for decide(): per-slot lazy-decide patterns (see\n // local-mode's merge comment — one decide({ slots: [decl] }) per mounted\n // slot, all in the same tick) otherwise issue N roundtrips and N snapshot\n // rewrites for one page. Keyed by the full request payload, never just \"a\n // decide is running\": coalescing {slots:[a]} with {slots:[b]} would hand\n // slot b's caller an outcome that never decided b.\n const inflightDecides = new Map<string, Promise<DecideOutcome | null>>();\n\n // --- Adaptive-slot state (decide) ---\n // Results served for this session, keyed by slot id. Written by decide();\n // read by getSlotResult() (Task 3.3) and componentGoal's slot fallback.\n const slotStore = new Map<string, SlotResult>();\n // Ids whose slotStore entry the server decided for THIS session (SSR seed or\n // a decide response). Snapshot seeds and failure baselines are deliberately\n // absent: they render (pre-paint parity, \"always resolve to something\") but\n // have no slot_decisions row, so the React exposure gates must not record an\n // impression for them — a failed 30-declaration batch used to yield up to\n // 30 phantom baseline exposures, and a snapshot arm was exposed and then a\n // second, different arm exposed again when the real decide landed.\n const decidedSlotIds = new Set<string>();\n // Registry slot config (content/ops/blocks) served this session. Written by\n // decide() and the SSR/snapshot seeds below; read by getSlotConfig() so SDK\n // surfaces (AdaptiveSlot) can render server-authored arms — previously the\n // snippet was the only consumer and this never left the decide outcome.\n const slotConfigStore = new Map<string, SlotConfigEntry>();\n let sitePalette: import('./blocks.js').SitePalette | null = null;\n let styleVocabulary: import('./style-vocabulary.js').StyleVocabulary | null = null;\n let personaState: { persona: string; confidence: number } | null = null;\n // First-seen slot registration (reportSlots): once per id per client.\n const reportedSlotIds = new Set<string>();\n const pendingSlotReports = new Set<string>();\n // Baseline text captured with the first report of an id. Bounded by the\n // once-per-id dedupe above, normalized + capped before it leaves the page.\n const pendingBaselineTexts = new Map<string, string>();\n const pendingBaselineSkeletons = new Map<string, SkeletonReport>();\n const reportedSkeletonIds = new Set<string>();\n // Drift: once per (slot, expected fp) per client.\n const reportedDrift = new Set<string>();\n const reportedAuthored = new Set<string>();\n let slotReportTimer: ReturnType<typeof setTimeout> | null = null;\n // Mirror of the server's slot-id rule (apps/api/src/routes/slots-observed.ts):\n // the server 400s the WHOLE batch when any one id fails it, and every\n // co-batched valid id is already in reportedSlotIds by then — so a single\n // `hero.cta` on the page would silently unregister every other new slot for\n // the client lifetime. Invalid ids are refused at the door instead.\n const SLOT_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/;\n const warnedInvalidSlotIds = new Set<string>();\n // requestSlots: mounted-slot decides, once per id per client.\n const slotListeners = new Set<() => void>();\n const requestedSlotIds = new Set<string>();\n const pendingSlotTexts = new Map<string, { text?: string; render?: RenderCaps; skeleton?: SkeletonReport }>();\n let slotRequestTimer: ReturnType<typeof setTimeout> | null = null;\n // decideSlots: mounted request-declared slots, once per id per client.\n const decidedDeclIds = new Set<string>();\n const pendingDecls = new Map<string, SlotDeclInput>();\n let declTimer: ReturnType<typeof setTimeout> | null = null;\n // \"Once per id per client\" was keyed on the ASK, not the answer: a decide\n // that failed (5xx, offline, tab suspended mid-flight) left its ids marked\n // as requested, so the slots served their baseline/snapshot — unexposed,\n // untrained — for the rest of the client lifetime, and a SPA visitor never\n // got a decision for that page again. Failed ids are released so a remount\n // re-asks, and each batch gets a bounded automatic retry with backoff so a\n // blip during the initial render still resolves without user action.\n // Bounded per id per client, not per mount: a server that is really down\n // must not turn every route change into a retry storm.\n const SLOT_DECIDE_AUTO_RETRIES = 2;\n const slotDecideFailures = new Map<string, number>();\n let slotDecideTornDown = false;\n // Releases every id in the failed batch, then schedules `resend` (after the\n // backoff for the worst-off id) with the subset still under the retry cap.\n const retryFailedSlots = (ids: string[], requested: Set<string>, resend: (retry: Set<string>) => void): void => {\n const retry = new Set<string>();\n let worst = 1;\n for (const id of ids) {\n requested.delete(id);\n const n = (slotDecideFailures.get(id) ?? 0) + 1;\n slotDecideFailures.set(id, n);\n if (n <= SLOT_DECIDE_AUTO_RETRIES) {\n retry.add(id);\n if (n > worst) worst = n;\n }\n }\n if (retry.size > 0) {\n setTimeout(() => {\n if (!slotDecideTornDown) resend(retry);\n }, backoffDelayMs(worst));\n }\n };\n\n // On decide failure every declared slot must still resolve — to its baseline.\n // Never overwrite a previously served result.\n const seedSlotBaselines = (decls: SlotDeclInput[]): void => {\n for (const d of decls) {\n if (!slotStore.has(d.id)) slotStore.set(d.id, baselineResultFor(d));\n }\n };\n\n // Seed slot/persona state. Priority: explicit SSR seeds → snapshot.\n if (config.initialSlots) {\n for (const [slotId, result] of Object.entries(config.initialSlots)) {\n slotStore.set(slotId, result);\n // The SSR preload decided these against this very session id.\n decidedSlotIds.add(slotId);\n }\n }\n if (config.initialSlotConfig) {\n for (const [slotId, entry] of Object.entries(config.initialSlotConfig)) {\n slotConfigStore.set(slotId, entry);\n }\n }\n if (config.initialPalette) sitePalette = config.initialPalette;\n if (config.initialVocabulary) styleVocabulary = config.initialVocabulary;\n const seedSnapshot = readSnapshot(config.apiKey);\n if (seedSnapshot) {\n for (const [slotId, result] of Object.entries(seedSnapshot.slots)) {\n if (!slotStore.has(slotId)) slotStore.set(slotId, result);\n }\n for (const [slotId, entry] of Object.entries(seedSnapshot.slotConfig ?? {})) {\n if (!slotConfigStore.has(slotId)) slotConfigStore.set(slotId, entry);\n }\n if (!sitePalette && seedSnapshot.palette) sitePalette = seedSnapshot.palette;\n if (!styleVocabulary && seedSnapshot.vocabulary) styleVocabulary = seedSnapshot.vocabulary;\n }\n\n // Band-only persona sources (html attrs, snapshot) become a band-consistent\n // numeric confidence so confidenceBand(confidence) always equals the band.\n const BAND_CONFIDENCE: Record<string, number> = { low: 0.15, medium: 0.5, high: 0.85 };\n if (config.initialPersona) {\n personaState = { ...config.initialPersona };\n } else {\n // Single-writer rule: the inline pre-paint script owns the <html>\n // attributes. The client ADOPTS them as truth and never rewrites them\n // mid-session (next visit's script picks up the new snapshot instead).\n const ds = document.documentElement.dataset;\n if (ds.sentientPersona) {\n personaState = {\n persona: ds.sentientPersona,\n confidence: BAND_CONFIDENCE[ds.sentientConfidence ?? 'low'] ?? 0.15,\n };\n } else if (seedSnapshot) {\n personaState = {\n persona: seedSnapshot.persona,\n confidence: BAND_CONFIDENCE[seedSnapshot.band] ?? 0.15,\n };\n }\n }\n\n // Seed SSR-preloaded assignments into the local cache so assign() finds a\n // cache hit immediately — no network call, no variant flash on hydration.\n if (config.initialAssignments) {\n for (const [componentId, variantId] of Object.entries(config.initialAssignments)) {\n assignmentCache.set(componentId, sessionSegment, {\n variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n });\n }\n }\n\n // Upsert session metadata once on init. assign() awaits this promise so\n // the server isn't asked to assign for a session row that doesn't exist yet.\n let sessionReady: Promise<void> = Promise.resolve();\n\n const sessionId = session.getSessionId();\n if (sessionId) {\n const referrerDomain = referrerDomainFromReferer(document.referrer ?? '');\n const { utmParams, clickIds } = readTrackedParams();\n const sessionBody = {\n sessionId,\n deviceClass,\n trafficSource,\n referrerDomain,\n utmParams,\n // Ad-platform click IDs (gclid & co). Captured separately from utmParams\n // because Google Ads auto-tagging appends ONLY gclid — without this,\n // paid search with no manual UTM template reported as organic.\n clickIds,\n // The landing page's PATH (never its query string) — it is what tells a\n // paid click to a product page or a Shopify /discount/ link apart from\n // any other arrival (server-side arrival classification).\n landingPath: typeof location !== 'undefined' ? location.pathname : undefined,\n timeOfDay: detectTimeOfDay(new Date()),\n dayOfWeek: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][new Date().getDay()],\n ephemeral: session.isEphemeral(),\n // Likely-automation hint: navigator.webdriver (set under automation\n // control) or a known agent token in the UA. Probabilistic — used for\n // metrics + bandit exclusion server-side, never to change what's served.\n automation:\n (typeof navigator !== 'undefined' && navigator.webdriver === true) ||\n uaTokenMatch(navigator.userAgent ?? ''),\n ...(config.userId ? { userId: config.userId } : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n ...(config.country ? { country: config.country } : {}),\n // Version-skew reporting. Only a wrapper that knows its own released\n // version sets this — a dev-sentinel version is dropped by the caller,\n // not smuggled through, or the dashboard would read it as \"behind\"\n // forever (the same trap the snippet's decide reporting documents).\n ...(config.sdk ? { sdk: config.sdk.name, sdkVersion: config.sdk.version } : {}),\n };\n // The session row is a PRECONDITION for every conversion: /v1/goals answers\n // 400 session_not_found without it, and the durable queue classifies a 4xx\n // as terminal — so a session upsert that fails silently turns every later\n // conversion into a permanent drop. That is not hypothetical: /v1/sessions\n // carries the same per-IP limiter as /v1/goals, so under shared egress\n // (offices, mobile carriers, corporate NAT) the SESSION call 429s first and\n // the goals that follow are dropped for good. Retry it, so a transient\n // failure costs a moment rather than the visit's whole conversion history.\n const upsertSession = async (): Promise<undefined> => {\n for (let attempt = 0; ; attempt++) {\n // Stop retrying once this client is torn down or the visitor was\n // forgotten: the retries POSTed the forgotten id again (N7-6).\n if (slotDecideTornDown || !mayPersist()) return undefined;\n const t = timeoutSignal(REQUEST_TIMEOUT_MS);\n try {\n const res = await fetch(`${baseUrl}/sessions`, {\n method: 'POST',\n keepalive: true,\n body: JSON.stringify(sessionBody),\n headers: authHeaders,\n signal: t.signal,\n });\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n return undefined; // terminal: retrying a quota will not clear it\n }\n if (res.ok || classifyResponse(res) === 'dropped') return undefined;\n } catch {\n /* network failure or timeout — same retry path as a 5xx (the\n upsert is idempotent, so a timed-out attempt that did land is\n harmless to repeat) */\n } finally {\n t.clear();\n }\n if (attempt >= SESSION_UPSERT_RETRIES) {\n // Say so once: from here every conversion this visit will 400, and\n // that used to be entirely silent.\n console.warn(\n '[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.',\n );\n return undefined;\n }\n await new Promise((r) => setTimeout(r, backoffDelayMs(attempt + 1)));\n }\n };\n try {\n sessionReady = upsertSession();\n } catch {\n /* never throw on init */\n }\n }\n\n if (config.debug) {\n console.log('[sentient] initialized', { context: config.context });\n (\n window as unknown as {\n __sentient?: {\n client: SentientClient;\n queue: EventQueue;\n };\n }\n ).__sentient = {\n client: null as unknown as SentientClient,\n queue: eventQueue,\n };\n }\n\n // One user action must record ONE session-level conversion per goal name.\n // Nested components each fire their declared goal on the same click (every\n // <Adaptive>/hook path calls componentGoal() AND goal()), so a hero nested\n // inside a CTA wrapper wrote two goal_events rows for one click: harmless for\n // a weight-1.0 goal (close-out clamps at 1) but a 0.3-weight step summed to\n // 0.6, and the Goals page counts Hits as COUNT(*) either way.\n //\n // The scope is one event dispatch, not one session and no longer one task:\n // see createActionLatch. A session-wide latch would swallow genuine repeat\n // conversions (two purchases in one visit are two conversions), and a\n // time-boxed one did exactly that whenever the box outlived the action.\n // Calls carrying distinct externalIds are never collapsed — those are, by\n // definition, distinct orders.\n const firedThisAction = createActionLatch();\n\n // Set once tracking starts; dispose() and destroy() call it so a replaced\n // client stops watching history instead of emitting forever. The flag records\n // teardown for the delivery-marking below, which runs on a later microtask.\n let stopPageviews: (() => void) | null = null;\n let pageviewsTornDown = false;\n\n const client: SentientClient = {\n goal(name: string, metadataOrOpts: Record<string, unknown> = {}, weight = 1.0, stepIndex = 0) {\n const sid = session.getSessionId();\n // Nothing is sent by a client that was disposed (a pause) or forgotten.\n if (!sid || slotDecideTornDown || !mayPersist()) return;\n const opts: GoalOptions = isGoalOptions(metadataOrOpts)\n ? (metadataOrOpts as GoalOptions)\n : { metadata: metadataOrOpts };\n // stepIndex and weight are part of the key: funnel steps share a goal\n // name and differ by stepIndex, so collapsing on name alone dropped a\n // step fired in the same handler. Only IDENTICAL calls are one action.\n //\n // value and currency key the payload SEPARATELY (the latch's valueKey),\n // not as more segments of the flat key, and for a costlier reason: they\n // are the money. Flattened out of the key entirely, a $50 order and a\n // $70 order landing in one window collapsed into a single $50 record —\n // the client half of CONTRACTS §1 \"two orders are worth two orders\",\n // which the server already honours (migration 119 records the repeat if\n // it arrives; this is what stopped it arriving). But flattened INTO the\n // key, a valued inner component nested in a valueless wrapper made two\n // keys out of one click — two rows for one order. So the latch compares\n // values only between valued fires ($50 vs $70 stays two records) and\n // lets a valued record absorb a valueless re-fire of the same action\n // (see createActionLatch for the one asymmetric case).\n //\n // NOT metadata: every nested <Adaptive>/hook path stamps its own\n // componentId and variantId in there, so keying on it would make the\n // duplicate this latch exists to collapse look distinct again.\n const actionKey = [\n name,\n opts.externalId ?? '',\n opts.stepIndex ?? stepIndex,\n opts.weight ?? weight,\n ].join('\\0');\n const valueKey = opts.value !== undefined ? `${opts.value}\\0${opts.currency ?? ''}` : null;\n if (firedThisAction.firedBefore(actionKey, valueKey)) {\n if (config.debug) {\n console.log(`[sentient] goal(\"${name}\") already recorded for this action — not sent twice`);\n }\n return;\n }\n const goalId = generateEventId();\n // undefined values vanish at JSON.stringify time, so optional fields\n // need no conditional assembly.\n const body = {\n sessionId: sid,\n name,\n metadata: opts.metadata ?? {},\n weight: opts.weight ?? weight,\n stepIndex: opts.stepIndex ?? stepIndex,\n goalId,\n value: opts.value,\n currency: opts.currency,\n externalId: opts.externalId,\n };\n if (config.debug) {\n console.log('[sentient] goal', body);\n }\n // Serialize once, here: the queued copy must replay byte-identically\n // (same goalId) so a retry dedupes server-side instead of double-counting.\n const payload = { id: goalId, body: JSON.stringify(body) };\n sessionReady.then(() => goalQueue.send(payload));\n },\n\n componentGoal(componentId, goalType, opts) {\n const sid = session.getSessionId();\n // Same gate as goal(): a paused or forgotten client's component\n // conversion was still queued and sent (review R8 #3).\n if (!sid || slotDecideTornDown || !mayPersist()) return;\n // Variant experiments resolve from the assignment cache; adaptive slots\n // (useAdaptiveTokens / AdaptiveGroup) resolve from the slot state, using\n // the canonical arm string as the attributed variantId.\n const assignment = assignmentCache.get(componentId, sessionSegment);\n const slotResult = assignment ? null : slotStore.get(componentId) ?? null;\n if (!assignment && slotResult === null) {\n if (config.debug) {\n console.warn(\n `[sentient] componentGoal(\"${componentId}\"): no assignment or slot decision yet — render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`,\n );\n }\n return;\n }\n // A slot result the core only HOLDS (pre-paint snapshot, failure\n // baseline) has no slot_decisions row this session, so a goal attributed\n // to its arm would be a conversion with no trial behind it. The React\n // hooks gate this on `source === 'seeded'`; this is the same rule at the\n // transport, so a hand-rolled integration cannot bypass it.\n if (!assignment && !decidedSlotIds.has(componentId)) {\n if (config.debug) console.warn(`[sentient] componentGoal(\"${componentId}\"): slot not decided this session — not attributed`);\n return;\n }\n const attributedVariantId = assignment ? assignment.variantId : armOfResult(slotResult!);\n const fullEvent: SentientEvent = {\n id: generateEventId(),\n sessionId: sid,\n projectId: config.apiKey,\n componentId,\n variantId: attributedVariantId,\n eventType: 'goal_achieved',\n goalType,\n // undefined goalValue/currency vanish at JSON.stringify time.\n payload: {\n reward: opts?.reward ?? 1,\n goalValue: opts?.value,\n currency: opts?.currency,\n ...(opts?.metadata ?? {}),\n },\n timestamp: Date.now(),\n timeInSession: Date.now() - sessionStart,\n path: currentPath(),\n };\n if (config.debug) {\n console.log('[sentient] componentGoal', fullEvent);\n }\n sessionReady.then(() => {\n if (!slotDecideTornDown && mayPersist()) eventQueue.push(fullEvent);\n });\n },\n\n identify(userId) {\n const sid = session.getSessionId();\n if (!sid || slotDecideTornDown || !mayPersist()) return;\n sessionReady.then(() => {\n fetch(`${baseUrl}/sessions`, {\n method: 'POST',\n keepalive: true,\n body: JSON.stringify({ sessionId: sid, userId, ephemeral: session.isEphemeral() }),\n headers: authHeaders,\n }).catch(() => undefined);\n });\n },\n\n track(event) {\n const sessionId = session.getSessionId();\n if (!sessionId || slotDecideTornDown || !mayPersist()) return;\n // Same rule as componentGoal: an impression for a slot arm the core holds\n // without a decision this session (snapshot, failure baseline) trains an\n // arm the server never served. Only ids the core knows AS SLOTS are\n // gated — variant components never enter slotStore and pass through.\n if (\n event.eventType === 'variant_assigned' &&\n slotStore.get(event.componentId) !== undefined &&\n !decidedSlotIds.has(event.componentId) &&\n !assignmentCache.get(event.componentId, sessionSegment)\n ) return;\n\n const fullEvent: SentientEvent = {\n // `path` first so an explicit event.path from the caller wins over the\n // ambient one — a server-side or replayed event knows its page better\n // than location does.\n path: currentPath(),\n ...event,\n id: generateEventId(),\n sessionId,\n timestamp: Date.now(),\n timeInSession: Date.now() - sessionStart,\n };\n\n if (config.debug) {\n console.log('[sentient] track', fullEvent);\n }\n\n sessionReady.then(() => eventQueue.push(fullEvent));\n },\n\n getAssignment(componentId, segment) {\n return assignmentCache.get(componentId, segment);\n },\n\n async assign(componentId, variantIds, agentData?, agentDataByVariant?) {\n const sid = session.getSessionId();\n if (!sid) return null;\n\n const cached = assignmentCache.get(componentId, sessionSegment);\n // When variantIds are provided (A/B code variant), a cache hit is always final.\n // When variantIds are absent (managed text component), only hit the cache if content\n // is present — a seed from initialAssignments has no content and must still fetch.\n if (cached && (variantIds?.length || cached.content !== undefined)) {\n // Surface the entry's remaining TTL (server-provided when set) instead of\n // a hardcoded 0, so callers can reason about when a re-assign is due.\n const remainingTtlMs =\n cached.ttlMs && cached.ttlMs > 0\n ? Math.max(0, cached.assignedAt + cached.ttlMs - Date.now())\n : 0;\n return { variantId: cached.variantId, assignmentTtlMs: remainingTtlMs, content: cached.content };\n }\n\n // Coalesce concurrent assigns for the same component (e.g. several\n // mounted slots sharing one id) into a single network request.\n return coalesce(inflightAssigns, componentId, async () => {\n // Bounded: see SESSION_WAIT_MS. null = the caller keeps its fallback.\n if (!(await settlesWithin(sessionReady, SESSION_WAIT_MS))) return null;\n // Torn down or forgotten while waiting for the session: never send —\n // a sent assign books an exposure the page will not show (NEW-2).\n if (slotDecideTornDown || !mayPersist()) return null;\n const t = timeoutSignal(DECIDE_TIMEOUT_MS);\n try {\n const body: Record<string, unknown> = { sessionId: sid, componentId, variantIds };\n if (agentDataByVariant !== undefined) body.agentDataByVariant = agentDataByVariant;\n else if (agentData !== undefined) body.agentData = agentData;\n // Sent = booked: /v1/assign records the exposure at draw time, so\n // like decide it is never cut short on latency (DECIDE_TIMEOUT_MS\n // frees a dead connection only; a slow answer is still applied).\n const res = await fetch(`${baseUrl}/assign`, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: authHeaders,\n signal: t.signal,\n });\n if (!res.ok) return null;\n const result = (await res.json()) as AssignResult;\n assignmentCache.set(componentId, sessionSegment, {\n variantId: result.variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n content: result.content,\n // Honor the server's TTL as this entry's expiry; omit when absent/0\n // so the cache falls back to its default (DEFAULT_TTL_MS).\n ...(result.assignmentTtlMs && result.assignmentTtlMs > 0\n ? { ttlMs: result.assignmentTtlMs }\n : {}),\n });\n return result;\n } catch {\n return null;\n } finally {\n t.clear();\n }\n });\n },\n\n async decide(input) {\n const sid = session.getSessionId();\n if (!sid) return null;\n const declared = input.slots ?? [];\n\n const body: Record<string, unknown> = { sessionId: sid };\n if (input.sections && input.sections.length > 0) {\n body.sections = input.sections.map((id) => ({ id }));\n }\n body.components = input.components ?? [];\n if (declared.length > 0) body.slots = declared.map(toWireSlot);\n if (input.slotsFrom === 'registry') {\n body.slotsFrom = 'registry';\n if (input.registrySlotIds) body.registrySlotIds = input.registrySlotIds;\n if (input.bootstrap === false) body.bootstrap = false;\n if (input.render && Object.keys(input.render).length > 0) body.render = input.render;\n }\n if (input.v) body.v = input.v;\n // 0 is meaningful here (a two-tag snippet install with no inline pre-paint\n // script), so this is a presence check, not a truthiness one.\n if (typeof input.pp === 'number') body.pp = input.pp;\n // Declared persona rides on decide too: SSR-first flows can race the\n // session upsert, and the decide-body value wins for this decision.\n if (config.persona) body.persona = config.persona;\n\n // Coalesce concurrent IDENTICAL decides into one request + one snapshot\n // write, keyed by the serialized wire payload (also reused as the fetch\n // body). Never key on just \"a decide is running\": coalescing {slots:[a]}\n // with {slots:[b]} would hand slot b's caller an outcome that never\n // decided b. The wire projection is a safe key even though toWireSlot\n // strips SDK-only decl fields — the baselines synthesized for omitted\n // slots below go through baselineResultFor, which projects with the\n // same toWireSlot, so identical payloads imply identical outcomes.\n const decideKey = JSON.stringify(body);\n return coalesce(inflightDecides, decideKey, async () => {\n // Bounded: a decide never sent writes no trial (SESSION_WAIT_MS).\n if (!(await settlesWithin(sessionReady, SESSION_WAIT_MS)) || slotDecideTornDown || !mayPersist()) {\n // Not sent: the session never came, or the visitor withdrew\n // (dispose/destroy/forget) while we waited — a decide sent now\n // would book trials for a page that will not show them (NEW-2).\n seedSlotBaselines(declared);\n return null;\n }\n // Once sent, the server writes the decision whether or not we read\n // the answer, so this is NOT a latency ceiling (see DECIDE_TIMEOUT_MS):\n // an abort leaves a trial for an arm the page never showed.\n const t = timeoutSignal(DECIDE_TIMEOUT_MS);\n try {\n const res = await fetch(`${baseUrl}/decide`, {\n method: 'POST',\n body: decideKey,\n headers: authHeaders,\n signal: t.signal,\n });\n if (!res.ok) {\n seedSlotBaselines(declared);\n return null;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[] | null;\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n slotConfig?: Record<string, SlotConfigEntry>;\n goals?: GoalDefinition[];\n sectionMap?: SectionMapEntry[];\n palette?: import('./blocks.js').SitePalette;\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n persona?: string;\n confidence?: number;\n stage?: string;\n context?: string;\n };\n // Opt-in theme attribute: what this visit's decide says, overwriting\n // the pre-paint value (last visit's) — absent means \"no stage for\n // this visitor\" (control group, stages off) and removes it.\n const shownStage = exposedStage(data.stage, config.stageAttributes);\n if (config.stageAttributes) setStageAttribute(shownStage);\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declared) {\n // `data.slots === undefined` means the server predates the slots\n // contract: serve the declared baseline everywhere, do NOT retry.\n // (Distinct from `slots: {}`, which also falls back per-slot.)\n const served = data.slots?.[d.id];\n if (served !== undefined) {\n slots[d.id] = served;\n slotStore.set(d.id, served);\n decidedSlotIds.add(d.id);\n continue;\n }\n // Slot omitted from the response → synthesize a baseline for the\n // RETURN value, but apply the same never-overwrite rule the failure\n // path (seedSlotBaselines) has always had. This success path used\n // to write unconditionally, so a partial response — or a pre-slots\n // server — clobbered SSR-seeded and previously-served results with\n // synthetic baselines.\n const prior = slotStore.get(d.id);\n if (prior !== undefined) {\n slots[d.id] = prior;\n } else {\n const baseline = baselineResultFor(d);\n slots[d.id] = baseline;\n slotStore.set(d.id, baseline);\n }\n }\n // Registry mode: the server returns slots the request never declared.\n // Take them verbatim (classic mode returns only declared slots, so this\n // union is a no-op there — back-compatible). These are real served\n // results, so they may overwrite the store, unlike the baselines above.\n if (data.slots) {\n for (const [slotId, result] of Object.entries(data.slots)) {\n if (!(slotId in slots)) {\n slots[slotId] = result;\n slotStore.set(slotId, result);\n decidedSlotIds.add(slotId);\n }\n }\n }\n // Only overwrite persona when the response actually carries one, and\n // never downgrade a known persona to 'unknown' — a decide that omits\n // persona (or returns 'unknown') must not clobber a good SSR/snapshot/\n // initialPersona value, and must not persist that regression below.\n const known = personaState != null && personaState.persona !== 'unknown';\n if (data.persona && !(data.persona === 'unknown' && known)) {\n personaState = { persona: data.persona, confidence: data.confidence ?? 0 };\n } else if (!personaState) {\n personaState = { persona: 'unknown', confidence: 0 };\n }\n\n // Seed component assignments so <Adaptive>/assign() agree with this\n // decide (same shape as the initialAssignments seed above).\n for (const [componentId, variantId] of Object.entries(data.assignments ?? {})) {\n assignmentCache.set(componentId, sessionSegment, {\n variantId,\n assignedAt: Date.now(),\n segment: sessionSegment,\n confidence: 1,\n });\n }\n\n // Registry slot config accumulates like slotStore does: a later\n // decide that omits slotConfig (classic mode, partial response) must\n // not evict entries an earlier registry decide served.\n if (data.slotConfig) {\n for (const [slotId, entry] of Object.entries(data.slotConfig)) {\n slotConfigStore.set(slotId, entry);\n }\n }\n if (data.palette) sitePalette = data.palette;\n // Served wins; an absent one leaves the cached copy (same rule as palette).\n if (data.vocabulary) styleVocabulary = data.vocabulary;\n // A scoped registry decide is authoritative for the ids it asked\n // about: one with no config has nothing published NOW. Drop what an\n // earlier visit's snapshot seeded — before the snapshot is rewritten\n // below — or an unpublished/archived slot keeps rendering its old\n // version from localStorage on every visit.\n for (const id of input.registrySlotIds ?? []) {\n if (data.slotConfig?.[id]) continue;\n slotConfigStore.delete(id);\n slotStore.delete(id);\n decidedSlotIds.delete(id);\n }\n\n // Persist for the next visit's pre-paint (SPA cache-first pattern).\n // A decide that landed after forget-me must not write the visitor back\n // (grader NEW-3: destroy() ran while it was in flight).\n if (mayPersist()) writeSnapshot(config.apiKey, {\n v: 1,\n persona: personaState.persona,\n band: confidenceBand(personaState.confidence),\n slots: Object.fromEntries(slotStore),\n layoutOrder: data.layoutOrder ?? null,\n savedAt: Date.now(),\n ...(slotConfigStore.size > 0 ? { slotConfig: Object.fromEntries(slotConfigStore) } : {}),\n ...(sitePalette ? { palette: sitePalette } : {}),\n ...(styleVocabulary ? { vocabulary: styleVocabulary } : {}),\n // Only the EXPOSED value, and only when opted in: localStorage is\n // readable by every script on the page, so the raw stage (and the\n // context) never go there.\n ...(shownStage ? { stage: shownStage } : {}),\n });\n\n return {\n layoutOrder: data.layoutOrder ?? null,\n assignments: data.assignments ?? {},\n slots,\n persona: personaState.persona,\n confidence: personaState.confidence,\n ...(data.slotConfig ? { slotConfig: data.slotConfig } : {}),\n ...(data.goals ? { goals: data.goals } : {}),\n ...(data.sectionMap ? { sectionMap: data.sectionMap } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n ...(data.vocabulary ? { vocabulary: data.vocabulary } : {}),\n ...(data.stage ? { stage: data.stage } : {}),\n ...(data.context ? { context: data.context } : {}),\n };\n } catch {\n seedSlotBaselines(declared);\n return null;\n } finally {\n t.clear();\n }\n });\n },\n\n getSlotResult(slotId) {\n return slotStore.get(slotId) ?? null;\n },\n\n isSlotDecided(slotId) {\n return decidedSlotIds.has(slotId);\n },\n\n getSlotConfig(slotId) {\n return slotConfigStore.get(slotId) ?? null;\n },\n\n reportSlots(slotIds, baselineTexts, baselineSkeletons, authoredArms) {\n // Authored arms go straight out, deduped per (slot, key): unlike the\n // first-seen id registration below, a hybrid's arms are seen one at a\n // time as the visitor is served them.\n const authored: Record<string, AuthoredArmReport[]> = {};\n for (const [id, list] of Object.entries(authoredArms ?? {})) {\n for (const a of list) {\n const k = `${id}|${a.key}`;\n if (!SLOT_ID_RE.test(id) || reportedAuthored.has(k)) continue;\n reportedAuthored.add(k);\n // Sent as given: the server normalizes and caps the text (the same\n // rule as baselineText), so the lean bundle doesn't carry it twice.\n (authored[id] ??= []).push(a);\n }\n }\n if (Object.keys(authored).length > 0) {\n void fetch(`${baseUrl}/slots/observed`, {\n method: 'POST',\n headers: authHeaders,\n body: JSON.stringify({ slotIds: Object.keys(authored), authoredArms: authored }),\n }).catch(() => undefined);\n }\n // Batch a tick's worth of AdaptiveSlot mounts into one request, once per\n // id per client lifetime — a page of N slots must not fire N registrations\n // on every navigation.\n for (const id of slotIds) {\n if (typeof id !== 'string' || id.length === 0) continue;\n if (!SLOT_ID_RE.test(id)) {\n // Warn once per id, dev builds only — the fetch error the server\n // batch rejection produced was swallowed, so an invalid id was\n // completely silent AND poisoned its whole batch.\n if (isDevBuild() && !warnedInvalidSlotIds.has(id)) {\n warnedInvalidSlotIds.add(id);\n console.warn(\n `[sentient] reportSlots: slot id ${JSON.stringify(id)} will not register — ids must start ` +\n `with a letter or digit and contain only letters, digits, '_' or '-' (max 128 chars): ` +\n `/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.`,\n );\n }\n continue;\n }\n if (!reportedSlotIds.has(id)) {\n reportedSlotIds.add(id);\n pendingSlotReports.add(id);\n // Normalize before it leaves the page: whitespace collapsed, hard\n // 400-char cap. Only the region the developer explicitly wrapped\n // for replacement is read — never the page around it.\n const raw = baselineTexts?.[id];\n if (typeof raw === 'string') {\n const text = raw.replace(/\\s+/g, ' ').trim().slice(0, 400);\n if (text !== '') pendingBaselineTexts.set(id, text);\n }\n const sk = baselineSkeletons?.[id];\n if (sk !== undefined) pendingBaselineSkeletons.set(id, sk);\n }\n }\n if (pendingSlotReports.size === 0 || slotReportTimer != null) return;\n slotReportTimer = setTimeout(() => {\n slotReportTimer = null;\n const all = [...pendingSlotReports];\n pendingSlotReports.clear();\n // Chunks of 20 — the server's MAX_BATCH. This used to slice(0, 20) and\n // clear(), so ids 21+ were dropped permanently: already marked as\n // reported, never sent, never retried. Sequential fire-and-forget keeps\n // the send path as cheap as the single-batch one.\n for (let i = 0; i < all.length; i += 20) {\n const chunk = all.slice(i, i + 20);\n const texts: Record<string, string> = {};\n const skels: Record<string, SkeletonReport> = {};\n for (const id of chunk) {\n const t = pendingBaselineTexts.get(id);\n if (t !== undefined) {\n texts[id] = t;\n pendingBaselineTexts.delete(id);\n }\n const sk = pendingBaselineSkeletons.get(id);\n if (sk !== undefined) {\n skels[id] = sk;\n pendingBaselineSkeletons.delete(id);\n }\n }\n void fetch(`${baseUrl}/slots/observed`, {\n method: 'POST',\n headers: authHeaders,\n body: JSON.stringify({\n slotIds: chunk,\n ...(Object.keys(texts).length > 0 ? { baselineTexts: texts } : {}),\n ...(Object.keys(skels).length > 0 ? { baselineSkeletons: skels } : {}),\n // Where these regions live: a Redesign brief reads that page's text.\n pagePaths: Object.fromEntries(chunk.map((id) => [id, location.pathname])),\n // A baseline-text vote counts only once this session is scored\n // human with events (server C8); without it the vote never\n // promotes, so the text would wait for owner confirmation.\n ...(Object.keys(texts).length > 0 && session.getSessionId() ? { sessionId: session.getSessionId() } : {}),\n }),\n }).catch(() => undefined);\n }\n }, 1000);\n },\n\n reportSkeleton(slotId, skeleton) {\n if (!SLOT_ID_RE.test(slotId) || reportedSkeletonIds.has(slotId)) return;\n reportedSkeletonIds.add(slotId);\n // Same endpoint as first registration: the slot exists, so the insert is\n // a no-op and the server's fill-once UPDATE stores the skeleton.\n void fetch(`${baseUrl}/slots/observed`, {\n method: 'POST',\n headers: authHeaders,\n body: JSON.stringify({ slotIds: [slotId], baselineSkeletons: { [slotId]: skeleton } }),\n }).catch(() => undefined);\n },\n\n reportDrift(slotId, expectedFp, observedFp, reason) {\n // Once per (slot, fingerprint) per client — that dedupe bounds volume,\n // so no batching timer. The server applies the visitors-and-rate rule.\n const key = `${slotId}|${expectedFp}`;\n const sid = session.getSessionId();\n if (!sid || reportedDrift.has(key)) return;\n reportedDrift.add(key);\n void fetch(`${baseUrl}/slots/drift`, {\n method: 'POST',\n headers: authHeaders,\n body: JSON.stringify({ sessionId: sid, reports: [{ slotId, expectedFp, observedFp, reason }] }),\n }).catch(() => undefined);\n },\n\n requestSlots(slotIds, baselineTexts, extras) {\n for (const id of slotIds) {\n if (requestedSlotIds.has(id)) continue;\n requestedSlotIds.add(id);\n // An invalid id would 400 the whole scoped decide; reportSlots owns\n // the dev warning for it and refuses it there.\n if (SLOT_ID_RE.test(id)) {\n pendingSlotTexts.set(id, {\n text: baselineTexts?.[id],\n render: extras?.render?.[id],\n skeleton: extras?.skeletons?.[id],\n });\n } else client.reportSlots([id]);\n }\n if (pendingSlotTexts.size === 0 || slotRequestTimer != null) return;\n // 0ms: every AdaptiveSlot mounted in the same commit lands in one request.\n slotRequestTimer = setTimeout(() => {\n slotRequestTimer = null;\n const all = [...pendingSlotTexts];\n pendingSlotTexts.clear();\n for (let i = 0; i < all.length; i += 50) {\n const chunk = all.slice(i, i + 50);\n const render: Record<string, RenderCaps> = {};\n for (const [id, p] of chunk) if (p.render) render[id] = p.render;\n void client\n .decide({ slotsFrom: 'registry', registrySlotIds: chunk.map(([id]) => id), bootstrap: false, render })\n .then((out) => {\n // A failed decide registers nothing: \"the network blipped\" must not\n // read as \"this slot has nothing published\".\n if (out) {\n const texts: Record<string, string> = {};\n const skels: Record<string, SkeletonReport> = {};\n const missing: string[] = [];\n for (const [id, p] of chunk) {\n const cfg = out.slotConfig?.[id];\n if (cfg) {\n // Published but never captured: fill it from this page.\n if (cfg.needsSkeleton && p.skeleton) client.reportSkeleton?.(id, p.skeleton);\n continue;\n }\n missing.push(id);\n if (p.text) texts[id] = p.text;\n if (p.skeleton) skels[id] = p.skeleton;\n }\n if (missing.length > 0) client.reportSlots(missing, texts, skels);\n } else {\n // Release the ids (a remount re-asks) and retry this batch with\n // backoff — see retryFailedSlots.\n retryFailedSlots(chunk.map(([id]) => id), requestedSlotIds, (retry) => {\n const texts: Record<string, string> = {};\n const retryRender: Record<string, RenderCaps> = {};\n const skels: Record<string, SkeletonReport> = {};\n for (const [id, p] of chunk) {\n if (!retry.has(id)) continue;\n if (p.text) texts[id] = p.text;\n if (p.render) retryRender[id] = p.render;\n if (p.skeleton) skels[id] = p.skeleton;\n }\n client.requestSlots?.([...retry], texts, { render: retryRender, skeletons: skels });\n });\n }\n slotListeners.forEach((l) => l());\n });\n }\n }, 0);\n },\n\n decideSlots(decls) {\n for (const d of decls) {\n if (decidedDeclIds.has(d.id)) continue;\n decidedDeclIds.add(d.id);\n pendingDecls.set(d.id, d);\n }\n if (pendingDecls.size === 0 || declTimer != null) return;\n declTimer = setTimeout(() => {\n declTimer = null;\n const all = [...pendingDecls.values()];\n pendingDecls.clear();\n // 30 per request: the server's decide `slots` cap.\n for (let i = 0; i < all.length; i += 30) {\n const batch = all.slice(i, i + 30);\n void client.decide({ slots: batch }).then((out) => {\n // The failure path already seeded every declared slot's baseline\n // into slotStore (unexposed — isSlotDecided stays false); release\n // the ids and retry with backoff so the slot gets a real decision.\n if (!out) {\n retryFailedSlots(batch.map((d) => d.id), decidedDeclIds, (retry) =>\n client.decideSlots?.(batch.filter((d) => retry.has(d.id))));\n }\n slotListeners.forEach((l) => l());\n });\n }\n }, 0);\n },\n\n cancelSlots(slotIds) {\n for (const id of slotIds) {\n // Only a still-pending ask is withdrawn; once sent, the id stays\n // marked so the in-flight answer is not duplicated by a remount.\n if (pendingSlotTexts.delete(id)) requestedSlotIds.delete(id);\n if (pendingDecls.delete(id)) decidedDeclIds.delete(id);\n }\n },\n\n onSlotsChanged(listener) {\n slotListeners.add(listener);\n return () => void slotListeners.delete(listener);\n },\n\n getStyleVocabulary() {\n return styleVocabulary;\n },\n\n getSitePalette() {\n return sitePalette;\n },\n\n getPersona() {\n if (!personaState) return null;\n return {\n persona: personaState.persona,\n confidence: personaState.confidence,\n band: confidenceBand(personaState.confidence),\n };\n },\n\n async fetchWeights() {\n const t = timeoutSignal(REQUEST_TIMEOUT_MS);\n try {\n const res = await fetch(`${baseUrl}/weights`, { headers: authHeaders, signal: t.signal });\n if (!res.ok) return [];\n const data = (await res.json()) as { components: ComponentWeightEntry[] };\n return data.components ?? [];\n } catch {\n return [];\n } finally {\n t.clear();\n }\n },\n\n getGraph() {\n return { pageNodes: [], capturedAt: 0 };\n },\n\n flush() {\n // Both queues: a goal banked late in a lifecycle handler races the same\n // unload pipeline the event queue does.\n eventQueue.flush();\n goalQueue.flush();\n },\n\n dispose() {\n // Stops the flush timer and unload listeners (with a final flush) but\n // leaves identity, snapshot, and retry buckets for the next client.\n stopPageviews?.();\n pageviewsTornDown = true;\n slotDecideTornDown = true;\n eventQueue.destroy();\n goalQueue.destroy();\n // Drop the registry entry so a later re-init doesn't try to dispose an\n // already-torn-down client (and so the map doesn't pin this closure).\n if (_clients.get(config.apiKey)?.dispose === client.dispose) {\n _clients.delete(config.apiKey);\n }\n if (config.debug) {\n console.log('[sentient] disposed');\n }\n },\n\n destroy() {\n stopPageviews?.();\n pageviewsTornDown = true;\n slotDecideTornDown = true;\n // Before anything else: in-flight decides/assigns check these.\n forgottenHere = true;\n markForgotten(config.apiKey);\n eventQueue.destroy({ forget: true });\n goalQueue.destroy({ forget: true });\n session.destroy();\n // The assignment cache persists in localStorage (`_snt_asgn_*`) with a\n // 30-minute default TTL — left in place, a revoked visitor returning\n // within that window was handed their previous personalized variants\n // back, so forget-me wasn't total.\n assignmentCache.clear();\n if (_clients.get(config.apiKey)?.dispose === client.dispose) {\n _clients.delete(config.apiKey);\n }\n // Forget-me must be total: a surviving decision snapshot would\n // re-personalize the next visit via the pre-paint script, and a\n // persisted retry bucket would re-send events for the deleted identity.\n try {\n localStorage.removeItem(SNAPSHOT_STORAGE_KEY_PREFIX + config.apiKey);\n localStorage.removeItem(retryStorageKey(config.apiKey));\n localStorage.removeItem(goalRetryStorageKey(config.apiKey));\n // The graph caches too (the graph entry also clears them): forget-me\n // on a lean client left them (review #9).\n localStorage.removeItem(`_snt_graph_nodes${storageSuffix(config.apiKey)}`);\n localStorage.removeItem('_snt_graph_edges');\n } catch {\n /* storage unavailable — nothing persisted to remove */\n }\n if (config.debug) {\n console.log('[sentient] destroyed');\n }\n },\n };\n\n _clients.set(config.apiKey, { config, upgrade: null, dispose: client.dispose });\n\n stopPageviews = startPageviewTracking(client, config.apiKey, (key) => {\n // track() defers its enqueue on sessionReady; chaining after it means this\n // runs once the push has happened. If the client was torn down first, the\n // event went into a destroyed queue and never ships — leave the page\n // unmarked so the replacement client's emit is the one that counts.\n void sessionReady.then(() => {\n if (!pageviewsTornDown) emittedPages.add(key);\n });\n });\n\n if (config.debug) {\n const win = window as unknown as { __sentient?: { client: SentientClient } };\n if (win.__sentient) {\n win.__sentient.client = client;\n }\n }\n\n return client;\n}\n","export type MicroSignalEmitter = (\n signalType: 'rage_click' | 'text_copy' | 'scroll_hesitation' | 'tab_loss',\n extra?: Record<string, unknown>,\n) => void;\n\nexport type MicroSignalType = Parameters<MicroSignalEmitter>[0];\n\n/**\n * Attaches passive behavioral detectors to `node`. Calls `emit` when a signal\n * fires. Each signal type fires at most once per call to this function.\n * Returns a cleanup function that removes all listeners.\n */\nexport function attachMicroSignalDetectors(\n emit: MicroSignalEmitter,\n node: Element,\n variantAssignedAt?: number,\n options?: { tabLoss?: boolean },\n): () => void {\n const cleanups: Array<() => void> = [];\n\n // --- Rage click: 3+ clicks within 500ms ---\n {\n const WINDOW_MS = 500;\n const THRESHOLD = 3;\n let firedOnce = false;\n const timestamps: number[] = [];\n\n const onClick = (): void => {\n if (firedOnce) return;\n const now = Date.now();\n timestamps.push(now);\n while (timestamps.length > 0 && now - timestamps[0]! > WINDOW_MS) {\n timestamps.shift();\n }\n if (timestamps.length >= THRESHOLD) {\n firedOnce = true;\n emit('rage_click');\n }\n };\n\n node.addEventListener('click', onClick);\n cleanups.push(() => node.removeEventListener('click', onClick));\n }\n\n // --- Text copy: copy event within node ---\n {\n let firedOnce = false;\n\n const onCopy = (e: Event): void => {\n if (firedOnce) return;\n if (!(e.target instanceof Node)) return;\n if (!node.contains(e.target) && node !== e.target) return;\n firedOnce = true;\n const sel = typeof window !== 'undefined' ? window.getSelection() : null;\n const selectionLength = sel ? sel.toString().length : 0;\n emit('text_copy', { selectionLength });\n };\n\n document.addEventListener('copy', onCopy);\n cleanups.push(() => document.removeEventListener('copy', onCopy));\n }\n\n // --- Scroll hesitation: scroll stops 3s while component visible ---\n {\n let firedOnce = false;\n let isVisible = false;\n let hesitationTimer: ReturnType<typeof setTimeout> | null = null;\n\n const clearHesitation = (): void => {\n if (hesitationTimer !== null) {\n clearTimeout(hesitationTimer);\n hesitationTimer = null;\n }\n };\n\n const startHesitation = (): void => {\n if (firedOnce || !isVisible) return;\n clearHesitation();\n hesitationTimer = setTimeout(() => {\n if (!firedOnce && isVisible) {\n firedOnce = true;\n emit('scroll_hesitation');\n }\n }, 3000);\n };\n\n const onScroll = (): void => {\n clearHesitation();\n startHesitation();\n };\n\n const ioCallback = (entries: IntersectionObserverEntry[]): void => {\n for (const entry of entries) {\n isVisible = entry.intersectionRatio > 0.3;\n if (!isVisible) clearHesitation();\n else startHesitation();\n }\n };\n const io = new IntersectionObserver(ioCallback, { threshold: [0.3] });\n io.observe(node);\n window.addEventListener('scroll', onScroll, { passive: true });\n\n cleanups.push(() => {\n io.disconnect();\n window.removeEventListener('scroll', onScroll);\n clearHesitation();\n });\n }\n\n // --- Tab loss: tab hidden within 15s of variant_assigned ---\n // Document-level (not node-scoped), so callers that attach detectors to many\n // nodes at once (e.g. the snippet's per-option slot signals) can opt out on all\n // but one node to avoid emitting a duplicate tab_loss per node (audit M5).\n if (options?.tabLoss !== false) {\n let firedOnce = false;\n const assignedAt = variantAssignedAt ?? Date.now();\n\n const onVisibility = (): void => {\n if (firedOnce) return;\n if (document.visibilityState !== 'hidden') return;\n const elapsed = Date.now() - assignedAt;\n if (elapsed < 15_000) {\n firedOnce = true;\n emit('tab_loss', { timeOnPage: elapsed });\n }\n };\n\n document.addEventListener('visibilitychange', onVisibility);\n cleanups.push(() => document.removeEventListener('visibilitychange', onVisibility));\n }\n\n return () => {\n for (const c of cleanups) c();\n };\n}\n","import type { CompoundLocator } from './snapshot.js';\n\n// Live-DOM twin of apps/api/src/domain/locator-from-html.ts. The two MUST stay\n// in step: section_key is a hash of this object, so any divergence silently\n// splits one physical section into two identities — a crawl-derived one and a\n// client-derived one — and every per-section number downstream halves.\n// Cross-implementation parity is locked by apps/api/src/domain/locator-parity.test.ts.\n// data-sentient-id FIRST (added 2026-09-05, both generators together): it is\n// the one attribute a site authors specifically to name a section for us, and\n// it is exactly what hydration and redesigns do NOT rewrite. Elements with a\n// unique `id` are unaffected (id outranks data attrs); for the rest the change\n// moves section_key once — ingest-time fingerprint reconciliation\n// (section-key-reconcile.ts) writes the alias, and no offline backfill is\n// possible because pre-change locators never captured the attribute.\nconst STABLE_DATA_ATTRS = ['data-sentient-id', 'data-testid', 'data-test', 'data-id', 'data-name', 'data-cy'];\nconst FINGERPRINT_TEXT_MAX = 40;\n\nfunction normalizedText(el: Element): string {\n return (el.textContent ?? '').replace(/\\s+/g, ' ').trim();\n}\n\nfunction fingerprintOf(el: Element): { tag: string; text: string } {\n return {\n tag: el.tagName.toLowerCase(),\n text: normalizedText(el).slice(0, FINGERPRINT_TEXT_MAX),\n };\n}\n\nfunction cssEscape(v: string): string {\n return v.replace(/[\"\\\\\\]]/g, '\\\\$&');\n}\n\nfunction unique(root: ParentNode, selector: string): boolean {\n try {\n return root.querySelectorAll(selector).length === 1;\n } catch {\n return false;\n }\n}\n\n/** Shortest unique selector: tag, tag.class, then parent-qualified, then nth-of-type chain. */\nfunction uniqueSelector(el: Element, root: ParentNode): string | null {\n const tag = el.tagName.toLowerCase();\n if (!tag) return null;\n const classes = (el.getAttribute('class') ?? '').split(/\\s+/).filter((c) => /^[a-zA-Z][\\w-]*$/.test(c));\n const candidates = [tag, ...classes.map((c) => `${tag}.${c}`)];\n for (const c of candidates) if (unique(root, c)) return c;\n const parent = el.parentElement;\n if (parent && (parent as ParentNode) !== root) {\n const parentSel = uniqueSelector(parent, root);\n if (parentSel) {\n for (const c of candidates) {\n const combined = `${parentSel} > ${c}`;\n if (unique(root, combined)) return combined;\n }\n // Element-only children: matches the server's rawTagName filter over\n // childNodes, which excludes text nodes.\n const siblings = Array.from(parent.children).filter((n) => n.tagName.toLowerCase() === tag);\n const idx = siblings.indexOf(el);\n // An nth-of-type selector is only trustworthy when it pairs with a\n // fingerprint that could actually catch drift: if every same-tag sibling\n // has identical text, the node is a true duplicate and the {tag, text}\n // check can never distinguish \"still the right one\" from \"DOM reordered,\n // now pointing at the wrong duplicate\". Refuse it rather than return a\n // false sense of precision.\n const distinguishable = siblings.some((s) => s !== el && normalizedText(s) !== normalizedText(el));\n if (idx >= 0 && distinguishable) {\n const nth = `${parentSel} > ${tag}:nth-of-type(${idx + 1})`;\n if (unique(root, nth)) return nth;\n }\n }\n }\n return null;\n}\n\n/** Build a compound locator for a live DOM element. Returns null when nothing\n * resolves uniquely — the runtime never guesses an identity. */\nexport function locatorFromElement(el: Element, root: ParentNode): CompoundLocator | null {\n const fingerprint = fingerprintOf(el);\n const id = el.getAttribute('id');\n if (id && unique(root, `#${cssEscape(id)}`)) return { v: 1, id, fingerprint };\n for (const name of STABLE_DATA_ATTRS) {\n const value = el.getAttribute(name);\n if (value && unique(root, `[${name}=\"${cssEscape(value)}\"]`)) {\n return { v: 1, dataAttr: { name, value }, fingerprint };\n }\n }\n const selector = uniqueSelector(el, root);\n if (selector) return { v: 1, selector, fingerprint };\n return null;\n}\n","//\n// Session-scoped interaction AGGREGATES for the browser-agent axis (spec\n// 2026-09-22-agent-axis-human-verified-numbers-design.md §4.1). Counts, means\n// and variances only: no per-event timestamps, no coordinates, no text. A\n// raw trace is arguably a biometric; these statistics are not, and the whole\n// privacy posture of the feature rests on that line staying where it is.\n//\n// The collector knows nothing about the network. It exposes a snapshot; the\n// engagement capture decides when to emit it, under its own DNT/consent gate.\n\nexport type InteractionStats = {\n v: 1;\n active_ms: number;\n mm: number;\n /** Mousemoves per VISIBLE second, 2 dp. The count alone does not separate:\n * a driver dispatches one mousemove per click, so `mm === 0` is false for\n * the commonest automation stack (measured: Playwright emits 3 over a\n * 6-action script). The rate does — humans emit tens per second, drivers\n * around one. Carried alongside `mm` so a future threshold can use either. */\n mm_rate: number;\n touches: number;\n clicks: number;\n /** How many mousedown→mouseup pairs `hold_mean`/`hold_std` rest on. Without\n * it a zero-variance hold (a driver pressing and releasing in one tick) is\n * indistinguishable from never having measured one at all, and the scorer\n * would condemn the second case on the evidence of the first. */\n hold_n: number;\n hold_mean: number;\n hold_std: number;\n teleport: number;\n wheel: number;\n scroll_px: number;\n keydowns: number;\n input_chars: number;\n ik_cv: number;\n backspaces: number;\n gaps: [number, number, number, number, number, number];\n reduced_motion: boolean;\n kb_nav: number;\n renderer: 'sw' | 'hw' | 'unknown';\n vp: [number, number];\n dpr: number;\n};\n\nexport type InteractionCollector = { snapshot(): InteractionStats; stop(): void };\n\n/** Log-spaced action-gap edges (ms). Six buckets: <100, <300, <1000, <3000,\n * <10000, >=10000. LLM agents pile into the two ends (instant bursts after\n * model latency); humans sit in the middle. */\nexport const GAP_EDGES_MS: readonly number[] = [100, 300, 1000, 3000, 10000];\n\nconst TELEPORT_WINDOW_MS = 250;\nconst TOUCH_RECENT_MS = 1000;\nconst NAV_KEYS = new Set(['Tab', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']);\n\n/** Welford running mean/variance — one object per measured quantity, so the\n * std of click hold and the CV of inter-key intervals cost 3 numbers each. */\ntype Welford = { n: number; mean: number; m2: number };\nfunction push(w: Welford, x: number): void {\n w.n++;\n const d = x - w.mean;\n w.mean += d / w.n;\n w.m2 += d * (x - w.mean);\n}\nconst std = (w: Welford): number => (w.n > 1 ? Math.sqrt(w.m2 / w.n) : 0);\n\nfunction rendererClass(doc: Document): InteractionStats['renderer'] {\n try {\n const canvas = doc.createElement('canvas');\n const gl = (canvas.getContext('webgl') || canvas.getContext('experimental-webgl')) as\n | (WebGLRenderingContext & { getExtension(name: string): { UNMASKED_RENDERER_WEBGL: number } | null })\n | null;\n if (!gl) return 'unknown';\n const ext = gl.getExtension('WEBGL_debug_renderer_info');\n const name = ext ? String(gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) ?? '') : '';\n if (!name) return 'unknown';\n // Software rasterisers are what headless Chromium ships without a GPU.\n // Corroboration only — stealth tooling patches this string first — so the\n // scorer weights it low (spec §4.2).\n return /swiftshader|llvmpipe|softpipe|software|mesa offscreen/i.test(name) ? 'sw' : 'hw';\n } catch {\n return 'unknown';\n }\n}\n\nexport function startInteractionCollector(doc: Document, now: () => number = Date.now): InteractionCollector {\n const win = doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined);\n const hold: Welford = { n: 0, mean: 0, m2: 0 };\n const interkey: Welford = { n: 0, mean: 0, m2: 0 };\n const gaps: InteractionStats['gaps'] = [0, 0, 0, 0, 0, 0];\n let mm = 0, touches = 0, clicks = 0, teleport = 0, wheel = 0, scrollPx = 0;\n let keydowns = 0, inputChars = 0, backspaces = 0, kbNav = 0;\n let lastMoveAt = -Infinity, lastTouchAt = -Infinity, downAt: number | null = null;\n let lastKeyAt: number | null = null, lastActionAt: number | null = null;\n let lastScrollY = win?.scrollY ?? 0;\n // Visible wall-clock: banked on hide, resumed on show. A hidden tab must not\n // accrue \"activity\", or a background tab left open all day reads as a\n // deeply engaged visitor with no mouse — the assistive-technology signature.\n let banked = 0;\n let visibleSince: number | null = doc.hidden ? null : now();\n\n const action = (): void => {\n const t = now();\n if (lastActionAt != null) {\n const g = t - lastActionAt;\n let i = 0;\n while (i < GAP_EDGES_MS.length && g >= GAP_EDGES_MS[i]!) i++;\n gaps[i as 0 | 1 | 2 | 3 | 4 | 5]++;\n }\n lastActionAt = t;\n };\n\n const onMove = (): void => { mm++; lastMoveAt = now(); };\n const onTouch = (): void => { touches++; lastTouchAt = now(); };\n const onDown = (): void => { downAt = now(); };\n const onUp = (): void => { if (downAt != null) { push(hold, now() - downAt); downAt = null; } };\n const onClick = (): void => {\n const t = now();\n clicks++;\n // A click with no pointer travel before it was placed at computed\n // coordinates — unless it was a tap, which never moves a mouse.\n if (t - lastMoveAt > TELEPORT_WINDOW_MS && t - lastTouchAt > TOUCH_RECENT_MS) teleport++;\n action();\n };\n const onWheel = (): void => { wheel++; };\n const onScroll = (): void => {\n const y = win?.scrollY ?? 0;\n scrollPx += Math.abs(y - lastScrollY);\n lastScrollY = y;\n // A scroll IS an action for gap purposes. Without this a session that\n // reads by scrolling contributes almost nothing to the gap histogram —\n // measured 3 gaps across a six-action script, far below what any shape\n // test can read.\n action();\n };\n const onKey = (e: KeyboardEvent): void => {\n const t = now();\n keydowns++;\n if (e.key === 'Backspace' || e.key === 'Delete') backspaces++;\n if (NAV_KEYS.has(e.key)) kbNav++;\n if (lastKeyAt != null) push(interkey, t - lastKeyAt);\n lastKeyAt = t;\n action();\n };\n const onInput = (e: Event): void => {\n const data = (e as InputEvent).data;\n if (typeof data === 'string') inputChars += data.length;\n action();\n };\n const onVisibility = (): void => {\n const t = now();\n if (doc.hidden) { if (visibleSince != null) { banked += t - visibleSince; visibleSince = null; } }\n else if (visibleSince == null) visibleSince = t;\n };\n\n const opts: AddEventListenerOptions = { passive: true, capture: true };\n doc.addEventListener('mousemove', onMove, opts);\n doc.addEventListener('touchstart', onTouch, opts);\n doc.addEventListener('touchmove', onWheel, opts);\n doc.addEventListener('mousedown', onDown, opts);\n doc.addEventListener('mouseup', onUp, opts);\n doc.addEventListener('click', onClick, opts);\n doc.addEventListener('wheel', onWheel, opts);\n doc.addEventListener('keydown', onKey as EventListener, opts);\n doc.addEventListener('input', onInput, opts);\n doc.addEventListener('visibilitychange', onVisibility);\n win?.addEventListener('scroll', onScroll, opts);\n\n const renderer = rendererClass(doc);\n const reducedMotion = ((): boolean => {\n try { return win?.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true; } catch { return false; }\n })();\n\n return {\n snapshot(): InteractionStats {\n const t = now();\n const active = banked + (visibleSince != null ? t - visibleSince : 0);\n return {\n v: 1,\n active_ms: Math.round(active),\n mm,\n mm_rate: active > 0 ? Number(((mm * 1000) / active).toFixed(2)) : 0,\n touches, clicks,\n hold_n: hold.n,\n hold_mean: Math.round(hold.mean),\n hold_std: Math.round(std(hold)),\n teleport, wheel,\n scroll_px: Math.round(scrollPx),\n keydowns,\n input_chars: inputChars,\n ik_cv: interkey.mean > 0 ? Number((std(interkey) / interkey.mean).toFixed(2)) : 0,\n backspaces,\n gaps: [...gaps] as InteractionStats['gaps'],\n reduced_motion: reducedMotion,\n kb_nav: kbNav,\n renderer,\n vp: [win?.innerWidth ?? 0, win?.innerHeight ?? 0],\n dpr: win?.devicePixelRatio || 1,\n };\n },\n stop(): void {\n doc.removeEventListener('mousemove', onMove, opts);\n doc.removeEventListener('touchstart', onTouch, opts);\n doc.removeEventListener('touchmove', onWheel, opts);\n doc.removeEventListener('mousedown', onDown, opts);\n doc.removeEventListener('mouseup', onUp, opts);\n doc.removeEventListener('click', onClick, opts);\n doc.removeEventListener('wheel', onWheel, opts);\n doc.removeEventListener('keydown', onKey as EventListener, opts);\n doc.removeEventListener('input', onInput, opts);\n doc.removeEventListener('visibilitychange', onVisibility);\n win?.removeEventListener('scroll', onScroll, opts);\n },\n };\n}\n"],"mappings":"2xBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,iCAAAE,GAAA,mBAAAC,EAAA,qBAAAC,EAAA,oBAAAC,GAAA,wBAAAC,EAAA,2BAAAC,KAAA,eAAAC,GAAAR,ICgCO,IAAMS,EAA0C,CACrD,UAAW,OAAQ,eAAgB,MAAO,WAC1C,MAAO,aAAc,QAAS,aAAc,SAC9C,EA4BMC,GAAqC,CACzC,OAAQ,OACR,WAAY,aACZ,YAAa,QACf,EAQO,SAASC,GAAkBC,EAAmC,CACnE,IAAMC,EAAOD,EAAE,SAAWF,GAAWE,EAAE,SAAS,YAAY,CAAC,EAAI,OACjE,GAAIC,EAAM,OAAOA,EACjB,GAAID,EAAE,MAAQ,MAAO,MAAO,aAC5B,GAAIA,EAAE,MAAQ,SAAU,MAAO,SAgB/B,GAAIA,EAAE,MAAQ,SAAU,OAAOA,EAAE,aAAe,EAAI,aAAe,OACnE,IAAME,EAAM,GAAGF,EAAE,OAAO,IAAIA,EAAE,WAAW,GAAG,YAAY,EACxD,MAAI,kEAAkE,KAAKE,CAAG,EACrE,SAAS,KAAKA,CAAG,EAAI,SAAW,aAMrC,iCAAiC,KAAKF,EAAE,OA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,cAAcS,CAAS,EACvBnB,EAAY,KAAK,EACjBlD,EAAI,oBAAoB,mBAAoB+D,CAAY,EACxDK,GAAA,MAAAA,EAAK,oBAAoB,WAAYH,GACrCG,GAAA,MAAAA,EAAK,oBAAoB,WAAYD,GACrC,QAAW/D,KAAKkE,EAAkBlE,EAAE,EACpC,GAAI,CAAEsD,EAAS,WAAW,CAAG,OAAQ/C,EAAA,CAAe,CACtD,CACF","names":["index_engagement_exports","__export","INTERACTION_STATS_COMPONENT","SEMANTIC_TYPES","classifyFeatures","classifySection","featuresFromElement","startEngagementCapture","__toCommonJS","SEMANTIC_TYPES","ARIA_TOPIC","structuralTopicOf","f","aria","hay","fallbackTopicOf","KEYWORDS","CONTENT_PATTERNS","SHARED_TOPIC_PARENT","headingText","el","_a","h","classifyFeatures","_b","structural","type","re","fb","featuresFromElement","text","role","__spreadValues","classifySection","import_policy","import_policy","attachMicroSignalDetectors","emit","node","variantAssignedAt","options","cleanups","firedOnce","timestamps","onClick","now","onCopy","e","sel","selectionLength","isVisible","hesitationTimer","clearHesitation","startHesitation","onScroll","ioCallback","entries","entry","io","assignedAt","onVisibility","elapsed","c","isDoNotTrackEnabled","v","STABLE_DATA_ATTRS","normalizedText","el","_a","fingerprintOf","cssEscape","v","unique","root","selector","e","uniqueSelector","tag","classes","c","candidates","parent","parentSel","combined","siblings","n","idx","distinguishable","s","nth","locatorFromElement","fingerprint","id","name","STABLE_DATA_ATTRS","value","GAP_EDGES_MS","TELEPORT_WINDOW_MS","TOUCH_RECENT_MS","NAV_KEYS","push","w","x","d","std","rendererClass","doc","_a","canvas","gl","ext","name","e","startInteractionCollector","now","_b","win","hold","interkey","gaps","mm","touches","clicks","teleport","wheel","scrollPx","keydowns","inputChars","backspaces","kbNav","lastMoveAt","lastTouchAt","downAt","lastKeyAt","lastActionAt","lastScrollY","banked","visibleSince","action","t","g","i","onMove","onTouch","onDown","onUp","onClick","onWheel","onScroll","y","onKey","onInput","data","onVisibility","opts","renderer","reducedMotion","active","SECTION_SELECTOR","HEARTBEAT_MS","INTERACTION_STATS_COMPONENT","selectSections","doc","candidates","kept","el","c","k","registerSections","apiKey","apiBase","pageUrl","sections","e","NOOP","startEngagementCapture","client","opts","_a","_b","_c","_d","_e","_f","_g","_h","_i","_j","_k","_l","_m","_n","_o","isDoNotTrackEnabled","els","componentOf","entries","markup","t","SEMANTIC_TYPES","f","featuresFromElement","type","classifyFeatures","locator","locatorFromElement","componentId","patternFlags","CONTENT_PATTERNS","re","__spreadProps","__spreadValues","interaction","startInteractionCollector","emitInteraction","snap","state","get","id","s","observer","entry","emit","leaving","now","onVisibility","frozen","onPageHide","event","onPageShow","win","heartbeat","detectorCleanups","i","attachMicroSignalDetectors","signalType","extra"]}