@sentientui/react 0.24.4 → 0.24.5

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,4 +1,4 @@
1
- var pe=Object.defineProperty,le=Object.defineProperties;var ue=Object.getOwnPropertyDescriptors;var O=Object.getOwnPropertySymbols;var G=Object.prototype.hasOwnProperty,z=Object.prototype.propertyIsEnumerable;var q=(e,t,n)=>t in e?pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,y=(e,t)=>{for(var n in t||(t={}))G.call(t,n)&&q(e,n,t[n]);if(O)for(var n of O(t))z.call(t,n)&&q(e,n,t[n]);return e},S=(e,t)=>le(e,ue(t));var Y=(e,t)=>{var n={};for(var s in e)G.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&O)for(var s of O(e))t.indexOf(s)<0&&z.call(e,s)&&(n[s]=e[s]);return n};import{deriveSessionSegment as xe,matchedAgentToken as Oe}from"@sentientui/core";import{cookies as Pe,headers as Le}from"next/headers";import{renderPrePaintScript as me}from"@sentientui/core";import{confidenceBand as fe}from"@sentientui/policy";import{jsx as ye}from"react/jsx-runtime";function Q(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function Ae(e){return e.persona?'(function(){try{var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+Q(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+Q(fe(e.persona.confidence))+");}catch(e){}})();":me(e.apiKey)}function Z(e){return ye("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:Ae(e)}})}import{preloadAssignments as he,readSessionCookie as ve}from"@sentientui/core/server";import{preloadDecisions as je}from"@sentientui/core/server";function ee(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function te(e,t){var r,i,a;let n=(a=(i=ve(t.cookies))!=null?i:(r=t.createSessionId)==null?void 0:r.call(t))!=null?a:ee();return{assignments:await he(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,origin:t.origin,userAgent:t.userAgent,referer:t.referer,doNotTrack:t.doNotTrack,timeoutMs:t.timeoutMs,persona:t.persona}),sessionId:n}}async function ne(e){var a,c,p,I,k,w,o,l,u,h;let{preloadDecisions:t,readSessionCookie:n}=await import("@sentientui/core/server"),s=(p=(c=n(e.cookies))!=null?c:(a=e.createSessionId)==null?void 0:a.call(e))!=null?p:ee();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let d={layoutOrder:(I=e.sections)!=null?I:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:s};try{let m=await import("@sentientui/core/local");if(!m.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."),d;let f=m.createLocalEngine({sessionId:s}).decide({sections:e.sections,components:(k=e.components)!=null?k:[],slots:(w=e.slots)!=null?w:[]});return{layoutOrder:(l=(o=f.layoutOrder)!=null?o:e.sections)!=null?l:[],assignments:f.assignments,slots:f.slots,persona:f.persona,confidence:f.confidence,sessionId:s}}catch(m){return d}}let i=await t({sections:e.sections,components:(u=e.components)!=null?u:[],slots:(h=e.slots)!=null?h:[]},s,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona});return S(y({},i),{sessionId:s})}import{AdaptiveRootClient as Fe}from"./adaptive-root-client.js";var Se=["page","blocks","layoutOrder"],se=new Map;function ke(e,t){se.set(e,t)}function be(e){return se.get(e)}function E(e){var r,i;let t=(i=(r=e.content)!=null?r:be(e.page))!=null?i:{},n={};for(let[a,c]of Object.entries(t))Se.includes(a)||(n[a]=c);let s=S(y({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(s.layoutOrder=e.layoutOrder),s}function re(e){return JSON.stringify(y({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function oe(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,s]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(s,null,2),"```","");if(e.blocks.length>0){t.push("## blocks","");for(let n of e.blocks)t.push(`- **${n.id}** \u2192 variant \`${n.variant}\``),n.content!==void 0&&t.push(""," ```json",JSON.stringify(n.content,null,2)," ```");t.push("")}return t.join(`
1
+ var pe=Object.defineProperty,le=Object.defineProperties;var ue=Object.getOwnPropertyDescriptors;var O=Object.getOwnPropertySymbols;var G=Object.prototype.hasOwnProperty,z=Object.prototype.propertyIsEnumerable;var q=(e,t,n)=>t in e?pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,y=(e,t)=>{for(var n in t||(t={}))G.call(t,n)&&q(e,n,t[n]);if(O)for(var n of O(t))z.call(t,n)&&q(e,n,t[n]);return e},S=(e,t)=>le(e,ue(t));var Y=(e,t)=>{var n={};for(var s in e)G.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&O)for(var s of O(e))t.indexOf(s)<0&&z.call(e,s)&&(n[s]=e[s]);return n};import{deriveSessionSegment as xe,matchedAgentToken as Oe}from"@sentientui/core";import{cookies as Pe,headers as Le}from"next/headers";import{renderPrePaintScript as me}from"@sentientui/core";import{confidenceBand as fe}from"@sentientui/policy";import{jsx as ye}from"react/jsx-runtime";function Q(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function Ae(e){return e.persona?'(function(){try{var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+Q(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+Q(fe(e.persona.confidence))+");}catch(e){}})();":me(e.apiKey)}function Z(e){return ye("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:Ae(e)}})}import{preloadAssignments as he,readSessionCookie as ve}from"@sentientui/core/server";import{preloadDecisions as je}from"@sentientui/core/server";function ee(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function te(e,t){var r,i,a;let n=(a=(i=ve(t.cookies,t.apiKey))!=null?i:(r=t.createSessionId)==null?void 0:r.call(t))!=null?a:ee();return{assignments:await he(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,origin:t.origin,userAgent:t.userAgent,referer:t.referer,doNotTrack:t.doNotTrack,timeoutMs:t.timeoutMs,persona:t.persona}),sessionId:n}}async function ne(e){var a,c,p,I,k,w,o,l,u,h;let{preloadDecisions:t,readSessionCookie:n}=await import("@sentientui/core/server"),s=(p=(c=n(e.cookies,e.apiKey))!=null?c:(a=e.createSessionId)==null?void 0:a.call(e))!=null?p:ee();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let d={layoutOrder:(I=e.sections)!=null?I:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:s};try{let m=await import("@sentientui/core/local");if(!m.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."),d;let f=m.createLocalEngine({sessionId:s}).decide({sections:e.sections,components:(k=e.components)!=null?k:[],slots:(w=e.slots)!=null?w:[]});return{layoutOrder:(l=(o=f.layoutOrder)!=null?o:e.sections)!=null?l:[],assignments:f.assignments,slots:f.slots,persona:f.persona,confidence:f.confidence,sessionId:s}}catch(m){return d}}let i=await t({sections:e.sections,components:(u=e.components)!=null?u:[],slots:(h=e.slots)!=null?h:[]},s,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona});return S(y({},i),{sessionId:s})}import{AdaptiveRootClient as Fe}from"./adaptive-root-client.js";var Se=["page","blocks","layoutOrder"],se=new Map;function ke(e,t){se.set(e,t)}function be(e){return se.get(e)}function E(e){var r,i;let t=(i=(r=e.content)!=null?r:be(e.page))!=null?i:{},n={};for(let[a,c]of Object.entries(t))Se.includes(a)||(n[a]=c);let s=S(y({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(s.layoutOrder=e.layoutOrder),s}function re(e){return JSON.stringify(y({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function oe(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,s]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(s,null,2),"```","");if(e.blocks.length>0){t.push("## blocks","");for(let n of e.blocks)t.push(`- **${n.id}** \u2192 variant \`${n.variant}\``),n.content!==void 0&&t.push(""," ```json",JSON.stringify(n.content,null,2)," ```");t.push("")}return t.join(`
2
2
  `).trimEnd()+`
3
3
  `}function ie(e,t={}){var s,r;let n=(s=t.fetchImpl)!=null?s:fetch;try{n(`${e.baseUrl}/crawler-events`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({path:e.path,botName:e.botName,userAgent:(r=e.userAgent)!=null?r:null,source:"ssr"})}).catch(()=>{})}catch(i){}}import{matchedAgentToken as Re}from"@sentientui/core";function Ie(e,t){return e.pathname.endsWith(".md")||t.toLowerCase().includes("text/markdown")}function we(e){return async t=>{var c;let n=new URL(t.url),s=(c=t.headers.get("accept"))!=null?c:"",r=t.headers.get("user-agent"),i=n.pathname.replace(/\.(md|json)$/,"");if(e.onRead)try{Promise.resolve(e.onRead({path:i,userAgent:r,botName:Re(r!=null?r:"")})).catch(()=>{})}catch(p){}let a=await e.getFeed(t);return Ie(n,s)?new Response(oe(a),{headers:{"content-type":"text/markdown; charset=utf-8"}}):new Response(JSON.stringify(a),{headers:{"content-type":"application/json; charset=utf-8"}})}}import{matchedAgentToken as at,uaTokenMatch as ct,agentIntent as dt,classifiedAgents as gt}from"@sentientui/core";import{Fragment as ae,jsx as D,jsxs as ce}from"react/jsx-runtime";var Ne="https://api.sentient-ui.com/v1";function Ee(e){return Object.entries(e).map(([t,n])=>{var s;return{id:t,variant:typeof n=="string"?n:(s=n==null?void 0:n.variantId)!=null?s:""}})}async function nt(e){var M,j,J,$,V,H,W,X;let B=e,{components:t=[],sections:n,slots:s,appOrigin:r,initialAssignments:i,ssrSessionId:a,timeoutMs:c,agentFeed:p,captureAgents:I,nonce:k,children:w}=B,o=Y(B,["components","sections","slots","appOrigin","initialAssignments","ssrSessionId","timeoutMs","agentFeed","captureAgents","nonce","children"]),l=await Le(),u=l.get("host");!r&&process.env.NODE_ENV==="production"&&!u&&console.error("[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. Pass appOrigin explicitly \u2014 the https://localhost fallback will likely fail allowed_origins validation.");let h=r!=null?r:process.env.NODE_ENV==="production"?`https://${u!=null?u:"localhost"}`:"http://localhost:3001",d=(M=l.get("user-agent"))!=null?M:void 0,m=(j=l.get("referer"))!=null?j:void 0,f=l.get("dnt")==="1"||l.get("sec-gpc")==="1",de=xe({userAgent:d,referer:m,appOrigin:h}),P=await Pe(),A=o.consentFrom,L=(V=o.consent)!=null?V:A!=null&&A.cookie&&!A.check?((J=P.get(A.cookie))==null?void 0:J.value)===(($=A.value)!=null?$:"accepted"):void 0,F=f||L===!1||A!=null&&L!==!0,N=o.apiBaseUrl?o.apiBaseUrl.replace(/\/$/,""):Ne,K=(W=(H=p==null?void 0:p.path)!=null?H:l.get("x-pathname"))!=null?W:"/",T=Oe(d!=null?d:"");I!==!1&&T&&ie({baseUrl:N,apiKey:o.apiKey,path:K,botName:T,userAgent:d});let v,b=null,U,R=null,x;if(i)v=i,x=a;else if(F)v={};else if(n&&n.length>0||s&&s.length>0){let g=await ne({sections:n!=null?n:[],components:t,slots:s,cookies:P,apiKey:o.apiKey,baseUrl:N,origin:h,userAgent:d,referer:m,doNotTrack:F,timeoutMs:c,persona:o.persona});v=g.assignments,b=g.layoutOrder,U=g.slots,R=g.persona!==void 0?{persona:g.persona,confidence:(X=g.confidence)!=null?X:0}:null,x=g.sessionId}else{let g=await te(t,{cookies:P,apiKey:o.apiKey,baseUrl:N,origin:h,userAgent:d,referer:m,doNotTrack:F,timeoutMs:c,persona:o.persona});v=g.assignments,x=g.sessionId}let _=D(Z,{apiKey:o.apiKey,persona:R,nonce:k}),C=D(Fe,S(y({},o),{consent:L,initialAssignments:v,initialLayoutOrder:b,declaredSections:n,initialSlots:U,initialPersona:R!=null?R:void 0,sessionSegment:de,ssrSessionId:x,children:w}));if(!p)return ce(ae,{children:[_,C]});let ge=E({page:K,blocks:Ee(v),layoutOrder:b!=null?b:void 0,content:p.content});return ce(ae,{children:[_,D("script",{type:"application/ld+json",nonce:k,dangerouslySetInnerHTML:{__html:re(ge)}}),C]})}export{nt as AdaptiveRoot,dt as agentIntent,E as buildAgentFeedFor,gt as classifiedAgents,we as createAgentFeed,ke as defineAgentContent,at as matchedAgentToken,ct as uaTokenMatch};
4
4
  //# sourceMappingURL=adaptive-root.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/next/adaptive-root.tsx","../../src/persona-script.tsx","../../src/server.ts","../../src/agent-feed.ts","../../src/next/log-agent-fetch.ts","../../src/next/agent-feed-route.ts"],"sourcesContent":["import { deriveSessionSegment, matchedAgentToken } 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';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\n// Re-exported from core on the SERVER entry (this module is server-only — it\n// imports next/headers). Lets server components do agent detection with just the\n// `@sentientui/react` package, no direct core dependency. Do NOT add this to the\n// package's client index: re-exporting a plain function through a 'use client'\n// module turns it into a client reference that throws when called during SSR.\nexport { matchedAgentToken, uaTokenMatch, agentIntent, classifiedAgents } from '@sentientui/core';\nexport type { AgentIntent } from '@sentientui/core';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\nexport type AdaptiveRootProps = Omit<\n AdaptiveProviderProps,\n 'initialAssignments' | 'onAssignment' | 'initialSlots' | 'initialPersona'\n> & {\n /**\n * Components to assign server-side (SEO-safe). Optional — omit when the\n * tree uses only slots/sections, or assigns client-side via hooks.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * @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 /**\n * When true (default), a known AI-agent fetch (matched by user-agent —\n * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side\n * to your agent analytics. Machine telemetry only (no cookie, no session);\n * fire-and-forget, never affects render. Set false to opt out.\n */\n captureAgents?: boolean;\n /**\n * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.\n * Pass through from Next.js middleware / `headers()` when using a strict CSP.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * 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 captureAgents,\n nonce,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `consent: false` must gate the SERVER too, not just the client. Without\n // this the SSR decide/assign still ran and still minted a session row for a\n // visitor who had not consented — contradicting the documented contract\n // (\"no SDK is initialised, no cookies are written, no events are sent\") and\n // forcing sites to hide AdaptiveRoot behind a conditional render, which is\n // what made consent-after-load cost a full server round trip.\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n // This is a Server Component and already has the request cookies, so resolve\n // a cookie-based `consentFrom` here rather than making the app read the same\n // cookie again just to pass `consent` — naming it twice only invites drift.\n // An already-consented visitor therefore gets SSR variant assignment (zero\n // layout shift) with no extra code.\n //\n // A `check()` source runs in the browser and cannot be evaluated here, so it\n // stays gated until the client resolves it. An explicit `consent` prop always\n // wins — it is the escape hatch for apps that track consent elsewhere.\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n const consent =\n providerProps.consent ??\n (cf?.cookie && !cf.check\n ? cookieStore.get(cf.cookie)?.value === (cf.value ?? 'accepted')\n : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n\n // SSR preload MUST hit the same API host the client will use, otherwise the\n // SSR-minted session lives on the wrong host and the client's first /assign\n // misses it and re-mints — silently breaking SSR→client continuity for any\n // non-default / self-hosted deployment. The client derives its base from\n // apiBaseUrl too (see provider.tsx), so thread the same value here.\n const baseUrl = providerProps.apiBaseUrl\n ? providerProps.apiBaseUrl.replace(/\\/$/, '')\n : DEFAULT_API_BASE_URL;\n\n // Server-side agent-fetch capture (spec: nextjs-agent-fetch-capture). JS-less\n // assistants (GPTBot / ChatGPT-User / Claude-User / PerplexityBot / …) never\n // run client JS, but they trigger SSR — so AdaptiveRoot sees their UA here.\n // Fire-and-forget; never blocks or breaks render. `agentPath` is reused by the\n // agentFeed JSON-LD below.\n const agentPath = agentFeed?.path ?? headerStore.get('x-pathname') ?? '/';\n const agentBot = matchedAgentToken(userAgent ?? '');\n if (captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let 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 (skipSsr) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0)) {\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n doNotTrack: skipSsr,\n timeoutMs,\n persona: providerProps.persona,\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,\n origin: resolvedOrigin,\n userAgent,\n referer,\n doNotTrack: skipSsr,\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n const personaScript = (\n <SentientPersonaScript apiKey={providerProps.apiKey} persona={initialPersona} nonce={nonce} />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // Forward the server-resolved value so a consented visitor's client does\n // not start gated and re-resolve the same cookie on mount.\n consent={consent}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n // Declared regardless of what came back, so devtools can preview layout on\n // a page whose decision was gated or timed out.\n declaredSections={sections}\n initialSlots={initialSlots}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) {\n return (\n <>\n {personaScript}\n {client}\n </>\n );\n }\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const feed = buildAgentFeed({\n page: agentPath,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","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 * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n};\n\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 nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n 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 doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n};\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 doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"qlBAAA,OAAS,wBAAAA,GAAsB,qBAAAC,OAAyB,mBAExD,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCFjC,OAAS,wBAAAC,OAA4B,mBACrC,OAAS,kBAAAC,OAAsB,qBAoD3B,cAAAC,OAAA,oBAhCJ,SAASC,EAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAAK,EAAE,QAAQ,KAAM,SAAS,CACtD,CAGO,SAASC,GAAkBC,EAA2C,CAC3E,OAAIA,EAAM,QAEN,2IAE4CH,EAAeG,EAAM,QAAQ,OAAO,EAAI,+CACrCH,EAAeF,GAAeK,EAAM,QAAQ,UAAU,CAAC,EAAI,qBAIvGN,GAAqBM,EAAM,MAAM,CAC1C,CAcO,SAASC,EAAsBD,EAAgD,CACpF,OACEJ,GAAC,UACC,+BAA6B,GAC7B,MAAOI,EAAM,MACb,wBAAyB,CAAE,OAAQD,GAAkBC,CAAK,CAAE,EAC9D,CAEJ,CCxDA,OACE,sBAAAE,GACA,qBAAAC,OAGK,0BAyEP,OAAS,oBAAAC,OAAwB,0BAnCjC,SAASC,IAA2B,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,GACpBC,EAC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CAAE,QAASA,EAAS,QAAS,YAAYtC,EAAAsC,EAAS,aAAT,KAAAtC,EAAuB,CAAE,EAClE,KACNqC,EAAeC,EAAS,SAC1B,KAAO,CACL,IAAME,EAAS,MAAMC,GAAwBxC,EAAY,CACvD,QAASsB,EACT,OAAQX,EAAc,OACtB,QAAAgB,EACA,OAAQX,EACR,UAAAC,EACA,QAAAC,EACA,WAAYQ,EACZ,UAAApB,EACA,QAASK,EAAc,OACzB,CAAC,EACDqB,EAAqBO,EAAO,YAC5BH,EAAeG,EAAO,SACxB,CAIA,IAAME,EACJ3D,EAAC4D,EAAA,CAAsB,OAAQ/B,EAAc,OAAQ,QAASwB,EAAgB,MAAO1B,EAAO,EAGxFkC,EACJ7D,EAAC8D,GAAAC,EAAAC,EAAA,GACKnC,GADL,CAIC,QAASc,EACT,mBAAoBO,EACpB,mBAAoBC,EAGpB,iBAAkBhC,EAClB,aAAciC,EACd,eAAgBC,GAAA,KAAAA,EAAkB,OAClC,eAAgBf,GAChB,aAAcgB,EAEb,SAAA1B,GACH,EAGF,GAAI,CAACH,EACH,OACExB,GAAAF,GAAA,CACG,UAAA4D,EACAE,GACH,EAOJ,IAAMI,GAAOC,EAAe,CAC1B,KAAMpB,EACN,OAAQ3C,GAAoB+C,CAAkB,EAC9C,YAAaC,GAAA,KAAAA,EAAsB,OACnC,QAAS1B,EAAU,OACrB,CAAC,EAED,OACExB,GAAAF,GAAA,CACG,UAAA4D,EACD3D,EAAC,UACC,KAAK,sBACL,MAAO2B,EACP,wBAAyB,CAAE,OAAQwC,GAAsBF,EAAI,CAAE,EACjE,EACCJ,GACH,CAEJ","names":["deriveSessionSegment","matchedAgentToken","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","_i","components","sections","slots","appOrigin","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","skipSsr","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialLayoutOrder","initialSlots","initialPersona","ssrSessionId","decision","loadAdaptiveDecision","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","__spreadProps","__spreadValues","feed","buildAgentFeed","renderAgentJsonLdBody"]}
1
+ {"version":3,"sources":["../../src/next/adaptive-root.tsx","../../src/persona-script.tsx","../../src/server.ts","../../src/agent-feed.ts","../../src/next/log-agent-fetch.ts","../../src/next/agent-feed-route.ts"],"sourcesContent":["import { deriveSessionSegment, matchedAgentToken } 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';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\n// Re-exported from core on the SERVER entry (this module is server-only — it\n// imports next/headers). Lets server components do agent detection with just the\n// `@sentientui/react` package, no direct core dependency. Do NOT add this to the\n// package's client index: re-exporting a plain function through a 'use client'\n// module turns it into a client reference that throws when called during SSR.\nexport { matchedAgentToken, uaTokenMatch, agentIntent, classifiedAgents } from '@sentientui/core';\nexport type { AgentIntent } from '@sentientui/core';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\nexport type AdaptiveRootProps = Omit<\n AdaptiveProviderProps,\n 'initialAssignments' | 'onAssignment' | 'initialSlots' | 'initialPersona'\n> & {\n /**\n * Components to assign server-side (SEO-safe). Optional — omit when the\n * tree uses only slots/sections, or assigns client-side via hooks.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * @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 /**\n * When true (default), a known AI-agent fetch (matched by user-agent —\n * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side\n * to your agent analytics. Machine telemetry only (no cookie, no session);\n * fire-and-forget, never affects render. Set false to opt out.\n */\n captureAgents?: boolean;\n /**\n * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.\n * Pass through from Next.js middleware / `headers()` when using a strict CSP.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * 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 captureAgents,\n nonce,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `consent: false` must gate the SERVER too, not just the client. Without\n // this the SSR decide/assign still ran and still minted a session row for a\n // visitor who had not consented — contradicting the documented contract\n // (\"no SDK is initialised, no cookies are written, no events are sent\") and\n // forcing sites to hide AdaptiveRoot behind a conditional render, which is\n // what made consent-after-load cost a full server round trip.\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n // This is a Server Component and already has the request cookies, so resolve\n // a cookie-based `consentFrom` here rather than making the app read the same\n // cookie again just to pass `consent` — naming it twice only invites drift.\n // An already-consented visitor therefore gets SSR variant assignment (zero\n // layout shift) with no extra code.\n //\n // A `check()` source runs in the browser and cannot be evaluated here, so it\n // stays gated until the client resolves it. An explicit `consent` prop always\n // wins — it is the escape hatch for apps that track consent elsewhere.\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n const consent =\n providerProps.consent ??\n (cf?.cookie && !cf.check\n ? cookieStore.get(cf.cookie)?.value === (cf.value ?? 'accepted')\n : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n\n // SSR preload MUST hit the same API host the client will use, otherwise the\n // SSR-minted session lives on the wrong host and the client's first /assign\n // misses it and re-mints — silently breaking SSR→client continuity for any\n // non-default / self-hosted deployment. The client derives its base from\n // apiBaseUrl too (see provider.tsx), so thread the same value here.\n const baseUrl = providerProps.apiBaseUrl\n ? providerProps.apiBaseUrl.replace(/\\/$/, '')\n : DEFAULT_API_BASE_URL;\n\n // Server-side agent-fetch capture (spec: nextjs-agent-fetch-capture). JS-less\n // assistants (GPTBot / ChatGPT-User / Claude-User / PerplexityBot / …) never\n // run client JS, but they trigger SSR — so AdaptiveRoot sees their UA here.\n // Fire-and-forget; never blocks or breaks render. `agentPath` is reused by the\n // agentFeed JSON-LD below.\n const agentPath = agentFeed?.path ?? headerStore.get('x-pathname') ?? '/';\n const agentBot = matchedAgentToken(userAgent ?? '');\n if (captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let 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 (skipSsr) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0)) {\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n doNotTrack: skipSsr,\n timeoutMs,\n persona: providerProps.persona,\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,\n origin: resolvedOrigin,\n userAgent,\n referer,\n doNotTrack: skipSsr,\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n const personaScript = (\n <SentientPersonaScript apiKey={providerProps.apiKey} persona={initialPersona} nonce={nonce} />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // Forward the server-resolved value so a consented visitor's client does\n // not start gated and re-resolve the same cookie on mount.\n consent={consent}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n // Declared regardless of what came back, so devtools can preview layout on\n // a page whose decision was gated or timed out.\n declaredSections={sections}\n initialSlots={initialSlots}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) {\n return (\n <>\n {personaScript}\n {client}\n </>\n );\n }\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const feed = buildAgentFeed({\n page: agentPath,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","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 * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n};\n\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 nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"qlBAAA,OAAS,wBAAAA,GAAsB,qBAAAC,OAAyB,mBAExD,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCFjC,OAAS,wBAAAC,OAA4B,mBACrC,OAAS,kBAAAC,OAAsB,qBAoD3B,cAAAC,OAAA,oBAhCJ,SAASC,EAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAAK,EAAE,QAAQ,KAAM,SAAS,CACtD,CAGO,SAASC,GAAkBC,EAA2C,CAC3E,OAAIA,EAAM,QAEN,2IAE4CH,EAAeG,EAAM,QAAQ,OAAO,EAAI,+CACrCH,EAAeF,GAAeK,EAAM,QAAQ,UAAU,CAAC,EAAI,qBAIvGN,GAAqBM,EAAM,MAAM,CAC1C,CAcO,SAASC,EAAsBD,EAAgD,CACpF,OACEJ,GAAC,UACC,+BAA6B,GAC7B,MAAOI,EAAM,MACb,wBAAyB,CAAE,OAAQD,GA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UAAA4D,EACD3D,EAAC,UACC,KAAK,sBACL,MAAO2B,EACP,wBAAyB,CAAE,OAAQwC,GAAsBF,EAAI,CAAE,EACjE,EACCJ,GACH,CAEJ","names":["deriveSessionSegment","matchedAgentToken","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","_i","components","sections","slots","appOrigin","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","skipSsr","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialLayoutOrder","initialSlots","initialPersona","ssrSessionId","decision","loadAdaptiveDecision","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","__spreadProps","__spreadValues","feed","buildAgentFeed","renderAgentJsonLdBody"]}
package/dist/server.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var U=Object.create;var c=Object.defineProperty,_=Object.defineProperties,K=Object.getOwnPropertyDescriptor,T=Object.getOwnPropertyDescriptors,w=Object.getOwnPropertyNames,k=Object.getOwnPropertySymbols,C=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty,M=Object.prototype.propertyIsEnumerable;var S=(e,s,t)=>s in e?c(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t,N=(e,s)=>{for(var t in s||(s={}))D.call(s,t)&&S(e,t,s[t]);if(k)for(var t of k(s))M.call(s,t)&&S(e,t,s[t]);return e},E=(e,s)=>_(e,T(s));var P=(e,s)=>{for(var t in s)c(e,t,{get:s[t],enumerable:!0})},O=(e,s,t,n)=>{if(s&&typeof s=="object"||typeof s=="function")for(let r of w(s))!D.call(e,r)&&r!==t&&c(e,r,{get:()=>s[r],enumerable:!(n=K(s,r))||n.enumerable});return e};var b=(e,s,t)=>(t=e!=null?U(C(e)):{},O(s||!e||!e.__esModule?c(t,"default",{value:e,enumerable:!0}):t,e)),h=e=>O(c({},"__esModule",{value:!0}),e);var G={};P(G,{loadAdaptiveAssignments:()=>V,loadAdaptiveDecision:()=>B,preloadAssignments:()=>i.preloadAssignments,preloadDecisions:()=>x.preloadDecisions,readSessionCookie:()=>i.readSessionCookie});module.exports=h(G);var i=require("@sentientui/core/server"),x=require("@sentientui/core/server");function R(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function V(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:R();return{assignments:await(0,i.preloadAssignments)(e,t,{apiKey:s.apiKey,baseUrl:s.baseUrl,origin:s.origin,userAgent:s.userAgent,referer:s.referer,doNotTrack:s.doNotTrack,timeoutMs:s.timeoutMs,persona:s.persona}),sessionId:t}}async function B(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:R();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,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona});return E(N({},d),{sessionId:n})}0&&(module.exports={loadAdaptiveAssignments,loadAdaptiveDecision,preloadAssignments,preloadDecisions,readSessionCookie});
1
+ "use strict";var K=Object.create;var c=Object.defineProperty,U=Object.defineProperties,_=Object.getOwnPropertyDescriptor,T=Object.getOwnPropertyDescriptors,w=Object.getOwnPropertyNames,k=Object.getOwnPropertySymbols,C=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty,M=Object.prototype.propertyIsEnumerable;var S=(e,s,t)=>s in e?c(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t,N=(e,s)=>{for(var t in s||(s={}))D.call(s,t)&&S(e,t,s[t]);if(k)for(var t of k(s))M.call(s,t)&&S(e,t,s[t]);return e},E=(e,s)=>U(e,T(s));var P=(e,s)=>{for(var t in s)c(e,t,{get:s[t],enumerable:!0})},O=(e,s,t,r)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of w(s))!D.call(e,n)&&n!==t&&c(e,n,{get:()=>s[n],enumerable:!(r=_(s,n))||r.enumerable});return e};var b=(e,s,t)=>(t=e!=null?K(C(e)):{},O(s||!e||!e.__esModule?c(t,"default",{value:e,enumerable:!0}):t,e)),h=e=>O(c({},"__esModule",{value:!0}),e);var G={};P(G,{loadAdaptiveAssignments:()=>V,loadAdaptiveDecision:()=>B,preloadAssignments:()=>i.preloadAssignments,preloadDecisions:()=>x.preloadDecisions,readSessionCookie:()=>i.readSessionCookie});module.exports=h(G);var i=require("@sentientui/core/server"),x=require("@sentientui/core/server");function R(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function V(e,s){var n,d,o;let t=(o=(d=(0,i.readSessionCookie)(s.cookies,s.apiKey))!=null?d:(n=s.createSessionId)==null?void 0:n.call(s))!=null?o:R();return{assignments:await(0,i.preloadAssignments)(e,t,{apiKey:s.apiKey,baseUrl:s.baseUrl,origin:s.origin,userAgent:s.userAgent,referer:s.referer,doNotTrack:s.doNotTrack,timeoutMs:s.timeoutMs,persona:s.persona}),sessionId:t}}async function B(e){var o,l,u,m,p,A,y,f,v,I;let{preloadDecisions:s,readSessionCookie:t}=await import("@sentientui/core/server"),r=(u=(l=t(e.cookies,e.apiKey))!=null?l:(o=e.createSessionId)==null?void 0:o.call(e))!=null?u:R();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let L={layoutOrder:(m=e.sections)!=null?m:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:r};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:r}).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:r}}catch(g){return L}}let d=await s({sections:e.sections,components:(v=e.components)!=null?v:[],slots:(I=e.slots)!=null?I:[]},r,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona});return E(N({},d),{sessionId:r})}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 /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n 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 doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n};\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 doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\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,mCAyEPA,EAAiC,mCAnCjC,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,CA7D1C,IAAAC,EAAAC,EAAAC,EA8DE,IAAMC,GACJD,GAAAD,KAAA,qBAAkBF,EAAQ,OAAO,IAAjC,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,EAAiB,EAanB,MAAO,CAAE,YAXW,QAAM,sBAAmBE,EAAYK,EAAW,CAClE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,WAAYA,EAAQ,WACpB,UAA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,SAClB,YAAYW,EAAAX,EAAQ,aAAR,KAAAW,EAAsB,CAAC,EACnC,OAAOC,EAAAZ,EAAQ,QAAR,KAAAY,EAAiB,CAAC,CAC3B,EACAR,EACA,CACE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,WAAYA,EAAQ,WACpB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,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"]}
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 /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\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,mCA4EPA,EAAiC,mCAtCjC,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,CA7D1C,IAAAC,EAAAC,EAAAC,EAiEE,IAAMC,GACJD,GAAAD,K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AAR,KAAAQ,EAAiB,CAAC,CAC3B,CAAC,EACD,MAAO,CACL,aAAaE,GAAAD,EAAAQ,EAAQ,cAAR,KAAAR,EAAuBT,EAAQ,WAA/B,KAAAU,EAA2C,CAAC,EACzD,YAAaO,EAAQ,YACrB,MAAOA,EAAQ,MACf,QAASA,EAAQ,QACjB,WAAYA,EAAQ,WACpB,UAAAb,CACF,CACF,OAAQc,EAAA,CACN,OAAOH,CACT,CACF,CAEA,IAAMI,EAAS,MAAMN,EACnB,CACE,SAAUb,EAAQ,SAClB,YAAYW,EAAAX,EAAQ,aAAR,KAAAW,EAAsB,CAAC,EACnC,OAAOC,EAAAZ,EAAQ,QAAR,KAAAY,EAAiB,CAAC,CAC3B,EACAR,EACA,CACE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,WAAYA,EAAQ,WACpB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,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 N=Object.defineProperty,E=Object.defineProperties;var O=Object.getOwnPropertyDescriptors;var I=Object.getOwnPropertySymbols;var b=Object.prototype.hasOwnProperty,R=Object.prototype.propertyIsEnumerable;var L=(e,s,t)=>s in e?N(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t,k=(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))R.call(s,t)&&L(e,t,s[t]);return e},S=(e,s)=>E(e,O(s));import{preloadAssignments as x,readSessionCookie as U}from"@sentientui/core/server";import{preloadDecisions as P}from"@sentientui/core/server";function D(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function T(e,s){var a,o,r;let t=(r=(o=U(s.cookies))!=null?o:(a=s.createSessionId)==null?void 0:a.call(s))!=null?r:D();return{assignments:await x(e,t,{apiKey:s.apiKey,baseUrl:s.baseUrl,origin:s.origin,userAgent:s.userAgent,referer:s.referer,doNotTrack:s.doNotTrack,timeoutMs:s.timeoutMs,persona:s.persona}),sessionId:t}}async function w(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:D();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,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona});return S(k({},o),{sessionId:n})}export{T as loadAdaptiveAssignments,w as loadAdaptiveDecision,x as preloadAssignments,P as preloadDecisions,U as readSessionCookie};
1
+ var N=Object.defineProperty,E=Object.defineProperties;var O=Object.getOwnPropertyDescriptors;var I=Object.getOwnPropertySymbols;var b=Object.prototype.hasOwnProperty,R=Object.prototype.propertyIsEnumerable;var L=(e,s,t)=>s in e?N(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t,k=(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))R.call(s,t)&&L(e,t,s[t]);return e},S=(e,s)=>E(e,O(s));import{preloadAssignments as x,readSessionCookie as K}from"@sentientui/core/server";import{preloadDecisions as P}from"@sentientui/core/server";function D(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function T(e,s){var a,o,n;let t=(n=(o=K(s.cookies,s.apiKey))!=null?o:(a=s.createSessionId)==null?void 0:a.call(s))!=null?n:D();return{assignments:await x(e,t,{apiKey:s.apiKey,baseUrl:s.baseUrl,origin:s.origin,userAgent:s.userAgent,referer:s.referer,doNotTrack:s.doNotTrack,timeoutMs:s.timeoutMs,persona:s.persona}),sessionId:t}}async function w(e){var n,d,g,l,u,m,p,A,y,f;let{preloadDecisions:s,readSessionCookie:t}=await import("@sentientui/core/server"),r=(g=(d=t(e.cookies,e.apiKey))!=null?d:(n=e.createSessionId)==null?void 0:n.call(e))!=null?g:D();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let v={layoutOrder:(l=e.sections)!=null?l:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:r};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:r}).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:r}}catch(c){return v}}let o=await s({sections:e.sections,components:(y=e.components)!=null?y:[],slots:(f=e.slots)!=null?f:[]},r,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona});return S(k({},o),{sessionId:r})}export{T as loadAdaptiveAssignments,w as loadAdaptiveDecision,x as preloadAssignments,P as preloadDecisions,K 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 /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n 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 doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n};\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 doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n },\n );\n\n return { ...result, sessionId };\n}\n"],"mappings":"6aAGA,OACE,sBAAAA,EACA,qBAAAC,MAGK,0BAyEP,OAAS,oBAAAC,MAAwB,0BAnCjC,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,CA7D1C,IAAAC,EAAAC,EAAAC,EA8DE,IAAMC,GACJD,GAAAD,EAAAG,EAAkBL,EAAQ,OAAO,IAAjC,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,EAAiB,EAanB,MAAO,CAAE,YAXW,MAAMS,EAAmBP,EAAYK,EAAW,CAClE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,WAAYA,EAAQ,WACpB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,CAAC,EAEqB,UAAAI,CAAU,CAClC,CAmCA,eAAsBG,EACpBP,EACqC,CApHvC,IAAAC,EAAA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EACAV,EACA,CACE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,WAAYA,EAAQ,WACpB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,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"]}
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 /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n },\n );\n\n return { ...result, sessionId };\n}\n"],"mappings":"6aAGA,OACE,sBAAAA,EACA,qBAAAC,MAGK,0BA4EP,OAAS,oBAAAC,MAAwB,0BAtCjC,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,CA7D1C,IAAAC,EAAAC,EAAAC,EAiEE,IAAMC,GACJD,GAAAD,EAAAG,EAAkBL,EAAQ,QAASA,EAAQ,MAAM,IAAjD,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,EAAiB,EAanB,MAAO,CAAE,YAXW,MAAMS,EAAmBP,EAAYK,EAAW,CAClE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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,WAAYA,EAAQ,WACpB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,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"]}
package/dist/testing.js CHANGED
@@ -1,3 +1,3 @@
1
1
  'use client';
2
- "use strict";var be=Object.create;var G=Object.defineProperty,he=Object.defineProperties,xe=Object.getOwnPropertyDescriptor,Ce=Object.getOwnPropertyDescriptors,Re=Object.getOwnPropertyNames,Y=Object.getOwnPropertySymbols,ke=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty,Ee=Object.prototype.propertyIsEnumerable;var Z=(e,t,n)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,D=(e,t)=>{for(var n in t||(t={}))ee.call(t,n)&&Z(e,n,t[n]);if(Y)for(var n of Y(t))Ee.call(t,n)&&Z(e,n,t[n]);return e},te=(e,t)=>he(e,Ce(t));var Ae=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},ne=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Re(t))!ee.call(e,o)&&o!==n&&G(e,o,{get:()=>t[o],enumerable:!(i=xe(t,o))||i.enumerable});return e};var ie=(e,t,n)=>(n=e!=null?be(ke(e)):{},ne(t||!e||!e.__esModule?G(n,"default",{value:e,enumerable:!0}):n,e)),Pe=e=>ne(G({},"__esModule",{value:!0}),e);var Ue={};Ae(Ue,{applyScenario:()=>j,clearSentientEvents:()=>pe,getSentientEvents:()=>T,hasFiredGoal:()=>ge,mockSentient:()=>ye,mockSentientCypress:()=>_e,renderWithSentient:()=>Ne,resetScenario:()=>U,resolveScenario:()=>C,scenarioToHandlers:()=>ve,setupSentientTests:()=>je});module.exports=Pe(Ue);var we=require("@testing-library/react");var c=require("react"),A=require("@sentientui/core");var Oe=new Map,Ge=new Map;function re(e,t){Oe.set(e,t);let n=Ge.get(e);if(n)for(let i of n)try{i(t)}catch(o){}}var De={on:!1,listeners:new Set};function oe(){if(typeof window=="undefined")return De;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function M(){return oe().on}function se(e){let t=oe().listeners;return t.add(e),()=>{t.delete(e)}}function ae(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,i,o)=>e.assign(t,n,i,o),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var Ie="sentient:overrides-changed";function B(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(Ie))}function le(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function ce(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Le={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function K(){if(typeof window=="undefined")return Le;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function We(){K().version+=1;for(let e of K().listeners)e()}function N(e){ce()&&(K().sections=[...e],We())}var fe=require("react/jsx-runtime");function Te(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{let n=(0,A.detectDeviceClass)((e=navigator.userAgent)!=null?e:""),i=(0,A.detectTrafficSource)((t=document.referrer)!=null?t:"",window.location.origin);return`${n}:${i}`}catch(n){return"desktop:direct"}}var de="https://api.sentient-ui.com/v1",Fe=(0,c.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialPersona:null,apiBaseUrl:de,debug:!1});function Me(e){let[t,n]=(0,c.useState)(!1),i=(0,c.useRef)(e);i.current=e;let{cookie:o,value:s,event:p}=e!=null?e:{},u=typeof(e==null?void 0:e.check)=="function";return(0,c.useEffect)(()=>{let a=()=>{var g;let d=i.current;if(!d)return!1;if(d.check)return d.check()===!0;if(!d.cookie||typeof document=="undefined")return!1;let S=`${d.cookie}=${(g=d.value)!=null?g:"accepted"}`;return document.cookie.split("; ").some(_=>_.trim()===S)};if(a()){n(!0);return}if(!p)return;let l=()=>{a()&&n(!0)};return window.addEventListener(p,l),()=>window.removeEventListener(p,l)},[o,s,p,u]),t}function ue(e){var _,h;let[t,n]=(0,c.useState)(null),[i]=(0,c.useState)(()=>{var r;return(r=e.sessionSegment)!=null?r:Te()}),[o,s]=(0,c.useState)(M());(0,c.useEffect)(()=>se(()=>s(M())),[]);let p=Me(e.consentFrom),u=e.consentFrom?e.consent===!0||p:e.consent;(0,c.useEffect)(()=>{if(u===!1&&!e.preConsentBehavior){n(b=>(b==null||b.destroy(),null));return}let r={apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:u,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},y=!1,f=null,m=null,w=b=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:x})=>{y||(m=x(b,{apiKey:e.apiKey,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:b})=>{y||(f=b(te(D({},r),{graph:!0,captureDomText:e.captureDomText===!0})),n(f),w(f))}):(f=(0,A.init)(r),n(f),w(f)),()=>{y=!0,m==null||m(),f==null||f.dispose()}},[u]),(0,c.useEffect)(()=>{if(!t)return;let r=!1,y=async()=>{if(r)return;let m;try{m=await t.fetchWeights()}catch(w){return}if(!r)for(let w of m){let b={componentId:w.componentId,updatedAt:w.updatedAt,variants:w.variants.map(x=>{var P;return{variantId:x.variantId,pulls:x.pulls,avgReward:(P=x.avgReward)!=null?P:0}})};re(w.componentId,b)}};y();let f=setInterval(()=>{y()},6e4);return()=>{r=!0,clearInterval(f)}},[t]);let a=(_=e.ssrFallback)!=null?_:"first",l=((h=e.apiBaseUrl)!=null?h:de).replace(/\/$/,""),d=(0,c.useRef)(null);(0,c.useEffect)(()=>{var f;if(typeof process!="undefined"&&((f=process.env)==null?void 0:f.NODE_ENV)==="production")return;let r={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:l},y=d.current;if(d.current=r,y!==null)for(let m of["apiKey","context","country","persona","apiBaseUrl"])Object.is(y[m],r[m])||console.warn(`[sentient] AdaptiveProvider: \`${m}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,l]),(0,c.useEffect)(()=>{var r;typeof process!="undefined"&&((r=process.env)==null?void 0:r.NODE_ENV)==="production"||le({apiKey:e.apiKey,apiBaseUrl:l,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,l]),(0,c.useEffect)(()=>{let r=e.initialLayoutOrder;if(r&&r.length>0){N(r);return}e.declaredSections&&e.declaredSections.length>0&&N(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]);let S=(0,c.useMemo)(()=>t&&o?ae(t):t,[t,o]),g=(0,c.useMemo)(()=>{var r,y,f,m,w;return{client:S,apiKey:e.apiKey,initialAssignments:(r=e.initialAssignments)!=null?r:{},sessionSegment:i,ssrFallback:a,onAssignment:e.onAssignment,initialLayoutOrder:(y=e.initialLayoutOrder)!=null?y:null,initialSlots:(f=e.initialSlots)!=null?f:{},initialPersona:(m=e.initialPersona)!=null?m:null,apiBaseUrl:l,debug:(w=e.debug)!=null?w:!1}},[S,e.apiKey,e.initialAssignments,i,a,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialPersona,l,e.debug]);return(0,fe.jsx)(Fe.Provider,{value:g,children:e.children})}function I(e){return e<.3?"low":e<.7?"medium":"high"}function j(e={}){var n,i,o;let t=window;if(t.__sentient_overrides=D({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=D({},e.slots):delete t.__sentient_slot_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let s=document.documentElement;s.setAttribute("data-sentient-persona",e.persona),s.setAttribute("data-sentient-confidence",I((o=e.confidence)!=null?o:1))}catch(s){}}else delete t.__sentient_persona_override;B()}function U(){let e=window;delete e.__sentient_overrides,delete e.__sentient_layout_override,delete e.__sentient_slot_overrides,delete e.__sentient_persona_override;try{document.documentElement.removeAttribute("data-sentient-persona"),document.documentElement.removeAttribute("data-sentient-confidence")}catch(t){}B()}var L=require("msw");var V=[];function $(e){V.push(e)}function T(){return[...V]}function pe(){V.length=0}function ge(e,t){return e.some(n=>(n.eventType==="goal_achieved"||n.eventType==="goal")&&n.goalType===t)}function Be(e){var t;try{return new URL(e).pathname}catch(n){return(t=e.split("?")[0])!=null?t:e}}async function Ke(e,t){var i,o,s;let n=(i=e.api)==null?void 0:i[t];return n===void 0?null:n==="error"?{status:500}:typeof n=="number"?{status:n}:(n.delayMs&&await new Promise(p=>setTimeout(p,n.delayMs)),{status:(o=n.status)!=null?o:200,json:(s=n.body)!=null?s:{}})}async function C(e,t,n,i){var a,l,d,S,g,_,h,r,y,f,m,w,b,x,P,H,z,J,X,q,Q;let o=Be(n);if(!o.includes("/v1/"))return null;let s="/v1/"+((a=o.split("/v1/")[1])!=null?a:""),p=await Ke(e,s);if(p)return p;let u=i?JSON.parse(i):{};if(s==="/v1/sessions")return{status:204};if(s==="/v1/events"){for(let v of u)$(v);return{status:204}}if(s==="/v1/goals")return $({eventType:"goal",goalType:u.name}),{status:204};if(s==="/v1/assign"){let v=u;return{status:200,json:{variantId:(g=(S=(l=e.variants)==null?void 0:l[v.componentId])!=null?S:(d=v.variantIds)==null?void 0:d[0])!=null?g:"control",assignmentTtlMs:6e4}}}if(s==="/v1/decide"){let v=u,R={layoutOrder:(h=e.layout)!=null?h:((_=v.sections)!=null?_:[]).map(k=>k.id),assignments:(r=e.variants)!=null?r:{},persona:(y=e.persona)!=null?y:"unknown",confidence:(f=e.confidence)!=null?f:1};if(v.slots&&v.slots.length>0){let k={};for(let E of v.slots)k[E.id]=(w=(m=e.slots)==null?void 0:m[E.id])!=null?w:me(E);R.slots=k}return{status:200,json:R}}if(s==="/v1/explain"){let v=u,O=(x=e.layout)!=null?x:((b=v.sections)!=null?b:[]).map(W=>W.id),R=(H=(P=v.persona)!=null?P:e.persona)!=null?H:"unknown",k=(z=e.confidence)!=null?z:1,E={layoutOrder:O,assignments:(J=e.variants)!=null?J:{},persona:R,reasons:[],personaAttributes:{persona:R,confidence:I(k)}};if(v.slots&&v.slots.length>0){let W={};for(let F of v.slots)W[F.id]=(q=(X=e.slots)==null?void 0:X[F.id])!=null?q:me(F);E.slots=W}return{status:200,json:E}}return s==="/v1/weights"?{status:200,json:{components:Object.entries((Q=e.weights)!=null?Q:{}).map(([O,R])=>({componentId:O,updatedAt:0,variants:R}))}}:null}function me(e){var n,i,o;if(e.arms)return typeof e.baseline=="string"?e.baseline:(n=e.arms[0])!=null?n:"baseline";let t={};for(let[s,p]of Object.entries((i=e.dims)!=null?i:{})){let u=typeof e.baseline=="object"&&e.baseline!==null?e.baseline[s]:void 0;t[s]=(o=u!=null?u:p[0])!=null?o:""}return t}function ve(e={}){return[L.http.all("*/v1/*",async({request:t})=>{let n=t.method==="GET"||t.method==="HEAD"?null:await t.text(),i=await C(e,t.method,t.url,n);if(i)return i.json===void 0?new L.HttpResponse(null,{status:i.status}):L.HttpResponse.json(i.json,{status:i.status})})]}async function ye(e,t={}){var i,o,s,p,u;let n={overrides:(i=t.variants)!=null?i:{},layout:(o=t.layout)!=null?o:null,slots:(s=t.slots)!=null?s:null,persona:(p=t.persona)!=null?p:null,confidence:(u=t.confidence)!=null?u:1};return await e.addInitScript(a=>{let l=window;if(l.__sentient_overrides=a.overrides,a.layout&&(l.__sentient_layout_override=a.layout),a.slots&&(l.__sentient_slot_overrides=a.slots),a.persona){l.__sentient_persona_override={persona:a.persona,confidence:a.confidence};try{let d=a.confidence<.3?"low":a.confidence<.7?"medium":"high";document.documentElement.setAttribute("data-sentient-persona",a.persona),document.documentElement.setAttribute("data-sentient-confidence",d)}catch(d){}}},n),await e.route("**/v1/**",async a=>{var S;let l=a.request(),d=await C(t,l.method(),l.url(),l.postData());if(!d)return a.continue();await a.fulfill({status:d.status,contentType:"application/json",body:JSON.stringify((S=d.json)!=null?S:{})})}),{events:()=>T()}}function _e(e,t={}){var u,a,l,d,S;let n=(u=t.variants)!=null?u:{},i=(a=t.layout)!=null?a:null,o=(l=t.slots)!=null?l:null,s=(d=t.persona)!=null?d:null,p=(S=t.confidence)!=null?S:1;e.on("window:before:load",g=>{var _,h;if(g.__sentient_overrides=n,i&&(g.__sentient_layout_override=i),o&&(g.__sentient_slot_overrides=o),s){g.__sentient_persona_override={persona:s,confidence:p};try{let r=g.document;(_=r==null?void 0:r.documentElement)==null||_.setAttribute("data-sentient-persona",s),(h=r==null?void 0:r.documentElement)==null||h.setAttribute("data-sentient-confidence",I(p))}catch(r){}}}),e.intercept("**/v1/**",async g=>{var h;let _=await C(t,g.method,g.url,g.body!=null?JSON.stringify(g.body):null);_&&g.reply({statusCode:_.status,body:(h=_.json)!=null?h:""})})}var Se=require("react/jsx-runtime");function Ne(e,t={},n){return j(t),(0,we.render)((0,Se.jsx)(ue,{apiKey:"pk_test",context:"saas",consent:!1,children:e}),n)}function je(){var t;let e=globalThis;(t=e.afterEach)==null||t.call(e,()=>U())}0&&(module.exports={applyScenario,clearSentientEvents,getSentientEvents,hasFiredGoal,mockSentient,mockSentientCypress,renderWithSentient,resetScenario,resolveScenario,scenarioToHandlers,setupSentientTests});
2
+ "use strict";var be=Object.create;var G=Object.defineProperty,he=Object.defineProperties,Ce=Object.getOwnPropertyDescriptor,xe=Object.getOwnPropertyDescriptors,Re=Object.getOwnPropertyNames,Y=Object.getOwnPropertySymbols,ke=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty,Ee=Object.prototype.propertyIsEnumerable;var Z=(e,t,n)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,I=(e,t)=>{for(var n in t||(t={}))ee.call(t,n)&&Z(e,n,t[n]);if(Y)for(var n of Y(t))Ee.call(t,n)&&Z(e,n,t[n]);return e},te=(e,t)=>he(e,xe(t));var Ae=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},ne=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Re(t))!ee.call(e,o)&&o!==n&&G(e,o,{get:()=>t[o],enumerable:!(i=Ce(t,o))||i.enumerable});return e};var ie=(e,t,n)=>(n=e!=null?be(ke(e)):{},ne(t||!e||!e.__esModule?G(n,"default",{value:e,enumerable:!0}):n,e)),Pe=e=>ne(G({},"__esModule",{value:!0}),e);var Ue={};Ae(Ue,{applyScenario:()=>j,clearSentientEvents:()=>pe,getSentientEvents:()=>W,hasFiredGoal:()=>ge,mockSentient:()=>ye,mockSentientCypress:()=>_e,renderWithSentient:()=>Ne,resetScenario:()=>U,resolveScenario:()=>x,scenarioToHandlers:()=>ve,setupSentientTests:()=>je});module.exports=Pe(Ue);var we=require("@testing-library/react");var c=require("react"),A=require("@sentientui/core");var Oe=new Map,Ge=new Map;function re(e,t){Oe.set(e,t);let n=Ge.get(e);if(n)for(let i of n)try{i(t)}catch(o){}}var Ie={on:!1,listeners:new Set};function oe(){if(typeof window=="undefined")return Ie;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function M(){return oe().on}function se(e){let t=oe().listeners;return t.add(e),()=>{t.delete(e)}}function ae(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,i,o)=>e.assign(t,n,i,o),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var De="sentient:overrides-changed";function B(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(De))}function le(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function ce(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Le={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function K(){if(typeof window=="undefined")return Le;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function Te(){K().version+=1;for(let e of K().listeners)e()}function N(e){ce()&&(K().sections=[...e],Te())}var fe=require("react/jsx-runtime");function We(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{let n=(0,A.detectDeviceClass)((e=navigator.userAgent)!=null?e:""),i=(0,A.detectTrafficSource)((t=document.referrer)!=null?t:"",window.location.origin);return`${n}:${i}`}catch(n){return"desktop:direct"}}var de="https://api.sentient-ui.com/v1",Fe=(0,c.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialPersona:null,apiBaseUrl:de,debug:!1});function Me(e){let[t,n]=(0,c.useState)(!1),i=(0,c.useRef)(e);i.current=e;let{cookie:o,value:s,event:p}=e!=null?e:{},u=typeof(e==null?void 0:e.check)=="function";return(0,c.useEffect)(()=>{let a=()=>{var g;let d=i.current;if(!d)return!1;if(d.check)return d.check()===!0;if(!d.cookie||typeof document=="undefined")return!1;let S=`${d.cookie}=${(g=d.value)!=null?g:"accepted"}`;return document.cookie.split("; ").some(_=>_.trim()===S)};if(n(a()),!p)return;let l=()=>{n(a())};return window.addEventListener(p,l),()=>window.removeEventListener(p,l)},[o,s,p,u]),t}function ue(e){var _,h;let[t,n]=(0,c.useState)(null),[i]=(0,c.useState)(()=>{var r;return(r=e.sessionSegment)!=null?r:We()}),[o,s]=(0,c.useState)(M());(0,c.useEffect)(()=>se(()=>s(M())),[]);let p=Me(e.consentFrom),u=e.consentFrom?e.consent===!0||p:e.consent;(0,c.useEffect)(()=>{if(u===!1&&!e.preConsentBehavior){n(b=>(b==null||b.destroy(),null));return}let r={apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:u,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},y=!1,f=null,m=null,w=b=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:C})=>{y||(m=C(b,{apiKey:e.apiKey,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:b})=>{y||(f=b(te(I({},r),{graph:!0,captureDomText:e.captureDomText===!0})),n(f),w(f))}):(f=(0,A.init)(r),n(f),w(f)),()=>{y=!0,m==null||m(),f==null||f.dispose()}},[u]),(0,c.useEffect)(()=>{if(!t)return;let r=!1,y=async()=>{if(r)return;let m;try{m=await t.fetchWeights()}catch(w){return}if(!r)for(let w of m){let b={componentId:w.componentId,updatedAt:w.updatedAt,variants:w.variants.map(C=>{var P;return{variantId:C.variantId,pulls:C.pulls,avgReward:(P=C.avgReward)!=null?P:0}})};re(w.componentId,b)}};y();let f=setInterval(()=>{y()},6e4);return()=>{r=!0,clearInterval(f)}},[t]);let a=(_=e.ssrFallback)!=null?_:"first",l=((h=e.apiBaseUrl)!=null?h:de).replace(/\/$/,""),d=(0,c.useRef)(null);(0,c.useEffect)(()=>{var f;if(typeof process!="undefined"&&((f=process.env)==null?void 0:f.NODE_ENV)==="production")return;let r={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:l},y=d.current;if(d.current=r,y!==null)for(let m of["apiKey","context","country","persona","apiBaseUrl"])Object.is(y[m],r[m])||console.warn(`[sentient] AdaptiveProvider: \`${m}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,l]),(0,c.useEffect)(()=>{var r;typeof process!="undefined"&&((r=process.env)==null?void 0:r.NODE_ENV)==="production"||le({apiKey:e.apiKey,apiBaseUrl:l,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,l]),(0,c.useEffect)(()=>{let r=e.initialLayoutOrder;if(r&&r.length>0){N(r);return}e.declaredSections&&e.declaredSections.length>0&&N(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]);let S=(0,c.useMemo)(()=>t&&o?ae(t):t,[t,o]),g=(0,c.useMemo)(()=>{var r,y,f,m,w;return{client:S,apiKey:e.apiKey,initialAssignments:(r=e.initialAssignments)!=null?r:{},sessionSegment:i,ssrFallback:a,onAssignment:e.onAssignment,initialLayoutOrder:(y=e.initialLayoutOrder)!=null?y:null,initialSlots:(f=e.initialSlots)!=null?f:{},initialPersona:(m=e.initialPersona)!=null?m:null,apiBaseUrl:l,debug:(w=e.debug)!=null?w:!1}},[S,e.apiKey,e.initialAssignments,i,a,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialPersona,l,e.debug]);return(0,fe.jsx)(Fe.Provider,{value:g,children:e.children})}function D(e){return e<.3?"low":e<.7?"medium":"high"}function j(e={}){var n,i,o;let t=window;if(t.__sentient_overrides=I({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=I({},e.slots):delete t.__sentient_slot_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let s=document.documentElement;s.setAttribute("data-sentient-persona",e.persona),s.setAttribute("data-sentient-confidence",D((o=e.confidence)!=null?o:1))}catch(s){}}else delete t.__sentient_persona_override;B()}function U(){let e=window;delete e.__sentient_overrides,delete e.__sentient_layout_override,delete e.__sentient_slot_overrides,delete e.__sentient_persona_override;try{document.documentElement.removeAttribute("data-sentient-persona"),document.documentElement.removeAttribute("data-sentient-confidence")}catch(t){}B()}var L=require("msw");var V=[];function $(e){V.push(e)}function W(){return[...V]}function pe(){V.length=0}function ge(e,t){return e.some(n=>(n.eventType==="goal_achieved"||n.eventType==="goal")&&n.goalType===t)}function Be(e){var t;try{return new URL(e).pathname}catch(n){return(t=e.split("?")[0])!=null?t:e}}async function Ke(e,t){var i,o,s;let n=(i=e.api)==null?void 0:i[t];return n===void 0?null:n==="error"?{status:500}:typeof n=="number"?{status:n}:(n.delayMs&&await new Promise(p=>setTimeout(p,n.delayMs)),{status:(o=n.status)!=null?o:200,json:(s=n.body)!=null?s:{}})}async function x(e,t,n,i){var a,l,d,S,g,_,h,r,y,f,m,w,b,C,P,H,z,J,X,q,Q;let o=Be(n);if(!o.includes("/v1/"))return null;let s="/v1/"+((a=o.split("/v1/")[1])!=null?a:""),p=await Ke(e,s);if(p)return p;let u=i?JSON.parse(i):{};if(s==="/v1/sessions")return{status:204};if(s==="/v1/events"){for(let v of u)$(v);return{status:204}}if(s==="/v1/goals")return $({eventType:"goal",goalType:u.name}),{status:204};if(s==="/v1/assign"){let v=u;return{status:200,json:{variantId:(g=(S=(l=e.variants)==null?void 0:l[v.componentId])!=null?S:(d=v.variantIds)==null?void 0:d[0])!=null?g:"control",assignmentTtlMs:6e4}}}if(s==="/v1/decide"){let v=u,R={layoutOrder:(h=e.layout)!=null?h:((_=v.sections)!=null?_:[]).map(k=>k.id),assignments:(r=e.variants)!=null?r:{},persona:(y=e.persona)!=null?y:"unknown",confidence:(f=e.confidence)!=null?f:1};if(v.slots&&v.slots.length>0){let k={};for(let E of v.slots)k[E.id]=(w=(m=e.slots)==null?void 0:m[E.id])!=null?w:me(E);R.slots=k}return{status:200,json:R}}if(s==="/v1/explain"){let v=u,O=(C=e.layout)!=null?C:((b=v.sections)!=null?b:[]).map(T=>T.id),R=(H=(P=v.persona)!=null?P:e.persona)!=null?H:"unknown",k=(z=e.confidence)!=null?z:1,E={layoutOrder:O,assignments:(J=e.variants)!=null?J:{},persona:R,reasons:[],personaAttributes:{persona:R,confidence:D(k)}};if(v.slots&&v.slots.length>0){let T={};for(let F of v.slots)T[F.id]=(q=(X=e.slots)==null?void 0:X[F.id])!=null?q:me(F);E.slots=T}return{status:200,json:E}}return s==="/v1/weights"?{status:200,json:{components:Object.entries((Q=e.weights)!=null?Q:{}).map(([O,R])=>({componentId:O,updatedAt:0,variants:R}))}}:null}function me(e){var n,i,o;if(e.arms)return typeof e.baseline=="string"?e.baseline:(n=e.arms[0])!=null?n:"baseline";let t={};for(let[s,p]of Object.entries((i=e.dims)!=null?i:{})){let u=typeof e.baseline=="object"&&e.baseline!==null?e.baseline[s]:void 0;t[s]=(o=u!=null?u:p[0])!=null?o:""}return t}function ve(e={}){return[L.http.all("*/v1/*",async({request:t})=>{let n=t.method==="GET"||t.method==="HEAD"?null:await t.text(),i=await x(e,t.method,t.url,n);if(i)return i.json===void 0?new L.HttpResponse(null,{status:i.status}):L.HttpResponse.json(i.json,{status:i.status})})]}async function ye(e,t={}){var i,o,s,p,u;let n={overrides:(i=t.variants)!=null?i:{},layout:(o=t.layout)!=null?o:null,slots:(s=t.slots)!=null?s:null,persona:(p=t.persona)!=null?p:null,confidence:(u=t.confidence)!=null?u:1};return await e.addInitScript(a=>{let l=window;if(l.__sentient_overrides=a.overrides,a.layout&&(l.__sentient_layout_override=a.layout),a.slots&&(l.__sentient_slot_overrides=a.slots),a.persona){l.__sentient_persona_override={persona:a.persona,confidence:a.confidence};try{let d=a.confidence<.3?"low":a.confidence<.7?"medium":"high";document.documentElement.setAttribute("data-sentient-persona",a.persona),document.documentElement.setAttribute("data-sentient-confidence",d)}catch(d){}}},n),await e.route("**/v1/**",async a=>{var S;let l=a.request(),d=await x(t,l.method(),l.url(),l.postData());if(!d)return a.continue();await a.fulfill({status:d.status,contentType:"application/json",body:JSON.stringify((S=d.json)!=null?S:{})})}),{events:()=>W()}}function _e(e,t={}){var u,a,l,d,S;let n=(u=t.variants)!=null?u:{},i=(a=t.layout)!=null?a:null,o=(l=t.slots)!=null?l:null,s=(d=t.persona)!=null?d:null,p=(S=t.confidence)!=null?S:1;e.on("window:before:load",g=>{var _,h;if(g.__sentient_overrides=n,i&&(g.__sentient_layout_override=i),o&&(g.__sentient_slot_overrides=o),s){g.__sentient_persona_override={persona:s,confidence:p};try{let r=g.document;(_=r==null?void 0:r.documentElement)==null||_.setAttribute("data-sentient-persona",s),(h=r==null?void 0:r.documentElement)==null||h.setAttribute("data-sentient-confidence",D(p))}catch(r){}}}),e.intercept("**/v1/**",async g=>{var h;let _=await x(t,g.method,g.url,g.body!=null?JSON.stringify(g.body):null);_&&g.reply({statusCode:_.status,body:(h=_.json)!=null?h:""})})}var Se=require("react/jsx-runtime");function Ne(e,t={},n){return j(t),(0,we.render)((0,Se.jsx)(ue,{apiKey:"pk_test",context:"saas",consent:!1,children:e}),n)}function je(){var t;let e=globalThis;(t=e.afterEach)==null||t.call(e,()=>U())}0&&(module.exports={applyScenario,clearSentientEvents,getSentientEvents,hasFiredGoal,mockSentient,mockSentientCypress,renderWithSentient,resetScenario,resolveScenario,scenarioToHandlers,setupSentientTests});
3
3
  //# sourceMappingURL=testing.js.map