@sentientui/react 0.39.0 → 0.39.1
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/next/adaptive-root.tsx","../../src/persona-script.tsx","../../src/server.ts","../../src/agent-feed.ts","../../src/next/log-agent-fetch.ts","../../src/next/agent-feed-route.ts"],"sourcesContent":["import { deriveSessionSegment, exposedStage, extractTrackedParams, matchedAgentToken } from '@sentientui/core';\nimport { consentFromCookies } from '@sentientui/core/consent';\nimport type { SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX, ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type LoadAdaptiveDecisionResult,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\n// Re-exported from core on the SERVER entry (this module is server-only — it\n// imports next/headers). Lets server components do agent detection with just the\n// `@sentientui/react` package, no direct core dependency. Do NOT add this to the\n// package's client index: re-exporting a plain function through a 'use client'\n// module turns it into a client reference that throws when called during SSR.\nexport { matchedAgentToken, uaTokenMatch, agentIntent, classifiedAgents } from '@sentientui/core';\nexport type { AgentIntent } from '@sentientui/core';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\nexport type AdaptiveRootProps = Omit<\n AdaptiveProviderProps,\n // Every provider prop AdaptiveRoot itself resolves and passes AFTER the\n // {...providerProps} spread must be omitted here: a caller-supplied value\n // would typecheck but be silently clobbered by the spread order\n // (initialLayoutOrder, declaredSections and sessionSegment were missing\n // from this list and suffered exactly that).\n | 'initialAssignments'\n | 'onAssignment'\n | 'initialSlots'\n | 'initialSlotConfig'\n | 'initialPalette'\n | 'initialVocabulary'\n | 'initialPersona'\n | 'initialLayoutOrder'\n | 'declaredSections'\n | 'sessionSegment'\n | 'consentFrom'\n> & {\n /**\n * Consent source — see `AdaptiveProviderProps.consentFrom`. A platform preset\n * (`'cookiebot'`, `'onetrust'`, `'cookieyes'`, `'tcf'`, `'google-consent-mode'`)\n * or a cookie. Resolved on the server from the platform's own cookie, so a\n * visitor who already consented gets SSR with no layout shift.\n *\n * No `check` form: AdaptiveRoot is a Server Component and spreads\n * this straight into its client boundary, and a function prop crossing the\n * server→client boundary throws at render (\"Functions cannot be passed\n * directly to Client Components\"). The provider's type accepted `check`, so\n * a Cookiebot-style predicate typechecked here and then crashed the layout.\n * Need a JS-API CMP predicate? Use `<AdaptiveProvider>` in a client component.\n */\n consentFrom?: Exclude<NonNullable<AdaptiveProviderProps['consentFrom']>, { check?: () => boolean; cmp?: undefined }> | { cmp?: undefined; cookie?: string; value?: string; event?: string };\n /**\n * Code-variant components to assign server-side (SEO-safe). Optional — an\n * `<Adaptive>` works without an entry here and assigns after mount.\n *\n * List only ids this tree actually renders. Each one is assigned on every\n * request, rendered or not, and every assignment logs an impression (or a\n * holdout exposure). An id the page never renders therefore accrues trials\n * that cannot convert, and in a root layout that happens on every route.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * Give each section's rendered element `data-sentient-id=\"<sectionId>\"` —\n * the only markup a section needs — so the DOM graph scanner can register\n * it under the same id. Without it the server never learns what the section\n * IS, types it `generic`, and serves the identity order to every persona —\n * the integration looks live but cannot personalize. The provider warns\n * about unresolvable ids in development. Correct a section the content\n * classifier mistypes with `sectionTypes`, not extra markup.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n * // …and in the tree: <section data-sentient-id=\"pricing\">\n */\n sections?: string[];\n /**\n * Adaptive-slot declarations used by `useAdaptiveTokens` / `AdaptiveGroup`\n * in this tree. Declaring them here decides them in the same SSR\n * round trip, so their values serialize into the server HTML.\n */\n slots?: SlotDeclInput[];\n /**\n * The generated-mode `<Adaptive id>`s THIS page renders. Declaring them\n * decides their published versions in the same SSR round trip\n * (`/v1/decide` registry mode) and serializes the served content into the\n * server HTML, so the first paint shows the version rather than the\n * original children until the client-side decide answers. Without it a\n * registry slot renders its children first and swaps after mount.\n *\n * Scoped to exactly these ids on purpose: an unscoped registry decide\n * records a close-out trial for every published slot on every page.\n *\n * @example registrySlotIds={['hero-headline', 'pricing-cta']}\n */\n registrySlotIds?: string[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /**\n * The page's `searchParams` prop (or an equivalent query string /\n * URLSearchParams). Server Components cannot read the request URL from\n * `headers()`, so without this the SSR-minted session carries no `utm_*`\n * params and no ad click IDs (gclid, fbclid, ttclid, …) — campaign\n * attribution only lands after client hydration, and never for visits the\n * client SDK doesn't get to finish (bounce before hydrate). Pass it on\n * landing pages that receive ad traffic:\n *\n * ```tsx\n * export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {\n * return <AdaptiveRoot ... searchParams={await searchParams}>...</AdaptiveRoot>;\n * }\n * ```\n */\n searchParams?: Record<string, string | string[] | undefined> | URLSearchParams | string;\n /**\n * The page's path (e.g. `/products/trail-shoe`). Server components cannot\n * read their own URL, so pass it on landing pages that receive ad or email\n * traffic: with it, a paid click to a product page or a `/discount/` link\n * is recognised on the server render — adapted from the first byte.\n */\n pathname?: string;\n /** Override: when set no network fetch is made. Useful for tests. */\n initialAssignments?: ServerAssignments;\n /**\n * Milliseconds to wait for the API before rendering default variants.\n * Defaults to 1000. The hot path typically returns in well under 150 ms;\n * the full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host. Lower it if your API is\n * co-located and warm.\n */\n timeoutMs?: number;\n /**\n * When set, AdaptiveRoot emits a server-rendered inline JSON-LD block\n * describing the page's winning variants, layout order, and developer-supplied\n * content — readable by passive AI crawlers (which do not run JS). Invisible to\n * humans (a JSON-LD script renders no visible DOM). Omit to emit nothing.\n */\n agentFeed?: {\n /** Page path for the feed. Falls back to the `x-pathname` request header, then '/'. */\n path?: string;\n /** Structured page content. Falls back to the `defineAgentContent` registry for this path. */\n content?: Record<string, unknown>;\n };\n /**\n * When true (default), a known AI-agent fetch (matched by user-agent —\n * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side\n * to your agent analytics. Machine telemetry only (no cookie, no session);\n * fire-and-forget, never affects render. Set false to opt out.\n */\n captureAgents?: boolean;\n /**\n * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.\n * Pass through from Next.js middleware / `headers()` when using a strict CSP.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * A cookie's value exactly as the browser sent it. The CMP parsers need the\n * raw form: Next's cookies() decodes every value, which turns an encoded\n * `&groups=C0002:1` inside OneTrust's `landingPath` (a crafted link, before\n * any answer) into a real field that read as consent on the server — SSR\n * then minted a session and handed the client consent={true} (grader R8 NEW-1).\n * First match wins, like the browser's document.cookie read. A consent cookie\n * set only by middleware in this request is not in the header: the server\n * then reads \"unknown\" and the browser decides (fail-closed).\n */\nfunction rawCookie(header: string | null | undefined, name: string): string | undefined {\n if (!header) return undefined;\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq > 0 && part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();\n }\n return undefined;\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout. Declared on the page (not the root\n * // layout) because hero_cta renders only here; see the `components` prop.\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components = [],\n sections,\n slots,\n registrySlotIds,\n appOrigin,\n searchParams,\n pathname,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n captureAgents,\n nonce,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Landing-URL attribution (utm_* + ad click IDs). Only available when the\n // page passes its searchParams down — headers() never carries the request's\n // own query string, and the Referer is the PREVIOUS page, not this one.\n const { utmParams, clickIds } = extractTrackedParams(searchParams ?? {});\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `consent: false` must gate the SERVER too, not just the client. Without\n // this the SSR decide/assign still ran and still minted a session row for a\n // visitor who had not consented — contradicting the documented contract\n // (\"no SDK is initialised, no cookies are written, no events are sent\") and\n // forcing sites to hide AdaptiveRoot behind a conditional render, which is\n // what made consent-after-load cost a full server round trip.\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n // This is a Server Component and already has the request cookies, so resolve\n // a cookie-based `consentFrom` here rather than making the app read the same\n // cookie again just to pass `consent` — naming it twice only invites drift.\n // An already-consented visitor therefore gets SSR variant assignment (zero\n // layout shift) with no extra code.\n //\n // An explicit `consent` prop always wins — it is the escape hatch for apps\n // that track consent elsewhere. (No `check()` form here: see the prop type.)\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n // The platform's own cookie (Cookiebot CookieConsent, OneTrust\n // OptanonConsent, CookieYes, the TCF string). Unknown (no cookie yet, a\n // JS-only source like Consent Mode) stays undefined → gated below; the\n // browser decides after hydration. A fixed-value cookie comparison could not\n // express Cookiebot's or OneTrust's format, so consented visitors on those\n // platforms were never server-rendered.\n const consent =\n providerProps.consent ??\n (cf ? (consentFromCookies(cf, (name) => rawCookie(headerStore.get('cookie'), name)) ?? undefined) : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n\n // SSR preload MUST hit the same API host the client will use, otherwise the\n // SSR-minted session lives on the wrong host and the client's first /assign\n // misses it and re-mints — silently breaking SSR→client continuity for any\n // non-default / self-hosted deployment. The client derives its base from\n // apiBaseUrl too (see provider.tsx), so thread the same value here.\n const baseUrl = providerProps.apiBaseUrl\n ? providerProps.apiBaseUrl.replace(/\\/$/, '')\n : DEFAULT_API_BASE_URL;\n\n // Server-side agent-fetch capture (spec: nextjs-agent-fetch-capture). JS-less\n // assistants (GPTBot / ChatGPT-User / Claude-User / PerplexityBot / …) never\n // run client JS, but they trigger SSR — so AdaptiveRoot sees their UA here.\n // Fire-and-forget; never blocks or breaks render. `agentPath` is reused by the\n // agentFeed JSON-LD below.\n const agentPath = agentFeed?.path ?? headerStore.get('x-pathname') ?? '/';\n const agentBot = matchedAgentToken(userAgent ?? '');\n if (captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialSlotConfig: LoadAdaptiveDecisionResult['slotConfig'];\n let initialPalette: LoadAdaptiveDecisionResult['palette'];\n let initialVocabulary: LoadAdaptiveDecisionResult['vocabulary'];\n let initialPersona: { persona: string; confidence: number } | null = null;\n // Opt-in theme attribute: this request's stage, coarsened unless 'detailed'.\n let initialStage: string | null = null;\n let ssrSessionId: string | undefined;\n\n // Registry mode only when ids were declared: an unscoped registry decide\n // records a close-out trial for every published slot on every page.\n const registry = !!registrySlotIds?.length;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (skipSsr) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0) || registry) {\n // `loadAdaptiveDecision` accepted `registrySlotIds` long before AdaptiveRoot\n // passed them, so an `<Adaptive id>` under AdaptiveRoot showed its original\n // children on first paint until the client-side decide returned.\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n ...(registry ? { slotsFrom: 'registry' as const, registrySlotIds } : {}),\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n landingPath: pathname,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialSlotConfig = decision.slotConfig;\n initialPalette = decision.palette;\n // The site styles the served Redesign trees borrow. Without forwarding\n // them, SSR sites (Bodyshop, 2026-09-24) rendered an approved redesign\n // with no site classes at all — black palette buttons and near-invisible\n // text on a navy card — because the client never re-decides a preloaded\n // slot and so never receives them either.\n initialVocabulary = decision.vocabulary;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n initialStage = exposedStage(decision.stage, providerProps.stageAttributes);\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n landingPath: pathname,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n // Not for a request that must not be tracked (DNT/GPC, consent refused or\n // not yet known): with no server decision the script's fallback reads the\n // stored snapshot from localStorage, and reading the device's storage before\n // consent is exactly what a consent gate exists to prevent. The browser SDK\n // takes over once the visitor's platform says yes.\n const personaScript = skipSsr ? null : (\n <SentientPersonaScript\n apiKey={providerProps.apiKey}\n persona={initialPersona}\n nonce={nonce}\n stageAttributes={providerProps.stageAttributes}\n stage={initialStage}\n />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // The same nonce also covers the <style> the client injects (reveal).\n nonce={nonce}\n // Forward the server-resolved value so a consented visitor's client does\n // not start gated and re-resolve the same cookie on mount.\n consent={consent}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n // Declared regardless of what came back, so devtools can preview layout on\n // a page whose decision was gated or timed out.\n declaredSections={sections}\n initialSlots={initialSlots}\n // Registry-mode preload: the hook treats a preloaded slot config as\n // settled, so the client does not decide the same slot a second time.\n initialSlotConfig={initialSlotConfig}\n initialPalette={initialPalette}\n initialVocabulary={initialVocabulary}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) {\n return (\n <>\n {personaScript}\n {client}\n </>\n );\n }\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const feed = buildAgentFeed({\n page: agentPath,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\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 type { JSX } from 'react';\nimport { renderPrePaintScript, type StageAttributes } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n /**\n * The same consent gate you give the provider. With `consent={false}`, or a\n * `consentFrom` source and no `consent={true}`, nothing is rendered: the\n * fallback reads the stored decision from the visitor's device, and that\n * must wait for consent (grader F3). `AdaptiveRoot` handles this for you.\n */\n consent?: boolean;\n consentFrom?: unknown;\n /**\n * Opt-in `data-sentient-stage` (see `AdaptiveProviderProps.stageAttributes`).\n * With a server decision, pass the value to write as `stage` (already\n * coarsened — `exposedStage` from `@sentientui/core`); without one the\n * script copies the stage the visitor's last decide stored.\n */\n stageAttributes?: StageAttributes;\n /** The stage value to write, from this request's decide; null writes none. */\n stage?: string | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n // The stage first, with its own single-writer check: an already-set\n // persona must not stop it. Only a value this request's decide gave.\n (props.stage\n ? 'if(!d.hasAttribute(\"data-sentient-stage\"))d.setAttribute(\"data-sentient-stage\",' + inlineJsString(props.stage) + ');'\n : '') +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey, props.stageAttributes ? { stage: true } : undefined);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element | null {\n // A server-decided persona is not a storage read, so it always renders.\n if (!props.persona && (props.consent === false || (props.consentFrom !== undefined && props.consent !== true))) return null;\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\n * `utm_*` params from the landing URL. The Referer header never carries the\n * page's OWN query string, so without this the SSR-minted session has no\n * campaign attribution until the client SDK hydrates and re-upserts.\n * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.\n */\n utmParams?: Record<string, string>;\n /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */\n clickIds?: Record<string, string>;\n /** The landing page's path (no query string) — recognises a paid click to a product page or a `/discount/` link on the first decision. */\n landingPath?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"+lBAAA,OAAS,wBAAAA,GAAsB,gBAAAC,GAAc,wBAAAC,GAAsB,qBAAAC,OAAyB,mBAC5F,OAAS,sBAAAC,OAA0B,2BAEnC,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCAjC,OAAS,wBAAAC,OAAkD,mBAC3D,OAAS,kBAAAC,OAAsB,qBA4E3B,cAAAC,OAAA,oBAvCJ,SAASC,EAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAAK,EAAE,QAAQ,KAAM,SAAS,CACtD,CAGO,SAASC,GAAkBC,EAA2C,CAC3E,OAAIA,EAAM,QAEN,mDAGCA,EAAM,MACH,kFAAoFH,EAAeG,EAAM,KAAK,EAAI,KAClH,IACJ,4FAC4CH,EAAeG,EAAM,QAAQ,OAAO,EAAI,+CACrCH,EAAeF,GAAeK,EAAM,QAAQ,UAAU,CAAC,EAAI,qBAIvGN,GAAqBM,EAAM,OAAQA,EAAM,gBAAkB,CAAE,MAAO,EAAK,EAAI,MAAS,CAC/F,CAcO,SAASC,GAAsBD,EAAuD,CAE3F,MAAI,CAACA,EAAM,UAAYA,EAAM,UAAY,IAAUA,EA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Segment","exposedStage","extractTrackedParams","matchedAgentToken","consentFromCookies","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","rawCookie","header","name","part","eq","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","components","sections","slots","registrySlotIds","appOrigin","searchParams","pathname","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","utmParams","clickIds","extractTrackedParams","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","consentFromCookies","skipSsr","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialLayoutOrder","initialSlots","initialSlotConfig","initialPalette","initialVocabulary","initialPersona","initialStage","ssrSessionId","registry","decision","loadAdaptiveDecision","__spreadProps","__spreadValues","exposedStage","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","feed","buildAgentFeed","renderAgentJsonLdBody"]}
|
|
1
|
+
{"version":3,"sources":["../../src/next/adaptive-root.tsx","../../src/persona-script.tsx","../../src/server.ts","../../src/agent-feed.ts","../../src/next/log-agent-fetch.ts","../../src/next/agent-feed-route.ts"],"sourcesContent":["import { deriveSessionSegment, exposedStage, extractTrackedParams, matchedAgentToken } from '@sentientui/core';\nimport { consentFromCookies } from '@sentientui/core/consent';\nimport type { SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX, ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type LoadAdaptiveDecisionResult,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\n// Re-exported from core on the SERVER entry (this module is server-only — it\n// imports next/headers). Lets server components do agent detection with just the\n// `@sentientui/react` package, no direct core dependency. Do NOT add this to the\n// package's client index: re-exporting a plain function through a 'use client'\n// module turns it into a client reference that throws when called during SSR.\nexport { matchedAgentToken, uaTokenMatch, agentIntent, classifiedAgents } from '@sentientui/core';\nexport type { AgentIntent } from '@sentientui/core';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\nexport type AdaptiveRootProps = Omit<\n AdaptiveProviderProps,\n // Every provider prop AdaptiveRoot itself resolves and passes AFTER the\n // {...providerProps} spread must be omitted here: a caller-supplied value\n // would typecheck but be silently clobbered by the spread order\n // (initialLayoutOrder, declaredSections and sessionSegment were missing\n // from this list and suffered exactly that).\n | 'initialAssignments'\n | 'onAssignment'\n | 'initialSlots'\n | 'initialSlotConfig'\n | 'initialPalette'\n | 'initialVocabulary'\n | 'initialPersona'\n | 'initialLayoutOrder'\n | 'declaredSections'\n | 'sessionSegment'\n | 'consentFrom'\n> & {\n /**\n * Consent source — see `AdaptiveProviderProps.consentFrom`. A platform preset\n * (`'cookiebot'`, `'onetrust'`, `'cookieyes'`, `'tcf'`, `'google-consent-mode'`)\n * or a cookie. Resolved on the server from the platform's own cookie, so a\n * visitor who already consented gets SSR with no layout shift.\n *\n * No `check` form: AdaptiveRoot is a Server Component and spreads\n * this straight into its client boundary, and a function prop crossing the\n * server→client boundary throws at render (\"Functions cannot be passed\n * directly to Client Components\"). The provider's type accepted `check`, so\n * a Cookiebot-style predicate typechecked here and then crashed the layout.\n * Need a JS-API CMP predicate? Use `<AdaptiveProvider>` in a client component.\n */\n consentFrom?: Exclude<NonNullable<AdaptiveProviderProps['consentFrom']>, { check?: () => boolean; cmp?: undefined }> | { cmp?: undefined; cookie?: string; value?: string; event?: string };\n /**\n * Code-variant components to assign server-side (SEO-safe). Optional — an\n * `<Adaptive>` works without an entry here and assigns after mount.\n *\n * List only ids this tree actually renders. Each one is assigned on every\n * request, rendered or not, and every assignment logs an impression (or a\n * holdout exposure). An id the page never renders therefore accrues trials\n * that cannot convert, and in a root layout that happens on every route.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * Give each section's rendered element `data-sentient-id=\"<sectionId>\"` —\n * the only markup a section needs — so the DOM graph scanner can register\n * it under the same id. Without it the server never learns what the section\n * IS, types it `generic`, and serves the identity order to every persona —\n * the integration looks live but cannot personalize. The provider warns\n * about unresolvable ids in development. Correct a section the content\n * classifier mistypes with `sectionTypes`, not extra markup.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n * // …and in the tree: <section data-sentient-id=\"pricing\">\n */\n sections?: string[];\n /**\n * Adaptive-slot declarations used by `useAdaptiveTokens` / `AdaptiveGroup`\n * in this tree. Declaring them here decides them in the same SSR\n * round trip, so their values serialize into the server HTML.\n */\n slots?: SlotDeclInput[];\n /**\n * The generated-mode `<Adaptive id>`s THIS page renders. Declaring them\n * decides their published versions in the same SSR round trip\n * (`/v1/decide` registry mode) and serializes the served content into the\n * server HTML, so the first paint shows the version rather than the\n * original children until the client-side decide answers. Without it a\n * registry slot renders its children first and swaps after mount.\n *\n * Scoped to exactly these ids on purpose: an unscoped registry decide\n * records a close-out trial for every published slot on every page.\n *\n * @example registrySlotIds={['hero-headline', 'pricing-cta']}\n */\n registrySlotIds?: string[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /**\n * The page's `searchParams` prop (or an equivalent query string /\n * URLSearchParams). Server Components cannot read the request URL from\n * `headers()`, so without this the SSR-minted session carries no `utm_*`\n * params and no ad click IDs (gclid, fbclid, ttclid, …) — campaign\n * attribution only lands after client hydration, and never for visits the\n * client SDK doesn't get to finish (bounce before hydrate). Pass it on\n * landing pages that receive ad traffic:\n *\n * ```tsx\n * export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {\n * return <AdaptiveRoot ... searchParams={await searchParams}>...</AdaptiveRoot>;\n * }\n * ```\n */\n searchParams?: Record<string, string | string[] | undefined> | URLSearchParams | string;\n /**\n * The page's path (e.g. `/products/trail-shoe`). Server components cannot\n * read their own URL, so pass it on landing pages that receive ad or email\n * traffic: with it, a paid click to a product page or a `/discount/` link\n * is recognised on the server render — adapted from the first byte.\n */\n pathname?: string;\n /** Override: when set no network fetch is made. Useful for tests. */\n initialAssignments?: ServerAssignments;\n /**\n * Milliseconds to wait for the API before rendering default variants.\n * Defaults to 1000. The hot path typically returns in well under 150 ms;\n * the full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host. Lower it if your API is\n * co-located and warm.\n */\n timeoutMs?: number;\n /**\n * When set, AdaptiveRoot emits a server-rendered inline JSON-LD block\n * describing the page's winning variants, layout order, and developer-supplied\n * content — readable by passive AI crawlers (which do not run JS). Invisible to\n * humans (a JSON-LD script renders no visible DOM). Omit to emit nothing.\n */\n agentFeed?: {\n /** Page path for the feed. Falls back to the `x-pathname` request header, then '/'. */\n path?: string;\n /** Structured page content. Falls back to the `defineAgentContent` registry for this path. */\n content?: Record<string, unknown>;\n };\n /**\n * When true (default), a known AI-agent fetch (matched by user-agent —\n * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side\n * to your agent analytics. Machine telemetry only (no cookie, no session);\n * fire-and-forget, never affects render. Set false to opt out.\n */\n captureAgents?: boolean;\n /**\n * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.\n * Pass through from Next.js middleware / `headers()` when using a strict CSP.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * A cookie's value exactly as the browser sent it. The CMP parsers need the\n * raw form: Next's cookies() decodes every value, which turns an encoded\n * `&groups=C0002:1` inside OneTrust's `landingPath` (a crafted link, before\n * any answer) into a real field that read as consent on the server — SSR\n * then minted a session and handed the client consent={true} (grader R8 NEW-1).\n * First match wins, like the browser's document.cookie read. A consent cookie\n * set only by middleware in this request is not in the header: the server\n * then reads \"unknown\" and the browser decides (fail-closed).\n */\nfunction rawCookie(header: string | null | undefined, name: string): string | undefined {\n if (!header) return undefined;\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq > 0 && part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();\n }\n return undefined;\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout. Declared on the page (not the root\n * // layout) because hero_cta renders only here; see the `components` prop.\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components = [],\n sections,\n slots,\n registrySlotIds,\n appOrigin,\n searchParams,\n pathname,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n captureAgents,\n nonce,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Landing-URL attribution (utm_* + ad click IDs). Only available when the\n // page passes its searchParams down — headers() never carries the request's\n // own query string, and the Referer is the PREVIOUS page, not this one.\n const { utmParams, clickIds } = extractTrackedParams(searchParams ?? {});\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `consent: false` must gate the SERVER too, not just the client. Without\n // this the SSR decide/assign still ran and still minted a session row for a\n // visitor who had not consented — contradicting the documented contract\n // (\"no SDK is initialised, no cookies are written, no events are sent\") and\n // forcing sites to hide AdaptiveRoot behind a conditional render, which is\n // what made consent-after-load cost a full server round trip.\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n // This is a Server Component and already has the request cookies, so resolve\n // a cookie-based `consentFrom` here rather than making the app read the same\n // cookie again just to pass `consent` — naming it twice only invites drift.\n // An already-consented visitor therefore gets SSR variant assignment (zero\n // layout shift) with no extra code.\n //\n // An explicit `consent` prop always wins — it is the escape hatch for apps\n // that track consent elsewhere. (No `check()` form here: see the prop type.)\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n // The platform's own cookie (Cookiebot CookieConsent, OneTrust\n // OptanonConsent, CookieYes, the TCF string). Unknown (no cookie yet, a\n // JS-only source like Consent Mode) stays undefined → gated below; the\n // browser decides after hydration. A fixed-value cookie comparison could not\n // express Cookiebot's or OneTrust's format, so consented visitors on those\n // platforms were never server-rendered.\n const consent =\n providerProps.consent ??\n (cf ? (consentFromCookies(cf, (name) => rawCookie(headerStore.get('cookie'), name)) ?? undefined) : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n // Keyless local mode, by the client's own rule (core init: a `pk_` key or\n // `localMode: false` means hosted). The browser runs on simulated decisions\n // with no network, but the server still called the hosted API with the\n // empty key — every SSR request logged `session upsert failed (401)` and\n // spent a round trip on a decision the client would never use. Nothing\n // hosted runs server-side either.\n const keyless =\n providerProps.localMode === true ||\n (providerProps.localMode !== false && !(typeof providerProps.apiKey === 'string' && providerProps.apiKey.startsWith('pk_')));\n\n // SSR preload MUST hit the same API host the client will use, otherwise the\n // SSR-minted session lives on the wrong host and the client's first /assign\n // misses it and re-mints — silently breaking SSR→client continuity for any\n // non-default / self-hosted deployment. The client derives its base from\n // apiBaseUrl too (see provider.tsx), so thread the same value here.\n const baseUrl = providerProps.apiBaseUrl\n ? providerProps.apiBaseUrl.replace(/\\/$/, '')\n : DEFAULT_API_BASE_URL;\n\n // Server-side agent-fetch capture (spec: nextjs-agent-fetch-capture). JS-less\n // assistants (GPTBot / ChatGPT-User / Claude-User / PerplexityBot / …) never\n // run client JS, but they trigger SSR — so AdaptiveRoot sees their UA here.\n // Fire-and-forget; never blocks or breaks render. `agentPath` is reused by the\n // agentFeed JSON-LD below.\n const agentPath = agentFeed?.path ?? headerStore.get('x-pathname') ?? '/';\n const agentBot = matchedAgentToken(userAgent ?? '');\n if (!keyless && captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialSlotConfig: LoadAdaptiveDecisionResult['slotConfig'];\n let initialPalette: LoadAdaptiveDecisionResult['palette'];\n let initialVocabulary: LoadAdaptiveDecisionResult['vocabulary'];\n let initialPersona: { persona: string; confidence: number } | null = null;\n // Opt-in theme attribute: this request's stage, coarsened unless 'detailed'.\n let initialStage: string | null = null;\n let ssrSessionId: string | undefined;\n\n // Registry mode only when ids were declared: an unscoped registry decide\n // records a close-out trial for every published slot on every page.\n const registry = !!registrySlotIds?.length;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (skipSsr || keyless) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload. Keyless: the client's local engine decides.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0) || registry) {\n // `loadAdaptiveDecision` accepted `registrySlotIds` long before AdaptiveRoot\n // passed them, so an `<Adaptive id>` under AdaptiveRoot showed its original\n // children on first paint until the client-side decide returned.\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n ...(registry ? { slotsFrom: 'registry' as const, registrySlotIds } : {}),\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n landingPath: pathname,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialSlotConfig = decision.slotConfig;\n initialPalette = decision.palette;\n // The site styles the served Redesign trees borrow. Without forwarding\n // them, SSR sites (Bodyshop, 2026-09-24) rendered an approved redesign\n // with no site classes at all — black palette buttons and near-invisible\n // text on a navy card — because the client never re-decides a preloaded\n // slot and so never receives them either.\n initialVocabulary = decision.vocabulary;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n initialStage = exposedStage(decision.stage, providerProps.stageAttributes);\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n landingPath: pathname,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n // Not for a request that must not be tracked (DNT/GPC, consent refused or\n // not yet known): with no server decision the script's fallback reads the\n // stored snapshot from localStorage, and reading the device's storage before\n // consent is exactly what a consent gate exists to prevent. The browser SDK\n // takes over once the visitor's platform says yes.\n const personaScript = skipSsr ? null : (\n <SentientPersonaScript\n apiKey={providerProps.apiKey}\n persona={initialPersona}\n nonce={nonce}\n stageAttributes={providerProps.stageAttributes}\n stage={initialStage}\n />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // The same nonce also covers the <style> the client injects (reveal).\n nonce={nonce}\n // Forward the server-resolved value so a consented visitor's client does\n // not start gated and re-resolve the same cookie on mount.\n consent={consent}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n // Declared regardless of what came back, so devtools can preview layout on\n // a page whose decision was gated or timed out.\n declaredSections={sections}\n initialSlots={initialSlots}\n // Registry-mode preload: the hook treats a preloaded slot config as\n // settled, so the client does not decide the same slot a second time.\n initialSlotConfig={initialSlotConfig}\n initialPalette={initialPalette}\n initialVocabulary={initialVocabulary}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) {\n return (\n <>\n {personaScript}\n {client}\n </>\n );\n }\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const feed = buildAgentFeed({\n page: agentPath,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\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 type { JSX } from 'react';\nimport { renderPrePaintScript, type StageAttributes } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n /**\n * The same consent gate you give the provider. With `consent={false}`, or a\n * `consentFrom` source and no `consent={true}`, nothing is rendered: the\n * fallback reads the stored decision from the visitor's device, and that\n * must wait for consent (grader F3). `AdaptiveRoot` handles this for you.\n */\n consent?: boolean;\n consentFrom?: unknown;\n /**\n * Opt-in `data-sentient-stage` (see `AdaptiveProviderProps.stageAttributes`).\n * With a server decision, pass the value to write as `stage` (already\n * coarsened — `exposedStage` from `@sentientui/core`); without one the\n * script copies the stage the visitor's last decide stored.\n */\n stageAttributes?: StageAttributes;\n /** The stage value to write, from this request's decide; null writes none. */\n stage?: string | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n // The stage first, with its own single-writer check: an already-set\n // persona must not stop it. Only a value this request's decide gave.\n (props.stage\n ? 'if(!d.hasAttribute(\"data-sentient-stage\"))d.setAttribute(\"data-sentient-stage\",' + inlineJsString(props.stage) + ');'\n : '') +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey, props.stageAttributes ? { stage: true } : undefined);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element | null {\n // A server-decided persona is not a storage read, so it always renders.\n if (!props.persona && (props.consent === false || (props.consentFrom !== undefined && props.consent !== true))) return null;\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\n * `utm_*` params from the landing URL. The Referer header never carries the\n * page's OWN query string, so without this the SSR-minted session has no\n * campaign attribution until the client SDK hydrates and re-upserts.\n * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.\n */\n utmParams?: Record<string, string>;\n /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */\n clickIds?: Record<string, string>;\n /** The landing page's path (no query string) — recognises a paid click to a product page or a `/discount/` link on the first decision. */\n landingPath?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"+lBAAA,OAAS,wBAAAA,GAAsB,gBAAAC,GAAc,wBAAAC,GAAsB,qBAAAC,OAAyB,mBAC5F,OAAS,sBAAAC,OAA0B,2BAEnC,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCAjC,OAAS,wBAAAC,OAAkD,mBAC3D,OAAS,kBAAAC,OAAsB,qBA4E3B,cAAAC,OAAA,oBAvCJ,SAASC,EAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAAK,EAAE,QAAQ,KAAM,SAAS,CACtD,CAGO,SAASC,GAAkBC,EAA2C,CAC3E,OAAIA,EAAM,QAEN,mDAGCA,EAAM,MACH,kFAAoFH,EAAeG,EAAM,KAAK,EAAI,KAClH,IACJ,4FAC4CH,EAAeG,EAAM,QAAQ,OAAO,EAAI,+CACrCH,EAAeF,GAAeK,EAAM,QAAQ,UAAU,CAAC,EAAI,qBAIvGN,GAAq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OC,EAAe,CAC1B,KAAM1B,EACN,OAAQvD,GAAoB2D,CAAkB,EAC9C,YAAaC,GAAA,KAAAA,EAAsB,OACnC,QAAS/B,EAAU,OACrB,CAAC,EAED,OACE/B,GAAAF,GAAA,CACG,UAAAgF,EACD/E,EAAC,UACC,KAAK,sBACL,MAAOkC,EACP,wBAAyB,CAAE,OAAQmD,GAAsBF,EAAI,CAAE,EACjE,EACCF,GACH,CAEJ","names":["deriveSessionSegment","exposedStage","extractTrackedParams","matchedAgentToken","consentFromCookies","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","rawCookie","header","name","part","eq","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","components","sections","slots","registrySlotIds","appOrigin","searchParams","pathname","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","utmParams","clickIds","extractTrackedParams","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","consentFromCookies","skipSsr","keyless","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialLayoutOrder","initialSlots","initialSlotConfig","initialPalette","initialVocabulary","initialPersona","initialStage","ssrSessionId","registry","decision","loadAdaptiveDecision","__spreadProps","__spreadValues","exposedStage","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","feed","buildAgentFeed","renderAgentJsonLdBody"]}
|
package/dist/testing/react.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
"use strict";var Ae=Object.create;var G=Object.defineProperty,Oe=Object.defineProperties,Ie=Object.getOwnPropertyDescriptor,Te=Object.getOwnPropertyDescriptors,Ve=Object.getOwnPropertyNames,ie=Object.getOwnPropertySymbols,De=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty,Le=Object.prototype.propertyIsEnumerable;var re=(e,t,n)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))oe.call(t,n)&&re(e,n,t[n]);if(ie)for(var n of ie(t))Le.call(t,n)&&re(e,n,t[n]);return e},M=(e,t)=>Oe(e,Te(t));var Ge=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},se=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ve(t))!oe.call(e,a)&&a!==n&&G(e,a,{get:()=>t[a],enumerable:!(i=Ie(t,a))||i.enumerable});return e};var $=(e,t,n)=>(n=e!=null?Ae(De(e)):{},se(t||!e||!e.__esModule?G(n,"default",{value:e,enumerable:!0}):n,e)),Fe=e=>se(G({},"__esModule",{value:!0}),e);var et={};Ge(et,{renderWithSentient:()=>Ze});module.exports=Fe(et);var Ee=require("@testing-library/react");var o=require("react"),B=require("@sentientui/core");var Ne=new Map,We=new Map;function ae(e,t){Ne.set(e,t);let n=We.get(e);if(n)for(let i of n)try{i(t)}catch(a){}}var Me={on:!1,listeners:new Set};function le(){if(typeof window=="undefined")return Me;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function U(){return le().on}function ce(e){let t=le().listeners;return t.add(e),()=>{t.delete(e)}}function de(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,i,a)=>e.assign(t,n,i,a),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var $e="sentient:overrides-changed";function F(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event($e))}function ue(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function N(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Ke={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function j(){if(typeof window=="undefined")return Ke;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function Be(){j().version+=1;for(let e of j().listeners)e()}function H(e){N()&&(j().sections=[...e],Be())}var fe="0.39.0",z=fe!=="0.0.0-dev"?{name:"react",version:fe}:void 0;function Ue(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function T(e,t){Ue()[e]=t}function ge(e){window.__sentient_vocabulary_override=e}function je(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function V(e,t){je()[e]=t}function pe(e){let t=null;try{let n=location.hash.slice(1),i=RegExp("(^|[?&])"+e+"=([^&]*)").exec(n);if(i){t=i[2];let a=n.slice(i.index+i[0].length);i[1]!="&"&&a[0]=="&"&&(a=i[1]+a.slice(1));let u=n.slice(0,i.index)+a;history.replaceState(history.state,"",u?"#"+u:location.pathname+location.search)}}catch(n){}return t}var q="__snt_editor_token",D=null,J=!1;function me(){return J}function He(){try{return sessionStorage.getItem(q)}catch(e){return null}}function K(e){if(D)return D;let t=typeof window=="undefined"?null:pe("sentient_editor_code");if(!t){let n=typeof window=="undefined"?null:He();return J=!!n,D=Promise.resolve(n?{token:n,fresh:!1}:null),D}return J=!0,D=fetch(`${e}/editor/exchange`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:t})}).then(async n=>{let i=n.ok?(await n.json()).token:void 0;if(!i)return{error:n.ok?500:n.status};try{sessionStorage.setItem(q,i)}catch(a){}return{token:i,fresh:!0}}).catch(()=>({error:0})),D}function ye(){try{sessionStorage.removeItem(q)}catch(e){}}var ve="sentient_preview_cell",_e="sentient_refresh_region",X="sentient-cell-preview-bar",A="__preview__",ze=null;function Se(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(X))return;let t,n;try{let l=new URLSearchParams(window.location.search);t=l.get(ve),n=l.get(_e)}catch(l){return}if(!t&&!n)return;let i=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),a=K(i);if(!me())return;if(n){ze={slotId:n,session:a,base:i},T(n,{kind:"arms"}),V(n,A),F();return}if(!t)return;let u=t.lastIndexOf("~");if(u<=0)return;let g=t.slice(0,u),O=t.slice(u+1);a.then(l=>l?"token"in l?fetch(`${i}/editor/cell-preview?slotId=${encodeURIComponent(g)}&persona=${encodeURIComponent(O)}`,{headers:{authorization:`Bearer ${l.token}`}}):(W(l.error===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard."),null):null).then(async l=>{if(!l)return;if(!l.ok){W(l.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let c=await l.json();if(c.vocabulary&&Array.isArray(c.vocabulary.entries)&&ge(c.vocabulary),c.compose!=null)T(g,{kind:"arms",compose:{[A]:c.compose}}),V(g,A);else if(c.edits!=null&&typeof c.skeletonFp=="string"&&Array.isArray(c.leafToNode))T(g,{kind:"arms",edits:{edits:c.edits,fp:c.skeletonFp,leafToNode:c.leafToNode}}),V(g,A);else if(c.blocks!=null)T(g,{kind:"arms",blocks:{[A]:c.blocks}}),V(g,A);else if(c.content!=null)T(g,{kind:"arms",content:c.content}),V(g,A);else{W("Nothing to preview in that square yet.");return}F(),W(`Previewing \u201C${c.slotName}\u201D for ${c.personaDisplay}${c.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var p;try{(p=document.querySelector(`[data-sentient-slot="${g}"]`))==null||p.scrollIntoView({block:"center"})}catch(y){}},300)}).catch(()=>W("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function W(e){var a;if(document.getElementById(X))return;let t=document.createElement("div");t.id=X,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.textContent="Exit preview",Object.assign(i.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),i.onclick=()=>{ye();let u=new URL(window.location.href);u.searchParams.delete(ve),u.searchParams.delete(_e),window.location.assign(u.toString())},t.append(n,i),((a=document.body)!=null?a:document.documentElement).append(t)}var he=!1;function we(e){if(he||typeof window=="undefined")return;he=!0;let t=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");K(t).then(n=>{!n||!("token"in n)||!n.fresh||Je(t,n.token)})}function Je(e,t){let n=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:i})=>fetch(`${e}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(i(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?n():window.addEventListener("load",n,{once:!0})}var Re=require("react/jsx-runtime");function qe(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return(0,B.deriveSessionSegment)({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var Ce="https://api.sentient-ui.com/v1",Xe=(0,o.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:Ce,debug:!1}),be=!1,Y=new Set;function Ye(e,t,n){let i=(0,o.useRef)(n);i.current=n;let[a,u]=(0,o.useState)(null),[g,O]=(0,o.useState)(!1),l=(0,o.useRef)(e);l.current=e;let c=e===void 0?"":typeof e=="string"?e:JSON.stringify(M(v({},e),{check:typeof e.check,refused:typeof e.refused}));return(0,o.useEffect)(()=>{let p=l.current;if(p===void 0||typeof window=="undefined")return;let y,k=!1;return import("@sentientui/core/consent").then(({consentWatcher:x,forgetVisitor:I})=>{if(k)return;let E=x(typeof p=="object"&&p.cmp===void 0&&p.check?v(M(v({},p),{check:()=>l.current.check()}),p.refused?{refused:()=>{var h,w;return((w=(h=l.current).refused)==null?void 0:w.call(h))===!0}}:{}):p),S=!1,L=()=>{let h=E.refused()&&E.read()!==!0;h&&!S&&(I(t),i.current()),S=h,O(h);let w=E.read();w!==null&&Y.add(t),u(w!=null?w:Y.has(t)?!1:null)};L(),y=E.subscribe(L)}),()=>{k=!0,y==null||y()}},[c,t]),{granted:a,refused:g}}function xe(e){var Q,Z,ee;let[t,n]=(0,o.useState)(null),[i]=(0,o.useState)(()=>{var r;return(r=e.sessionSegment)!=null?r:qe()}),[a,u]=(0,o.useState)(U());(0,o.useEffect)(()=>ce(()=>u(U())),[]),(0,o.useEffect)(()=>{Se(e.apiBaseUrl),we(e.apiBaseUrl)},[]);let g=(0,o.useRef)(()=>{}),O=Ye(e.consentFrom,e.apiKey,()=>g.current()),l=e.consentFrom?(Q=O.granted)!=null?Q:Y.has(e.apiKey)?!1:e.consent===!0:e.consent,c=e.consentFrom?O.refused:!0,p=(0,o.useRef)(c);p.current=c;let y=(0,o.useRef)(null),k=(0,o.useRef)(!1),x=(0,o.useRef)([]),I=(0,o.useRef)(!1);g.current=()=>{var f;x.current=[],I.current=!0;let r=y.current;r!=null&&r.gated?r.dispose():(f=r==null?void 0:r.takeHeld)==null||f.call(r)},(0,o.useEffect)(()=>{var te,ne;if(p.current&&l===!1&&(x.current=[]),l===!1&&k.current&&(p.current&&((te=y.current)==null||te.destroy()),y.current=null,k.current=!1),l===!1&&!e.preConsentBehavior){p.current&&((ne=y.current)==null||ne.destroy()),y.current=null,n(null);return}let r=l!==!1;r&&(I.current=!1);let f=_=>{!r&&I.current&&_.gated&&_.dispose()},m=v({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:l,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,stageAttributes:e.stageAttributes,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0,nonce:e.nonce},z?{sdk:z}:{}),d=!1,s=null,b=null,C=_=>{for(let P of x.current.splice(0))setTimeout(()=>{if(y.current!==_){I.current||x.current.push(P);return}try{P(_)}catch(tt){}},0)},R=_=>{e.engagement===!1||!r||import("@sentientui/core/engagement").then(({startEngagementCapture:P})=>{d||(b=P(_,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:_})=>{d||(s=_(M(v({},m),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),f(s),y.current=s,k.current=r,C(s),n(s),R(s))}):(s=(0,B.init)(m),f(s),y.current=s,k.current=r,C(s),n(s),R(s)),()=>{var _,P;d=!0,b==null||b(),x.current=x.current.concat((P=(_=s==null?void 0:s.takeHeld)==null?void 0:_.call(s))!=null?P:[]),s==null||s.dispose()}},[l]),(0,o.useEffect)(()=>{if(!t)return;let r=!1,f=async()=>{if(r)return;let d;try{d=await t.fetchWeights()}catch(s){return}if(!r)for(let s of d){let b={componentId:s.componentId,updatedAt:s.updatedAt,variants:s.variants.map(C=>{var R;return{variantId:C.variantId,pulls:C.pulls,avgReward:(R=C.avgReward)!=null?R:0}})};ae(s.componentId,b)}};f();let m=setInterval(()=>{f()},6e4);return()=>{r=!0,clearInterval(m)}},[t]);let E=(Z=e.ssrFallback)!=null?Z:"first",S=((ee=e.apiBaseUrl)!=null?ee:Ce).replace(/\/$/,""),L=(0,o.useRef)(null);(0,o.useEffect)(()=>{var m;if(typeof process!="undefined"&&((m=process.env)==null?void 0:m.NODE_ENV)==="production")return;let r={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:S},f=L.current;if(L.current=r,f!==null)for(let d of["apiKey","context","country","persona","apiBaseUrl"])Object.is(f[d],r[d])||console.warn(`[sentient] AdaptiveProvider: \`${d}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,S]),(0,o.useEffect)(()=>{var r;typeof process!="undefined"&&((r=process.env)==null?void 0:r.NODE_ENV)==="production"||ue({apiKey:e.apiKey,apiBaseUrl:S,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,S]),(0,o.useEffect)(()=>{let r=e.initialLayoutOrder;if(r&&r.length>0){H(r);return}e.declaredSections&&e.declaredSections.length>0&&H(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),(0,o.useEffect)(()=>{!N()||e.consent!==void 0||e.consentFrom!==void 0||be||(be=!0,console.warn('[SentientUI] No consent gate: every visitor is tracked from first paint. Pass consentFrom="<your CMP>" (or consent={true} to silence). https://sentient-ui.com/docs#consent'))},[]),(0,o.useEffect)(()=>{if(!N())return;let r=e.declaredSections;if(!r||r.length===0||typeof document=="undefined")return;let f=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),d=>d.getAttribute("data-sentient-id"))),m=r.filter(d=>!f.has(d));m.length>0&&console.warn(`[SentientUI] Declared section${m.length>1?"s":""} ${m.map(d=>`"${d}"`).join(", ")} ${m.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let h=(0,o.useMemo)(()=>t&&a?de(t):t,[t,a]),w=(0,o.useMemo)(()=>{var r,f,m,d,s,b,C,R;return{client:h,apiKey:e.apiKey,initialAssignments:(r=e.initialAssignments)!=null?r:{},sessionSegment:i,ssrFallback:E,onAssignment:e.onAssignment,initialLayoutOrder:(f=e.initialLayoutOrder)!=null?f:null,initialSlots:(m=e.initialSlots)!=null?m:{},initialSlotConfig:(d=e.initialSlotConfig)!=null?d:{},initialPalette:(s=e.initialPalette)!=null?s:null,initialVocabulary:(b=e.initialVocabulary)!=null?b:null,initialPersona:(C=e.initialPersona)!=null?C:null,apiBaseUrl:S,debug:(R=e.debug)!=null?R:!1}},[h,e.apiKey,e.initialAssignments,i,E,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,S,e.debug]);return(0,Re.jsx)(Xe.Provider,{value:w,children:e.children})}function Qe(e){return e<.3?"low":e<.7?"medium":"high"}function ke(e={}){var n,i,a;let t=window;if(t.__sentient_overrides=v({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=v({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=v({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let u=document.documentElement;u.setAttribute("data-sentient-persona",e.persona),u.setAttribute("data-sentient-confidence",Qe((a=e.confidence)!=null?a:1))}catch(u){}}else delete t.__sentient_persona_override;F()}var Pe=require("react/jsx-runtime");function Ze(e,t={},n){return ke(t),(0,Ee.render)((0,Pe.jsx)(xe,{apiKey:"pk_test",consent:!1,children:e}),n)}0&&(module.exports={renderWithSentient});
|
|
2
|
+
"use strict";var Ae=Object.create;var G=Object.defineProperty,Oe=Object.defineProperties,Ie=Object.getOwnPropertyDescriptor,Te=Object.getOwnPropertyDescriptors,Ve=Object.getOwnPropertyNames,ie=Object.getOwnPropertySymbols,De=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty,Le=Object.prototype.propertyIsEnumerable;var re=(e,t,n)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))oe.call(t,n)&&re(e,n,t[n]);if(ie)for(var n of ie(t))Le.call(t,n)&&re(e,n,t[n]);return e},M=(e,t)=>Oe(e,Te(t));var Ge=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},se=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ve(t))!oe.call(e,a)&&a!==n&&G(e,a,{get:()=>t[a],enumerable:!(i=Ie(t,a))||i.enumerable});return e};var $=(e,t,n)=>(n=e!=null?Ae(De(e)):{},se(t||!e||!e.__esModule?G(n,"default",{value:e,enumerable:!0}):n,e)),Fe=e=>se(G({},"__esModule",{value:!0}),e);var et={};Ge(et,{renderWithSentient:()=>Ze});module.exports=Fe(et);var Ee=require("@testing-library/react");var o=require("react"),B=require("@sentientui/core");var Ne=new Map,We=new Map;function ae(e,t){Ne.set(e,t);let n=We.get(e);if(n)for(let i of n)try{i(t)}catch(a){}}var Me={on:!1,listeners:new Set};function le(){if(typeof window=="undefined")return Me;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function U(){return le().on}function ce(e){let t=le().listeners;return t.add(e),()=>{t.delete(e)}}function de(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,i,a)=>e.assign(t,n,i,a),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var $e="sentient:overrides-changed";function F(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event($e))}function ue(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function N(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Ke={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function j(){if(typeof window=="undefined")return Ke;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function Be(){j().version+=1;for(let e of j().listeners)e()}function H(e){N()&&(j().sections=[...e],Be())}var fe="0.39.1",z=fe!=="0.0.0-dev"?{name:"react",version:fe}:void 0;function Ue(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function T(e,t){Ue()[e]=t}function ge(e){window.__sentient_vocabulary_override=e}function je(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function V(e,t){je()[e]=t}function pe(e){let t=null;try{let n=location.hash.slice(1),i=RegExp("(^|[?&])"+e+"=([^&]*)").exec(n);if(i){t=i[2];let a=n.slice(i.index+i[0].length);i[1]!="&"&&a[0]=="&"&&(a=i[1]+a.slice(1));let u=n.slice(0,i.index)+a;history.replaceState(history.state,"",u?"#"+u:location.pathname+location.search)}}catch(n){}return t}var q="__snt_editor_token",D=null,J=!1;function me(){return J}function He(){try{return sessionStorage.getItem(q)}catch(e){return null}}function K(e){if(D)return D;let t=typeof window=="undefined"?null:pe("sentient_editor_code");if(!t){let n=typeof window=="undefined"?null:He();return J=!!n,D=Promise.resolve(n?{token:n,fresh:!1}:null),D}return J=!0,D=fetch(`${e}/editor/exchange`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:t})}).then(async n=>{let i=n.ok?(await n.json()).token:void 0;if(!i)return{error:n.ok?500:n.status};try{sessionStorage.setItem(q,i)}catch(a){}return{token:i,fresh:!0}}).catch(()=>({error:0})),D}function ye(){try{sessionStorage.removeItem(q)}catch(e){}}var ve="sentient_preview_cell",_e="sentient_refresh_region",X="sentient-cell-preview-bar",A="__preview__",ze=null;function Se(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(X))return;let t,n;try{let l=new URLSearchParams(window.location.search);t=l.get(ve),n=l.get(_e)}catch(l){return}if(!t&&!n)return;let i=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),a=K(i);if(!me())return;if(n){ze={slotId:n,session:a,base:i},T(n,{kind:"arms"}),V(n,A),F();return}if(!t)return;let u=t.lastIndexOf("~");if(u<=0)return;let g=t.slice(0,u),O=t.slice(u+1);a.then(l=>l?"token"in l?fetch(`${i}/editor/cell-preview?slotId=${encodeURIComponent(g)}&persona=${encodeURIComponent(O)}`,{headers:{authorization:`Bearer ${l.token}`}}):(W(l.error===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard."),null):null).then(async l=>{if(!l)return;if(!l.ok){W(l.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let c=await l.json();if(c.vocabulary&&Array.isArray(c.vocabulary.entries)&&ge(c.vocabulary),c.compose!=null)T(g,{kind:"arms",compose:{[A]:c.compose}}),V(g,A);else if(c.edits!=null&&typeof c.skeletonFp=="string"&&Array.isArray(c.leafToNode))T(g,{kind:"arms",edits:{edits:c.edits,fp:c.skeletonFp,leafToNode:c.leafToNode}}),V(g,A);else if(c.blocks!=null)T(g,{kind:"arms",blocks:{[A]:c.blocks}}),V(g,A);else if(c.content!=null)T(g,{kind:"arms",content:c.content}),V(g,A);else{W("Nothing to preview in that square yet.");return}F(),W(`Previewing \u201C${c.slotName}\u201D for ${c.personaDisplay}${c.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var p;try{(p=document.querySelector(`[data-sentient-slot="${g}"]`))==null||p.scrollIntoView({block:"center"})}catch(y){}},300)}).catch(()=>W("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function W(e){var a;if(document.getElementById(X))return;let t=document.createElement("div");t.id=X,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.textContent="Exit preview",Object.assign(i.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),i.onclick=()=>{ye();let u=new URL(window.location.href);u.searchParams.delete(ve),u.searchParams.delete(_e),window.location.assign(u.toString())},t.append(n,i),((a=document.body)!=null?a:document.documentElement).append(t)}var he=!1;function we(e){if(he||typeof window=="undefined")return;he=!0;let t=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");K(t).then(n=>{!n||!("token"in n)||!n.fresh||Je(t,n.token)})}function Je(e,t){let n=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:i})=>fetch(`${e}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(i(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?n():window.addEventListener("load",n,{once:!0})}var Re=require("react/jsx-runtime");function qe(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return(0,B.deriveSessionSegment)({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var Ce="https://api.sentient-ui.com/v1",Xe=(0,o.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:Ce,debug:!1}),be=!1,Y=new Set;function Ye(e,t,n){let i=(0,o.useRef)(n);i.current=n;let[a,u]=(0,o.useState)(null),[g,O]=(0,o.useState)(!1),l=(0,o.useRef)(e);l.current=e;let c=e===void 0?"":typeof e=="string"?e:JSON.stringify(M(v({},e),{check:typeof e.check,refused:typeof e.refused}));return(0,o.useEffect)(()=>{let p=l.current;if(p===void 0||typeof window=="undefined")return;let y,k=!1;return import("@sentientui/core/consent").then(({consentWatcher:x,forgetVisitor:I})=>{if(k)return;let E=x(typeof p=="object"&&p.cmp===void 0&&p.check?v(M(v({},p),{check:()=>l.current.check()}),p.refused?{refused:()=>{var h,w;return((w=(h=l.current).refused)==null?void 0:w.call(h))===!0}}:{}):p),S=!1,L=()=>{let h=E.refused()&&E.read()!==!0;h&&!S&&(I(t),i.current()),S=h,O(h);let w=E.read();w!==null&&Y.add(t),u(w!=null?w:Y.has(t)?!1:null)};L(),y=E.subscribe(L)}),()=>{k=!0,y==null||y()}},[c,t]),{granted:a,refused:g}}function xe(e){var Q,Z,ee;let[t,n]=(0,o.useState)(null),[i]=(0,o.useState)(()=>{var r;return(r=e.sessionSegment)!=null?r:qe()}),[a,u]=(0,o.useState)(U());(0,o.useEffect)(()=>ce(()=>u(U())),[]),(0,o.useEffect)(()=>{Se(e.apiBaseUrl),we(e.apiBaseUrl)},[]);let g=(0,o.useRef)(()=>{}),O=Ye(e.consentFrom,e.apiKey,()=>g.current()),l=e.consentFrom?(Q=O.granted)!=null?Q:Y.has(e.apiKey)?!1:e.consent===!0:e.consent,c=e.consentFrom?O.refused:!0,p=(0,o.useRef)(c);p.current=c;let y=(0,o.useRef)(null),k=(0,o.useRef)(!1),x=(0,o.useRef)([]),I=(0,o.useRef)(!1);g.current=()=>{var f;x.current=[],I.current=!0;let r=y.current;r!=null&&r.gated?r.dispose():(f=r==null?void 0:r.takeHeld)==null||f.call(r)},(0,o.useEffect)(()=>{var te,ne;if(p.current&&l===!1&&(x.current=[]),l===!1&&k.current&&(p.current&&((te=y.current)==null||te.destroy()),y.current=null,k.current=!1),l===!1&&!e.preConsentBehavior){p.current&&((ne=y.current)==null||ne.destroy()),y.current=null,n(null);return}let r=l!==!1;r&&(I.current=!1);let f=_=>{!r&&I.current&&_.gated&&_.dispose()},m=v({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:l,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,stageAttributes:e.stageAttributes,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0,nonce:e.nonce},z?{sdk:z}:{}),d=!1,s=null,b=null,C=_=>{for(let P of x.current.splice(0))setTimeout(()=>{if(y.current!==_){I.current||x.current.push(P);return}try{P(_)}catch(tt){}},0)},R=_=>{e.engagement===!1||!r||import("@sentientui/core/engagement").then(({startEngagementCapture:P})=>{d||(b=P(_,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:_})=>{d||(s=_(M(v({},m),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),f(s),y.current=s,k.current=r,C(s),n(s),R(s))}):(s=(0,B.init)(m),f(s),y.current=s,k.current=r,C(s),n(s),R(s)),()=>{var _,P;d=!0,b==null||b(),x.current=x.current.concat((P=(_=s==null?void 0:s.takeHeld)==null?void 0:_.call(s))!=null?P:[]),s==null||s.dispose()}},[l]),(0,o.useEffect)(()=>{if(!t)return;let r=!1,f=async()=>{if(r)return;let d;try{d=await t.fetchWeights()}catch(s){return}if(!r)for(let s of d){let b={componentId:s.componentId,updatedAt:s.updatedAt,variants:s.variants.map(C=>{var R;return{variantId:C.variantId,pulls:C.pulls,avgReward:(R=C.avgReward)!=null?R:0}})};ae(s.componentId,b)}};f();let m=setInterval(()=>{f()},6e4);return()=>{r=!0,clearInterval(m)}},[t]);let E=(Z=e.ssrFallback)!=null?Z:"first",S=((ee=e.apiBaseUrl)!=null?ee:Ce).replace(/\/$/,""),L=(0,o.useRef)(null);(0,o.useEffect)(()=>{var m;if(typeof process!="undefined"&&((m=process.env)==null?void 0:m.NODE_ENV)==="production")return;let r={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:S},f=L.current;if(L.current=r,f!==null)for(let d of["apiKey","context","country","persona","apiBaseUrl"])Object.is(f[d],r[d])||console.warn(`[sentient] AdaptiveProvider: \`${d}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,S]),(0,o.useEffect)(()=>{var r;typeof process!="undefined"&&((r=process.env)==null?void 0:r.NODE_ENV)==="production"||ue({apiKey:e.apiKey,apiBaseUrl:S,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,S]),(0,o.useEffect)(()=>{let r=e.initialLayoutOrder;if(r&&r.length>0){H(r);return}e.declaredSections&&e.declaredSections.length>0&&H(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),(0,o.useEffect)(()=>{!N()||e.consent!==void 0||e.consentFrom!==void 0||be||(be=!0,console.warn('[SentientUI] No consent gate: every visitor is tracked from first paint. Pass consentFrom="<your CMP>" (or consent={true} to silence). https://sentient-ui.com/docs#consent'))},[]),(0,o.useEffect)(()=>{if(!N())return;let r=e.declaredSections;if(!r||r.length===0||typeof document=="undefined")return;let f=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),d=>d.getAttribute("data-sentient-id"))),m=r.filter(d=>!f.has(d));m.length>0&&console.warn(`[SentientUI] Declared section${m.length>1?"s":""} ${m.map(d=>`"${d}"`).join(", ")} ${m.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let h=(0,o.useMemo)(()=>t&&a?de(t):t,[t,a]),w=(0,o.useMemo)(()=>{var r,f,m,d,s,b,C,R;return{client:h,apiKey:e.apiKey,initialAssignments:(r=e.initialAssignments)!=null?r:{},sessionSegment:i,ssrFallback:E,onAssignment:e.onAssignment,initialLayoutOrder:(f=e.initialLayoutOrder)!=null?f:null,initialSlots:(m=e.initialSlots)!=null?m:{},initialSlotConfig:(d=e.initialSlotConfig)!=null?d:{},initialPalette:(s=e.initialPalette)!=null?s:null,initialVocabulary:(b=e.initialVocabulary)!=null?b:null,initialPersona:(C=e.initialPersona)!=null?C:null,apiBaseUrl:S,debug:(R=e.debug)!=null?R:!1}},[h,e.apiKey,e.initialAssignments,i,E,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,S,e.debug]);return(0,Re.jsx)(Xe.Provider,{value:w,children:e.children})}function Qe(e){return e<.3?"low":e<.7?"medium":"high"}function ke(e={}){var n,i,a;let t=window;if(t.__sentient_overrides=v({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=v({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=v({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let u=document.documentElement;u.setAttribute("data-sentient-persona",e.persona),u.setAttribute("data-sentient-confidence",Qe((a=e.confidence)!=null?a:1))}catch(u){}}else delete t.__sentient_persona_override;F()}var Pe=require("react/jsx-runtime");function Ze(e,t={},n){return ke(t),(0,Ee.render)((0,Pe.jsx)(xe,{apiKey:"pk_test",consent:!1,children:e}),n)}0&&(module.exports={renderWithSentient});
|
|
3
3
|
//# sourceMappingURL=react.js.map
|
package/dist/testing/react.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
var xe=Object.defineProperty,Re=Object.defineProperties;var ke=Object.getOwnPropertyDescriptors;var ne=Object.getOwnPropertySymbols;var Ee=Object.prototype.hasOwnProperty,Pe=Object.prototype.propertyIsEnumerable;var ie=(e,t,n)=>t in e?xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,y=(e,t)=>{for(var n in t||(t={}))Ee.call(t,n)&&ie(e,n,t[n]);if(ne)for(var n of ne(t))Pe.call(t,n)&&ie(e,n,t[n]);return e},$=(e,t)=>Re(e,ke(t));import{render as Je}from"@testing-library/react";import{createContext as Me,useContext as Ct,useEffect as _,useMemo as Se,useRef as x,useState as M,useSyncExternalStore as xt}from"react";import{deriveSessionSegment as $e,init as Ke}from"@sentientui/core";var Ae=new Map,Oe=new Map;function re(e,t){Ae.set(e,t);let n=Oe.get(e);if(n)for(let r of n)try{r(t)}catch(l){}}var Ie={on:!1,listeners:new Set};function oe(){if(typeof window=="undefined")return Ie;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function B(){return oe().on}function se(e){let t=oe().listeners;return t.add(e),()=>{t.delete(e)}}function ae(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,r,l)=>e.assign(t,n,r,l),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var Te="sentient:overrides-changed";function F(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(Te))}function le(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function N(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Ve={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function U(){if(typeof window=="undefined")return Ve;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function De(){U().version+=1;for(let e of U().listeners)e()}function j(e){N()&&(U().sections=[...e],De())}var ce="0.39.0",H=ce!=="0.0.0-dev"?{name:"react",version:ce}:void 0;function Le(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function V(e,t){Le()[e]=t}function de(e){window.__sentient_vocabulary_override=e}function Ge(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function D(e,t){Ge()[e]=t}function ue(e){let t=null;try{let n=location.hash.slice(1),r=RegExp("(^|[?&])"+e+"=([^&]*)").exec(n);if(r){t=r[2];let l=n.slice(r.index+r[0].length);r[1]!="&"&&l[0]=="&"&&(l=r[1]+l.slice(1));let d=n.slice(0,r.index)+l;history.replaceState(history.state,"",d?"#"+d:location.pathname+location.search)}}catch(n){}return t}var J="__snt_editor_token",L=null,z=!1;function fe(){return z}function Fe(){try{return sessionStorage.getItem(J)}catch(e){return null}}function K(e){if(L)return L;let t=typeof window=="undefined"?null:ue("sentient_editor_code");if(!t){let n=typeof window=="undefined"?null:Fe();return z=!!n,L=Promise.resolve(n?{token:n,fresh:!1}:null),L}return z=!0,L=fetch(`${e}/editor/exchange`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:t})}).then(async n=>{let r=n.ok?(await n.json()).token:void 0;if(!r)return{error:n.ok?500:n.status};try{sessionStorage.setItem(J,r)}catch(l){}return{token:r,fresh:!0}}).catch(()=>({error:0})),L}function ge(){try{sessionStorage.removeItem(J)}catch(e){}}var pe="sentient_preview_cell",me="sentient_refresh_region",q="sentient-cell-preview-bar",O="__preview__",Ne=null;function ye(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(q))return;let t,n;try{let s=new URLSearchParams(window.location.search);t=s.get(pe),n=s.get(me)}catch(s){return}if(!t&&!n)return;let r=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),l=K(r);if(!fe())return;if(n){Ne={slotId:n,session:l,base:r},V(n,{kind:"arms"}),D(n,O),F();return}if(!t)return;let d=t.lastIndexOf("~");if(d<=0)return;let f=t.slice(0,d),I=t.slice(d+1);l.then(s=>s?"token"in s?fetch(`${r}/editor/cell-preview?slotId=${encodeURIComponent(f)}&persona=${encodeURIComponent(I)}`,{headers:{authorization:`Bearer ${s.token}`}}):(W(s.error===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard."),null):null).then(async s=>{if(!s)return;if(!s.ok){W(s.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let a=await s.json();if(a.vocabulary&&Array.isArray(a.vocabulary.entries)&&de(a.vocabulary),a.compose!=null)V(f,{kind:"arms",compose:{[O]:a.compose}}),D(f,O);else if(a.edits!=null&&typeof a.skeletonFp=="string"&&Array.isArray(a.leafToNode))V(f,{kind:"arms",edits:{edits:a.edits,fp:a.skeletonFp,leafToNode:a.leafToNode}}),D(f,O);else if(a.blocks!=null)V(f,{kind:"arms",blocks:{[O]:a.blocks}}),D(f,O);else if(a.content!=null)V(f,{kind:"arms",content:a.content}),D(f,O);else{W("Nothing to preview in that square yet.");return}F(),W(`Previewing \u201C${a.slotName}\u201D for ${a.personaDisplay}${a.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var g;try{(g=document.querySelector(`[data-sentient-slot="${f}"]`))==null||g.scrollIntoView({block:"center"})}catch(m){}},300)}).catch(()=>W("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function W(e){var l;if(document.getElementById(q))return;let t=document.createElement("div");t.id=q,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let r=document.createElement("button");r.textContent="Exit preview",Object.assign(r.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),r.onclick=()=>{ge();let d=new URL(window.location.href);d.searchParams.delete(pe),d.searchParams.delete(me),window.location.assign(d.toString())},t.append(n,r),((l=document.body)!=null?l:document.documentElement).append(t)}var ve=!1;function _e(e){if(ve||typeof window=="undefined")return;ve=!0;let t=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");K(t).then(n=>{!n||!("token"in n)||!n.fresh||We(t,n.token)})}function We(e,t){let n=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:r})=>fetch(`${e}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(r(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?n():window.addEventListener("load",n,{once:!0})}import{jsx as He}from"react/jsx-runtime";function Be(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return $e({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var we="https://api.sentient-ui.com/v1",Ue=Me({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:we,debug:!1}),he=!1,X=new Set;function je(e,t,n){let r=x(n);r.current=n;let[l,d]=M(null),[f,I]=M(!1),s=x(e);s.current=e;let a=e===void 0?"":typeof e=="string"?e:JSON.stringify($(y({},e),{check:typeof e.check,refused:typeof e.refused}));return _(()=>{let g=s.current;if(g===void 0||typeof window=="undefined")return;let m,E=!1;return import("@sentientui/core/consent").then(({consentWatcher:R,forgetVisitor:T})=>{if(E)return;let P=R(typeof g=="object"&&g.cmp===void 0&&g.check?y($(y({},g),{check:()=>s.current.check()}),g.refused?{refused:()=>{var h,w;return((w=(h=s.current).refused)==null?void 0:w.call(h))===!0}}:{}):g),S=!1,G=()=>{let h=P.refused()&&P.read()!==!0;h&&!S&&(T(t),r.current()),S=h,I(h);let w=P.read();w!==null&&X.add(t),d(w!=null?w:X.has(t)?!1:null)};G(),m=P.subscribe(G)}),()=>{E=!0,m==null||m()}},[a,t]),{granted:l,refused:f}}function be(e){var Y,Q,Z;let[t,n]=M(null),[r]=M(()=>{var i;return(i=e.sessionSegment)!=null?i:Be()}),[l,d]=M(B());_(()=>se(()=>d(B())),[]),_(()=>{ye(e.apiBaseUrl),_e(e.apiBaseUrl)},[]);let f=x(()=>{}),I=je(e.consentFrom,e.apiKey,()=>f.current()),s=e.consentFrom?(Y=I.granted)!=null?Y:X.has(e.apiKey)?!1:e.consent===!0:e.consent,a=e.consentFrom?I.refused:!0,g=x(a);g.current=a;let m=x(null),E=x(!1),R=x([]),T=x(!1);f.current=()=>{var u;R.current=[],T.current=!0;let i=m.current;i!=null&&i.gated?i.dispose():(u=i==null?void 0:i.takeHeld)==null||u.call(i)},_(()=>{var ee,te;if(g.current&&s===!1&&(R.current=[]),s===!1&&E.current&&(g.current&&((ee=m.current)==null||ee.destroy()),m.current=null,E.current=!1),s===!1&&!e.preConsentBehavior){g.current&&((te=m.current)==null||te.destroy()),m.current=null,n(null);return}let i=s!==!1;i&&(T.current=!1);let u=v=>{!i&&T.current&&v.gated&&v.dispose()},p=y({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:r,consent:s,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,stageAttributes:e.stageAttributes,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0,nonce:e.nonce},H?{sdk:H}:{}),c=!1,o=null,b=null,C=v=>{for(let A of R.current.splice(0))setTimeout(()=>{if(m.current!==v){T.current||R.current.push(A);return}try{A(v)}catch(Xe){}},0)},k=v=>{e.engagement===!1||!i||import("@sentientui/core/engagement").then(({startEngagementCapture:A})=>{c||(b=A(v,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:v})=>{c||(o=v($(y({},p),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),u(o),m.current=o,E.current=i,C(o),n(o),k(o))}):(o=Ke(p),u(o),m.current=o,E.current=i,C(o),n(o),k(o)),()=>{var v,A;c=!0,b==null||b(),R.current=R.current.concat((A=(v=o==null?void 0:o.takeHeld)==null?void 0:v.call(o))!=null?A:[]),o==null||o.dispose()}},[s]),_(()=>{if(!t)return;let i=!1,u=async()=>{if(i)return;let c;try{c=await t.fetchWeights()}catch(o){return}if(!i)for(let o of c){let b={componentId:o.componentId,updatedAt:o.updatedAt,variants:o.variants.map(C=>{var k;return{variantId:C.variantId,pulls:C.pulls,avgReward:(k=C.avgReward)!=null?k:0}})};re(o.componentId,b)}};u();let p=setInterval(()=>{u()},6e4);return()=>{i=!0,clearInterval(p)}},[t]);let P=(Q=e.ssrFallback)!=null?Q:"first",S=((Z=e.apiBaseUrl)!=null?Z:we).replace(/\/$/,""),G=x(null);_(()=>{var p;if(typeof process!="undefined"&&((p=process.env)==null?void 0:p.NODE_ENV)==="production")return;let i={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:S},u=G.current;if(G.current=i,u!==null)for(let c of["apiKey","context","country","persona","apiBaseUrl"])Object.is(u[c],i[c])||console.warn(`[sentient] AdaptiveProvider: \`${c}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,S]),_(()=>{var i;typeof process!="undefined"&&((i=process.env)==null?void 0:i.NODE_ENV)==="production"||le({apiKey:e.apiKey,apiBaseUrl:S,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,S]),_(()=>{let i=e.initialLayoutOrder;if(i&&i.length>0){j(i);return}e.declaredSections&&e.declaredSections.length>0&&j(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),_(()=>{!N()||e.consent!==void 0||e.consentFrom!==void 0||he||(he=!0,console.warn('[SentientUI] No consent gate: every visitor is tracked from first paint. Pass consentFrom="<your CMP>" (or consent={true} to silence). https://sentient-ui.com/docs#consent'))},[]),_(()=>{if(!N())return;let i=e.declaredSections;if(!i||i.length===0||typeof document=="undefined")return;let u=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),c=>c.getAttribute("data-sentient-id"))),p=i.filter(c=>!u.has(c));p.length>0&&console.warn(`[SentientUI] Declared section${p.length>1?"s":""} ${p.map(c=>`"${c}"`).join(", ")} ${p.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let h=Se(()=>t&&l?ae(t):t,[t,l]),w=Se(()=>{var i,u,p,c,o,b,C,k;return{client:h,apiKey:e.apiKey,initialAssignments:(i=e.initialAssignments)!=null?i:{},sessionSegment:r,ssrFallback:P,onAssignment:e.onAssignment,initialLayoutOrder:(u=e.initialLayoutOrder)!=null?u:null,initialSlots:(p=e.initialSlots)!=null?p:{},initialSlotConfig:(c=e.initialSlotConfig)!=null?c:{},initialPalette:(o=e.initialPalette)!=null?o:null,initialVocabulary:(b=e.initialVocabulary)!=null?b:null,initialPersona:(C=e.initialPersona)!=null?C:null,apiBaseUrl:S,debug:(k=e.debug)!=null?k:!1}},[h,e.apiKey,e.initialAssignments,r,P,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,S,e.debug]);return He(Ue.Provider,{value:w,children:e.children})}function ze(e){return e<.3?"low":e<.7?"medium":"high"}function Ce(e={}){var n,r,l;let t=window;if(t.__sentient_overrides=y({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=y({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=y({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(r=e.confidence)!=null?r:1};try{let d=document.documentElement;d.setAttribute("data-sentient-persona",e.persona),d.setAttribute("data-sentient-confidence",ze((l=e.confidence)!=null?l:1))}catch(d){}}else delete t.__sentient_persona_override;F()}import{jsx as qe}from"react/jsx-runtime";function Bt(e,t={},n){return Ce(t),Je(qe(be,{apiKey:"pk_test",consent:!1,children:e}),n)}export{Bt as renderWithSentient};
|
|
2
|
+
var xe=Object.defineProperty,Re=Object.defineProperties;var ke=Object.getOwnPropertyDescriptors;var ne=Object.getOwnPropertySymbols;var Ee=Object.prototype.hasOwnProperty,Pe=Object.prototype.propertyIsEnumerable;var ie=(e,t,n)=>t in e?xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,y=(e,t)=>{for(var n in t||(t={}))Ee.call(t,n)&&ie(e,n,t[n]);if(ne)for(var n of ne(t))Pe.call(t,n)&&ie(e,n,t[n]);return e},$=(e,t)=>Re(e,ke(t));import{render as Je}from"@testing-library/react";import{createContext as Me,useContext as Ct,useEffect as _,useMemo as Se,useRef as x,useState as M,useSyncExternalStore as xt}from"react";import{deriveSessionSegment as $e,init as Ke}from"@sentientui/core";var Ae=new Map,Oe=new Map;function re(e,t){Ae.set(e,t);let n=Oe.get(e);if(n)for(let r of n)try{r(t)}catch(l){}}var Ie={on:!1,listeners:new Set};function oe(){if(typeof window=="undefined")return Ie;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function B(){return oe().on}function se(e){let t=oe().listeners;return t.add(e),()=>{t.delete(e)}}function ae(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,r,l)=>e.assign(t,n,r,l),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var Te="sentient:overrides-changed";function F(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(Te))}function le(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function N(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Ve={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function U(){if(typeof window=="undefined")return Ve;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function De(){U().version+=1;for(let e of U().listeners)e()}function j(e){N()&&(U().sections=[...e],De())}var ce="0.39.1",H=ce!=="0.0.0-dev"?{name:"react",version:ce}:void 0;function Le(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function V(e,t){Le()[e]=t}function de(e){window.__sentient_vocabulary_override=e}function Ge(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function D(e,t){Ge()[e]=t}function ue(e){let t=null;try{let n=location.hash.slice(1),r=RegExp("(^|[?&])"+e+"=([^&]*)").exec(n);if(r){t=r[2];let l=n.slice(r.index+r[0].length);r[1]!="&"&&l[0]=="&"&&(l=r[1]+l.slice(1));let d=n.slice(0,r.index)+l;history.replaceState(history.state,"",d?"#"+d:location.pathname+location.search)}}catch(n){}return t}var J="__snt_editor_token",L=null,z=!1;function fe(){return z}function Fe(){try{return sessionStorage.getItem(J)}catch(e){return null}}function K(e){if(L)return L;let t=typeof window=="undefined"?null:ue("sentient_editor_code");if(!t){let n=typeof window=="undefined"?null:Fe();return z=!!n,L=Promise.resolve(n?{token:n,fresh:!1}:null),L}return z=!0,L=fetch(`${e}/editor/exchange`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:t})}).then(async n=>{let r=n.ok?(await n.json()).token:void 0;if(!r)return{error:n.ok?500:n.status};try{sessionStorage.setItem(J,r)}catch(l){}return{token:r,fresh:!0}}).catch(()=>({error:0})),L}function ge(){try{sessionStorage.removeItem(J)}catch(e){}}var pe="sentient_preview_cell",me="sentient_refresh_region",q="sentient-cell-preview-bar",O="__preview__",Ne=null;function ye(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(q))return;let t,n;try{let s=new URLSearchParams(window.location.search);t=s.get(pe),n=s.get(me)}catch(s){return}if(!t&&!n)return;let r=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),l=K(r);if(!fe())return;if(n){Ne={slotId:n,session:l,base:r},V(n,{kind:"arms"}),D(n,O),F();return}if(!t)return;let d=t.lastIndexOf("~");if(d<=0)return;let f=t.slice(0,d),I=t.slice(d+1);l.then(s=>s?"token"in s?fetch(`${r}/editor/cell-preview?slotId=${encodeURIComponent(f)}&persona=${encodeURIComponent(I)}`,{headers:{authorization:`Bearer ${s.token}`}}):(W(s.error===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard."),null):null).then(async s=>{if(!s)return;if(!s.ok){W(s.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let a=await s.json();if(a.vocabulary&&Array.isArray(a.vocabulary.entries)&&de(a.vocabulary),a.compose!=null)V(f,{kind:"arms",compose:{[O]:a.compose}}),D(f,O);else if(a.edits!=null&&typeof a.skeletonFp=="string"&&Array.isArray(a.leafToNode))V(f,{kind:"arms",edits:{edits:a.edits,fp:a.skeletonFp,leafToNode:a.leafToNode}}),D(f,O);else if(a.blocks!=null)V(f,{kind:"arms",blocks:{[O]:a.blocks}}),D(f,O);else if(a.content!=null)V(f,{kind:"arms",content:a.content}),D(f,O);else{W("Nothing to preview in that square yet.");return}F(),W(`Previewing \u201C${a.slotName}\u201D for ${a.personaDisplay}${a.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var g;try{(g=document.querySelector(`[data-sentient-slot="${f}"]`))==null||g.scrollIntoView({block:"center"})}catch(m){}},300)}).catch(()=>W("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function W(e){var l;if(document.getElementById(q))return;let t=document.createElement("div");t.id=q,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let r=document.createElement("button");r.textContent="Exit preview",Object.assign(r.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),r.onclick=()=>{ge();let d=new URL(window.location.href);d.searchParams.delete(pe),d.searchParams.delete(me),window.location.assign(d.toString())},t.append(n,r),((l=document.body)!=null?l:document.documentElement).append(t)}var ve=!1;function _e(e){if(ve||typeof window=="undefined")return;ve=!0;let t=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");K(t).then(n=>{!n||!("token"in n)||!n.fresh||We(t,n.token)})}function We(e,t){let n=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:r})=>fetch(`${e}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(r(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?n():window.addEventListener("load",n,{once:!0})}import{jsx as He}from"react/jsx-runtime";function Be(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return $e({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var we="https://api.sentient-ui.com/v1",Ue=Me({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:we,debug:!1}),he=!1,X=new Set;function je(e,t,n){let r=x(n);r.current=n;let[l,d]=M(null),[f,I]=M(!1),s=x(e);s.current=e;let a=e===void 0?"":typeof e=="string"?e:JSON.stringify($(y({},e),{check:typeof e.check,refused:typeof e.refused}));return _(()=>{let g=s.current;if(g===void 0||typeof window=="undefined")return;let m,E=!1;return import("@sentientui/core/consent").then(({consentWatcher:R,forgetVisitor:T})=>{if(E)return;let P=R(typeof g=="object"&&g.cmp===void 0&&g.check?y($(y({},g),{check:()=>s.current.check()}),g.refused?{refused:()=>{var h,w;return((w=(h=s.current).refused)==null?void 0:w.call(h))===!0}}:{}):g),S=!1,G=()=>{let h=P.refused()&&P.read()!==!0;h&&!S&&(T(t),r.current()),S=h,I(h);let w=P.read();w!==null&&X.add(t),d(w!=null?w:X.has(t)?!1:null)};G(),m=P.subscribe(G)}),()=>{E=!0,m==null||m()}},[a,t]),{granted:l,refused:f}}function be(e){var Y,Q,Z;let[t,n]=M(null),[r]=M(()=>{var i;return(i=e.sessionSegment)!=null?i:Be()}),[l,d]=M(B());_(()=>se(()=>d(B())),[]),_(()=>{ye(e.apiBaseUrl),_e(e.apiBaseUrl)},[]);let f=x(()=>{}),I=je(e.consentFrom,e.apiKey,()=>f.current()),s=e.consentFrom?(Y=I.granted)!=null?Y:X.has(e.apiKey)?!1:e.consent===!0:e.consent,a=e.consentFrom?I.refused:!0,g=x(a);g.current=a;let m=x(null),E=x(!1),R=x([]),T=x(!1);f.current=()=>{var u;R.current=[],T.current=!0;let i=m.current;i!=null&&i.gated?i.dispose():(u=i==null?void 0:i.takeHeld)==null||u.call(i)},_(()=>{var ee,te;if(g.current&&s===!1&&(R.current=[]),s===!1&&E.current&&(g.current&&((ee=m.current)==null||ee.destroy()),m.current=null,E.current=!1),s===!1&&!e.preConsentBehavior){g.current&&((te=m.current)==null||te.destroy()),m.current=null,n(null);return}let i=s!==!1;i&&(T.current=!1);let u=v=>{!i&&T.current&&v.gated&&v.dispose()},p=y({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:r,consent:s,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,stageAttributes:e.stageAttributes,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0,nonce:e.nonce},H?{sdk:H}:{}),c=!1,o=null,b=null,C=v=>{for(let A of R.current.splice(0))setTimeout(()=>{if(m.current!==v){T.current||R.current.push(A);return}try{A(v)}catch(Xe){}},0)},k=v=>{e.engagement===!1||!i||import("@sentientui/core/engagement").then(({startEngagementCapture:A})=>{c||(b=A(v,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:v})=>{c||(o=v($(y({},p),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),u(o),m.current=o,E.current=i,C(o),n(o),k(o))}):(o=Ke(p),u(o),m.current=o,E.current=i,C(o),n(o),k(o)),()=>{var v,A;c=!0,b==null||b(),R.current=R.current.concat((A=(v=o==null?void 0:o.takeHeld)==null?void 0:v.call(o))!=null?A:[]),o==null||o.dispose()}},[s]),_(()=>{if(!t)return;let i=!1,u=async()=>{if(i)return;let c;try{c=await t.fetchWeights()}catch(o){return}if(!i)for(let o of c){let b={componentId:o.componentId,updatedAt:o.updatedAt,variants:o.variants.map(C=>{var k;return{variantId:C.variantId,pulls:C.pulls,avgReward:(k=C.avgReward)!=null?k:0}})};re(o.componentId,b)}};u();let p=setInterval(()=>{u()},6e4);return()=>{i=!0,clearInterval(p)}},[t]);let P=(Q=e.ssrFallback)!=null?Q:"first",S=((Z=e.apiBaseUrl)!=null?Z:we).replace(/\/$/,""),G=x(null);_(()=>{var p;if(typeof process!="undefined"&&((p=process.env)==null?void 0:p.NODE_ENV)==="production")return;let i={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:S},u=G.current;if(G.current=i,u!==null)for(let c of["apiKey","context","country","persona","apiBaseUrl"])Object.is(u[c],i[c])||console.warn(`[sentient] AdaptiveProvider: \`${c}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,S]),_(()=>{var i;typeof process!="undefined"&&((i=process.env)==null?void 0:i.NODE_ENV)==="production"||le({apiKey:e.apiKey,apiBaseUrl:S,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,S]),_(()=>{let i=e.initialLayoutOrder;if(i&&i.length>0){j(i);return}e.declaredSections&&e.declaredSections.length>0&&j(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),_(()=>{!N()||e.consent!==void 0||e.consentFrom!==void 0||he||(he=!0,console.warn('[SentientUI] No consent gate: every visitor is tracked from first paint. Pass consentFrom="<your CMP>" (or consent={true} to silence). https://sentient-ui.com/docs#consent'))},[]),_(()=>{if(!N())return;let i=e.declaredSections;if(!i||i.length===0||typeof document=="undefined")return;let u=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),c=>c.getAttribute("data-sentient-id"))),p=i.filter(c=>!u.has(c));p.length>0&&console.warn(`[SentientUI] Declared section${p.length>1?"s":""} ${p.map(c=>`"${c}"`).join(", ")} ${p.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let h=Se(()=>t&&l?ae(t):t,[t,l]),w=Se(()=>{var i,u,p,c,o,b,C,k;return{client:h,apiKey:e.apiKey,initialAssignments:(i=e.initialAssignments)!=null?i:{},sessionSegment:r,ssrFallback:P,onAssignment:e.onAssignment,initialLayoutOrder:(u=e.initialLayoutOrder)!=null?u:null,initialSlots:(p=e.initialSlots)!=null?p:{},initialSlotConfig:(c=e.initialSlotConfig)!=null?c:{},initialPalette:(o=e.initialPalette)!=null?o:null,initialVocabulary:(b=e.initialVocabulary)!=null?b:null,initialPersona:(C=e.initialPersona)!=null?C:null,apiBaseUrl:S,debug:(k=e.debug)!=null?k:!1}},[h,e.apiKey,e.initialAssignments,r,P,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,S,e.debug]);return He(Ue.Provider,{value:w,children:e.children})}function ze(e){return e<.3?"low":e<.7?"medium":"high"}function Ce(e={}){var n,r,l;let t=window;if(t.__sentient_overrides=y({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=y({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=y({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(r=e.confidence)!=null?r:1};try{let d=document.documentElement;d.setAttribute("data-sentient-persona",e.persona),d.setAttribute("data-sentient-confidence",ze((l=e.confidence)!=null?l:1))}catch(d){}}else delete t.__sentient_persona_override;F()}import{jsx as qe}from"react/jsx-runtime";function Bt(e,t={},n){return Ce(t),Je(qe(be,{apiKey:"pk_test",consent:!1,children:e}),n)}export{Bt as renderWithSentient};
|
|
3
3
|
//# sourceMappingURL=react.mjs.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sentientui/react",
|
|
3
|
-
"version": "0.39.
|
|
3
|
+
"version": "0.39.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"engines": {
|
|
@@ -78,8 +78,8 @@
|
|
|
78
78
|
"llms.txt"
|
|
79
79
|
],
|
|
80
80
|
"dependencies": {
|
|
81
|
-
"@sentientui/
|
|
82
|
-
"@sentientui/
|
|
81
|
+
"@sentientui/core": "0.38.0",
|
|
82
|
+
"@sentientui/policy": "0.16.0"
|
|
83
83
|
},
|
|
84
84
|
"peerDependencies": {
|
|
85
85
|
"@testing-library/react": ">=14.0.0 <17.0.0",
|