@sentientui/react 0.12.1 → 0.14.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/server.ts","../../src/agent-feed.ts","../../src/next/agent-feed-route.ts","../../src/next/agent-middleware.ts"],"sourcesContent":["import { deriveSessionSegment } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\nimport type { ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { sentientAgentMiddleware } from './agent-middleware.js';\nexport type { SentientAgentMiddlewareConfig, CrawlerRequestEntry } from './agent-middleware.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\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<AdaptiveProviderProps, 'initialAssignments' | 'onAssignment'> & {\n /** Components to assign server-side (SEO-safe). */\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 * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n */\n sections?: string[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: 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 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 * 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\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 * context=\"landing\"\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 appOrigin,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\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 const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let ssrSessionId: string | undefined;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (sections && sections.length > 0) {\n const decision = await loadAdaptiveDecision({\n sections,\n components,\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl: DEFAULT_API_BASE_URL,\n origin: resolvedOrigin,\n userAgent,\n referer,\n timeoutMs,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl: DEFAULT_API_BASE_URL,\n origin: resolvedOrigin,\n userAgent,\n referer,\n timeoutMs,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) return client;\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 path = agentFeed.path ?? headerStore.get('x-pathname') ?? '/';\n const feed = buildAgentFeed({\n page: path,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n <script\n type=\"application/ld+json\"\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\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 /** 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\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 timeoutMs: options.timeoutMs,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult } 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 /** Section IDs in default order. Passed to /v1/decide as the candidate layout. */\n sections: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n};\n\n/**\n * SSR helper for pages with a declared section layout. Calls `/v1/decide`\n * 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 */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n const sessionId =\n readSessionCookie(options.cookies) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\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 timeoutMs: options.timeoutMs,\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","/**\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","/**\n * `sentientAgentMiddleware` — additive-discovery middleware. Detects known AI\n * crawler / agent user-agents on page requests and reports them so they can be\n * logged to `crawler_requests` (the only way to observe passive crawlers, which\n * run no JS and never create a session). It NEVER changes the response — the\n * caller composes it into their Next.js middleware and returns `NextResponse.next()`.\n *\n * export async function middleware(request: NextRequest) {\n * await logCrawler(request); // sentientAgentMiddleware instance\n * return NextResponse.next();\n * }\n */\nimport { matchedAgentToken } from '@sentientui/core';\n\nexport type CrawlerRequestEntry = {\n path: string;\n userAgent: string | null;\n botName: string;\n};\n\nexport type SentientAgentMiddlewareConfig = {\n /** Best-effort sink — persist to `crawler_requests` here. Failures are swallowed. */\n onCrawler: (entry: CrawlerRequestEntry) => void | Promise<void>;\n};\n\nexport function sentientAgentMiddleware(\n config: SentientAgentMiddlewareConfig,\n): (request: Request) => Promise<boolean> {\n return async (request: Request): Promise<boolean> => {\n const userAgent = request.headers.get('user-agent');\n const botName = matchedAgentToken(userAgent ?? '');\n if (!botName) return false;\n\n try {\n const path = new URL(request.url).pathname;\n await Promise.resolve(config.onCrawler({ path, userAgent, botName })).catch(() => {});\n } catch {\n /* detection/logging must never break the request */\n }\n return true;\n };\n}\n"],"mappings":"+kBAAA,OAAS,wBAAAA,OAA4B,mBACrC,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCEjC,OACE,sBAAAC,EACA,qBAAAC,MAGK,0BA8DP,OAAS,oBAAAC,OAAwB,0BAjCjC,SAASC,GAA2B,CAClC,OAAI,OAAO,QAAW,aAAe,OAAO,OAAO,YAAe,WACzD,OAAO,WAAW,EAEpB,OAAO,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,EAAG,EAAE,CAAC,EACrE,CAOA,eAAsBC,EACpBC,EACAC,EACwC,CApD1C,IAAAC,EAAAC,EAAAC,EAqDE,IAAMC,GACJD,GAAAD,EAAAG,EAAkBL,EAAQ,OAAO,IAAjC,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,EAAiB,EAWnB,MAAO,CAAE,YATW,MAAMS,EAAmBP,EAAYK,EAAW,CAClE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,UAAWA,EAAQ,SACrB,CAAC,EAEqB,UAAAI,CAAU,CAClC,CAuBA,eAAsBG,EACpBP,EAC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,IAAME,EAAS,MAAMC,EAAwB1B,EAAY,CACvD,QAASkB,EACT,OAAQV,EAAc,OACtB,QAASpB,EACT,OAAQyB,EACR,UAAAC,EACA,QAAAC,EACA,UAAAV,CACF,CAAC,EACDe,EAAqBK,EAAO,YAC5BH,EAAeG,EAAO,SACxB,CAEA,IAAME,EACJzC,EAAC0C,GAAAC,EAAAC,EAAA,GACKtB,GADL,CAEC,mBAAoBY,EACpB,mBAAoBC,EACpB,eAAgBL,EAChB,aAAcM,EAEb,SAAAf,GACH,EAGF,GAAI,CAACD,EAAW,OAAOqB,EAKvB,IAAMI,GAAOhC,GAAAD,EAAAQ,EAAU,OAAV,KAAAR,EAAkBY,EAAY,IAAI,YAAY,IAA9C,KAAAX,EAAmD,IAC1DiC,EAAOC,EAAe,CAC1B,KAAMF,EACN,OAAQ1C,GAAoB+B,CAAkB,EAC9C,YAAaC,GAAA,KAAAA,EAAsB,OACnC,QAASf,EAAU,OACrB,CAAC,EAED,OACEnB,GAAAF,GAAA,CACE,UAAAC,EAAC,UACC,KAAK,sBACL,wBAAyB,CAAE,OAAQgD,EAAsBF,CAAI,CAAE,EACjE,EACCL,GACH,CAEJ","names":["deriveSessionSegment","cookies","headers","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","preloadDecisions","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","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","sentientAgentMiddleware","config","request","userAgent","botName","path","e","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","components","sections","appOrigin","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","sessionSegment","deriveSessionSegment","cookieStore","cookies","initialAssignments","initialLayoutOrder","ssrSessionId","decision","loadAdaptiveDecision","result","loadAdaptiveAssignments","client","AdaptiveRootClient","__spreadProps","__spreadValues","path","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/agent-feed-route.ts","../../src/next/agent-middleware.ts"],"sourcesContent":["import { deriveSessionSegment } from '@sentientui/core';\nimport type { SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\nimport type { ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { sentientAgentMiddleware } from './agent-middleware.js';\nexport type { SentientAgentMiddlewareConfig, CrawlerRequestEntry } from './agent-middleware.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\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 'initialAssignments' | 'onAssignment' | 'initialSlots' | 'initialPersona'\n> & {\n /** Components to assign server-side (SEO-safe). */\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 * @example sections={['hero', 'pricing', 'features', 'social_proof']}\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 /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: 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 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 * 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\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 * context=\"landing\"\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 appOrigin,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\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 const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialPersona: { persona: string; confidence: number } | null = null;\n let ssrSessionId: string | undefined;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0)) {\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl: DEFAULT_API_BASE_URL,\n origin: resolvedOrigin,\n userAgent,\n referer,\n timeoutMs,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl: DEFAULT_API_BASE_URL,\n origin: resolvedOrigin,\n userAgent,\n referer,\n timeoutMs,\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 const personaScript = (\n <SentientPersonaScript apiKey={providerProps.apiKey} persona={initialPersona} />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n initialSlots={initialSlots}\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 path = agentFeed.path ?? headerStore.get('x-pathname') ?? '/';\n const feed = buildAgentFeed({\n page: path,\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 dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","import { renderPrePaintScript } 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 * 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\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 '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);\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 {\n return (\n <script\n data-sentient-persona-script=\"\"\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 /** 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\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 timeoutMs: options.timeoutMs,\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};\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n timeoutMs: options.timeoutMs,\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","/**\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","/**\n * `sentientAgentMiddleware` — additive-discovery middleware. Detects known AI\n * crawler / agent user-agents on page requests and reports them so they can be\n * logged to `crawler_requests` (the only way to observe passive crawlers, which\n * run no JS and never create a session). It NEVER changes the response — the\n * caller composes it into their Next.js middleware and returns `NextResponse.next()`.\n *\n * export async function middleware(request: NextRequest) {\n * await logCrawler(request); // sentientAgentMiddleware instance\n * return NextResponse.next();\n * }\n */\nimport { matchedAgentToken } from '@sentientui/core';\n\nexport type CrawlerRequestEntry = {\n path: string;\n userAgent: string | null;\n botName: string;\n};\n\nexport type SentientAgentMiddlewareConfig = {\n /** Best-effort sink — persist to `crawler_requests` here. Failures are swallowed. */\n onCrawler: (entry: CrawlerRequestEntry) => void | Promise<void>;\n};\n\nexport function sentientAgentMiddleware(\n config: SentientAgentMiddlewareConfig,\n): (request: Request) => Promise<boolean> {\n return async (request: Request): Promise<boolean> => {\n const userAgent = request.headers.get('user-agent');\n const botName = matchedAgentToken(userAgent ?? '');\n if (!botName) return false;\n\n try {\n const path = new URL(request.url).pathname;\n await Promise.resolve(config.onCrawler({ path, userAgent, botName })).catch(() => {});\n } catch {\n /* detection/logging must never break the request */\n }\n return true;\n };\n}\n"],"mappings":"qlBAAA,OAAS,wBAAAA,OAA4B,mBAErC,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCFjC,OAAS,wBAAAC,OAA4B,mBACrC,OAAS,kBAAAC,OAAsB,qBA8C3B,cAAA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AAME,EACJ7C,EAAC8C,EAAA,CAAsB,OAAQtB,EAAc,OAAQ,QAASe,EAAgB,EAG1EQ,EACJ/C,EAACgD,GAAAC,EAAAC,EAAA,GACK1B,GADL,CAEC,mBAAoBY,EACpB,mBAAoBC,EACpB,aAAcC,EACd,eAAgBC,GAAA,KAAAA,EAAkB,OAClC,eAAgBP,EAChB,aAAcQ,EAEb,SAAAjB,GACH,EAGF,GAAI,CAACD,EACH,OACErB,EAAAF,EAAA,CACG,UAAA8C,EACAE,GACH,EAOJ,IAAMI,GAAOrC,GAAAD,EAAAS,EAAU,OAAV,KAAAT,EAAkBa,EAAY,IAAI,YAAY,IAA9C,KAAAZ,EAAmD,IAC1DsC,EAAOC,EAAe,CAC1B,KAAMF,EACN,OAAQhD,GAAoBiC,CAAkB,EAC9C,YAAaC,GAAA,KAAAA,EAAsB,OACnC,QAASf,EAAU,OACrB,CAAC,EAED,OACErB,EAAAF,EAAA,CACG,UAAA8C,EACD7C,EAAC,UACC,KAAK,sBACL,wBAAyB,CAAE,OAAQsD,EAAsBF,CAAI,CAAE,EACjE,EACCL,GACH,CAEJ","names":["deriveSessionSegment","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","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","sentientAgentMiddleware","config","request","userAgent","botName","path","e","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","_f","components","sections","slots","appOrigin","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","sessionSegment","deriveSessionSegment","cookieStore","cookies","initialAssignments","initialLayoutOrder","initialSlots","initialPersona","ssrSessionId","decision","loadAdaptiveDecision","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","__spreadProps","__spreadValues","path","feed","buildAgentFeed","renderAgentJsonLdBody"]}
package/dist/server.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as _sentientui_core_server from '@sentientui/core/server';
2
2
  import { ServerAssignments } from '@sentientui/core/server';
3
- export { DecideResult, ServerAssignConfig, ServerAssignments, preloadAssignments, preloadDecisions, readSessionCookie } from '@sentientui/core/server';
3
+ export { DecideResult, ServerAssignConfig, ServerAssignments, SlotDeclInput, SlotResult, preloadAssignments, preloadDecisions, readSessionCookie } from '@sentientui/core/server';
4
4
 
5
5
  /** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */
6
6
  type LoadAdaptiveAssignmentsResult = {
@@ -43,19 +43,31 @@ type LoadAdaptiveDecisionResult = _sentientui_core_server.DecideResult & {
43
43
  sessionId: string;
44
44
  };
45
45
  type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {
46
- /** Section IDs in default order. Passed to /v1/decide as the candidate layout. */
47
- sections: string[];
46
+ /**
47
+ * Section IDs in default order. Passed to /v1/decide as the candidate
48
+ * layout. Optional since 0.13.0 — slot-only pages may omit it (at least
49
+ * one of `sections`/`components`/`slots` must be non-empty).
50
+ */
51
+ sections?: string[];
48
52
  /** Components to assign in the same decide call. */
49
53
  components?: Array<{
50
54
  id: string;
51
55
  variantIds?: string[];
52
56
  }>;
57
+ /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */
58
+ slots?: _sentientui_core_server.SlotDeclInput[];
53
59
  };
54
60
  /**
55
- * SSR helper for pages with a declared section layout. Calls `/v1/decide`
56
- * instead of multiple `/v1/assign` round trips.
61
+ * SSR helper for pages with a declared section layout and/or adaptive slots.
62
+ * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.
57
63
  * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client
58
64
  * adopts the same session on first visit.
65
+ *
66
+ * Keyless: with no valid `pk_` key this never fetches (no timeout burn).
67
+ * Under the `development` export condition the decision is computed by the
68
+ * deterministic local engine with the same sessionId the client will adopt —
69
+ * server and client agree by construction. In production the engine resolves
70
+ * to a stub and defaults are returned with one console.error.
59
71
  */
60
72
  declare function loadAdaptiveDecision(options: LoadAdaptiveDecisionOptions): Promise<LoadAdaptiveDecisionResult>;
61
73
 
package/dist/server.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as _sentientui_core_server from '@sentientui/core/server';
2
2
  import { ServerAssignments } from '@sentientui/core/server';
3
- export { DecideResult, ServerAssignConfig, ServerAssignments, preloadAssignments, preloadDecisions, readSessionCookie } from '@sentientui/core/server';
3
+ export { DecideResult, ServerAssignConfig, ServerAssignments, SlotDeclInput, SlotResult, preloadAssignments, preloadDecisions, readSessionCookie } from '@sentientui/core/server';
4
4
 
5
5
  /** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */
6
6
  type LoadAdaptiveAssignmentsResult = {
@@ -43,19 +43,31 @@ type LoadAdaptiveDecisionResult = _sentientui_core_server.DecideResult & {
43
43
  sessionId: string;
44
44
  };
45
45
  type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {
46
- /** Section IDs in default order. Passed to /v1/decide as the candidate layout. */
47
- sections: string[];
46
+ /**
47
+ * Section IDs in default order. Passed to /v1/decide as the candidate
48
+ * layout. Optional since 0.13.0 — slot-only pages may omit it (at least
49
+ * one of `sections`/`components`/`slots` must be non-empty).
50
+ */
51
+ sections?: string[];
48
52
  /** Components to assign in the same decide call. */
49
53
  components?: Array<{
50
54
  id: string;
51
55
  variantIds?: string[];
52
56
  }>;
57
+ /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */
58
+ slots?: _sentientui_core_server.SlotDeclInput[];
53
59
  };
54
60
  /**
55
- * SSR helper for pages with a declared section layout. Calls `/v1/decide`
56
- * instead of multiple `/v1/assign` round trips.
61
+ * SSR helper for pages with a declared section layout and/or adaptive slots.
62
+ * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.
57
63
  * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client
58
64
  * adopts the same session on first visit.
65
+ *
66
+ * Keyless: with no valid `pk_` key this never fetches (no timeout burn).
67
+ * Under the `development` export condition the decision is computed by the
68
+ * deterministic local engine with the same sessionId the client will adopt —
69
+ * server and client agree by construction. In production the engine resolves
70
+ * to a stub and defaults are returned with one console.error.
59
71
  */
60
72
  declare function loadAdaptiveDecision(options: LoadAdaptiveDecisionOptions): Promise<LoadAdaptiveDecisionResult>;
61
73
 
package/dist/server.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var D=Object.create;var d=Object.defineProperty,I=Object.defineProperties,S=Object.getOwnPropertyDescriptor,x=Object.getOwnPropertyDescriptors,L=Object.getOwnPropertyNames,m=Object.getOwnPropertySymbols,U=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty,b=Object.prototype.propertyIsEnumerable;var u=(e,s,r)=>s in e?d(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r,p=(e,s)=>{for(var r in s||(s={}))A.call(s,r)&&u(e,r,s[r]);if(m)for(var r of m(s))b.call(s,r)&&u(e,r,s[r]);return e},y=(e,s)=>I(e,x(s));var M=(e,s)=>{for(var r in s)d(e,r,{get:s[r],enumerable:!0})},v=(e,s,r,i)=>{if(s&&typeof s=="object"||typeof s=="function")for(let t of L(s))!A.call(e,t)&&t!==r&&d(e,t,{get:()=>s[t],enumerable:!(i=S(s,t))||i.enumerable});return e};var R=(e,s,r)=>(r=e!=null?D(U(e)):{},v(s||!e||!e.__esModule?d(r,"default",{value:e,enumerable:!0}):r,e)),k=e=>v(d({},"__esModule",{value:!0}),e);var w={};M(w,{loadAdaptiveAssignments:()=>K,loadAdaptiveDecision:()=>O,preloadAssignments:()=>n.preloadAssignments,preloadDecisions:()=>l.preloadDecisions,readSessionCookie:()=>n.readSessionCookie});module.exports=k(w);var n=require("@sentientui/core/server"),l=require("@sentientui/core/server");function f(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function K(e,s){var t,a,o;let r=(o=(a=(0,n.readSessionCookie)(s.cookies))!=null?a:(t=s.createSessionId)==null?void 0:t.call(s))!=null?o:f();return{assignments:await(0,n.preloadAssignments)(e,r,{apiKey:s.apiKey,baseUrl:s.baseUrl,origin:s.origin,userAgent:s.userAgent,referer:s.referer,timeoutMs:s.timeoutMs}),sessionId:r}}async function O(e){var a,o,g,c;let{preloadDecisions:s,readSessionCookie:r}=await import("@sentientui/core/server"),i=(g=(o=r(e.cookies))!=null?o:(a=e.createSessionId)==null?void 0:a.call(e))!=null?g:f(),t=await s({sections:e.sections,components:(c=e.components)!=null?c:[]},i,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,timeoutMs:e.timeoutMs});return y(p({},t),{sessionId:i})}0&&(module.exports={loadAdaptiveAssignments,loadAdaptiveDecision,preloadAssignments,preloadDecisions,readSessionCookie});
1
+ "use strict";var _=Object.create;var c=Object.defineProperty,K=Object.defineProperties,N=Object.getOwnPropertyDescriptor,w=Object.getOwnPropertyDescriptors,C=Object.getOwnPropertyNames,S=Object.getOwnPropertySymbols,M=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty,P=Object.prototype.propertyIsEnumerable;var D=(e,s,t)=>s in e?c(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t,E=(e,s)=>{for(var t in s||(s={}))k.call(s,t)&&D(e,t,s[t]);if(S)for(var t of S(s))P.call(s,t)&&D(e,t,s[t]);return e},O=(e,s)=>K(e,w(s));var h=(e,s)=>{for(var t in s)c(e,t,{get:s[t],enumerable:!0})},R=(e,s,t,n)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of C(s))!k.call(e,r)&&r!==t&&c(e,r,{get:()=>s[r],enumerable:!(n=N(s,r))||n.enumerable});return e};var b=(e,s,t)=>(t=e!=null?_(M(e)):{},R(s||!e||!e.__esModule?c(t,"default",{value:e,enumerable:!0}):t,e)),V=e=>R(c({},"__esModule",{value:!0}),e);var G={};h(G,{loadAdaptiveAssignments:()=>B,loadAdaptiveDecision:()=>T,preloadAssignments:()=>i.preloadAssignments,preloadDecisions:()=>U.preloadDecisions,readSessionCookie:()=>i.readSessionCookie});module.exports=V(G);var i=require("@sentientui/core/server"),U=require("@sentientui/core/server");function x(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function B(e,s){var r,d,o;let t=(o=(d=(0,i.readSessionCookie)(s.cookies))!=null?d:(r=s.createSessionId)==null?void 0:r.call(s))!=null?o:x();return{assignments:await(0,i.preloadAssignments)(e,t,{apiKey:s.apiKey,baseUrl:s.baseUrl,origin:s.origin,userAgent:s.userAgent,referer:s.referer,timeoutMs:s.timeoutMs}),sessionId:t}}async function T(e){var o,l,u,m,p,A,y,f,v,I;let{preloadDecisions:s,readSessionCookie:t}=await import("@sentientui/core/server"),n=(u=(l=t(e.cookies))!=null?l:(o=e.createSessionId)==null?void 0:o.call(e))!=null?u:x();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let L={layoutOrder:(m=e.sections)!=null?m:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:n};try{let g=await import("@sentientui/core/local");if(!g.LOCAL_ENGINE_AVAILABLE)return console.error("[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development."),L;let a=g.createLocalEngine({sessionId:n}).decide({sections:e.sections,components:(p=e.components)!=null?p:[],slots:(A=e.slots)!=null?A:[]});return{layoutOrder:(f=(y=a.layoutOrder)!=null?y:e.sections)!=null?f:[],assignments:a.assignments,slots:a.slots,persona:a.persona,confidence:a.confidence,sessionId:n}}catch(g){return L}}let d=await s({sections:e.sections,components:(v=e.components)!=null?v:[],slots:(I=e.slots)!=null?I:[]},n,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,timeoutMs:e.timeoutMs});return O(E({},d),{sessionId:n})}0&&(module.exports={loadAdaptiveAssignments,loadAdaptiveDecision,preloadAssignments,preloadDecisions,readSessionCookie});
2
2
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\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 /** 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\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 timeoutMs: options.timeoutMs,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult } 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 /** Section IDs in default order. Passed to /v1/decide as the candidate layout. */\n sections: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n};\n\n/**\n * SSR helper for pages with a declared section layout. Calls `/v1/decide`\n * 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 */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n const sessionId =\n readSessionCookie(options.cookies) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\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 timeoutMs: options.timeoutMs,\n },\n );\n\n return { ...result, sessionId };\n}\n"],"mappings":"i5BAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,yBAAAC,EAAA,+IAAAC,EAAAJ,GAGA,IAAAK,EAKO,mCA8DPA,EAAiC,mCAjCjC,SAASC,GAA2B,CAClC,OAAI,OAAO,QAAW,aAAe,OAAO,OAAO,YAAe,WACzD,OAAO,WAAW,EAEpB,OAAO,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,EAAG,EAAE,CAAC,EACrE,CAOA,eAAsBC,EACpBC,EACAC,EACwC,CApD1C,IAAAC,EAAAC,EAAAC,EAqDE,IAAMC,GACJD,GAAAD,KAAA,qBAAkBF,EAAQ,OAAO,IAAjC,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,EAAiB,EAWnB,MAAO,CAAE,YATW,QAAM,sBAAmBE,EAAYK,EAAW,CAClE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,UAAWA,EAAQ,SACrB,CAAC,EAEqB,UAAAI,CAAU,CAClC,CAuBA,eAAsBC,EACpBL,EACqC,CA7FvC,IAAAC,EAAAC,EAAAC,EAAAG,EA8FE,GAAM,CAAE,iBAAAC,EAAkB,kBAAAC,CAAkB,EAAI,KAAM,QAAO,yBAAyB,EAEhFJ,GACJD,GAAAD,EAAAM,EAAkBR,EAAQ,OAAO,IAAjC,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,EAAiB,EAEbY,EAAS,MAAMF,EACnB,CACE,SAAUP,EAAQ,SAClB,YAAYM,EAAAN,EAAQ,aAAR,KAAAM,EAAsB,CAAC,CACrC,EACAF,EACA,CACE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,UAAWA,EAAQ,SACrB,CACF,EAEA,OAAOU,EAAAC,EAAA,GAAKF,GAAL,CAAa,UAAAL,CAAU,EAChC","names":["server_exports","__export","loadAdaptiveAssignments","loadAdaptiveDecision","__toCommonJS","import_server","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","loadAdaptiveDecision","_d","preloadDecisions","readSessionCookie","result","__spreadProps","__spreadValues"]}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\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 /** 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\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 timeoutMs: options.timeoutMs,\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};\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n timeoutMs: options.timeoutMs,\n },\n );\n\n return { ...result, sessionId };\n}\n"],"mappings":"i5BAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,yBAAAC,EAAA,+IAAAC,EAAAJ,GAGA,IAAAK,EAKO,mCA8DPA,EAAiC,mCAjCjC,SAASC,GAA2B,CAClC,OAAI,OAAO,QAAW,aAAe,OAAO,OAAO,YAAe,WACzD,OAAO,WAAW,EAEpB,OAAO,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,EAAG,EAAE,CAAC,EACrE,CAOA,eAAsBC,EACpBC,EACAC,EACwC,CApD1C,IAAAC,EAAAC,EAAAC,EAqDE,IAAMC,GACJD,GAAAD,KAAA,qBAAkBF,EAAQ,OAAO,IAAjC,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,EAAiB,EAWnB,MAAO,CAAE,YATW,QAAM,sBAAmBE,EAAYK,EAAW,CAClE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,UAAWA,EAAQ,SACrB,CAAC,EAEqB,UAAAI,CAAU,CAClC,CAmCA,eAAsBC,EACpBL,EACqC,CAzGvC,IAAAC,EAAAC,EAAAC,EAAAG,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EA0GE,GAAM,CAAE,iBAAAC,EAAkB,kBAAAC,CAAkB,E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,QACjB,UAAWA,EAAQ,SACrB,CACF,EAEA,OAAOoB,EAAAC,EAAA,GAAKF,GAAL,CAAa,UAAAf,CAAU,EAChC","names":["server_exports","__export","loadAdaptiveAssignments","loadAdaptiveDecision","__toCommonJS","import_server","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","readSessionCookie","fallback","mod","outcome","e","result","__spreadProps","__spreadValues"]}
package/dist/server.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var p=Object.defineProperty,y=Object.defineProperties;var v=Object.getOwnPropertyDescriptors;var g=Object.getOwnPropertySymbols;var f=Object.prototype.hasOwnProperty,l=Object.prototype.propertyIsEnumerable;var c=(s,e,r)=>e in s?p(s,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[e]=r,m=(s,e)=>{for(var r in e||(e={}))f.call(e,r)&&c(s,r,e[r]);if(g)for(var r of g(e))l.call(e,r)&&c(s,r,e[r]);return s},u=(s,e)=>y(s,v(e));import{preloadAssignments as D,readSessionCookie as I}from"@sentientui/core/server";import{preloadDecisions as R}from"@sentientui/core/server";function A(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function L(s,e){var n,t,i;let r=(i=(t=I(e.cookies))!=null?t:(n=e.createSessionId)==null?void 0:n.call(e))!=null?i:A();return{assignments:await D(s,r,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,timeoutMs:e.timeoutMs}),sessionId:r}}async function U(s){var t,i,o,d;let{preloadDecisions:e,readSessionCookie:r}=await import("@sentientui/core/server"),a=(o=(i=r(s.cookies))!=null?i:(t=s.createSessionId)==null?void 0:t.call(s))!=null?o:A(),n=await e({sections:s.sections,components:(d=s.components)!=null?d:[]},a,{apiKey:s.apiKey,baseUrl:s.baseUrl,origin:s.origin,userAgent:s.userAgent,referer:s.referer,timeoutMs:s.timeoutMs});return u(m({},n),{sessionId:a})}export{L as loadAdaptiveAssignments,U as loadAdaptiveDecision,D as preloadAssignments,R as preloadDecisions,I as readSessionCookie};
1
+ var E=Object.defineProperty,O=Object.defineProperties;var R=Object.getOwnPropertyDescriptors;var I=Object.getOwnPropertySymbols;var b=Object.prototype.hasOwnProperty,x=Object.prototype.propertyIsEnumerable;var L=(e,s,t)=>s in e?E(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t,S=(e,s)=>{for(var t in s||(s={}))b.call(s,t)&&L(e,t,s[t]);if(I)for(var t of I(s))x.call(s,t)&&L(e,t,s[t]);return e},D=(e,s)=>O(e,R(s));import{preloadAssignments as U,readSessionCookie as _}from"@sentientui/core/server";import{preloadDecisions as h}from"@sentientui/core/server";function k(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function w(e,s){var a,o,r;let t=(r=(o=_(s.cookies))!=null?o:(a=s.createSessionId)==null?void 0:a.call(s))!=null?r:k();return{assignments:await U(e,t,{apiKey:s.apiKey,baseUrl:s.baseUrl,origin:s.origin,userAgent:s.userAgent,referer:s.referer,timeoutMs:s.timeoutMs}),sessionId:t}}async function C(e){var r,d,g,l,u,m,p,A,y,f;let{preloadDecisions:s,readSessionCookie:t}=await import("@sentientui/core/server"),n=(g=(d=t(e.cookies))!=null?d:(r=e.createSessionId)==null?void 0:r.call(e))!=null?g:k();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let v={layoutOrder:(l=e.sections)!=null?l:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:n};try{let c=await import("@sentientui/core/local");if(!c.LOCAL_ENGINE_AVAILABLE)return console.error("[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development."),v;let i=c.createLocalEngine({sessionId:n}).decide({sections:e.sections,components:(u=e.components)!=null?u:[],slots:(m=e.slots)!=null?m:[]});return{layoutOrder:(A=(p=i.layoutOrder)!=null?p:e.sections)!=null?A:[],assignments:i.assignments,slots:i.slots,persona:i.persona,confidence:i.confidence,sessionId:n}}catch(c){return v}}let o=await s({sections:e.sections,components:(y=e.components)!=null?y:[],slots:(f=e.slots)!=null?f:[]},n,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,timeoutMs:e.timeoutMs});return D(S({},o),{sessionId:n})}export{w as loadAdaptiveAssignments,C as loadAdaptiveDecision,U as preloadAssignments,h as preloadDecisions,_ as readSessionCookie};
2
2
  //# sourceMappingURL=server.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\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 /** 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\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 timeoutMs: options.timeoutMs,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult } 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 /** Section IDs in default order. Passed to /v1/decide as the candidate layout. */\n sections: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n};\n\n/**\n * SSR helper for pages with a declared section layout. Calls `/v1/decide`\n * 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 */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n const sessionId =\n readSessionCookie(options.cookies) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\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 timeoutMs: options.timeoutMs,\n },\n );\n\n return { ...result, sessionId };\n}\n"],"mappings":"6aAGA,OACE,sBAAAA,EACA,qBAAAC,MAGK,0BA8DP,OAAS,oBAAAC,MAAwB,0BAjCjC,SAASC,GAA2B,CAClC,OAAI,OAAO,QAAW,aAAe,OAAO,OAAO,YAAe,WACzD,OAAO,WAAW,EAEpB,OAAO,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,EAAG,EAAE,CAAC,EACrE,CAOA,eAAsBC,EACpBC,EACAC,EACwC,CApD1C,IAAAC,EAAAC,EAAAC,EAqDE,IAAMC,GACJD,GAAAD,EAAAG,EAAkBL,EAAQ,OAAO,IAAjC,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,EAAiB,EAWnB,MAAO,CAAE,YATW,MAAMS,EAAmBP,EAAYK,EAAW,CAClE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,UAAWA,EAAQ,SACrB,CAAC,EAEqB,UAAAI,CAAU,CAClC,CAuBA,eAAsBG,EACpBP,EACqC,CA7FvC,IAAAC,EAAAC,EAAAC,EAAAK,EA8FE,GAAM,CAAE,iBAAAC,EAAkB,kBAAAJ,CAAkB,EAAI,KAAM,QAAO,yBAAyB,EAEhFD,GACJD,GAAAD,EAAAG,EAAkBL,EAAQ,OAAO,IAAjC,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,EAAiB,EAEba,EAAS,MAAMD,EACnB,CACE,SAAUT,EAAQ,SAClB,YAAYQ,EAAAR,EAAQ,aAAR,KAAAQ,EAAsB,CAAC,CACrC,EACAJ,EACA,CACE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,UAAWA,EAAQ,SACrB,CACF,EAEA,OAAOW,EAAAC,EAAA,GAAKF,GAAL,CAAa,UAAAN,CAAU,EAChC","names":["preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","preloadDecisions","result","__spreadProps","__spreadValues"]}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\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 /** 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\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 timeoutMs: options.timeoutMs,\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};\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 const sessionId =\n readSessionCookie(options.cookies) ??\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 },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n timeoutMs: options.timeoutMs,\n },\n );\n\n return { ...result, sessionId };\n}\n"],"mappings":"6aAGA,OACE,sBAAAA,EACA,qBAAAC,MAGK,0BA8DP,OAAS,oBAAAC,MAAwB,0BAjCjC,SAASC,GAA2B,CAClC,OAAI,OAAO,QAAW,aAAe,OAAO,OAAO,YAAe,WACzD,OAAO,WAAW,EAEpB,OAAO,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,EAAG,EAAE,CAAC,EACrE,CAOA,eAAsBC,EACpBC,EACAC,EACwC,CApD1C,IAAAC,EAAAC,EAAAC,EAqDE,IAAMC,GACJD,GAAAD,EAAAG,EAAkBL,EAAQ,OAAO,IAAjC,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,EAAiB,EAWnB,MAAO,CAAE,YATW,MAAMS,EAAmBP,EAAYK,EAAW,CAClE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,UAAWA,EAAQ,SACrB,CAAC,EAEqB,UAAAI,CAAU,CAClC,CAmCA,eAAsBG,EACpBP,EACqC,CAzGvC,IAAAC,EAAAC,EAAAC,EAAAK,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EA0GE,GAAM,CAAE,iBAAAC,EAAkB,kBAAAV,CAAkB,EAAI,KAAM,QAAO,yBAAyB,EAEhFD,GACJD,GAAAD,EAAAG,EAAkBL,EAAQ,OAAO,IAAjC,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,EAAiB,EAGnB,GAAI,EADa,OAAOG,EAAQ,QAAW,UAAYA,EAAQ,OAAO,WAAW,KAAK,GACvE,CACb,IAAMgB,EAAuC,CAC3C,aAAaR,EAAAR,EAAQ,WAAR,KAAAQ,EAAoB,CAAC,EAClC,YAAa,CAAC,EACd,MAAO,CAAC,EACR,QAAS,UACT,WAAY,EACZ,UAAAJ,CACF,EACA,GAAI,CACF,IAAMa,EAAO,KAAM,QAAO,wBAAwB,EAgBlD,GAAI,CAACA,EAAI,uBAEP,eAAQ,MACN,mJACF,EACOD,EAET,IAAME,EAAUD,EAAI,kBAAkB,CAAE,UAAAb,CAAU,CAAC,EAAE,OAAO,CAC1D,SAAUJ,EAAQ,SAClB,YAAYS,EAAAT,EAAQ,aAAR,KAAAS,EAAsB,CAAC,EACnC,OAAOC,EAAAV,EAAQ,QAAR,KAAAU,EAAiB,CAAC,CAC3B,CAAC,EACD,MAAO,CACL,aAAaE,GAAAD,EAAAO,EAAQ,cAAR,KAAAP,EAAuBX,EAAQ,WAA/B,KAAAY,EAA2C,CAAC,EACzD,YAAaM,EAAQ,YACrB,MAAOA,EAAQ,MACf,QAASA,EAAQ,QACjB,WAAYA,EAAQ,WACpB,UAAAd,CACF,CACF,OAAQe,EAAA,CACN,OAAOH,CACT,CACF,CAEA,IAAMI,EAAS,MAAML,EACnB,CACE,SAAUf,EAAQ,SAClB,YAAYa,EAAAb,EAAQ,aAAR,KAAAa,EAAsB,CAAC,EACnC,OAAOC,EAAAd,EAAQ,QAAR,KAAAc,EAAiB,CAAC,CAC3B,EACAV,EACA,CACE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,UAAWA,EAAQ,SACrB,CACF,EAEA,OAAOqB,EAAAC,EAAA,GAAKF,GAAL,CAAa,UAAAhB,CAAU,EAChC","names":["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"]}
@@ -13,7 +13,12 @@ type ScenarioApiOverride = 'error' | number | {
13
13
  type SentientScenario = {
14
14
  variants?: Record<string, string>;
15
15
  layout?: string[];
16
+ /** Forced persona (canonical PersonaKey). Also sets the persona html attributes. */
16
17
  persona?: string;
18
+ /** Persona confidence 0–1; buckets to low/medium/high for the html attribute. Default 1. */
19
+ confidence?: number;
20
+ /** Forced slot results: slot id → arm id (arms slots) or per-dim values (token slots). */
21
+ slots?: Record<string, string | Record<string, string>>;
17
22
  weights?: Record<string, ScenarioWeight[]>;
18
23
  api?: Record<string, ScenarioApiOverride>;
19
24
  };
@@ -13,7 +13,12 @@ type ScenarioApiOverride = 'error' | number | {
13
13
  type SentientScenario = {
14
14
  variants?: Record<string, string>;
15
15
  layout?: string[];
16
+ /** Forced persona (canonical PersonaKey). Also sets the persona html attributes. */
16
17
  persona?: string;
18
+ /** Persona confidence 0–1; buckets to low/medium/high for the html attribute. Default 1. */
19
+ confidence?: number;
20
+ /** Forced slot results: slot id → arm id (arms slots) or per-dim values (token slots). */
21
+ slots?: Record<string, string | Record<string, string>>;
17
22
  weights?: Record<string, ScenarioWeight[]>;
18
23
  api?: Record<string, ScenarioApiOverride>;
19
24
  };
@@ -1,2 +1,2 @@
1
- "use strict";var v=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var U=(t,e)=>{for(var n in e)v(t,n,{get:e[n],enumerable:!0})},D=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _(e))!G.call(t,s)&&s!==n&&v(t,s,{get:()=>e[s],enumerable:!(r=P(e,s))||r.enumerable});return t};var F=t=>D(v({},"__esModule",{value:!0}),t);var z={};U(z,{setupSentientServer:()=>A});module.exports=F(z);var H=require("msw/node");var d=require("msw");var J=[];function l(t){J.push(t)}function L(t){var e;try{return new URL(t).pathname}catch(n){return(e=t.split("?")[0])!=null?e:t}}async function N(t,e){var r,s,o;let n=(r=t.api)==null?void 0:r[e];return n===void 0?null:n==="error"?{status:500}:typeof n=="number"?{status:n}:(n.delayMs&&await new Promise(c=>setTimeout(c,n.delayMs)),{status:(s=n.status)!=null?s:200,json:(o=n.body)!=null?o:{}})}async function k(t,e,n,r){var f,g,S,y,h,w,j,E,x,T,b,R,O,I,C;let s=L(n);if(!s.includes("/v1/"))return null;let o="/v1/"+((f=s.split("/v1/")[1])!=null?f:""),c=await N(t,o);if(c)return c;let a=r?JSON.parse(r):{};if(o==="/v1/sessions")return{status:204};if(o==="/v1/events"){for(let i of a)l(i);return{status:204}}if(o==="/v1/goals")return l({eventType:"goal",goalType:a.name}),{status:204};if(o==="/v1/assign"){let i=a;return{status:200,json:{variantId:(h=(y=(g=t.variants)==null?void 0:g[i.componentId])!=null?y:(S=i.variantIds)==null?void 0:S[0])!=null?h:"control",assignmentTtlMs:6e4}}}if(o==="/v1/decide"){let i=a;return{status:200,json:{layoutOrder:(j=t.layout)!=null?j:((w=i.sections)!=null?w:[]).map(p=>p.id),assignments:(E=t.variants)!=null?E:{},persona:(x=t.persona)!=null?x:"unknown",confidence:1}}}if(o==="/v1/explain"){let i=a,u=(b=t.layout)!=null?b:((T=i.sections)!=null?T:[]).map(M=>M.id),p=(O=(R=i.persona)!=null?R:t.persona)!=null?O:"unknown";return{status:200,json:{layoutOrder:u,assignments:(I=t.variants)!=null?I:{},persona:p,reasons:[]}}}return o==="/v1/weights"?{status:200,json:{components:Object.entries((C=t.weights)!=null?C:{}).map(([u,p])=>({componentId:u,updatedAt:0,variants:p}))}}:null}function m(t={}){return[d.http.all("*/v1/*",async({request:e})=>{let n=e.method==="GET"||e.method==="HEAD"?null:await e.text(),r=await k(t,e.method,e.url,n);if(r)return r.json===void 0?new d.HttpResponse(null,{status:r.status}):d.HttpResponse.json(r.json,{status:r.status})})]}function A(){let t=(0,H.setupServer)(...m());return t.listen({onUnhandledRequest:"bypass"}),{server:t,use:(e={})=>t.use(...m(e))}}0&&(module.exports={setupSentientServer});
1
+ "use strict";var m=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var Q=Object.prototype.hasOwnProperty;var V=(e,t)=>{for(var n in t)m(e,n,{get:t[n],enumerable:!0})},X=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of K(t))!Q.call(e,o)&&o!==n&&m(e,o,{get:()=>t[o],enumerable:!(r=z(t,o))||r.enumerable});return e};var Y=e=>X(m({},"__esModule",{value:!0}),e);var ee={};V(ee,{setupSentientServer:()=>N});module.exports=Y(ee);var L=require("msw/node");var g=require("msw");var Z=[];function _(e){Z.push(e)}function D(e){return e<.3?"low":e<.7?"medium":"high"}function $(e){var t;try{return new URL(e).pathname}catch(n){return(t=e.split("?")[0])!=null?t:e}}async function q(e,t){var r,o,i;let n=(r=e.api)==null?void 0:r[t];return n===void 0?null:n==="error"?{status:500}:typeof n=="number"?{status:n}:(n.delayMs&&await new Promise(u=>setTimeout(u,n.delayMs)),{status:(o=n.status)!=null?o:200,json:(i=n.body)!=null?i:{}})}async function J(e,t,n,r){var S,b,w,R,h,x,E,j,O,k,A,T,I,C,H,W,M,P,B,G,U;let o=$(n);if(!o.includes("/v1/"))return null;let i="/v1/"+((S=o.split("/v1/")[1])!=null?S:""),u=await q(e,i);if(u)return u;let a=r?JSON.parse(r):{};if(i==="/v1/sessions")return{status:204};if(i==="/v1/events"){for(let s of a)_(s);return{status:204}}if(i==="/v1/goals")return _({eventType:"goal",goalType:a.name}),{status:204};if(i==="/v1/assign"){let s=a;return{status:200,json:{variantId:(h=(R=(b=e.variants)==null?void 0:b[s.componentId])!=null?R:(w=s.variantIds)==null?void 0:w[0])!=null?h:"control",assignmentTtlMs:6e4}}}if(i==="/v1/decide"){let s=a,d={layoutOrder:(E=e.layout)!=null?E:((x=s.sections)!=null?x:[]).map(c=>c.id),assignments:(j=e.variants)!=null?j:{},persona:(O=e.persona)!=null?O:"unknown",confidence:(k=e.confidence)!=null?k:1};if(s.slots&&s.slots.length>0){let c={};for(let p of s.slots)c[p.id]=(T=(A=e.slots)==null?void 0:A[p.id])!=null?T:F(p);d.slots=c}return{status:200,json:d}}if(i==="/v1/explain"){let s=a,l=(C=e.layout)!=null?C:((I=s.sections)!=null?I:[]).map(v=>v.id),d=(W=(H=s.persona)!=null?H:e.persona)!=null?W:"unknown",c=(M=e.confidence)!=null?M:1,p={layoutOrder:l,assignments:(P=e.variants)!=null?P:{},persona:d,reasons:[],personaAttributes:{persona:d,confidence:D(c)}};if(s.slots&&s.slots.length>0){let v={};for(let f of s.slots)v[f.id]=(G=(B=e.slots)==null?void 0:B[f.id])!=null?G:F(f);p.slots=v}return{status:200,json:p}}return i==="/v1/weights"?{status:200,json:{components:Object.entries((U=e.weights)!=null?U:{}).map(([l,d])=>({componentId:l,updatedAt:0,variants:d}))}}:null}function F(e){var n,r,o;if(e.arms)return typeof e.baseline=="string"?e.baseline:(n=e.arms[0])!=null?n:"baseline";let t={};for(let[i,u]of Object.entries((r=e.dims)!=null?r:{})){let a=typeof e.baseline=="object"&&e.baseline!==null?e.baseline[i]:void 0;t[i]=(o=a!=null?a:u[0])!=null?o:""}return t}function y(e={}){return[g.http.all("*/v1/*",async({request:t})=>{let n=t.method==="GET"||t.method==="HEAD"?null:await t.text(),r=await J(e,t.method,t.url,n);if(r)return r.json===void 0?new g.HttpResponse(null,{status:r.status}):g.HttpResponse.json(r.json,{status:r.status})})]}function N(){let e=(0,L.setupServer)(...y());return e.listen({onUnhandledRequest:"bypass"}),{server:e,use:(t={})=>e.use(...y(t))}}0&&(module.exports={setupSentientServer});
2
2
  //# sourceMappingURL=node.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/testing/node.ts","../../src/testing/server.ts","../../src/testing/handlers.ts","../../src/testing/events.ts","../../src/testing/resolve.ts"],"sourcesContent":["// Node-only testing helpers. Kept out of the main `@sentientui/react/testing`\n// entry so that entry stays browser-bundle-safe (Cypress/webpack) — `msw/node`\n// pulls Node built-ins that break a browser bundle.\nexport { setupSentientServer } from './server.js';\n","import { setupServer, type SetupServer } from 'msw/node';\nimport { scenarioToHandlers } from './handlers.js';\nimport type { SentientScenario } from './scenario.js';\n\n/**\n * Create and start an msw/node server pre-loaded with the default (control)\n * scenario. Call `use(scenario)` to swap in a scenario for the current test.\n * Remember to `server.close()` in afterAll and `server.resetHandlers()` between tests.\n */\nexport function setupSentientServer(): {\n server: SetupServer;\n use: (scenario?: SentientScenario) => void;\n} {\n const server = setupServer(...scenarioToHandlers());\n server.listen({ onUnhandledRequest: 'bypass' });\n return {\n server,\n use: (scenario: SentientScenario = {}) => server.use(...scenarioToHandlers(scenario)),\n };\n}\n","import { http, HttpResponse } from 'msw';\nimport type { RequestHandler } from 'msw';\nimport { resolveScenario } from './resolve.js';\nimport type { SentientScenario } from './scenario.js';\n\n/** Turn a scenario into MSW handlers stubbing every SDK endpoint + capturing events. */\nexport function scenarioToHandlers(scenario: SentientScenario = {}): RequestHandler[] {\n return [\n http.all('*/v1/*', async ({ request }) => {\n const bodyText =\n request.method === 'GET' || request.method === 'HEAD' ? null : await request.text();\n const r = await resolveScenario(scenario, request.method, request.url, bodyText);\n if (!r) return undefined; // not a stubbed route — let MSW handle passthrough\n if (r.json === undefined) return new HttpResponse(null, { status: r.status });\n return HttpResponse.json(r.json as object, { status: r.status });\n }),\n ];\n}\n","export type CapturedEvent = {\n eventType: string;\n goalType?: string;\n componentId?: string;\n variantId?: string;\n [k: string]: unknown;\n};\n\nconst captured: CapturedEvent[] = [];\n\nexport function recordEvent(e: CapturedEvent): void {\n captured.push(e);\n}\n\nexport function getSentientEvents(): CapturedEvent[] {\n return [...captured];\n}\n\nexport function clearSentientEvents(): void {\n captured.length = 0;\n}\n\n/** True if any captured event is a goal (component goal_achieved or named goal) with this name. */\nexport function hasFiredGoal(events: CapturedEvent[], goalName: string): boolean {\n return events.some(\n (e) => (e.eventType === 'goal_achieved' || e.eventType === 'goal') && e.goalType === goalName,\n );\n}\n","import { recordEvent, type CapturedEvent } from './events.js';\nimport type { SentientScenario, ScenarioApiOverride } from './scenario.js';\n\n/** A framework-agnostic resolved response. `json` undefined ⇒ empty body. */\nexport type ResolvedResponse = { status: number; json?: unknown };\n\nfunction pathOf(url: string): string {\n try { return new URL(url).pathname; } catch { return url.split('?')[0] ?? url; }\n}\n\nasync function apiOverride(scenario: SentientScenario, route: string): Promise<ResolvedResponse | null> {\n const o: ScenarioApiOverride | undefined = scenario.api?.[route];\n if (o === undefined) return null;\n if (o === 'error') return { status: 500 };\n if (typeof o === 'number') return { status: o };\n if (o.delayMs) await new Promise((r) => setTimeout(r, o.delayMs));\n return { status: o.status ?? 200, json: o.body ?? {} };\n}\n\n/**\n * Resolve a request against a scenario. Returns a response, or null for routes\n * outside `/v1/*` (let the caller pass through). Shared by the MSW handlers and\n * the Playwright/Cypress adapters so behaviour can't drift.\n */\nexport async function resolveScenario(\n scenario: SentientScenario,\n _method: string,\n url: string,\n bodyText: string | null,\n): Promise<ResolvedResponse | null> {\n const path = pathOf(url);\n if (!path.includes('/v1/')) return null;\n\n const route = '/v1/' + (path.split('/v1/')[1] ?? '');\n const override = await apiOverride(scenario, route);\n if (override) return override;\n\n const body = bodyText ? (JSON.parse(bodyText) as unknown) : {};\n\n if (route === '/v1/sessions') return { status: 204 };\n\n if (route === '/v1/events') {\n for (const e of body as CapturedEvent[]) recordEvent(e);\n return { status: 204 };\n }\n\n if (route === '/v1/goals') {\n recordEvent({ eventType: 'goal', goalType: (body as { name?: string }).name });\n return { status: 204 };\n }\n\n if (route === '/v1/assign') {\n const b = body as { componentId: string; variantIds?: string[] };\n const variantId = scenario.variants?.[b.componentId] ?? b.variantIds?.[0] ?? 'control';\n return { status: 200, json: { variantId, assignmentTtlMs: 60_000 } };\n }\n\n if (route === '/v1/decide') {\n const b = body as { sections?: { id: string }[] };\n const layoutOrder = scenario.layout ?? (b.sections ?? []).map((s) => s.id);\n return { status: 200, json: { layoutOrder, assignments: scenario.variants ?? {}, persona: scenario.persona ?? 'unknown', confidence: 1 } };\n }\n\n if (route === '/v1/explain') {\n const b = body as { sections?: { id: string }[]; persona?: string };\n const layoutOrder = scenario.layout ?? (b.sections ?? []).map((s) => s.id);\n const persona = b.persona ?? scenario.persona ?? 'unknown';\n return { status: 200, json: { layoutOrder, assignments: scenario.variants ?? {}, persona, reasons: [] } };\n }\n\n if (route === '/v1/weights') {\n const components = Object.entries(scenario.weights ?? {}).map(([componentId, variants]) => ({ componentId, updatedAt: 0, variants }));\n return { status: 200, json: { components } };\n }\n\n return null;\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,yBAAAE,IAAA,eAAAC,EAAAH,GCAA,IAAAI,EAA8C,oBCA9C,IAAAC,EAAmC,eCQnC,IAAMC,EAA4B,CAAC,EAE5B,SAASC,EAAYC,EAAwB,CAClDF,EAAS,KAAKE,CAAC,CACjB,CCNA,SAASC,EAAOC,EAAqB,CANrC,IAAAC,EAOE,GAAI,CAAE,OAAO,IAAI,IAAID,CAAG,EAAE,QAAU,OAAQE,EAAA,CAAE,OAAOD,EAAAD,EAAI,MAAM,GAAG,EAAE,CAAC,IAAhB,KAAAC,EAAqBD,CAAK,CACjF,CAEA,eAAeG,EAAYC,EAA4BC,EAAiD,CAVxG,IAAAJ,EAAAK,EAAAC,EAWE,IAAMC,GAAqCP,EAAAG,EAAS,MAAT,YAAAH,EAAeI,GAC1D,OAAIG,IAAM,OAAkB,KACxBA,IAAM,QAAgB,CAAE,OAAQ,GAAI,EACpC,OAAOA,GAAM,SAAiB,CAAE,OAAQA,CAAE,GAC1CA,EAAE,SAAS,MAAM,IAAI,QAASC,GAAM,WAAWA,EAAGD,EAAE,OAAO,CAAC,EACzD,CAAE,QAAQF,EAAAE,EAAE,SAAF,KAAAF,EAAY,IAAK,MAAMC,EAAAC,EAAE,OAAF,KAAAD,EAAU,CAAC,CAAE,EACvD,CAOA,eAAsBG,EACpBN,EACAO,EACAX,EACAY,EACkC,CA7BpC,IAAAX,EAAAK,EAAAC,EAAAM,EA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S,CAAC,EACvC,CACL,OAAAA,EACA,IAAK,CAACE,EAA6B,CAAC,IAAMF,EAAO,IAAI,GAAGC,EAAmBC,CAAQ,CAAC,CACtF,CACF","names":["node_exports","__export","setupSentientServer","__toCommonJS","import_node","import_msw","captured","recordEvent","e","pathOf","url","_a","e","apiOverride","scenario","route","_b","_c","o","r","resolveScenario","_method","bodyText","_d","_e","_f","_g","_h","_i","_j","_k","_l","_m","_n","_o","path","override","body","recordEvent","b","s","layoutOrder","persona","componentId","variants","scenarioToHandlers","scenario","request","bodyText","resolveScenario","setupSentientServer","server","scenarioToHandlers","scenario"]}
1
+ {"version":3,"sources":["../../src/testing/node.ts","../../src/testing/server.ts","../../src/testing/handlers.ts","../../src/testing/events.ts","../../src/testing/scenario.ts","../../src/testing/resolve.ts"],"sourcesContent":["// Node-only testing helpers. Kept out of the main `@sentientui/react/testing`\n// entry so that entry stays browser-bundle-safe (Cypress/webpack) — `msw/node`\n// pulls Node built-ins that break a browser bundle.\nexport { setupSentientServer } from './server.js';\n","import { setupServer, type SetupServer } from 'msw/node';\nimport { scenarioToHandlers } from './handlers.js';\nimport type { SentientScenario } from './scenario.js';\n\n/**\n * Create and start an msw/node server pre-loaded with the default (control)\n * scenario. Call `use(scenario)` to swap in a scenario for the current test.\n * Remember to `server.close()` in afterAll and `server.resetHandlers()` between tests.\n */\nexport function setupSentientServer(): {\n server: SetupServer;\n use: (scenario?: SentientScenario) => void;\n} {\n const server = setupServer(...scenarioToHandlers());\n server.listen({ onUnhandledRequest: 'bypass' });\n return {\n server,\n use: (scenario: SentientScenario = {}) => server.use(...scenarioToHandlers(scenario)),\n };\n}\n","import { http, HttpResponse } from 'msw';\nimport type { RequestHandler } from 'msw';\nimport { resolveScenario } from './resolve.js';\nimport type { SentientScenario } from './scenario.js';\n\n/** Turn a scenario into MSW handlers stubbing every SDK endpoint + capturing events. */\nexport function scenarioToHandlers(scenario: SentientScenario = {}): RequestHandler[] {\n return [\n http.all('*/v1/*', async ({ request }) => {\n const bodyText =\n request.method === 'GET' || request.method === 'HEAD' ? null : await request.text();\n const r = await resolveScenario(scenario, request.method, request.url, bodyText);\n if (!r) return undefined; // not a stubbed route — let MSW handle passthrough\n if (r.json === undefined) return new HttpResponse(null, { status: r.status });\n return HttpResponse.json(r.json as object, { status: r.status });\n }),\n ];\n}\n","export type CapturedEvent = {\n eventType: string;\n goalType?: string;\n componentId?: string;\n variantId?: string;\n [k: string]: unknown;\n};\n\nconst captured: CapturedEvent[] = [];\n\nexport function recordEvent(e: CapturedEvent): void {\n captured.push(e);\n}\n\nexport function getSentientEvents(): CapturedEvent[] {\n return [...captured];\n}\n\nexport function clearSentientEvents(): void {\n captured.length = 0;\n}\n\n/** True if any captured event is a goal (component goal_achieved or named goal) with this name. */\nexport function hasFiredGoal(events: CapturedEvent[], goalName: string): boolean {\n return events.some(\n (e) => (e.eventType === 'goal_achieved' || e.eventType === 'goal') && e.goalType === goalName,\n );\n}\n","export type ScenarioWeight = { variantId: string; pulls: number; avgReward: number };\nexport type ScenarioApiOverride =\n | 'error'\n | number\n | { status?: number; body?: unknown; delayMs?: number };\n\nexport type SentientScenario = {\n variants?: Record<string, string>;\n layout?: string[];\n /** Forced persona (canonical PersonaKey). Also sets the persona html attributes. */\n persona?: string;\n /** Persona confidence 0–1; buckets to low/medium/high for the html attribute. Default 1. */\n confidence?: number;\n /** Forced slot results: slot id → arm id (arms slots) or per-dim values (token slots). */\n slots?: Record<string, string | Record<string, string>>;\n weights?: Record<string, ScenarioWeight[]>;\n api?: Record<string, ScenarioApiOverride>;\n};\n\ntype ScenarioWindow = {\n __sentient_overrides?: Record<string, string>;\n __sentient_layout_override?: string[];\n __sentient_slot_overrides?: Record<string, string | Record<string, string>>;\n __sentient_persona_override?: { persona: string; confidence?: number };\n};\n\n/**\n * Confidence → band. Cutoffs pinned to @sentientui/policy `confidenceBand`\n * (<0.3 low, <0.7 medium, else high). Duplicated (not imported) because the\n * Playwright init function is serialized into the page and cannot close\n * over imports — both copies are pinned by tests.\n */\nexport function confidenceBandOf(c: number): 'low' | 'medium' | 'high' {\n return c < 0.3 ? 'low' : c < 0.7 ? 'medium' : 'high';\n}\n\n/** Apply a scenario by setting the client-forcing globals the SDK reads. */\nexport function applyScenario(scenario: SentientScenario = {}): void {\n const w = window as unknown as ScenarioWindow;\n w.__sentient_overrides = { ...(scenario.variants ?? {}) };\n if (scenario.layout) w.__sentient_layout_override = scenario.layout;\n else delete w.__sentient_layout_override;\n if (scenario.slots) w.__sentient_slot_overrides = { ...scenario.slots };\n else delete w.__sentient_slot_overrides;\n if (scenario.persona) {\n w.__sentient_persona_override = {\n persona: scenario.persona,\n confidence: scenario.confidence ?? 1,\n };\n try {\n const d = document.documentElement;\n d.setAttribute('data-sentient-persona', scenario.persona);\n d.setAttribute('data-sentient-confidence', confidenceBandOf(scenario.confidence ?? 1));\n } catch {\n /* no DOM (node env) — the override globals still apply */\n }\n } else {\n delete w.__sentient_persona_override;\n }\n}\n\n/** Clear all forced state. */\nexport function resetScenario(): void {\n const w = window as unknown as ScenarioWindow;\n delete w.__sentient_overrides;\n delete w.__sentient_layout_override;\n delete w.__sentient_slot_overrides;\n delete w.__sentient_persona_override;\n try {\n document.documentElement.removeAttribute('data-sentient-persona');\n document.documentElement.removeAttribute('data-sentient-confidence');\n } catch {\n /* no DOM */\n }\n}\n","import { recordEvent, type CapturedEvent } from './events.js';\nimport { confidenceBandOf, type SentientScenario, type ScenarioApiOverride } from './scenario.js';\n\n/** A framework-agnostic resolved response. `json` undefined ⇒ empty body. */\nexport type ResolvedResponse = { status: number; json?: unknown };\n\nfunction pathOf(url: string): string {\n try { return new URL(url).pathname; } catch { return url.split('?')[0] ?? url; }\n}\n\nasync function apiOverride(scenario: SentientScenario, route: string): Promise<ResolvedResponse | null> {\n const o: ScenarioApiOverride | undefined = scenario.api?.[route];\n if (o === undefined) return null;\n if (o === 'error') return { status: 500 };\n if (typeof o === 'number') return { status: o };\n if (o.delayMs) await new Promise((r) => setTimeout(r, o.delayMs));\n return { status: o.status ?? 200, json: o.body ?? {} };\n}\n\n/**\n * Resolve a request against a scenario. Returns a response, or null for routes\n * outside `/v1/*` (let the caller pass through). Shared by the MSW handlers and\n * the Playwright/Cypress adapters so behaviour can't drift.\n */\nexport async function resolveScenario(\n scenario: SentientScenario,\n _method: string,\n url: string,\n bodyText: string | null,\n): Promise<ResolvedResponse | null> {\n const path = pathOf(url);\n if (!path.includes('/v1/')) return null;\n\n const route = '/v1/' + (path.split('/v1/')[1] ?? '');\n const override = await apiOverride(scenario, route);\n if (override) return override;\n\n const body = bodyText ? (JSON.parse(bodyText) as unknown) : {};\n\n if (route === '/v1/sessions') return { status: 204 };\n\n if (route === '/v1/events') {\n for (const e of body as CapturedEvent[]) recordEvent(e);\n return { status: 204 };\n }\n\n if (route === '/v1/goals') {\n recordEvent({ eventType: 'goal', goalType: (body as { name?: string }).name });\n return { status: 204 };\n }\n\n if (route === '/v1/assign') {\n const b = body as { componentId: string; variantIds?: string[] };\n const variantId = scenario.variants?.[b.componentId] ?? b.variantIds?.[0] ?? 'control';\n return { status: 200, json: { variantId, assignmentTtlMs: 60_000 } };\n }\n\n if (route === '/v1/decide') {\n const b = body as {\n sections?: { id: string }[];\n slots?: Array<{\n id: string;\n arms?: string[];\n dims?: Record<string, string[]>;\n baseline?: string | Record<string, string>;\n }>;\n };\n const layoutOrder = scenario.layout ?? (b.sections ?? []).map((s) => s.id);\n const json: Record<string, unknown> = {\n layoutOrder,\n assignments: scenario.variants ?? {},\n persona: scenario.persona ?? 'unknown',\n confidence: scenario.confidence ?? 1,\n };\n // Mirror the real server: the slots key exists ONLY when slots were requested.\n if (b.slots && b.slots.length > 0) {\n const slots: Record<string, unknown> = {};\n for (const decl of b.slots) {\n slots[decl.id] = scenario.slots?.[decl.id] ?? defaultSlotResult(decl);\n }\n json.slots = slots;\n }\n return { status: 200, json };\n }\n\n if (route === '/v1/explain') {\n const b = body as {\n sections?: { id: string }[];\n persona?: string;\n slots?: Array<{\n id: string;\n arms?: string[];\n dims?: Record<string, string[]>;\n baseline?: string | Record<string, string>;\n }>;\n };\n const layoutOrder = scenario.layout ?? (b.sections ?? []).map((s) => s.id);\n const persona = b.persona ?? scenario.persona ?? 'unknown';\n const confidence = scenario.confidence ?? 1;\n const json: Record<string, unknown> = {\n layoutOrder,\n assignments: scenario.variants ?? {},\n persona,\n reasons: [],\n personaAttributes: { persona, confidence: confidenceBandOf(confidence) },\n };\n if (b.slots && b.slots.length > 0) {\n const slots: Record<string, unknown> = {};\n for (const decl of b.slots) {\n slots[decl.id] = scenario.slots?.[decl.id] ?? defaultSlotResult(decl);\n }\n json.slots = slots;\n }\n return { status: 200, json };\n }\n\n if (route === '/v1/weights') {\n const components = Object.entries(scenario.weights ?? {}).map(([componentId, variants]) => ({ componentId, updatedAt: 0, variants }));\n return { status: 200, json: { components } };\n }\n\n return null;\n}\n\n/** Declared baseline of a slot: explicit `baseline`, else first arm / first value per dim. */\nfunction defaultSlotResult(decl: {\n arms?: string[];\n dims?: Record<string, string[]>;\n baseline?: string | Record<string, string>;\n}): string | Record<string, string> {\n if (decl.arms) {\n return typeof decl.baseline === 'string' ? decl.baseline : decl.arms[0] ?? 'baseline';\n }\n const out: Record<string, string> = {};\n for (const [dim, values] of Object.entries(decl.dims ?? {})) {\n const declared =\n typeof decl.baseline === 'object' && decl.baseline !== null ? decl.baseline[dim] : undefined;\n out[dim] = declared ?? values[0] ?? '';\n }\n return out;\n}\n"],"mappings":"yaAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,yBAAAE,IAAA,eAAAC,EAAAH,ICAA,IAAAI,EAA8C,oBCA9C,IAAAC,EAAmC,eCQnC,IAAMC,EAA4B,CAAC,EAE5B,SAASC,EAAY,EAAwB,CAClDD,EAAS,KAAK,CAAC,CACjB,CCoBO,SAASE,EAAiBC,EAAsC,CACrE,OAAOA,EAAI,GAAM,MAAQA,EAAI,GAAM,SAAW,MAChD,CC5BA,SAASC,EAAOC,EAAqB,CANrC,IAAAC,EA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KAAOA,EAAK,SAASS,CAAG,EAAI,OACrFD,EAAIC,CAAG,GAAIzC,EAAA2C,GAAA,KAAAA,EAAYD,EAAO,CAAC,IAApB,KAAA1C,EAAyB,EACtC,CACA,OAAOwC,CACT,CHtIO,SAASI,EAAmBC,EAA6B,CAAC,EAAqB,CACpF,MAAO,CACL,OAAK,IAAI,SAAU,MAAO,CAAE,QAAAC,CAAQ,IAAM,CACxC,IAAMC,EACJD,EAAQ,SAAW,OAASA,EAAQ,SAAW,OAAS,KAAO,MAAMA,EAAQ,KAAK,EAC9E,EAAI,MAAME,EAAgBH,EAAUC,EAAQ,OAAQA,EAAQ,IAAKC,CAAQ,EAC/E,GAAK,EACL,OAAI,EAAE,OAAS,OAAkB,IAAI,eAAa,KAAM,CAAE,OAAQ,EAAE,MAAO,CAAC,EACrE,eAAa,KAAK,EAAE,KAAgB,CAAE,OAAQ,EAAE,MAAO,CAAC,CACjE,CAAC,CACH,CACF,CDRO,SAASE,GAGd,CACA,IAAMC,KAAS,eAAY,GAAGC,EAAmB,CAAC,EAClD,OAAAD,EAAO,OAAO,CAAE,mBAAoB,QAAS,CAAC,EACvC,CACL,OAAAA,EACA,IAAK,CAACE,EAA6B,CAAC,IAAMF,EAAO,IAAI,GAAGC,EAAmBC,CAAQ,CAAC,CACtF,CACF","names":["node_exports","__export","setupSentientServer","__toCommonJS","import_node","import_msw","captured","recordEvent","confidenceBandOf","c","pathOf","url","_a","e","apiOverride","scenario","route","_b","_c","o","r","resolveScenario","_method","bodyText","_d","_e","_f","_g","_h","_i","_j","_k","_l","_m","_n","_o","_p","_q","_r","_s","_t","_u","path","override","body","recordEvent","b","json","s","slots","decl","defaultSlotResult","layoutOrder","persona","confidence","confidenceBandOf","componentId","variants","out","dim","values","declared","scenarioToHandlers","scenario","request","bodyText","resolveScenario","setupSentientServer","server","scenarioToHandlers","scenario"]}
@@ -1,2 +1,2 @@
1
- import{setupServer as _}from"msw/node";import{http as P,HttpResponse as C}from"msw";var H=[];function c(t){H.push(t)}function A(t){var e;try{return new URL(t).pathname}catch(n){return(e=t.split("?")[0])!=null?e:t}}async function M(t,e){var r,i,s;let n=(r=t.api)==null?void 0:r[e];return n===void 0?null:n==="error"?{status:500}:typeof n=="number"?{status:n}:(n.delayMs&&await new Promise(d=>setTimeout(d,n.delayMs)),{status:(i=n.status)!=null?i:200,json:(s=n.body)!=null?s:{}})}async function I(t,e,n,r){var l,m,f,g,S,y,h,w,j,E,x,T,b,R,O;let i=A(n);if(!i.includes("/v1/"))return null;let s="/v1/"+((l=i.split("/v1/")[1])!=null?l:""),d=await M(t,s);if(d)return d;let a=r?JSON.parse(r):{};if(s==="/v1/sessions")return{status:204};if(s==="/v1/events"){for(let o of a)c(o);return{status:204}}if(s==="/v1/goals")return c({eventType:"goal",goalType:a.name}),{status:204};if(s==="/v1/assign"){let o=a;return{status:200,json:{variantId:(S=(g=(m=t.variants)==null?void 0:m[o.componentId])!=null?g:(f=o.variantIds)==null?void 0:f[0])!=null?S:"control",assignmentTtlMs:6e4}}}if(s==="/v1/decide"){let o=a;return{status:200,json:{layoutOrder:(h=t.layout)!=null?h:((y=o.sections)!=null?y:[]).map(p=>p.id),assignments:(w=t.variants)!=null?w:{},persona:(j=t.persona)!=null?j:"unknown",confidence:1}}}if(s==="/v1/explain"){let o=a,u=(x=t.layout)!=null?x:((E=o.sections)!=null?E:[]).map(k=>k.id),p=(b=(T=o.persona)!=null?T:t.persona)!=null?b:"unknown";return{status:200,json:{layoutOrder:u,assignments:(R=t.variants)!=null?R:{},persona:p,reasons:[]}}}return s==="/v1/weights"?{status:200,json:{components:Object.entries((O=t.weights)!=null?O:{}).map(([u,p])=>({componentId:u,updatedAt:0,variants:p}))}}:null}function v(t={}){return[P.all("*/v1/*",async({request:e})=>{let n=e.method==="GET"||e.method==="HEAD"?null:await e.text(),r=await I(t,e.method,e.url,n);if(r)return r.json===void 0?new C(null,{status:r.status}):C.json(r.json,{status:r.status})})]}function G(){let t=_(...v());return t.listen({onUnhandledRequest:"bypass"}),{server:t,use:(e={})=>t.use(...v(e))}}export{G as setupSentientServer};
1
+ import{setupServer as K}from"msw/node";import{http as z,HttpResponse as F}from"msw";var J=[];function f(e){J.push(e)}function G(e){return e<.3?"low":e<.7?"medium":"high"}function L(e){var t;try{return new URL(e).pathname}catch(n){return(t=e.split("?")[0])!=null?t:e}}async function N(e,t){var s,a,o;let n=(s=e.api)==null?void 0:s[t];return n===void 0?null:n==="error"?{status:500}:typeof n=="number"?{status:n}:(n.delayMs&&await new Promise(u=>setTimeout(u,n.delayMs)),{status:(a=n.status)!=null?a:200,json:(o=n.body)!=null?o:{}})}async function D(e,t,n,s){var _,y,S,b,w,R,h,x,E,j,O,k,A,T,I,C,H,W,M,P,B;let a=L(n);if(!a.includes("/v1/"))return null;let o="/v1/"+((_=a.split("/v1/")[1])!=null?_:""),u=await N(e,o);if(u)return u;let i=s?JSON.parse(s):{};if(o==="/v1/sessions")return{status:204};if(o==="/v1/events"){for(let r of i)f(r);return{status:204}}if(o==="/v1/goals")return f({eventType:"goal",goalType:i.name}),{status:204};if(o==="/v1/assign"){let r=i;return{status:200,json:{variantId:(w=(b=(y=e.variants)==null?void 0:y[r.componentId])!=null?b:(S=r.variantIds)==null?void 0:S[0])!=null?w:"control",assignmentTtlMs:6e4}}}if(o==="/v1/decide"){let r=i,d={layoutOrder:(h=e.layout)!=null?h:((R=r.sections)!=null?R:[]).map(c=>c.id),assignments:(x=e.variants)!=null?x:{},persona:(E=e.persona)!=null?E:"unknown",confidence:(j=e.confidence)!=null?j:1};if(r.slots&&r.slots.length>0){let c={};for(let p of r.slots)c[p.id]=(k=(O=e.slots)==null?void 0:O[p.id])!=null?k:U(p);d.slots=c}return{status:200,json:d}}if(o==="/v1/explain"){let r=i,l=(T=e.layout)!=null?T:((A=r.sections)!=null?A:[]).map(g=>g.id),d=(C=(I=r.persona)!=null?I:e.persona)!=null?C:"unknown",c=(H=e.confidence)!=null?H:1,p={layoutOrder:l,assignments:(W=e.variants)!=null?W:{},persona:d,reasons:[],personaAttributes:{persona:d,confidence:G(c)}};if(r.slots&&r.slots.length>0){let g={};for(let v of r.slots)g[v.id]=(P=(M=e.slots)==null?void 0:M[v.id])!=null?P:U(v);p.slots=g}return{status:200,json:p}}return o==="/v1/weights"?{status:200,json:{components:Object.entries((B=e.weights)!=null?B:{}).map(([l,d])=>({componentId:l,updatedAt:0,variants:d}))}}:null}function U(e){var n,s,a;if(e.arms)return typeof e.baseline=="string"?e.baseline:(n=e.arms[0])!=null?n:"baseline";let t={};for(let[o,u]of Object.entries((s=e.dims)!=null?s:{})){let i=typeof e.baseline=="object"&&e.baseline!==null?e.baseline[o]:void 0;t[o]=(a=i!=null?i:u[0])!=null?a:""}return t}function m(e={}){return[z.all("*/v1/*",async({request:t})=>{let n=t.method==="GET"||t.method==="HEAD"?null:await t.text(),s=await D(e,t.method,t.url,n);if(s)return s.json===void 0?new F(null,{status:s.status}):F.json(s.json,{status:s.status})})]}function Q(){let e=K(...m());return e.listen({onUnhandledRequest:"bypass"}),{server:e,use:(t={})=>e.use(...m(t))}}export{Q as setupSentientServer};
2
2
  //# sourceMappingURL=node.mjs.map