@sentientui/react 0.44.1 → 0.44.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/testing/react.tsx","../../src/provider.tsx","../../src/weights-store.ts","../../src/preview-mode.ts","../../src/override-events.ts","../../src/devtools-config.ts","../../src/adaptive-shared.ts","../../src/devtools-registry.ts","../../src/sdk-version.ts","../../src/devtools-slot-config-overrides.ts","../../src/devtools-slot-overrides.ts","../../src/hash-param.ts","../../src/editor-session.ts","../../src/cell-preview.ts","../../src/style-capture.ts","../../src/testing/scenario.ts"],"sourcesContent":["// RTL-dependent helper behind its own subpath (`@sentientui/react/testing/react`):\n// @testing-library/react is an OPTIONAL peer, so importing it at the top of the\n// main /testing entry crashed any consumer without it installed the moment they\n// imported ANY testing helper — same split as /testing/node (msw/node) and\n// /testing/msw (msw).\nimport type { ReactElement } from 'react';\nimport { render, type RenderOptions, type RenderResult } from '@testing-library/react';\nimport { AdaptiveProvider } from '../provider.js';\nimport { applyScenario, type SentientScenario } from './scenario.js';\n\n/**\n * Render `ui` under a SentientUI provider configured for tests: consent is off,\n * so the SDK never initialises a client and every <Adaptive> renders its control\n * variant with zero network. A scenario forces specific variants/layout.\n */\nexport function renderWithSentient(\n ui: ReactElement,\n scenario: SentientScenario = {},\n options?: RenderOptions,\n): RenderResult {\n applyScenario(scenario);\n return render(\n <AdaptiveProvider apiKey=\"pk_test\" consent={false}>\n {ui}\n </AdaptiveProvider>,\n options,\n );\n}\n","'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type JSX,\n type ReactNode,\n} from 'react';\nimport {\n deriveSessionSegment,\n init,\n type ConsentSource,\n type SentientClient,\n type SentientConfig,\n type SitePalette,\n type SlotConfigEntry,\n type StyleVocabulary,\n type StageAttributes,\n type SlotResult,\n} from '@sentientui/core';\nimport type { SemanticType } from '@sentientui/core/engagement';\nimport { update as updateWeightsStore, type ComponentWeights } from './weights-store.js';\nimport { getPreviewMode, subscribePreview, createPreviewClient, setPreviewMode } from './preview-mode.js';\nimport { subscribeOverridesChanged } from './override-events.js';\nimport { publishDevtoolsConfig } from './devtools-config.js';\nimport { registerSections } from './devtools-registry.js';\nimport { isDevBuild } from './adaptive-shared.js';\nimport { SDK_IDENT } from './sdk-version.js';\nimport { maybeStartCellPreview } from './cell-preview.js';\nimport { maybeCaptureStyles } from './style-capture.js';\n\n/**\n * Feeds browser globals into core's `deriveSessionSegment` so the cache key\n * used by `useAssignment` always matches the key `assign()` writes under.\n * Before this, the context defaulted to 'desktop:direct' while core used the\n * detected segment — a systematic cache miss for every integration that\n * didn't pass `sessionSegment` explicitly. The derivation itself lives in\n * core (audit REACT-14): a hand-mirrored `${device}:${source}` copy here\n * drifted independently of the key core writes, which is the cache-miss bug\n * all over again, one refactor later.\n */\nfunction deriveDefaultSegment(): string {\n if (typeof window === 'undefined') return 'desktop:direct';\n try {\n return deriveSessionSegment({\n userAgent: navigator.userAgent ?? '',\n referer: document.referrer ?? '',\n appOrigin: window.location.origin,\n });\n } catch {\n return 'desktop:direct';\n }\n}\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\n/** How to render adaptive slots during SSR when assignments are not preloaded. */\nexport type SsrFallback = 'first' | 'none';\n\ntype AdaptiveContextValue = {\n client: SentientClient | null;\n // The publishable API key (pk_…). Historically named `projectId` because the\n // API uses it as the project identifier on the wire, but it is the API key,\n // not the project UUID. Field renamed for clarity.\n apiKey: string;\n initialAssignments: Record<string, string>;\n /** Components an SSR preload found moved onto the shared track. */\n initialUnified: readonly string[];\n sessionSegment: string;\n ssrFallback: SsrFallback;\n onAssignment: ((componentId: string, variantId: string) => void) | undefined;\n initialLayoutOrder: string[] | null;\n initialSlots: Record<string, SlotResult>;\n initialSlotConfig: Record<string, SlotConfigEntry>;\n initialPalette: SitePalette | null;\n initialVocabulary: StyleVocabulary | null;\n initialPersona: { persona: string; confidence: number } | null;\n apiBaseUrl: string;\n debug: boolean;\n};\n\nconst AdaptiveContext = createContext<AdaptiveContextValue>({\n client: null,\n apiKey: '',\n initialAssignments: {},\n initialUnified: [],\n sessionSegment: 'desktop:direct',\n ssrFallback: 'first',\n onAssignment: undefined,\n initialLayoutOrder: null,\n initialSlots: {},\n initialSlotConfig: {},\n initialPalette: null,\n initialVocabulary: null,\n initialPersona: null,\n apiBaseUrl: DEFAULT_API_BASE_URL,\n debug: false,\n});\n\nexport type AdaptiveProviderProps = {\n apiKey: string;\n /**\n * @deprecated Unused — the project's type is set in the dashboard. Safe to omit.\n * Still accepted (and forwarded to core, which ignores it) so existing code compiles.\n */\n context?: SentientConfig['context'];\n debug?: boolean;\n /**\n * SSR-preloaded assignments from `preloadAssignments()` / `loadAdaptiveAssignments()`.\n * Passed through to `useAssignment` as synchronous initial state so crawlers and\n * the first paint see real content (recommended for SEO).\n */\n initialAssignments?: Record<string, string>;\n /**\n * Component ids the SSR preload found moved onto the shared track (the\n * `unified` of `loadAdaptiveAssignments()` / `loadAdaptiveDecision()`;\n * `<AdaptiveRoot>` passes it for you). A variants-only `<Adaptive>` with one\n * of these ids renders on the shared track from the server HTML on, and an\n * assignment cached before the move is ignored.\n */\n initialUnified?: string[];\n /**\n * Bandit segment from SSR (`device:source`). Keeps cache, assign, and worker\n * weights on one row — must match `loadAdaptiveAssignments` / session upsert.\n */\n sessionSegment?: string;\n /**\n * @deprecated Use `clientOnly` on the component; the default behaviour renders\n * the first variant.\n *\n * When no `initialAssignments` exist for a component, `'first'` renders\n * `variantIds[0]` in server HTML (safe default for SEO); `'none'` renders\n * nothing until the client resolves. Still accepted with that exact behaviour\n * so existing trees don't change. Deprecated because it was a provider-wide\n * switch for a per-component decision (`clientOnly` already expresses it), and\n * it only ever reached `<Adaptive variants>` / `useAssignment` — `useAdaptive`\n * falls back to the first key regardless, and AdaptiveText, generated-version\n * `<Adaptive>` and slots never read it, so it read broader than it was.\n * @default 'first'\n */\n ssrFallback?: SsrFallback;\n /**\n * Consent gate. When `false` the SDK is not initialised and no events are\n * sent. Flip to `true` (e.g. after the user accepts the cookie banner) to\n * initialise and begin tracking.\n */\n consent?: boolean;\n /**\n * Where to read the visitor's consent decision from, so the SDK can gate and\n * un-gate itself instead of the host app wiring `grantConsent()` by hand.\n *\n * Keep your own banner or CMP — this only tells us how to observe it. The\n * provider reads the source on mount, re-reads it whenever `event` fires, and\n * initialises the moment it grants. Nothing is requested and no cookie is set\n * until then, and there is no page reload.\n *\n * Because the provider owns the whole lifecycle there is no ordering rule to\n * get right: pass this instead of managing `consent` yourself.\n *\n * @example // cookie written by your own banner\n * consentFrom={{ cookie: 'cookie_consent', value: 'accepted', event: 'consent-decided' }}\n * @example // a supported consent platform (reads its API, events and cookie)\n * consentFrom=\"cookiebot\" // or 'onetrust' | 'cookieyes' | 'tcf' | 'google-consent-mode'\n * consentFrom={{ cmp: 'onetrust', group: 'C0004' }}\n * @example // any other CMP with a JS API\n * consentFrom={{ check: () => window.myCmp?.analytics === true, event: 'mycmp:changed' }}\n */\n consentFrom?: ConsentSource;\n /**\n * Behavior before consent is granted. Pass `'statistical_winner'` to serve the\n * best-performing variant via `GET /v1/winner` with zero tracking while the\n * consent banner is showing. Requires `consent: false`.\n * @see SentientConfig.preConsentBehavior\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Honor the browser's Do Not Track signal. Defaults to `true`: when DNT is\n * enabled the SDK sets no cookies and sends no tracking data (overriding\n * `consent: true`). Set `false` to make your own consent gate authoritative.\n * @see SentientConfig.respectDoNotTrack\n */\n respectDoNotTrack?: boolean;\n /**\n * Called once per component the first time a variant is resolved for that\n * component in this session. Use to forward assignments to your own analytics\n * (Mixpanel, PostHog, Segment, etc.) without having to wrap `useAssignment`.\n */\n onAssignment?: (componentId: string, variantId: string) => void;\n /**\n * SSR-preloaded section order from `loadAdaptiveDecision()`.\n * Pass the `layoutOrder` field from `DecideResult`. When set,\n * `useLayoutOrder()` returns this on first render so there is no layout shift.\n */\n initialLayoutOrder?: string[] | null;\n /**\n * The section ids the app declares as reorderable, independent of any\n * decision. `AdaptiveRoot` forwards its `sections` prop here.\n *\n * Devtools reads this to offer layout previewing: a page whose decision was\n * gated by consent, or timed out, has no `initialLayoutOrder`, and registering\n * only that left the layout panel empty in exactly the situation you reach for\n * it — running the site locally before accepting a cookie banner.\n */\n declaredSections?: string[];\n /**\n * What each section IS, keyed by its `data-sentient-id`:\n * `{ about: 'trust', contact: 'cta' }`. Optional — sections are classified\n * from their content — but the classifier reads a section with little\n * signal-bearing copy (an \"About us\" band, a contact form) as `generic`, and\n * a `generic` section is ordered the same for every persona. Declare the\n * ones it gets wrong; any section with a `data-sentient-id` can appear here,\n * reorderable or not. Wins over legacy `data-sentient-type` markup.\n */\n sectionTypes?: Readonly<Partial<Record<string, SemanticType>>>;\n /**\n * SSR-preloaded slot results from `loadAdaptiveDecision()` (the `slots`\n * field of its result). Guarantees `useAdaptiveTokens`/`AdaptiveGroup`\n * render the decided arm in server HTML — zero flicker, hydration-safe.\n */\n initialSlots?: Record<string, SlotResult>;\n /**\n * SSR-preloaded registry slot config from `loadAdaptiveDecision()` (the\n * `slotConfig` field of its result, registry mode). Lets `AdaptiveSlot`\n * render server-authored content/blocks in server HTML — zero flicker.\n */\n initialSlotConfig?: Record<string, SlotConfigEntry>;\n /** SSR-preloaded site palette (`palette` field of `loadAdaptiveDecision()`'s\n * registry-mode result) for block rendering. */\n initialPalette?: SitePalette;\n /** SSR-preloaded site styles (`vocabulary` field of `loadAdaptiveDecision()`'s\n * registry-mode result) that served Redesign arms borrow. */\n initialVocabulary?: StyleVocabulary;\n /**\n * Persona decided during SSR (`persona` + `confidence` fields of\n * `loadAdaptiveDecision()`'s result). Adopted by the core client;\n * rendered into html attributes only by `SentientPersonaScript`.\n */\n initialPersona?: { persona: string; confidence: number };\n /**\n * Base URL of the Sentient API (no trailing slash). Read by the devtools\n * panel for /v1/explain and by future client helpers. Defaults to the\n * hosted API.\n */\n apiBaseUrl?: string;\n /**\n * Session ID generated during SSR (the `sessionId` field returned by\n * `loadAdaptiveAssignments` / `loadAdaptiveDecision`). When provided and no\n * existing session cookie or localStorage entry is found, the client adopts\n * this ID so events and goals are attributed to the same session the server\n * used for variant assignment.\n */\n ssrSessionId?: string;\n /**\n * Where the visitor cookie lives. By default it is shared on the site's\n * registrable domain (auto-detected), so `example.com` and\n * `app.example.com` running the same project key count one visitor and one\n * journey. `false` keeps it on this host only; a string names the domain.\n */\n cookieDomain?: string | false;\n /**\n * The signed-in user: identifies the visitor once per client. Pass the\n * server-signed `userHash` (`signUserId` from `@sentientui/core/server`,\n * or let `<AdaptiveRoot userId>` do it) to make it a VERIFIED identify —\n * required for server goals by `userId` once a project signs its identifies.\n */\n identity?: { userId: string; userHash?: string; email?: string };\n /**\n * Your own team or a test site: the visit is served versions as usual (QA\n * keeps working) but left out of every report and out of learning. Compute\n * it in your code — `internal={user.email.endsWith('@example.com')}` — and\n * only `internal: true` is sent, never the email. Read once when the client\n * starts (like `persona`): a value that arrives later (auth still loading)\n * is ignored, so decide it before the provider mounts or remount it.\n * Sticky server-side. Needs a SentientUI API that knows internal traffic;\n * older ones ignore it.\n */\n internal?: boolean;\n /**\n * ISO 3166-1 alpha-2 country code. Pass the value of the `CF-IPCountry`\n * header from your Next.js server component to populate country on landing\n * sessions without client-side geo lookup.\n */\n country?: 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 → Audiences); unrecognized values are\n * ignored server-side and surfaced in the dashboard. Served at full\n * confidence, overriding the inferred persona. Stable for the session —\n * like `country`, changing it after init is ignored (decisions are locked\n * per visit); remount the provider to apply a new value.\n */\n persona?: string;\n /**\n * Opt-in theme hook: put the visitor's funnel stage on\n * `<html data-sentient-stage>` so CSS can make deterministic per-stage\n * changes (hide the first-order discount from people who have bought).\n * Projects with stages turned on only; never for the control group.\n * `true` exposes `new`, `browsing`, `carted` and `returning` (has bought\n * here); `'detailed'` splits `returning` into `customer` and `lapsed`. Any\n * script on the page can read it, which is why detail is a second opt-in.\n * How the visitor arrived (ads, emails) is never written to the page.\n * `AdaptiveRoot` also writes it in the server HTML.\n */\n stageAttributes?: StageAttributes;\n /**\n * Keyless local mode. 'auto' (default) simulates decisions on-device in\n * development builds when no valid API key is configured; `true` forces the\n * local engine; `false` restores the silent keyless no-op.\n * @see SentientConfig.localMode\n */\n localMode?: 'auto' | boolean;\n /**\n * DOM graph scanning + page-structure sync. ON by default: the provider\n * dynamically loads `@sentientui/core/graph` and uses its graph-capable\n * `init()` for the single client, so the SDK scans your page structure,\n * auto-detects semantic sections, and syncs them to power personas and the\n * dashboard graph page. Pass `false` to keep the lean bundle only.\n */\n enableGraph?: boolean;\n /**\n * Include captured heading / DOM text in graph sync payloads. OFF by default.\n * Only applies when graph scanning is enabled (`enableGraph` not `false`).\n */\n captureDomText?: boolean;\n /**\n * Behavioral engagement capture (per-section dwell/scroll + semantic section\n * registration) powering personas. ON by default — pass `false` to disable.\n * Never runs for a DNT/GPC or consent-gated visitor (no client → no capture).\n */\n engagement?: boolean;\n /**\n * CSP nonce for the <style> the SDK injects (the adaptation reveal), so a\n * nonce-based CSP needs no `style-src 'unsafe-inline'`. `AdaptiveRoot`\n * forwards its own `nonce`. Defaults to the nonce of a script on the page.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Once per page load — StrictMode and route-level providers remount. */\nlet warnedNoConsentGate = false;\n\n/** Projects whose consent source has answered (non-null) in this page load.\n * Module-level, not per mount: a remounted provider (route-level placement,\n * a cached RSC payload on Back) or a changed consentFrom started over and fell\n * back to AdaptiveRoot's stale request-time consent={true} (review R11 #1). */\nconst answeredThisPage = new Set<string>();\n\n/**\n * Watches a {@link AdaptiveProviderProps.consentFrom} source and reports whether\n * it currently grants consent. Returns false (and subscribes to nothing) when no\n * source is configured.\n */\nfunction useConsentSource(\n source: AdaptiveProviderProps['consentFrom'],\n apiKey: string,\n onRefused: () => void,\n): { granted: boolean | null; refused: boolean } {\n const onRefusedRef = useRef(onRefused);\n onRefusedRef.current = onRefused;\n const [granted, setGranted] = useState<boolean | null>(null);\n const [refused, setRefused] = useState(false);\n\n // The source is usually an inline object literal, so its identity changes\n // every render. Read it through a ref and key the effect on a stable string,\n // otherwise the listener would be torn down and re-added on every render.\n const sourceRef = useRef(source);\n sourceRef.current = source;\n const key =\n source === undefined\n ? ''\n : typeof source === 'string'\n ? source\n : JSON.stringify({\n ...source,\n check: typeof (source as { check?: unknown }).check,\n refused: typeof (source as { refused?: unknown }).refused,\n });\n\n useEffect(() => {\n const s = sourceRef.current;\n if (s === undefined || typeof window === 'undefined') return;\n // Symmetric: every signal re-reads the source both ways, so a CMP\n // \"withdrawn\" decision later in the visit re-gates the SDK (the old shape\n // latched true and stopped listening). Payloads are never trusted.\n // The watcher is its own core entry, loaded only by pages that configure\n // a consent source; until it arrives the state stays \"unknown\" (gated,\n // or the server's read).\n let stop: (() => void) | undefined;\n let cancelled = false;\n void import('@sentientui/core/consent').then(({ consentWatcher, forgetVisitor }) => {\n if (cancelled) return;\n const watcher = consentWatcher(\n // Both predicates through the ref: an inline `refused` closing over\n // state was frozen at the first render, so a later \"no\" never\n // forgot the visitor (review R7 #4).\n typeof s === 'object' && s.cmp === undefined && s.check\n ? {\n ...s,\n check: () => (sourceRef.current as { check: () => boolean }).check(),\n ...(s.refused ? { refused: () => (sourceRef.current as { refused?: () => boolean }).refused?.() === true } : {}),\n }\n : s,\n );\n // A recorded refusal forgets the visitor even when no tracking client\n // exists to destroy — a \"no\" given where the SDK wasn't watching (a CMP\n // settings page, checkout) otherwise left the 365-day id and the\n // decision snapshot in place for good (audit N2). refused() is false for\n // \"not loaded yet\" and \"banner up\", so a consented visitor is never\n // wiped by a slow CMP.\n let wasRefused = false;\n // Once the platform has answered in this page view, \"no answer\" again\n // (a custom banner's reset deleting its cookie) reads false — a pause.\n // As null it fell back to the server's request-time read, so a visitor\n // who withdrew under AdaptiveRoot's consent={true} was tracked again\n // under a fresh identity (grader N10-1). See answeredThisPage.\n const update = (): void => {\n // Never while the source reads granted (a custom `refused` that\n // disagrees with its own `check`): that would wipe a tracked visitor.\n const r = watcher.refused() && watcher.read() !== true;\n // On a change only: Consent Mode calls back on every dataLayer push.\n if (r && !wasRefused) {\n forgetVisitor(apiKey);\n onRefusedRef.current();\n }\n wasRefused = r;\n setRefused(r);\n const g = watcher.read();\n if (g !== null) answeredThisPage.add(apiKey);\n setGranted(g ?? (answeredThisPage.has(apiKey) ? false : null));\n };\n update();\n stop = watcher.subscribe(update);\n });\n return () => {\n cancelled = true;\n stop?.();\n };\n }, [key, apiKey]);\n\n return { granted, refused };\n}\n\n/**\n * Initialises the Sentient core SDK in a useEffect (SSR-safe) and exposes the\n * client via React context. Re-initialises when consent changes.\n */\nexport function AdaptiveProvider(props: AdaptiveProviderProps): JSX.Element {\n const [client, setClient] = useState<SentientClient | null>(null);\n // Derived once per mount: identical to what core init() computes, so cache\n // reads (context segment) and cache writes (core segment) always agree.\n const [sessionSegment] = useState(() => props.sessionSegment ?? deriveDefaultSegment());\n // Devtools preview: when on, expose an event-suppressing client so previewing\n // variants/personas writes nothing. Off by default (inert in production).\n const [previewOn, setPreviewOn] = useState(getPreviewMode());\n useEffect(() => subscribePreview(() => setPreviewOn(getPreviewMode())), []);\n // On-site cell preview (dashboard \"Preview on your site\" link). No-ops\n // without both URL params; forces the previewed arm through the override\n // channel AdaptiveSlot already renders exposure-free.\n useEffect(() => {\n maybeStartCellPreview(props.apiBaseUrl);\n // Read-only version preview (?sentient_preview=<component>:<version>):\n // the link the dashboard's pictures are taken through. Preview mode goes\n // on HERE, synchronously — before anything on the page decides or records\n // — and the preview itself loads only for that link: a preview is not a\n // visit, and no ordinary visitor should download it.\n // A cheap look for the link's shape (<component>:<version>); the preview\n // entry checks it properly and turns preview mode back off if it is not\n // a link we wrote.\n if (typeof window !== 'undefined' && /[?&]sentient_preview=[^&]*(:|%3A)/i.test(window.location.search)) {\n setPreviewMode(true);\n void import('@sentientui/react/version-preview')\n .then((m) => m.maybeStartVersionPreview(props.apiKey, props.apiBaseUrl))\n .catch(() => undefined);\n }\n // Any editor-token session also samples the site's styles for Redesign\n // (React sites never load the snippet editor that does it elsewhere).\n maybeCaptureStyles(props.apiBaseUrl);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // When a consentFrom source is configured it owns the gate: start closed and\n // open only once the source grants. An explicit consent={true} (e.g. resolved\n // from the cookie on the server by AdaptiveRoot) short-circuits it, so a\n // returning visitor isn't gated waiting for a client-side re-read.\n // The browser source decides as soon as it knows (true OR false). Until then\n // (null: CMP not loaded yet) the server's read stands. The old\n // `props.consent === true || sourceGranted` let a server-side grant override\n // a mid-visit revocation for the rest of the page view.\n // Declared ahead of useConsentSource (which must call it): the refs it\n // clears are created further down.\n const dropHeldRef = useRef<() => void>(() => undefined);\n const source = useConsentSource(props.consentFrom, props.apiKey, () => dropHeldRef.current());\n // The server's read stands only until the browser source has answered in\n // this page load — also across remounts, before the watcher reloads.\n const consent = props.consentFrom\n ? (source.granted ?? (answeredThisPage.has(props.apiKey) ? false : props.consent === true))\n : props.consent;\n // Whether a `false` means \"forget the visitor\" or only \"stop for now\". An\n // explicit consent={false} is the site's own revocation; from a platform,\n // only a recorded refusal forgets — a consented visitor reopening the TCF\n // banner reads false too and was fully forgotten (review M2).\n const forgetOnFalse = props.consentFrom ? source.refused : true;\n const forgetRef = useRef(forgetOnFalse);\n forgetRef.current = forgetOnFalse;\n\n // The live client mirrored outside React state, so teardown can reach it\n // without a side effect inside a setState updater: React double-invokes\n // updaters in StrictMode dev (they must be pure), so `prev?.destroy()` inside\n // setClient ran twice — and could run during a render that never commits.\n const clientRef = useRef<SentientClient | null>(null);\n // Whether clientRef holds a TRACKING client (created with consent not false).\n // A revocation must forget that client's visitor; a pre-consent proxy has\n // nothing to forget.\n const trackingRef = useRef(false);\n // Conversions a gated client held (goal() before the consent source\n // answered), taken from it on teardown and handed to the next client: React\n // replaces the gated client on a grant instead of upgrading it in place, so\n // they were discarded with it (grader F2).\n const heldRef = useRef<Array<(c: SentientClient) => void>>([]);\n // A recorded refusal drops held conversions — ours and the gated client's —\n // so a later accept in the same page view can't send them (grader F-R1:\n // the effect is keyed on `consent`, which stays false from \"unknown\" to\n // \"refused\", so nothing else runs on the refusal).\n // The gated client is RELEASED, not just drained: draining left it holding,\n // so a goal fired after the refusal was held again and sent on a later\n // accept (grader R8 NEW-2). dispose() on a gated proxy drops its held calls,\n // answers its decides with null and holds nothing more; its read-only\n // winner (preConsentBehavior) keeps serving until the next consent change.\n // Latched too, until the next grant: a gated client created AFTER the\n // refusal — the re-init when a tracked visitor refuses, or the /graph\n // client landing after a boot-time refusal — was never released, so its\n // held goals reached the tracking client on a later accept (grader R9-1).\n const refusedRef = useRef(false);\n dropHeldRef.current = () => {\n heldRef.current = [];\n refusedRef.current = true;\n const c = clientRef.current;\n if (c?.gated) c.dispose();\n else c?.takeHeld?.();\n };\n\n useEffect(() => {\n // Revocation (a tracking client → consent false): forget the visitor —\n // identity cookie, assignment cache, decision snapshot, retry buckets —\n // via the ref, in the effect body (see clientRef above). This used to run\n // only without preConsentBehavior; with 'statistical_winner' the previous\n // run's cleanup merely dispose()d, so a withdrawn visitor kept the 365-day\n // cookie and their snapshot re-personalized the next page load.\n // (Only a forgetting revocation destroys; a pause was already disposed by\n // the previous run's cleanup, which keeps the identity.)\n if (forgetRef.current && consent === false) heldRef.current = [];\n if (consent === false && trackingRef.current) {\n if (forgetRef.current) clientRef.current?.destroy();\n clientRef.current = null;\n trackingRef.current = false;\n }\n if (consent === false && !props.preConsentBehavior) {\n if (forgetRef.current) clientRef.current?.destroy();\n clientRef.current = null;\n setClient(null);\n return;\n }\n const tracking = consent !== false;\n if (tracking) refusedRef.current = false;\n // A gated client born after a refusal is released at once (see refusedRef).\n const adopt = (c: SentientClient): void => {\n if (!tracking && refusedRef.current && c.gated) c.dispose();\n };\n\n const config = {\n apiKey: props.apiKey,\n context: props.context,\n debug: props.debug,\n initialAssignments: props.initialAssignments,\n initialUnified: props.initialUnified,\n sessionSegment,\n consent,\n preConsentBehavior: props.preConsentBehavior,\n respectDoNotTrack: props.respectDoNotTrack,\n ssrSessionId: props.ssrSessionId,\n cookieDomain: props.cookieDomain,\n country: props.country,\n persona: props.persona,\n internal: props.internal,\n stageAttributes: props.stageAttributes,\n localMode: props.localMode,\n initialSlots: props.initialSlots,\n initialSlotConfig: props.initialSlotConfig,\n initialPalette: props.initialPalette,\n initialVocabulary: props.initialVocabulary,\n initialPersona: props.initialPersona,\n ingestUrl: props.apiBaseUrl ? `${props.apiBaseUrl.replace(/\\/$/, '')}/events` : undefined,\n nonce: props.nonce,\n // Declare which SDK (and which release) is driving this client, so the\n // dashboard can tell the project when it is running an old one. A React\n // install cannot self-update the way the snippet's CDN tag does, so this\n // nudge is the only update path there is.\n ...(SDK_IDENT ? { sdk: SDK_IDENT } : {}),\n };\n\n // Track the client created by this effect run so cleanup destroys exactly\n // the right one, and so a late-resolving dynamic import can bail if the\n // effect was already torn down (unmount / consent change).\n let cancelled = false;\n let created: SentientClient | null = null;\n let stopEngagement: (() => void) | null = null;\n\n // Engagement capture (default ON): per-section dwell/scroll + semantic\n // section registration, lazy-loaded so the lean bundle stays lean. Only for\n // a TRACKING client: with preConsentBehavior a gated visitor still gets a\n // (pre-consent proxy) client, and capture used to start on it — POSTing\n // /v1/section-map and attaching collectors while consent was false. The\n // capture module re-checks DNT internally.\n // Replay held conversions: sent by a tracking client, re-held by a gated one.\n // Each in its own task, like core's replay: one task would put them in\n // one latch window and collapse repeat conversions into one.\n const handOff = (c: SentientClient): void => {\n for (const call of heldRef.current.splice(0)) {\n setTimeout(() => {\n // Replaced before this task ran (unmount, another consent flip):\n // back into the stash for the next client, never into a disposed\n // one's dead queue (review R7 #6).\n if (clientRef.current !== c) {\n // …unless a refusal landed in between: it dropped the stash,\n // and pushing back revived the goal for a later accept\n // (review R10 #2).\n if (!refusedRef.current) heldRef.current.push(call);\n return;\n }\n try {\n call(c);\n } catch {\n /* one bad call never blocks the rest */\n }\n }, 0);\n }\n };\n\n const startEngagement = (c: SentientClient): void => {\n if (props.engagement === false || !tracking) return;\n void import('@sentientui/core/engagement').then(({ startEngagementCapture }) => {\n if (cancelled) return;\n stopEngagement = startEngagementCapture(c, {\n apiKey: props.apiKey,\n sectionTypes: props.sectionTypes,\n apiBase: props.apiBaseUrl ? props.apiBaseUrl.replace(/\\/$/, '') : undefined,\n });\n });\n };\n\n if (props.enableGraph !== false) {\n // Graph scanning is the default — load the graph entry dynamically so the\n // scanner never lands in the lean bundle. The provider still creates ONE\n // client (graph-capable). Pass enableGraph={false} for the lean client.\n void import('@sentientui/core/graph').then(({ init: initGraph }) => {\n if (cancelled) return;\n created = initGraph({\n ...config,\n graph: true,\n captureDomText: props.captureDomText === true,\n sectionTypes: props.sectionTypes,\n });\n adopt(created);\n clientRef.current = created;\n trackingRef.current = tracking;\n handOff(created);\n setClient(created);\n startEngagement(created);\n });\n } else {\n created = init(config);\n adopt(created);\n clientRef.current = created;\n trackingRef.current = tracking;\n handOff(created);\n setClient(created);\n startEngagement(created);\n }\n\n return () => {\n cancelled = true;\n stopEngagement?.();\n heldRef.current = heldRef.current.concat(created?.takeHeld?.() ?? []);\n // dispose, not destroy: effect cleanup runs on unmount, StrictMode's\n // dev double-invoke, and consent re-init — the visitor identity must\n // survive all of those. Full destroy() happens only on the explicit\n // consent-revocation branch above.\n created?.dispose();\n };\n // Re-init when consent changes — whether that came from the prop or from a\n // consentFrom source granting. Other props (incl. enableGraph) are\n // intentionally stable for a session.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [consent]);\n\n // Poll /v1/weights every 60 s so long-lived sessions see updated bandit weights\n // without a page reload. useAssignment subscribers react via weights-store.\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n const poll = async (): Promise<void> => {\n if (cancelled) return;\n let entries;\n try {\n entries = await client.fetchWeights();\n } catch {\n // Network/transient error: skip this cycle and retry on the next\n // interval. Swallowed deliberately so a failed poll never surfaces as\n // an unhandled rejection.\n return;\n }\n if (cancelled) return;\n for (const entry of entries) {\n const weights: ComponentWeights = {\n componentId: entry.componentId,\n updatedAt: entry.updatedAt,\n variants: entry.variants.map((v) => ({\n variantId: v.variantId,\n pulls: v.pulls,\n avgReward: v.avgReward ?? 0,\n })),\n };\n updateWeightsStore(entry.componentId, weights);\n }\n };\n void poll();\n const timerId = setInterval(() => void poll(), 60_000);\n return () => {\n cancelled = true;\n clearInterval(timerId);\n };\n }, [client]);\n\n const ssrFallback = props.ssrFallback ?? 'first';\n // Strip a trailing slash so consumers (devtools /explain, useAdaptiveApiBaseUrl)\n // build URLs the same way the core client does (it strips before appending\n // /events and /section-map) — otherwise an apiBaseUrl ending in \"/\" yields a\n // double slash like \".../v1//explain\".\n const apiBaseUrl = (props.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\\/$/, '');\n\n // The init effect above re-runs only on `props.consent`: apiKey / context /\n // country / apiBaseUrl are captured once and are deliberately stable for the\n // session, so changing them at runtime silently no-ops. That silence is\n // surprising — warn (dev only) when one actually changes value after init, so\n // the no-op is visible. To apply a new value, remount the provider (e.g. a\n // changing React `key`).\n const frozenConfigRef = useRef<{\n apiKey: string;\n // Optional since `context` was deprecated: undefined → undefined compares\n // equal under Object.is, so omitting it never trips the warning below.\n context: SentientConfig['context'] | undefined;\n country: string | undefined;\n persona: string | undefined;\n internal: boolean | undefined;\n apiBaseUrl: string;\n } | null>(null);\n useEffect(() => {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') return;\n const current = { apiKey: props.apiKey, context: props.context, country: props.country, persona: props.persona, internal: props.internal, apiBaseUrl };\n const prev = frozenConfigRef.current;\n frozenConfigRef.current = current;\n if (prev === null) return; // first run: capture the frozen baseline, nothing to compare\n // `internal` too: `internal={user?.isStaff}` with auth still loading\n // starts the client unmarked, and the later `true` silently did nothing.\n for (const key of ['apiKey', 'context', 'country', 'persona', 'internal', 'apiBaseUrl'] as const) {\n if (!Object.is(prev[key], current[key])) {\n console.warn(\n `[sentient] AdaptiveProvider: \\`${key}\\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \\`consent\\` — the new value is ignored. Remount the provider (e.g. via a changing \\`key\\` prop) to apply it.`,\n );\n }\n }\n }, [props.apiKey, props.context, props.country, props.persona, props.internal, apiBaseUrl]);\n\n // Publish devtools config through window: the /devtools entry is a separate\n // bundle and cannot read this provider's context instance. Dev-only.\n useEffect(() => {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') return;\n publishDevtoolsConfig({\n apiKey: props.apiKey,\n apiBaseUrl,\n isLocal: client?.isLocal === true,\n });\n }, [client, props.apiKey, apiBaseUrl]);\n\n // identify() is an upsert: once per client and user, never per render. A\n // consent grant makes a new client, which identifies again — the gated one\n // dropped it.\n const identityUser = props.identity?.userId;\n const identityHash = props.identity?.userHash;\n // Hashed by core before it leaves the page; only the hash + domain are sent.\n const identityEmail = props.identity?.email;\n useEffect(() => {\n if (client && identityUser) client.identify(identityUser, { userHash: identityHash, email: identityEmail });\n }, [client, identityUser, identityHash, identityEmail]);\n\n // Sections registry for devtools /v1/explain + local simulation. The decided\n // order wins when there is one (it is what the page is actually rendering);\n // the declared list is the fallback so the layout panel still knows what is\n // reorderable when no decision arrived.\n useEffect(() => {\n const decided = props.initialLayoutOrder;\n if (decided && decided.length > 0) {\n registerSections(decided);\n return;\n }\n if (props.declaredSections && props.declaredSections.length > 0) {\n registerSections(props.declaredSections);\n }\n }, [props.initialLayoutOrder, props.declaredSections]);\n\n // Dev-only: tracking is on by default, so an install that never wires a\n // consent gate tracks EU visitors from the first paint without anyone\n // having decided that (audit S6). Say so once, with the one-line fix.\n useEffect(() => {\n if (!isDevBuild() || props.consent !== undefined || props.consentFrom !== undefined) return;\n if (warnedNoConsentGate) return;\n warnedNoConsentGate = true;\n console.warn(\n '[SentientUI] No consent gate: every visitor is tracked from first paint. Pass consentFrom=\"<your CMP>\" ' +\n '(or consent={true} to silence). https://sentient-ui.com/docs#consent',\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Dev-only: a declared section with no `data-sentient-id=\"<id>\"` element is\n // invisible to the DOM graph scanner, so the server never learns its semantic\n // type and every persona gets the identity order — the layout looks \"on\" but\n // can never personalize (found on a real site 2026-09-05: nine declared\n // sections, zero graph rows, one bandit arm). Warn once with the exact fix\n // rather than leaving the integration silently inert.\n useEffect(() => {\n if (!isDevBuild()) return;\n const declared = props.declaredSections;\n if (!declared || declared.length === 0 || typeof document === 'undefined') return;\n const present = new Set(\n Array.from(document.querySelectorAll('[data-sentient-id]'), (el) =>\n el.getAttribute('data-sentient-id'),\n ),\n );\n const missing = declared.filter((id) => !present.has(id));\n if (missing.length > 0) {\n console.warn(\n `[SentientUI] Declared section${missing.length > 1 ? 's' : ''} ${missing\n .map((id) => `\"${id}\"`)\n .join(', ')} ${missing.length > 1 ? 'have' : 'has'} no matching ` +\n 'data-sentient-id element, so the layout engine cannot learn what ' +\n 'they are and will serve the same order to every persona. Add ' +\n 'data-sentient-id=\"<sectionId>\" to each section\\'s element.',\n );\n }\n }, [props.declaredSections]);\n\n // The client exposed to consumers — wrapped to suppress events while previewing.\n const exposedClient = useMemo(\n () => (client && previewOn ? createPreviewClient(client) : client),\n [client, previewOn],\n );\n\n // Memoized so unrelated parent re-renders don't cascade through every\n // useSentient / useAssignment consumer via a fresh context object.\n const value = useMemo<AdaptiveContextValue>(\n () => ({\n client: exposedClient,\n apiKey: props.apiKey,\n initialAssignments: props.initialAssignments ?? {},\n initialUnified: props.initialUnified ?? NO_UNIFIED,\n sessionSegment,\n ssrFallback,\n onAssignment: props.onAssignment,\n initialLayoutOrder: props.initialLayoutOrder ?? null,\n initialSlots: props.initialSlots ?? {},\n initialSlotConfig: props.initialSlotConfig ?? {},\n initialPalette: props.initialPalette ?? null,\n initialVocabulary: props.initialVocabulary ?? null,\n initialPersona: props.initialPersona ?? null,\n apiBaseUrl,\n debug: props.debug ?? false,\n }),\n [\n exposedClient,\n props.apiKey,\n props.initialAssignments,\n props.initialUnified,\n sessionSegment,\n ssrFallback,\n props.onAssignment,\n props.initialLayoutOrder,\n props.initialSlots,\n props.initialSlotConfig,\n props.initialPalette,\n props.initialVocabulary,\n props.initialPersona,\n apiBaseUrl,\n props.debug,\n ],\n );\n\n return (\n <AdaptiveContext.Provider value={value}>\n {props.children}\n </AdaptiveContext.Provider>\n );\n}\n\n/**\n * Returns the SentientClient, or null until the provider has finished\n * initialising on the client.\n */\nexport function useSentient(): SentientClient | null {\n return useContext(AdaptiveContext).client;\n}\n\n/** Internal: publishable API key carried alongside the client. */\nexport function useAdaptiveApiKey(): string {\n return useContext(AdaptiveContext).apiKey;\n}\n\n/** Internal: SSR-preloaded assignments for hydration-safe first render. */\nexport function useInitialAssignments(): Record<string, string> {\n return useContext(AdaptiveContext).initialAssignments;\n}\n\nconst NO_UNIFIED: readonly string[] = [];\n\n/** Internal. Ids the SSR preload found moved onto the shared track. */\nexport function useInitialUnified(): readonly string[] {\n return useContext(AdaptiveContext).initialUnified;\n}\n\n/** The `device:source` segment this provider decides and caches under —\n * the SSR value when one was passed, else derived once per mount. */\nexport function useSessionSegment(): string {\n return useContext(AdaptiveContext).sessionSegment;\n}\n\n/** Internal: SSR fallback strategy when a slot has no preloaded assignment. */\nexport function useSsrFallback(): SsrFallback {\n return useContext(AdaptiveContext).ssrFallback;\n}\n\n/** Internal: forwarding hook for consumer analytics integration. */\nexport function useOnAssignment(): ((componentId: string, variantId: string) => void) | undefined {\n return useContext(AdaptiveContext).onAssignment;\n}\n\n/** Internal: debug flag from the provider config, for dev-only diagnostic logging. */\nexport function useDebug(): boolean {\n return useContext(AdaptiveContext).debug;\n}\n\n/**\n * Returns the persona-specific section order from SSR, or null when no\n * sections were declared on AdaptiveRoot or reliability is below threshold.\n * Devtools/testing can force it via `window.__sentient_layout_override`;\n * consumers re-render when the devtools notifies an override change.\n */\nexport function useLayoutOrder(): string[] | null {\n const contextOrder = useContext(AdaptiveContext).initialLayoutOrder;\n const override = useSyncExternalStore(\n subscribeOverridesChanged,\n () =>\n typeof window === 'undefined'\n ? null\n : ((window as unknown as { __sentient_layout_override?: string[] })\n .__sentient_layout_override ?? null),\n () => null,\n );\n return override ?? contextOrder;\n}\n\n/** Internal: SSR-preloaded slot results for hydration-safe first render. */\nexport function useInitialSlots(): Record<string, SlotResult> {\n return useContext(AdaptiveContext).initialSlots;\n}\n\n/** Internal: SSR-decided persona carried alongside the client. */\nexport function useInitialPersona(): { persona: string; confidence: number } | null {\n return useContext(AdaptiveContext).initialPersona;\n}\n\n/** Internal: SSR-preloaded registry slot config for hydration-safe AdaptiveSlot. */\nexport function useInitialSlotConfig(): Record<string, SlotConfigEntry> {\n return useContext(AdaptiveContext).initialSlotConfig;\n}\n\n/** Internal: SSR-preloaded site palette for block rendering. */\nexport function useInitialPalette(): SitePalette | null {\n return useContext(AdaptiveContext).initialPalette;\n}\n\n/** Internal: SSR-preloaded site styles for Redesign rendering. */\nexport function useInitialVocabulary(): StyleVocabulary | null {\n return useContext(AdaptiveContext).initialVocabulary;\n}\n\n/** Internal: configured API base URL (devtools fetches /v1/explain against this, never a relative URL). */\nexport function useAdaptiveApiBaseUrl(): string {\n return useContext(AdaptiveContext).apiBaseUrl;\n}\n","/** Per-component weights store with isolated subscriptions. */\n\nexport type VariantWeight = {\n variantId: string;\n pulls: number;\n avgReward: number;\n};\n\nexport type ComponentWeights = {\n componentId: string;\n variants: VariantWeight[];\n updatedAt: number;\n};\n\ntype Listener = (weights: ComponentWeights) => void;\n\nconst store = new Map<string, ComponentWeights>();\nconst listeners = new Map<string, Set<Listener>>();\n\n/**\n * Subscribes a listener to a single component. Returns an unsubscribe function.\n * Updates to other components never trigger this listener.\n */\nexport function subscribe(componentId: string, cb: Listener): () => void {\n let set = listeners.get(componentId);\n if (!set) {\n set = new Set();\n listeners.set(componentId, set);\n }\n set.add(cb);\n return () => {\n set!.delete(cb);\n if (set!.size === 0) listeners.delete(componentId);\n };\n}\n\n/**\n * Replaces the weights for a component and notifies only that component's\n * subscribers.\n */\nexport function update(componentId: string, weights: ComponentWeights): void {\n store.set(componentId, weights);\n const set = listeners.get(componentId);\n if (!set) return;\n for (const cb of set) {\n try {\n cb(weights);\n } catch {\n /* never throw to other listeners */\n }\n }\n}\n\n/**\n * Returns the latest known weights for a component, or null if none seen.\n */\nexport function getWeights(componentId: string): ComponentWeights | null {\n return store.get(componentId) ?? null;\n}\n\n/** Test-only: wipe the entire store. */\nexport function _resetWeightsStore(): void {\n store.clear();\n listeners.clear();\n}\n","import type { SentientClient } from '@sentientui/core';\n\ntype PreviewState = { on: boolean; listeners: Set<() => void> };\nconst ssrFallback: PreviewState = { on: false, listeners: new Set() };\n\n// Window-backed: the /devtools entry (a separate bundle) toggles preview mode\n// and the provider (main bundle) must observe it.\nfunction state(): PreviewState {\n if (typeof window === 'undefined') return ssrFallback;\n const w = window as unknown as { __sentient_preview?: PreviewState };\n if (!w.__sentient_preview) w.__sentient_preview = { on: false, listeners: new Set() };\n return w.__sentient_preview;\n}\n\nexport function setPreviewMode(on: boolean): void {\n const s = state();\n if (s.on === on) return;\n s.on = on;\n for (const fn of s.listeners) fn();\n}\n\nexport function getPreviewMode(): boolean {\n return state().on;\n}\n\nexport function subscribePreview(fn: () => void): () => void {\n const listeners = state().listeners;\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/**\n * Wraps a client so it writes nothing: reads pass through, all emitters no-op.\n * Used while previewing variants/personas so no `variant_assigned`, goal, or\n * session events are sent.\n */\nexport function createPreviewClient(inner: SentientClient): SentientClient {\n return {\n isLocal: inner.isLocal,\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n fetchWeights: () => Promise.resolve([]),\n getAssignment: (componentId, segment) => inner.getAssignment(componentId, segment),\n isUnified: (componentId) => inner.isUnified?.(componentId) ?? false,\n assign: (componentId, variantIds, agentData, agentDataByVariant, opts) =>\n inner.assign(componentId, variantIds, agentData, agentDataByVariant, opts),\n // Reads pass through; decide is a write (slot decisions persist server-side)\n // so preview mode never issues it.\n decide: () => Promise.resolve(null),\n getSlotResult: (slotId) => inner.getSlotResult(slotId),\n getSlotConfig: (slotId) => inner.getSlotConfig(slotId),\n getSitePalette: () => inner.getSitePalette(),\n reportSlots: (ids) => inner.reportSlots(ids),\n getPersona: () => inner.getPersona(),\n getGraph: () => inner.getGraph(),\n flush: () => inner.flush(),\n dispose: () => inner.dispose(),\n destroy: () => inner.destroy(),\n };\n}\n","/**\n * Cross-bundle re-render bus for devtools overrides. The main entry and the\n * /devtools entry are separate bundles, so state and notifications go through\n * window (a version counter + a DOM event) — never module-local state.\n */\nconst EVENT = 'sentient:overrides-changed';\n\ntype VersionWindow = Window & { __sentient_overrides_version?: number };\n\nexport function getOverridesVersion(): number {\n if (typeof window === 'undefined') return 0;\n return (window as VersionWindow).__sentient_overrides_version ?? 0;\n}\n\nexport function notifyOverridesChanged(): void {\n if (typeof window === 'undefined') return;\n const w = window as VersionWindow;\n w.__sentient_overrides_version = (w.__sentient_overrides_version ?? 0) + 1;\n window.dispatchEvent(new Event(EVENT));\n}\n\nexport function subscribeOverridesChanged(fn: () => void): () => void {\n if (typeof window === 'undefined') return () => undefined;\n window.addEventListener(EVENT, fn);\n return () => window.removeEventListener(EVENT, fn);\n}\n","/** Provider → devtools config handoff. Window-backed: the /devtools entry is a\n * separate bundle and cannot share the provider's React context instance. */\nexport type DevtoolsConfig = {\n apiKey: string;\n apiBaseUrl: string;\n isLocal: boolean;\n};\n\ntype ConfigWindow = Window & { __sentient_devtools_config?: DevtoolsConfig };\n\nexport function publishDevtoolsConfig(config: DevtoolsConfig): void {\n if (typeof window === 'undefined') return;\n (window as ConfigWindow).__sentient_devtools_config = config;\n}\n\nexport function readDevtoolsConfig(): DevtoolsConfig | null {\n if (typeof window === 'undefined') return null;\n return (window as ConfigWindow).__sentient_devtools_config ?? null;\n}\n","import type { GoalName } from './goal-names.js';\nimport type { SentientClient } from '@sentientui/core';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\n/**\n * True unless NODE_ENV is 'production'. Never `process?.env` — optional\n * chaining still throws ReferenceError on an undeclared global, and browsers\n * without a bundler shim (raw esbuild, vanilla script tags) have no `process`.\n */\nexport function isDevBuild(): boolean {\n return typeof process === 'undefined' || process.env?.NODE_ENV !== 'production';\n}\n\n/**\n * The element `<Adaptive>` renders around its content (audit S17: it was\n * always a `<div>`, which is invalid inside a `<ul>`, a `<p>` or a table row\n * and broke `display: grid` children). Intrinsic tags only: the wrapper is\n * what exposure, goals and micro-signals observe, so it must be a real box —\n * `display: contents` would give IntersectionObserver nothing to measure.\n */\nexport type AdaptiveElement =\n | 'div' | 'section' | 'article' | 'aside' | 'header' | 'footer' | 'main' | 'nav'\n | 'span' | 'li' | 'figure' | 'form' | 'label' | 'td' | 'th';\n\nexport type ScrollDepthGoal = { type: 'scroll_depth'; threshold: number; value?: number };\nexport type ClickGoal = { type: 'click'; selector?: string; value?: number };\nexport type FormSubmitGoal = { type: 'form_submit'; value?: number };\nexport type CompositeGoal = { type: 'composite'; all: GoalConfig[] };\nexport type WeightedStep = { goal: GoalConfig; name: GoalName; weight: number };\nexport type WeightedCompositeGoal = { type: 'weighted_composite'; steps: WeightedStep[] };\nexport type GoalConfig = ScrollDepthGoal | ClickGoal | FormSubmitGoal | CompositeGoal | WeightedCompositeGoal;\n\nexport function normalizeGoal(goal: string | GoalConfig): GoalConfig {\n if (typeof goal === 'string') return { type: 'click' };\n return goal;\n}\n\n/** The goalType label events are recorded under (named goal or config type). */\nexport function goalLabelOf(goal: string | GoalConfig): string {\n return typeof goal === 'string' ? goal : goal.type;\n}\n\n/** Static revenue value declared on a simple goal config, if any. Composites\n * carry no value (weights and values don't mix — spec §9.4); dynamic values\n * go through the imperative hooks. */\nexport function goalValueOf(goal: string | GoalConfig): number | undefined {\n if (typeof goal === 'string') return undefined;\n if (goal.type === 'click' || goal.type === 'form_submit' || goal.type === 'scroll_depth') {\n return goal.value;\n }\n return undefined;\n}\n\n/**\n * Collapses scroll-depth goal fires that belong to one observation moment.\n *\n * Two nested Adaptive components sharing one scroll_depth goal label attach two\n * SEPARATE IntersectionObservers (they observe different container nodes), and\n * one scroll can satisfy both. The platform delivers all IntersectionObserver\n * notifications for that moment within one task, but runs a microtask\n * checkpoint between the two callback invocations (\"clean up after running\n * script\" fires whenever the JS stack empties — including between separate UA\n * callback invocations in the same task). Core's action latch closes its\n * non-dispatch window on a microtask precisely so a genuine repeat conversion\n * can never be swallowed by a stale window — which means that checkpoint SPLITS\n * the two observer callbacks into two windows, and the goal double-records.\n *\n * So the collapse for this one double-fire lives here, at the layer that knows\n * both fires are scroll-driven, instead of widening core's window for every\n * caller. The scope is one task — the very clock core abandoned — and that is\n * safe HERE for the reason it was wrong there: core's window could be jumped\n * because ANY code (an already-armed timer on the page) can call goal(), so a\n * genuinely separate conversion could land inside a window that outlived its\n * action. Every caller of this gate is an IntersectionObserver callback; timers\n * never consult it, and a genuinely separate scroll fire arrives in a later\n * rendering-update task. Worst case, an implausibly delayed close collapses two\n * same-label, same-value scroll fires — exactly the collapse this gate exists\n * to perform — never a differently-valued or click-driven conversion.\n */\nconst scrollFiredThisTask = new Set<string>();\nlet scrollGateClearArmed = false;\n\nexport function scrollFireCollapsedThisTask(key: string): boolean {\n if (scrollFiredThisTask.has(key)) return true;\n scrollFiredThisTask.add(key);\n if (!scrollGateClearArmed) {\n scrollGateClearArmed = true;\n const clear = (): void => {\n scrollGateClearArmed = false;\n scrollFiredThisTask.clear();\n };\n // MessageChannel over setTimeout when available: fake-timer test setups\n // freeze setTimeout, which would latch the gate open and swallow every\n // later scroll goal (the same hazard core's old clearNextTask named).\n // Both are macrotasks, so either closes the window after this task.\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 } else {\n setTimeout(clear, 0);\n }\n }\n return false;\n}\n\nfunction isClickableTarget(el: EventTarget | null): boolean {\n if (!(el instanceof Element)) return false;\n const tag = el.tagName.toLowerCase();\n if (tag === 'a' || tag === 'button') return true;\n const role = el.getAttribute('role');\n return role === 'button';\n}\n\nfunction findClickable(start: Element, container: Element, selector?: string): boolean {\n if (selector) {\n try {\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (cursor.matches(selector)) return true;\n cursor = cursor.parentElement;\n }\n } catch {\n // Invalid CSS selector — treat as no match rather than breaking all click handlers.\n }\n return false;\n }\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (isClickableTarget(cursor)) return true;\n cursor = cursor.parentElement;\n }\n return false;\n}\n\nexport type GoalHandlers = {\n /** Primary goal completion. Latch-once semantics are the CALLER's job. */\n fireGoal: () => void;\n /** Weighted-composite step completion (already deduped per step here). */\n fireStep: (name: string, weight: number, stepIndex: number) => void;\n};\n\n/**\n * Attaches the goal-detection listeners `<Adaptive>`'s container uses —\n * click / form_submit / scroll_depth, composite (all-of), and\n * weighted_composite (independent steps). Returns the cleanup function.\n * Extracted from adaptive.tsx so useAdaptive / useAdaptiveTokens /\n * AdaptiveGroup wire the SAME machinery instead of duplicating it.\n *\n * `scrollDedupeKey` is the goal LABEL: nested instances sharing a label and\n * satisfied by one scroll moment are one user action, whatever value each\n * instance declares, so scroll-driven fires collapse per label — see\n * scrollFireCollapsedThisTask. (The inner instance's observer is created first\n * and its callback delivered first, so when an inner valued goal nests in a\n * valueless wrapper, the valued fire is the one that wins the gate.)\n * Click/submit fires never consult it: those share a real event dispatch,\n * which core's action latch already collapses on.\n */\nexport function attachGoalListeners(\n node: Element,\n goal: GoalConfig,\n handlers: GoalHandlers,\n scrollDedupeKey?: string,\n): () => void {\n // --- Weighted composite: each step fires independently as it completes ---\n if (goal.type === 'weighted_composite') {\n const firedSteps = new Set<number>();\n const wcCleanups: Array<() => void> = [];\n\n goal.steps.forEach(({ goal: sub, name: stepName, weight: stepWeight }, idx) => {\n // viaScroll: a step completed by an IntersectionObserver callback runs the\n // same nested-instance double-fire risk as a plain scroll_depth goal (the\n // microtask checkpoint between two observers' callbacks splits core's\n // window), so it goes through the task gate under its own step identity.\n const fireStep = (viaScroll = false): void => {\n if (firedSteps.has(idx)) return;\n if (\n viaScroll &&\n scrollDedupeKey !== undefined &&\n scrollFireCollapsedThisTask(`step\\0${stepName}\\0${stepWeight}\\0${idx}`)\n ) {\n return;\n }\n firedSteps.add(idx);\n handlers.fireStep(stepName, stepWeight, idx);\n };\n\n if (sub.type === 'click') {\n const onClick = (e: Event): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n fireStep();\n };\n node.addEventListener('click', onClick);\n wcCleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n fireStep();\n };\n node.addEventListener('submit', onSubmit);\n wcCleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n fireStep(true);\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n wcCleanups.push(() => io.disconnect());\n }\n });\n\n return () => {\n for (const c of wcCleanups) c();\n };\n }\n // --- End weighted composite ---\n\n const subgoals: GoalConfig[] = goal.type === 'composite' ? goal.all : [goal];\n const remaining = new Set<number>(subgoals.map((_, i) => i));\n // The scroll gate is consulted only at the moment a goal actually FIRES from\n // a scroll callback — never when a scroll merely completes one subgoal of a\n // still-open composite. Consulting it early would claim the key for an\n // instance that fires nothing, suppressing the nested instance that would\n // have fired, and the conversion would be lost outright.\n const fireViaScroll = (): void => {\n if (scrollDedupeKey !== undefined && scrollFireCollapsedThisTask(scrollDedupeKey)) return;\n handlers.fireGoal();\n };\n const checkComposite = (idx: number, viaScroll = false): void => {\n remaining.delete(idx);\n if (remaining.size !== 0) return;\n if (viaScroll) fireViaScroll();\n else handlers.fireGoal();\n };\n\n const cleanups: Array<() => void> = [];\n\n subgoals.forEach((sub, idx) => {\n if (sub.type === 'click') {\n const onClick = (e: Event): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else handlers.fireGoal();\n };\n node.addEventListener('click', onClick);\n cleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else handlers.fireGoal();\n };\n node.addEventListener('submit', onSubmit);\n cleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n if (goal.type === 'composite') checkComposite(idx, true);\n else fireViaScroll();\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n cleanups.push(() => io.disconnect());\n return;\n }\n });\n\n return () => {\n for (const c of cleanups) c();\n };\n}\n\n/**\n * Funnel declaration (spec §7.4): one steps-declaration per funnel per page\n * load; membership is per component and idempotent server-side, so re-sends\n * are harmless but avoided. Only a weighted_composite carries steps — a plain\n * goal declares membership only (the funnel must exist server-side already).\n */\nconst declaredFunnels = new Set<string>();\nconst declaredMemberships = new Set<string>();\n\n/** Test-only: clears the page-load dedup sets. */\nexport function __resetFunnelDeclarations(): void {\n declaredFunnels.clear();\n declaredMemberships.clear();\n}\n\n/**\n * The funnel a weighted composite declares when no `funnel` prop names one.\n * Composites and funnels are one model: without this, a composite on its own\n * was credited the SUM of its steps' weights while the same steps under a\n * `funnel` prop earned the furthest step reached — two rewards for one\n * journey, picked by whether a prop was present. Deterministic from the\n * component id so every page and visit lands on the same funnel; the\n * `-steps` suffix keeps it off ids a human is likely to author (a human funnel\n * with the id would otherwise absorb the component as a member).\n */\nexport function compositeFunnelId(componentId: string): string {\n const slug = componentId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 100);\n // A lossy slug (\"Hero CTA\" and \"hero_cta\" both → \"hero-cta\") gets a short\n // hash of the raw id so two components never share one funnel.\n if (slug && slug === componentId) return `${slug}-steps`;\n let h = 5381;\n for (let i = 0; i < componentId.length; i++) h = ((h << 5) + h + componentId.charCodeAt(i)) >>> 0;\n return `${slug || 'component'}-${h.toString(36)}-steps`;\n}\n\nconst MAX_FUNNEL_STEPS = 12;\n\n/**\n * A composite's steps as a funnel declaration the server will ACCEPT\n * (funnel-declare parseSteps + validateFunnelSteps). A rejected declaration is\n * silent and leaves the component off the funnel, back on the summed-steps\n * reward — so instead of sending something invalid: weights clamp to [0, 1];\n * a repeated name, a name the server can't take as a goal id (empty, > 128,\n * the reserved `funnel:` prefix) and anything past 12 steps are skipped.\n *\n * Steps are then ORDERED BY WEIGHT, lowest first. A composite's steps were\n * never ordered — each was credited on its own and summed — so the weight is\n * the only statement of which step matters most. Keeping the listed order made\n * a low-value step listed last the funnel's completion (full credit) and the\n * real conversion an intermediate step: the objective, inverted. The sort is\n * stable, so equal weights keep their listed order. Dev builds say when any of\n * this changed what was written.\n */\nexport function compositeFunnelSteps(componentId: string, goal: WeightedCompositeGoal): Array<{ goalId: string; weight: number }> {\n const seen = new Set<string>();\n const steps: Array<{ goalId: string; weight: number }> = [];\n for (const s of goal.steps) {\n const n = s.name;\n if (!n || n.length > 128 || n.startsWith('funnel:') || seen.has(n) || steps.length === MAX_FUNNEL_STEPS) continue;\n seen.add(n);\n steps.push({ goalId: n, weight: Math.min(1, Math.max(0, s.weight || 0)) });\n }\n const ordered = [...steps].sort((a, b) => a.weight - b.weight);\n // Bundle budget: one message for every adjustment, not one per kind.\n if ((steps.length < goal.steps.length || ordered.some((s, i) => s !== steps[i])) && isDevBuild()) {\n console.warn(`[SentientUI] \"${componentId}\": weighted_composite steps adjusted for its funnel (skipped invalid/repeated/over-12 steps, or ordered by weight)`);\n }\n return ordered;\n}\n\n/**\n * Declares the component's funnel: the explicit `funnel` prop, else — for a\n * weighted composite — its own derived funnel (compositeFunnelId). Anything\n * else declares nothing.\n */\nexport function maybeDeclareFunnel(\n client: SentientClient,\n apiKey: string,\n componentId: string,\n explicitFunnelId: string | undefined,\n goal: GoalConfig | null,\n): void {\n const composite = goal?.type === 'weighted_composite' ? goal : null;\n const funnelId = explicitFunnelId ?? (composite ? compositeFunnelId(componentId) : undefined);\n if (!funnelId) return;\n const memberKey = `${funnelId}|${componentId}`;\n if (declaredMemberships.has(memberKey)) return;\n declaredMemberships.add(memberKey);\n // Counted AFTER cleaning: a composite whose steps dedupe to one is a single\n // goal, not a funnel (the server needs 2+, and rejecting it would leave the\n // component on the summed rule).\n const steps = composite && !declaredFunnels.has(funnelId) ? compositeFunnelSteps(componentId, composite) : null;\n const withSteps = steps !== null && steps.length >= 2;\n if (withSteps) declaredFunnels.add(funnelId);\n if (!withSteps && explicitFunnelId === undefined) return; // nothing a derived funnel could join\n client.track({\n projectId: apiKey,\n componentId,\n eventType: 'funnel_declared',\n payload: withSteps ? { funnelId, steps } : { funnelId },\n });\n}\n\n/**\n * Records the `variant_assigned` exposure event.\n */\nexport function trackExposure(\n client: SentientClient,\n apiKey: string,\n componentId: string,\n variantId: string,\n): void {\n client.track({\n projectId: apiKey,\n componentId,\n variantId,\n eventType: 'variant_assigned',\n payload: {},\n });\n}\n","import { isDevBuild } from './adaptive-shared.js';\n\nexport type RegisteredComponent = { id: string; variantIds: string[]; goal?: string };\nexport type RegisteredSlot = {\n id: string;\n arms?: string[];\n dims?: Record<string, readonly string[]>;\n};\n\ntype RegistryState = {\n components: Map<string, RegisteredComponent>;\n slots: Map<string, RegisteredSlot>;\n sections: string[];\n listeners: Set<() => void>;\n /** Bumped on every mutation so `useSyncExternalStore` can read a stable, comparable snapshot. */\n version: number;\n};\n\n// Shared through a window global: the main entry and the /devtools entry are\n// separate bundles, each with its own copy of this module — module-local\n// state would give the devtools an always-empty registry in published apps.\nconst ssrFallback: RegistryState = {\n components: new Map(),\n slots: new Map(),\n sections: [],\n listeners: new Set(),\n version: 0,\n};\n\nfunction state(): RegistryState {\n if (typeof window === 'undefined') return ssrFallback;\n const w = window as unknown as { __sentient_registry?: RegistryState };\n if (!w.__sentient_registry) {\n w.__sentient_registry = {\n components: new Map(),\n slots: new Map(),\n sections: [],\n listeners: new Set(),\n version: 0,\n };\n }\n return w.__sentient_registry;\n}\n\nfunction emit(): void {\n // Bump BEFORE notifying so a useSyncExternalStore consumer re-reading its\n // snapshot inside the notification sees the new value and re-renders.\n state().version += 1;\n for (const fn of state().listeners) fn();\n}\n\n// The registry exists solely to feed the opt-in devtools panel, which is a\n// dev-only surface. In a production build there is no panel reading it, so\n// every register call is dead work plus a `window.__sentient_registry`\n// footprint on the customer's page. Short-circuit to a noop in production —\n// every <Adaptive>/useAdaptive/slot mount calls one of these.\nconst NOOP_UNREGISTER = (): void => undefined;\n\n/** Register (or re-register) a component. Returns an unregister function. */\nexport function registerComponent(c: RegisteredComponent): () => void {\n if (!isDevBuild()) return NOOP_UNREGISTER;\n state().components.set(c.id, c);\n emit();\n return () => {\n state().components.delete(c.id);\n emit();\n };\n}\n\n/** Register (or re-register) a slot declaration. Returns an unregister function. */\nexport function registerSlot(s: RegisteredSlot): () => void {\n if (!isDevBuild()) return NOOP_UNREGISTER;\n state().slots.set(s.id, s);\n emit();\n return () => {\n state().slots.delete(s.id);\n emit();\n };\n}\n\n/** Register the page's declared section ids (from AdaptiveRoot/provider). */\nexport function registerSections(sections: string[]): void {\n if (!isDevBuild()) return;\n state().sections = [...sections];\n emit();\n}\n\nexport function getRegistered(): RegisteredComponent[] {\n return [...state().components.values()];\n}\n\nexport function getRegisteredSlots(): RegisteredSlot[] {\n return [...state().slots.values()];\n}\n\nexport function getRegisteredSections(): string[] {\n return [...state().sections];\n}\n\nexport function subscribeRegistry(fn: () => void): () => void {\n const listeners = state().listeners;\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/** Monotonic snapshot for `useSyncExternalStore` — changes on every registry mutation. */\nexport function getRegistryVersion(): number {\n return state().version;\n}\n","/**\n * This package's released build version, injected by tsup's `define` from\n * package.json (see tsup.config.ts) so the version inside a published bundle\n * can never drift from the version on npm. Mirrors the snippet's\n * `__SNIPPET_VERSION__`.\n *\n * Why the React SDK reports a version at all: unlike the snippet, it is a\n * build-time npm dependency, so it CANNOT self-update — a customer on an old\n * release stays there until they run an install. Telling them they're behind is\n * the only remedy available, and the dashboard can only tell them if the\n * running bundle says what it is.\n */\ndeclare const __REACT_SDK_VERSION__: string;\n\nexport const version: string =\n typeof __REACT_SDK_VERSION__ !== 'undefined' ? __REACT_SDK_VERSION__ : '0.0.0-dev';\n\n/**\n * The identity handed to core's session upsert, or undefined for a dev build.\n * The '0.0.0-dev' sentinel (unit tests, or any build without tsup's define)\n * passes the server's semver validation and would be persisted as the\n * project's SDK version, leaving the dashboard permanently claiming the\n * project is behind — the same trap the snippet documents as audit M12.\n */\nexport const SDK_IDENT: { name: string; version: string } | undefined =\n version !== '0.0.0-dev' ? { name: 'react', version } : undefined;\n","import type { SlotConfigEntry, StyleVocabulary } from '@sentientui/core';\n\n/**\n * Slot-CONFIG override store — the channel `useSlotConfig` reads (AdaptiveSlot).\n * Separate from `__sentient_slot_overrides` (which forces the slot RESULT — the\n * arm): forcing an arm alone can't test AdaptiveSlot's rendering, because the\n * content/blocks live in the config entry. Window-backed so the /devtools and\n * /testing bundles and the main bundle share one store.\n */\nfunction store(): Record<string, SlotConfigEntry> {\n const w = window as unknown as { __sentient_slot_config_overrides?: Record<string, SlotConfigEntry> };\n if (!w.__sentient_slot_config_overrides) w.__sentient_slot_config_overrides = {};\n return w.__sentient_slot_config_overrides;\n}\n\n/** Force `slotId`'s config entry — read by `useSlotConfig`. */\nexport function setSlotConfigOverride(slotId: string, entry: SlotConfigEntry): void {\n store()[slotId] = entry;\n}\n\n/** Site styles for forced configs (the on-site preview of a redesigned\n * section): the decision that would normally carry them never ran. */\nexport function setVocabularyOverride(v: StyleVocabulary | null): void {\n (window as unknown as { __sentient_vocabulary_override?: StyleVocabulary | null }).__sentient_vocabulary_override = v;\n}\n\nexport function getVocabularyOverride(): StyleVocabulary | null {\n if (typeof window === 'undefined') return null;\n return (window as unknown as { __sentient_vocabulary_override?: StyleVocabulary | null }).__sentient_vocabulary_override ?? null;\n}\n\nexport function clearSlotConfigOverride(slotId: string): void {\n delete store()[slotId];\n}\n\nexport function getSlotConfigOverrides(): Record<string, SlotConfigEntry> {\n return { ...store() };\n}\n","import type { SlotResult } from '@sentientui/core';\n\n/**\n * Slot-override store — the channel `useSlotResult` reads (`useAdaptiveTokens` /\n * `AdaptiveGroup`). Separate from `__sentient_overrides` (variant components):\n * a slot result is a token object (`{ tone: 'urgent' }`) or an arm string\n * (`'social_first'`), never a bare variant id. Window-backed so the /devtools\n * bundle and the main bundle share one store.\n */\nfunction store(): Record<string, SlotResult> {\n const w = window as unknown as { __sentient_slot_overrides?: Record<string, SlotResult> };\n if (!w.__sentient_slot_overrides) w.__sentient_slot_overrides = {};\n return w.__sentient_slot_overrides;\n}\n\n/** Force `slotId` to resolve to `result` — read by `useSlotResult`. */\nexport function setSlotOverride(slotId: string, result: SlotResult): void {\n store()[slotId] = result;\n}\n\nexport function clearSlotOverride(slotId: string): void {\n delete store()[slotId];\n}\n\nexport function getSlotOverrides(): Record<string, SlotResult> {\n return { ...store() };\n}\n","// Credentials the dashboard hands the site (`sentient_preview_token`, the\n// editor's one-time `sentient_editor_code`) ride the URL FRAGMENT, which is\n// never sent over the network — no server/CDN log, no Referer (grades C13, E1).\n//\n// The fragment is also where hash-routed sites keep their route (grade E2).\n// The first version wrote `#sentient_preview_token=…` over the whole hash, so a\n// preview of `/#/pricing` opened the home route instead. The dashboard now\n// APPENDS the param (appendHashParam in apps/dashboard/app/lib/hash-param.ts):\n// '' → #name=v\n// '/pricing' → #/pricing?name=v (routers read it as a query param, so\n// '/p?x=1' → #/p?x=1&name=v the route still matches pre-strip)\n// and this takes it back out, restoring the site's own hash EXACTLY — or\n// removing the '#' altogether when the site had none. Twin of\n// packages/snippet/src/hash-param.ts (the snippet cannot import this package\n// and vice versa); keep the two in step — both suites run the same cases.\nexport function takeHashParam(name: string): string | null {\n let v: string | null = null;\n try {\n const h = location.hash.slice(1);\n const m = RegExp('(^|[?&])' + name + '=([^&]*)').exec(h);\n if (m) {\n // Taken BEFORE the rewrite: an opaque-origin frame may refuse\n // replaceState, and the value is still ours to use. Base64url, so no\n // decoding (the dashboard never percent-encodes it).\n v = m[2]!;\n let after = h.slice(m.index + m[0].length);\n // '?name=v&rest' / 'name=v&rest': the next param inherits the separator.\n if (m[1] != '&' && after[0] == '&') after = m[1] + after.slice(1);\n const rest = h.slice(0, m.index) + after;\n // replaceState, not location.hash=: no hashchange, so a hash router does\n // not re-route mid-boot; history.state kept so its entry key survives.\n history.replaceState(history.state, '', rest ? '#' + rest : location.pathname + location.search);\n }\n } catch {\n /* fail-safe */\n }\n return v;\n}\n","// The operator's editor session on a React site (dashboard \"Preview on your\n// site\", \"Refresh from page\", style capture). The dashboard sends a one-time\n// code in the URL FRAGMENT (#sentient_editor_code=, grade E1) — never the\n// token itself, which as `?sentient_editor=` reached server/CDN logs,\n// analytics page URLs and Referer headers, and can publish. This trades the\n// code for the token (POST /v1/editor/exchange; the API checks the Origin is\n// the project's own) and keeps the token in sessionStorage only.\n//\n// Memoised: cell preview, region refresh and style capture all ask, but the\n// code is single use — a second exchange would be refused and whichever\n// caller lost the race would report an \"expired\" link that was fine.\nimport { takeHashParam } from './hash-param.js';\n\n// Same key as the snippet's cache, so both SDKs agree on \"this tab is in an\n// editor session\" if a page ever carries both.\nconst TOKEN_KEY = '__snt_editor_token';\n\nexport type EditorSession = { token: string; fresh: boolean };\ntype Outcome = EditorSession | { error: number } | null;\n\nlet pending: Promise<Outcome> | null = null;\nlet active = false;\n\n/** Synchronous: did editorSession() find a code or a cached token? Lets a\n * caller refuse to act on a bare URL param (a visitor, not an operator)\n * without waiting for the exchange — the old token-in-query check was sync. */\nexport function editorSessionActive(): boolean {\n return active;\n}\n\nfunction cached(): string | null {\n try {\n return sessionStorage.getItem(TOKEN_KEY);\n } catch {\n return null;\n }\n}\n\n/**\n * The editor token for this page view: exchanged from a fresh fragment code\n * (`fresh: true`), else the one cached earlier in this tab. `{ error }` is a\n * refused exchange (401 = expired/used, anything else = couldn't load); null\n * means this is not an editor session at all.\n */\nexport function editorSession(apiBase: string): Promise<Outcome> {\n if (pending) return pending;\n const code = typeof window === 'undefined' ? null : takeHashParam('sentient_editor_code');\n if (!code) {\n const t = typeof window === 'undefined' ? null : cached();\n active = !!t;\n pending = Promise.resolve(t ? { token: t, fresh: false } : null);\n return pending;\n }\n active = true;\n pending = fetch(`${apiBase}/editor/exchange`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ code }),\n })\n .then(async (res): Promise<Outcome> => {\n const token = res.ok ? ((await res.json()) as { token?: string }).token : undefined;\n if (!token) return { error: res.ok ? 500 : res.status };\n try {\n sessionStorage.setItem(TOKEN_KEY, token);\n } catch {\n /* the session still works for this page view */\n }\n return { token, fresh: true };\n })\n .catch((): Outcome => ({ error: 0 }));\n return pending;\n}\n\n/** End the session (Exit preview): a reload is a normal visit again. */\nexport function endEditorSession(): void {\n try {\n sessionStorage.removeItem(TOKEN_KEY);\n } catch {\n /* fail-safe */\n }\n}\n\n/** Test hook. */\nexport function resetEditorSessionForTests(): void {\n pending = null;\n active = false;\n}\n","// On-site preview for generated versions (the dashboard's \"Preview on your\n// site\" link): ?sentient_preview_cell=<slotId>~<persona>#sentient_editor_code=…\n// (a one-time code exchanged for the editor token — editor-session.ts, E1)\n// fetches the square's PENDING (review) or live arm through the editor-token\n// API and forces it through the devtools override channel — which AdaptiveSlot\n// already renders IN PLACE, with the page's real CSS, and WITHOUT recording an\n// exposure ('override' source is excluded from tracking by design). A floating\n// bar names what is being previewed and offers Exit.\n//\n// Deliberately framework-light: the bar is plain DOM (no React tree to mount\n// into), and everything no-ops without both params, so normal visitors pay\n// one URLSearchParams read.\nimport { setSlotConfigOverride, setVocabularyOverride } from './devtools-slot-config-overrides.js';\nimport { setSlotOverride } from './devtools-slot-overrides.js';\nimport { notifyOverridesChanged } from './override-events.js';\nimport { editorSession, editorSessionActive, endEditorSession } from './editor-session.js';\nimport type { ComposeArm, StyleVocabulary } from '@sentientui/core';\n\nconst PARAM_CELL = 'sentient_preview_cell';\nconst PARAM_REFRESH = 'sentient_refresh_region';\nconst BAR_ID = 'sentient-cell-preview-bar';\nconst PREVIEW_ARM = '__preview__';\n\ntype CellPreviewResponse = {\n status: 'review' | 'live';\n slotName: string;\n personaDisplay: string;\n content: string | null;\n blocks: unknown | null;\n edits?: unknown;\n skeletonFp?: string;\n leafToNode?: number[];\n compose?: unknown;\n vocabulary?: StyleVocabulary;\n};\n\n// \"Refresh from page\" (spec 2026-09-23 §4.2): the operator says the region\n// changed. The capture runs INSIDE the AdaptiveSlot — only it holds the\n// children the element-tree parity check needs — so this module just forces\n// the original to show and leaves the request here for the slot to take.\n// `session` is a promise: the token arrives by exchange after this module ran,\n// but the slot's capture effect may run first and only once — holding the\n// promise lets it take the request now and post when the token lands.\ntype RegionRefresh = { slotId: string; session: ReturnType<typeof editorSession>; base: string };\nlet pendingRefresh: RegionRefresh | null = null;\n\n/** The refresh this page was opened for, if it targets `slotId`. Taken once. */\nexport function takeRegionRefresh(slotId: string): RegionRefresh | null {\n if (pendingRefresh?.slotId !== slotId) return null;\n const r = pendingRefresh;\n pendingRefresh = null;\n return r;\n}\n\n/** Post a trusted skeleton and tell the operator how it went. */\nexport function submitRegionRefresh(r: RegionRefresh, body: Record<string, unknown>): void {\n void r.session\n .then((s) => {\n if (!s || !('token' in s)) throw new Error('no editor session');\n return fetch(`${r.base}/editor/region-skeleton`, {\n method: 'POST',\n headers: { authorization: `Bearer ${s.token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ slotId: r.slotId, ...body }),\n });\n })\n .then((res) =>\n mountBar(res.ok ? 'Region refreshed — you can regenerate its versions now.' : 'Couldn’t refresh this region — reopen the link from your dashboard.'),\n )\n .catch(() => mountBar('Couldn’t refresh this region — check your connection and reopen the link from your dashboard.'));\n}\n\n/** Start the on-site cell preview when the URL asks for one. Idempotent. */\nexport function maybeStartCellPreview(apiBaseUrl?: string): void {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n if (document.getElementById(BAR_ID)) return;\n let cell: string | null;\n let refresh: string | null;\n try {\n const params = new URLSearchParams(window.location.search);\n cell = params.get(PARAM_CELL);\n refresh = params.get(PARAM_REFRESH);\n } catch {\n return;\n }\n if (!cell && !refresh) return;\n const base = (apiBaseUrl ?? 'https://api.sentient-ui.com/v1').replace(/\\/$/, '');\n const session = editorSession(base);\n // Only an operator's session acts on these params; a visitor who lands on a\n // shared ?sentient_refresh_region= URL gets the normal page.\n if (!editorSessionActive()) return;\n if (refresh) {\n pendingRefresh = { slotId: refresh, session, base };\n // Force the original: a served version on screen is not the region.\n // 'override' records no exposure, so the refresh visit is never a trial.\n setSlotConfigOverride(refresh, { kind: 'arms' });\n setSlotOverride(refresh, PREVIEW_ARM);\n notifyOverridesChanged();\n return;\n }\n if (!cell) return;\n const sep = cell.lastIndexOf('~');\n if (sep <= 0) return;\n const slotId = cell.slice(0, sep);\n const persona = cell.slice(sep + 1);\n\n void session\n .then((s) => {\n // No code and nothing cached: a bare param, not an editor session.\n if (!s) return null;\n if (!('token' in s)) {\n mountBar(s.error === 401\n ? 'This preview link has expired — reopen it from your dashboard.'\n : 'Couldn’t load this preview — reopen it from your dashboard.');\n return null;\n }\n return fetch(`${base}/editor/cell-preview?slotId=${encodeURIComponent(slotId)}&persona=${encodeURIComponent(persona)}`, {\n headers: { authorization: `Bearer ${s.token}` },\n });\n })\n .then(async (res) => {\n if (!res) return;\n if (!res.ok) {\n mountBar(res.status === 401\n ? 'This preview link has expired — reopen it from your dashboard.'\n : 'Couldn’t load this preview — reopen it from your dashboard.');\n return;\n }\n const data = (await res.json()) as CellPreviewResponse;\n if (data.vocabulary && Array.isArray(data.vocabulary.entries)) setVocabularyOverride(data.vocabulary);\n if (data.compose != null) {\n setSlotConfigOverride(slotId, { kind: 'arms', compose: { [PREVIEW_ARM]: data.compose as ComposeArm } });\n setSlotOverride(slotId, PREVIEW_ARM);\n } else if (data.edits != null && typeof data.skeletonFp === 'string' && Array.isArray(data.leafToNode)) {\n setSlotConfigOverride(slotId, { kind: 'arms', edits: { edits: data.edits as never, fp: data.skeletonFp, leafToNode: data.leafToNode } });\n setSlotOverride(slotId, PREVIEW_ARM);\n } else if (data.blocks != null) {\n setSlotConfigOverride(slotId, { kind: 'arms', blocks: { [PREVIEW_ARM]: data.blocks } } as never);\n setSlotOverride(slotId, PREVIEW_ARM);\n } else if (data.content != null) {\n setSlotConfigOverride(slotId, { kind: 'arms', content: data.content });\n setSlotOverride(slotId, PREVIEW_ARM);\n } else {\n mountBar('Nothing to preview in that square yet.');\n return;\n }\n notifyOverridesChanged();\n mountBar(\n `Previewing “${data.slotName}” for ${data.personaDisplay}${data.status === 'review' ? ' — waiting for your approval' : ''}. Nothing is being tracked.`,\n );\n // Bring the slot into view once it re-renders with the forced arm.\n setTimeout(() => {\n try {\n document.querySelector(`[data-sentient-slot=\"${slotId}\"]`)?.scrollIntoView({ block: 'center' });\n } catch {\n /* older browsers */\n }\n }, 300);\n })\n .catch(() => mountBar('Couldn’t load this preview — check your connection and reopen it from your dashboard.'));\n}\n\nfunction mountBar(text: string): void {\n if (document.getElementById(BAR_ID)) return;\n const bar = document.createElement('div');\n bar.id = BAR_ID;\n Object.assign(bar.style, {\n position: 'fixed', bottom: '16px', left: '50%', transform: 'translateX(-50%)', zIndex: '2147483647',\n display: 'flex', alignItems: 'center', gap: '10px', padding: '10px 14px', borderRadius: '12px',\n maxWidth: '90vw', background: '#111827', color: '#fff', font: '13px system-ui, sans-serif',\n border: '1px solid rgba(139,92,246,0.6)', boxShadow: '0 10px 34px rgba(0,0,0,0.45)',\n } satisfies Partial<CSSStyleDeclaration>);\n const label = document.createElement('span');\n label.textContent = text;\n const exit = document.createElement('button');\n exit.textContent = 'Exit preview';\n Object.assign(exit.style, {\n padding: '4px 10px', borderRadius: '999px', border: '1px solid rgba(255,255,255,0.35)',\n background: 'transparent', color: '#fff', font: '12px system-ui, sans-serif', cursor: 'pointer',\n } satisfies Partial<CSSStyleDeclaration>);\n exit.onclick = () => {\n endEditorSession();\n const url = new URL(window.location.href);\n url.searchParams.delete(PARAM_CELL);\n url.searchParams.delete(PARAM_REFRESH);\n window.location.assign(url.toString());\n };\n bar.append(label, exit);\n (document.body ?? document.documentElement).append(bar);\n}\n","// Style-vocabulary capture for React installs (native generation phase 2).\n// React sites never load the snippet editor, so without this a React project\n// (Bodyshop) would only ever get the crawler's colorless guess. Runs ONLY when\n// this page load exchanged a fresh editor code (#sentient_editor_code=, see\n// editor-session.ts), i.e. when an operator opened the page from the dashboard\n// — never for visitors, and not on every later page of a cached session. The\n// sampler is a separate core subpath, dynamically imported, so the normal\n// bundle pays nothing.\nimport { editorSession, resetEditorSessionForTests } from './editor-session.js';\n\nlet started = false;\n\nexport function maybeCaptureStyles(apiBaseUrl?: string): void {\n if (started || typeof window === 'undefined') return;\n started = true;\n const base = (apiBaseUrl ?? 'https://api.sentient-ui.com/v1').replace(/\\/$/, '');\n void editorSession(base).then((session) => {\n if (!session || !('token' in session) || !session.fresh) return;\n capture(base, session.token);\n });\n}\n\nfunction capture(base: string, token: string): void {\n // After load + 1s, so client-rendered heroes exist before we look.\n const run = (): void => {\n window.setTimeout(() => {\n void import('@sentientui/core/style-sample')\n .then(({ sampleStyleVocabulary }) =>\n fetch(`${base}/editor/style-vocabulary`, {\n method: 'POST',\n headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },\n body: JSON.stringify(sampleStyleVocabulary(document)),\n }),\n )\n .catch(() => undefined);\n }, 1000);\n };\n if (document.readyState === 'complete') run();\n else window.addEventListener('load', run, { once: true });\n}\n\n/** Test hook. */\nexport function resetStyleCaptureForTests(): void {\n started = false;\n resetEditorSessionForTests();\n}\n","import { notifyOverridesChanged } from '../override-events.js';\n\nexport type ScenarioWeight = { variantId: string; pulls: number; avgReward: number };\nexport type ScenarioApiOverride =\n | 'error'\n | number\n | { status?: number; body?: unknown; delayMs?: number };\n\nexport type SentientScenario = {\n variants?: Record<string, string>;\n layout?: string[];\n /** Forced persona key (any project vocabulary key). Also sets the persona html attributes. */\n persona?: string;\n /** Persona confidence 0–1; buckets to low/medium/high for the html attribute. Default 1. */\n confidence?: number;\n /** Forced slot results: slot id → arm id (arms slots) or per-dim values (token slots). */\n slots?: Record<string, string | Record<string, string>>;\n /** Forced registry slot config (AdaptiveSlot content/blocks): slot id → entry.\n * Pair with `slots` to name which arm is \"served\" (blocks are keyed by arm). */\n slotConfig?: Record<string, unknown>;\n weights?: Record<string, ScenarioWeight[]>;\n api?: Record<string, ScenarioApiOverride>;\n};\n\ntype ScenarioWindow = {\n __sentient_overrides?: Record<string, string>;\n __sentient_layout_override?: string[];\n __sentient_slot_overrides?: Record<string, string | Record<string, string>>;\n __sentient_slot_config_overrides?: Record<string, unknown>;\n __sentient_persona_override?: { persona: string; confidence?: number };\n};\n\n/**\n * Confidence → band. Cutoffs pinned to @sentientui/policy `confidenceBand`\n * (<0.3 low, <0.7 medium, else high). Duplicated (not imported) because the\n * Playwright init function is serialized into the page and cannot close\n * over imports — both copies are pinned by tests.\n */\nexport function confidenceBandOf(c: number): 'low' | 'medium' | 'high' {\n return c < 0.3 ? 'low' : c < 0.7 ? 'medium' : 'high';\n}\n\n/** Apply a scenario by setting the client-forcing globals the SDK reads. */\nexport function applyScenario(scenario: SentientScenario = {}): void {\n const w = window as unknown as ScenarioWindow;\n w.__sentient_overrides = { ...(scenario.variants ?? {}) };\n if (scenario.layout) w.__sentient_layout_override = scenario.layout;\n else delete w.__sentient_layout_override;\n if (scenario.slots) w.__sentient_slot_overrides = { ...scenario.slots };\n else delete w.__sentient_slot_overrides;\n if (scenario.slotConfig) w.__sentient_slot_config_overrides = { ...scenario.slotConfig };\n else delete w.__sentient_slot_config_overrides;\n if (scenario.persona) {\n w.__sentient_persona_override = {\n persona: scenario.persona,\n confidence: scenario.confidence ?? 1,\n };\n try {\n const d = document.documentElement;\n d.setAttribute('data-sentient-persona', scenario.persona);\n d.setAttribute('data-sentient-confidence', confidenceBandOf(scenario.confidence ?? 1));\n } catch {\n /* no DOM (node env) — the override globals still apply */\n }\n } else {\n delete w.__sentient_persona_override;\n }\n // Ring the override bus so hooks already mounted (useAssignment /\n // useSlotResult / useAdaptivePersona subscribe via useSyncExternalStore)\n // re-render immediately — otherwise forcing state mid-test only takes effect\n // on the next unrelated render.\n notifyOverridesChanged();\n}\n\n/** Clear all forced state. */\nexport function resetScenario(): void {\n const w = window as unknown as ScenarioWindow;\n delete w.__sentient_overrides;\n delete w.__sentient_layout_override;\n delete w.__sentient_slot_overrides;\n delete w.__sentient_slot_config_overrides;\n delete w.__sentient_persona_override;\n try {\n document.documentElement.removeAttribute('data-sentient-persona');\n document.documentElement.removeAttribute('data-sentient-confidence');\n } catch {\n /* no DOM */\n }\n notifyOverridesChanged();\n}\n"],"mappings":";66BAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,wBAAAE,KAAA,eAAAC,GAAAH,IAMA,IAAAI,GAA8D,kCCA9D,IAAAC,EAUO,iBACPC,EAWO,4BCZP,IAAMC,GAAQ,IAAI,IACZC,GAAY,IAAI,IAuBf,SAASC,G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ASC,GACdC,EACAC,EAA6B,CAAC,EAC9BC,EACc,CACd,OAAAC,GAAcF,CAAQ,KACf,cACL,QAACG,GAAA,CAAiB,OAAO,UAAU,QAAS,GACzC,SAAAJ,EACH,EACAE,CACF,CACF","names":["react_exports","__export","renderWithSentient","__toCommonJS","import_react","import_react","import_core","store","listeners","update","componentId","weights","store","set","listeners","cb","e","ssrFallback","state","w","setPreviewMode","on","s","fn","getPreviewMode","subscribePreview","listeners","createPreviewClient","inner","componentId","segment","_a","_b","variantIds","agentData","agentDataByVariant","opts","slotId","ids","EVENT","notifyOverridesChanged","_a","w","EVENT","publishDevtoolsConfig","config","isDevBuild","_a","ssrFallback","state","w","emit","fn","registerSections","sections","isDevBuild","state","emit","version","SDK_IDENT","store","w","setSlotConfigOverride","slotId","entry","setVocabularyOverride","v","store","w","setSlotOverride","slotId","result","takeHashParam","name","v","h","m","after","rest","e","TOKEN_KEY","pending","active","editorSessionActive","cached","editorSession","apiBase","code","takeHashParam","t","res","token","e","endEditorSession","PARAM_CELL","PARAM_REFRESH","BAR_ID","PREVIEW_ARM","pendingRefresh","maybeStartCellPreview","apiBaseUrl","BAR_ID","cell","refresh","params","PARAM_CELL","PARAM_REFRESH","e","base","session","editorSession","editorSessionActive","pendingRefresh","setSlotConfigOverride","setSlotOverride","PREVIEW_ARM","notifyOverridesChanged","sep","slotId","persona","s","mountBar","res","data","setVocabularyOverride","_a","text","bar","label","exit","endEditorSession","url","started","maybeCaptureStyles","apiBaseUrl","base","editorSession","session","capture","token","run","sampleStyleVocabulary","import_jsx_runtime","deriveDefaultSegment","_a","_b","e","DEFAULT_API_BASE_URL","AdaptiveContext","warnedNoConsentGate","answeredThisPage","useConsentSource","source","apiKey","onRefused","onRefusedRef","granted","setGranted","refused","setRefused","sourceRef","key","__spreadProps","__spreadValues","s","stop","cancelled","consentWatcher","forgetVisitor","watcher","wasRefused","update","r","g","AdaptiveProvider","props","_c","_d","_e","_f","client","setClient","sessionSegment","previewOn","setPreviewOn","getPreviewMode","subscribePreview","maybeStartCellPreview","setPreviewMode","m","maybeCaptureStyles","dropHeldRef","consent","forgetOnFalse","forgetRef","clientRef","trackingRef","heldRef","refusedRef","c","tracking","adopt","config","SDK_IDENT","created","stopEngagement","handOff","call","startEngagement","startEngagementCapture","initGraph","poll","entries","entry","weights","v","timerId","ssrFallback","apiBaseUrl","frozenConfigRef","current","prev","publishDevtoolsConfig","identityUser","identityHash","identityEmail","decided","registerSections","isDevBuild","declared","present","el","missing","id","exposedClient","createPreviewClient","value","_g","_h","_i","NO_UNIFIED","NO_UNIFIED","confidenceBandOf","c","applyScenario","scenario","_a","_b","_c","w","__spreadValues","e","notifyOverridesChanged","import_jsx_runtime","renderWithSentient","ui","scenario","options","applyScenario","AdaptiveProvider"]}
1
+ {"version":3,"sources":["../../src/testing/react.tsx","../../src/provider.tsx","../../src/weights-store.ts","../../src/preview-mode.ts","../../src/override-events.ts","../../src/devtools-config.ts","../../src/dev-build.ts","../../src/devtools-registry.ts","../../src/sdk-version.ts","../../src/devtools-slot-config-overrides.ts","../../src/devtools-slot-overrides.ts","../../src/hash-param.ts","../../src/editor-session.ts","../../src/cell-preview.ts","../../src/style-capture.ts","../../src/testing/scenario.ts"],"sourcesContent":["// RTL-dependent helper behind its own subpath (`@sentientui/react/testing/react`):\n// @testing-library/react is an OPTIONAL peer, so importing it at the top of the\n// main /testing entry crashed any consumer without it installed the moment they\n// imported ANY testing helper — same split as /testing/node (msw/node) and\n// /testing/msw (msw).\nimport type { ReactElement } from 'react';\nimport { render, type RenderOptions, type RenderResult } from '@testing-library/react';\nimport { AdaptiveProvider } from '../provider.js';\nimport { applyScenario, type SentientScenario } from './scenario.js';\n\n/**\n * Render `ui` under a SentientUI provider configured for tests: consent is off,\n * so the SDK never initialises a client and every <Adaptive> renders its control\n * variant with zero network. A scenario forces specific variants/layout.\n */\nexport function renderWithSentient(\n ui: ReactElement,\n scenario: SentientScenario = {},\n options?: RenderOptions,\n): RenderResult {\n applyScenario(scenario);\n return render(\n <AdaptiveProvider apiKey=\"pk_test\" consent={false}>\n {ui}\n </AdaptiveProvider>,\n options,\n );\n}\n","'use client';\n\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n type JSX,\n type ReactNode,\n} from 'react';\nimport {\n deriveSessionSegment,\n init,\n type ConsentSource,\n type SentientClient,\n type SentientConfig,\n type SitePalette,\n type SlotConfigEntry,\n type StyleVocabulary,\n type StageAttributes,\n type SlotResult,\n} from '@sentientui/core';\nimport type { SemanticType } from '@sentientui/core/engagement';\nimport { update as updateWeightsStore, type ComponentWeights } from './weights-store.js';\nimport { getPreviewMode, subscribePreview, createPreviewClient, setPreviewMode } from './preview-mode.js';\nimport { subscribeOverridesChanged } from './override-events.js';\nimport { publishDevtoolsConfig } from './devtools-config.js';\nimport { registerSections } from './devtools-registry.js';\nimport { isDevBuild } from './adaptive-shared.js';\nimport { SDK_IDENT } from './sdk-version.js';\nimport { maybeStartCellPreview } from './cell-preview.js';\nimport { maybeCaptureStyles } from './style-capture.js';\n\n/**\n * Feeds browser globals into core's `deriveSessionSegment` so the cache key\n * used by `useAssignment` always matches the key `assign()` writes under.\n * Before this, the context defaulted to 'desktop:direct' while core used the\n * detected segment — a systematic cache miss for every integration that\n * didn't pass `sessionSegment` explicitly. The derivation itself lives in\n * core (audit REACT-14): a hand-mirrored `${device}:${source}` copy here\n * drifted independently of the key core writes, which is the cache-miss bug\n * all over again, one refactor later.\n */\nfunction deriveDefaultSegment(): string {\n if (typeof window === 'undefined') return 'desktop:direct';\n try {\n return deriveSessionSegment({\n userAgent: navigator.userAgent ?? '',\n referer: document.referrer ?? '',\n appOrigin: window.location.origin,\n });\n } catch {\n return 'desktop:direct';\n }\n}\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\n/** How to render adaptive slots during SSR when assignments are not preloaded. */\nexport type SsrFallback = 'first' | 'none';\n\ntype AdaptiveContextValue = {\n client: SentientClient | null;\n // The publishable API key (pk_…). Historically named `projectId` because the\n // API uses it as the project identifier on the wire, but it is the API key,\n // not the project UUID. Field renamed for clarity.\n apiKey: string;\n initialAssignments: Record<string, string>;\n /** Components an SSR preload found moved onto the shared track. */\n initialUnified: readonly string[];\n sessionSegment: string;\n ssrFallback: SsrFallback;\n onAssignment: ((componentId: string, variantId: string) => void) | undefined;\n initialLayoutOrder: string[] | null;\n initialSlots: Record<string, SlotResult>;\n initialSlotConfig: Record<string, SlotConfigEntry>;\n initialPalette: SitePalette | null;\n initialVocabulary: StyleVocabulary | null;\n initialPersona: { persona: string; confidence: number } | null;\n apiBaseUrl: string;\n debug: boolean;\n};\n\nconst AdaptiveContext = createContext<AdaptiveContextValue>({\n client: null,\n apiKey: '',\n initialAssignments: {},\n initialUnified: [],\n sessionSegment: 'desktop:direct',\n ssrFallback: 'first',\n onAssignment: undefined,\n initialLayoutOrder: null,\n initialSlots: {},\n initialSlotConfig: {},\n initialPalette: null,\n initialVocabulary: null,\n initialPersona: null,\n apiBaseUrl: DEFAULT_API_BASE_URL,\n debug: false,\n});\n\nexport type AdaptiveProviderProps = {\n apiKey: string;\n /**\n * @deprecated Unused — the project's type is set in the dashboard. Safe to omit.\n * Still accepted (and forwarded to core, which ignores it) so existing code compiles.\n */\n context?: SentientConfig['context'];\n debug?: boolean;\n /**\n * SSR-preloaded assignments from `preloadAssignments()` / `loadAdaptiveAssignments()`.\n * Passed through to `useAssignment` as synchronous initial state so crawlers and\n * the first paint see real content (recommended for SEO).\n */\n initialAssignments?: Record<string, string>;\n /**\n * Component ids the SSR preload found moved onto the shared track (the\n * `unified` of `loadAdaptiveAssignments()` / `loadAdaptiveDecision()`;\n * `<AdaptiveRoot>` passes it for you). A variants-only `<Adaptive>` with one\n * of these ids renders on the shared track from the server HTML on, and an\n * assignment cached before the move is ignored.\n */\n initialUnified?: string[];\n /**\n * Bandit segment from SSR (`device:source`). Keeps cache, assign, and worker\n * weights on one row — must match `loadAdaptiveAssignments` / session upsert.\n */\n sessionSegment?: string;\n /**\n * @deprecated Use `clientOnly` on the component; the default behaviour renders\n * the first variant.\n *\n * When no `initialAssignments` exist for a component, `'first'` renders\n * `variantIds[0]` in server HTML (safe default for SEO); `'none'` renders\n * nothing until the client resolves. Still accepted with that exact behaviour\n * so existing trees don't change. Deprecated because it was a provider-wide\n * switch for a per-component decision (`clientOnly` already expresses it), and\n * it only ever reached `<Adaptive variants>` / `useAssignment` — `useAdaptive`\n * falls back to the first key regardless, and AdaptiveText, generated-version\n * `<Adaptive>` and slots never read it, so it read broader than it was.\n * @default 'first'\n */\n ssrFallback?: SsrFallback;\n /**\n * Consent gate. When `false` the SDK is not initialised and no events are\n * sent. Flip to `true` (e.g. after the user accepts the cookie banner) to\n * initialise and begin tracking.\n */\n consent?: boolean;\n /**\n * Where to read the visitor's consent decision from, so the SDK can gate and\n * un-gate itself instead of the host app wiring `grantConsent()` by hand.\n *\n * Keep your own banner or CMP — this only tells us how to observe it. The\n * provider reads the source on mount, re-reads it whenever `event` fires, and\n * initialises the moment it grants. Nothing is requested and no cookie is set\n * until then, and there is no page reload.\n *\n * Because the provider owns the whole lifecycle there is no ordering rule to\n * get right: pass this instead of managing `consent` yourself.\n *\n * @example // cookie written by your own banner\n * consentFrom={{ cookie: 'cookie_consent', value: 'accepted', event: 'consent-decided' }}\n * @example // a supported consent platform (reads its API, events and cookie)\n * consentFrom=\"cookiebot\" // or 'onetrust' | 'cookieyes' | 'tcf' | 'google-consent-mode'\n * consentFrom={{ cmp: 'onetrust', group: 'C0004' }}\n * @example // any other CMP with a JS API\n * consentFrom={{ check: () => window.myCmp?.analytics === true, event: 'mycmp:changed' }}\n */\n consentFrom?: ConsentSource;\n /**\n * Behavior before consent is granted. Pass `'statistical_winner'` to serve the\n * best-performing variant via `GET /v1/winner` with zero tracking while the\n * consent banner is showing. Requires `consent: false`.\n * @see SentientConfig.preConsentBehavior\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Honor the browser's Do Not Track signal. Defaults to `true`: when DNT is\n * enabled the SDK sets no cookies and sends no tracking data (overriding\n * `consent: true`). Set `false` to make your own consent gate authoritative.\n * @see SentientConfig.respectDoNotTrack\n */\n respectDoNotTrack?: boolean;\n /**\n * Called once per component the first time a variant is resolved for that\n * component in this session. Use to forward assignments to your own analytics\n * (Mixpanel, PostHog, Segment, etc.) without having to wrap `useAssignment`.\n */\n onAssignment?: (componentId: string, variantId: string) => void;\n /**\n * SSR-preloaded section order from `loadAdaptiveDecision()`.\n * Pass the `layoutOrder` field from `DecideResult`. When set,\n * `useLayoutOrder()` returns this on first render so there is no layout shift.\n */\n initialLayoutOrder?: string[] | null;\n /**\n * The section ids the app declares as reorderable, independent of any\n * decision. `AdaptiveRoot` forwards its `sections` prop here.\n *\n * Devtools reads this to offer layout previewing: a page whose decision was\n * gated by consent, or timed out, has no `initialLayoutOrder`, and registering\n * only that left the layout panel empty in exactly the situation you reach for\n * it — running the site locally before accepting a cookie banner.\n */\n declaredSections?: string[];\n /**\n * What each section IS, keyed by its `data-sentient-id`:\n * `{ about: 'trust', contact: 'cta' }`. Optional — sections are classified\n * from their content — but the classifier reads a section with little\n * signal-bearing copy (an \"About us\" band, a contact form) as `generic`, and\n * a `generic` section is ordered the same for every persona. Declare the\n * ones it gets wrong; any section with a `data-sentient-id` can appear here,\n * reorderable or not. Wins over legacy `data-sentient-type` markup.\n */\n sectionTypes?: Readonly<Partial<Record<string, SemanticType>>>;\n /**\n * SSR-preloaded slot results from `loadAdaptiveDecision()` (the `slots`\n * field of its result). Guarantees `useAdaptiveTokens`/`AdaptiveGroup`\n * render the decided arm in server HTML — zero flicker, hydration-safe.\n */\n initialSlots?: Record<string, SlotResult>;\n /**\n * SSR-preloaded registry slot config from `loadAdaptiveDecision()` (the\n * `slotConfig` field of its result, registry mode). Lets `AdaptiveSlot`\n * render server-authored content/blocks in server HTML — zero flicker.\n */\n initialSlotConfig?: Record<string, SlotConfigEntry>;\n /** SSR-preloaded site palette (`palette` field of `loadAdaptiveDecision()`'s\n * registry-mode result) for block rendering. */\n initialPalette?: SitePalette;\n /** SSR-preloaded site styles (`vocabulary` field of `loadAdaptiveDecision()`'s\n * registry-mode result) that served Redesign arms borrow. */\n initialVocabulary?: StyleVocabulary;\n /**\n * Persona decided during SSR (`persona` + `confidence` fields of\n * `loadAdaptiveDecision()`'s result). Adopted by the core client;\n * rendered into html attributes only by `SentientPersonaScript`.\n */\n initialPersona?: { persona: string; confidence: number };\n /**\n * Base URL of the Sentient API (no trailing slash). Read by the devtools\n * panel for /v1/explain and by future client helpers. Defaults to the\n * hosted API.\n */\n apiBaseUrl?: string;\n /**\n * Session ID generated during SSR (the `sessionId` field returned by\n * `loadAdaptiveAssignments` / `loadAdaptiveDecision`). When provided and no\n * existing session cookie or localStorage entry is found, the client adopts\n * this ID so events and goals are attributed to the same session the server\n * used for variant assignment.\n */\n ssrSessionId?: string;\n /**\n * Where the visitor cookie lives. By default it is shared on the site's\n * registrable domain (auto-detected), so `example.com` and\n * `app.example.com` running the same project key count one visitor and one\n * journey. `false` keeps it on this host only; a string names the domain.\n */\n cookieDomain?: string | false;\n /**\n * The signed-in user: identifies the visitor once per client. Pass the\n * server-signed `userHash` (`signUserId` from `@sentientui/core/server`,\n * or let `<AdaptiveRoot userId>` do it) to make it a VERIFIED identify —\n * required for server goals by `userId` once a project signs its identifies.\n */\n identity?: { userId: string; userHash?: string; email?: string };\n /**\n * Your own team or a test site: the visit is served versions as usual (QA\n * keeps working) but left out of every report and out of learning. Compute\n * it in your code — `internal={user.email.endsWith('@example.com')}` — and\n * only `internal: true` is sent, never the email. Read once when the client\n * starts (like `persona`): a value that arrives later (auth still loading)\n * is ignored, so decide it before the provider mounts or remount it.\n * Sticky server-side. Needs a SentientUI API that knows internal traffic;\n * older ones ignore it.\n */\n internal?: boolean;\n /**\n * ISO 3166-1 alpha-2 country code. Pass the value of the `CF-IPCountry`\n * header from your Next.js server component to populate country on landing\n * sessions without client-side geo lookup.\n */\n country?: 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 → Audiences); unrecognized values are\n * ignored server-side and surfaced in the dashboard. Served at full\n * confidence, overriding the inferred persona. Stable for the session —\n * like `country`, changing it after init is ignored (decisions are locked\n * per visit); remount the provider to apply a new value.\n */\n persona?: string;\n /**\n * Opt-in theme hook: put the visitor's funnel stage on\n * `<html data-sentient-stage>` so CSS can make deterministic per-stage\n * changes (hide the first-order discount from people who have bought).\n * Projects with stages turned on only; never for the control group.\n * `true` exposes `new`, `browsing`, `carted` and `returning` (has bought\n * here); `'detailed'` splits `returning` into `customer` and `lapsed`. Any\n * script on the page can read it, which is why detail is a second opt-in.\n * How the visitor arrived (ads, emails) is never written to the page.\n * `AdaptiveRoot` also writes it in the server HTML.\n */\n stageAttributes?: StageAttributes;\n /**\n * Keyless local mode. 'auto' (default) simulates decisions on-device in\n * development builds when no valid API key is configured; `true` forces the\n * local engine; `false` restores the silent keyless no-op.\n * @see SentientConfig.localMode\n */\n localMode?: 'auto' | boolean;\n /**\n * DOM graph scanning + page-structure sync. ON by default: the provider\n * dynamically loads `@sentientui/core/graph` and uses its graph-capable\n * `init()` for the single client, so the SDK scans your page structure,\n * auto-detects semantic sections, and syncs them to power personas and the\n * dashboard graph page. Pass `false` to keep the lean bundle only.\n */\n enableGraph?: boolean;\n /**\n * Include captured heading / DOM text in graph sync payloads. OFF by default.\n * Only applies when graph scanning is enabled (`enableGraph` not `false`).\n */\n captureDomText?: boolean;\n /**\n * Behavioral engagement capture (per-section dwell/scroll + semantic section\n * registration) powering personas. ON by default — pass `false` to disable.\n * Never runs for a DNT/GPC or consent-gated visitor (no client → no capture).\n */\n engagement?: boolean;\n /**\n * CSP nonce for the <style> the SDK injects (the adaptation reveal), so a\n * nonce-based CSP needs no `style-src 'unsafe-inline'`. `AdaptiveRoot`\n * forwards its own `nonce`. Defaults to the nonce of a script on the page.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Once per page load — StrictMode and route-level providers remount. */\nlet warnedNoConsentGate = false;\n\n/** Projects whose consent source has answered (non-null) in this page load.\n * Module-level, not per mount: a remounted provider (route-level placement,\n * a cached RSC payload on Back) or a changed consentFrom started over and fell\n * back to AdaptiveRoot's stale request-time consent={true} (review R11 #1). */\nconst answeredThisPage = new Set<string>();\n\n/**\n * Watches a {@link AdaptiveProviderProps.consentFrom} source and reports whether\n * it currently grants consent. Returns false (and subscribes to nothing) when no\n * source is configured.\n */\nfunction useConsentSource(\n source: AdaptiveProviderProps['consentFrom'],\n apiKey: string,\n onRefused: () => void,\n): { granted: boolean | null; refused: boolean } {\n const onRefusedRef = useRef(onRefused);\n onRefusedRef.current = onRefused;\n const [granted, setGranted] = useState<boolean | null>(null);\n const [refused, setRefused] = useState(false);\n\n // The source is usually an inline object literal, so its identity changes\n // every render. Read it through a ref and key the effect on a stable string,\n // otherwise the listener would be torn down and re-added on every render.\n const sourceRef = useRef(source);\n sourceRef.current = source;\n const key =\n source === undefined\n ? ''\n : typeof source === 'string'\n ? source\n : JSON.stringify({\n ...source,\n check: typeof (source as { check?: unknown }).check,\n refused: typeof (source as { refused?: unknown }).refused,\n });\n\n useEffect(() => {\n const s = sourceRef.current;\n if (s === undefined || typeof window === 'undefined') return;\n // Symmetric: every signal re-reads the source both ways, so a CMP\n // \"withdrawn\" decision later in the visit re-gates the SDK (the old shape\n // latched true and stopped listening). Payloads are never trusted.\n // The watcher is its own core entry, loaded only by pages that configure\n // a consent source; until it arrives the state stays \"unknown\" (gated,\n // or the server's read).\n let stop: (() => void) | undefined;\n let cancelled = false;\n void import('@sentientui/core/consent').then(({ consentWatcher, forgetVisitor }) => {\n if (cancelled) return;\n const watcher = consentWatcher(\n // Both predicates through the ref: an inline `refused` closing over\n // state was frozen at the first render, so a later \"no\" never\n // forgot the visitor (review R7 #4).\n typeof s === 'object' && s.cmp === undefined && s.check\n ? {\n ...s,\n check: () => (sourceRef.current as { check: () => boolean }).check(),\n ...(s.refused ? { refused: () => (sourceRef.current as { refused?: () => boolean }).refused?.() === true } : {}),\n }\n : s,\n );\n // A recorded refusal forgets the visitor even when no tracking client\n // exists to destroy — a \"no\" given where the SDK wasn't watching (a CMP\n // settings page, checkout) otherwise left the 365-day id and the\n // decision snapshot in place for good (audit N2). refused() is false for\n // \"not loaded yet\" and \"banner up\", so a consented visitor is never\n // wiped by a slow CMP.\n let wasRefused = false;\n // Once the platform has answered in this page view, \"no answer\" again\n // (a custom banner's reset deleting its cookie) reads false — a pause.\n // As null it fell back to the server's request-time read, so a visitor\n // who withdrew under AdaptiveRoot's consent={true} was tracked again\n // under a fresh identity (grader N10-1). See answeredThisPage.\n const update = (): void => {\n // Never while the source reads granted (a custom `refused` that\n // disagrees with its own `check`): that would wipe a tracked visitor.\n const r = watcher.refused() && watcher.read() !== true;\n // On a change only: Consent Mode calls back on every dataLayer push.\n if (r && !wasRefused) {\n forgetVisitor(apiKey);\n onRefusedRef.current();\n }\n wasRefused = r;\n setRefused(r);\n const g = watcher.read();\n if (g !== null) answeredThisPage.add(apiKey);\n setGranted(g ?? (answeredThisPage.has(apiKey) ? false : null));\n };\n update();\n stop = watcher.subscribe(update);\n });\n return () => {\n cancelled = true;\n stop?.();\n };\n }, [key, apiKey]);\n\n return { granted, refused };\n}\n\n/**\n * Initialises the Sentient core SDK in a useEffect (SSR-safe) and exposes the\n * client via React context. Re-initialises when consent changes.\n */\nexport function AdaptiveProvider(props: AdaptiveProviderProps): JSX.Element {\n const [client, setClient] = useState<SentientClient | null>(null);\n // Derived once per mount: identical to what core init() computes, so cache\n // reads (context segment) and cache writes (core segment) always agree.\n const [sessionSegment] = useState(() => props.sessionSegment ?? deriveDefaultSegment());\n // Devtools preview: when on, expose an event-suppressing client so previewing\n // variants/personas writes nothing. Off by default (inert in production).\n const [previewOn, setPreviewOn] = useState(getPreviewMode());\n useEffect(() => subscribePreview(() => setPreviewOn(getPreviewMode())), []);\n // On-site cell preview (dashboard \"Preview on your site\" link). No-ops\n // without both URL params; forces the previewed arm through the override\n // channel AdaptiveSlot already renders exposure-free.\n useEffect(() => {\n maybeStartCellPreview(props.apiBaseUrl);\n // Read-only version preview (?sentient_preview=<component>:<version>):\n // the link the dashboard's pictures are taken through. Preview mode goes\n // on HERE, synchronously — before anything on the page decides or records\n // — and the preview itself loads only for that link: a preview is not a\n // visit, and no ordinary visitor should download it.\n // A cheap look for the link's shape (<component>:<version>); the preview\n // entry checks it properly and turns preview mode back off if it is not\n // a link we wrote.\n if (typeof window !== 'undefined' && /[?&]sentient_preview=[^&]*(:|%3A)/i.test(window.location.search)) {\n setPreviewMode(true);\n void import('@sentientui/react/version-preview')\n .then((m) => m.maybeStartVersionPreview(props.apiKey, props.apiBaseUrl))\n .catch(() => undefined);\n }\n // Any editor-token session also samples the site's styles for Redesign\n // (React sites never load the snippet editor that does it elsewhere).\n maybeCaptureStyles(props.apiBaseUrl);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // When a consentFrom source is configured it owns the gate: start closed and\n // open only once the source grants. An explicit consent={true} (e.g. resolved\n // from the cookie on the server by AdaptiveRoot) short-circuits it, so a\n // returning visitor isn't gated waiting for a client-side re-read.\n // The browser source decides as soon as it knows (true OR false). Until then\n // (null: CMP not loaded yet) the server's read stands. The old\n // `props.consent === true || sourceGranted` let a server-side grant override\n // a mid-visit revocation for the rest of the page view.\n // Declared ahead of useConsentSource (which must call it): the refs it\n // clears are created further down.\n const dropHeldRef = useRef<() => void>(() => undefined);\n const source = useConsentSource(props.consentFrom, props.apiKey, () => dropHeldRef.current());\n // The server's read stands only until the browser source has answered in\n // this page load — also across remounts, before the watcher reloads.\n const consent = props.consentFrom\n ? (source.granted ?? (answeredThisPage.has(props.apiKey) ? false : props.consent === true))\n : props.consent;\n // Whether a `false` means \"forget the visitor\" or only \"stop for now\". An\n // explicit consent={false} is the site's own revocation; from a platform,\n // only a recorded refusal forgets — a consented visitor reopening the TCF\n // banner reads false too and was fully forgotten (review M2).\n const forgetOnFalse = props.consentFrom ? source.refused : true;\n const forgetRef = useRef(forgetOnFalse);\n forgetRef.current = forgetOnFalse;\n\n // The live client mirrored outside React state, so teardown can reach it\n // without a side effect inside a setState updater: React double-invokes\n // updaters in StrictMode dev (they must be pure), so `prev?.destroy()` inside\n // setClient ran twice — and could run during a render that never commits.\n const clientRef = useRef<SentientClient | null>(null);\n // Whether clientRef holds a TRACKING client (created with consent not false).\n // A revocation must forget that client's visitor; a pre-consent proxy has\n // nothing to forget.\n const trackingRef = useRef(false);\n // Conversions a gated client held (goal() before the consent source\n // answered), taken from it on teardown and handed to the next client: React\n // replaces the gated client on a grant instead of upgrading it in place, so\n // they were discarded with it (grader F2).\n const heldRef = useRef<Array<(c: SentientClient) => void>>([]);\n // A recorded refusal drops held conversions — ours and the gated client's —\n // so a later accept in the same page view can't send them (grader F-R1:\n // the effect is keyed on `consent`, which stays false from \"unknown\" to\n // \"refused\", so nothing else runs on the refusal).\n // The gated client is RELEASED, not just drained: draining left it holding,\n // so a goal fired after the refusal was held again and sent on a later\n // accept (grader R8 NEW-2). dispose() on a gated proxy drops its held calls,\n // answers its decides with null and holds nothing more; its read-only\n // winner (preConsentBehavior) keeps serving until the next consent change.\n // Latched too, until the next grant: a gated client created AFTER the\n // refusal — the re-init when a tracked visitor refuses, or the /graph\n // client landing after a boot-time refusal — was never released, so its\n // held goals reached the tracking client on a later accept (grader R9-1).\n const refusedRef = useRef(false);\n dropHeldRef.current = () => {\n heldRef.current = [];\n refusedRef.current = true;\n const c = clientRef.current;\n if (c?.gated) c.dispose();\n else c?.takeHeld?.();\n };\n\n useEffect(() => {\n // Revocation (a tracking client → consent false): forget the visitor —\n // identity cookie, assignment cache, decision snapshot, retry buckets —\n // via the ref, in the effect body (see clientRef above). This used to run\n // only without preConsentBehavior; with 'statistical_winner' the previous\n // run's cleanup merely dispose()d, so a withdrawn visitor kept the 365-day\n // cookie and their snapshot re-personalized the next page load.\n // (Only a forgetting revocation destroys; a pause was already disposed by\n // the previous run's cleanup, which keeps the identity.)\n if (forgetRef.current && consent === false) heldRef.current = [];\n if (consent === false && trackingRef.current) {\n if (forgetRef.current) clientRef.current?.destroy();\n clientRef.current = null;\n trackingRef.current = false;\n }\n if (consent === false && !props.preConsentBehavior) {\n if (forgetRef.current) clientRef.current?.destroy();\n clientRef.current = null;\n setClient(null);\n return;\n }\n const tracking = consent !== false;\n if (tracking) refusedRef.current = false;\n // A gated client born after a refusal is released at once (see refusedRef).\n const adopt = (c: SentientClient): void => {\n if (!tracking && refusedRef.current && c.gated) c.dispose();\n };\n\n const config = {\n apiKey: props.apiKey,\n context: props.context,\n debug: props.debug,\n initialAssignments: props.initialAssignments,\n initialUnified: props.initialUnified,\n sessionSegment,\n consent,\n preConsentBehavior: props.preConsentBehavior,\n respectDoNotTrack: props.respectDoNotTrack,\n ssrSessionId: props.ssrSessionId,\n cookieDomain: props.cookieDomain,\n country: props.country,\n persona: props.persona,\n internal: props.internal,\n stageAttributes: props.stageAttributes,\n localMode: props.localMode,\n initialSlots: props.initialSlots,\n initialSlotConfig: props.initialSlotConfig,\n initialPalette: props.initialPalette,\n initialVocabulary: props.initialVocabulary,\n initialPersona: props.initialPersona,\n ingestUrl: props.apiBaseUrl ? `${props.apiBaseUrl.replace(/\\/$/, '')}/events` : undefined,\n nonce: props.nonce,\n // Declare which SDK (and which release) is driving this client, so the\n // dashboard can tell the project when it is running an old one. A React\n // install cannot self-update the way the snippet's CDN tag does, so this\n // nudge is the only update path there is.\n ...(SDK_IDENT ? { sdk: SDK_IDENT } : {}),\n };\n\n // Track the client created by this effect run so cleanup destroys exactly\n // the right one, and so a late-resolving dynamic import can bail if the\n // effect was already torn down (unmount / consent change).\n let cancelled = false;\n let created: SentientClient | null = null;\n let stopEngagement: (() => void) | null = null;\n\n // Engagement capture (default ON): per-section dwell/scroll + semantic\n // section registration, lazy-loaded so the lean bundle stays lean. Only for\n // a TRACKING client: with preConsentBehavior a gated visitor still gets a\n // (pre-consent proxy) client, and capture used to start on it — POSTing\n // /v1/section-map and attaching collectors while consent was false. The\n // capture module re-checks DNT internally.\n // Replay held conversions: sent by a tracking client, re-held by a gated one.\n // Each in its own task, like core's replay: one task would put them in\n // one latch window and collapse repeat conversions into one.\n const handOff = (c: SentientClient): void => {\n for (const call of heldRef.current.splice(0)) {\n setTimeout(() => {\n // Replaced before this task ran (unmount, another consent flip):\n // back into the stash for the next client, never into a disposed\n // one's dead queue (review R7 #6).\n if (clientRef.current !== c) {\n // …unless a refusal landed in between: it dropped the stash,\n // and pushing back revived the goal for a later accept\n // (review R10 #2).\n if (!refusedRef.current) heldRef.current.push(call);\n return;\n }\n try {\n call(c);\n } catch {\n /* one bad call never blocks the rest */\n }\n }, 0);\n }\n };\n\n const startEngagement = (c: SentientClient): void => {\n if (props.engagement === false || !tracking) return;\n void import('@sentientui/core/engagement').then(({ startEngagementCapture }) => {\n if (cancelled) return;\n stopEngagement = startEngagementCapture(c, {\n apiKey: props.apiKey,\n sectionTypes: props.sectionTypes,\n apiBase: props.apiBaseUrl ? props.apiBaseUrl.replace(/\\/$/, '') : undefined,\n });\n });\n };\n\n if (props.enableGraph !== false) {\n // Graph scanning is the default — load the graph entry dynamically so the\n // scanner never lands in the lean bundle. The provider still creates ONE\n // client (graph-capable). Pass enableGraph={false} for the lean client.\n void import('@sentientui/core/graph').then(({ init: initGraph }) => {\n if (cancelled) return;\n created = initGraph({\n ...config,\n graph: true,\n captureDomText: props.captureDomText === true,\n sectionTypes: props.sectionTypes,\n });\n adopt(created);\n clientRef.current = created;\n trackingRef.current = tracking;\n handOff(created);\n setClient(created);\n startEngagement(created);\n });\n } else {\n created = init(config);\n adopt(created);\n clientRef.current = created;\n trackingRef.current = tracking;\n handOff(created);\n setClient(created);\n startEngagement(created);\n }\n\n return () => {\n cancelled = true;\n stopEngagement?.();\n heldRef.current = heldRef.current.concat(created?.takeHeld?.() ?? []);\n // dispose, not destroy: effect cleanup runs on unmount, StrictMode's\n // dev double-invoke, and consent re-init — the visitor identity must\n // survive all of those. Full destroy() happens only on the explicit\n // consent-revocation branch above.\n created?.dispose();\n };\n // Re-init when consent changes — whether that came from the prop or from a\n // consentFrom source granting. Other props (incl. enableGraph) are\n // intentionally stable for a session.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [consent]);\n\n // Poll /v1/weights every 60 s so long-lived sessions see updated bandit weights\n // without a page reload. useAssignment subscribers react via weights-store.\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n const poll = async (): Promise<void> => {\n if (cancelled) return;\n let entries;\n try {\n entries = await client.fetchWeights();\n } catch {\n // Network/transient error: skip this cycle and retry on the next\n // interval. Swallowed deliberately so a failed poll never surfaces as\n // an unhandled rejection.\n return;\n }\n if (cancelled) return;\n for (const entry of entries) {\n const weights: ComponentWeights = {\n componentId: entry.componentId,\n updatedAt: entry.updatedAt,\n variants: entry.variants.map((v) => ({\n variantId: v.variantId,\n pulls: v.pulls,\n avgReward: v.avgReward ?? 0,\n })),\n };\n updateWeightsStore(entry.componentId, weights);\n }\n };\n void poll();\n const timerId = setInterval(() => void poll(), 60_000);\n return () => {\n cancelled = true;\n clearInterval(timerId);\n };\n }, [client]);\n\n const ssrFallback = props.ssrFallback ?? 'first';\n // Strip a trailing slash so consumers (devtools /explain, useAdaptiveApiBaseUrl)\n // build URLs the same way the core client does (it strips before appending\n // /events and /section-map) — otherwise an apiBaseUrl ending in \"/\" yields a\n // double slash like \".../v1//explain\".\n const apiBaseUrl = (props.apiBaseUrl ?? DEFAULT_API_BASE_URL).replace(/\\/$/, '');\n\n // The init effect above re-runs only on `props.consent`: apiKey / context /\n // country / apiBaseUrl are captured once and are deliberately stable for the\n // session, so changing them at runtime silently no-ops. That silence is\n // surprising — warn (dev only) when one actually changes value after init, so\n // the no-op is visible. To apply a new value, remount the provider (e.g. a\n // changing React `key`).\n const frozenConfigRef = useRef<{\n apiKey: string;\n // Optional since `context` was deprecated: undefined → undefined compares\n // equal under Object.is, so omitting it never trips the warning below.\n context: SentientConfig['context'] | undefined;\n country: string | undefined;\n persona: string | undefined;\n internal: boolean | undefined;\n apiBaseUrl: string;\n } | null>(null);\n useEffect(() => {\n if (!isDevBuild()) return;\n const current = { apiKey: props.apiKey, context: props.context, country: props.country, persona: props.persona, internal: props.internal, apiBaseUrl };\n const prev = frozenConfigRef.current;\n frozenConfigRef.current = current;\n if (prev === null) return; // first run: capture the frozen baseline, nothing to compare\n // `internal` too: `internal={user?.isStaff}` with auth still loading\n // starts the client unmarked, and the later `true` silently did nothing.\n for (const key of ['apiKey', 'context', 'country', 'persona', 'internal', 'apiBaseUrl'] as const) {\n if (!Object.is(prev[key], current[key])) {\n console.warn(\n `[sentient] AdaptiveProvider: \\`${key}\\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \\`consent\\` — the new value is ignored. Remount the provider (e.g. via a changing \\`key\\` prop) to apply it.`,\n );\n }\n }\n }, [props.apiKey, props.context, props.country, props.persona, props.internal, apiBaseUrl]);\n\n // Publish devtools config through window: the /devtools entry is a separate\n // bundle and cannot read this provider's context instance. Dev-only.\n useEffect(() => {\n if (!isDevBuild()) return;\n publishDevtoolsConfig({\n apiKey: props.apiKey,\n apiBaseUrl,\n isLocal: client?.isLocal === true,\n });\n }, [client, props.apiKey, apiBaseUrl]);\n\n // identify() is an upsert: once per client and user, never per render. A\n // consent grant makes a new client, which identifies again — the gated one\n // dropped it.\n const identityUser = props.identity?.userId;\n const identityHash = props.identity?.userHash;\n // Hashed by core before it leaves the page; only the hash + domain are sent.\n const identityEmail = props.identity?.email;\n useEffect(() => {\n if (client && identityUser) client.identify(identityUser, { userHash: identityHash, email: identityEmail });\n }, [client, identityUser, identityHash, identityEmail]);\n\n // Sections registry for devtools /v1/explain + local simulation. The decided\n // order wins when there is one (it is what the page is actually rendering);\n // the declared list is the fallback so the layout panel still knows what is\n // reorderable when no decision arrived.\n useEffect(() => {\n const decided = props.initialLayoutOrder;\n if (decided && decided.length > 0) {\n registerSections(decided);\n return;\n }\n if (props.declaredSections && props.declaredSections.length > 0) {\n registerSections(props.declaredSections);\n }\n }, [props.initialLayoutOrder, props.declaredSections]);\n\n // Dev-only: tracking is on by default, so an install that never wires a\n // consent gate tracks EU visitors from the first paint without anyone\n // having decided that (audit S6). Say so once, with the one-line fix.\n useEffect(() => {\n if (!isDevBuild() || props.consent !== undefined || props.consentFrom !== undefined) return;\n if (warnedNoConsentGate) return;\n warnedNoConsentGate = true;\n console.warn(\n '[SentientUI] No consent gate: every visitor is tracked from first paint. Pass consentFrom=\"<your CMP>\" ' +\n '(or consent={true} to silence). https://sentient-ui.com/docs#consent',\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Dev-only: a declared section with no `data-sentient-id=\"<id>\"` element is\n // invisible to the DOM graph scanner, so the server never learns its semantic\n // type and every persona gets the identity order — the layout looks \"on\" but\n // can never personalize (found on a real site 2026-09-05: nine declared\n // sections, zero graph rows, one bandit arm). Warn once with the exact fix\n // rather than leaving the integration silently inert.\n useEffect(() => {\n if (!isDevBuild()) return;\n const declared = props.declaredSections;\n if (!declared || declared.length === 0 || typeof document === 'undefined') return;\n const present = new Set(\n Array.from(document.querySelectorAll('[data-sentient-id]'), (el) =>\n el.getAttribute('data-sentient-id'),\n ),\n );\n const missing = declared.filter((id) => !present.has(id));\n if (missing.length > 0) {\n console.warn(\n `[SentientUI] Declared section${missing.length > 1 ? 's' : ''} ${missing\n .map((id) => `\"${id}\"`)\n .join(', ')} ${missing.length > 1 ? 'have' : 'has'} no matching ` +\n 'data-sentient-id element, so the layout engine cannot learn what ' +\n 'they are and will serve the same order to every persona. Add ' +\n 'data-sentient-id=\"<sectionId>\" to each section\\'s element.',\n );\n }\n }, [props.declaredSections]);\n\n // The client exposed to consumers — wrapped to suppress events while previewing.\n const exposedClient = useMemo(\n () => (client && previewOn ? createPreviewClient(client) : client),\n [client, previewOn],\n );\n\n // Memoized so unrelated parent re-renders don't cascade through every\n // useSentient / useAssignment consumer via a fresh context object.\n const value = useMemo<AdaptiveContextValue>(\n () => ({\n client: exposedClient,\n apiKey: props.apiKey,\n initialAssignments: props.initialAssignments ?? {},\n initialUnified: props.initialUnified ?? NO_UNIFIED,\n sessionSegment,\n ssrFallback,\n onAssignment: props.onAssignment,\n initialLayoutOrder: props.initialLayoutOrder ?? null,\n initialSlots: props.initialSlots ?? {},\n initialSlotConfig: props.initialSlotConfig ?? {},\n initialPalette: props.initialPalette ?? null,\n initialVocabulary: props.initialVocabulary ?? null,\n initialPersona: props.initialPersona ?? null,\n apiBaseUrl,\n debug: props.debug ?? false,\n }),\n [\n exposedClient,\n props.apiKey,\n props.initialAssignments,\n props.initialUnified,\n sessionSegment,\n ssrFallback,\n props.onAssignment,\n props.initialLayoutOrder,\n props.initialSlots,\n props.initialSlotConfig,\n props.initialPalette,\n props.initialVocabulary,\n props.initialPersona,\n apiBaseUrl,\n props.debug,\n ],\n );\n\n return (\n <AdaptiveContext.Provider value={value}>\n {props.children}\n </AdaptiveContext.Provider>\n );\n}\n\n/**\n * Returns the SentientClient, or null until the provider has finished\n * initialising on the client.\n */\nexport function useSentient(): SentientClient | null {\n return useContext(AdaptiveContext).client;\n}\n\n/** Internal: publishable API key carried alongside the client. */\nexport function useAdaptiveApiKey(): string {\n return useContext(AdaptiveContext).apiKey;\n}\n\n/** Internal: SSR-preloaded assignments for hydration-safe first render. */\nexport function useInitialAssignments(): Record<string, string> {\n return useContext(AdaptiveContext).initialAssignments;\n}\n\nconst NO_UNIFIED: readonly string[] = [];\n\n/** Internal. Ids the SSR preload found moved onto the shared track. */\nexport function useInitialUnified(): readonly string[] {\n return useContext(AdaptiveContext).initialUnified;\n}\n\n/** The `device:source` segment this provider decides and caches under —\n * the SSR value when one was passed, else derived once per mount. */\nexport function useSessionSegment(): string {\n return useContext(AdaptiveContext).sessionSegment;\n}\n\n/** Internal: SSR fallback strategy when a slot has no preloaded assignment. */\nexport function useSsrFallback(): SsrFallback {\n return useContext(AdaptiveContext).ssrFallback;\n}\n\n/** Internal: forwarding hook for consumer analytics integration. */\nexport function useOnAssignment(): ((componentId: string, variantId: string) => void) | undefined {\n return useContext(AdaptiveContext).onAssignment;\n}\n\n/** Internal: debug flag from the provider config, for dev-only diagnostic logging. */\nexport function useDebug(): boolean {\n return useContext(AdaptiveContext).debug;\n}\n\n/**\n * Returns the persona-specific section order from SSR, or null when no\n * sections were declared on AdaptiveRoot or reliability is below threshold.\n * Devtools/testing can force it via `window.__sentient_layout_override`;\n * consumers re-render when the devtools notifies an override change.\n */\nexport function useLayoutOrder(): string[] | null {\n const contextOrder = useContext(AdaptiveContext).initialLayoutOrder;\n const override = useSyncExternalStore(\n subscribeOverridesChanged,\n () =>\n typeof window === 'undefined'\n ? null\n : ((window as unknown as { __sentient_layout_override?: string[] })\n .__sentient_layout_override ?? null),\n () => null,\n );\n return override ?? contextOrder;\n}\n\n/** Internal: SSR-preloaded slot results for hydration-safe first render. */\nexport function useInitialSlots(): Record<string, SlotResult> {\n return useContext(AdaptiveContext).initialSlots;\n}\n\n/** Internal: SSR-decided persona carried alongside the client. */\nexport function useInitialPersona(): { persona: string; confidence: number } | null {\n return useContext(AdaptiveContext).initialPersona;\n}\n\n/** Internal: SSR-preloaded registry slot config for hydration-safe AdaptiveSlot. */\nexport function useInitialSlotConfig(): Record<string, SlotConfigEntry> {\n return useContext(AdaptiveContext).initialSlotConfig;\n}\n\n/** Internal: SSR-preloaded site palette for block rendering. */\nexport function useInitialPalette(): SitePalette | null {\n return useContext(AdaptiveContext).initialPalette;\n}\n\n/** Internal: SSR-preloaded site styles for Redesign rendering. */\nexport function useInitialVocabulary(): StyleVocabulary | null {\n return useContext(AdaptiveContext).initialVocabulary;\n}\n\n/** Internal: configured API base URL (devtools fetches /v1/explain against this, never a relative URL). */\nexport function useAdaptiveApiBaseUrl(): string {\n return useContext(AdaptiveContext).apiBaseUrl;\n}\n","/** Per-component weights store with isolated subscriptions. */\n\nexport type VariantWeight = {\n variantId: string;\n pulls: number;\n avgReward: number;\n};\n\nexport type ComponentWeights = {\n componentId: string;\n variants: VariantWeight[];\n updatedAt: number;\n};\n\ntype Listener = (weights: ComponentWeights) => void;\n\nconst store = new Map<string, ComponentWeights>();\nconst listeners = new Map<string, Set<Listener>>();\n\n/**\n * Subscribes a listener to a single component. Returns an unsubscribe function.\n * Updates to other components never trigger this listener.\n */\nexport function subscribe(componentId: string, cb: Listener): () => void {\n let set = listeners.get(componentId);\n if (!set) {\n set = new Set();\n listeners.set(componentId, set);\n }\n set.add(cb);\n return () => {\n set!.delete(cb);\n if (set!.size === 0) listeners.delete(componentId);\n };\n}\n\n/**\n * Replaces the weights for a component and notifies only that component's\n * subscribers.\n */\nexport function update(componentId: string, weights: ComponentWeights): void {\n store.set(componentId, weights);\n const set = listeners.get(componentId);\n if (!set) return;\n for (const cb of set) {\n try {\n cb(weights);\n } catch {\n /* never throw to other listeners */\n }\n }\n}\n\n/**\n * Returns the latest known weights for a component, or null if none seen.\n */\nexport function getWeights(componentId: string): ComponentWeights | null {\n return store.get(componentId) ?? null;\n}\n\n/** Test-only: wipe the entire store. */\nexport function _resetWeightsStore(): void {\n store.clear();\n listeners.clear();\n}\n","import type { SentientClient } from '@sentientui/core';\n\ntype PreviewState = { on: boolean; listeners: Set<() => void> };\nconst ssrFallback: PreviewState = { on: false, listeners: new Set() };\n\n// Window-backed: the /devtools entry (a separate bundle) toggles preview mode\n// and the provider (main bundle) must observe it.\nfunction state(): PreviewState {\n if (typeof window === 'undefined') return ssrFallback;\n const w = window as unknown as { __sentient_preview?: PreviewState };\n if (!w.__sentient_preview) w.__sentient_preview = { on: false, listeners: new Set() };\n return w.__sentient_preview;\n}\n\nexport function setPreviewMode(on: boolean): void {\n const s = state();\n if (s.on === on) return;\n s.on = on;\n for (const fn of s.listeners) fn();\n}\n\nexport function getPreviewMode(): boolean {\n return state().on;\n}\n\nexport function subscribePreview(fn: () => void): () => void {\n const listeners = state().listeners;\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/**\n * Wraps a client so it writes nothing: reads pass through, all emitters no-op.\n * Used while previewing variants/personas so no `variant_assigned`, goal, or\n * session events are sent.\n */\nexport function createPreviewClient(inner: SentientClient): SentientClient {\n return {\n isLocal: inner.isLocal,\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n fetchWeights: () => Promise.resolve([]),\n getAssignment: (componentId, segment) => inner.getAssignment(componentId, segment),\n isUnified: (componentId) => inner.isUnified?.(componentId) ?? false,\n assign: (componentId, variantIds, agentData, agentDataByVariant, opts) =>\n inner.assign(componentId, variantIds, agentData, agentDataByVariant, opts),\n // Reads pass through; decide is a write (slot decisions persist server-side)\n // so preview mode never issues it.\n decide: () => Promise.resolve(null),\n getSlotResult: (slotId) => inner.getSlotResult(slotId),\n getSlotConfig: (slotId) => inner.getSlotConfig(slotId),\n getSitePalette: () => inner.getSitePalette(),\n reportSlots: (ids) => inner.reportSlots(ids),\n getPersona: () => inner.getPersona(),\n getGraph: () => inner.getGraph(),\n flush: () => inner.flush(),\n dispose: () => inner.dispose(),\n destroy: () => inner.destroy(),\n };\n}\n","/**\n * Cross-bundle re-render bus for devtools overrides. The main entry and the\n * /devtools entry are separate bundles, so state and notifications go through\n * window (a version counter + a DOM event) — never module-local state.\n */\nconst EVENT = 'sentient:overrides-changed';\n\ntype VersionWindow = Window & { __sentient_overrides_version?: number };\n\nexport function getOverridesVersion(): number {\n if (typeof window === 'undefined') return 0;\n return (window as VersionWindow).__sentient_overrides_version ?? 0;\n}\n\nexport function notifyOverridesChanged(): void {\n if (typeof window === 'undefined') return;\n const w = window as VersionWindow;\n w.__sentient_overrides_version = (w.__sentient_overrides_version ?? 0) + 1;\n window.dispatchEvent(new Event(EVENT));\n}\n\nexport function subscribeOverridesChanged(fn: () => void): () => void {\n if (typeof window === 'undefined') return () => undefined;\n window.addEventListener(EVENT, fn);\n return () => window.removeEventListener(EVENT, fn);\n}\n","/** Provider → devtools config handoff. Window-backed: the /devtools entry is a\n * separate bundle and cannot share the provider's React context instance. */\nexport type DevtoolsConfig = {\n apiKey: string;\n apiBaseUrl: string;\n isLocal: boolean;\n};\n\ntype ConfigWindow = Window & { __sentient_devtools_config?: DevtoolsConfig };\n\nexport function publishDevtoolsConfig(config: DevtoolsConfig): void {\n if (typeof window === 'undefined') return;\n (window as ConfigWindow).__sentient_devtools_config = config;\n}\n\nexport function readDevtoolsConfig(): DevtoolsConfig | null {\n if (typeof window === 'undefined') return null;\n return (window as ConfigWindow).__sentient_devtools_config ?? null;\n}\n","// `env` is non-optional on purpose: the check below must be written as the\n// exact expression `process.env.NODE_ENV` (see isDevBuild).\ndeclare const process: { env: { NODE_ENV?: string } };\n\n/**\n * True unless the app was built for production.\n *\n * Written as the literal `process.env.NODE_ENV`, inside try/catch, because\n * that exact expression is the only one every bundler rewrites. Vite (like\n * webpack and esbuild) replaces `process.env.NODE_ENV` with a string literal\n * but leaves `typeof process` alone and defines nothing in the browser, so the\n * previous `typeof process === 'undefined' || process.env?.NODE_ENV !==\n * 'production'` read \"no process\" in every Vite production build and returned\n * true: production visitors got the dev-only warnings (\"No consent gate\",\n * \"rendering its baseline children\") and the devtools registry. `?.` defeats\n * the replacement too — Vite turned `process.env?.NODE_ENV` into\n * `{}.NODE_ENV`, i.e. undefined.\n *\n * The catch is for a page with no bundler at all (a raw ESM import, a CDN):\n * there `process` is undeclared and the read throws ReferenceError. That has\n * no build mode, so it counts as development, as it always did.\n */\nexport function isDevBuild(): boolean {\n try {\n return process.env.NODE_ENV !== 'production';\n } catch {\n return true;\n }\n}\n","import { isDevBuild } from './adaptive-shared.js';\n\nexport type RegisteredComponent = { id: string; variantIds: string[]; goal?: string };\nexport type RegisteredSlot = {\n id: string;\n arms?: string[];\n dims?: Record<string, readonly string[]>;\n};\n\ntype RegistryState = {\n components: Map<string, RegisteredComponent>;\n slots: Map<string, RegisteredSlot>;\n sections: string[];\n listeners: Set<() => void>;\n /** Bumped on every mutation so `useSyncExternalStore` can read a stable, comparable snapshot. */\n version: number;\n};\n\n// Shared through a window global: the main entry and the /devtools entry are\n// separate bundles, each with its own copy of this module — module-local\n// state would give the devtools an always-empty registry in published apps.\nconst ssrFallback: RegistryState = {\n components: new Map(),\n slots: new Map(),\n sections: [],\n listeners: new Set(),\n version: 0,\n};\n\nfunction state(): RegistryState {\n if (typeof window === 'undefined') return ssrFallback;\n const w = window as unknown as { __sentient_registry?: RegistryState };\n if (!w.__sentient_registry) {\n w.__sentient_registry = {\n components: new Map(),\n slots: new Map(),\n sections: [],\n listeners: new Set(),\n version: 0,\n };\n }\n return w.__sentient_registry;\n}\n\nfunction emit(): void {\n // Bump BEFORE notifying so a useSyncExternalStore consumer re-reading its\n // snapshot inside the notification sees the new value and re-renders.\n state().version += 1;\n for (const fn of state().listeners) fn();\n}\n\n// The registry exists solely to feed the opt-in devtools panel, which is a\n// dev-only surface. In a production build there is no panel reading it, so\n// every register call is dead work plus a `window.__sentient_registry`\n// footprint on the customer's page. Short-circuit to a noop in production —\n// every <Adaptive>/useAdaptive/slot mount calls one of these.\nconst NOOP_UNREGISTER = (): void => undefined;\n\n/** Register (or re-register) a component. Returns an unregister function. */\nexport function registerComponent(c: RegisteredComponent): () => void {\n if (!isDevBuild()) return NOOP_UNREGISTER;\n state().components.set(c.id, c);\n emit();\n return () => {\n state().components.delete(c.id);\n emit();\n };\n}\n\n/** Register (or re-register) a slot declaration. Returns an unregister function. */\nexport function registerSlot(s: RegisteredSlot): () => void {\n if (!isDevBuild()) return NOOP_UNREGISTER;\n state().slots.set(s.id, s);\n emit();\n return () => {\n state().slots.delete(s.id);\n emit();\n };\n}\n\n/** Register the page's declared section ids (from AdaptiveRoot/provider). */\nexport function registerSections(sections: string[]): void {\n if (!isDevBuild()) return;\n state().sections = [...sections];\n emit();\n}\n\nexport function getRegistered(): RegisteredComponent[] {\n return [...state().components.values()];\n}\n\nexport function getRegisteredSlots(): RegisteredSlot[] {\n return [...state().slots.values()];\n}\n\nexport function getRegisteredSections(): string[] {\n return [...state().sections];\n}\n\nexport function subscribeRegistry(fn: () => void): () => void {\n const listeners = state().listeners;\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/** Monotonic snapshot for `useSyncExternalStore` — changes on every registry mutation. */\nexport function getRegistryVersion(): number {\n return state().version;\n}\n","/**\n * This package's released build version, injected by tsup's `define` from\n * package.json (see tsup.config.ts) so the version inside a published bundle\n * can never drift from the version on npm. Mirrors the snippet's\n * `__SNIPPET_VERSION__`.\n *\n * Why the React SDK reports a version at all: unlike the snippet, it is a\n * build-time npm dependency, so it CANNOT self-update — a customer on an old\n * release stays there until they run an install. Telling them they're behind is\n * the only remedy available, and the dashboard can only tell them if the\n * running bundle says what it is.\n */\ndeclare const __REACT_SDK_VERSION__: string;\n\nexport const version: string =\n typeof __REACT_SDK_VERSION__ !== 'undefined' ? __REACT_SDK_VERSION__ : '0.0.0-dev';\n\n/**\n * The identity handed to core's session upsert, or undefined for a dev build.\n * The '0.0.0-dev' sentinel (unit tests, or any build without tsup's define)\n * passes the server's semver validation and would be persisted as the\n * project's SDK version, leaving the dashboard permanently claiming the\n * project is behind — the same trap the snippet documents as audit M12.\n */\nexport const SDK_IDENT: { name: string; version: string } | undefined =\n version !== '0.0.0-dev' ? { name: 'react', version } : undefined;\n","import type { SlotConfigEntry, StyleVocabulary } from '@sentientui/core';\n\n/**\n * Slot-CONFIG override store — the channel `useSlotConfig` reads (AdaptiveSlot).\n * Separate from `__sentient_slot_overrides` (which forces the slot RESULT — the\n * arm): forcing an arm alone can't test AdaptiveSlot's rendering, because the\n * content/blocks live in the config entry. Window-backed so the /devtools and\n * /testing bundles and the main bundle share one store.\n */\nfunction store(): Record<string, SlotConfigEntry> {\n const w = window as unknown as { __sentient_slot_config_overrides?: Record<string, SlotConfigEntry> };\n if (!w.__sentient_slot_config_overrides) w.__sentient_slot_config_overrides = {};\n return w.__sentient_slot_config_overrides;\n}\n\n/** Force `slotId`'s config entry — read by `useSlotConfig`. */\nexport function setSlotConfigOverride(slotId: string, entry: SlotConfigEntry): void {\n store()[slotId] = entry;\n}\n\n/** Site styles for forced configs (the on-site preview of a redesigned\n * section): the decision that would normally carry them never ran. */\nexport function setVocabularyOverride(v: StyleVocabulary | null): void {\n (window as unknown as { __sentient_vocabulary_override?: StyleVocabulary | null }).__sentient_vocabulary_override = v;\n}\n\nexport function getVocabularyOverride(): StyleVocabulary | null {\n if (typeof window === 'undefined') return null;\n return (window as unknown as { __sentient_vocabulary_override?: StyleVocabulary | null }).__sentient_vocabulary_override ?? null;\n}\n\nexport function clearSlotConfigOverride(slotId: string): void {\n delete store()[slotId];\n}\n\nexport function getSlotConfigOverrides(): Record<string, SlotConfigEntry> {\n return { ...store() };\n}\n","import type { SlotResult } from '@sentientui/core';\n\n/**\n * Slot-override store — the channel `useSlotResult` reads (`useAdaptiveTokens` /\n * `AdaptiveGroup`). Separate from `__sentient_overrides` (variant components):\n * a slot result is a token object (`{ tone: 'urgent' }`) or an arm string\n * (`'social_first'`), never a bare variant id. Window-backed so the /devtools\n * bundle and the main bundle share one store.\n */\nfunction store(): Record<string, SlotResult> {\n const w = window as unknown as { __sentient_slot_overrides?: Record<string, SlotResult> };\n if (!w.__sentient_slot_overrides) w.__sentient_slot_overrides = {};\n return w.__sentient_slot_overrides;\n}\n\n/** Force `slotId` to resolve to `result` — read by `useSlotResult`. */\nexport function setSlotOverride(slotId: string, result: SlotResult): void {\n store()[slotId] = result;\n}\n\nexport function clearSlotOverride(slotId: string): void {\n delete store()[slotId];\n}\n\nexport function getSlotOverrides(): Record<string, SlotResult> {\n return { ...store() };\n}\n","// Credentials the dashboard hands the site (`sentient_preview_token`, the\n// editor's one-time `sentient_editor_code`) ride the URL FRAGMENT, which is\n// never sent over the network — no server/CDN log, no Referer (grades C13, E1).\n//\n// The fragment is also where hash-routed sites keep their route (grade E2).\n// The first version wrote `#sentient_preview_token=…` over the whole hash, so a\n// preview of `/#/pricing` opened the home route instead. The dashboard now\n// APPENDS the param (appendHashParam in apps/dashboard/app/lib/hash-param.ts):\n// '' → #name=v\n// '/pricing' → #/pricing?name=v (routers read it as a query param, so\n// '/p?x=1' → #/p?x=1&name=v the route still matches pre-strip)\n// and this takes it back out, restoring the site's own hash EXACTLY — or\n// removing the '#' altogether when the site had none. Twin of\n// packages/snippet/src/hash-param.ts (the snippet cannot import this package\n// and vice versa); keep the two in step — both suites run the same cases.\nexport function takeHashParam(name: string): string | null {\n let v: string | null = null;\n try {\n const h = location.hash.slice(1);\n const m = RegExp('(^|[?&])' + name + '=([^&]*)').exec(h);\n if (m) {\n // Taken BEFORE the rewrite: an opaque-origin frame may refuse\n // replaceState, and the value is still ours to use. Base64url, so no\n // decoding (the dashboard never percent-encodes it).\n v = m[2]!;\n let after = h.slice(m.index + m[0].length);\n // '?name=v&rest' / 'name=v&rest': the next param inherits the separator.\n if (m[1] != '&' && after[0] == '&') after = m[1] + after.slice(1);\n const rest = h.slice(0, m.index) + after;\n // replaceState, not location.hash=: no hashchange, so a hash router does\n // not re-route mid-boot; history.state kept so its entry key survives.\n history.replaceState(history.state, '', rest ? '#' + rest : location.pathname + location.search);\n }\n } catch {\n /* fail-safe */\n }\n return v;\n}\n","// The operator's editor session on a React site (dashboard \"Preview on your\n// site\", \"Refresh from page\", style capture). The dashboard sends a one-time\n// code in the URL FRAGMENT (#sentient_editor_code=, grade E1) — never the\n// token itself, which as `?sentient_editor=` reached server/CDN logs,\n// analytics page URLs and Referer headers, and can publish. This trades the\n// code for the token (POST /v1/editor/exchange; the API checks the Origin is\n// the project's own) and keeps the token in sessionStorage only.\n//\n// Memoised: cell preview, region refresh and style capture all ask, but the\n// code is single use — a second exchange would be refused and whichever\n// caller lost the race would report an \"expired\" link that was fine.\nimport { takeHashParam } from './hash-param.js';\n\n// Same key as the snippet's cache, so both SDKs agree on \"this tab is in an\n// editor session\" if a page ever carries both.\nconst TOKEN_KEY = '__snt_editor_token';\n\nexport type EditorSession = { token: string; fresh: boolean };\ntype Outcome = EditorSession | { error: number } | null;\n\nlet pending: Promise<Outcome> | null = null;\nlet active = false;\n\n/** Synchronous: did editorSession() find a code or a cached token? Lets a\n * caller refuse to act on a bare URL param (a visitor, not an operator)\n * without waiting for the exchange — the old token-in-query check was sync. */\nexport function editorSessionActive(): boolean {\n return active;\n}\n\nfunction cached(): string | null {\n try {\n return sessionStorage.getItem(TOKEN_KEY);\n } catch {\n return null;\n }\n}\n\n/**\n * The editor token for this page view: exchanged from a fresh fragment code\n * (`fresh: true`), else the one cached earlier in this tab. `{ error }` is a\n * refused exchange (401 = expired/used, anything else = couldn't load); null\n * means this is not an editor session at all.\n */\nexport function editorSession(apiBase: string): Promise<Outcome> {\n if (pending) return pending;\n const code = typeof window === 'undefined' ? null : takeHashParam('sentient_editor_code');\n if (!code) {\n const t = typeof window === 'undefined' ? null : cached();\n active = !!t;\n pending = Promise.resolve(t ? { token: t, fresh: false } : null);\n return pending;\n }\n active = true;\n pending = fetch(`${apiBase}/editor/exchange`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ code }),\n })\n .then(async (res): Promise<Outcome> => {\n const token = res.ok ? ((await res.json()) as { token?: string }).token : undefined;\n if (!token) return { error: res.ok ? 500 : res.status };\n try {\n sessionStorage.setItem(TOKEN_KEY, token);\n } catch {\n /* the session still works for this page view */\n }\n return { token, fresh: true };\n })\n .catch((): Outcome => ({ error: 0 }));\n return pending;\n}\n\n/** End the session (Exit preview): a reload is a normal visit again. */\nexport function endEditorSession(): void {\n try {\n sessionStorage.removeItem(TOKEN_KEY);\n } catch {\n /* fail-safe */\n }\n}\n\n/** Test hook. */\nexport function resetEditorSessionForTests(): void {\n pending = null;\n active = false;\n}\n","// On-site preview for generated versions (the dashboard's \"Preview on your\n// site\" link): ?sentient_preview_cell=<slotId>~<persona>#sentient_editor_code=…\n// (a one-time code exchanged for the editor token — editor-session.ts, E1)\n// fetches the square's PENDING (review) or live arm through the editor-token\n// API and forces it through the devtools override channel — which AdaptiveSlot\n// already renders IN PLACE, with the page's real CSS, and WITHOUT recording an\n// exposure ('override' source is excluded from tracking by design). A floating\n// bar names what is being previewed and offers Exit.\n//\n// Deliberately framework-light: the bar is plain DOM (no React tree to mount\n// into), and everything no-ops without both params, so normal visitors pay\n// one URLSearchParams read.\nimport { setSlotConfigOverride, setVocabularyOverride } from './devtools-slot-config-overrides.js';\nimport { setSlotOverride } from './devtools-slot-overrides.js';\nimport { notifyOverridesChanged } from './override-events.js';\nimport { editorSession, editorSessionActive, endEditorSession } from './editor-session.js';\nimport type { ComposeArm, StyleVocabulary } from '@sentientui/core';\n\nconst PARAM_CELL = 'sentient_preview_cell';\nconst PARAM_REFRESH = 'sentient_refresh_region';\nconst BAR_ID = 'sentient-cell-preview-bar';\nconst PREVIEW_ARM = '__preview__';\n\ntype CellPreviewResponse = {\n status: 'review' | 'live';\n slotName: string;\n personaDisplay: string;\n content: string | null;\n blocks: unknown | null;\n edits?: unknown;\n skeletonFp?: string;\n leafToNode?: number[];\n compose?: unknown;\n vocabulary?: StyleVocabulary;\n};\n\n// \"Refresh from page\" (spec 2026-09-23 §4.2): the operator says the region\n// changed. The capture runs INSIDE the AdaptiveSlot — only it holds the\n// children the element-tree parity check needs — so this module just forces\n// the original to show and leaves the request here for the slot to take.\n// `session` is a promise: the token arrives by exchange after this module ran,\n// but the slot's capture effect may run first and only once — holding the\n// promise lets it take the request now and post when the token lands.\ntype RegionRefresh = { slotId: string; session: ReturnType<typeof editorSession>; base: string };\nlet pendingRefresh: RegionRefresh | null = null;\n\n/** The refresh this page was opened for, if it targets `slotId`. Taken once. */\nexport function takeRegionRefresh(slotId: string): RegionRefresh | null {\n if (pendingRefresh?.slotId !== slotId) return null;\n const r = pendingRefresh;\n pendingRefresh = null;\n return r;\n}\n\n/** Post a trusted skeleton and tell the operator how it went. */\nexport function submitRegionRefresh(r: RegionRefresh, body: Record<string, unknown>): void {\n void r.session\n .then((s) => {\n if (!s || !('token' in s)) throw new Error('no editor session');\n return fetch(`${r.base}/editor/region-skeleton`, {\n method: 'POST',\n headers: { authorization: `Bearer ${s.token}`, 'content-type': 'application/json' },\n body: JSON.stringify({ slotId: r.slotId, ...body }),\n });\n })\n .then((res) =>\n mountBar(res.ok ? 'Region refreshed — you can regenerate its versions now.' : 'Couldn’t refresh this region — reopen the link from your dashboard.'),\n )\n .catch(() => mountBar('Couldn’t refresh this region — check your connection and reopen the link from your dashboard.'));\n}\n\n/** Start the on-site cell preview when the URL asks for one. Idempotent. */\nexport function maybeStartCellPreview(apiBaseUrl?: string): void {\n if (typeof window === 'undefined' || typeof document === 'undefined') return;\n if (document.getElementById(BAR_ID)) return;\n let cell: string | null;\n let refresh: string | null;\n try {\n const params = new URLSearchParams(window.location.search);\n cell = params.get(PARAM_CELL);\n refresh = params.get(PARAM_REFRESH);\n } catch {\n return;\n }\n if (!cell && !refresh) return;\n const base = (apiBaseUrl ?? 'https://api.sentient-ui.com/v1').replace(/\\/$/, '');\n const session = editorSession(base);\n // Only an operator's session acts on these params; a visitor who lands on a\n // shared ?sentient_refresh_region= URL gets the normal page.\n if (!editorSessionActive()) return;\n if (refresh) {\n pendingRefresh = { slotId: refresh, session, base };\n // Force the original: a served version on screen is not the region.\n // 'override' records no exposure, so the refresh visit is never a trial.\n setSlotConfigOverride(refresh, { kind: 'arms' });\n setSlotOverride(refresh, PREVIEW_ARM);\n notifyOverridesChanged();\n return;\n }\n if (!cell) return;\n const sep = cell.lastIndexOf('~');\n if (sep <= 0) return;\n const slotId = cell.slice(0, sep);\n const persona = cell.slice(sep + 1);\n\n void session\n .then((s) => {\n // No code and nothing cached: a bare param, not an editor session.\n if (!s) return null;\n if (!('token' in s)) {\n mountBar(s.error === 401\n ? 'This preview link has expired — reopen it from your dashboard.'\n : 'Couldn’t load this preview — reopen it from your dashboard.');\n return null;\n }\n return fetch(`${base}/editor/cell-preview?slotId=${encodeURIComponent(slotId)}&persona=${encodeURIComponent(persona)}`, {\n headers: { authorization: `Bearer ${s.token}` },\n });\n })\n .then(async (res) => {\n if (!res) return;\n if (!res.ok) {\n mountBar(res.status === 401\n ? 'This preview link has expired — reopen it from your dashboard.'\n : 'Couldn’t load this preview — reopen it from your dashboard.');\n return;\n }\n const data = (await res.json()) as CellPreviewResponse;\n if (data.vocabulary && Array.isArray(data.vocabulary.entries)) setVocabularyOverride(data.vocabulary);\n if (data.compose != null) {\n setSlotConfigOverride(slotId, { kind: 'arms', compose: { [PREVIEW_ARM]: data.compose as ComposeArm } });\n setSlotOverride(slotId, PREVIEW_ARM);\n } else if (data.edits != null && typeof data.skeletonFp === 'string' && Array.isArray(data.leafToNode)) {\n setSlotConfigOverride(slotId, { kind: 'arms', edits: { edits: data.edits as never, fp: data.skeletonFp, leafToNode: data.leafToNode } });\n setSlotOverride(slotId, PREVIEW_ARM);\n } else if (data.blocks != null) {\n setSlotConfigOverride(slotId, { kind: 'arms', blocks: { [PREVIEW_ARM]: data.blocks } } as never);\n setSlotOverride(slotId, PREVIEW_ARM);\n } else if (data.content != null) {\n setSlotConfigOverride(slotId, { kind: 'arms', content: data.content });\n setSlotOverride(slotId, PREVIEW_ARM);\n } else {\n mountBar('Nothing to preview in that square yet.');\n return;\n }\n notifyOverridesChanged();\n mountBar(\n `Previewing “${data.slotName}” for ${data.personaDisplay}${data.status === 'review' ? ' — waiting for your approval' : ''}. Nothing is being tracked.`,\n );\n // Bring the slot into view once it re-renders with the forced arm.\n setTimeout(() => {\n try {\n document.querySelector(`[data-sentient-slot=\"${slotId}\"]`)?.scrollIntoView({ block: 'center' });\n } catch {\n /* older browsers */\n }\n }, 300);\n })\n .catch(() => mountBar('Couldn’t load this preview — check your connection and reopen it from your dashboard.'));\n}\n\nfunction mountBar(text: string): void {\n if (document.getElementById(BAR_ID)) return;\n const bar = document.createElement('div');\n bar.id = BAR_ID;\n Object.assign(bar.style, {\n position: 'fixed', bottom: '16px', left: '50%', transform: 'translateX(-50%)', zIndex: '2147483647',\n display: 'flex', alignItems: 'center', gap: '10px', padding: '10px 14px', borderRadius: '12px',\n maxWidth: '90vw', background: '#111827', color: '#fff', font: '13px system-ui, sans-serif',\n border: '1px solid rgba(139,92,246,0.6)', boxShadow: '0 10px 34px rgba(0,0,0,0.45)',\n } satisfies Partial<CSSStyleDeclaration>);\n const label = document.createElement('span');\n label.textContent = text;\n const exit = document.createElement('button');\n exit.textContent = 'Exit preview';\n Object.assign(exit.style, {\n padding: '4px 10px', borderRadius: '999px', border: '1px solid rgba(255,255,255,0.35)',\n background: 'transparent', color: '#fff', font: '12px system-ui, sans-serif', cursor: 'pointer',\n } satisfies Partial<CSSStyleDeclaration>);\n exit.onclick = () => {\n endEditorSession();\n const url = new URL(window.location.href);\n url.searchParams.delete(PARAM_CELL);\n url.searchParams.delete(PARAM_REFRESH);\n window.location.assign(url.toString());\n };\n bar.append(label, exit);\n (document.body ?? document.documentElement).append(bar);\n}\n","// Style-vocabulary capture for React installs (native generation phase 2).\n// React sites never load the snippet editor, so without this a React project\n// (Bodyshop) would only ever get the crawler's colorless guess. Runs ONLY when\n// this page load exchanged a fresh editor code (#sentient_editor_code=, see\n// editor-session.ts), i.e. when an operator opened the page from the dashboard\n// — never for visitors, and not on every later page of a cached session. The\n// sampler is a separate core subpath, dynamically imported, so the normal\n// bundle pays nothing.\nimport { editorSession, resetEditorSessionForTests } from './editor-session.js';\n\nlet started = false;\n\nexport function maybeCaptureStyles(apiBaseUrl?: string): void {\n if (started || typeof window === 'undefined') return;\n started = true;\n const base = (apiBaseUrl ?? 'https://api.sentient-ui.com/v1').replace(/\\/$/, '');\n void editorSession(base).then((session) => {\n if (!session || !('token' in session) || !session.fresh) return;\n capture(base, session.token);\n });\n}\n\nfunction capture(base: string, token: string): void {\n // After load + 1s, so client-rendered heroes exist before we look.\n const run = (): void => {\n window.setTimeout(() => {\n void import('@sentientui/core/style-sample')\n .then(({ sampleStyleVocabulary }) =>\n fetch(`${base}/editor/style-vocabulary`, {\n method: 'POST',\n headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },\n body: JSON.stringify(sampleStyleVocabulary(document)),\n }),\n )\n .catch(() => undefined);\n }, 1000);\n };\n if (document.readyState === 'complete') run();\n else window.addEventListener('load', run, { once: true });\n}\n\n/** Test hook. */\nexport function resetStyleCaptureForTests(): void {\n started = false;\n resetEditorSessionForTests();\n}\n","import { notifyOverridesChanged } from '../override-events.js';\n\nexport type ScenarioWeight = { variantId: string; pulls: number; avgReward: number };\nexport type ScenarioApiOverride =\n | 'error'\n | number\n | { status?: number; body?: unknown; delayMs?: number };\n\nexport type SentientScenario = {\n variants?: Record<string, string>;\n layout?: string[];\n /** Forced persona key (any project vocabulary key). Also sets the persona html attributes. */\n persona?: string;\n /** Persona confidence 0–1; buckets to low/medium/high for the html attribute. Default 1. */\n confidence?: number;\n /** Forced slot results: slot id → arm id (arms slots) or per-dim values (token slots). */\n slots?: Record<string, string | Record<string, string>>;\n /** Forced registry slot config (AdaptiveSlot content/blocks): slot id → entry.\n * Pair with `slots` to name which arm is \"served\" (blocks are keyed by arm). */\n slotConfig?: Record<string, unknown>;\n weights?: Record<string, ScenarioWeight[]>;\n api?: Record<string, ScenarioApiOverride>;\n};\n\ntype ScenarioWindow = {\n __sentient_overrides?: Record<string, string>;\n __sentient_layout_override?: string[];\n __sentient_slot_overrides?: Record<string, string | Record<string, string>>;\n __sentient_slot_config_overrides?: Record<string, unknown>;\n __sentient_persona_override?: { persona: string; confidence?: number };\n};\n\n/**\n * Confidence → band. Cutoffs pinned to @sentientui/policy `confidenceBand`\n * (<0.3 low, <0.7 medium, else high). Duplicated (not imported) because the\n * Playwright init function is serialized into the page and cannot close\n * over imports — both copies are pinned by tests.\n */\nexport function confidenceBandOf(c: number): 'low' | 'medium' | 'high' {\n return c < 0.3 ? 'low' : c < 0.7 ? 'medium' : 'high';\n}\n\n/** Apply a scenario by setting the client-forcing globals the SDK reads. */\nexport function applyScenario(scenario: SentientScenario = {}): void {\n const w = window as unknown as ScenarioWindow;\n w.__sentient_overrides = { ...(scenario.variants ?? {}) };\n if (scenario.layout) w.__sentient_layout_override = scenario.layout;\n else delete w.__sentient_layout_override;\n if (scenario.slots) w.__sentient_slot_overrides = { ...scenario.slots };\n else delete w.__sentient_slot_overrides;\n if (scenario.slotConfig) w.__sentient_slot_config_overrides = { ...scenario.slotConfig };\n else delete w.__sentient_slot_config_overrides;\n if (scenario.persona) {\n w.__sentient_persona_override = {\n persona: scenario.persona,\n confidence: scenario.confidence ?? 1,\n };\n try {\n const d = document.documentElement;\n d.setAttribute('data-sentient-persona', scenario.persona);\n d.setAttribute('data-sentient-confidence', confidenceBandOf(scenario.confidence ?? 1));\n } catch {\n /* no DOM (node env) — the override globals still apply */\n }\n } else {\n delete w.__sentient_persona_override;\n }\n // Ring the override bus so hooks already mounted (useAssignment /\n // useSlotResult / useAdaptivePersona subscribe via useSyncExternalStore)\n // re-render immediately — otherwise forcing state mid-test only takes effect\n // on the next unrelated render.\n notifyOverridesChanged();\n}\n\n/** Clear all forced state. */\nexport function resetScenario(): void {\n const w = window as unknown as ScenarioWindow;\n delete w.__sentient_overrides;\n delete w.__sentient_layout_override;\n delete w.__sentient_slot_overrides;\n delete w.__sentient_slot_config_overrides;\n delete w.__sentient_persona_override;\n try {\n document.documentElement.removeAttribute('data-sentient-persona');\n document.documentElement.removeAttribute('data-sentient-confidence');\n } catch {\n /* no DOM */\n }\n notifyOverridesChanged();\n}\n"],"mappings":";66BAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,wBAAAE,KAAA,eAAAC,GAAAH,IAMA,IAAAI,GAA8D,kCCF9D,IAAAC,EAUO,iBACPC,EAWO,4BCVP,IAAMC,GAAQ,IAAI,IACZC,GAAY,IAAI,IAuBf,SAASC,GAAOC,EAAqBC,EAAiC,CAC3EC,GAAM,IAAIF,EAAaC,CAAO,EAC9B,IAAME,EAAMC,GAAU,IAAIJ,CAAW,EACrC,GAAKG,EACL,QAAWE,KAAMF,EACf,GAAI,CACFE,EAAGJ,CAAO,CACZ,OAAQK,EAAA,CAER,CAEJ,CChDA,IAAMC,GAA4B,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GAAgC,CAAC,Ec73BhC,SAASC,GAAiBC,EAAsC,CACrE,OAAOA,EAAI,GAAM,MAAQA,EAAI,GAAM,SAAW,MAChD,CAGO,SAASC,GAAcC,EAA6B,CAAC,EAAS,CA3CrE,IAAAC,EAAAC,EAAAC,EA4CE,IAAMC,EAAI,OAQV,GAPAA,EAAE,qBAAuBC,EAAA,IAAMJ,EAAAD,EAAS,WAAT,KAAAC,EAAqB,CAAC,GACjDD,EAAS,OAAQI,EAAE,2BAA6BJ,EAAS,OACxD,OAAOI,EAAE,2BACVJ,EAAS,MAAOI,EAAE,0BAA4BC,EAAA,GAAKL,EAAS,OAC3D,OAAOI,EAAE,0BACVJ,EAAS,WAAYI,EAAE,iCAAmCC,EAAA,GAAKL,EAAS,YACvE,OAAOI,EAAE,iCACVJ,EAAS,QAAS,CACpBI,EAAE,4BAA8B,CAC9B,QAASJ,EAAS,QAClB,YAAYE,EAAAF,EAAS,aAAT,KAAAE,EAAuB,CACrC,EACA,GAAI,CACF,IAAM,EAAI,SAAS,gBACnB,EAAE,aAAa,wBAAyBF,EAAS,OAAO,EACxD,EAAE,aAAa,2BAA4BH,IAAiBM,EAAAH,EAAS,aAAT,KAAAG,EAAuB,CAAC,CAAC,CACvF,OAAQG,EAAA,CAER,CACF,MACE,OAAOF,EAAE,4BAMXG,EAAuB,CACzB,CflDI,IAAAC,GAAA,6BAPG,SAASC,GACdC,EACAC,EAA6B,CAAC,EAC9BC,EACc,CACd,OAAAC,GAAcF,CAAQ,KACf,cACL,QAACG,GAAA,CAAiB,OAAO,UAAU,QAAS,GACzC,SAAAJ,EACH,EACAE,CACF,CACF","names":["react_exports","__export","renderWithSentient","__toCommonJS","import_react","import_react","import_core","store","listeners","update","componentId","weights","store","set","listeners","cb","e","ssrFallback","state","w","setPreviewMode","on","s","fn","getPreviewMode","subscribePreview","listeners","createPreviewClient","inner","componentId","segment","_a","_b","variantIds","agentData","agentDataByVariant","opts","slotId","ids","EVENT","notifyOverridesChanged","_a","w","EVENT","publishDevtoolsConfig","config","isDevBuild","ssrFallback","state","w","emit","fn","registerSections","sections","isDevBuild","state","emit","version","SDK_IDENT","store","w","setSlotConfigOverride","slotId","entry","setVocabularyOverride","v","store","w","setSlotOverride","slotId","result","takeHashParam","name","v","h","m","after","rest","e","TOKEN_KEY","pending","active","editorSessionActive","cached","editorSession","apiBase","code","takeHashParam","t","res","token","e","endEditorSession","PARAM_CELL","PARAM_REFRESH","BAR_ID","PREVIEW_ARM","pendingRefresh","maybeStartCellPreview","apiBaseUrl","BAR_ID","cell","refresh","params","PARAM_CELL","PARAM_REFRESH","e","base","session","editorSession","editorSessionActive","pendingRefresh","setSlotConfigOverride","setSlotOverride","PREVIEW_ARM","notifyOverridesChanged","sep","slotId","persona","s","mountBar","res","data","setVocabularyOverride","_a","text","bar","label","exit","endEditorSession","url","started","maybeCaptureStyles","apiBaseUrl","base","editorSession","session","capture","token","run","sampleStyleVocabulary","import_jsx_runtime","deriveDefaultSegment","_a","_b","e","DEFAULT_API_BASE_URL","AdaptiveContext","warnedNoConsentGate","answeredThisPage","useConsentSource","source","apiKey","onRefused","onRefusedRef","granted","setGranted","refused","setRefused","sourceRef","key","__spreadProps","__spreadValues","s","stop","cancelled","consentWatcher","forgetVisitor","watcher","wasRefused","update","r","g","AdaptiveProvider","props","_c","_d","_e","_f","client","setClient","sessionSegment","previewOn","setPreviewOn","getPreviewMode","subscribePreview","maybeStartCellPreview","setPreviewMode","m","maybeCaptureStyles","dropHeldRef","consent","forgetOnFalse","forgetRef","clientRef","trackingRef","heldRef","refusedRef","c","tracking","adopt","config","SDK_IDENT","created","stopEngagement","handOff","call","startEngagement","startEngagementCapture","initGraph","poll","entries","entry","weights","v","timerId","ssrFallback","apiBaseUrl","frozenConfigRef","isDevBuild","current","prev","publishDevtoolsConfig","identityUser","identityHash","identityEmail","decided","registerSections","declared","present","el","missing","id","exposedClient","createPreviewClient","value","_g","_h","_i","NO_UNIFIED","NO_UNIFIED","confidenceBandOf","c","applyScenario","scenario","_a","_b","_c","w","__spreadValues","e","notifyOverridesChanged","import_jsx_runtime","renderWithSentient","ui","scenario","options","applyScenario","AdaptiveProvider"]}