@sentientui/react 0.44.1 → 0.44.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var Ce=Object.defineProperty,De=Object.defineProperties;var Te=Object.getOwnPropertyDescriptors;var D=Object.getOwnPropertySymbols;var pe=Object.prototype.hasOwnProperty,me=Object.prototype.propertyIsEnumerable;var ue=(e,t,n)=>t in e?Ce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,l=(e,t)=>{for(var n in t||(t={}))pe.call(t,n)&&ue(e,n,t[n]);if(D)for(var n of D(t))me.call(t,n)&&ue(e,n,t[n]);return e},m=(e,t)=>De(e,Te(t));var fe=(e,t)=>{var n={};for(var s in e)pe.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&D)for(var s of D(e))t.indexOf(s)<0&&me.call(e,s)&&(n[s]=e[s]);return n};import{deriveSessionSegment as Ge,exposedStage as Ye,extractTrackedParams as ze,matchedAgentToken as Qe}from"@sentientui/core";import{consentFromCookies as Ze}from"@sentientui/core/consent";import{signUserId as et}from"@sentientui/core/server";import{cookies as tt,headers as nt}from"next/headers";import{renderPrePaintScript as Ke}from"@sentientui/core";import{confidenceBand as _e}from"@sentientui/policy";import{jsx as Be}from"react/jsx-runtime";function _(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function Ue(e){return e.persona?"(function(){try{var d=document.documentElement;"+(e.stage?'if(!d.hasAttribute("data-sentient-stage"))d.setAttribute("data-sentient-stage",'+_(e.stage)+");":"")+'if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+_(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+_(_e(e.persona.confidence))+");}catch(e){}})();":Ke(e.apiKey,e.stageAttributes?{stage:!0}:void 0)}function ye(e){return!e.persona&&(e.consent===!1||e.consentFrom!==void 0&&e.consent!==!0)?null:Be("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:Ue(e)}})}import{preloadAssignments as pt,preloadAssignmentsDetailed as Me,readInternalToken as je,readSessionCookie as Je,signUserId as mt,trackServerGoal as ft}from"@sentientui/core/server";import{preloadDecisions as ht}from"@sentientui/core/server";function Ae(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function he(e,t){var a,d,c;let n=(c=(d=Je(t.cookies,t.apiKey))!=null?d:(a=t.createSessionId)==null?void 0:a.call(t))!=null?c:Ae(),{assignments:s,unified:i}=await Me(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,origin:t.origin,userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,clickIds:t.clickIds,landingPath:t.landingPath,doNotTrack:t.doNotTrack,timeoutMs:t.timeoutMs,persona:t.persona,internal:t.internal,internalToken:je(t.cookies)},{unified:!0});return{assignments:s,sessionId:n,unified:i}}async function ve(e){var c,k,b,x,F,g,E,f,L,y;let{preloadDecisions:t,readSessionCookie:n,readInternalToken:s}=await import("@sentientui/core/server"),i=(b=(k=n(e.cookies,e.apiKey))!=null?k:(c=e.createSessionId)==null?void 0:c.call(e))!=null?b:Ae();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let A={layoutOrder:(x=e.sections)!=null?x:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:i};try{let o=await import("@sentientui/core/local");if(!o.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."),A;let u=o.createLocalEngine({sessionId:i}).decide({sections:e.sections,components:(F=e.components)!=null?F:[],slots:(g=e.slots)!=null?g:[]});return{layoutOrder:(f=(E=u.layoutOrder)!=null?E:e.sections)!=null?f:[],assignments:u.assignments,slots:u.slots,persona:u.persona,confidence:u.confidence,sessionId:i}}catch(o){return A}}let d=await t(m(l({sections:e.sections,components:(L=e.components)!=null?L:[],slots:(y=e.slots)!=null?y:[],slotsFrom:e.slotsFrom,registrySlotIds:e.registrySlotIds},e.renderCaps?{renderCaps:e.renderCaps}:{}),{unifiedCaps:!0}),i,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,landingPath:e.landingPath,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona,internal:e.internal,internalToken:s(e.cookies)});return m(l({},d),{sessionId:i})}import{AdaptiveRootClient as st}from"./adaptive-root-client.js";var $e=["page","blocks","layoutOrder"],Se=new Map;function Ve(e,t){Se.set(e,t)}function Xe(e){return Se.get(e)}function U(e){var i,a;let t=(a=(i=e.content)!=null?i:Xe(e.page))!=null?a:{},n={};for(let[d,c]of Object.entries(t))$e.includes(d)||(n[d]=c);let s=m(l({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(s.layoutOrder=e.layoutOrder),s}function ke(e){return JSON.stringify(l({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function be(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 Ce=Object.defineProperty,De=Object.defineProperties;var Te=Object.getOwnPropertyDescriptors;var D=Object.getOwnPropertySymbols;var pe=Object.prototype.hasOwnProperty,me=Object.prototype.propertyIsEnumerable;var ue=(e,t,n)=>t in e?Ce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,l=(e,t)=>{for(var n in t||(t={}))pe.call(t,n)&&ue(e,n,t[n]);if(D)for(var n of D(t))me.call(t,n)&&ue(e,n,t[n]);return e},m=(e,t)=>De(e,Te(t));var fe=(e,t)=>{var n={};for(var s in e)pe.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&D)for(var s of D(e))t.indexOf(s)<0&&me.call(e,s)&&(n[s]=e[s]);return n};import{deriveSessionSegment as Ye,exposedStage as Ge,extractTrackedParams as ze,matchedAgentToken as Qe}from"@sentientui/core";import{consentFromCookies as Ze}from"@sentientui/core/consent";import{signUserId as et}from"@sentientui/core/server";import{cookies as tt,headers as nt}from"next/headers";import{renderPrePaintScript as _e}from"@sentientui/core";import{confidenceBand as Ke}from"@sentientui/policy";import{jsx as Be}from"react/jsx-runtime";function K(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function Ue(e){return e.persona?"(function(){try{var d=document.documentElement;"+(e.stage?'if(!d.hasAttribute("data-sentient-stage"))d.setAttribute("data-sentient-stage",'+K(e.stage)+");":"")+'if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+K(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+K(Ke(e.persona.confidence))+");}catch(e){}})();":_e(e.apiKey,e.stageAttributes?{stage:!0}:void 0)}function ye(e){return!e.persona&&(e.consent===!1||e.consentFrom!==void 0&&e.consent!==!0)?null:Be("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:Ue(e)}})}import{preloadAssignments as pt,preloadAssignmentsDetailed as Me,readInternalToken as je,readSessionCookie as Je,signUserId as mt,trackServerGoal as ft}from"@sentientui/core/server";import{preloadDecisions as ht}from"@sentientui/core/server";function Ae(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function he(e,t){var a,d,c;let n=(c=(d=Je(t.cookies,t.apiKey))!=null?d:(a=t.createSessionId)==null?void 0:a.call(t))!=null?c:Ae(),{assignments:s,unified:i}=await Me(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,origin:t.origin,userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,clickIds:t.clickIds,landingPath:t.landingPath,doNotTrack:t.doNotTrack,timeoutMs:t.timeoutMs,persona:t.persona,internal:t.internal,internalToken:je(t.cookies)},{unified:!0});return{assignments:s,sessionId:n,unified:i}}async function ve(e){var c,k,b,O,x,g,F,f,N,y;let{preloadDecisions:t,readSessionCookie:n,readInternalToken:s}=await import("@sentientui/core/server"),i=(b=(k=n(e.cookies,e.apiKey))!=null?k:(c=e.createSessionId)==null?void 0:c.call(e))!=null?b:Ae();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let A={layoutOrder:(O=e.sections)!=null?O:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:i};try{let o=await import("@sentientui/core/local");if(!o.LOCAL_ENGINE_AVAILABLE)return console.error("[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY (Vite: VITE_SENTIENT_API_KEY) or localMode: true."),A;let u=o.createLocalEngine({sessionId:i}).decide({sections:e.sections,components:(x=e.components)!=null?x:[],slots:(g=e.slots)!=null?g:[]});return{layoutOrder:(f=(F=u.layoutOrder)!=null?F:e.sections)!=null?f:[],assignments:u.assignments,slots:u.slots,persona:u.persona,confidence:u.confidence,sessionId:i}}catch(o){return A}}let d=await t(m(l({sections:e.sections,components:(N=e.components)!=null?N:[],slots:(y=e.slots)!=null?y:[],slotsFrom:e.slotsFrom,registrySlotIds:e.registrySlotIds},e.renderCaps?{renderCaps:e.renderCaps}:{}),{unifiedCaps:!0}),i,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,landingPath:e.landingPath,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona,internal:e.internal,internalToken:s(e.cookies)});return m(l({},d),{sessionId:i})}import{AdaptiveRootClient as st}from"./adaptive-root-client.js";var Ve=["page","blocks","layoutOrder"],Se=new Map;function $e(e,t){Se.set(e,t)}function Xe(e){return Se.get(e)}function U(e){var i,a;let t=(a=(i=e.content)!=null?i:Xe(e.page))!=null?a:{},n={};for(let[d,c]of Object.entries(t))Ve.includes(d)||(n[d]=c);let s=m(l({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(s.layoutOrder=e.layoutOrder),s}function ke(e){return JSON.stringify(l({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function be(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
- `}function Re(e,t={}){var s,i;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:(i=e.userAgent)!=null?i:null,source:"ssr"})}).catch(()=>{})}catch(a){}}import{matchedAgentToken as qe}from"@sentientui/core";function He(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:"",i=t.headers.get("user-agent"),a=n.pathname.replace(/\.(md|json)$/,"");if(e.onRead)try{Promise.resolve(e.onRead({path:a,userAgent:i,botName:qe(i!=null?i:"")})).catch(()=>{})}catch(k){}let d=await e.getFeed(t);return He(n,s)?new Response(be(d),{headers:{"content-type":"text/markdown; charset=utf-8"}}):new Response(JSON.stringify(d),{headers:{"content-type":"application/json; charset=utf-8"}})}}import{matchedAgentToken as Mt,uaTokenMatch as jt,agentIntent as Jt,classifiedAgents as $t}from"@sentientui/core";import{Fragment as Ie,jsx as B,jsxs as Pe}from"react/jsx-runtime";var rt="https://api.sentient-ui.com/v1";function it(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:""}})}function ot(e,t){if(e)for(let n of e.split(";")){let s=n.indexOf("=");if(s>0&&n.slice(0,s).trim()===t)return n.slice(s+1).trim()}}async function Tt(e){var re,ie,oe,ae,de,ce,le;let se=e,{components:t=[],sections:n,slots:s,registrySlotIds:i,registrySlots:a,appOrigin:d,searchParams:c,pathname:k,initialAssignments:b,ssrSessionId:x,timeoutMs:F,agentFeed:g,captureAgents:E,nonce:f,children:L,userId:y,serverKey:A=process.env.SENTIENT_SECRET_KEY}=se,o=fe(se,["components","sections","slots","registrySlotIds","registrySlots","appOrigin","searchParams","pathname","initialAssignments","ssrSessionId","timeoutMs","agentFeed","captureAgents","nonce","children","userId","serverKey"]),u;y&&(u={userId:y,userHash:A&&await et(y,A)||void 0},!A&&process.env.NODE_ENV!=="production"&&console.warn("[SentientUI] <AdaptiveRoot userId> without SENTIENT_SECRET_KEY: the identify is unverified. Set the env var (or pass serverKey) to verify it."));let p=await nt(),N=p.get("host");!d&&process.env.NODE_ENV==="production"&&!N&&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 M=d!=null?d:process.env.NODE_ENV==="production"?`https://${N!=null?N:"localhost"}`:"http://localhost:3001",h=(re=p.get("user-agent"))!=null?re:void 0,j=(ie=p.get("referer"))!=null?ie:void 0,{utmParams:we,clickIds:Oe}=ze(c!=null?c:{}),xe=p.get("dnt")==="1"||p.get("sec-gpc")==="1",Fe=Ge({userAgent:h,referer:j,appOrigin:M}),Ee=await tt(),T=o.consentFrom,K=(ae=o.consent)!=null?ae:T&&(oe=Ze(T,r=>ot(p.get("cookie"),r)))!=null?oe:void 0,J=xe||K===!1||T!=null&&K!==!0,$=o.localMode===!0||o.localMode!==!1&&!(typeof o.apiKey=="string"&&o.apiKey.startsWith("pk_")),V=o.apiBaseUrl?o.apiBaseUrl.replace(/\/$/,""):rt,X=(ce=(de=g==null?void 0:g.path)!=null?de:p.get("x-pathname"))!=null?ce:"/",q=Qe(h!=null?h:"");!$&&E!==!1&&q&&Re({baseUrl:V,apiKey:o.apiKey,path:X,botName:q,userAgent:h});let v,S,R=null,I,H,W,G,P=null,Y=null,C,z=[...new Set([...i!=null?i:[],...(a!=null?a:[]).map(r=>r.id)])],Q=a!=null&&a.length?Object.fromEntries(a.map(r=>{var w,O;return[r.id,l({forms:(w=r.forms)!=null?w:!0,compose:!0,ops:!1},(O=r.authored)!=null&&O.length?{authored:r.authored,children:!0}:{})]})):void 0,Z=z.length>0,ee={cookies:Ee,apiKey:o.apiKey,baseUrl:V,origin:M,userAgent:h,referer:j,utmParams:we,clickIds:Oe,landingPath:k,timeoutMs:F,persona:o.persona,internal:o.internal};if(b)v=b,C=x;else if(J||$)v={};else if(n&&n.length>0||s&&s.length>0||Z){let r=await ve(l(l({sections:n!=null?n:[],components:t,slots:s},Z?l({slotsFrom:"registry",registrySlotIds:z},Q?{renderCaps:Q}:{}):{}),ee));v=r.assignments,S=r.unified,R=r.layoutOrder,I=r.slots,H=r.slotConfig,W=r.palette,G=r.vocabulary,P=r.persona!==void 0?{persona:r.persona,confidence:(le=r.confidence)!=null?le:0}:null,Y=Ye(r.stage,o.stageAttributes),C=r.sessionId}else{let r=await he(t,ee);v=r.assignments,S=r.unified,C=r.sessionId}let te=J?null:B(ye,{apiKey:o.apiKey,persona:P,nonce:f,stageAttributes:o.stageAttributes,stage:Y}),ne=B(st,m(l({},o),{nonce:f,consent:K,initialAssignments:v,initialUnified:S,initialLayoutOrder:R,declaredSections:n,initialSlots:I,initialSlotConfig:H,initialPalette:W,initialVocabulary:G,initialPersona:P!=null?P:void 0,sessionSegment:Fe,ssrSessionId:C,identity:u,children:L}));if(!g)return Pe(Ie,{children:[te,ne]});let Le=U({page:X,blocks:[...it(v),...(S!=null?S:[]).map(r=>{var ge;let w=I==null?void 0:I[r],O=(ge=t.find(Ne=>Ne.id===r))==null?void 0:ge.variantIds[0];return{id:r,variant:typeof w=="string"?w:O!==void 0?`authored.${O}`:""}})],layoutOrder:R!=null?R:void 0,content:g.content});return Pe(Ie,{children:[te,B("script",{type:"application/ld+json",nonce:f,dangerouslySetInnerHTML:{__html:ke(Le)}}),ne]})}export{Tt as AdaptiveRoot,Jt as agentIntent,U as buildAgentFeedFor,$t as classifiedAgents,We as createAgentFeed,Ve as defineAgentContent,Mt as matchedAgentToken,jt as uaTokenMatch};
3
+ `}function Ie(e,t={}){var s,i;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:(i=e.userAgent)!=null?i:null,source:"ssr"})}).catch(()=>{})}catch(a){}}import{matchedAgentToken as qe}from"@sentientui/core";function He(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:"",i=t.headers.get("user-agent"),a=n.pathname.replace(/\.(md|json)$/,"");if(e.onRead)try{Promise.resolve(e.onRead({path:a,userAgent:i,botName:qe(i!=null?i:"")})).catch(()=>{})}catch(k){}let d=await e.getFeed(t);return He(n,s)?new Response(be(d),{headers:{"content-type":"text/markdown; charset=utf-8"}}):new Response(JSON.stringify(d),{headers:{"content-type":"application/json; charset=utf-8"}})}}import{matchedAgentToken as Mt,uaTokenMatch as jt,agentIntent as Jt,classifiedAgents as Vt}from"@sentientui/core";import{Fragment as Re,jsx as B,jsxs as Pe}from"react/jsx-runtime";var rt="https://api.sentient-ui.com/v1";function it(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:""}})}function ot(e,t){if(e)for(let n of e.split(";")){let s=n.indexOf("=");if(s>0&&n.slice(0,s).trim()===t)return n.slice(s+1).trim()}}async function Tt(e){var re,ie,oe,ae,de,ce,le;let se=e,{components:t=[],sections:n,slots:s,registrySlotIds:i,registrySlots:a,appOrigin:d,searchParams:c,pathname:k,initialAssignments:b,ssrSessionId:O,timeoutMs:x,agentFeed:g,captureAgents:F,nonce:f,children:N,userId:y,serverKey:A=process.env.SENTIENT_SECRET_KEY}=se,o=fe(se,["components","sections","slots","registrySlotIds","registrySlots","appOrigin","searchParams","pathname","initialAssignments","ssrSessionId","timeoutMs","agentFeed","captureAgents","nonce","children","userId","serverKey"]),u;y&&(u={userId:y,userHash:A&&await et(y,A)||void 0},!A&&process.env.NODE_ENV!=="production"&&console.warn("[SentientUI] <AdaptiveRoot userId> without SENTIENT_SECRET_KEY: the identify is unverified. Set the env var (or pass serverKey) to verify it."));let p=await nt(),L=p.get("host");!d&&process.env.NODE_ENV==="production"&&!L&&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 M=d!=null?d:process.env.NODE_ENV==="production"?`https://${L!=null?L:"localhost"}`:"http://localhost:3001",h=(re=p.get("user-agent"))!=null?re:void 0,j=(ie=p.get("referer"))!=null?ie:void 0,{utmParams:we,clickIds:Ee}=ze(c!=null?c:{}),Oe=p.get("dnt")==="1"||p.get("sec-gpc")==="1",xe=Ye({userAgent:h,referer:j,appOrigin:M}),Fe=await tt(),T=o.consentFrom,_=(ae=o.consent)!=null?ae:T&&(oe=Ze(T,r=>ot(p.get("cookie"),r)))!=null?oe:void 0,J=Oe||_===!1||T!=null&&_!==!0,V=o.localMode===!0||o.localMode!==!1&&!(typeof o.apiKey=="string"&&o.apiKey.startsWith("pk_")),$=o.apiBaseUrl?o.apiBaseUrl.replace(/\/$/,""):rt,X=(ce=(de=g==null?void 0:g.path)!=null?de:p.get("x-pathname"))!=null?ce:"/",q=Qe(h!=null?h:"");!V&&F!==!1&&q&&Ie({baseUrl:$,apiKey:o.apiKey,path:X,botName:q,userAgent:h});let v,S,I=null,R,H,W,Y,P=null,G=null,C,z=[...new Set([...i!=null?i:[],...(a!=null?a:[]).map(r=>r.id)])],Q=a!=null&&a.length?Object.fromEntries(a.map(r=>{var w,E;return[r.id,l({forms:(w=r.forms)!=null?w:!0,compose:!0,ops:!1},(E=r.authored)!=null&&E.length?{authored:r.authored,children:!0}:{})]})):void 0,Z=z.length>0,ee={cookies:Fe,apiKey:o.apiKey,baseUrl:$,origin:M,userAgent:h,referer:j,utmParams:we,clickIds:Ee,landingPath:k,timeoutMs:x,persona:o.persona,internal:o.internal};if(b)v=b,C=O;else if(J||V)v={};else if(n&&n.length>0||s&&s.length>0||Z){let r=await ve(l(l({sections:n!=null?n:[],components:t,slots:s},Z?l({slotsFrom:"registry",registrySlotIds:z},Q?{renderCaps:Q}:{}):{}),ee));v=r.assignments,S=r.unified,I=r.layoutOrder,R=r.slots,H=r.slotConfig,W=r.palette,Y=r.vocabulary,P=r.persona!==void 0?{persona:r.persona,confidence:(le=r.confidence)!=null?le:0}:null,G=Ge(r.stage,o.stageAttributes),C=r.sessionId}else{let r=await he(t,ee);v=r.assignments,S=r.unified,C=r.sessionId}let te=J?null:B(ye,{apiKey:o.apiKey,persona:P,nonce:f,stageAttributes:o.stageAttributes,stage:G}),ne=B(st,m(l({},o),{nonce:f,consent:_,initialAssignments:v,initialUnified:S,initialLayoutOrder:I,declaredSections:n,initialSlots:R,initialSlotConfig:H,initialPalette:W,initialVocabulary:Y,initialPersona:P!=null?P:void 0,sessionSegment:xe,ssrSessionId:C,identity:u,children:N}));if(!g)return Pe(Re,{children:[te,ne]});let Ne=U({page:X,blocks:[...it(v),...(S!=null?S:[]).map(r=>{var ge;let w=R==null?void 0:R[r],E=(ge=t.find(Le=>Le.id===r))==null?void 0:ge.variantIds[0];return{id:r,variant:typeof w=="string"?w:E!==void 0?`authored.${E}`:""}})],layoutOrder:I!=null?I:void 0,content:g.content});return Pe(Re,{children:[te,B("script",{type:"application/ld+json",nonce:f,dangerouslySetInnerHTML:{__html:ke(Ne)}}),ne]})}export{Tt as AdaptiveRoot,Jt as agentIntent,U as buildAgentFeedFor,Vt as classifiedAgents,We as createAgentFeed,$e as defineAgentContent,Mt as matchedAgentToken,jt 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, exposedStage, extractTrackedParams, matchedAgentToken } from '@sentientui/core';\nimport { consentFromCookies } from '@sentientui/core/consent';\nimport { signUserId } from '@sentientui/core/server';\nimport type { RenderCaps, SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX, ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type LoadAdaptiveDecisionResult,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\n// Re-exported from core on the SERVER entry (this module is server-only — it\n// imports next/headers). Lets server components do agent detection with just the\n// `@sentientui/react` package, no direct core dependency. Do NOT add this to the\n// package's client index: re-exporting a plain function through a 'use client'\n// module turns it into a client reference that throws when called during SSR.\nexport { matchedAgentToken, uaTokenMatch, agentIntent, classifiedAgents } from '@sentientui/core';\nexport type { AgentIntent } from '@sentientui/core';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\n/** A registry `<Adaptive id>` declared with what it can render — see `AdaptiveRootProps.registrySlots`. */\nexport type RegistrySlotDecl = {\n id: string;\n /** The `variants` keys of a hybrid `<Adaptive variants>{children}</Adaptive>`. */\n authored?: string[];\n /** The `<Adaptive>` has an `onFormSubmit`. @default true */\n forms?: boolean;\n};\n\nexport type AdaptiveRootProps = Omit<\n AdaptiveProviderProps,\n // Every provider prop AdaptiveRoot itself resolves and passes AFTER the\n // {...providerProps} spread must be omitted here: a caller-supplied value\n // would typecheck but be silently clobbered by the spread order\n // (initialLayoutOrder, declaredSections and sessionSegment were missing\n // from this list and suffered exactly that).\n | 'initialAssignments'\n | 'onAssignment'\n | 'initialSlots'\n | 'initialSlotConfig'\n | 'initialPalette'\n | 'initialVocabulary'\n | 'initialPersona'\n | 'initialLayoutOrder'\n | 'declaredSections'\n | 'sessionSegment'\n | 'consentFrom'\n | 'identity'\n> & {\n /**\n * Consent source — see `AdaptiveProviderProps.consentFrom`. A platform preset\n * (`'cookiebot'`, `'onetrust'`, `'cookieyes'`, `'tcf'`, `'google-consent-mode'`)\n * or a cookie. Resolved on the server from the platform's own cookie, so a\n * visitor who already consented gets SSR with no layout shift.\n *\n * No `check` form: AdaptiveRoot is a Server Component and spreads\n * this straight into its client boundary, and a function prop crossing the\n * server→client boundary throws at render (\"Functions cannot be passed\n * directly to Client Components\"). The provider's type accepted `check`, so\n * a Cookiebot-style predicate typechecked here and then crashed the layout.\n * Need a JS-API CMP predicate? Use `<AdaptiveProvider>` in a client component.\n */\n consentFrom?: Exclude<NonNullable<AdaptiveProviderProps['consentFrom']>, { check?: () => boolean; cmp?: undefined }> | { cmp?: undefined; cookie?: string; value?: string; event?: string };\n /**\n * Code-variant components to assign server-side (SEO-safe). Optional — an\n * `<Adaptive>` works without an entry here and assigns after mount.\n *\n * List only ids this tree actually renders. Each one is assigned on every\n * request, rendered or not, and every assignment logs an impression (or a\n * holdout exposure). An id the page never renders therefore accrues trials\n * that cannot convert, and in a root layout that happens on every route.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * Give each section's rendered element `data-sentient-id=\"<sectionId>\"` —\n * the only markup a section needs — so the DOM graph scanner can register\n * it under the same id. Without it the server never learns what the section\n * IS, types it `generic`, and serves the identity order to every persona —\n * the integration looks live but cannot personalize. The provider warns\n * about unresolvable ids in development. Correct a section the content\n * classifier mistypes with `sectionTypes`, not extra markup.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n * // …and in the tree: <section data-sentient-id=\"pricing\">\n */\n sections?: string[];\n /**\n * Adaptive-slot declarations used by `useAdaptiveTokens` / `AdaptiveGroup`\n * in this tree. Declaring them here decides them in the same SSR\n * round trip, so their values serialize into the server HTML.\n */\n slots?: SlotDeclInput[];\n /**\n * The generated-mode `<Adaptive id>`s THIS page renders. Declaring them\n * decides their published versions in the same SSR round trip\n * (`/v1/decide` registry mode) and serializes the served content into the\n * server HTML, so the first paint shows the version rather than the\n * original children until the client-side decide answers. Without it a\n * registry slot renders its children first and swaps after mount.\n *\n * Scoped to exactly these ids on purpose: an unscoped registry decide\n * records a close-out trial for every published slot on every page.\n *\n * @example registrySlotIds={['hero-headline', 'pricing-cta']}\n */\n registrySlotIds?: string[];\n /**\n * Like `registrySlotIds`, for `<Adaptive id>`s that need to tell the server\n * more than their id. Most often that is a hybrid —\n * `<Adaptive id variants={{ a, b }}>{original}</Adaptive>`. List its\n * `variants` keys as `authored`, or the SSR decide cannot draw them. In that\n * case the first paint can only be the original or a generated version, and\n * the hand-written ones appear only on pages the browser decides.\n *\n * `forms`: whether the `<Adaptive>` has an `onFormSubmit`. Declare\n * `forms: false` when it has none, or SSR can draw a generated form version\n * that the page then refuses. The default is `true`, the same as a bare\n * `registrySlotIds` entry.\n *\n * You may list an id in both props: it is decided once, with these caps.\n *\n * @example registrySlots={[{ id: 'hero_cta', authored: ['action', 'social'], forms: false }]}\n */\n registrySlots?: RegistrySlotDecl[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /**\n * The page's `searchParams` prop (or an equivalent query string /\n * URLSearchParams). Server Components cannot read the request URL from\n * `headers()`, so without this the SSR-minted session carries no `utm_*`\n * params and no ad click IDs (gclid, fbclid, ttclid, …) — campaign\n * attribution only lands after client hydration, and never for visits the\n * client SDK doesn't get to finish (bounce before hydrate). Pass it on\n * landing pages that receive ad traffic:\n *\n * ```tsx\n * export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {\n * return <AdaptiveRoot ... searchParams={await searchParams}>...</AdaptiveRoot>;\n * }\n * ```\n */\n searchParams?: Record<string, string | string[] | undefined> | URLSearchParams | string;\n /**\n * The page's path (e.g. `/products/trail-shoe`). Server components cannot\n * read their own URL, so pass it on landing pages that receive ad or email\n * traffic: with it, a paid click to a product page or a `/discount/` link\n * is recognised on the server render — adapted from the first byte.\n */\n pathname?: string;\n /** Override: when set no network fetch is made. Useful for tests. */\n initialAssignments?: ServerAssignments;\n /**\n * Milliseconds to wait for the API before rendering default variants.\n * Defaults to 1000. The hot path typically returns in well under 150 ms;\n * the full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host. Lower it if your API is\n * co-located and warm.\n */\n timeoutMs?: number;\n /**\n * When set, AdaptiveRoot emits a server-rendered inline JSON-LD block\n * describing the page's winning variants, layout order, and developer-supplied\n * content — readable by passive AI crawlers (which do not run JS). Invisible to\n * humans (a JSON-LD script renders no visible DOM). Omit to emit nothing.\n */\n agentFeed?: {\n /** Page path for the feed. Falls back to the `x-pathname` request header, then '/'. */\n path?: string;\n /** Structured page content. Falls back to the `defineAgentContent` registry for this path. */\n content?: Record<string, unknown>;\n };\n /**\n * When true (default), a known AI-agent fetch (matched by user-agent —\n * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side\n * to your agent analytics. Machine telemetry only (no cookie, no session);\n * fire-and-forget, never affects render. Set false to opt out.\n */\n captureAgents?: boolean;\n /**\n * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.\n * Pass through from Next.js middleware / `headers()` when using a strict CSP.\n */\n nonce?: string;\n /**\n * The signed-in user's id (null/undefined when signed out). AdaptiveRoot\n * signs it on the server and identifies the visitor as that user — a\n * VERIFIED identify, so `trackServerGoal({ userId })` from your backend\n * reaches this visit and nobody else's.\n */\n userId?: string | null;\n /** Secret key used to sign `userId`. Defaults to `process.env.SENTIENT_SECRET_KEY`. Server-only. */\n serverKey?: string;\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * A cookie's value exactly as the browser sent it. The CMP parsers need the\n * raw form: Next's cookies() decodes every value, which turns an encoded\n * `&groups=C0002:1` inside OneTrust's `landingPath` (a crafted link, before\n * any answer) into a real field that read as consent on the server — SSR\n * then minted a session and handed the client consent={true} (grader R8 NEW-1).\n * First match wins, like the browser's document.cookie read. A consent cookie\n * set only by middleware in this request is not in the header: the server\n * then reads \"unknown\" and the browser decides (fail-closed).\n */\nfunction rawCookie(header: string | null | undefined, name: string): string | undefined {\n if (!header) return undefined;\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq > 0 && part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();\n }\n return undefined;\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout. Declared on the page (not the root\n * // layout) because hero_cta renders only here; see the `components` prop.\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components = [],\n sections,\n slots,\n registrySlotIds: registrySlotIdsProp,\n registrySlots,\n appOrigin,\n searchParams,\n pathname,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n captureAgents,\n nonce,\n children,\n userId,\n serverKey = process.env.SENTIENT_SECRET_KEY,\n ...providerProps\n } = props;\n // Verified identify, signed HERE on the server: the secret key never leaves\n // it, and the hash it yields is useless for any other user id. Without a key\n // the identify still happens, unverified — said once in dev, since a project\n // that signs elsewhere would stop trusting these.\n let identity: AdaptiveProviderProps['identity'];\n if (userId) {\n // `|| undefined`: signUserId returns '' when it refuses (a browser global\n // present) — an empty hash is no hash, not a failed verification.\n identity = { userId, userHash: (serverKey && (await signUserId(userId, serverKey))) || undefined };\n if (!serverKey && process.env.NODE_ENV !== 'production') {\n console.warn('[SentientUI] <AdaptiveRoot userId> without SENTIENT_SECRET_KEY: the identify is unverified. Set the env var (or pass serverKey) to verify it.');\n }\n }\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Landing-URL attribution (utm_* + ad click IDs). Only available when the\n // page passes its searchParams down — headers() never carries the request's\n // own query string, and the Referer is the PREVIOUS page, not this one.\n const { utmParams, clickIds } = extractTrackedParams(searchParams ?? {});\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `consent: false` must gate the SERVER too, not just the client. Without\n // this the SSR decide/assign still ran and still minted a session row for a\n // visitor who had not consented — contradicting the documented contract\n // (\"no SDK is initialised, no cookies are written, no events are sent\") and\n // forcing sites to hide AdaptiveRoot behind a conditional render, which is\n // what made consent-after-load cost a full server round trip.\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n // This is a Server Component and already has the request cookies, so resolve\n // a cookie-based `consentFrom` here rather than making the app read the same\n // cookie again just to pass `consent` — naming it twice only invites drift.\n // An already-consented visitor therefore gets SSR variant assignment (zero\n // layout shift) with no extra code.\n //\n // An explicit `consent` prop always wins — it is the escape hatch for apps\n // that track consent elsewhere. (No `check()` form here: see the prop type.)\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n // The platform's own cookie (Cookiebot CookieConsent, OneTrust\n // OptanonConsent, CookieYes, the TCF string). Unknown (no cookie yet, a\n // JS-only source like Consent Mode) stays undefined → gated below; the\n // browser decides after hydration. A fixed-value cookie comparison could not\n // express Cookiebot's or OneTrust's format, so consented visitors on those\n // platforms were never server-rendered.\n const consent =\n providerProps.consent ??\n (cf ? (consentFromCookies(cf, (name) => rawCookie(headerStore.get('cookie'), name)) ?? undefined) : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n // Keyless local mode, by the client's own rule (core init: a `pk_` key or\n // `localMode: false` means hosted). The browser runs on simulated decisions\n // with no network, but the server still called the hosted API with the\n // empty key — every SSR request logged `session upsert failed (401)` and\n // spent a round trip on a decision the client would never use. Nothing\n // hosted runs server-side either.\n const keyless =\n providerProps.localMode === true ||\n (providerProps.localMode !== false && !(typeof providerProps.apiKey === 'string' && providerProps.apiKey.startsWith('pk_')));\n\n // SSR preload MUST hit the same API host the client will use, otherwise the\n // SSR-minted session lives on the wrong host and the client's first /assign\n // misses it and re-mints — silently breaking SSR→client continuity for any\n // non-default / self-hosted deployment. The client derives its base from\n // apiBaseUrl too (see provider.tsx), so thread the same value here.\n const baseUrl = providerProps.apiBaseUrl\n ? providerProps.apiBaseUrl.replace(/\\/$/, '')\n : DEFAULT_API_BASE_URL;\n\n // Server-side agent-fetch capture (spec: nextjs-agent-fetch-capture). JS-less\n // assistants (GPTBot / ChatGPT-User / Claude-User / PerplexityBot / …) never\n // run client JS, but they trigger SSR — so AdaptiveRoot sees their UA here.\n // Fire-and-forget; never blocks or breaks render. `agentPath` is reused by the\n // agentFeed JSON-LD below.\n const agentPath = agentFeed?.path ?? headerStore.get('x-pathname') ?? '/';\n const agentBot = matchedAgentToken(userAgent ?? '');\n if (!keyless && captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n // SSR-declared components the operator moved onto the shared track: the\n // client renders them as slots (children:false, first variant key = the\n // original) instead of seeding a frozen variant (ruling C20).\n let initialUnified: string[] | undefined;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialSlotConfig: LoadAdaptiveDecisionResult['slotConfig'];\n let initialPalette: LoadAdaptiveDecisionResult['palette'];\n let initialVocabulary: LoadAdaptiveDecisionResult['vocabulary'];\n let initialPersona: { persona: string; confidence: number } | null = null;\n // Opt-in theme attribute: this request's stage, coarsened unless 'detailed'.\n let initialStage: string | null = null;\n let ssrSessionId: string | undefined;\n\n // One decided id list from both props, each id once. The caps come only from\n // `registrySlots` entries: a bare id keeps core's default.\n const registrySlotIds = [...new Set([...(registrySlotIdsProp ?? []), ...(registrySlots ?? []).map((d) => d.id)])];\n // The caps a mounted AdaptiveSlot sends, minus the fingerprint (it needs a\n // DOM).\n // - `ops: false`: React never applies ops (see core's preloadDecisions).\n // - `children: true`: a hybrid's original is a real arm, so the server keeps\n // drawing `baseline` next to `authored.*`. A migrated variants-only\n // component's `children: false` comes from the decide's handed-off path,\n // not from here.\n const renderCaps: Record<string, Omit<RenderCaps, 'fp'>> | undefined = registrySlots?.length\n ? Object.fromEntries(registrySlots.map((d) => [d.id, {\n forms: d.forms ?? true,\n compose: true,\n ops: false,\n ...(d.authored?.length ? { authored: d.authored, children: true } : {}),\n }]))\n : undefined;\n // Registry mode only when ids were declared: an unscoped registry decide\n // records a close-out trial for every published slot on every page.\n const registry = registrySlotIds.length > 0;\n // What both SSR loaders send. One object, so a field added to one loader\n // cannot silently miss the other (the decide and assign paths are the same\n // visit's first request either way).\n const ssrOptions = {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n landingPath: pathname,\n // doNotTrack is deliberately not passed: it is necessarily false wherever\n // these are used — a DNT/GPC or consent-gated request takes the skipSsr\n // arm below and never reaches a loader.\n timeoutMs,\n persona: providerProps.persona,\n internal: providerProps.internal,\n };\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (skipSsr || keyless) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload. Keyless: the client's local engine decides.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0) || registry) {\n // `loadAdaptiveDecision` accepted `registrySlotIds` long before AdaptiveRoot\n // passed them, so an `<Adaptive id>` under AdaptiveRoot showed its original\n // children on first paint until the client-side decide returned.\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n ...(registry ? { slotsFrom: 'registry' as const, registrySlotIds, ...(renderCaps ? { renderCaps } : {}) } : {}),\n ...ssrOptions,\n });\n initialAssignments = decision.assignments;\n initialUnified = decision.unified;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialSlotConfig = decision.slotConfig;\n initialPalette = decision.palette;\n // The site styles the served Redesign trees borrow. Without forwarding\n // them, SSR sites (Bodyshop, 2026-09-24) rendered an approved redesign\n // with no site classes at all — black palette buttons and near-invisible\n // text on a navy card — because the client never re-decides a preloaded\n // slot and so never receives them either.\n initialVocabulary = decision.vocabulary;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n initialStage = exposedStage(decision.stage, providerProps.stageAttributes);\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, ssrOptions);\n initialAssignments = result.assignments;\n initialUnified = result.unified;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n // Not for a request that must not be tracked (DNT/GPC, consent refused or\n // not yet known): with no server decision the script's fallback reads the\n // stored snapshot from localStorage, and reading the device's storage before\n // consent is exactly what a consent gate exists to prevent. The browser SDK\n // takes over once the visitor's platform says yes.\n const personaScript = skipSsr ? null : (\n <SentientPersonaScript\n apiKey={providerProps.apiKey}\n persona={initialPersona}\n nonce={nonce}\n stageAttributes={providerProps.stageAttributes}\n stage={initialStage}\n />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // The same nonce also covers the <style> the client injects (reveal).\n nonce={nonce}\n // Forward the server-resolved value so a consented visitor's client does\n // not start gated and re-resolve the same cookie on mount.\n consent={consent}\n initialAssignments={initialAssignments}\n initialUnified={initialUnified}\n initialLayoutOrder={initialLayoutOrder}\n // Declared regardless of what came back, so devtools can preview layout on\n // a page whose decision was gated or timed out.\n declaredSections={sections}\n initialSlots={initialSlots}\n // Registry-mode preload: the hook treats a preloaded slot config as\n // settled, so the client does not decide the same slot a second time.\n initialSlotConfig={initialSlotConfig}\n initialPalette={initialPalette}\n initialVocabulary={initialVocabulary}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n identity={identity}\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: [\n ...assignmentsToBlocks(initialAssignments),\n // A moved component is not in initialAssignments (it was handed back to\n // be decided as a slot), so without this the JSON-LD dropped it — the\n // hero, for a crawler. Its decided arm, else the control: the first\n // variant key, as the page renders it (children:false).\n ...(initialUnified ?? []).map((id): AgentBlock => {\n const decided = initialSlots?.[id];\n const first = components.find((c) => c.id === id)?.variantIds[0];\n return { id, variant: typeof decided === 'string' ? decided : first !== undefined ? `authored.${first}` : '' };\n }),\n ],\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX } from 'react';\nimport { renderPrePaintScript, type StageAttributes } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n /**\n * The same consent gate you give the provider. With `consent={false}`, or a\n * `consentFrom` source and no `consent={true}`, nothing is rendered: the\n * fallback reads the stored decision from the visitor's device, and that\n * must wait for consent (grader F3). `AdaptiveRoot` handles this for you.\n */\n consent?: boolean;\n consentFrom?: unknown;\n /**\n * Opt-in `data-sentient-stage` (see `AdaptiveProviderProps.stageAttributes`).\n * With a server decision, pass the value to write as `stage` (already\n * coarsened — `exposedStage` from `@sentientui/core`); without one the\n * script copies the stage the visitor's last decide stored.\n */\n stageAttributes?: StageAttributes;\n /** The stage value to write, from this request's decide; null writes none. */\n stage?: string | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n // The stage first, with its own single-writer check: an already-set\n // persona must not stop it. Only a value this request's decide gave.\n (props.stage\n ? 'if(!d.hasAttribute(\"data-sentient-stage\"))d.setAttribute(\"data-sentient-stage\",' + inlineJsString(props.stage) + ');'\n : '') +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey, props.stageAttributes ? { stage: true } : undefined);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element | null {\n // A server-decided persona is not a storage read, so it always renders.\n if (!props.persona && (props.consent === false || (props.consentFrom !== undefined && props.consent !== true))) return null;\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n preloadAssignmentsDetailed,\n readInternalToken,\n readSessionCookie,\n signUserId,\n trackServerGoal,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie, signUserId, trackServerGoal };\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 /** Components the operator moved onto the shared track: not in\n * `assignments`. Pass as `initialUnified` to `<AdaptiveProvider>`. */\n unified: string[];\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\n * `utm_*` params from the landing URL. The Referer header never carries the\n * page's OWN query string, so without this the SSR-minted session has no\n * campaign attribution until the client SDK hydrates and re-upserts.\n * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.\n */\n utmParams?: Record<string, string>;\n /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */\n clickIds?: Record<string, string>;\n /** The landing page's path (no query string) — recognises a paid click to a product page or a `/discount/` link on the first decision. */\n landingPath?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n /**\n * Your team / a test site — the same flag as `<AdaptiveProvider internal>`,\n * sent on the SSR upsert and decide so a server-rendered first page is\n * never counted or learned from. The request's `sentient_internal` cookie\n * (the \"mark this browser\" link) is read from `cookies` and forwarded too.\n */\n internal?: boolean;\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 // With the unified cap: a moved component is not assigned (nothing is\n // recorded) and comes back in `unified`, so the page renders it on the\n // shared track instead of seeding the frozen variant it would otherwise get.\n const { assignments, unified } = await preloadAssignmentsDetailed(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n internal: options.internal,\n internalToken: readInternalToken(options.cookies),\n }, { unified: true });\n\n return { assignments, sessionId, unified };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render, keyed by slot id\n * (see `preloadDecisions`). Ids without an entry get core's default caps.\n * A hybrid `<Adaptive variants>{children}</Adaptive>` needs its entry: the\n * server draws `authored.<key>` only for keys the page declares here.\n */\n renderCaps?: Record<string, Omit<import('@sentientui/core').RenderCaps, 'fp'>>;\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, readInternalToken } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n ...(options.renderCaps ? { renderCaps: options.renderCaps } : {}),\n // Moved components come back in `unified`, not as assignments (see\n // loadAdaptiveAssignments). Pass them as `initialUnified`.\n unifiedCaps: true,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n internal: options.internal,\n internalToken: readInternalToken(options.cookies),\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"+lBAAA,OAAS,wBAAAA,GAAsB,gBAAAC,GAAc,wBAAAC,GAAsB,qBAAAC,OAAyB,mBAC5F,OAAS,sBAAAC,OAA0B,2BACnC,OAAS,cAAAC,OAAkB,0BAE3B,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCDjC,OAAS,wBAAAC,OAAkD,mBAC3D,OAAS,kBAAAC,OAAsB,qBA4E3B,cAAAC,OAAA,oBAvCJ,SAASC,EAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAAK,EAAE,QAAQ,KAAM,SAAS,CACtD,CAGO,SAASC,GAAkBC,EAA2C,CAC3E,OAAIA,EAAM,QAEN,mDAGCA,EAAM,MACH,kFAAoFH,EAAeG,EAAM,KAAK,EAAI,KAClH,IACJ,4FAC4CH,EAAeG,EAAM,QAAQ,OAAO,EAAI,+CACrCH,EAAeF,GAAeK,EAAM,QAAQ,UAAU,CAAC,EAAI,qBAIvGN,GAAqBM,EAAM,OAAQA,EAAM,gBAAkB,CAAE,MAAO,EAAK,EAAI,MAAS,CAC/F,CAcO,SAASC,GAAsBD,EAAuD,CAE3F,MAAI,CAACA,EAAM,UAAYA,EAAM,UAAY,IAAUA,EAAM,cAAgB,QAAaA,EAAM,UAAY,IAAe,KAErHJ,GAAC,UACC,+BAA6B,GAC7B,MAAOI,EAAM,MACb,wBAAyB,CAAE,OAAQD,GAAkBC,CAAK,CAAE,EAC9D,CAEJ,CCnFA,OACE,sB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A,EAAsB,OACnC,QAASpC,EAAU,OACrB,CAAC,EAED,OACEhC,GAAAF,GAAA,CACG,UAAAyF,GACDxF,EAAC,UACC,KAAK,sBACL,MAAOmC,EACP,wBAAyB,CAAE,OAAQ+D,GAAsBL,EAAI,CAAE,EACjE,EACCH,IACH,CAEJ","names":["deriveSessionSegment","exposedStage","extractTrackedParams","matchedAgentToken","consentFromCookies","signUserId","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","preloadAssignmentsDetailed","readInternalToken","readSessionCookie","signUserId","trackServerGoal","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","assignments","unified","preloadAssignmentsDetailed","readInternalToken","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","rawCookie","header","name","part","eq","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","components","sections","slots","registrySlotIdsProp","registrySlots","appOrigin","searchParams","pathname","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","userId","serverKey","providerProps","__objRest","identity","signUserId","headerStore","headers","host","resolvedOrigin","userAgent","referer","utmParams","clickIds","extractTrackedParams","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","consentFromCookies","skipSsr","keyless","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialUnified","initialLayoutOrder","initialSlots","initialSlotConfig","initialPalette","initialVocabulary","initialPersona","initialStage","ssrSessionId","registrySlotIds","d","renderCaps","__spreadValues","registry","ssrOptions","decision","loadAdaptiveDecision","exposedStage","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","__spreadProps","feed","buildAgentFeed","decided","first","c","renderAgentJsonLdBody"]}
1
+ {"version":3,"sources":["../../src/next/adaptive-root.tsx","../../src/persona-script.tsx","../../src/server.ts","../../src/agent-feed.ts","../../src/next/log-agent-fetch.ts","../../src/next/agent-feed-route.ts"],"sourcesContent":["import { deriveSessionSegment, exposedStage, extractTrackedParams, matchedAgentToken } from '@sentientui/core';\nimport { consentFromCookies } from '@sentientui/core/consent';\nimport { signUserId } from '@sentientui/core/server';\nimport type { RenderCaps, SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX, ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type LoadAdaptiveDecisionResult,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\n// Re-exported from core on the SERVER entry (this module is server-only — it\n// imports next/headers). Lets server components do agent detection with just the\n// `@sentientui/react` package, no direct core dependency. Do NOT add this to the\n// package's client index: re-exporting a plain function through a 'use client'\n// module turns it into a client reference that throws when called during SSR.\nexport { matchedAgentToken, uaTokenMatch, agentIntent, classifiedAgents } from '@sentientui/core';\nexport type { AgentIntent } from '@sentientui/core';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\n/** A registry `<Adaptive id>` declared with what it can render — see `AdaptiveRootProps.registrySlots`. */\nexport type RegistrySlotDecl = {\n id: string;\n /** The `variants` keys of a hybrid `<Adaptive variants>{children}</Adaptive>`. */\n authored?: string[];\n /** The `<Adaptive>` has an `onFormSubmit`. @default true */\n forms?: boolean;\n};\n\nexport type AdaptiveRootProps = Omit<\n AdaptiveProviderProps,\n // Every provider prop AdaptiveRoot itself resolves and passes AFTER the\n // {...providerProps} spread must be omitted here: a caller-supplied value\n // would typecheck but be silently clobbered by the spread order\n // (initialLayoutOrder, declaredSections and sessionSegment were missing\n // from this list and suffered exactly that).\n | 'initialAssignments'\n | 'onAssignment'\n | 'initialSlots'\n | 'initialSlotConfig'\n | 'initialPalette'\n | 'initialVocabulary'\n | 'initialPersona'\n | 'initialLayoutOrder'\n | 'declaredSections'\n | 'sessionSegment'\n | 'consentFrom'\n | 'identity'\n> & {\n /**\n * Consent source — see `AdaptiveProviderProps.consentFrom`. A platform preset\n * (`'cookiebot'`, `'onetrust'`, `'cookieyes'`, `'tcf'`, `'google-consent-mode'`)\n * or a cookie. Resolved on the server from the platform's own cookie, so a\n * visitor who already consented gets SSR with no layout shift.\n *\n * No `check` form: AdaptiveRoot is a Server Component and spreads\n * this straight into its client boundary, and a function prop crossing the\n * server→client boundary throws at render (\"Functions cannot be passed\n * directly to Client Components\"). The provider's type accepted `check`, so\n * a Cookiebot-style predicate typechecked here and then crashed the layout.\n * Need a JS-API CMP predicate? Use `<AdaptiveProvider>` in a client component.\n */\n consentFrom?: Exclude<NonNullable<AdaptiveProviderProps['consentFrom']>, { check?: () => boolean; cmp?: undefined }> | { cmp?: undefined; cookie?: string; value?: string; event?: string };\n /**\n * Code-variant components to assign server-side (SEO-safe). Optional — an\n * `<Adaptive>` works without an entry here and assigns after mount.\n *\n * List only ids this tree actually renders. Each one is assigned on every\n * request, rendered or not, and every assignment logs an impression (or a\n * holdout exposure). An id the page never renders therefore accrues trials\n * that cannot convert, and in a root layout that happens on every route.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * Give each section's rendered element `data-sentient-id=\"<sectionId>\"` —\n * the only markup a section needs — so the DOM graph scanner can register\n * it under the same id. Without it the server never learns what the section\n * IS, types it `generic`, and serves the identity order to every persona —\n * the integration looks live but cannot personalize. The provider warns\n * about unresolvable ids in development. Correct a section the content\n * classifier mistypes with `sectionTypes`, not extra markup.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n * // …and in the tree: <section data-sentient-id=\"pricing\">\n */\n sections?: string[];\n /**\n * Adaptive-slot declarations used by `useAdaptiveTokens` / `AdaptiveGroup`\n * in this tree. Declaring them here decides them in the same SSR\n * round trip, so their values serialize into the server HTML.\n */\n slots?: SlotDeclInput[];\n /**\n * The generated-mode `<Adaptive id>`s THIS page renders. Declaring them\n * decides their published versions in the same SSR round trip\n * (`/v1/decide` registry mode) and serializes the served content into the\n * server HTML, so the first paint shows the version rather than the\n * original children until the client-side decide answers. Without it a\n * registry slot renders its children first and swaps after mount.\n *\n * Scoped to exactly these ids on purpose: an unscoped registry decide\n * records a close-out trial for every published slot on every page.\n *\n * @example registrySlotIds={['hero-headline', 'pricing-cta']}\n */\n registrySlotIds?: string[];\n /**\n * Like `registrySlotIds`, for `<Adaptive id>`s that need to tell the server\n * more than their id. Most often that is a hybrid —\n * `<Adaptive id variants={{ a, b }}>{original}</Adaptive>`. List its\n * `variants` keys as `authored`, or the SSR decide cannot draw them. In that\n * case the first paint can only be the original or a generated version, and\n * the hand-written ones appear only on pages the browser decides.\n *\n * `forms`: whether the `<Adaptive>` has an `onFormSubmit`. Declare\n * `forms: false` when it has none, or SSR can draw a generated form version\n * that the page then refuses. The default is `true`, the same as a bare\n * `registrySlotIds` entry.\n *\n * You may list an id in both props: it is decided once, with these caps.\n *\n * @example registrySlots={[{ id: 'hero_cta', authored: ['action', 'social'], forms: false }]}\n */\n registrySlots?: RegistrySlotDecl[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /**\n * The page's `searchParams` prop (or an equivalent query string /\n * URLSearchParams). Server Components cannot read the request URL from\n * `headers()`, so without this the SSR-minted session carries no `utm_*`\n * params and no ad click IDs (gclid, fbclid, ttclid, …) — campaign\n * attribution only lands after client hydration, and never for visits the\n * client SDK doesn't get to finish (bounce before hydrate). Pass it on\n * landing pages that receive ad traffic:\n *\n * ```tsx\n * export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {\n * return <AdaptiveRoot ... searchParams={await searchParams}>...</AdaptiveRoot>;\n * }\n * ```\n */\n searchParams?: Record<string, string | string[] | undefined> | URLSearchParams | string;\n /**\n * The page's path (e.g. `/products/trail-shoe`). Server components cannot\n * read their own URL, so pass it on landing pages that receive ad or email\n * traffic: with it, a paid click to a product page or a `/discount/` link\n * is recognised on the server render — adapted from the first byte.\n */\n pathname?: string;\n /** Override: when set no network fetch is made. Useful for tests. */\n initialAssignments?: ServerAssignments;\n /**\n * Milliseconds to wait for the API before rendering default variants.\n * Defaults to 1000. The hot path typically returns in well under 150 ms;\n * the full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host. Lower it if your API is\n * co-located and warm.\n */\n timeoutMs?: number;\n /**\n * When set, AdaptiveRoot emits a server-rendered inline JSON-LD block\n * describing the page's winning variants, layout order, and developer-supplied\n * content — readable by passive AI crawlers (which do not run JS). Invisible to\n * humans (a JSON-LD script renders no visible DOM). Omit to emit nothing.\n */\n agentFeed?: {\n /** Page path for the feed. Falls back to the `x-pathname` request header, then '/'. */\n path?: string;\n /** Structured page content. Falls back to the `defineAgentContent` registry for this path. */\n content?: Record<string, unknown>;\n };\n /**\n * When true (default), a known AI-agent fetch (matched by user-agent —\n * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side\n * to your agent analytics. Machine telemetry only (no cookie, no session);\n * fire-and-forget, never affects render. Set false to opt out.\n */\n captureAgents?: boolean;\n /**\n * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.\n * Pass through from Next.js middleware / `headers()` when using a strict CSP.\n */\n nonce?: string;\n /**\n * The signed-in user's id (null/undefined when signed out). AdaptiveRoot\n * signs it on the server and identifies the visitor as that user — a\n * VERIFIED identify, so `trackServerGoal({ userId })` from your backend\n * reaches this visit and nobody else's.\n */\n userId?: string | null;\n /** Secret key used to sign `userId`. Defaults to `process.env.SENTIENT_SECRET_KEY`. Server-only. */\n serverKey?: string;\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * A cookie's value exactly as the browser sent it. The CMP parsers need the\n * raw form: Next's cookies() decodes every value, which turns an encoded\n * `&groups=C0002:1` inside OneTrust's `landingPath` (a crafted link, before\n * any answer) into a real field that read as consent on the server — SSR\n * then minted a session and handed the client consent={true} (grader R8 NEW-1).\n * First match wins, like the browser's document.cookie read. A consent cookie\n * set only by middleware in this request is not in the header: the server\n * then reads \"unknown\" and the browser decides (fail-closed).\n */\nfunction rawCookie(header: string | null | undefined, name: string): string | undefined {\n if (!header) return undefined;\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq > 0 && part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();\n }\n return undefined;\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout. Declared on the page (not the root\n * // layout) because hero_cta renders only here; see the `components` prop.\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components = [],\n sections,\n slots,\n registrySlotIds: registrySlotIdsProp,\n registrySlots,\n appOrigin,\n searchParams,\n pathname,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n captureAgents,\n nonce,\n children,\n userId,\n serverKey = process.env.SENTIENT_SECRET_KEY,\n ...providerProps\n } = props;\n // Verified identify, signed HERE on the server: the secret key never leaves\n // it, and the hash it yields is useless for any other user id. Without a key\n // the identify still happens, unverified — said once in dev, since a project\n // that signs elsewhere would stop trusting these.\n let identity: AdaptiveProviderProps['identity'];\n if (userId) {\n // `|| undefined`: signUserId returns '' when it refuses (a browser global\n // present) — an empty hash is no hash, not a failed verification.\n identity = { userId, userHash: (serverKey && (await signUserId(userId, serverKey))) || undefined };\n if (!serverKey && process.env.NODE_ENV !== 'production') {\n console.warn('[SentientUI] <AdaptiveRoot userId> without SENTIENT_SECRET_KEY: the identify is unverified. Set the env var (or pass serverKey) to verify it.');\n }\n }\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Landing-URL attribution (utm_* + ad click IDs). Only available when the\n // page passes its searchParams down — headers() never carries the request's\n // own query string, and the Referer is the PREVIOUS page, not this one.\n const { utmParams, clickIds } = extractTrackedParams(searchParams ?? {});\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `consent: false` must gate the SERVER too, not just the client. Without\n // this the SSR decide/assign still ran and still minted a session row for a\n // visitor who had not consented — contradicting the documented contract\n // (\"no SDK is initialised, no cookies are written, no events are sent\") and\n // forcing sites to hide AdaptiveRoot behind a conditional render, which is\n // what made consent-after-load cost a full server round trip.\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n // This is a Server Component and already has the request cookies, so resolve\n // a cookie-based `consentFrom` here rather than making the app read the same\n // cookie again just to pass `consent` — naming it twice only invites drift.\n // An already-consented visitor therefore gets SSR variant assignment (zero\n // layout shift) with no extra code.\n //\n // An explicit `consent` prop always wins — it is the escape hatch for apps\n // that track consent elsewhere. (No `check()` form here: see the prop type.)\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n // The platform's own cookie (Cookiebot CookieConsent, OneTrust\n // OptanonConsent, CookieYes, the TCF string). Unknown (no cookie yet, a\n // JS-only source like Consent Mode) stays undefined → gated below; the\n // browser decides after hydration. A fixed-value cookie comparison could not\n // express Cookiebot's or OneTrust's format, so consented visitors on those\n // platforms were never server-rendered.\n const consent =\n providerProps.consent ??\n (cf ? (consentFromCookies(cf, (name) => rawCookie(headerStore.get('cookie'), name)) ?? undefined) : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n // Keyless local mode, by the client's own rule (core init: a `pk_` key or\n // `localMode: false` means hosted). The browser runs on simulated decisions\n // with no network, but the server still called the hosted API with the\n // empty key — every SSR request logged `session upsert failed (401)` and\n // spent a round trip on a decision the client would never use. Nothing\n // hosted runs server-side either.\n const keyless =\n providerProps.localMode === true ||\n (providerProps.localMode !== false && !(typeof providerProps.apiKey === 'string' && providerProps.apiKey.startsWith('pk_')));\n\n // SSR preload MUST hit the same API host the client will use, otherwise the\n // SSR-minted session lives on the wrong host and the client's first /assign\n // misses it and re-mints — silently breaking SSR→client continuity for any\n // non-default / self-hosted deployment. The client derives its base from\n // apiBaseUrl too (see provider.tsx), so thread the same value here.\n const baseUrl = providerProps.apiBaseUrl\n ? providerProps.apiBaseUrl.replace(/\\/$/, '')\n : DEFAULT_API_BASE_URL;\n\n // Server-side agent-fetch capture (spec: nextjs-agent-fetch-capture). JS-less\n // assistants (GPTBot / ChatGPT-User / Claude-User / PerplexityBot / …) never\n // run client JS, but they trigger SSR — so AdaptiveRoot sees their UA here.\n // Fire-and-forget; never blocks or breaks render. `agentPath` is reused by the\n // agentFeed JSON-LD below.\n const agentPath = agentFeed?.path ?? headerStore.get('x-pathname') ?? '/';\n const agentBot = matchedAgentToken(userAgent ?? '');\n if (!keyless && captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n // SSR-declared components the operator moved onto the shared track: the\n // client renders them as slots (children:false, first variant key = the\n // original) instead of seeding a frozen variant (ruling C20).\n let initialUnified: string[] | undefined;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialSlotConfig: LoadAdaptiveDecisionResult['slotConfig'];\n let initialPalette: LoadAdaptiveDecisionResult['palette'];\n let initialVocabulary: LoadAdaptiveDecisionResult['vocabulary'];\n let initialPersona: { persona: string; confidence: number } | null = null;\n // Opt-in theme attribute: this request's stage, coarsened unless 'detailed'.\n let initialStage: string | null = null;\n let ssrSessionId: string | undefined;\n\n // One decided id list from both props, each id once. The caps come only from\n // `registrySlots` entries: a bare id keeps core's default.\n const registrySlotIds = [...new Set([...(registrySlotIdsProp ?? []), ...(registrySlots ?? []).map((d) => d.id)])];\n // The caps a mounted AdaptiveSlot sends, minus the fingerprint (it needs a\n // DOM).\n // - `ops: false`: React never applies ops (see core's preloadDecisions).\n // - `children: true`: a hybrid's original is a real arm, so the server keeps\n // drawing `baseline` next to `authored.*`. A migrated variants-only\n // component's `children: false` comes from the decide's handed-off path,\n // not from here.\n const renderCaps: Record<string, Omit<RenderCaps, 'fp'>> | undefined = registrySlots?.length\n ? Object.fromEntries(registrySlots.map((d) => [d.id, {\n forms: d.forms ?? true,\n compose: true,\n ops: false,\n ...(d.authored?.length ? { authored: d.authored, children: true } : {}),\n }]))\n : undefined;\n // Registry mode only when ids were declared: an unscoped registry decide\n // records a close-out trial for every published slot on every page.\n const registry = registrySlotIds.length > 0;\n // What both SSR loaders send. One object, so a field added to one loader\n // cannot silently miss the other (the decide and assign paths are the same\n // visit's first request either way).\n const ssrOptions = {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n landingPath: pathname,\n // doNotTrack is deliberately not passed: it is necessarily false wherever\n // these are used — a DNT/GPC or consent-gated request takes the skipSsr\n // arm below and never reaches a loader.\n timeoutMs,\n persona: providerProps.persona,\n internal: providerProps.internal,\n };\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (skipSsr || keyless) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload. Keyless: the client's local engine decides.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0) || registry) {\n // `loadAdaptiveDecision` accepted `registrySlotIds` long before AdaptiveRoot\n // passed them, so an `<Adaptive id>` under AdaptiveRoot showed its original\n // children on first paint until the client-side decide returned.\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n ...(registry ? { slotsFrom: 'registry' as const, registrySlotIds, ...(renderCaps ? { renderCaps } : {}) } : {}),\n ...ssrOptions,\n });\n initialAssignments = decision.assignments;\n initialUnified = decision.unified;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialSlotConfig = decision.slotConfig;\n initialPalette = decision.palette;\n // The site styles the served Redesign trees borrow. Without forwarding\n // them, SSR sites (Bodyshop, 2026-09-24) rendered an approved redesign\n // with no site classes at all — black palette buttons and near-invisible\n // text on a navy card — because the client never re-decides a preloaded\n // slot and so never receives them either.\n initialVocabulary = decision.vocabulary;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n initialStage = exposedStage(decision.stage, providerProps.stageAttributes);\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, ssrOptions);\n initialAssignments = result.assignments;\n initialUnified = result.unified;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n // Not for a request that must not be tracked (DNT/GPC, consent refused or\n // not yet known): with no server decision the script's fallback reads the\n // stored snapshot from localStorage, and reading the device's storage before\n // consent is exactly what a consent gate exists to prevent. The browser SDK\n // takes over once the visitor's platform says yes.\n const personaScript = skipSsr ? null : (\n <SentientPersonaScript\n apiKey={providerProps.apiKey}\n persona={initialPersona}\n nonce={nonce}\n stageAttributes={providerProps.stageAttributes}\n stage={initialStage}\n />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // The same nonce also covers the <style> the client injects (reveal).\n nonce={nonce}\n // Forward the server-resolved value so a consented visitor's client does\n // not start gated and re-resolve the same cookie on mount.\n consent={consent}\n initialAssignments={initialAssignments}\n initialUnified={initialUnified}\n initialLayoutOrder={initialLayoutOrder}\n // Declared regardless of what came back, so devtools can preview layout on\n // a page whose decision was gated or timed out.\n declaredSections={sections}\n initialSlots={initialSlots}\n // Registry-mode preload: the hook treats a preloaded slot config as\n // settled, so the client does not decide the same slot a second time.\n initialSlotConfig={initialSlotConfig}\n initialPalette={initialPalette}\n initialVocabulary={initialVocabulary}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n identity={identity}\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: [\n ...assignmentsToBlocks(initialAssignments),\n // A moved component is not in initialAssignments (it was handed back to\n // be decided as a slot), so without this the JSON-LD dropped it — the\n // hero, for a crawler. Its decided arm, else the control: the first\n // variant key, as the page renders it (children:false).\n ...(initialUnified ?? []).map((id): AgentBlock => {\n const decided = initialSlots?.[id];\n const first = components.find((c) => c.id === id)?.variantIds[0];\n return { id, variant: typeof decided === 'string' ? decided : first !== undefined ? `authored.${first}` : '' };\n }),\n ],\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX } from 'react';\nimport { renderPrePaintScript, type StageAttributes } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n /**\n * The same consent gate you give the provider. With `consent={false}`, or a\n * `consentFrom` source and no `consent={true}`, nothing is rendered: the\n * fallback reads the stored decision from the visitor's device, and that\n * must wait for consent (grader F3). `AdaptiveRoot` handles this for you.\n */\n consent?: boolean;\n consentFrom?: unknown;\n /**\n * Opt-in `data-sentient-stage` (see `AdaptiveProviderProps.stageAttributes`).\n * With a server decision, pass the value to write as `stage` (already\n * coarsened — `exposedStage` from `@sentientui/core`); without one the\n * script copies the stage the visitor's last decide stored.\n */\n stageAttributes?: StageAttributes;\n /** The stage value to write, from this request's decide; null writes none. */\n stage?: string | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n // The stage first, with its own single-writer check: an already-set\n // persona must not stop it. Only a value this request's decide gave.\n (props.stage\n ? 'if(!d.hasAttribute(\"data-sentient-stage\"))d.setAttribute(\"data-sentient-stage\",' + inlineJsString(props.stage) + ');'\n : '') +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey, props.stageAttributes ? { stage: true } : undefined);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element | null {\n // A server-decided persona is not a storage read, so it always renders.\n if (!props.persona && (props.consent === false || (props.consentFrom !== undefined && props.consent !== true))) return null;\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n preloadAssignmentsDetailed,\n readInternalToken,\n readSessionCookie,\n signUserId,\n trackServerGoal,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie, signUserId, trackServerGoal };\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 /** Components the operator moved onto the shared track: not in\n * `assignments`. Pass as `initialUnified` to `<AdaptiveProvider>`. */\n unified: string[];\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\n * `utm_*` params from the landing URL. The Referer header never carries the\n * page's OWN query string, so without this the SSR-minted session has no\n * campaign attribution until the client SDK hydrates and re-upserts.\n * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.\n */\n utmParams?: Record<string, string>;\n /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */\n clickIds?: Record<string, string>;\n /** The landing page's path (no query string) — recognises a paid click to a product page or a `/discount/` link on the first decision. */\n landingPath?: string;\n /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n /**\n * Your team / a test site — the same flag as `<AdaptiveProvider internal>`,\n * sent on the SSR upsert and decide so a server-rendered first page is\n * never counted or learned from. The request's `sentient_internal` cookie\n * (the \"mark this browser\" link) is read from `cookies` and forwarded too.\n */\n internal?: boolean;\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 // With the unified cap: a moved component is not assigned (nothing is\n // recorded) and comes back in `unified`, so the page renders it on the\n // shared track instead of seeding the frozen variant it would otherwise get.\n const { assignments, unified } = await preloadAssignmentsDetailed(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n internal: options.internal,\n internalToken: readInternalToken(options.cookies),\n }, { unified: true });\n\n return { assignments, sessionId, unified };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render, keyed by slot id\n * (see `preloadDecisions`). Ids without an entry get core's default caps.\n * A hybrid `<Adaptive variants>{children}</Adaptive>` needs its entry: the\n * server draws `authored.<key>` only for keys the page declares here.\n */\n renderCaps?: Record<string, Omit<import('@sentientui/core').RenderCaps, 'fp'>>;\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, readInternalToken } = 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 (Vite: VITE_SENTIENT_API_KEY) or localMode: true.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n ...(options.renderCaps ? { renderCaps: options.renderCaps } : {}),\n // Moved components come back in `unified`, not as assignments (see\n // loadAdaptiveAssignments). Pass them as `initialUnified`.\n unifiedCaps: true,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n landingPath: options.landingPath,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n internal: options.internal,\n internalToken: readInternalToken(options.cookies),\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"+lBAAA,OAAS,wBAAAA,GAAsB,gBAAAC,GAAc,wBAAAC,GAAsB,qBAAAC,OAAyB,mBAC5F,OAAS,sBAAAC,OAA0B,2BACnC,OAAS,cAAAC,OAAkB,0BAE3B,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCDjC,OAAS,wBAAAC,OAAkD,mBAC3D,OAAS,kBAAAC,OAAsB,qBA4E3B,cAAAC,OAAA,oBAvCJ,SAASC,EAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAAK,EAAE,QAAQ,KAAM,SAAS,CACtD,CAGO,SAASC,GAAkBC,EAA2C,CAC3E,OAAIA,EAAM,QAEN,mDAGCA,EAAM,MACH,kFAAoFH,EAAeG,EAAM,KAAK,EAAI,KAClH,IACJ,4FAC4CH,EAAeG,EAAM,QAAQ,OAAO,EAAI,+CACrCH,EAAeF,GAAeK,EAAM,QAAQ,UAAU,CAAC,EAAI,qBAIvGN,GAAqBM,EAAM,OAAQA,EAAM,gBAAkB,CAAE,MAAO,EAAK,EAAI,MAAS,CAC/F,CAcO,SAASC,GAAsBD,EAAuD,CAE3F,MAAI,CAACA,EAAM,UAAYA,EAAM,UAAY,IAAUA,EAAM,cAAgB,QAAaA,EAAM,UAAY,IAAe,KAErHJ,GAAC,UACC,+BAA6B,GAC7B,MAAOI,EAAM,MACb,wBAAyB,CAAE,OAAQD,GAAkBC,CAAK,CAAE,EAC9D,CAEJ,CCnFA,O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,KAAAA,EAAsB,OACnC,QAASpC,EAAU,OACrB,CAAC,EAED,OACEhC,GAAAF,GAAA,CACG,UAAAyF,GACDxF,EAAC,UACC,KAAK,sBACL,MAAOmC,EACP,wBAAyB,CAAE,OAAQ+D,GAAsBL,EAAI,CAAE,EACjE,EACCH,IACH,CAEJ","names":["deriveSessionSegment","exposedStage","extractTrackedParams","matchedAgentToken","consentFromCookies","signUserId","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","preloadAssignmentsDetailed","readInternalToken","readSessionCookie","signUserId","trackServerGoal","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","assignments","unified","preloadAssignmentsDetailed","readInternalToken","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","rawCookie","header","name","part","eq","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","components","sections","slots","registrySlotIdsProp","registrySlots","appOrigin","searchParams","pathname","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","userId","serverKey","providerProps","__objRest","identity","signUserId","headerStore","headers","host","resolvedOrigin","userAgent","referer","utmParams","clickIds","extractTrackedParams","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","consentFromCookies","skipSsr","keyless","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialUnified","initialLayoutOrder","initialSlots","initialSlotConfig","initialPalette","initialVocabulary","initialPersona","initialStage","ssrSessionId","registrySlotIds","d","renderCaps","__spreadValues","registry","ssrOptions","decision","loadAdaptiveDecision","exposedStage","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","__spreadProps","feed","buildAgentFeed","decided","first","c","renderAgentJsonLdBody"]}
@@ -0,0 +1,123 @@
1
+ import * as _sentientui_core from '@sentientui/core';
2
+ import * as _sentientui_core_server from '@sentientui/core/server';
3
+ import { ServerAssignments } from '@sentientui/core/server';
4
+ export { DecideResult, ServerAssignConfig, ServerAssignments, SlotDeclInput, SlotResult, preloadAssignments, preloadDecisions, readSessionCookie, signUserId, trackServerGoal } from '@sentientui/core/server';
5
+
6
+ /** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */
7
+ type LoadAdaptiveAssignmentsResult = {
8
+ assignments: ServerAssignments;
9
+ /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */
10
+ sessionId: string;
11
+ /** Components the operator moved onto the shared track: not in
12
+ * `assignments`. Pass as `initialUnified` to `<AdaptiveProvider>`. */
13
+ unified: string[];
14
+ };
15
+ type LoadAdaptiveAssignmentsOptions = {
16
+ /** Next.js `cookies()` return value, or any object with `get(name)`. */
17
+ cookies: {
18
+ get(name: string): {
19
+ value: string;
20
+ } | undefined;
21
+ };
22
+ apiKey: string;
23
+ baseUrl: string;
24
+ /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */
25
+ createSessionId?: () => string;
26
+ /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */
27
+ origin?: string;
28
+ /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */
29
+ userAgent?: string;
30
+ /** From Next.js `headers().get('referer')`. */
31
+ referer?: string;
32
+ /**
33
+ * `utm_*` params from the landing URL. The Referer header never carries the
34
+ * page's OWN query string, so without this the SSR-minted session has no
35
+ * campaign attribution until the client SDK hydrates and re-upserts.
36
+ * Derive with `extractTrackedParams(searchParams)` from `@sentientui/core/server`.
37
+ */
38
+ utmParams?: Record<string, string>;
39
+ /** Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL — same derivation as `utmParams`. */
40
+ clickIds?: Record<string, string>;
41
+ /** The landing page's path (no query string) — recognises a paid click to a product page or a `/discount/` link on the first decision. */
42
+ landingPath?: string;
43
+ /** 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. */
44
+ doNotTrack?: boolean;
45
+ /** 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). */
46
+ timeoutMs?: number;
47
+ /**
48
+ * Declared persona — the role your app already knows for this visitor (e.g.
49
+ * from your auth context: 'admin', 'evaluator'). Must be a key in the
50
+ * project's persona vocabulary; unrecognized values are ignored server-side.
51
+ * Never a user id or email.
52
+ */
53
+ persona?: string;
54
+ /**
55
+ * Your team / a test site — the same flag as `<AdaptiveProvider internal>`,
56
+ * sent on the SSR upsert and decide so a server-rendered first page is
57
+ * never counted or learned from. The request's `sentient_internal` cookie
58
+ * (the "mark this browser" link) is read from `cookies` and forwarded too.
59
+ */
60
+ internal?: boolean;
61
+ };
62
+ /**
63
+ * Fetches bandit assignments on the server for SEO-safe HTML.
64
+ * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`
65
+ * on `<AdaptiveProvider>` so the client adopts the same session on first visit.
66
+ */
67
+ declare function loadAdaptiveAssignments(components: Array<{
68
+ id: string;
69
+ variantIds: string[];
70
+ }>, options: LoadAdaptiveAssignmentsOptions): Promise<LoadAdaptiveAssignmentsResult>;
71
+
72
+ /** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */
73
+ type LoadAdaptiveDecisionResult = _sentientui_core_server.DecideResult & {
74
+ sessionId: string;
75
+ };
76
+ type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {
77
+ /**
78
+ * Section IDs in default order. Passed to /v1/decide as the candidate
79
+ * layout. Optional since 0.13.0 — slot-only pages may omit it (at least
80
+ * one of `sections`/`components`/`slots` must be non-empty).
81
+ */
82
+ sections?: string[];
83
+ /** Components to assign in the same decide call. */
84
+ components?: Array<{
85
+ id: string;
86
+ variantIds?: string[];
87
+ }>;
88
+ /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */
89
+ slots?: _sentientui_core_server.SlotDeclInput[];
90
+ /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)
91
+ * and is the only way `slotConfig`/`palette` come back. Default 'request'.
92
+ * Requires `registrySlotIds`. */
93
+ slotsFrom?: 'request' | 'registry';
94
+ /**
95
+ * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is
96
+ * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it
97
+ * the call downgrades to request mode (with a console.error) instead of
98
+ * recording a close-out trial for every published slot on every page.
99
+ */
100
+ registrySlotIds?: string[];
101
+ /**
102
+ * Registry mode: what each slot on this page can render, keyed by slot id
103
+ * (see `preloadDecisions`). Ids without an entry get core's default caps.
104
+ * A hybrid `<Adaptive variants>{children}</Adaptive>` needs its entry: the
105
+ * server draws `authored.<key>` only for keys the page declares here.
106
+ */
107
+ renderCaps?: Record<string, Omit<_sentientui_core.RenderCaps, 'fp'>>;
108
+ };
109
+ /**
110
+ * SSR helper for pages with a declared section layout and/or adaptive slots.
111
+ * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.
112
+ * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client
113
+ * adopts the same session on first visit.
114
+ *
115
+ * Keyless: with no valid `pk_` key this never fetches (no timeout burn).
116
+ * Under the `development` export condition the decision is computed by the
117
+ * deterministic local engine with the same sessionId the client will adopt —
118
+ * server and client agree by construction. In production the engine resolves
119
+ * to a stub and defaults are returned with one console.error.
120
+ */
121
+ declare function loadAdaptiveDecision(options: LoadAdaptiveDecisionOptions): Promise<LoadAdaptiveDecisionResult>;
122
+
123
+ export { type LoadAdaptiveAssignmentsOptions, type LoadAdaptiveAssignmentsResult, type LoadAdaptiveDecisionOptions, type LoadAdaptiveDecisionResult, loadAdaptiveAssignments, loadAdaptiveDecision };