@sentientui/react 0.35.2 → 0.35.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.
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
"use strict";var er=Object.create;var Ce=Object.defineProperty,tr=Object.defineProperties,nr=Object.getOwnPropertyDescriptor,rr=Object.getOwnPropertyDescriptors,ir=Object.getOwnPropertyNames,Le=Object.getOwnPropertySymbols,or=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty,kt=Object.prototype.propertyIsEnumerable;var wt=(e,t,n)=>t in e?Ce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))Ye.call(t,n)&&wt(e,n,t[n]);if(Le)for(var n of Le(t))kt.call(t,n)&&wt(e,n,t[n]);return e},I=(e,t)=>tr(e,rr(t));var De=(e,t)=>{var n={};for(var r in e)Ye.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Le)for(var r of Le(e))t.indexOf(r)<0&&kt.call(e,r)&&(n[r]=e[r]);return n};var sr=(e,t)=>{for(var n in t)Ce(e,n,{get:t[n],enumerable:!0})},Rt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ir(t))!Ye.call(e,i)&&i!==n&&Ce(e,i,{get:()=>t[i],enumerable:!(r=nr(t,i))||r.enumerable});return e};var Qe=(e,t,n)=>(n=e!=null?er(or(e)):{},Rt(t||!e||!e.__esModule?Ce(n,"default",{value:e,enumerable:!0}):n,e)),ar=e=>Rt(Ce({},"__esModule",{value:!0}),e);var Tr={};sr(Tr,{Adaptive:()=>On,AdaptiveGroup:()=>Wn,AdaptiveProvider:()=>Zt,AdaptiveSlot:()=>Pe,AdaptiveText:()=>En,SentientPersonaScript:()=>In,buildAgentFeed:()=>Xn,defineAgentContent:()=>Hn,detectSegment:()=>yt.deriveSessionSegment,getAgentContent:()=>vt,grantConsent:()=>Zn.grantConsent,renderAgentJsonLd:()=>zn,renderAgentJsonLdBody:()=>St,renderAgentMarkdown:()=>qn,renderBlocks:()=>ge,renderCompose:()=>We,useAdaptive:()=>Kn,useAdaptiveApiBaseUrl:()=>sn,useAdaptiveGoal:()=>ze,useAdaptivePersona:()=>Fn,useAdaptiveTokens:()=>Bn,useAssignment:()=>je,useInitialAssignments:()=>Ve,useLayoutOrder:()=>en,usePageGoal:()=>Gn,useSentient:()=>N});module.exports=ar(Tr);var C=require("react"),Ne=require("@sentientui/core");var At=new Map,Ie=new Map;function Ct(e,t){let n=Ie.get(e);return n||(n=new Set,Ie.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&Ie.delete(e)}}function _t(e,t){At.set(e,t);let n=Ie.get(e);if(n)for(let r of n)try{r(t)}catch(i){}}function et(e){var t;return(t=At.get(e))!=null?t:null}var lr={on:!1,listeners:new Set};function Ot(){if(typeof window=="undefined")return lr;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function tt(){return Ot().on}function Et(e){let t=Ot().listeners;return t.add(e),()=>{t.delete(e)}}function Pt(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,r,i)=>e.assign(t,n,r,i),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var nt="sentient:overrides-changed";function Gt(){var e;return typeof window=="undefined"?0:(e=window.__sentient_overrides_version)!=null?e:0}function rt(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(nt))}function J(e){return typeof window=="undefined"?()=>{}:(window.addEventListener(nt,e),()=>window.removeEventListener(nt,e))}function Tt(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function T(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}function U(e){return typeof e=="string"?{type:"click"}:e}function se(e){return typeof e=="string"?e:e.type}function ee(e){if(typeof e!="string"&&(e.type==="click"||e.type==="form_submit"||e.type==="scroll_depth"))return e.value}var it=new Set,ot=!1;function Lt(e){if(it.has(e))return!0;if(it.add(e),!ot){ot=!0;let t=()=>{ot=!1,it.clear()};if(typeof MessageChannel=="function"){let n=new MessageChannel;n.port1.onmessage=()=>{n.port1.close(),n.port2.close(),t()},n.port2.postMessage(0)}else setTimeout(t,0)}return!1}function ur(e){if(!(e instanceof Element))return!1;let t=e.tagName.toLowerCase();return t==="a"||t==="button"?!0:e.getAttribute("role")==="button"}function Dt(e,t,n){if(n){try{let i=e;for(;i&&i!==t;){if(i.matches(n))return!0;i=i.parentElement}}catch(i){}return!1}let r=e;for(;r&&r!==t;){if(ur(r))return!0;r=r.parentElement}return!1}function te(e,t,n,r){if(t.type==="weighted_composite"){let s=new Set,y=[];return t.steps.forEach(({goal:f,name:h,weight:R},c)=>{let u=(p=!1)=>{s.has(c)||p&&r!==void 0&&Lt(`step\0${h}\0${R}\0${c}`)||(s.add(c),n.fireStep(h,R,c))};if(f.type==="click"){let p=g=>{let a=g.target;a instanceof Element&&Dt(a,e,f.selector)&&u()};e.addEventListener("click",p),y.push(()=>e.removeEventListener("click",p));return}if(f.type==="form_submit"){let p=g=>{g.target instanceof HTMLFormElement&&e.contains(g.target)&&u()};e.addEventListener("submit",p),y.push(()=>e.removeEventListener("submit",p));return}if(f.type==="scroll_depth"){let p=Math.max(0,Math.min(1,f.threshold)),g=new IntersectionObserver(a=>{for(let S of a)if(S.intersectionRatio>=p){u(!0),g.disconnect();break}},{threshold:[p]});g.observe(e),y.push(()=>g.disconnect())}}),()=>{for(let f of y)f()}}let i=t.type==="composite"?t.all:[t],l=new Set(i.map((s,y)=>y)),d=()=>{r!==void 0&&Lt(r)||n.fireGoal()},o=(s,y=!1)=>{l.delete(s),l.size===0&&(y?d():n.fireGoal())},m=[];return i.forEach((s,y)=>{if(s.type==="click"){let f=h=>{let R=h.target;R instanceof Element&&Dt(R,e,s.selector)&&(t.type==="composite"?o(y):n.fireGoal())};e.addEventListener("click",f),m.push(()=>e.removeEventListener("click",f));return}if(s.type==="form_submit"){let f=h=>{h.target instanceof HTMLFormElement&&e.contains(h.target)&&(t.type==="composite"?o(y):n.fireGoal())};e.addEventListener("submit",f),m.push(()=>e.removeEventListener("submit",f));return}if(s.type==="scroll_depth"){let f=Math.max(0,Math.min(1,s.threshold)),h=new IntersectionObserver(R=>{for(let c of R)if(c.intersectionRatio>=f){t.type==="composite"?o(y,!0):d(),h.disconnect();break}},{threshold:[f]});h.observe(e),m.push(()=>h.disconnect());return}}),()=>{for(let s of m)s()}}var It=new Set,Nt=new Set;function ye(e,t,n,r,i){let l=`${r}|${n}`;if(Nt.has(l))return;Nt.add(l);let d=i.type==="weighted_composite"&&!It.has(r);d&&It.add(r),e.track({projectId:t,componentId:n,eventType:"funnel_declared",payload:d?{funnelId:r,steps:i.steps.map(o=>({goalId:o.name,weight:o.weight}))}:{funnelId:r}})}function ae(e,t,n,r){e.track({projectId:t,componentId:n,variantId:r,eventType:"variant_assigned",payload:{}})}var cr={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function de(){if(typeof window=="undefined")return cr;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function _e(){de().version+=1;for(let e of de().listeners)e()}var Vt=()=>{};function Ft(e){return T()?(de().components.set(e.id,e),_e(),()=>{de().components.delete(e.id),_e()}):Vt}function ve(e){return T()?(de().slots.set(e.id,e),_e(),()=>{de().slots.delete(e.id),_e()}):Vt}function st(e){T()&&(de().sections=[...e],_e())}var Mt="0.35.2",at=Mt!=="0.0.0-dev"?{name:"react",version:Mt}:void 0;function dr(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function Se(e,t){dr()[e]=t}function $t(e){window.__sentient_vocabulary_override=e}function Bt(){var e;return typeof window=="undefined"?null:(e=window.__sentient_vocabulary_override)!=null?e:null}function fr(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function he(e,t){fr()[e]=t}var jt="sentient_editor",Kt="sentient_preview_cell",Wt="sentient_refresh_region",lt="sentient-cell-preview-bar",fe="__preview__",be=null;function Jt(e){if((be==null?void 0:be.slotId)!==e)return null;let t=be;return be=null,t}function Ut(e,t){fetch(`${e.base}/editor/region-skeleton`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json"},body:JSON.stringify(v({slotId:e.slotId},t))}).then(n=>xe(n.ok?"Region refreshed \u2014 you can regenerate its versions now.":"Couldn\u2019t refresh this region \u2014 reopen the link from your dashboard.")).catch(()=>xe("Couldn\u2019t refresh this region \u2014 check your connection and reopen the link from your dashboard."))}function Ht(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(lt))return;let t,n,r;try{let m=new URLSearchParams(window.location.search);t=m.get(jt),n=m.get(Kt),r=m.get(Wt)}catch(m){return}if(t&&r){be={slotId:r,token:t,base:(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"")},Se(r,{kind:"arms"}),he(r,fe),rt();return}if(!t||!n)return;let i=n.lastIndexOf("~");if(i<=0)return;let l=n.slice(0,i),d=n.slice(i+1),o=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");fetch(`${o}/editor/cell-preview?slotId=${encodeURIComponent(l)}&persona=${encodeURIComponent(d)}`,{headers:{authorization:`Bearer ${t}`}}).then(async m=>{if(!m.ok){xe(m.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let s=await m.json();if(s.vocabulary&&Array.isArray(s.vocabulary.entries)&&$t(s.vocabulary),s.compose!=null)Se(l,{kind:"arms",compose:{[fe]:s.compose}}),he(l,fe);else if(s.edits!=null&&typeof s.skeletonFp=="string"&&Array.isArray(s.leafToNode))Se(l,{kind:"arms",edits:{edits:s.edits,fp:s.skeletonFp,leafToNode:s.leafToNode}}),he(l,fe);else if(s.blocks!=null)Se(l,{kind:"arms",blocks:{[fe]:s.blocks}}),he(l,fe);else if(s.content!=null)Se(l,{kind:"arms",content:s.content}),he(l,fe);else{xe("Nothing to preview in that square yet.");return}rt(),xe(`Previewing \u201C${s.slotName}\u201D for ${s.personaDisplay}${s.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var y;try{(y=document.querySelector(`[data-sentient-slot="${l}"]`))==null||y.scrollIntoView({block:"center"})}catch(f){}},300)}).catch(()=>xe("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function xe(e){var i;if(document.getElementById(lt))return;let t=document.createElement("div");t.id=lt,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let r=document.createElement("button");r.textContent="Exit preview",Object.assign(r.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),r.onclick=()=>{let l=new URL(window.location.href);l.searchParams.delete(jt),l.searchParams.delete(Kt),l.searchParams.delete(Wt),window.location.assign(l.toString())},t.append(n,r),((i=document.body)!=null?i:document.documentElement).append(t)}var gr="sentient_editor",Xt=!1;function zt(e){if(Xt||typeof window=="undefined")return;let t=null;try{t=new URLSearchParams(window.location.search).get(gr)}catch(i){return}if(!t)return;Xt=!0;let n=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),r=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:i})=>fetch(`${n}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(i(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?r():window.addEventListener("load",r,{once:!0})}var an=require("react/jsx-runtime");function mr(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return(0,Ne.deriveSessionSegment)({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var qt="https://api.sentient-ui.com/v1",B=(0,C.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:qt,debug:!1});function pr(e){let[t,n]=(0,C.useState)(!1),r=(0,C.useRef)(e);r.current=e;let{cookie:i,value:l,event:d}=e!=null?e:{},o=typeof(e==null?void 0:e.check)=="function";return(0,C.useEffect)(()=>{let m=()=>{var h;let y=r.current;if(!y)return!1;if(y.check)return y.check()===!0;if(!y.cookie||typeof document=="undefined")return!1;let f=`${y.cookie}=${(h=y.value)!=null?h:"accepted"}`;return document.cookie.split("; ").some(R=>R.trim()===f)};if(n(m()),!d)return;let s=()=>{n(m())};return window.addEventListener(d,s),()=>window.removeEventListener(d,s)},[i,l,d,o]),t}function Zt(e){var c,u;let[t,n]=(0,C.useState)(null),[r]=(0,C.useState)(()=>{var p;return(p=e.sessionSegment)!=null?p:mr()}),[i,l]=(0,C.useState)(tt());(0,C.useEffect)(()=>Et(()=>l(tt())),[]),(0,C.useEffect)(()=>{Ht(e.apiBaseUrl),zt(e.apiBaseUrl)},[]);let d=pr(e.consentFrom),o=e.consentFrom?e.consent===!0||d:e.consent,m=(0,C.useRef)(null);(0,C.useEffect)(()=>{var A;if(o===!1&&!e.preConsentBehavior){(A=m.current)==null||A.destroy(),m.current=null,n(null);return}let p=v({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:r,consent:o,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},at?{sdk:at}:{}),g=!1,a=null,S=null,x=E=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:b})=>{g||(S=b(E,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:E})=>{g||(a=E(I(v({},p),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),m.current=a,n(a),x(a))}):(a=(0,Ne.init)(p),m.current=a,n(a),x(a)),()=>{g=!0,S==null||S(),a==null||a.dispose()}},[o]),(0,C.useEffect)(()=>{if(!t)return;let p=!1,g=async()=>{if(p)return;let S;try{S=await t.fetchWeights()}catch(x){return}if(!p)for(let x of S){let A={componentId:x.componentId,updatedAt:x.updatedAt,variants:x.variants.map(E=>{var b;return{variantId:E.variantId,pulls:E.pulls,avgReward:(b=E.avgReward)!=null?b:0}})};_t(x.componentId,A)}};g();let a=setInterval(()=>{g()},6e4);return()=>{p=!0,clearInterval(a)}},[t]);let s=(c=e.ssrFallback)!=null?c:"first",y=((u=e.apiBaseUrl)!=null?u:qt).replace(/\/$/,""),f=(0,C.useRef)(null);(0,C.useEffect)(()=>{var a;if(typeof process!="undefined"&&((a=process.env)==null?void 0:a.NODE_ENV)==="production")return;let p={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:y},g=f.current;if(f.current=p,g!==null)for(let S of["apiKey","context","country","persona","apiBaseUrl"])Object.is(g[S],p[S])||console.warn(`[sentient] AdaptiveProvider: \`${S}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,y]),(0,C.useEffect)(()=>{var p;typeof process!="undefined"&&((p=process.env)==null?void 0:p.NODE_ENV)==="production"||Tt({apiKey:e.apiKey,apiBaseUrl:y,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,y]),(0,C.useEffect)(()=>{let p=e.initialLayoutOrder;if(p&&p.length>0){st(p);return}e.declaredSections&&e.declaredSections.length>0&&st(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),(0,C.useEffect)(()=>{if(!T())return;let p=e.declaredSections;if(!p||p.length===0||typeof document=="undefined")return;let g=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),S=>S.getAttribute("data-sentient-id"))),a=p.filter(S=>!g.has(S));a.length>0&&console.warn(`[SentientUI] Declared section${a.length>1?"s":""} ${a.map(S=>`"${S}"`).join(", ")} ${a.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let h=(0,C.useMemo)(()=>t&&i?Pt(t):t,[t,i]),R=(0,C.useMemo)(()=>{var p,g,a,S,x,A,E,b;return{client:h,apiKey:e.apiKey,initialAssignments:(p=e.initialAssignments)!=null?p:{},sessionSegment:r,ssrFallback:s,onAssignment:e.onAssignment,initialLayoutOrder:(g=e.initialLayoutOrder)!=null?g:null,initialSlots:(a=e.initialSlots)!=null?a:{},initialSlotConfig:(S=e.initialSlotConfig)!=null?S:{},initialPalette:(x=e.initialPalette)!=null?x:null,initialVocabulary:(A=e.initialVocabulary)!=null?A:null,initialPersona:(E=e.initialPersona)!=null?E:null,apiBaseUrl:y,debug:(b=e.debug)!=null?b:!1}},[h,e.apiKey,e.initialAssignments,r,s,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,y,e.debug]);return(0,an.jsx)(B.Provider,{value:R,children:e.children})}function N(){return(0,C.useContext)(B).client}function ne(){return(0,C.useContext)(B).apiKey}function Ve(){return(0,C.useContext)(B).initialAssignments}function Fe(){return(0,C.useContext)(B).sessionSegment}function Yt(){return(0,C.useContext)(B).ssrFallback}function Me(){return(0,C.useContext)(B).onAssignment}function Qt(){return(0,C.useContext)(B).debug}function en(){let e=(0,C.useContext)(B).initialLayoutOrder,t=(0,C.useSyncExternalStore)(J,()=>{var n;return typeof window=="undefined"?null:(n=window.__sentient_layout_override)!=null?n:null},()=>null);return t!=null?t:e}function $e(){return(0,C.useContext)(B).initialSlots}function tn(){return(0,C.useContext)(B).initialPersona}function nn(){return(0,C.useContext)(B).initialSlotConfig}function rn(){return(0,C.useContext)(B).initialPalette}function on(){return(0,C.useContext)(B).initialVocabulary}function sn(){return(0,C.useContext)(B).apiBaseUrl}var ke=require("react");var V=require("react"),ln=require("@sentientui/core");var H=require("react"),Be=require("@sentientui/policy");function we(e){var n;if(typeof window=="undefined")return null;let t=(n=window.__sentient_overrides)==null?void 0:n[e];if(t)return t;if(!window.location.search)return null;try{let r=new URLSearchParams(window.location.search);for(let i of r.getAll("sentient_variant")){let l=i.indexOf(":");if(l!==-1&&i.slice(0,l)===e)return i.slice(l+1)}}catch(r){}return null}function je(e,t,n,r){let i=Ve(),l=Yt(),d=N(),o=Fe(),m=Me(),s=Qt(),y=(0,H.useRef)(null),f=(0,H.useSyncExternalStore)(J,()=>we(e),()=>null),h=f&&t.includes(f)?f:null,R=(0,H.useRef)(null);(0,H.useEffect)(()=>{s&&h&&R.current!==h&&(R.current=h,console.info(`[sentient] override active: ${e} -> ${h}`))},[s,h,e]);let[c,u]=(0,H.useState)(()=>{var S,x;if(h)return{variantId:h,content:null,isLoading:!1,settled:!0};if(!d){let A=i[e];return A&&t.includes(A)?{variantId:A,content:null,isLoading:!1,settled:!0}:l==="first"&&t.length>0?{variantId:t[0],content:null,isLoading:!1,settled:!1}:{variantId:null,content:null,isLoading:!0,settled:!1}}let g=d.getAssignment(e,o);if(g&&(t.includes(g.variantId)||g.content))return{variantId:g.variantId,content:(S=g.content)!=null?S:null,isLoading:!1,settled:!0};let a=et(e);if(a){let A=(0,Be.pickFromWeights)(a.variants,t);if(A)return{variantId:A,content:null,isLoading:!1,settled:!0}}return{variantId:(x=t[0])!=null?x:null,content:null,isLoading:!1,settled:!1}}),p=g=>{m&&y.current!==g&&(y.current=g,m(e,g))};return(0,H.useEffect)(()=>{var S;if(h||!d)return;let g=d.getAssignment(e,o);if(g&&(t.includes(g.variantId)||g.content)){u({variantId:g.variantId,content:(S=g.content)!=null?S:null,isLoading:!1,settled:!0}),p(g.variantId);return}let a=et(e);if(a&&c.settled&&c.variantId&&c.variantId===(0,Be.pickFromWeights)(a.variants,t)){p(c.variantId);return}u(x=>{var A;return x.variantId?x:{variantId:(A=t[0])!=null?A:null,content:null,isLoading:!1,settled:!1}})},[h,d,e,o]),(0,H.useEffect)(()=>{if(h||!d)return;let g=d.getAssignment(e,o);if(g&&t.includes(g.variantId))return;let a=!1;return d.assign(e,t,n,r).then(S=>{var x;a||S&&(!t.includes(S.variantId)&&!S.content||(u({variantId:S.variantId,content:(x=S.content)!=null?x:null,isLoading:!1,settled:!0}),p(S.variantId)))}),()=>{a=!0}},[h,d,e,o]),(0,H.useEffect)(()=>{if(!h&&d)return Ct(e,g=>{var x;let a=d.getAssignment(e,o);if(a&&(t.includes(a.variantId)||a.content)){u({variantId:a.variantId,content:(x=a.content)!=null?x:null,isLoading:!1,settled:!0}),p(a.variantId);return}let S=(0,Be.pickFromWeights)(g.variants,t);S&&(u({variantId:S,content:null,isLoading:!1,settled:!0}),p(S))})},[h,d,e,o]),h?{variantId:h,content:null,isLoading:!1,settled:!0,isOverride:!0}:c}function Ke(e,t,n){let r=N(),i=ne(),l=Object.keys(t).join("\0"),d=(0,V.useMemo)(()=>Object.keys(t),[l]),{variantId:o,content:m,isOverride:s=!1,settled:y}=je(e,d,n.agentData,n.agentDataByVariant),[f,h]=(0,V.useState)(null),R=(0,V.useRef)(null),c=(0,V.useCallback)(O=>{R.current=O,h(O)},[]),u=n.goal,p=typeof u=="string"?u:JSON.stringify(u),g=(0,V.useMemo)(()=>u?U(u):null,[p]),a=u?se(u):"";(0,V.useEffect)(()=>Ft({id:e,variantIds:d,goal:a}),[e,d,a]);let S=(0,V.useRef)(null);(0,V.useEffect)(()=>{s||y&&(!r||!o||!i||!f||S.current!==o&&(S.current=o,ae(r,i,e,o)))},[r,o,i,e,f,s,y]);let x=(0,V.useRef)(!1),A=(0,V.useRef)(new Set);(0,V.useEffect)(()=>{x.current=!1,A.current=new Set},[o,g]);let E=n.funnel;(0,V.useEffect)(()=>{s||!y||!r||!E||!g||ye(r,i,e,E,g)},[r,i,e,E,g,s,y]);let b=n.cursorSignal===!0;(0,V.useEffect)(()=>{if(!b||s||!y||!r||!o||!f)return;let O=null,P=0,M=()=>{P=Date.now(),O=setTimeout(()=>{r.track({projectId:i,componentId:e,variantId:o,eventType:"cursor_signal",payload:{hoverDuration:Date.now()-P}}),O=null},800)},D=()=>{O!==null&&(clearTimeout(O),O=null)};return f.addEventListener("mouseenter",M),f.addEventListener("mouseleave",D),()=>{f.removeEventListener("mouseenter",M),f.removeEventListener("mouseleave",D),O!==null&&clearTimeout(O)}},[b,r,o,i,e,f,s,y]);let k=(0,V.useRef)(n.microSignalGoals);k.current=n.microSignalGoals;let w=n.microSignalGoals?JSON.stringify(n.microSignalGoals):"";return(0,V.useEffect)(()=>{if(s||!y||!r||!o||!f)return;let O=Date.now();return(0,ln.attachMicroSignalDetectors)((P,M={})=>{var oe,ue,Y;r.track({projectId:i,componentId:e,variantId:o,eventType:"micro_signal",payload:v({signalType:P},M)});let D=(oe=k.current)==null?void 0:oe[P];if(!D||A.current.has(P))return;A.current.add(P);let q=typeof D=="string"?D:D.name,Z=typeof D=="string"?1:(ue=D.weight)!=null?ue:1,ie=typeof D=="string"?0:(Y=D.stepIndex)!=null?Y:0;r.goal(q,{metadata:v({signalType:P},M),weight:Z,stepIndex:ie})},f,O)},[r,o,i,e,f,w,s,y]),(0,V.useEffect)(()=>{if(s||!y||!r||!o||!f||!g)return;let O=ee(g);return te(f,g,{fireGoal:()=>{x.current||(x.current=!0,r.track({projectId:i,componentId:e,variantId:o,eventType:"goal_achieved",goalType:a,payload:v({reward:1},O!==void 0?{goalValue:O}:{})}),r.goal(a,v({metadata:{componentId:e,variantId:o},weight:1,stepIndex:0},O!==void 0?{value:O}:{})))},fireStep:(P,M,D)=>{r.track({projectId:i,componentId:e,variantId:o,eventType:"goal_achieved",goalType:P,payload:{reward:M}}),r.goal(P,{metadata:{},weight:M,stepIndex:D})}},a)},[r,o,i,e,f,g,a,s,y]),{client:r,variantIds:d,variantId:o,content:m,settled:y,isOverride:s,goalLabel:a,ref:c,nodeRef:R}}var F=require("react"),Ee=require("@sentientui/core"),pt=require("@sentientui/core/region");var K=require("react"),cn=require("@sentientui/core");var un=new Set;function dn(e,t){var x,A,E;let n=N(),r=(0,K.useRef)(t==null?void 0:t.baselineText);r.current=t==null?void 0:t.baselineText;let i=(0,K.useRef)(t==null?void 0:t.render);i.current=t==null?void 0:t.render;let l=(0,K.useRef)(t==null?void 0:t.skeleton);l.current=t==null?void 0:t.skeleton;let d=$e(),o=nn(),m=rn(),s=on(),y=(0,K.useSyncExternalStore)(J,()=>{var b;return typeof window!="undefined"?(b=window.__sentient_slot_config_overrides)==null?void 0:b[e]:void 0},()=>{}),f=(0,K.useSyncExternalStore)(J,()=>{var b;return typeof window!="undefined"?(b=window.__sentient_slot_overrides)==null?void 0:b[e]:void 0},()=>{}),h=b=>b==null?"":(0,cn.armOfResult)(b),R=(0,K.useCallback)(b=>{var k,w;return(w=(k=n==null?void 0:n.onSlotsChanged)==null?void 0:k.call(n,b))!=null?w:(()=>{})},[n]);(0,K.useSyncExternalStore)(R,()=>{var b;return(b=n==null?void 0:n.getSlotConfig(e))!=null?b:null},()=>null),(0,K.useSyncExternalStore)(R,()=>h(n==null?void 0:n.getSlotResult(e)),()=>"");let c=y===void 0?o[e]:void 0,u=y===void 0&&c===void 0&&n?n.getSlotConfig(e):null,p=(x=m!=null?m:n==null?void 0:n.getSitePalette())!=null?x:null,g=(E=s!=null?s:(A=n==null?void 0:n.getStyleVocabulary)==null?void 0:A.call(n))!=null?E:null,a=(()=>{var b,k,w;if(y!==void 0)return{config:y,arm:h(f),palette:p,vocabulary:(b=Bt())!=null?b:g,source:"override"};if(c!==void 0)return{config:c,arm:h((k=d[e])!=null?k:n==null?void 0:n.getSlotResult(e)),palette:p,vocabulary:g,source:"preloaded"};if(u!==null){let O=n!=null&&n.isSlotDecided?n.isSlotDecided(e):!0;return{config:u,arm:h((w=n==null?void 0:n.getSlotResult(e))!=null?w:d[e]),palette:p,vocabulary:g,source:O?"client":"seeded"}}return{config:null,arm:"",palette:p,vocabulary:g,source:"none"}})(),S=a.source==="preloaded"||a.source==="override";return(0,K.useEffect)(()=>{var q,Z,ie,oe,ue;if(!n||n.isLocal===!0||S)return;let b=a.source==="none",k=b&&(Z=(q=r.current)==null?void 0:q.call(r))!=null?Z:null,w=k!=null&&k!==""?{[e]:k}:void 0,O=(ie=i.current)==null?void 0:ie.call(i),P=b&&(ue=(oe=l.current)==null?void 0:oe.call(l))!=null?ue:null,M=v(v({},O?{render:{[e]:O}}:{}),P?{skeletons:{[e]:P}}:{}),D=Object.keys(M).length>0;return n.requestSlots?D?n.requestSlots([e],w,M):w?n.requestSlots([e],w):n.requestSlots([e]):b&&(P?n.reportSlots([e],w!=null?w:{},{[e]:P}):w?n.reportSlots([e],w):n.reportSlots([e])),()=>{var Y;return(Y=n.cancelSlots)==null?void 0:Y.call(n,[e])}},[n,S,a.source,e]),(0,K.useEffect)(()=>{!T()||(n==null?void 0:n.isLocal)!==!0||a.source!=="none"||un.has(e)||(un.add(e),console.warn(`[sentient] <Adaptive id="${e}"> is rendering its baseline children: in local/keyless mode <Adaptive> serves ONLY what you pass as \`initialSlotConfig\` (there is no registry to decide from). Pass initialSlotConfig/initialSlots to <AdaptiveProvider> to preview arms locally.`))},[n,a.source,e]),a}var Oe=require("react");var L=require("react/jsx-runtime"),le={none:"0",sm:"8px",md:"16px",lg:"24px"},ut={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch",between:"space-between"},pn={sm:"0.875em",md:"1em",lg:"1.25em"},yr={sm:"1.25em",md:"1.5em",lg:"2em"},fn={sm:"6px 14px",md:"10px 20px",lg:"14px 28px"},gn={sm:"8px",md:"16px",lg:"32px"},vr={square:"1 / 1",landscape:"4 / 3",wide:"16 / 9"},Sr={normal:"400",medium:"500",bold:"700"};function mn(e,t){return v(v({},e==="muted"?t!=null&&t.muted?{color:t.muted}:{opacity:.7}:{}),e==="accent"?v({fontWeight:600},t!=null&&t.accent?{color:t.accent}:{}):{})}function yn(e,t,n){var i,l,d,o;let r=t==null?void 0:t.accent;return I(v({display:"inline-block",padding:(i=fn[n!=null?n:"md"])!=null?i:fn.md,borderRadius:(l=t==null?void 0:t.radius)!=null?l:"8px",font:"inherit"},n?{fontSize:pn[n]}:{}),{textDecoration:e==="ghost"?"underline":"none",cursor:"pointer",background:e==="primary"?(d=t==null?void 0:t.primaryBg)!=null?d:"#111827":"transparent",color:e==="primary"?(o=t==null?void 0:t.primaryText)!=null?o:"#ffffff":r!=null?r:"inherit",border:e==="secondary"?`1px solid ${r!=null?r:"currentColor"}`:"none"})}function hr({node:e,opts:t}){var i,l,d,o,m;let n=(i=e.emphasis)!=null?i:"primary",r={padding:"8px 10px",font:"inherit",border:`1px solid ${(d=(l=t.palette)==null?void 0:l.border)!=null?d:"currentColor"}`,borderRadius:(m=(o=t.palette)==null?void 0:o.radius)!=null?m:"8px"};return(0,L.jsxs)("form",{onSubmit:s=>{var h,R,c;s.preventDefault();let y=new FormData(s.currentTarget),f={};for(let u of e.fields)f[u.name]=String((h=y.get(u.name))!=null?h:"");(R=t.onFormGoal)==null||R.call(t,e.submitGoal);try{(c=t.onFormSubmit)==null||c.call(t,f)}catch(u){}},style:{display:"flex",flexDirection:"column",gap:"12px"},children:[e.fields.map(s=>{var y,f;return(0,L.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"4px",font:"inherit"},children:[s.label,s.kind==="textarea"?(0,L.jsx)("textarea",{name:s.name,required:s.required,placeholder:s.placeholder,rows:3,style:r}):s.kind==="select"?(0,L.jsx)("select",{name:s.name,required:s.required,style:r,children:((y=s.options)!=null?y:[]).map(h=>(0,L.jsx)("option",{value:h,children:h},h))}):(0,L.jsx)("input",{name:s.name,type:(f=s.inputType)!=null?f:"text",required:s.required,placeholder:s.placeholder,style:r})]},s.name)}),(0,L.jsx)("button",{type:"submit",style:yn(n,t.palette),children:e.submitLabel})]})}function br(e,t){var r,i;let n=e.like;return n?(i=(r=t.vocabulary)==null?void 0:r.entries.find(l=>l.id===n))==null?void 0:i.classes:void 0}function vn(e,t){var r;let n=e?(r=t.vocabulary)==null?void 0:r.entries.find(i=>i.id===e):void 0;return n!=null&&n.computed.inheritsColor?n.computed.color:void 0}function ge(e,t){var i;let n=xr(e,t),r=vn(e.like,t);return n&&r?(0,Oe.cloneElement)(n,{style:I(v({},(i=n.props.style)!=null?i:{}),{color:r})}):n}function xr(e,t){var n,r,i,l,d,o,m,s,y,f,h,R,c,u,p,g,a,S,x,A,E,b,k;try{let w=br(e,t);switch(e.type){case"stack":{let O=(r=le[(n=e.gap)!=null?n:"md"])!=null?r:le.md,P=e.surface==="raised"&&!w,M=(i=e.pad)!=null?i:P?"md":void 0;return(0,L.jsx)("div",I(v({},w?{className:w}:{}),{style:v(v(v(v(v({display:"flex",flexDirection:e.direction,gap:O},e.align?{alignItems:ut[e.align]}:{}),e.justify?{justifyContent:ut[e.justify]}:{}),e.wrap?{flexWrap:"wrap"}:{}),M?{padding:(l=le[M])!=null?l:le.md}:{}),P?I(v(v({},(d=t.palette)!=null&&d.surface?{background:t.palette.surface}:{}),(o=t.palette)!=null&&o.surface&&((m=t.palette)!=null&&m.surfaceText)?{color:t.palette.surfaceText}:{}),{border:`1px solid ${(y=(s=t.palette)==null?void 0:s.border)!=null?y:"currentColor"}`,borderRadius:(h=(f=t.palette)==null?void 0:f.radius)!=null?h:"8px"}):{}),children:((R=e.children)!=null?R:[]).map((D,q)=>{let Z=ge(D,t);return Z===null?null:(0,L.jsx)(Oe.Fragment,{children:Z},q)})}))}case"grid":{let O=(u=le[(c=e.gap)!=null?c:"md"])!=null?u:le.md;return(0,L.jsx)("div",I(v({},w?{className:w}:{}),{style:v(v({display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(max(200px, calc((100% - ${e.columns-1} * ${O}) / ${e.columns})), 1fr))`,gap:O},e.align?{alignItems:ut[e.align]}:{}),e.pad?{padding:(p=le[e.pad])!=null?p:le.md}:{}),children:((g=e.children)!=null?g:[]).map((P,M)=>{let D=ge(P,t);return D===null?null:(0,L.jsx)(Oe.Fragment,{children:D},M)})}))}case"text":return w?(0,L.jsx)("p",{className:w,style:e.maxWidth==="measure"?{maxWidth:"65ch"}:void 0,children:e.value}):(0,L.jsx)("p",{style:v(v(v(v(v({margin:0},e.size?{fontSize:pn[e.size]}:{}),e.weight?{fontWeight:Sr[e.weight]}:{}),e.align?{textAlign:e.align}:{}),e.maxWidth==="measure"?{maxWidth:"65ch"}:{}),mn(e.tone,t.palette)),children:e.value});case"heading":{let O=`h${e.level}`;return w?(0,L.jsx)(O,{className:w,style:e.maxWidth==="measure"?{maxWidth:"65ch"}:void 0,children:e.value}):(0,L.jsx)(O,{style:v(v({margin:0,fontSize:yr[(a=e.size)!=null?a:"md"]},e.align?{textAlign:e.align}:{}),e.maxWidth==="measure"?{maxWidth:"65ch"}:{}),children:e.value})}case"button":{let O=(S=e.emphasis)!=null?S:"primary";return(0,L.jsx)("a",I(v(v({href:e.href},e.tag?{"data-sentient-tag":e.tag}:{}),w?{className:w}:{style:yn(O,t.palette,e.size)}),{children:e.label}))}case"link":return(0,L.jsx)("a",I(v(v({href:e.href},e.tag?{"data-sentient-tag":e.tag}:{}),w?{className:w}:{style:{color:"inherit",textDecoration:"underline"}}),{children:e.label}));case"image":return(0,L.jsx)("img",I(v({src:e.src,alt:e.alt},w?{className:w}:{}),{style:v(v({display:"block",maxWidth:"100%"},e.ratio&&e.ratio!=="auto"?{aspectRatio:vr[e.ratio],width:"100%"}:{}),e.fit?{objectFit:e.fit}:{})}));case"badge":return w?(0,L.jsx)("span",{className:w,children:e.value}):(0,L.jsx)("span",{style:v({display:"inline-block",padding:"2px 10px",borderRadius:"999px",fontSize:"0.75em",border:`1px solid ${(A=(x=t.palette)==null?void 0:x.border)!=null?A:"currentColor"}`},mn(e.tone,t.palette)),children:e.value});case"spacer":return(0,L.jsx)("div",{style:{height:(E=gn[e.size])!=null?E:gn.md}});case"divider":return(0,L.jsx)("hr",{style:{border:"none",borderTop:`1px solid ${(k=(b=t.palette)==null?void 0:b.border)!=null?k:"currentColor"}`,margin:0,width:"100%"}});case"form":return(0,L.jsx)(hr,{node:e,opts:t});default:return null}}catch(w){return null}}function We(e,t){var l,d,o,m;let n=ge(e.tree,t);if(n===null)return null;let r=(l=e.surface)!=null&&l.like?(o=(d=t.vocabulary)==null?void 0:d.entries.find(s=>s.id===e.surface.like))==null?void 0:o.classes:void 0,i=vn((m=e.surface)==null?void 0:m.like,t);return r?(0,L.jsx)("div",I(v({className:r},i?{style:{color:i}}:{}),{children:n})):n}var re=require("react"),Je=require("@sentientui/core/region");function Ue(e){return typeof e=="string"&&e.trim()!==""||typeof e=="number"}function He(e){let t=e.props;if(t.dangerouslySetInnerHTML==null)return t.children}function me(e){return Ue(e)?1:Array.isArray(e)?e.reduce((t,n)=>t+me(n),0):(0,re.isValidElement)(e)?me(He(e)):0}function wr(e,t){return Array.isArray(t)?(0,re.cloneElement)(e,void 0,...t):(0,re.cloneElement)(e,void 0,t)}function ct(e,t){if(Ue(e))return t;if(Array.isArray(e))return e.map(n=>ct(n,t));if((0,re.isValidElement)(e)){let n=He(e);return me(n)===0?e:wr(e,ct(n,t))}return e}function Sn(e,t){return me(e)===1?ct(e,t):null}var W=e=>e.join("/");function dt(e,t,n){if(Ue(e)){n.leafPaths.push(t),n.texts.push((0,Je.normalizeLeafText)(String(e)));return}if(Array.isArray(e)){e.forEach((r,i)=>dt(r,[...t,i],n));return}(0,re.isValidElement)(e)&&(n.elements.set(W(t),e),dt(He(e),[...t,"c"],n))}function gt(e){let t={leafPaths:[],texts:[],elements:new Map};return dt(e,[],t),t}function kr(e){return gt(e).texts}function hn(e){let t=kr(e);return t.length===0?null:(0,Je.skeletonFingerprint)(t)}function Rr(e){let t=[];return e.forEach((n,r)=>{n==="c"&&t.push(e.slice(0,r))}),t}function bn(e,t){let n=t.reduce((i,l)=>Math.max(i,l+1),0),r=[];for(let i=0;i<n;i++){let l=t.flatMap((o,m)=>o===i?[Rr(e.leafPaths[m])]:[]);if(l.length===0){r.push(null);continue}let d=l[0];for(let o of l.slice(1)){let m=new Set(o.map(W));d=d.filter(s=>m.has(W(s)))}r.push(d.length>0?d[d.length-1]:null)}return r}function ft(e){var n;let t=(n=e==null?void 0:e.props)==null?void 0:n.className;return typeof t=="string"?t:void 0}function mt(e,t){let n=gt(t);if(n.texts.length!==e.leaves.length||n.texts.some((l,d)=>l!==e.leaves[d]))return null;let r=bn(n,e.leafToNode),i=e.nodes.map((l,d)=>{let o=r[d],m=o?n.elements.get(W(o)):void 0,s=!!m&&(typeof m.type=="string"||ft(m)!==void 0);return I(v({},l),{restylable:s})});return I(v({},e),{nodes:i})}function xn(e,t,n){var c;let r=gt(e);if(r.leafPaths.length!==n.length)return null;let i=n.reduce((u,p)=>Math.max(u,p+1),0);for(let u of Object.keys(t.nodes))if(!/^\d+$/.test(u)||Number(u)>=i)return null;let l=bn(r,n),d=new Map;n.forEach((u,p)=>{d.has(u)||d.set(u,p)});let o=new Map(r.leafPaths.map((u,p)=>[W(u),p])),m=new Set,s=new Map,y=!1;for(let[u,p]of Object.entries(t.nodes)){let g=Number(u),a=l[g];if(p.hidden&&(a?m.add(W(a)):y=!0),p.like!==void 0){let S=l[p.like],x=a?r.elements.get(W(a)):void 0,A=S?ft(r.elements.get(W(S))):void 0;!a||A===void 0||ft(x)===void 0?y=!0:s.set(W(a),A)}}let f=new Map(Object.entries((c=t.order)!=null?c:{})),h=(u,p)=>{var g;if(Ue(u)){let a=o.get(W(p));if(a===void 0)return u;let S=n[a],x=(g=t.nodes[String(S)])==null?void 0:g.text;return x===void 0?u:d.get(S)===a?x:""}if(Array.isArray(u)){let a=u.map((S,x)=>h(S,[...p,x]));for(let[S,x]of f){let A=x.map(k=>{let w=l[k];return!w||w.length!==p.length+1||W(w.slice(0,-1))!==W(p)?-1:w[w.length-1]});if(A.some(k=>k<0))continue;let E=[...A].sort((k,w)=>k-w),b=[...a];E.forEach((k,w)=>{a[k]=b[A[w]]}),f.delete(S)}return a}if((0,re.isValidElement)(u)){let a=W(p);if(m.has(a))return null;let S=He(u);if(me(S)===0)return u;let x=h(S,[...p,"c"]),A=s.get(a),E=A!==void 0?{className:A}:void 0;return Array.isArray(x)?(0,re.cloneElement)(u,E,...x):(0,re.cloneElement)(u,E,x)}return u},R=h(e,[]);return y||f.size>0?null:R}var Cn=require("react/jsx-runtime"),wn=new Set,kn=new Set,Rn=new Set,An="authored.";function Pe({id:e,children:t,variants:n,onFormSubmit:r,goal:i,className:l,reportBaselineText:d=!0}){var ht,bt;let o=N(),m=ne(),s=(0,F.useRef)(null),y=(0,F.useMemo)(()=>hn(t),[t]),f=n?Object.keys(n).join("|"):"",h=(0,F.useMemo)(()=>v({fp:y!=null?y:"0000000000000000",forms:!!r,compose:!0,content:me(t)===1},f!==""?{authored:f.split("|"),children:!0}:{}),[y,t,r,f]),R=()=>{var Q;let _=s.current;if(!_||!d)return null;let G=(0,pt.captureRegionSkeleton)(_);return G.skeleton?(Q=mt(G.skeleton,t))!=null?Q:I(v({},G.skeleton),{editable:!1,nodes:G.skeleton.nodes.map(ce=>I(v({},ce),{restylable:!1}))}):{status:G.reason}},{config:c,arm:u,palette:p,vocabulary:g,source:a}=dn(e,{baselineText:d?()=>{var _,G;return(G=(_=s.current)==null?void 0:_.textContent)!=null?G:null}:void 0,render:()=>h,skeleton:R}),S=u!==""?(ht=c==null?void 0:c.blocks)==null?void 0:ht[u]:void 0,x=u!==""?(bt=c==null?void 0:c.compose)==null?void 0:bt[u]:void 0,A=(S!==void 0&&(0,Ee.containsFormBlock)(S)||x!==void 0&&(0,Ee.containsFormBlock)(x.tree))&&!r;(0,F.useEffect)(()=>{!A||!T()||wn.has(e)||(wn.add(e),console.warn(`[sentient] AdaptiveSlot "${e}" was served a form arm but has no onFormSubmit handler \u2014 rendering its baseline children instead. Pass onFormSubmit to render generated forms.`))},[A,e]);let E=_=>{!o||a==="override"||(a!=="seeded"&&o.componentGoal(e,_),o.goal(_,{metadata:{componentId:e,arm:u},weight:1,stepIndex:0}))},b=t,k=!1,w=u.startsWith(An)?u.slice(An.length):null;if((c==null?void 0:c.blocked)==="variant_history")k=!0;else if(w!==null)n&&Object.prototype.hasOwnProperty.call(n,w)?b=n[w]:k=!0;else if(x!==void 0){let _=A?null:We(x,{palette:p,vocabulary:g,onFormSubmit:r,onFormGoal:E});_===null?k=!0:b=_}else if(S!==void 0){let _=A?null:ge(S,{palette:p,vocabulary:g,onFormSubmit:r,onFormGoal:E});_===null?k=!0:b=_}else if((c==null?void 0:c.edits)!==void 0&&a!=="none"){let _=c.edits,G=_.fp===y?xn(t,_.edits,_.leafToNode):null;G===null?k=!0:b=G}else if((c==null?void 0:c.content)!==void 0&&a!=="none"){let _=Sn(t,c.content);_===null?k=!0:b=_}let O=k&&S===void 0&&x===void 0&&(c==null?void 0:c.edits)===void 0&&w===null&&(c==null?void 0:c.blocked)===void 0;(0,F.useEffect)(()=>{(c==null?void 0:c.blocked)!=="variant_history"||!T()||Rn.has(e)||(Rn.add(e),console.warn(`[sentient] <Adaptive id="${e}"> has results from its earlier variants experiment, so it is showing your original until you migrate it: Components \u2192 "${e}" \u2192 Migrate. Deploying code never switches an experiment.`))},[c==null?void 0:c.blocked,e]);let P=w!==null&&!k?w:null;(0,F.useEffect)(()=>{var Ae;if(!P||!d||!o)return;let _=s.current;if(!_)return;let G=(0,pt.captureRegionSkeleton)(_),Q=G.skeleton?mt(G.skeleton,n==null?void 0:n[P]):null,ce=(Ae=_.textContent)==null?void 0:Ae.trim();o.reportSlots([],void 0,void 0,{[e]:[v(v({key:P},ce?{text:ce}:{}),Q?{skeleton:Q}:{})]})},[P,o,e]);let M=k&&(c==null?void 0:c.edits)!==void 0&&(a==="preloaded"||a==="client");(0,F.useEffect)(()=>{var _;!M||!(c!=null&&c.edits)||(_=o==null?void 0:o.reportDrift)==null||_.call(o,e,c.edits.fp,y,c.edits.fp===y?"unaddressable":"fp_mismatch")},[M,e,y,o]);let D=b===t;(0,F.useEffect)(()=>{var G;if(!(c!=null&&c.needsSkeleton)||!D)return;let _=R();_&&((G=o==null?void 0:o.reportSkeleton)==null||G.call(o,e,_))},[c==null?void 0:c.needsSkeleton,D,e,o]),(0,F.useEffect)(()=>{if(!D)return;let _=Jt(e);if(!_)return;let G=R();Ut(_,G&&"status"in G?{status:G.status}:{skeleton:G})},[e,D]),(0,F.useEffect)(()=>{!O||!T()||kn.has(e)||(kn.add(e),console.warn(`[sentient] <Adaptive id="${e}"> was served a text version, but its children have several separate texts or none Sentient can reach \u2014 rendering the original instead. Regenerate the version (new versions edit each text in place), or put a single text inline.`))},[O,e]);let q=c!=null&&c.blocks?Object.keys(c.blocks).sort().join("|"):"";(0,F.useEffect)(()=>ve({id:e,arms:q===""?void 0:q.split("|")}),[e,q]);let Z=(0,F.useRef)(null);(0,F.useEffect)(()=>{!o||a==="none"||a==="seeded"||a==="override"||u===""||k||Z.current!==u&&(Z.current=u,ae(o,m,e,u))},[o,m,e,u,a,k]);let ie=a!=="none"&&a!=="seeded"&&!k,oe=ie?u:"",ue=i===void 0?null:typeof i=="string"?i:JSON.stringify(i);(0,F.useEffect)(()=>{if(!o||!i||a==="override")return;let _=s.current;if(!_)return;let G=se(i),Q=ee(i),ce=!1;return te(_,U(i),{fireGoal:()=>{ce||(ce=!0,ie&&(Q!==void 0?o.componentGoal(e,G,{value:Q}):o.componentGoal(e,G)),o.goal(G,v({metadata:{componentId:e,arm:oe},weight:1,stepIndex:0},Q!==void 0?{value:Q}:{})))},fireStep:(Ae,xt,Qn)=>{ie&&o.componentGoal(e,Ae,{reward:xt}),o.goal(Ae,{metadata:{componentId:e,arm:oe},weight:xt,stepIndex:Qn})}},G)},[o,e,ue,u,a,k,ie,oe]);let Y=(0,F.useRef)(null);(0,F.useEffect)(()=>{let _=s.current;if(_){if(Y.current===null){Y.current=u;return}Y.current!==u&&(Y.current=u,(0,Ee.reveal)(_))}},[u]);let Yn=(0,F.useMemo)(()=>v({"data-sentient-slot":e},u!==""?{"data-sentient-arm":u}:{}),[e,u]);return(0,Cn.jsx)("div",I(v({ref:s,className:l},Yn),{children:b}))}var Ge=require("react/jsx-runtime");function Ar(e){var s;let{client:t,variantId:n,content:r,ref:i}=Ke(e.id,e.variants,{goal:e.goal,funnel:e.funnel,microSignalGoals:e.microSignalGoals,agentData:e.agentData,agentDataByVariant:e.agentDataByVariant,cursorSignal:!0}),[l,d]=(0,ke.useState)(!1);if((0,ke.useEffect)(()=>{d(!0)},[]),e.clientOnly&&(!l||!t)||!n)return null;let o=(s=e.variants[n])!=null?s:null,m=o===null?r:null;return T()&&o===null&&m===null&&console.warn(`[sentient] <Adaptive id="${e.id}"> was assigned variant "${n}" but no matching key exists in props.variants. If this is a dashboard-managed text variant, use <AdaptiveText id="${e.id}"> instead.`),(0,Ge.jsx)("div",{ref:i,"data-sentient-id":e.id,"data-sentient-variant":n,children:o!=null?o:m})}var Cr=(0,ke.memo)(Ar,(e,t)=>{if(e.id!==t.id||e.goal!==t.goal&&JSON.stringify(e.goal)!==JSON.stringify(t.goal)||e.microSignalGoals!==t.microSignalGoals||e.funnel!==t.funnel||e.clientOnly!==t.clientOnly||e.agentData!==t.agentData||e.agentDataByVariant!==t.agentDataByVariant)return!1;if(e.variants===t.variants)return!0;let n=Object.keys(e.variants),r=Object.keys(t.variants);return n.length!==r.length?!1:n.every(i=>i in t.variants&&Object.is(e.variants[i],t.variants[i]))});function On(e){if(e.variants===void 0)return(0,Ge.jsx)(Pe,v({},e));let t=e;if(t.children!=null){T()&&_r(t);let n=t,{funnel:r,microSignalGoals:i,agentData:l,agentDataByVariant:d,clientOnly:o,variants:m}=n,s=De(n,["funnel","microSignalGoals","agentData","agentDataByVariant","clientOnly","variants"]);return(0,Ge.jsx)(Pe,I(v({},s),{children:t.children,variants:m}))}return(0,Ge.jsx)(Cr,v({},t))}var _n=new Set;function _r(e){let t=["funnel","microSignalGoals","agentData","agentDataByVariant","clientOnly"].filter(n=>e[n]!==void 0);t.length===0||_n.has(e.id)||(_n.add(e.id),console.warn(`[sentient] <Adaptive id="${e.id}"> has both variants and children, so it runs as one experiment with your original and generated versions. These props only apply to a variants-only component and are ignored here: ${t.join(", ")}.`))}var $=require("react");var Pn=require("react/jsx-runtime");function En({id:e,default:t,component:n="span",className:r,goal:i}){var E;let l=N(),d=ne(),o=Me(),m=Fe(),s=(0,$.useRef)(null),y=(0,$.useRef)(null),f=(0,$.useSyncExternalStore)(J,()=>we(e),()=>null),[h,R]=(0,$.useState)(()=>{var b,k;return(k=(b=l==null?void 0:l.getAssignment(e,m))==null?void 0:b.content)!=null?k:null}),[c,u]=(0,$.useState)(()=>{var b,k;return(k=(b=l==null?void 0:l.getAssignment(e,m))==null?void 0:b.variantId)!=null?k:null});(0,$.useEffect)(()=>{if(f||!l)return;let b=l.getAssignment(e,m);if((b==null?void 0:b.content)!==void 0){u(b.variantId),R(b.content);return}let k=!1;return l.assign(e).then(w=>{if(!k){if(!w){T()&&console.warn(`[sentient] <AdaptiveText id="${e}"> assignment failed \u2014 showing default text.`);return}u(w.variantId),w.content&&R(w.content)}}),()=>{k=!0}},[l,e,m,f]),(0,$.useEffect)(()=>{f||!l||!c||!d||s.current!==c&&(s.current=c,l.track({projectId:d,componentId:e,variantId:c,eventType:"variant_assigned",payload:{}}),o==null||o(e,c))},[l,c,d,e,o,f]);let p=i===void 0?"":typeof i=="string"?i:JSON.stringify(i),g=(0,$.useMemo)(()=>i===void 0?null:U(i),[p]),a=i===void 0?null:typeof i=="string"?i:g.type,S=(0,$.useRef)(!1);(0,$.useEffect)(()=>{S.current=!1},[c,p]),(0,$.useEffect)(()=>{if(f||!l||!c||!d||!g||!a)return;let b=y.current;if(!b)return;let k=ee(g);return te(b,g,{fireGoal:()=>{S.current||(S.current=!0,l.track({projectId:d,componentId:e,variantId:c,eventType:"goal_achieved",goalType:a,payload:v({reward:1},k!==void 0?{goalValue:k}:{})}),l.goal(a,v({metadata:{componentId:e,variantId:c},weight:1,stepIndex:0},k!==void 0?{value:k}:{})))},fireStep:(w,O,P)=>{l.track({projectId:d,componentId:e,variantId:c,eventType:"goal_achieved",goalType:w,payload:{reward:O}}),l.goal(w,{metadata:{},weight:O,stepIndex:P})}})},[l,c,d,e,g,a,f]);let x=h!=null?h:t;if(f){let b=l==null?void 0:l.getAssignment(e,m);x=b&&b.variantId===f&&(E=b.content)!=null?E:t}return(0,Pn.jsx)(n,{ref:b=>{y.current=b},className:r,children:x})}var Xe=require("react");function ze(e){let t=N(),n=(0,Xe.useRef)(new Set);return(0,Xe.useCallback)((r,i)=>{var l,d;if(!we(e)){if(i!=null&&i.once){if(n.current.has(r))return;n.current.add(r)}t==null||t.componentGoal(e,r,i),t==null||t.goal(r,v(v(v({metadata:(l=i==null?void 0:i.metadata)!=null?l:{},weight:(d=i==null?void 0:i.reward)!=null?d:1,stepIndex:0},(i==null?void 0:i.value)!==void 0?{value:i.value}:{}),(i==null?void 0:i.currency)!==void 0?{currency:i.currency}:{}),(i==null?void 0:i.externalId)!==void 0?{externalId:i.externalId}:{}))}},[t,e])}var Te=require("react");function Gn(e,t={}){let m=t,{componentId:n}=m,r=De(m,["componentId"]),i=N(),l=ze(n!=null?n:""),d=(0,Te.useRef)(!1),o=(0,Te.useRef)(r);o.current=r,(0,Te.useEffect)(()=>{if(!i||d.current)return;d.current=!0;let{metadata:s,reward:y,value:f,currency:h,externalId:R}=o.current;if(n){l(e,o.current);return}i.goal(e,v(v(v({metadata:s!=null?s:{},weight:y!=null?y:1,stepIndex:0},f!==void 0?{value:f}:{}),h!==void 0?{currency:h}:{}),R!==void 0?{externalId:R}:{}))},[i,n,e,l])}var Ln=require("@sentientui/core"),Dn=require("@sentientui/policy"),Nn=require("react/jsx-runtime");function Tn(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function Or(e){return e.persona?'(function(){try{var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+Tn(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+Tn((0,Dn.confidenceBand)(e.persona.confidence))+");}catch(e){}})();":(0,Ln.renderPrePaintScript)(e.apiKey)}function In(e){return(0,Nn.jsx)("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:Or(e)}})}var z=require("react"),$n=require("@sentientui/policy");var X=require("react"),pe=require("@sentientui/core"),Vn=require("@sentientui/policy");function qe(e,t){let n=N(),r=$e(),[,i]=(0,X.useReducer)(f=>f+1,0),l=(0,X.useSyncExternalStore)(J,()=>{var f;return typeof window!="undefined"?(f=window.__sentient_slot_overrides)==null?void 0:f[e]:void 0},()=>{}),d=l===void 0?r[e]:void 0,o=l===void 0&&d===void 0&&n?n.getSlotResult(e):null,m=(n==null?void 0:n.isLocal)===!0&&l===void 0&&d===void 0&&o===null;(0,X.useEffect)(()=>{if(!m||!n)return;let f=!1;return n.decide({slots:[t]}).then(h=>{!f&&h&&i()}),()=>{f=!0}},[n,e,m]);let s=(()=>{if(l!==void 0)return{result:l,arm:(0,pe.armOfResult)(l),source:"override"};if(d!==void 0)return{result:d,arm:(0,pe.armOfResult)(d),source:"preloaded"};if(o!==null){let h=n!=null&&n.isSlotDecided?n.isSlotDecided(e):!0;return{result:o,arm:(0,pe.armOfResult)(o),source:h?"client":"seeded"}}let f=(0,pe.baselineResultFor)(t);return{result:f,arm:(0,pe.armOfResult)(f),source:"baseline"}})(),y=s.source==="preloaded"||s.source==="override";return(0,X.useEffect)(()=>{var h;if(!n||n.isLocal===!0||y||!n.decideSlots)return;let f=(h=n.onSlotsChanged)==null?void 0:h.call(n,i);return n.decideSlots([t]),()=>{var R;(R=n.cancelSlots)==null||R.call(n,[e]),f==null||f()}},[n,e,y]),s}function Er(){var t;if(typeof window=="undefined")return null;let e=window.__sentient_persona_override;if(e!=null&&e.persona)return{persona:e.persona,confidence:(t=e.confidence)!=null?t:1};try{let n=new URLSearchParams(window.location.search).get("sentient_persona");if(n)return{persona:n,confidence:1}}catch(n){}return null}function Fn(){let e=N(),t=tn();(0,X.useSyncExternalStore)(J,Gt,()=>0);let[n,r]=(0,X.useState)(!1);(0,X.useEffect)(()=>r(!0),[]);let i=o=>({persona:o.persona,confidence:o.confidence,band:(0,Vn.confidenceBand)(o.confidence)});if(!n)return t?i(t):null;let l=Er();if(l)return i(l);if(t)return i(t);let d=e?e.getPersona():null;return d?i(d):null}var Mn=new Set;function Pr(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[\\"]/g,"\\$&")}function Bn(e,t,n){let r=N(),i=ne(),l=JSON.stringify(t),d=(0,z.useMemo)(()=>({id:e,dims:t}),[e,l]),{result:o,arm:m,source:s}=qe(e,d),y=(0,z.useMemo)(()=>typeof o=="string"?{}:o,[m]);if(T()&&!Mn.has(e)){Mn.add(e);let u=(0,$n.validateSlotDecl)({id:e,dims:Object.fromEntries(Object.entries(t).map(([g,a])=>[g,[...a]]))}),p=Object.values(t).reduce((g,a)=>g*a.length,1);u.ok?p>4&&console.warn(`[sentient] useAdaptiveTokens("${e}") declares ${p} combinations \u2014 more than the recommended 4. Each extra combination needs more traffic to learn; consider fewer dims/values.`):console.warn(`[sentient] useAdaptiveTokens("${e}"): invalid declaration \u2014 ${u.reason}. Serving baseline.`)}let f=(n==null?void 0:n.goal)===void 0?null:typeof n.goal=="string"?n.goal:JSON.stringify(n.goal);(0,z.useEffect)(()=>ve({id:e,dims:t}),[e]);let h=(0,z.useRef)(null);(0,z.useEffect)(()=>{!r||s==="baseline"||s==="seeded"||s==="override"||h.current===m||(h.current=m,ae(r,i,e,m))},[r,i,e,m,s]);let R=n==null?void 0:n.funnel;(0,z.useEffect)(()=>{var u;!r||!R||s==="override"||ye(r,i,e,R,U((u=n==null?void 0:n.goal)!=null?u:"click"))},[r,i,e,R,f,s]),(0,z.useEffect)(()=>{if(!r||!(n!=null&&n.goal)||s==="override"||s==="baseline"||s==="seeded")return;let u=document.querySelector(`[data-sentient-slot="${Pr(e)}"]`);if(!u){T()&&console.warn(`[sentient] useAdaptiveTokens("${e}"): a goal is declared but no element carries the returned props \u2014 spread {...props} on the slot's element.`);return}let p=se(n.goal),g=ee(n.goal),a=!1;return te(u,U(n.goal),{fireGoal:()=>{a||(a=!0,g!==void 0?r.componentGoal(e,p,{value:g}):r.componentGoal(e,p),r.goal(p,v({metadata:{componentId:e,arm:m},weight:1,stepIndex:0},g!==void 0?{value:g}:{})))},fireStep:(S,x,A)=>{r.componentGoal(e,S,{reward:x}),r.goal(S,{metadata:{componentId:e,arm:m},weight:x,stepIndex:A})}},p)},[r,e,f,m,s]);let c=(0,z.useMemo)(()=>{let u={"data-sentient-slot":e};for(let[p,g]of Object.entries(y))u[`data-${p}`]=g;return u},[e,y]);return{tokens:y,props:c}}var Re=require("react");var jn=new Set;function Kn(e,t){var R;if(T()&&!t.goal)throw new Error(`[sentient] useAdaptive("${e}"): a goal is required \u2014 without one the optimizer accumulates exposures with no rewards and cannot learn. Pass e.g. goal: 'buy_click'.`);let{client:n,variantIds:r,variantId:i,isOverride:l,goalLabel:d,ref:o,nodeRef:m}=Ke(e,t.variants,{goal:t.goal,funnel:t.funnel,microSignalGoals:t.microSignalGoals}),s=(R=i!=null?i:r[0])!=null?R:"",y=t.variants[s];(0,Re.useEffect)(()=>{if(!T()||!n)return;let c=setTimeout(()=>{!m.current&&!jn.has(e)&&(jn.add(e),console.warn(`[sentient] useAdaptive("${e}"): bind was never attached \u2014 spread {...bind} on the rendered element, otherwise exposure and goal tracking cannot work and the optimizer learns nothing.`))},0);return()=>clearTimeout(c)},[n,e]);let f=(0,Re.useCallback)((c,u)=>{var g,a;if(l)return;let p=c!=null?c:d;p&&(n==null||n.componentGoal(e,p,u),n==null||n.goal(p,v(v(v({metadata:(g=u==null?void 0:u.metadata)!=null?g:{},weight:(a=u==null?void 0:u.reward)!=null?a:1,stepIndex:0},(u==null?void 0:u.value)!==void 0?{value:u.value}:{}),(u==null?void 0:u.currency)!==void 0?{currency:u.currency}:{}),(u==null?void 0:u.externalId)!==void 0?{externalId:u.externalId}:{})))},[n,e,d,l]),h=(0,Re.useMemo)(()=>({ref:o,"data-sentient-id":e,"data-sentient-variant":s}),[o,e,s]);return{variant:s,value:y,bind:h,fireGoal:f}}var j=require("react");var Jn=require("react/jsx-runtime"),Ze=new Set;function Wn(e){var g;let t=N(),n=ne(),r=(0,j.useRef)(null),i=Object.keys(e.arrangements).join(" "),l=(0,j.useMemo)(()=>Object.keys(e.arrangements),[i]),d=(0,j.useMemo)(()=>v({id:e.id,arms:l},e.baseline!==void 0?{baseline:e.baseline}:{}),[e.id,l,e.baseline]),{arm:o,source:m}=qe(e.id,d);T()&&e.baseline!==void 0&&e.baseline!==l[0]&&!Ze.has(e.id+":baseline")&&(Ze.add(e.id+":baseline"),console.warn(`[sentient] <AdaptiveGroup id="${e.id}">: baseline "${e.baseline}" is not the first-declared arrangement ("${l[0]}"). The first arrangement should usually be the page's real incumbent (the holdout sees it).`));let s=j.Children.toArray(e.children).filter(j.isValidElement),y=new Map;for(let a of s)y.set(String((g=a.key)!=null?g:"").replace(/^\.\$/,""),a);let f=e.arrangements[o],h=f!==void 0&&f.length===s.length&&f.every(a=>y.has(a));T()&&f!==void 0&&!h&&!Ze.has(e.id+":keys")&&(Ze.add(e.id+":keys"),console.warn(`[sentient] <AdaptiveGroup id="${e.id}">: arrangement "${o}" [${f.join(", ")}] does not match the children's keys \u2014 rendering declaration order (fail-safe).`));let R=h?f.map(a=>y.get(a)):s;(0,j.useEffect)(()=>ve({id:e.id,arms:Object.keys(e.arrangements)}),[e.id]);let c=(0,j.useRef)(null);(0,j.useEffect)(()=>{!t||m==="baseline"||m==="seeded"||m==="override"||c.current===o||(c.current=o,ae(t,n,e.id,o))},[t,n,e.id,o,m]);let u=e.funnel;(0,j.useEffect)(()=>{var a;!t||!u||m==="override"||ye(t,n,e.id,u,U((a=e.goal)!=null?a:"click"))},[t,n,e.id,u,m]);let p=e.goal===void 0?null:typeof e.goal=="string"?e.goal:JSON.stringify(e.goal);return(0,j.useEffect)(()=>{if(!t||e.goal===void 0||m==="override"||m==="baseline"||m==="seeded")return;let a=r.current;if(!a)return;let S=se(e.goal),x=ee(e.goal),A=!1;return te(a,U(e.goal),{fireGoal:()=>{A||(A=!0,x!==void 0?t.componentGoal(e.id,S,{value:x}):t.componentGoal(e.id,S),t.goal(S,v({metadata:{componentId:e.id,arm:o},weight:1,stepIndex:0},x!==void 0?{value:x}:{})))},fireStep:(E,b,k)=>{t.componentGoal(e.id,E,{reward:b}),t.goal(E,{metadata:{componentId:e.id,arm:o},weight:b,stepIndex:k})}},S)},[t,e.id,p,o,m]),(0,Jn.jsx)("div",{ref:r,"data-sentient-id":e.id,"data-sentient-variant":o,children:R})}var yt=require("@sentientui/core");var Gr=["page","blocks","layoutOrder"],Un=new Map;function Hn(e,t){Un.set(e,t)}function vt(e){return Un.get(e)}function Xn(e){var i,l;let t=(l=(i=e.content)!=null?i:vt(e.page))!=null?l:{},n={};for(let[d,o]of Object.entries(t))Gr.includes(d)||(n[d]=o);let r=I(v({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(r.layoutOrder=e.layoutOrder),r}function zn(e){return`<script type="application/ld+json">${St(e)}</script>`}function St(e){return JSON.stringify(v({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function qn(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,r]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(r,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
|
+
"use strict";var er=Object.create;var Ce=Object.defineProperty,tr=Object.defineProperties,nr=Object.getOwnPropertyDescriptor,rr=Object.getOwnPropertyDescriptors,ir=Object.getOwnPropertyNames,Le=Object.getOwnPropertySymbols,or=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty,kt=Object.prototype.propertyIsEnumerable;var wt=(e,t,n)=>t in e?Ce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))Ye.call(t,n)&&wt(e,n,t[n]);if(Le)for(var n of Le(t))kt.call(t,n)&&wt(e,n,t[n]);return e},I=(e,t)=>tr(e,rr(t));var De=(e,t)=>{var n={};for(var r in e)Ye.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&Le)for(var r of Le(e))t.indexOf(r)<0&&kt.call(e,r)&&(n[r]=e[r]);return n};var sr=(e,t)=>{for(var n in t)Ce(e,n,{get:t[n],enumerable:!0})},Rt=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ir(t))!Ye.call(e,i)&&i!==n&&Ce(e,i,{get:()=>t[i],enumerable:!(r=nr(t,i))||r.enumerable});return e};var Qe=(e,t,n)=>(n=e!=null?er(or(e)):{},Rt(t||!e||!e.__esModule?Ce(n,"default",{value:e,enumerable:!0}):n,e)),ar=e=>Rt(Ce({},"__esModule",{value:!0}),e);var Tr={};sr(Tr,{Adaptive:()=>On,AdaptiveGroup:()=>Wn,AdaptiveProvider:()=>Zt,AdaptiveSlot:()=>Pe,AdaptiveText:()=>En,SentientPersonaScript:()=>In,buildAgentFeed:()=>Xn,defineAgentContent:()=>Hn,detectSegment:()=>yt.deriveSessionSegment,getAgentContent:()=>vt,grantConsent:()=>Zn.grantConsent,renderAgentJsonLd:()=>zn,renderAgentJsonLdBody:()=>St,renderAgentMarkdown:()=>qn,renderBlocks:()=>ge,renderCompose:()=>We,useAdaptive:()=>Kn,useAdaptiveApiBaseUrl:()=>sn,useAdaptiveGoal:()=>ze,useAdaptivePersona:()=>Fn,useAdaptiveTokens:()=>Bn,useAssignment:()=>je,useInitialAssignments:()=>Ve,useLayoutOrder:()=>en,usePageGoal:()=>Gn,useSentient:()=>N});module.exports=ar(Tr);var C=require("react"),Ne=require("@sentientui/core");var At=new Map,Ie=new Map;function Ct(e,t){let n=Ie.get(e);return n||(n=new Set,Ie.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&Ie.delete(e)}}function _t(e,t){At.set(e,t);let n=Ie.get(e);if(n)for(let r of n)try{r(t)}catch(i){}}function et(e){var t;return(t=At.get(e))!=null?t:null}var lr={on:!1,listeners:new Set};function Ot(){if(typeof window=="undefined")return lr;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function tt(){return Ot().on}function Et(e){let t=Ot().listeners;return t.add(e),()=>{t.delete(e)}}function Pt(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,r,i)=>e.assign(t,n,r,i),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var nt="sentient:overrides-changed";function Gt(){var e;return typeof window=="undefined"?0:(e=window.__sentient_overrides_version)!=null?e:0}function rt(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(nt))}function J(e){return typeof window=="undefined"?()=>{}:(window.addEventListener(nt,e),()=>window.removeEventListener(nt,e))}function Tt(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function T(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}function U(e){return typeof e=="string"?{type:"click"}:e}function se(e){return typeof e=="string"?e:e.type}function ee(e){if(typeof e!="string"&&(e.type==="click"||e.type==="form_submit"||e.type==="scroll_depth"))return e.value}var it=new Set,ot=!1;function Lt(e){if(it.has(e))return!0;if(it.add(e),!ot){ot=!0;let t=()=>{ot=!1,it.clear()};if(typeof MessageChannel=="function"){let n=new MessageChannel;n.port1.onmessage=()=>{n.port1.close(),n.port2.close(),t()},n.port2.postMessage(0)}else setTimeout(t,0)}return!1}function ur(e){if(!(e instanceof Element))return!1;let t=e.tagName.toLowerCase();return t==="a"||t==="button"?!0:e.getAttribute("role")==="button"}function Dt(e,t,n){if(n){try{let i=e;for(;i&&i!==t;){if(i.matches(n))return!0;i=i.parentElement}}catch(i){}return!1}let r=e;for(;r&&r!==t;){if(ur(r))return!0;r=r.parentElement}return!1}function te(e,t,n,r){if(t.type==="weighted_composite"){let s=new Set,y=[];return t.steps.forEach(({goal:f,name:h,weight:R},c)=>{let u=(p=!1)=>{s.has(c)||p&&r!==void 0&&Lt(`step\0${h}\0${R}\0${c}`)||(s.add(c),n.fireStep(h,R,c))};if(f.type==="click"){let p=g=>{let a=g.target;a instanceof Element&&Dt(a,e,f.selector)&&u()};e.addEventListener("click",p),y.push(()=>e.removeEventListener("click",p));return}if(f.type==="form_submit"){let p=g=>{g.target instanceof HTMLFormElement&&e.contains(g.target)&&u()};e.addEventListener("submit",p),y.push(()=>e.removeEventListener("submit",p));return}if(f.type==="scroll_depth"){let p=Math.max(0,Math.min(1,f.threshold)),g=new IntersectionObserver(a=>{for(let S of a)if(S.intersectionRatio>=p){u(!0),g.disconnect();break}},{threshold:[p]});g.observe(e),y.push(()=>g.disconnect())}}),()=>{for(let f of y)f()}}let i=t.type==="composite"?t.all:[t],l=new Set(i.map((s,y)=>y)),d=()=>{r!==void 0&&Lt(r)||n.fireGoal()},o=(s,y=!1)=>{l.delete(s),l.size===0&&(y?d():n.fireGoal())},m=[];return i.forEach((s,y)=>{if(s.type==="click"){let f=h=>{let R=h.target;R instanceof Element&&Dt(R,e,s.selector)&&(t.type==="composite"?o(y):n.fireGoal())};e.addEventListener("click",f),m.push(()=>e.removeEventListener("click",f));return}if(s.type==="form_submit"){let f=h=>{h.target instanceof HTMLFormElement&&e.contains(h.target)&&(t.type==="composite"?o(y):n.fireGoal())};e.addEventListener("submit",f),m.push(()=>e.removeEventListener("submit",f));return}if(s.type==="scroll_depth"){let f=Math.max(0,Math.min(1,s.threshold)),h=new IntersectionObserver(R=>{for(let c of R)if(c.intersectionRatio>=f){t.type==="composite"?o(y,!0):d(),h.disconnect();break}},{threshold:[f]});h.observe(e),m.push(()=>h.disconnect());return}}),()=>{for(let s of m)s()}}var It=new Set,Nt=new Set;function ye(e,t,n,r,i){let l=`${r}|${n}`;if(Nt.has(l))return;Nt.add(l);let d=i.type==="weighted_composite"&&!It.has(r);d&&It.add(r),e.track({projectId:t,componentId:n,eventType:"funnel_declared",payload:d?{funnelId:r,steps:i.steps.map(o=>({goalId:o.name,weight:o.weight}))}:{funnelId:r}})}function ae(e,t,n,r){e.track({projectId:t,componentId:n,variantId:r,eventType:"variant_assigned",payload:{}})}var cr={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function de(){if(typeof window=="undefined")return cr;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function _e(){de().version+=1;for(let e of de().listeners)e()}var Vt=()=>{};function Ft(e){return T()?(de().components.set(e.id,e),_e(),()=>{de().components.delete(e.id),_e()}):Vt}function ve(e){return T()?(de().slots.set(e.id,e),_e(),()=>{de().slots.delete(e.id),_e()}):Vt}function st(e){T()&&(de().sections=[...e],_e())}var Mt="0.35.3",at=Mt!=="0.0.0-dev"?{name:"react",version:Mt}:void 0;function dr(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function Se(e,t){dr()[e]=t}function $t(e){window.__sentient_vocabulary_override=e}function Bt(){var e;return typeof window=="undefined"?null:(e=window.__sentient_vocabulary_override)!=null?e:null}function fr(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function he(e,t){fr()[e]=t}var jt="sentient_editor",Kt="sentient_preview_cell",Wt="sentient_refresh_region",lt="sentient-cell-preview-bar",fe="__preview__",be=null;function Jt(e){if((be==null?void 0:be.slotId)!==e)return null;let t=be;return be=null,t}function Ut(e,t){fetch(`${e.base}/editor/region-skeleton`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json"},body:JSON.stringify(v({slotId:e.slotId},t))}).then(n=>xe(n.ok?"Region refreshed \u2014 you can regenerate its versions now.":"Couldn\u2019t refresh this region \u2014 reopen the link from your dashboard.")).catch(()=>xe("Couldn\u2019t refresh this region \u2014 check your connection and reopen the link from your dashboard."))}function Ht(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(lt))return;let t,n,r;try{let m=new URLSearchParams(window.location.search);t=m.get(jt),n=m.get(Kt),r=m.get(Wt)}catch(m){return}if(t&&r){be={slotId:r,token:t,base:(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"")},Se(r,{kind:"arms"}),he(r,fe),rt();return}if(!t||!n)return;let i=n.lastIndexOf("~");if(i<=0)return;let l=n.slice(0,i),d=n.slice(i+1),o=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");fetch(`${o}/editor/cell-preview?slotId=${encodeURIComponent(l)}&persona=${encodeURIComponent(d)}`,{headers:{authorization:`Bearer ${t}`}}).then(async m=>{if(!m.ok){xe(m.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let s=await m.json();if(s.vocabulary&&Array.isArray(s.vocabulary.entries)&&$t(s.vocabulary),s.compose!=null)Se(l,{kind:"arms",compose:{[fe]:s.compose}}),he(l,fe);else if(s.edits!=null&&typeof s.skeletonFp=="string"&&Array.isArray(s.leafToNode))Se(l,{kind:"arms",edits:{edits:s.edits,fp:s.skeletonFp,leafToNode:s.leafToNode}}),he(l,fe);else if(s.blocks!=null)Se(l,{kind:"arms",blocks:{[fe]:s.blocks}}),he(l,fe);else if(s.content!=null)Se(l,{kind:"arms",content:s.content}),he(l,fe);else{xe("Nothing to preview in that square yet.");return}rt(),xe(`Previewing \u201C${s.slotName}\u201D for ${s.personaDisplay}${s.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var y;try{(y=document.querySelector(`[data-sentient-slot="${l}"]`))==null||y.scrollIntoView({block:"center"})}catch(f){}},300)}).catch(()=>xe("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function xe(e){var i;if(document.getElementById(lt))return;let t=document.createElement("div");t.id=lt,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let r=document.createElement("button");r.textContent="Exit preview",Object.assign(r.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),r.onclick=()=>{let l=new URL(window.location.href);l.searchParams.delete(jt),l.searchParams.delete(Kt),l.searchParams.delete(Wt),window.location.assign(l.toString())},t.append(n,r),((i=document.body)!=null?i:document.documentElement).append(t)}var gr="sentient_editor",Xt=!1;function zt(e){if(Xt||typeof window=="undefined")return;let t=null;try{t=new URLSearchParams(window.location.search).get(gr)}catch(i){return}if(!t)return;Xt=!0;let n=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),r=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:i})=>fetch(`${n}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(i(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?r():window.addEventListener("load",r,{once:!0})}var an=require("react/jsx-runtime");function mr(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return(0,Ne.deriveSessionSegment)({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var qt="https://api.sentient-ui.com/v1",B=(0,C.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:qt,debug:!1});function pr(e){let[t,n]=(0,C.useState)(!1),r=(0,C.useRef)(e);r.current=e;let{cookie:i,value:l,event:d}=e!=null?e:{},o=typeof(e==null?void 0:e.check)=="function";return(0,C.useEffect)(()=>{let m=()=>{var h;let y=r.current;if(!y)return!1;if(y.check)return y.check()===!0;if(!y.cookie||typeof document=="undefined")return!1;let f=`${y.cookie}=${(h=y.value)!=null?h:"accepted"}`;return document.cookie.split("; ").some(R=>R.trim()===f)};if(n(m()),!d)return;let s=()=>{n(m())};return window.addEventListener(d,s),()=>window.removeEventListener(d,s)},[i,l,d,o]),t}function Zt(e){var c,u;let[t,n]=(0,C.useState)(null),[r]=(0,C.useState)(()=>{var p;return(p=e.sessionSegment)!=null?p:mr()}),[i,l]=(0,C.useState)(tt());(0,C.useEffect)(()=>Et(()=>l(tt())),[]),(0,C.useEffect)(()=>{Ht(e.apiBaseUrl),zt(e.apiBaseUrl)},[]);let d=pr(e.consentFrom),o=e.consentFrom?e.consent===!0||d:e.consent,m=(0,C.useRef)(null);(0,C.useEffect)(()=>{var A;if(o===!1&&!e.preConsentBehavior){(A=m.current)==null||A.destroy(),m.current=null,n(null);return}let p=v({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:r,consent:o,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},at?{sdk:at}:{}),g=!1,a=null,S=null,x=E=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:b})=>{g||(S=b(E,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:E})=>{g||(a=E(I(v({},p),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),m.current=a,n(a),x(a))}):(a=(0,Ne.init)(p),m.current=a,n(a),x(a)),()=>{g=!0,S==null||S(),a==null||a.dispose()}},[o]),(0,C.useEffect)(()=>{if(!t)return;let p=!1,g=async()=>{if(p)return;let S;try{S=await t.fetchWeights()}catch(x){return}if(!p)for(let x of S){let A={componentId:x.componentId,updatedAt:x.updatedAt,variants:x.variants.map(E=>{var b;return{variantId:E.variantId,pulls:E.pulls,avgReward:(b=E.avgReward)!=null?b:0}})};_t(x.componentId,A)}};g();let a=setInterval(()=>{g()},6e4);return()=>{p=!0,clearInterval(a)}},[t]);let s=(c=e.ssrFallback)!=null?c:"first",y=((u=e.apiBaseUrl)!=null?u:qt).replace(/\/$/,""),f=(0,C.useRef)(null);(0,C.useEffect)(()=>{var a;if(typeof process!="undefined"&&((a=process.env)==null?void 0:a.NODE_ENV)==="production")return;let p={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:y},g=f.current;if(f.current=p,g!==null)for(let S of["apiKey","context","country","persona","apiBaseUrl"])Object.is(g[S],p[S])||console.warn(`[sentient] AdaptiveProvider: \`${S}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,y]),(0,C.useEffect)(()=>{var p;typeof process!="undefined"&&((p=process.env)==null?void 0:p.NODE_ENV)==="production"||Tt({apiKey:e.apiKey,apiBaseUrl:y,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,y]),(0,C.useEffect)(()=>{let p=e.initialLayoutOrder;if(p&&p.length>0){st(p);return}e.declaredSections&&e.declaredSections.length>0&&st(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),(0,C.useEffect)(()=>{if(!T())return;let p=e.declaredSections;if(!p||p.length===0||typeof document=="undefined")return;let g=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),S=>S.getAttribute("data-sentient-id"))),a=p.filter(S=>!g.has(S));a.length>0&&console.warn(`[SentientUI] Declared section${a.length>1?"s":""} ${a.map(S=>`"${S}"`).join(", ")} ${a.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let h=(0,C.useMemo)(()=>t&&i?Pt(t):t,[t,i]),R=(0,C.useMemo)(()=>{var p,g,a,S,x,A,E,b;return{client:h,apiKey:e.apiKey,initialAssignments:(p=e.initialAssignments)!=null?p:{},sessionSegment:r,ssrFallback:s,onAssignment:e.onAssignment,initialLayoutOrder:(g=e.initialLayoutOrder)!=null?g:null,initialSlots:(a=e.initialSlots)!=null?a:{},initialSlotConfig:(S=e.initialSlotConfig)!=null?S:{},initialPalette:(x=e.initialPalette)!=null?x:null,initialVocabulary:(A=e.initialVocabulary)!=null?A:null,initialPersona:(E=e.initialPersona)!=null?E:null,apiBaseUrl:y,debug:(b=e.debug)!=null?b:!1}},[h,e.apiKey,e.initialAssignments,r,s,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,y,e.debug]);return(0,an.jsx)(B.Provider,{value:R,children:e.children})}function N(){return(0,C.useContext)(B).client}function ne(){return(0,C.useContext)(B).apiKey}function Ve(){return(0,C.useContext)(B).initialAssignments}function Fe(){return(0,C.useContext)(B).sessionSegment}function Yt(){return(0,C.useContext)(B).ssrFallback}function Me(){return(0,C.useContext)(B).onAssignment}function Qt(){return(0,C.useContext)(B).debug}function en(){let e=(0,C.useContext)(B).initialLayoutOrder,t=(0,C.useSyncExternalStore)(J,()=>{var n;return typeof window=="undefined"?null:(n=window.__sentient_layout_override)!=null?n:null},()=>null);return t!=null?t:e}function $e(){return(0,C.useContext)(B).initialSlots}function tn(){return(0,C.useContext)(B).initialPersona}function nn(){return(0,C.useContext)(B).initialSlotConfig}function rn(){return(0,C.useContext)(B).initialPalette}function on(){return(0,C.useContext)(B).initialVocabulary}function sn(){return(0,C.useContext)(B).apiBaseUrl}var ke=require("react");var V=require("react"),ln=require("@sentientui/core");var H=require("react"),Be=require("@sentientui/policy");function we(e){var n;if(typeof window=="undefined")return null;let t=(n=window.__sentient_overrides)==null?void 0:n[e];if(t)return t;if(!window.location.search)return null;try{let r=new URLSearchParams(window.location.search);for(let i of r.getAll("sentient_variant")){let l=i.indexOf(":");if(l!==-1&&i.slice(0,l)===e)return i.slice(l+1)}}catch(r){}return null}function je(e,t,n,r){let i=Ve(),l=Yt(),d=N(),o=Fe(),m=Me(),s=Qt(),y=(0,H.useRef)(null),f=(0,H.useSyncExternalStore)(J,()=>we(e),()=>null),h=f&&t.includes(f)?f:null,R=(0,H.useRef)(null);(0,H.useEffect)(()=>{s&&h&&R.current!==h&&(R.current=h,console.info(`[sentient] override active: ${e} -> ${h}`))},[s,h,e]);let[c,u]=(0,H.useState)(()=>{var S,x;if(h)return{variantId:h,content:null,isLoading:!1,settled:!0};if(!d){let A=i[e];return A&&t.includes(A)?{variantId:A,content:null,isLoading:!1,settled:!0}:l==="first"&&t.length>0?{variantId:t[0],content:null,isLoading:!1,settled:!1}:{variantId:null,content:null,isLoading:!0,settled:!1}}let g=d.getAssignment(e,o);if(g&&(t.includes(g.variantId)||g.content))return{variantId:g.variantId,content:(S=g.content)!=null?S:null,isLoading:!1,settled:!0};let a=et(e);if(a){let A=(0,Be.pickFromWeights)(a.variants,t);if(A)return{variantId:A,content:null,isLoading:!1,settled:!0}}return{variantId:(x=t[0])!=null?x:null,content:null,isLoading:!1,settled:!1}}),p=g=>{m&&y.current!==g&&(y.current=g,m(e,g))};return(0,H.useEffect)(()=>{var S;if(h||!d)return;let g=d.getAssignment(e,o);if(g&&(t.includes(g.variantId)||g.content)){u({variantId:g.variantId,content:(S=g.content)!=null?S:null,isLoading:!1,settled:!0}),p(g.variantId);return}let a=et(e);if(a&&c.settled&&c.variantId&&c.variantId===(0,Be.pickFromWeights)(a.variants,t)){p(c.variantId);return}u(x=>{var A;return x.variantId?x:{variantId:(A=t[0])!=null?A:null,content:null,isLoading:!1,settled:!1}})},[h,d,e,o]),(0,H.useEffect)(()=>{if(h||!d)return;let g=d.getAssignment(e,o);if(g&&t.includes(g.variantId))return;let a=!1;return d.assign(e,t,n,r).then(S=>{var x;a||S&&(!t.includes(S.variantId)&&!S.content||(u({variantId:S.variantId,content:(x=S.content)!=null?x:null,isLoading:!1,settled:!0}),p(S.variantId)))}),()=>{a=!0}},[h,d,e,o]),(0,H.useEffect)(()=>{if(!h&&d)return Ct(e,g=>{var x;let a=d.getAssignment(e,o);if(a&&(t.includes(a.variantId)||a.content)){u({variantId:a.variantId,content:(x=a.content)!=null?x:null,isLoading:!1,settled:!0}),p(a.variantId);return}let S=(0,Be.pickFromWeights)(g.variants,t);S&&(u({variantId:S,content:null,isLoading:!1,settled:!0}),p(S))})},[h,d,e,o]),h?{variantId:h,content:null,isLoading:!1,settled:!0,isOverride:!0}:c}function Ke(e,t,n){let r=N(),i=ne(),l=Object.keys(t).join("\0"),d=(0,V.useMemo)(()=>Object.keys(t),[l]),{variantId:o,content:m,isOverride:s=!1,settled:y}=je(e,d,n.agentData,n.agentDataByVariant),[f,h]=(0,V.useState)(null),R=(0,V.useRef)(null),c=(0,V.useCallback)(O=>{R.current=O,h(O)},[]),u=n.goal,p=typeof u=="string"?u:JSON.stringify(u),g=(0,V.useMemo)(()=>u?U(u):null,[p]),a=u?se(u):"";(0,V.useEffect)(()=>Ft({id:e,variantIds:d,goal:a}),[e,d,a]);let S=(0,V.useRef)(null);(0,V.useEffect)(()=>{s||y&&(!r||!o||!i||!f||S.current!==o&&(S.current=o,ae(r,i,e,o)))},[r,o,i,e,f,s,y]);let x=(0,V.useRef)(!1),A=(0,V.useRef)(new Set);(0,V.useEffect)(()=>{x.current=!1,A.current=new Set},[o,g]);let E=n.funnel;(0,V.useEffect)(()=>{s||!y||!r||!E||!g||ye(r,i,e,E,g)},[r,i,e,E,g,s,y]);let b=n.cursorSignal===!0;(0,V.useEffect)(()=>{if(!b||s||!y||!r||!o||!f)return;let O=null,P=0,M=()=>{P=Date.now(),O=setTimeout(()=>{r.track({projectId:i,componentId:e,variantId:o,eventType:"cursor_signal",payload:{hoverDuration:Date.now()-P}}),O=null},800)},D=()=>{O!==null&&(clearTimeout(O),O=null)};return f.addEventListener("mouseenter",M),f.addEventListener("mouseleave",D),()=>{f.removeEventListener("mouseenter",M),f.removeEventListener("mouseleave",D),O!==null&&clearTimeout(O)}},[b,r,o,i,e,f,s,y]);let k=(0,V.useRef)(n.microSignalGoals);k.current=n.microSignalGoals;let w=n.microSignalGoals?JSON.stringify(n.microSignalGoals):"";return(0,V.useEffect)(()=>{if(s||!y||!r||!o||!f)return;let O=Date.now();return(0,ln.attachMicroSignalDetectors)((P,M={})=>{var oe,ue,Y;r.track({projectId:i,componentId:e,variantId:o,eventType:"micro_signal",payload:v({signalType:P},M)});let D=(oe=k.current)==null?void 0:oe[P];if(!D||A.current.has(P))return;A.current.add(P);let q=typeof D=="string"?D:D.name,Z=typeof D=="string"?1:(ue=D.weight)!=null?ue:1,ie=typeof D=="string"?0:(Y=D.stepIndex)!=null?Y:0;r.goal(q,{metadata:v({signalType:P},M),weight:Z,stepIndex:ie})},f,O)},[r,o,i,e,f,w,s,y]),(0,V.useEffect)(()=>{if(s||!y||!r||!o||!f||!g)return;let O=ee(g);return te(f,g,{fireGoal:()=>{x.current||(x.current=!0,r.track({projectId:i,componentId:e,variantId:o,eventType:"goal_achieved",goalType:a,payload:v({reward:1},O!==void 0?{goalValue:O}:{})}),r.goal(a,v({metadata:{componentId:e,variantId:o},weight:1,stepIndex:0},O!==void 0?{value:O}:{})))},fireStep:(P,M,D)=>{r.track({projectId:i,componentId:e,variantId:o,eventType:"goal_achieved",goalType:P,payload:{reward:M}}),r.goal(P,{metadata:{},weight:M,stepIndex:D})}},a)},[r,o,i,e,f,g,a,s,y]),{client:r,variantIds:d,variantId:o,content:m,settled:y,isOverride:s,goalLabel:a,ref:c,nodeRef:R}}var F=require("react"),Ee=require("@sentientui/core"),pt=require("@sentientui/core/region");var K=require("react"),cn=require("@sentientui/core");var un=new Set;function dn(e,t){var x,A,E;let n=N(),r=(0,K.useRef)(t==null?void 0:t.baselineText);r.current=t==null?void 0:t.baselineText;let i=(0,K.useRef)(t==null?void 0:t.render);i.current=t==null?void 0:t.render;let l=(0,K.useRef)(t==null?void 0:t.skeleton);l.current=t==null?void 0:t.skeleton;let d=$e(),o=nn(),m=rn(),s=on(),y=(0,K.useSyncExternalStore)(J,()=>{var b;return typeof window!="undefined"?(b=window.__sentient_slot_config_overrides)==null?void 0:b[e]:void 0},()=>{}),f=(0,K.useSyncExternalStore)(J,()=>{var b;return typeof window!="undefined"?(b=window.__sentient_slot_overrides)==null?void 0:b[e]:void 0},()=>{}),h=b=>b==null?"":(0,cn.armOfResult)(b),R=(0,K.useCallback)(b=>{var k,w;return(w=(k=n==null?void 0:n.onSlotsChanged)==null?void 0:k.call(n,b))!=null?w:(()=>{})},[n]);(0,K.useSyncExternalStore)(R,()=>{var b;return(b=n==null?void 0:n.getSlotConfig(e))!=null?b:null},()=>null),(0,K.useSyncExternalStore)(R,()=>h(n==null?void 0:n.getSlotResult(e)),()=>"");let c=y===void 0?o[e]:void 0,u=y===void 0&&c===void 0&&n?n.getSlotConfig(e):null,p=(x=m!=null?m:n==null?void 0:n.getSitePalette())!=null?x:null,g=(E=s!=null?s:(A=n==null?void 0:n.getStyleVocabulary)==null?void 0:A.call(n))!=null?E:null,a=(()=>{var b,k,w;if(y!==void 0)return{config:y,arm:h(f),palette:p,vocabulary:(b=Bt())!=null?b:g,source:"override"};if(c!==void 0)return{config:c,arm:h((k=d[e])!=null?k:n==null?void 0:n.getSlotResult(e)),palette:p,vocabulary:g,source:"preloaded"};if(u!==null){let O=n!=null&&n.isSlotDecided?n.isSlotDecided(e):!0;return{config:u,arm:h((w=n==null?void 0:n.getSlotResult(e))!=null?w:d[e]),palette:p,vocabulary:g,source:O?"client":"seeded"}}return{config:null,arm:"",palette:p,vocabulary:g,source:"none"}})(),S=a.source==="preloaded"||a.source==="override";return(0,K.useEffect)(()=>{var q,Z,ie,oe,ue;if(!n||n.isLocal===!0||S)return;let b=a.source==="none",k=b&&(Z=(q=r.current)==null?void 0:q.call(r))!=null?Z:null,w=k!=null&&k!==""?{[e]:k}:void 0,O=(ie=i.current)==null?void 0:ie.call(i),P=b&&(ue=(oe=l.current)==null?void 0:oe.call(l))!=null?ue:null,M=v(v({},O?{render:{[e]:O}}:{}),P?{skeletons:{[e]:P}}:{}),D=Object.keys(M).length>0;return n.requestSlots?D?n.requestSlots([e],w,M):w?n.requestSlots([e],w):n.requestSlots([e]):b&&(P?n.reportSlots([e],w!=null?w:{},{[e]:P}):w?n.reportSlots([e],w):n.reportSlots([e])),()=>{var Y;return(Y=n.cancelSlots)==null?void 0:Y.call(n,[e])}},[n,S,a.source,e]),(0,K.useEffect)(()=>{!T()||(n==null?void 0:n.isLocal)!==!0||a.source!=="none"||un.has(e)||(un.add(e),console.warn(`[sentient] <Adaptive id="${e}"> is rendering its baseline children: in local/keyless mode <Adaptive> serves ONLY what you pass as \`initialSlotConfig\` (there is no registry to decide from). Pass initialSlotConfig/initialSlots to <AdaptiveProvider> to preview arms locally.`))},[n,a.source,e]),a}var Oe=require("react");var L=require("react/jsx-runtime"),le={none:"0",sm:"8px",md:"16px",lg:"24px"},ut={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch",between:"space-between"},pn={sm:"0.875em",md:"1em",lg:"1.25em"},yr={sm:"1.25em",md:"1.5em",lg:"2em"},fn={sm:"6px 14px",md:"10px 20px",lg:"14px 28px"},gn={sm:"8px",md:"16px",lg:"32px"},vr={square:"1 / 1",landscape:"4 / 3",wide:"16 / 9"},Sr={normal:"400",medium:"500",bold:"700"};function mn(e,t){return v(v({},e==="muted"?t!=null&&t.muted?{color:t.muted}:{opacity:.7}:{}),e==="accent"?v({fontWeight:600},t!=null&&t.accent?{color:t.accent}:{}):{})}function yn(e,t,n){var i,l,d,o;let r=t==null?void 0:t.accent;return I(v({display:"inline-block",padding:(i=fn[n!=null?n:"md"])!=null?i:fn.md,borderRadius:(l=t==null?void 0:t.radius)!=null?l:"8px",font:"inherit"},n?{fontSize:pn[n]}:{}),{textDecoration:e==="ghost"?"underline":"none",cursor:"pointer",background:e==="primary"?(d=t==null?void 0:t.primaryBg)!=null?d:"#111827":"transparent",color:e==="primary"?(o=t==null?void 0:t.primaryText)!=null?o:"#ffffff":r!=null?r:"inherit",border:e==="secondary"?`1px solid ${r!=null?r:"currentColor"}`:"none"})}function hr({node:e,opts:t}){var i,l,d,o,m;let n=(i=e.emphasis)!=null?i:"primary",r={padding:"8px 10px",font:"inherit",border:`1px solid ${(d=(l=t.palette)==null?void 0:l.border)!=null?d:"currentColor"}`,borderRadius:(m=(o=t.palette)==null?void 0:o.radius)!=null?m:"8px"};return(0,L.jsxs)("form",{onSubmit:s=>{var h,R,c;s.preventDefault();let y=new FormData(s.currentTarget),f={};for(let u of e.fields)f[u.name]=String((h=y.get(u.name))!=null?h:"");(R=t.onFormGoal)==null||R.call(t,e.submitGoal);try{(c=t.onFormSubmit)==null||c.call(t,f)}catch(u){}},style:{display:"flex",flexDirection:"column",gap:"12px"},children:[e.fields.map(s=>{var y,f;return(0,L.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:"4px",font:"inherit"},children:[s.label,s.kind==="textarea"?(0,L.jsx)("textarea",{name:s.name,required:s.required,placeholder:s.placeholder,rows:3,style:r}):s.kind==="select"?(0,L.jsx)("select",{name:s.name,required:s.required,style:r,children:((y=s.options)!=null?y:[]).map(h=>(0,L.jsx)("option",{value:h,children:h},h))}):(0,L.jsx)("input",{name:s.name,type:(f=s.inputType)!=null?f:"text",required:s.required,placeholder:s.placeholder,style:r})]},s.name)}),(0,L.jsx)("button",{type:"submit",style:yn(n,t.palette),children:e.submitLabel})]})}function br(e,t){var r,i;let n=e.like;return n?(i=(r=t.vocabulary)==null?void 0:r.entries.find(l=>l.id===n))==null?void 0:i.classes:void 0}function vn(e,t){var r;let n=e?(r=t.vocabulary)==null?void 0:r.entries.find(i=>i.id===e):void 0;return n!=null&&n.computed.inheritsColor?n.computed.color:void 0}function ge(e,t){var i;let n=xr(e,t),r=vn(e.like,t);return n&&r?(0,Oe.cloneElement)(n,{style:I(v({},(i=n.props.style)!=null?i:{}),{color:r})}):n}function xr(e,t){var n,r,i,l,d,o,m,s,y,f,h,R,c,u,p,g,a,S,x,A,E,b,k;try{let w=br(e,t);switch(e.type){case"stack":{let O=(r=le[(n=e.gap)!=null?n:"md"])!=null?r:le.md,P=e.surface==="raised"&&!w,M=(i=e.pad)!=null?i:P?"md":void 0;return(0,L.jsx)("div",I(v({},w?{className:w}:{}),{style:v(v(v(v(v({display:"flex",flexDirection:e.direction,gap:O},e.align?{alignItems:ut[e.align]}:{}),e.justify?{justifyContent:ut[e.justify]}:{}),e.wrap?{flexWrap:"wrap"}:{}),M?{padding:(l=le[M])!=null?l:le.md}:{}),P?I(v(v({},(d=t.palette)!=null&&d.surface?{background:t.palette.surface}:{}),(o=t.palette)!=null&&o.surface&&((m=t.palette)!=null&&m.surfaceText)?{color:t.palette.surfaceText}:{}),{border:`1px solid ${(y=(s=t.palette)==null?void 0:s.border)!=null?y:"currentColor"}`,borderRadius:(h=(f=t.palette)==null?void 0:f.radius)!=null?h:"8px"}):{}),children:((R=e.children)!=null?R:[]).map((D,q)=>{let Z=ge(D,t);return Z===null?null:(0,L.jsx)(Oe.Fragment,{children:Z},q)})}))}case"grid":{let O=(u=le[(c=e.gap)!=null?c:"md"])!=null?u:le.md;return(0,L.jsx)("div",I(v({},w?{className:w}:{}),{style:v(v({display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(max(200px, calc((100% - ${e.columns-1} * ${O}) / ${e.columns})), 1fr))`,gap:O},e.align?{alignItems:ut[e.align]}:{}),e.pad?{padding:(p=le[e.pad])!=null?p:le.md}:{}),children:((g=e.children)!=null?g:[]).map((P,M)=>{let D=ge(P,t);return D===null?null:(0,L.jsx)(Oe.Fragment,{children:D},M)})}))}case"text":return w?(0,L.jsx)("p",{className:w,style:e.maxWidth==="measure"?{maxWidth:"65ch"}:void 0,children:e.value}):(0,L.jsx)("p",{style:v(v(v(v(v({margin:0},e.size?{fontSize:pn[e.size]}:{}),e.weight?{fontWeight:Sr[e.weight]}:{}),e.align?{textAlign:e.align}:{}),e.maxWidth==="measure"?{maxWidth:"65ch"}:{}),mn(e.tone,t.palette)),children:e.value});case"heading":{let O=`h${e.level}`;return w?(0,L.jsx)(O,{className:w,style:e.maxWidth==="measure"?{maxWidth:"65ch"}:void 0,children:e.value}):(0,L.jsx)(O,{style:v(v({margin:0,fontSize:yr[(a=e.size)!=null?a:"md"]},e.align?{textAlign:e.align}:{}),e.maxWidth==="measure"?{maxWidth:"65ch"}:{}),children:e.value})}case"button":{let O=(S=e.emphasis)!=null?S:"primary";return(0,L.jsx)("a",I(v(v({href:e.href},e.tag?{"data-sentient-tag":e.tag}:{}),w?{className:w}:{style:yn(O,t.palette,e.size)}),{children:e.label}))}case"link":return(0,L.jsx)("a",I(v(v({href:e.href},e.tag?{"data-sentient-tag":e.tag}:{}),w?{className:w}:{style:{color:"inherit",textDecoration:"underline"}}),{children:e.label}));case"image":return(0,L.jsx)("img",I(v({src:e.src,alt:e.alt},w?{className:w}:{}),{style:v(v({display:"block",maxWidth:"100%"},e.ratio&&e.ratio!=="auto"?{aspectRatio:vr[e.ratio],width:"100%"}:{}),e.fit?{objectFit:e.fit}:{})}));case"badge":return w?(0,L.jsx)("span",{className:w,children:e.value}):(0,L.jsx)("span",{style:v({display:"inline-block",padding:"2px 10px",borderRadius:"999px",fontSize:"0.75em",border:`1px solid ${(A=(x=t.palette)==null?void 0:x.border)!=null?A:"currentColor"}`},mn(e.tone,t.palette)),children:e.value});case"spacer":return(0,L.jsx)("div",{style:{height:(E=gn[e.size])!=null?E:gn.md}});case"divider":return(0,L.jsx)("hr",{style:{border:"none",borderTop:`1px solid ${(k=(b=t.palette)==null?void 0:b.border)!=null?k:"currentColor"}`,margin:0,width:"100%"}});case"form":return(0,L.jsx)(hr,{node:e,opts:t});default:return null}}catch(w){return null}}function We(e,t){var l,d,o,m;let n=ge(e.tree,t);if(n===null)return null;let r=(l=e.surface)!=null&&l.like?(o=(d=t.vocabulary)==null?void 0:d.entries.find(s=>s.id===e.surface.like))==null?void 0:o.classes:void 0,i=vn((m=e.surface)==null?void 0:m.like,t);return r?(0,L.jsx)("div",I(v({className:r},i?{style:{color:i}}:{}),{children:n})):n}var re=require("react"),Je=require("@sentientui/core/region");function Ue(e){return typeof e=="string"&&e.trim()!==""||typeof e=="number"}function He(e){let t=e.props;if(t.dangerouslySetInnerHTML==null)return t.children}function me(e){return Ue(e)?1:Array.isArray(e)?e.reduce((t,n)=>t+me(n),0):(0,re.isValidElement)(e)?me(He(e)):0}function wr(e,t){return Array.isArray(t)?(0,re.cloneElement)(e,void 0,...t):(0,re.cloneElement)(e,void 0,t)}function ct(e,t){if(Ue(e))return t;if(Array.isArray(e))return e.map(n=>ct(n,t));if((0,re.isValidElement)(e)){let n=He(e);return me(n)===0?e:wr(e,ct(n,t))}return e}function Sn(e,t){return me(e)===1?ct(e,t):null}var W=e=>e.join("/");function dt(e,t,n){if(Ue(e)){n.leafPaths.push(t),n.texts.push((0,Je.normalizeLeafText)(String(e)));return}if(Array.isArray(e)){e.forEach((r,i)=>dt(r,[...t,i],n));return}(0,re.isValidElement)(e)&&(n.elements.set(W(t),e),dt(He(e),[...t,"c"],n))}function gt(e){let t={leafPaths:[],texts:[],elements:new Map};return dt(e,[],t),t}function kr(e){return gt(e).texts}function hn(e){let t=kr(e);return t.length===0?null:(0,Je.skeletonFingerprint)(t)}function Rr(e){let t=[];return e.forEach((n,r)=>{n==="c"&&t.push(e.slice(0,r))}),t}function bn(e,t){let n=t.reduce((i,l)=>Math.max(i,l+1),0),r=[];for(let i=0;i<n;i++){let l=t.flatMap((o,m)=>o===i?[Rr(e.leafPaths[m])]:[]);if(l.length===0){r.push(null);continue}let d=l[0];for(let o of l.slice(1)){let m=new Set(o.map(W));d=d.filter(s=>m.has(W(s)))}r.push(d.length>0?d[d.length-1]:null)}return r}function ft(e){var n;let t=(n=e==null?void 0:e.props)==null?void 0:n.className;return typeof t=="string"?t:void 0}function mt(e,t){let n=gt(t);if(n.texts.length!==e.leaves.length||n.texts.some((l,d)=>l!==e.leaves[d]))return null;let r=bn(n,e.leafToNode),i=e.nodes.map((l,d)=>{let o=r[d],m=o?n.elements.get(W(o)):void 0,s=!!m&&(typeof m.type=="string"||ft(m)!==void 0);return I(v({},l),{restylable:s})});return I(v({},e),{nodes:i})}function xn(e,t,n){var c;let r=gt(e);if(r.leafPaths.length!==n.length)return null;let i=n.reduce((u,p)=>Math.max(u,p+1),0);for(let u of Object.keys(t.nodes))if(!/^\d+$/.test(u)||Number(u)>=i)return null;let l=bn(r,n),d=new Map;n.forEach((u,p)=>{d.has(u)||d.set(u,p)});let o=new Map(r.leafPaths.map((u,p)=>[W(u),p])),m=new Set,s=new Map,y=!1;for(let[u,p]of Object.entries(t.nodes)){let g=Number(u),a=l[g];if(p.hidden&&(a?m.add(W(a)):y=!0),p.like!==void 0){let S=l[p.like],x=a?r.elements.get(W(a)):void 0,A=S?ft(r.elements.get(W(S))):void 0;!a||A===void 0||ft(x)===void 0?y=!0:s.set(W(a),A)}}let f=new Map(Object.entries((c=t.order)!=null?c:{})),h=(u,p)=>{var g;if(Ue(u)){let a=o.get(W(p));if(a===void 0)return u;let S=n[a],x=(g=t.nodes[String(S)])==null?void 0:g.text;return x===void 0?u:d.get(S)===a?x:""}if(Array.isArray(u)){let a=u.map((S,x)=>h(S,[...p,x]));for(let[S,x]of f){let A=x.map(k=>{let w=l[k];return!w||w.length!==p.length+1||W(w.slice(0,-1))!==W(p)?-1:w[w.length-1]});if(A.some(k=>k<0))continue;let E=[...A].sort((k,w)=>k-w),b=[...a];E.forEach((k,w)=>{a[k]=b[A[w]]}),f.delete(S)}return a}if((0,re.isValidElement)(u)){let a=W(p);if(m.has(a))return null;let S=He(u);if(me(S)===0)return u;let x=h(S,[...p,"c"]),A=s.get(a),E=A!==void 0?{className:A}:void 0;return Array.isArray(x)?(0,re.cloneElement)(u,E,...x):(0,re.cloneElement)(u,E,x)}return u},R=h(e,[]);return y||f.size>0?null:R}var Cn=require("react/jsx-runtime"),wn=new Set,kn=new Set,Rn=new Set,An="authored.";function Pe({id:e,children:t,variants:n,onFormSubmit:r,goal:i,className:l,reportBaselineText:d=!0}){var ht,bt;let o=N(),m=ne(),s=(0,F.useRef)(null),y=(0,F.useMemo)(()=>hn(t),[t]),f=n?Object.keys(n).join("|"):"",h=(0,F.useMemo)(()=>v({fp:y!=null?y:"0000000000000000",forms:!!r,compose:!0,content:me(t)===1},f!==""?{authored:f.split("|"),children:!0}:{}),[y,t,r,f]),R=()=>{var Q;let _=s.current;if(!_||!d)return null;let G=(0,pt.captureRegionSkeleton)(_);return G.skeleton?(Q=mt(G.skeleton,t))!=null?Q:I(v({},G.skeleton),{editable:!1,nodes:G.skeleton.nodes.map(ce=>I(v({},ce),{restylable:!1}))}):{status:G.reason}},{config:c,arm:u,palette:p,vocabulary:g,source:a}=dn(e,{baselineText:d?()=>{var _,G;return(G=(_=s.current)==null?void 0:_.textContent)!=null?G:null}:void 0,render:()=>h,skeleton:R}),S=u!==""?(ht=c==null?void 0:c.blocks)==null?void 0:ht[u]:void 0,x=u!==""?(bt=c==null?void 0:c.compose)==null?void 0:bt[u]:void 0,A=(S!==void 0&&(0,Ee.containsFormBlock)(S)||x!==void 0&&(0,Ee.containsFormBlock)(x.tree))&&!r;(0,F.useEffect)(()=>{!A||!T()||wn.has(e)||(wn.add(e),console.warn(`[sentient] AdaptiveSlot "${e}" was served a form arm but has no onFormSubmit handler \u2014 rendering its baseline children instead. Pass onFormSubmit to render generated forms.`))},[A,e]);let E=_=>{!o||a==="override"||(a!=="seeded"&&o.componentGoal(e,_),o.goal(_,{metadata:{componentId:e,arm:u},weight:1,stepIndex:0}))},b=t,k=!1,w=u.startsWith(An)?u.slice(An.length):null;if((c==null?void 0:c.blocked)==="variant_history")k=!0;else if(w!==null)n&&Object.prototype.hasOwnProperty.call(n,w)?b=n[w]:k=!0;else if(x!==void 0){let _=A?null:We(x,{palette:p,vocabulary:g,onFormSubmit:r,onFormGoal:E});_===null?k=!0:b=_}else if(S!==void 0){let _=A?null:ge(S,{palette:p,vocabulary:g,onFormSubmit:r,onFormGoal:E});_===null?k=!0:b=_}else if((c==null?void 0:c.edits)!==void 0&&a!=="none"){let _=c.edits,G=_.fp===y?xn(t,_.edits,_.leafToNode):null;G===null?k=!0:b=G}else if((c==null?void 0:c.content)!==void 0&&a!=="none"){let _=Sn(t,c.content);_===null?k=!0:b=_}let O=k&&S===void 0&&x===void 0&&(c==null?void 0:c.edits)===void 0&&w===null&&(c==null?void 0:c.blocked)===void 0;(0,F.useEffect)(()=>{(c==null?void 0:c.blocked)!=="variant_history"||!T()||Rn.has(e)||(Rn.add(e),console.warn(`[sentient] <Adaptive id="${e}"> has results from its earlier variants experiment, so it is showing your original until you migrate it: Components \u2192 "${e}" \u2192 Migrate. Deploying code never switches an experiment.`))},[c==null?void 0:c.blocked,e]);let P=w!==null&&!k?w:null;(0,F.useEffect)(()=>{var Ae;if(!P||!d||!o)return;let _=s.current;if(!_)return;let G=(0,pt.captureRegionSkeleton)(_),Q=G.skeleton?mt(G.skeleton,n==null?void 0:n[P]):null,ce=(Ae=_.textContent)==null?void 0:Ae.trim();o.reportSlots([],void 0,void 0,{[e]:[v(v({key:P},ce?{text:ce}:{}),Q?{skeleton:Q}:{})]})},[P,o,e]);let M=k&&(c==null?void 0:c.edits)!==void 0&&(a==="preloaded"||a==="client");(0,F.useEffect)(()=>{var _;!M||!(c!=null&&c.edits)||(_=o==null?void 0:o.reportDrift)==null||_.call(o,e,c.edits.fp,y,c.edits.fp===y?"unaddressable":"fp_mismatch")},[M,e,y,o]);let D=b===t;(0,F.useEffect)(()=>{var G;if(!(c!=null&&c.needsSkeleton)||!D)return;let _=R();_&&((G=o==null?void 0:o.reportSkeleton)==null||G.call(o,e,_))},[c==null?void 0:c.needsSkeleton,D,e,o]),(0,F.useEffect)(()=>{if(!D)return;let _=Jt(e);if(!_)return;let G=R();Ut(_,G&&"status"in G?{status:G.status}:{skeleton:G})},[e,D]),(0,F.useEffect)(()=>{!O||!T()||kn.has(e)||(kn.add(e),console.warn(`[sentient] <Adaptive id="${e}"> was served a text version, but its children have several separate texts or none Sentient can reach \u2014 rendering the original instead. Regenerate the version (new versions edit each text in place), or put a single text inline.`))},[O,e]);let q=c!=null&&c.blocks?Object.keys(c.blocks).sort().join("|"):"";(0,F.useEffect)(()=>ve({id:e,arms:q===""?void 0:q.split("|")}),[e,q]);let Z=(0,F.useRef)(null);(0,F.useEffect)(()=>{!o||a==="none"||a==="seeded"||a==="override"||u===""||k||Z.current!==u&&(Z.current=u,ae(o,m,e,u))},[o,m,e,u,a,k]);let ie=a!=="none"&&a!=="seeded"&&!k,oe=ie?u:"",ue=i===void 0?null:typeof i=="string"?i:JSON.stringify(i);(0,F.useEffect)(()=>{if(!o||!i||a==="override")return;let _=s.current;if(!_)return;let G=se(i),Q=ee(i),ce=!1;return te(_,U(i),{fireGoal:()=>{ce||(ce=!0,ie&&(Q!==void 0?o.componentGoal(e,G,{value:Q}):o.componentGoal(e,G)),o.goal(G,v({metadata:{componentId:e,arm:oe},weight:1,stepIndex:0},Q!==void 0?{value:Q}:{})))},fireStep:(Ae,xt,Qn)=>{ie&&o.componentGoal(e,Ae,{reward:xt}),o.goal(Ae,{metadata:{componentId:e,arm:oe},weight:xt,stepIndex:Qn})}},G)},[o,e,ue,u,a,k,ie,oe]);let Y=(0,F.useRef)(null);(0,F.useEffect)(()=>{let _=s.current;if(_){if(Y.current===null){Y.current=u;return}Y.current!==u&&(Y.current=u,(0,Ee.reveal)(_))}},[u]);let Yn=(0,F.useMemo)(()=>v({"data-sentient-slot":e},u!==""?{"data-sentient-arm":u}:{}),[e,u]);return(0,Cn.jsx)("div",I(v({ref:s,className:l},Yn),{children:b}))}var Ge=require("react/jsx-runtime");function Ar(e){var s;let{client:t,variantId:n,content:r,ref:i}=Ke(e.id,e.variants,{goal:e.goal,funnel:e.funnel,microSignalGoals:e.microSignalGoals,agentData:e.agentData,agentDataByVariant:e.agentDataByVariant,cursorSignal:!0}),[l,d]=(0,ke.useState)(!1);if((0,ke.useEffect)(()=>{d(!0)},[]),e.clientOnly&&(!l||!t)||!n)return null;let o=(s=e.variants[n])!=null?s:null,m=o===null?r:null;return T()&&o===null&&m===null&&console.warn(`[sentient] <Adaptive id="${e.id}"> was assigned variant "${n}" but no matching key exists in props.variants. If this is a dashboard-managed text variant, use <AdaptiveText id="${e.id}"> instead.`),(0,Ge.jsx)("div",{ref:i,"data-sentient-id":e.id,"data-sentient-variant":n,children:o!=null?o:m})}var Cr=(0,ke.memo)(Ar,(e,t)=>{if(e.id!==t.id||e.goal!==t.goal&&JSON.stringify(e.goal)!==JSON.stringify(t.goal)||e.microSignalGoals!==t.microSignalGoals||e.funnel!==t.funnel||e.clientOnly!==t.clientOnly||e.agentData!==t.agentData||e.agentDataByVariant!==t.agentDataByVariant)return!1;if(e.variants===t.variants)return!0;let n=Object.keys(e.variants),r=Object.keys(t.variants);return n.length!==r.length?!1:n.every(i=>i in t.variants&&Object.is(e.variants[i],t.variants[i]))});function On(e){if(e.variants===void 0)return(0,Ge.jsx)(Pe,v({},e));let t=e;if(t.children!=null){T()&&_r(t);let n=t,{funnel:r,microSignalGoals:i,agentData:l,agentDataByVariant:d,clientOnly:o,variants:m}=n,s=De(n,["funnel","microSignalGoals","agentData","agentDataByVariant","clientOnly","variants"]);return(0,Ge.jsx)(Pe,I(v({},s),{children:t.children,variants:m}))}return(0,Ge.jsx)(Cr,v({},t))}var _n=new Set;function _r(e){let t=["funnel","microSignalGoals","agentData","agentDataByVariant","clientOnly"].filter(n=>e[n]!==void 0);t.length===0||_n.has(e.id)||(_n.add(e.id),console.warn(`[sentient] <Adaptive id="${e.id}"> has both variants and children, so it runs as one experiment with your original and generated versions. These props only apply to a variants-only component and are ignored here: ${t.join(", ")}.`))}var $=require("react");var Pn=require("react/jsx-runtime");function En({id:e,default:t,component:n="span",className:r,goal:i}){var E;let l=N(),d=ne(),o=Me(),m=Fe(),s=(0,$.useRef)(null),y=(0,$.useRef)(null),f=(0,$.useSyncExternalStore)(J,()=>we(e),()=>null),[h,R]=(0,$.useState)(()=>{var b,k;return(k=(b=l==null?void 0:l.getAssignment(e,m))==null?void 0:b.content)!=null?k:null}),[c,u]=(0,$.useState)(()=>{var b,k;return(k=(b=l==null?void 0:l.getAssignment(e,m))==null?void 0:b.variantId)!=null?k:null});(0,$.useEffect)(()=>{if(f||!l)return;let b=l.getAssignment(e,m);if((b==null?void 0:b.content)!==void 0){u(b.variantId),R(b.content);return}let k=!1;return l.assign(e).then(w=>{if(!k){if(!w){T()&&console.warn(`[sentient] <AdaptiveText id="${e}"> assignment failed \u2014 showing default text.`);return}u(w.variantId),w.content&&R(w.content)}}),()=>{k=!0}},[l,e,m,f]),(0,$.useEffect)(()=>{f||!l||!c||!d||s.current!==c&&(s.current=c,l.track({projectId:d,componentId:e,variantId:c,eventType:"variant_assigned",payload:{}}),o==null||o(e,c))},[l,c,d,e,o,f]);let p=i===void 0?"":typeof i=="string"?i:JSON.stringify(i),g=(0,$.useMemo)(()=>i===void 0?null:U(i),[p]),a=i===void 0?null:typeof i=="string"?i:g.type,S=(0,$.useRef)(!1);(0,$.useEffect)(()=>{S.current=!1},[c,p]),(0,$.useEffect)(()=>{if(f||!l||!c||!d||!g||!a)return;let b=y.current;if(!b)return;let k=ee(g);return te(b,g,{fireGoal:()=>{S.current||(S.current=!0,l.track({projectId:d,componentId:e,variantId:c,eventType:"goal_achieved",goalType:a,payload:v({reward:1},k!==void 0?{goalValue:k}:{})}),l.goal(a,v({metadata:{componentId:e,variantId:c},weight:1,stepIndex:0},k!==void 0?{value:k}:{})))},fireStep:(w,O,P)=>{l.track({projectId:d,componentId:e,variantId:c,eventType:"goal_achieved",goalType:w,payload:{reward:O}}),l.goal(w,{metadata:{},weight:O,stepIndex:P})}})},[l,c,d,e,g,a,f]);let x=h!=null?h:t;if(f){let b=l==null?void 0:l.getAssignment(e,m);x=b&&b.variantId===f&&(E=b.content)!=null?E:t}return(0,Pn.jsx)(n,{ref:b=>{y.current=b},className:r,children:x})}var Xe=require("react");function ze(e){let t=N(),n=(0,Xe.useRef)(new Set);return(0,Xe.useCallback)((r,i)=>{var l,d;if(!we(e)){if(i!=null&&i.once){if(n.current.has(r))return;n.current.add(r)}t==null||t.componentGoal(e,r,i),t==null||t.goal(r,v(v(v({metadata:(l=i==null?void 0:i.metadata)!=null?l:{},weight:(d=i==null?void 0:i.reward)!=null?d:1,stepIndex:0},(i==null?void 0:i.value)!==void 0?{value:i.value}:{}),(i==null?void 0:i.currency)!==void 0?{currency:i.currency}:{}),(i==null?void 0:i.externalId)!==void 0?{externalId:i.externalId}:{}))}},[t,e])}var Te=require("react");function Gn(e,t={}){let m=t,{componentId:n}=m,r=De(m,["componentId"]),i=N(),l=ze(n!=null?n:""),d=(0,Te.useRef)(!1),o=(0,Te.useRef)(r);o.current=r,(0,Te.useEffect)(()=>{if(!i||d.current)return;d.current=!0;let{metadata:s,reward:y,value:f,currency:h,externalId:R}=o.current;if(n){l(e,o.current);return}i.goal(e,v(v(v({metadata:s!=null?s:{},weight:y!=null?y:1,stepIndex:0},f!==void 0?{value:f}:{}),h!==void 0?{currency:h}:{}),R!==void 0?{externalId:R}:{}))},[i,n,e,l])}var Ln=require("@sentientui/core"),Dn=require("@sentientui/policy"),Nn=require("react/jsx-runtime");function Tn(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function Or(e){return e.persona?'(function(){try{var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+Tn(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+Tn((0,Dn.confidenceBand)(e.persona.confidence))+");}catch(e){}})();":(0,Ln.renderPrePaintScript)(e.apiKey)}function In(e){return(0,Nn.jsx)("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:Or(e)}})}var z=require("react"),$n=require("@sentientui/policy");var X=require("react"),pe=require("@sentientui/core"),Vn=require("@sentientui/policy");function qe(e,t){let n=N(),r=$e(),[,i]=(0,X.useReducer)(f=>f+1,0),l=(0,X.useSyncExternalStore)(J,()=>{var f;return typeof window!="undefined"?(f=window.__sentient_slot_overrides)==null?void 0:f[e]:void 0},()=>{}),d=l===void 0?r[e]:void 0,o=l===void 0&&d===void 0&&n?n.getSlotResult(e):null,m=(n==null?void 0:n.isLocal)===!0&&l===void 0&&d===void 0&&o===null;(0,X.useEffect)(()=>{if(!m||!n)return;let f=!1;return n.decide({slots:[t]}).then(h=>{!f&&h&&i()}),()=>{f=!0}},[n,e,m]);let s=(()=>{if(l!==void 0)return{result:l,arm:(0,pe.armOfResult)(l),source:"override"};if(d!==void 0)return{result:d,arm:(0,pe.armOfResult)(d),source:"preloaded"};if(o!==null){let h=n!=null&&n.isSlotDecided?n.isSlotDecided(e):!0;return{result:o,arm:(0,pe.armOfResult)(o),source:h?"client":"seeded"}}let f=(0,pe.baselineResultFor)(t);return{result:f,arm:(0,pe.armOfResult)(f),source:"baseline"}})(),y=s.source==="preloaded"||s.source==="override";return(0,X.useEffect)(()=>{var h;if(!n||n.isLocal===!0||y||!n.decideSlots)return;let f=(h=n.onSlotsChanged)==null?void 0:h.call(n,i);return n.decideSlots([t]),()=>{var R;(R=n.cancelSlots)==null||R.call(n,[e]),f==null||f()}},[n,e,y]),s}function Er(){var t;if(typeof window=="undefined")return null;let e=window.__sentient_persona_override;if(e!=null&&e.persona)return{persona:e.persona,confidence:(t=e.confidence)!=null?t:1};try{let n=new URLSearchParams(window.location.search).get("sentient_persona");if(n)return{persona:n,confidence:1}}catch(n){}return null}function Fn(){let e=N(),t=tn();(0,X.useSyncExternalStore)(J,Gt,()=>0);let[n,r]=(0,X.useState)(!1);(0,X.useEffect)(()=>r(!0),[]);let i=o=>({persona:o.persona,confidence:o.confidence,band:(0,Vn.confidenceBand)(o.confidence)});if(!n)return t?i(t):null;let l=Er();if(l)return i(l);if(t)return i(t);let d=e?e.getPersona():null;return d?i(d):null}var Mn=new Set;function Pr(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[\\"]/g,"\\$&")}function Bn(e,t,n){let r=N(),i=ne(),l=JSON.stringify(t),d=(0,z.useMemo)(()=>({id:e,dims:t}),[e,l]),{result:o,arm:m,source:s}=qe(e,d),y=(0,z.useMemo)(()=>typeof o=="string"?{}:o,[m]);if(T()&&!Mn.has(e)){Mn.add(e);let u=(0,$n.validateSlotDecl)({id:e,dims:Object.fromEntries(Object.entries(t).map(([g,a])=>[g,[...a]]))}),p=Object.values(t).reduce((g,a)=>g*a.length,1);u.ok?p>4&&console.warn(`[sentient] useAdaptiveTokens("${e}") declares ${p} combinations \u2014 more than the recommended 4. Each extra combination needs more traffic to learn; consider fewer dims/values.`):console.warn(`[sentient] useAdaptiveTokens("${e}"): invalid declaration \u2014 ${u.reason}. Serving baseline.`)}let f=(n==null?void 0:n.goal)===void 0?null:typeof n.goal=="string"?n.goal:JSON.stringify(n.goal);(0,z.useEffect)(()=>ve({id:e,dims:t}),[e]);let h=(0,z.useRef)(null);(0,z.useEffect)(()=>{!r||s==="baseline"||s==="seeded"||s==="override"||h.current===m||(h.current=m,ae(r,i,e,m))},[r,i,e,m,s]);let R=n==null?void 0:n.funnel;(0,z.useEffect)(()=>{var u;!r||!R||s==="override"||ye(r,i,e,R,U((u=n==null?void 0:n.goal)!=null?u:"click"))},[r,i,e,R,f,s]),(0,z.useEffect)(()=>{if(!r||!(n!=null&&n.goal)||s==="override"||s==="baseline"||s==="seeded")return;let u=document.querySelector(`[data-sentient-slot="${Pr(e)}"]`);if(!u){T()&&console.warn(`[sentient] useAdaptiveTokens("${e}"): a goal is declared but no element carries the returned props \u2014 spread {...props} on the slot's element.`);return}let p=se(n.goal),g=ee(n.goal),a=!1;return te(u,U(n.goal),{fireGoal:()=>{a||(a=!0,g!==void 0?r.componentGoal(e,p,{value:g}):r.componentGoal(e,p),r.goal(p,v({metadata:{componentId:e,arm:m},weight:1,stepIndex:0},g!==void 0?{value:g}:{})))},fireStep:(S,x,A)=>{r.componentGoal(e,S,{reward:x}),r.goal(S,{metadata:{componentId:e,arm:m},weight:x,stepIndex:A})}},p)},[r,e,f,m,s]);let c=(0,z.useMemo)(()=>{let u={"data-sentient-slot":e};for(let[p,g]of Object.entries(y))u[`data-${p}`]=g;return u},[e,y]);return{tokens:y,props:c}}var Re=require("react");var jn=new Set;function Kn(e,t){var R;if(T()&&!t.goal)throw new Error(`[sentient] useAdaptive("${e}"): a goal is required \u2014 without one the optimizer accumulates exposures with no rewards and cannot learn. Pass e.g. goal: 'buy_click'.`);let{client:n,variantIds:r,variantId:i,isOverride:l,goalLabel:d,ref:o,nodeRef:m}=Ke(e,t.variants,{goal:t.goal,funnel:t.funnel,microSignalGoals:t.microSignalGoals}),s=(R=i!=null?i:r[0])!=null?R:"",y=t.variants[s];(0,Re.useEffect)(()=>{if(!T()||!n)return;let c=setTimeout(()=>{!m.current&&!jn.has(e)&&(jn.add(e),console.warn(`[sentient] useAdaptive("${e}"): bind was never attached \u2014 spread {...bind} on the rendered element, otherwise exposure and goal tracking cannot work and the optimizer learns nothing.`))},0);return()=>clearTimeout(c)},[n,e]);let f=(0,Re.useCallback)((c,u)=>{var g,a;if(l)return;let p=c!=null?c:d;p&&(n==null||n.componentGoal(e,p,u),n==null||n.goal(p,v(v(v({metadata:(g=u==null?void 0:u.metadata)!=null?g:{},weight:(a=u==null?void 0:u.reward)!=null?a:1,stepIndex:0},(u==null?void 0:u.value)!==void 0?{value:u.value}:{}),(u==null?void 0:u.currency)!==void 0?{currency:u.currency}:{}),(u==null?void 0:u.externalId)!==void 0?{externalId:u.externalId}:{})))},[n,e,d,l]),h=(0,Re.useMemo)(()=>({ref:o,"data-sentient-id":e,"data-sentient-variant":s}),[o,e,s]);return{variant:s,value:y,bind:h,fireGoal:f}}var j=require("react");var Jn=require("react/jsx-runtime"),Ze=new Set;function Wn(e){var g;let t=N(),n=ne(),r=(0,j.useRef)(null),i=Object.keys(e.arrangements).join(" "),l=(0,j.useMemo)(()=>Object.keys(e.arrangements),[i]),d=(0,j.useMemo)(()=>v({id:e.id,arms:l},e.baseline!==void 0?{baseline:e.baseline}:{}),[e.id,l,e.baseline]),{arm:o,source:m}=qe(e.id,d);T()&&e.baseline!==void 0&&e.baseline!==l[0]&&!Ze.has(e.id+":baseline")&&(Ze.add(e.id+":baseline"),console.warn(`[sentient] <AdaptiveGroup id="${e.id}">: baseline "${e.baseline}" is not the first-declared arrangement ("${l[0]}"). The first arrangement should usually be the page's real incumbent (the holdout sees it).`));let s=j.Children.toArray(e.children).filter(j.isValidElement),y=new Map;for(let a of s)y.set(String((g=a.key)!=null?g:"").replace(/^\.\$/,""),a);let f=e.arrangements[o],h=f!==void 0&&f.length===s.length&&f.every(a=>y.has(a));T()&&f!==void 0&&!h&&!Ze.has(e.id+":keys")&&(Ze.add(e.id+":keys"),console.warn(`[sentient] <AdaptiveGroup id="${e.id}">: arrangement "${o}" [${f.join(", ")}] does not match the children's keys \u2014 rendering declaration order (fail-safe).`));let R=h?f.map(a=>y.get(a)):s;(0,j.useEffect)(()=>ve({id:e.id,arms:Object.keys(e.arrangements)}),[e.id]);let c=(0,j.useRef)(null);(0,j.useEffect)(()=>{!t||m==="baseline"||m==="seeded"||m==="override"||c.current===o||(c.current=o,ae(t,n,e.id,o))},[t,n,e.id,o,m]);let u=e.funnel;(0,j.useEffect)(()=>{var a;!t||!u||m==="override"||ye(t,n,e.id,u,U((a=e.goal)!=null?a:"click"))},[t,n,e.id,u,m]);let p=e.goal===void 0?null:typeof e.goal=="string"?e.goal:JSON.stringify(e.goal);return(0,j.useEffect)(()=>{if(!t||e.goal===void 0||m==="override"||m==="baseline"||m==="seeded")return;let a=r.current;if(!a)return;let S=se(e.goal),x=ee(e.goal),A=!1;return te(a,U(e.goal),{fireGoal:()=>{A||(A=!0,x!==void 0?t.componentGoal(e.id,S,{value:x}):t.componentGoal(e.id,S),t.goal(S,v({metadata:{componentId:e.id,arm:o},weight:1,stepIndex:0},x!==void 0?{value:x}:{})))},fireStep:(E,b,k)=>{t.componentGoal(e.id,E,{reward:b}),t.goal(E,{metadata:{componentId:e.id,arm:o},weight:b,stepIndex:k})}},S)},[t,e.id,p,o,m]),(0,Jn.jsx)("div",{ref:r,"data-sentient-id":e.id,"data-sentient-variant":o,children:R})}var yt=require("@sentientui/core");var Gr=["page","blocks","layoutOrder"],Un=new Map;function Hn(e,t){Un.set(e,t)}function vt(e){return Un.get(e)}function Xn(e){var i,l;let t=(l=(i=e.content)!=null?i:vt(e.page))!=null?l:{},n={};for(let[d,o]of Object.entries(t))Gr.includes(d)||(n[d]=o);let r=I(v({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(r.layoutOrder=e.layoutOrder),r}function zn(e){return`<script type="application/ld+json">${St(e)}</script>`}function St(e){return JSON.stringify(v({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function qn(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,r]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(r,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(`
|
|
3
3
|
`).trimEnd()+`
|
|
4
4
|
`}var Zn=require("@sentientui/core");0&&(module.exports={Adaptive,AdaptiveGroup,AdaptiveProvider,AdaptiveSlot,AdaptiveText,SentientPersonaScript,buildAgentFeed,defineAgentContent,detectSegment,getAgentContent,grantConsent,renderAgentJsonLd,renderAgentJsonLdBody,renderAgentMarkdown,renderBlocks,renderCompose,useAdaptive,useAdaptiveApiBaseUrl,useAdaptiveGoal,useAdaptivePersona,useAdaptiveTokens,useAssignment,useInitialAssignments,useLayoutOrder,usePageGoal,useSentient});
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
var Vn=Object.defineProperty,Fn=Object.defineProperties;var Mn=Object.getOwnPropertyDescriptors;var he=Object.getOwnPropertySymbols;var St=Object.prototype.hasOwnProperty,ht=Object.prototype.propertyIsEnumerable;var vt=(e,t,n)=>t in e?Vn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))St.call(t,n)&&vt(e,n,t[n]);if(he)for(var n of he(t))ht.call(t,n)&&vt(e,n,t[n]);return e},L=(e,t)=>Fn(e,Mn(t));var be=(e,t)=>{var n={};for(var r in e)St.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&he)for(var r of he(e))t.indexOf(r)<0&&ht.call(e,r)&&(n[r]=e[r]);return n};import{createContext as Un,useContext as F,useEffect as Y,useMemo as Jt,useRef as qe,useState as we,useSyncExternalStore as Hn}from"react";import{deriveSessionSegment as Xn,init as zn}from"@sentientui/core";var bt=new Map,xe=new Map;function xt(e,t){let n=xe.get(e);return n||(n=new Set,xe.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&xe.delete(e)}}function wt(e,t){bt.set(e,t);let n=xe.get(e);if(n)for(let r of n)try{r(t)}catch(i){}}function Be(e){var t;return(t=bt.get(e))!=null?t:null}var $n={on:!1,listeners:new Set};function kt(){if(typeof window=="undefined")return $n;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function je(){return kt().on}function Rt(e){let t=kt().listeners;return t.add(e),()=>{t.delete(e)}}function At(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,r,i)=>e.assign(t,n,r,i),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var Ke="sentient:overrides-changed";function Ct(){var e;return typeof window=="undefined"?0:(e=window.__sentient_overrides_version)!=null?e:0}function We(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(Ke))}function $(e){return typeof window=="undefined"?()=>{}:(window.addEventListener(Ke,e),()=>window.removeEventListener(Ke,e))}function _t(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function G(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}function B(e){return typeof e=="string"?{type:"click"}:e}function Q(e){return typeof e=="string"?e:e.type}function H(e){if(typeof e!="string"&&(e.type==="click"||e.type==="form_submit"||e.type==="scroll_depth"))return e.value}var Je=new Set,Ue=!1;function Ot(e){if(Je.has(e))return!0;if(Je.add(e),!Ue){Ue=!0;let t=()=>{Ue=!1,Je.clear()};if(typeof MessageChannel=="function"){let n=new MessageChannel;n.port1.onmessage=()=>{n.port1.close(),n.port2.close(),t()},n.port2.postMessage(0)}else setTimeout(t,0)}return!1}function Bn(e){if(!(e instanceof Element))return!1;let t=e.tagName.toLowerCase();return t==="a"||t==="button"?!0:e.getAttribute("role")==="button"}function Et(e,t,n){if(n){try{let i=e;for(;i&&i!==t;){if(i.matches(n))return!0;i=i.parentElement}}catch(i){}return!1}let r=e;for(;r&&r!==t;){if(Bn(r))return!0;r=r.parentElement}return!1}function X(e,t,n,r){if(t.type==="weighted_composite"){let s=new Set,y=[];return t.steps.forEach(({goal:f,name:h,weight:R},c)=>{let u=(p=!1)=>{s.has(c)||p&&r!==void 0&&Ot(`step\0${h}\0${R}\0${c}`)||(s.add(c),n.fireStep(h,R,c))};if(f.type==="click"){let p=g=>{let a=g.target;a instanceof Element&&Et(a,e,f.selector)&&u()};e.addEventListener("click",p),y.push(()=>e.removeEventListener("click",p));return}if(f.type==="form_submit"){let p=g=>{g.target instanceof HTMLFormElement&&e.contains(g.target)&&u()};e.addEventListener("submit",p),y.push(()=>e.removeEventListener("submit",p));return}if(f.type==="scroll_depth"){let p=Math.max(0,Math.min(1,f.threshold)),g=new IntersectionObserver(a=>{for(let S of a)if(S.intersectionRatio>=p){u(!0),g.disconnect();break}},{threshold:[p]});g.observe(e),y.push(()=>g.disconnect())}}),()=>{for(let f of y)f()}}let i=t.type==="composite"?t.all:[t],l=new Set(i.map((s,y)=>y)),d=()=>{r!==void 0&&Ot(r)||n.fireGoal()},o=(s,y=!1)=>{l.delete(s),l.size===0&&(y?d():n.fireGoal())},m=[];return i.forEach((s,y)=>{if(s.type==="click"){let f=h=>{let R=h.target;R instanceof Element&&Et(R,e,s.selector)&&(t.type==="composite"?o(y):n.fireGoal())};e.addEventListener("click",f),m.push(()=>e.removeEventListener("click",f));return}if(s.type==="form_submit"){let f=h=>{h.target instanceof HTMLFormElement&&e.contains(h.target)&&(t.type==="composite"?o(y):n.fireGoal())};e.addEventListener("submit",f),m.push(()=>e.removeEventListener("submit",f));return}if(s.type==="scroll_depth"){let f=Math.max(0,Math.min(1,s.threshold)),h=new IntersectionObserver(R=>{for(let c of R)if(c.intersectionRatio>=f){t.type==="composite"?o(y,!0):d(),h.disconnect();break}},{threshold:[f]});h.observe(e),m.push(()=>h.disconnect());return}}),()=>{for(let s of m)s()}}var Pt=new Set,Gt=new Set;function le(e,t,n,r,i){let l=`${r}|${n}`;if(Gt.has(l))return;Gt.add(l);let d=i.type==="weighted_composite"&&!Pt.has(r);d&&Pt.add(r),e.track({projectId:t,componentId:n,eventType:"funnel_declared",payload:d?{funnelId:r,steps:i.steps.map(o=>({goalId:o.name,weight:o.weight}))}:{funnelId:r}})}function ee(e,t,n,r){e.track({projectId:t,componentId:n,variantId:r,eventType:"variant_assigned",payload:{}})}var jn={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function ie(){if(typeof window=="undefined")return jn;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function ve(){ie().version+=1;for(let e of ie().listeners)e()}var Tt=()=>{};function Lt(e){return G()?(ie().components.set(e.id,e),ve(),()=>{ie().components.delete(e.id),ve()}):Tt}function ue(e){return G()?(ie().slots.set(e.id,e),ve(),()=>{ie().slots.delete(e.id),ve()}):Tt}function He(e){G()&&(ie().sections=[...e],ve())}var Dt="0.35.2",Xe=Dt!=="0.0.0-dev"?{name:"react",version:Dt}:void 0;function Kn(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function ce(e,t){Kn()[e]=t}function It(e){window.__sentient_vocabulary_override=e}function Nt(){var e;return typeof window=="undefined"?null:(e=window.__sentient_vocabulary_override)!=null?e:null}function Wn(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function de(e,t){Wn()[e]=t}var Vt="sentient_editor",Ft="sentient_preview_cell",Mt="sentient_refresh_region",ze="sentient-cell-preview-bar",oe="__preview__",fe=null;function $t(e){if((fe==null?void 0:fe.slotId)!==e)return null;let t=fe;return fe=null,t}function Bt(e,t){fetch(`${e.base}/editor/region-skeleton`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json"},body:JSON.stringify(v({slotId:e.slotId},t))}).then(n=>ge(n.ok?"Region refreshed \u2014 you can regenerate its versions now.":"Couldn\u2019t refresh this region \u2014 reopen the link from your dashboard.")).catch(()=>ge("Couldn\u2019t refresh this region \u2014 check your connection and reopen the link from your dashboard."))}function jt(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(ze))return;let t,n,r;try{let m=new URLSearchParams(window.location.search);t=m.get(Vt),n=m.get(Ft),r=m.get(Mt)}catch(m){return}if(t&&r){fe={slotId:r,token:t,base:(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"")},ce(r,{kind:"arms"}),de(r,oe),We();return}if(!t||!n)return;let i=n.lastIndexOf("~");if(i<=0)return;let l=n.slice(0,i),d=n.slice(i+1),o=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");fetch(`${o}/editor/cell-preview?slotId=${encodeURIComponent(l)}&persona=${encodeURIComponent(d)}`,{headers:{authorization:`Bearer ${t}`}}).then(async m=>{if(!m.ok){ge(m.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let s=await m.json();if(s.vocabulary&&Array.isArray(s.vocabulary.entries)&&It(s.vocabulary),s.compose!=null)ce(l,{kind:"arms",compose:{[oe]:s.compose}}),de(l,oe);else if(s.edits!=null&&typeof s.skeletonFp=="string"&&Array.isArray(s.leafToNode))ce(l,{kind:"arms",edits:{edits:s.edits,fp:s.skeletonFp,leafToNode:s.leafToNode}}),de(l,oe);else if(s.blocks!=null)ce(l,{kind:"arms",blocks:{[oe]:s.blocks}}),de(l,oe);else if(s.content!=null)ce(l,{kind:"arms",content:s.content}),de(l,oe);else{ge("Nothing to preview in that square yet.");return}We(),ge(`Previewing \u201C${s.slotName}\u201D for ${s.personaDisplay}${s.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var y;try{(y=document.querySelector(`[data-sentient-slot="${l}"]`))==null||y.scrollIntoView({block:"center"})}catch(f){}},300)}).catch(()=>ge("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function ge(e){var i;if(document.getElementById(ze))return;let t=document.createElement("div");t.id=ze,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let r=document.createElement("button");r.textContent="Exit preview",Object.assign(r.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),r.onclick=()=>{let l=new URL(window.location.href);l.searchParams.delete(Vt),l.searchParams.delete(Ft),l.searchParams.delete(Mt),window.location.assign(l.toString())},t.append(n,r),((i=document.body)!=null?i:document.documentElement).append(t)}var Jn="sentient_editor",Kt=!1;function Wt(e){if(Kt||typeof window=="undefined")return;let t=null;try{t=new URLSearchParams(window.location.search).get(Jn)}catch(i){return}if(!t)return;Kt=!0;let n=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),r=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:i})=>fetch(`${n}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(i(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?r():window.addEventListener("load",r,{once:!0})}import{jsx as tr}from"react/jsx-runtime";function qn(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return Xn({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var Ut="https://api.sentient-ui.com/v1",V=Un({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:Ut,debug:!1});function Zn(e){let[t,n]=we(!1),r=qe(e);r.current=e;let{cookie:i,value:l,event:d}=e!=null?e:{},o=typeof(e==null?void 0:e.check)=="function";return Y(()=>{let m=()=>{var h;let y=r.current;if(!y)return!1;if(y.check)return y.check()===!0;if(!y.cookie||typeof document=="undefined")return!1;let f=`${y.cookie}=${(h=y.value)!=null?h:"accepted"}`;return document.cookie.split("; ").some(R=>R.trim()===f)};if(n(m()),!d)return;let s=()=>{n(m())};return window.addEventListener(d,s),()=>window.removeEventListener(d,s)},[i,l,d,o]),t}function Yn(e){var c,u;let[t,n]=we(null),[r]=we(()=>{var p;return(p=e.sessionSegment)!=null?p:qn()}),[i,l]=we(je());Y(()=>Rt(()=>l(je())),[]),Y(()=>{jt(e.apiBaseUrl),Wt(e.apiBaseUrl)},[]);let d=Zn(e.consentFrom),o=e.consentFrom?e.consent===!0||d:e.consent,m=qe(null);Y(()=>{var A;if(o===!1&&!e.preConsentBehavior){(A=m.current)==null||A.destroy(),m.current=null,n(null);return}let p=v({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:r,consent:o,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},Xe?{sdk:Xe}:{}),g=!1,a=null,S=null,x=O=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:b})=>{g||(S=b(O,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:O})=>{g||(a=O(L(v({},p),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),m.current=a,n(a),x(a))}):(a=zn(p),m.current=a,n(a),x(a)),()=>{g=!0,S==null||S(),a==null||a.dispose()}},[o]),Y(()=>{if(!t)return;let p=!1,g=async()=>{if(p)return;let S;try{S=await t.fetchWeights()}catch(x){return}if(!p)for(let x of S){let A={componentId:x.componentId,updatedAt:x.updatedAt,variants:x.variants.map(O=>{var b;return{variantId:O.variantId,pulls:O.pulls,avgReward:(b=O.avgReward)!=null?b:0}})};wt(x.componentId,A)}};g();let a=setInterval(()=>{g()},6e4);return()=>{p=!0,clearInterval(a)}},[t]);let s=(c=e.ssrFallback)!=null?c:"first",y=((u=e.apiBaseUrl)!=null?u:Ut).replace(/\/$/,""),f=qe(null);Y(()=>{var a;if(typeof process!="undefined"&&((a=process.env)==null?void 0:a.NODE_ENV)==="production")return;let p={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:y},g=f.current;if(f.current=p,g!==null)for(let S of["apiKey","context","country","persona","apiBaseUrl"])Object.is(g[S],p[S])||console.warn(`[sentient] AdaptiveProvider: \`${S}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,y]),Y(()=>{var p;typeof process!="undefined"&&((p=process.env)==null?void 0:p.NODE_ENV)==="production"||_t({apiKey:e.apiKey,apiBaseUrl:y,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,y]),Y(()=>{let p=e.initialLayoutOrder;if(p&&p.length>0){He(p);return}e.declaredSections&&e.declaredSections.length>0&&He(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),Y(()=>{if(!G())return;let p=e.declaredSections;if(!p||p.length===0||typeof document=="undefined")return;let g=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),S=>S.getAttribute("data-sentient-id"))),a=p.filter(S=>!g.has(S));a.length>0&&console.warn(`[SentientUI] Declared section${a.length>1?"s":""} ${a.map(S=>`"${S}"`).join(", ")} ${a.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let h=Jt(()=>t&&i?At(t):t,[t,i]),R=Jt(()=>{var p,g,a,S,x,A,O,b;return{client:h,apiKey:e.apiKey,initialAssignments:(p=e.initialAssignments)!=null?p:{},sessionSegment:r,ssrFallback:s,onAssignment:e.onAssignment,initialLayoutOrder:(g=e.initialLayoutOrder)!=null?g:null,initialSlots:(a=e.initialSlots)!=null?a:{},initialSlotConfig:(S=e.initialSlotConfig)!=null?S:{},initialPalette:(x=e.initialPalette)!=null?x:null,initialVocabulary:(A=e.initialVocabulary)!=null?A:null,initialPersona:(O=e.initialPersona)!=null?O:null,apiBaseUrl:y,debug:(b=e.debug)!=null?b:!1}},[h,e.apiKey,e.initialAssignments,r,s,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,y,e.debug]);return tr(V.Provider,{value:R,children:e.children})}function D(){return F(V).client}function z(){return F(V).apiKey}function Ze(){return F(V).initialAssignments}function ke(){return F(V).sessionSegment}function Ht(){return F(V).ssrFallback}function Re(){return F(V).onAssignment}function Xt(){return F(V).debug}function Qn(){let e=F(V).initialLayoutOrder,t=Hn($,()=>{var n;return typeof window=="undefined"?null:(n=window.__sentient_layout_override)!=null?n:null},()=>null);return t!=null?t:e}function Ae(){return F(V).initialSlots}function zt(){return F(V).initialPersona}function qt(){return F(V).initialSlotConfig}function Zt(){return F(V).initialPalette}function Yt(){return F(V).initialVocabulary}function er(){return F(V).apiBaseUrl}import{memo as kr,useEffect as Rr,useState as Ar}from"react";import{useCallback as ir,useEffect as se,useMemo as en,useRef as Se,useState as or}from"react";import{attachMicroSignalDetectors as sr}from"@sentientui/core";import{useEffect as Ce,useRef as Qt,useState as nr,useSyncExternalStore as rr}from"react";import{pickFromWeights as Ye}from"@sentientui/policy";function me(e){var n;if(typeof window=="undefined")return null;let t=(n=window.__sentient_overrides)==null?void 0:n[e];if(t)return t;if(!window.location.search)return null;try{let r=new URLSearchParams(window.location.search);for(let i of r.getAll("sentient_variant")){let l=i.indexOf(":");if(l!==-1&&i.slice(0,l)===e)return i.slice(l+1)}}catch(r){}return null}function Qe(e,t,n,r){let i=Ze(),l=Ht(),d=D(),o=ke(),m=Re(),s=Xt(),y=Qt(null),f=rr($,()=>me(e),()=>null),h=f&&t.includes(f)?f:null,R=Qt(null);Ce(()=>{s&&h&&R.current!==h&&(R.current=h,console.info(`[sentient] override active: ${e} -> ${h}`))},[s,h,e]);let[c,u]=nr(()=>{var S,x;if(h)return{variantId:h,content:null,isLoading:!1,settled:!0};if(!d){let A=i[e];return A&&t.includes(A)?{variantId:A,content:null,isLoading:!1,settled:!0}:l==="first"&&t.length>0?{variantId:t[0],content:null,isLoading:!1,settled:!1}:{variantId:null,content:null,isLoading:!0,settled:!1}}let g=d.getAssignment(e,o);if(g&&(t.includes(g.variantId)||g.content))return{variantId:g.variantId,content:(S=g.content)!=null?S:null,isLoading:!1,settled:!0};let a=Be(e);if(a){let A=Ye(a.variants,t);if(A)return{variantId:A,content:null,isLoading:!1,settled:!0}}return{variantId:(x=t[0])!=null?x:null,content:null,isLoading:!1,settled:!1}}),p=g=>{m&&y.current!==g&&(y.current=g,m(e,g))};return Ce(()=>{var S;if(h||!d)return;let g=d.getAssignment(e,o);if(g&&(t.includes(g.variantId)||g.content)){u({variantId:g.variantId,content:(S=g.content)!=null?S:null,isLoading:!1,settled:!0}),p(g.variantId);return}let a=Be(e);if(a&&c.settled&&c.variantId&&c.variantId===Ye(a.variants,t)){p(c.variantId);return}u(x=>{var A;return x.variantId?x:{variantId:(A=t[0])!=null?A:null,content:null,isLoading:!1,settled:!1}})},[h,d,e,o]),Ce(()=>{if(h||!d)return;let g=d.getAssignment(e,o);if(g&&t.includes(g.variantId))return;let a=!1;return d.assign(e,t,n,r).then(S=>{var x;a||S&&(!t.includes(S.variantId)&&!S.content||(u({variantId:S.variantId,content:(x=S.content)!=null?x:null,isLoading:!1,settled:!0}),p(S.variantId)))}),()=>{a=!0}},[h,d,e,o]),Ce(()=>{if(!h&&d)return xt(e,g=>{var x;let a=d.getAssignment(e,o);if(a&&(t.includes(a.variantId)||a.content)){u({variantId:a.variantId,content:(x=a.content)!=null?x:null,isLoading:!1,settled:!0}),p(a.variantId);return}let S=Ye(g.variants,t);S&&(u({variantId:S,content:null,isLoading:!1,settled:!0}),p(S))})},[h,d,e,o]),h?{variantId:h,content:null,isLoading:!1,settled:!0,isOverride:!0}:c}function _e(e,t,n){let r=D(),i=z(),l=Object.keys(t).join("\0"),d=en(()=>Object.keys(t),[l]),{variantId:o,content:m,isOverride:s=!1,settled:y}=Qe(e,d,n.agentData,n.agentDataByVariant),[f,h]=or(null),R=Se(null),c=ir(_=>{R.current=_,h(_)},[]),u=n.goal,p=typeof u=="string"?u:JSON.stringify(u),g=en(()=>u?B(u):null,[p]),a=u?Q(u):"";se(()=>Lt({id:e,variantIds:d,goal:a}),[e,d,a]);let S=Se(null);se(()=>{s||y&&(!r||!o||!i||!f||S.current!==o&&(S.current=o,ee(r,i,e,o)))},[r,o,i,e,f,s,y]);let x=Se(!1),A=Se(new Set);se(()=>{x.current=!1,A.current=new Set},[o,g]);let O=n.funnel;se(()=>{s||!y||!r||!O||!g||le(r,i,e,O,g)},[r,i,e,O,g,s,y]);let b=n.cursorSignal===!0;se(()=>{if(!b||s||!y||!r||!o||!f)return;let _=null,E=0,N=()=>{E=Date.now(),_=setTimeout(()=>{r.track({projectId:i,componentId:e,variantId:o,eventType:"cursor_signal",payload:{hoverDuration:Date.now()-E}}),_=null},800)},T=()=>{_!==null&&(clearTimeout(_),_=null)};return f.addEventListener("mouseenter",N),f.addEventListener("mouseleave",T),()=>{f.removeEventListener("mouseenter",N),f.removeEventListener("mouseleave",T),_!==null&&clearTimeout(_)}},[b,r,o,i,e,f,s,y]);let k=Se(n.microSignalGoals);k.current=n.microSignalGoals;let w=n.microSignalGoals?JSON.stringify(n.microSignalGoals):"";return se(()=>{if(s||!y||!r||!o||!f)return;let _=Date.now();return sr((E,N={})=>{var Z,ne,J;r.track({projectId:i,componentId:e,variantId:o,eventType:"micro_signal",payload:v({signalType:E},N)});let T=(Z=k.current)==null?void 0:Z[E];if(!T||A.current.has(E))return;A.current.add(E);let K=typeof T=="string"?T:T.name,W=typeof T=="string"?1:(ne=T.weight)!=null?ne:1,q=typeof T=="string"?0:(J=T.stepIndex)!=null?J:0;r.goal(K,{metadata:v({signalType:E},N),weight:W,stepIndex:q})},f,_)},[r,o,i,e,f,w,s,y]),se(()=>{if(s||!y||!r||!o||!f||!g)return;let _=H(g);return X(f,g,{fireGoal:()=>{x.current||(x.current=!0,r.track({projectId:i,componentId:e,variantId:o,eventType:"goal_achieved",goalType:a,payload:v({reward:1},_!==void 0?{goalValue:_}:{})}),r.goal(a,v({metadata:{componentId:e,variantId:o},weight:1,stepIndex:0},_!==void 0?{value:_}:{})))},fireStep:(E,N,T)=>{r.track({projectId:i,componentId:e,variantId:o,eventType:"goal_achieved",goalType:E,payload:{reward:N}}),r.goal(E,{metadata:{},weight:N,stepIndex:T})}},a)},[r,o,i,e,f,g,a,s,y]),{client:r,variantIds:d,variantId:o,content:m,settled:y,isOverride:s,goalLabel:a,ref:c,nodeRef:R}}import{useEffect as j,useMemo as lt,useRef as ut}from"react";import{containsFormBlock as vn,reveal as xr}from"@sentientui/core";import{captureRegionSkeleton as Sn}from"@sentientui/core/region";import{useCallback as ar,useEffect as tn,useRef as et,useSyncExternalStore as Oe}from"react";import{armOfResult as lr}from"@sentientui/core";var nn=new Set;function rn(e,t){var x,A,O;let n=D(),r=et(t==null?void 0:t.baselineText);r.current=t==null?void 0:t.baselineText;let i=et(t==null?void 0:t.render);i.current=t==null?void 0:t.render;let l=et(t==null?void 0:t.skeleton);l.current=t==null?void 0:t.skeleton;let d=Ae(),o=qt(),m=Zt(),s=Yt(),y=Oe($,()=>{var b;return typeof window!="undefined"?(b=window.__sentient_slot_config_overrides)==null?void 0:b[e]:void 0},()=>{}),f=Oe($,()=>{var b;return typeof window!="undefined"?(b=window.__sentient_slot_overrides)==null?void 0:b[e]:void 0},()=>{}),h=b=>b==null?"":lr(b),R=ar(b=>{var k,w;return(w=(k=n==null?void 0:n.onSlotsChanged)==null?void 0:k.call(n,b))!=null?w:(()=>{})},[n]);Oe(R,()=>{var b;return(b=n==null?void 0:n.getSlotConfig(e))!=null?b:null},()=>null),Oe(R,()=>h(n==null?void 0:n.getSlotResult(e)),()=>"");let c=y===void 0?o[e]:void 0,u=y===void 0&&c===void 0&&n?n.getSlotConfig(e):null,p=(x=m!=null?m:n==null?void 0:n.getSitePalette())!=null?x:null,g=(O=s!=null?s:(A=n==null?void 0:n.getStyleVocabulary)==null?void 0:A.call(n))!=null?O:null,a=(()=>{var b,k,w;if(y!==void 0)return{config:y,arm:h(f),palette:p,vocabulary:(b=Nt())!=null?b:g,source:"override"};if(c!==void 0)return{config:c,arm:h((k=d[e])!=null?k:n==null?void 0:n.getSlotResult(e)),palette:p,vocabulary:g,source:"preloaded"};if(u!==null){let _=n!=null&&n.isSlotDecided?n.isSlotDecided(e):!0;return{config:u,arm:h((w=n==null?void 0:n.getSlotResult(e))!=null?w:d[e]),palette:p,vocabulary:g,source:_?"client":"seeded"}}return{config:null,arm:"",palette:p,vocabulary:g,source:"none"}})(),S=a.source==="preloaded"||a.source==="override";return tn(()=>{var K,W,q,Z,ne;if(!n||n.isLocal===!0||S)return;let b=a.source==="none",k=b&&(W=(K=r.current)==null?void 0:K.call(r))!=null?W:null,w=k!=null&&k!==""?{[e]:k}:void 0,_=(q=i.current)==null?void 0:q.call(i),E=b&&(ne=(Z=l.current)==null?void 0:Z.call(l))!=null?ne:null,N=v(v({},_?{render:{[e]:_}}:{}),E?{skeletons:{[e]:E}}:{}),T=Object.keys(N).length>0;return n.requestSlots?T?n.requestSlots([e],w,N):w?n.requestSlots([e],w):n.requestSlots([e]):b&&(E?n.reportSlots([e],w!=null?w:{},{[e]:E}):w?n.reportSlots([e],w):n.reportSlots([e])),()=>{var J;return(J=n.cancelSlots)==null?void 0:J.call(n,[e])}},[n,S,a.source,e]),tn(()=>{!G()||(n==null?void 0:n.isLocal)!==!0||a.source!=="none"||nn.has(e)||(nn.add(e),console.warn(`[sentient] <Adaptive id="${e}"> is rendering its baseline children: in local/keyless mode <Adaptive> serves ONLY what you pass as \`initialSlotConfig\` (there is no registry to decide from). Pass initialSlotConfig/initialSlots to <AdaptiveProvider> to preview arms locally.`))},[n,a.source,e]),a}import{cloneElement as ur,Fragment as on}from"react";import{jsx as I,jsxs as un}from"react/jsx-runtime";var te={none:"0",sm:"8px",md:"16px",lg:"24px"},tt={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch",between:"space-between"},cn={sm:"0.875em",md:"1em",lg:"1.25em"},cr={sm:"1.25em",md:"1.5em",lg:"2em"},sn={sm:"6px 14px",md:"10px 20px",lg:"14px 28px"},an={sm:"8px",md:"16px",lg:"32px"},dr={square:"1 / 1",landscape:"4 / 3",wide:"16 / 9"},fr={normal:"400",medium:"500",bold:"700"};function ln(e,t){return v(v({},e==="muted"?t!=null&&t.muted?{color:t.muted}:{opacity:.7}:{}),e==="accent"?v({fontWeight:600},t!=null&&t.accent?{color:t.accent}:{}):{})}function dn(e,t,n){var i,l,d,o;let r=t==null?void 0:t.accent;return L(v({display:"inline-block",padding:(i=sn[n!=null?n:"md"])!=null?i:sn.md,borderRadius:(l=t==null?void 0:t.radius)!=null?l:"8px",font:"inherit"},n?{fontSize:cn[n]}:{}),{textDecoration:e==="ghost"?"underline":"none",cursor:"pointer",background:e==="primary"?(d=t==null?void 0:t.primaryBg)!=null?d:"#111827":"transparent",color:e==="primary"?(o=t==null?void 0:t.primaryText)!=null?o:"#ffffff":r!=null?r:"inherit",border:e==="secondary"?`1px solid ${r!=null?r:"currentColor"}`:"none"})}function gr({node:e,opts:t}){var i,l,d,o,m;let n=(i=e.emphasis)!=null?i:"primary",r={padding:"8px 10px",font:"inherit",border:`1px solid ${(d=(l=t.palette)==null?void 0:l.border)!=null?d:"currentColor"}`,borderRadius:(m=(o=t.palette)==null?void 0:o.radius)!=null?m:"8px"};return un("form",{onSubmit:s=>{var h,R,c;s.preventDefault();let y=new FormData(s.currentTarget),f={};for(let u of e.fields)f[u.name]=String((h=y.get(u.name))!=null?h:"");(R=t.onFormGoal)==null||R.call(t,e.submitGoal);try{(c=t.onFormSubmit)==null||c.call(t,f)}catch(u){}},style:{display:"flex",flexDirection:"column",gap:"12px"},children:[e.fields.map(s=>{var y,f;return un("label",{style:{display:"flex",flexDirection:"column",gap:"4px",font:"inherit"},children:[s.label,s.kind==="textarea"?I("textarea",{name:s.name,required:s.required,placeholder:s.placeholder,rows:3,style:r}):s.kind==="select"?I("select",{name:s.name,required:s.required,style:r,children:((y=s.options)!=null?y:[]).map(h=>I("option",{value:h,children:h},h))}):I("input",{name:s.name,type:(f=s.inputType)!=null?f:"text",required:s.required,placeholder:s.placeholder,style:r})]},s.name)}),I("button",{type:"submit",style:dn(n,t.palette),children:e.submitLabel})]})}function mr(e,t){var r,i;let n=e.like;return n?(i=(r=t.vocabulary)==null?void 0:r.entries.find(l=>l.id===n))==null?void 0:i.classes:void 0}function fn(e,t){var r;let n=e?(r=t.vocabulary)==null?void 0:r.entries.find(i=>i.id===e):void 0;return n!=null&&n.computed.inheritsColor?n.computed.color:void 0}function pe(e,t){var i;let n=pr(e,t),r=fn(e.like,t);return n&&r?ur(n,{style:L(v({},(i=n.props.style)!=null?i:{}),{color:r})}):n}function pr(e,t){var n,r,i,l,d,o,m,s,y,f,h,R,c,u,p,g,a,S,x,A,O,b,k;try{let w=mr(e,t);switch(e.type){case"stack":{let _=(r=te[(n=e.gap)!=null?n:"md"])!=null?r:te.md,E=e.surface==="raised"&&!w,N=(i=e.pad)!=null?i:E?"md":void 0;return I("div",L(v({},w?{className:w}:{}),{style:v(v(v(v(v({display:"flex",flexDirection:e.direction,gap:_},e.align?{alignItems:tt[e.align]}:{}),e.justify?{justifyContent:tt[e.justify]}:{}),e.wrap?{flexWrap:"wrap"}:{}),N?{padding:(l=te[N])!=null?l:te.md}:{}),E?L(v(v({},(d=t.palette)!=null&&d.surface?{background:t.palette.surface}:{}),(o=t.palette)!=null&&o.surface&&((m=t.palette)!=null&&m.surfaceText)?{color:t.palette.surfaceText}:{}),{border:`1px solid ${(y=(s=t.palette)==null?void 0:s.border)!=null?y:"currentColor"}`,borderRadius:(h=(f=t.palette)==null?void 0:f.radius)!=null?h:"8px"}):{}),children:((R=e.children)!=null?R:[]).map((T,K)=>{let W=pe(T,t);return W===null?null:I(on,{children:W},K)})}))}case"grid":{let _=(u=te[(c=e.gap)!=null?c:"md"])!=null?u:te.md;return I("div",L(v({},w?{className:w}:{}),{style:v(v({display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(max(200px, calc((100% - ${e.columns-1} * ${_}) / ${e.columns})), 1fr))`,gap:_},e.align?{alignItems:tt[e.align]}:{}),e.pad?{padding:(p=te[e.pad])!=null?p:te.md}:{}),children:((g=e.children)!=null?g:[]).map((E,N)=>{let T=pe(E,t);return T===null?null:I(on,{children:T},N)})}))}case"text":return w?I("p",{className:w,style:e.maxWidth==="measure"?{maxWidth:"65ch"}:void 0,children:e.value}):I("p",{style:v(v(v(v(v({margin:0},e.size?{fontSize:cn[e.size]}:{}),e.weight?{fontWeight:fr[e.weight]}:{}),e.align?{textAlign:e.align}:{}),e.maxWidth==="measure"?{maxWidth:"65ch"}:{}),ln(e.tone,t.palette)),children:e.value});case"heading":{let _=`h${e.level}`;return w?I(_,{className:w,style:e.maxWidth==="measure"?{maxWidth:"65ch"}:void 0,children:e.value}):I(_,{style:v(v({margin:0,fontSize:cr[(a=e.size)!=null?a:"md"]},e.align?{textAlign:e.align}:{}),e.maxWidth==="measure"?{maxWidth:"65ch"}:{}),children:e.value})}case"button":{let _=(S=e.emphasis)!=null?S:"primary";return I("a",L(v(v({href:e.href},e.tag?{"data-sentient-tag":e.tag}:{}),w?{className:w}:{style:dn(_,t.palette,e.size)}),{children:e.label}))}case"link":return I("a",L(v(v({href:e.href},e.tag?{"data-sentient-tag":e.tag}:{}),w?{className:w}:{style:{color:"inherit",textDecoration:"underline"}}),{children:e.label}));case"image":return I("img",L(v({src:e.src,alt:e.alt},w?{className:w}:{}),{style:v(v({display:"block",maxWidth:"100%"},e.ratio&&e.ratio!=="auto"?{aspectRatio:dr[e.ratio],width:"100%"}:{}),e.fit?{objectFit:e.fit}:{})}));case"badge":return w?I("span",{className:w,children:e.value}):I("span",{style:v({display:"inline-block",padding:"2px 10px",borderRadius:"999px",fontSize:"0.75em",border:`1px solid ${(A=(x=t.palette)==null?void 0:x.border)!=null?A:"currentColor"}`},ln(e.tone,t.palette)),children:e.value});case"spacer":return I("div",{style:{height:(O=an[e.size])!=null?O:an.md}});case"divider":return I("hr",{style:{border:"none",borderTop:`1px solid ${(k=(b=t.palette)==null?void 0:b.border)!=null?k:"currentColor"}`,margin:0,width:"100%"}});case"form":return I(gr,{node:e,opts:t});default:return null}}catch(w){return null}}function nt(e,t){var l,d,o,m;let n=pe(e.tree,t);if(n===null)return null;let r=(l=e.surface)!=null&&l.like?(o=(d=t.vocabulary)==null?void 0:d.entries.find(s=>s.id===e.surface.like))==null?void 0:o.classes:void 0,i=fn((m=e.surface)==null?void 0:m.like,t);return r?I("div",L(v({className:r},i?{style:{color:i}}:{}),{children:n})):n}import{cloneElement as Ee,isValidElement as Pe}from"react";import{normalizeLeafText as yr,skeletonFingerprint as vr}from"@sentientui/core/region";function Ge(e){return typeof e=="string"&&e.trim()!==""||typeof e=="number"}function Te(e){let t=e.props;if(t.dangerouslySetInnerHTML==null)return t.children}function ae(e){return Ge(e)?1:Array.isArray(e)?e.reduce((t,n)=>t+ae(n),0):Pe(e)?ae(Te(e)):0}function Sr(e,t){return Array.isArray(t)?Ee(e,void 0,...t):Ee(e,void 0,t)}function rt(e,t){if(Ge(e))return t;if(Array.isArray(e))return e.map(n=>rt(n,t));if(Pe(e)){let n=Te(e);return ae(n)===0?e:Sr(e,rt(n,t))}return e}function gn(e,t){return ae(e)===1?rt(e,t):null}var M=e=>e.join("/");function it(e,t,n){if(Ge(e)){n.leafPaths.push(t),n.texts.push(yr(String(e)));return}if(Array.isArray(e)){e.forEach((r,i)=>it(r,[...t,i],n));return}Pe(e)&&(n.elements.set(M(t),e),it(Te(e),[...t,"c"],n))}function st(e){let t={leafPaths:[],texts:[],elements:new Map};return it(e,[],t),t}function hr(e){return st(e).texts}function mn(e){let t=hr(e);return t.length===0?null:vr(t)}function br(e){let t=[];return e.forEach((n,r)=>{n==="c"&&t.push(e.slice(0,r))}),t}function pn(e,t){let n=t.reduce((i,l)=>Math.max(i,l+1),0),r=[];for(let i=0;i<n;i++){let l=t.flatMap((o,m)=>o===i?[br(e.leafPaths[m])]:[]);if(l.length===0){r.push(null);continue}let d=l[0];for(let o of l.slice(1)){let m=new Set(o.map(M));d=d.filter(s=>m.has(M(s)))}r.push(d.length>0?d[d.length-1]:null)}return r}function ot(e){var n;let t=(n=e==null?void 0:e.props)==null?void 0:n.className;return typeof t=="string"?t:void 0}function at(e,t){let n=st(t);if(n.texts.length!==e.leaves.length||n.texts.some((l,d)=>l!==e.leaves[d]))return null;let r=pn(n,e.leafToNode),i=e.nodes.map((l,d)=>{let o=r[d],m=o?n.elements.get(M(o)):void 0,s=!!m&&(typeof m.type=="string"||ot(m)!==void 0);return L(v({},l),{restylable:s})});return L(v({},e),{nodes:i})}function yn(e,t,n){var c;let r=st(e);if(r.leafPaths.length!==n.length)return null;let i=n.reduce((u,p)=>Math.max(u,p+1),0);for(let u of Object.keys(t.nodes))if(!/^\d+$/.test(u)||Number(u)>=i)return null;let l=pn(r,n),d=new Map;n.forEach((u,p)=>{d.has(u)||d.set(u,p)});let o=new Map(r.leafPaths.map((u,p)=>[M(u),p])),m=new Set,s=new Map,y=!1;for(let[u,p]of Object.entries(t.nodes)){let g=Number(u),a=l[g];if(p.hidden&&(a?m.add(M(a)):y=!0),p.like!==void 0){let S=l[p.like],x=a?r.elements.get(M(a)):void 0,A=S?ot(r.elements.get(M(S))):void 0;!a||A===void 0||ot(x)===void 0?y=!0:s.set(M(a),A)}}let f=new Map(Object.entries((c=t.order)!=null?c:{})),h=(u,p)=>{var g;if(Ge(u)){let a=o.get(M(p));if(a===void 0)return u;let S=n[a],x=(g=t.nodes[String(S)])==null?void 0:g.text;return x===void 0?u:d.get(S)===a?x:""}if(Array.isArray(u)){let a=u.map((S,x)=>h(S,[...p,x]));for(let[S,x]of f){let A=x.map(k=>{let w=l[k];return!w||w.length!==p.length+1||M(w.slice(0,-1))!==M(p)?-1:w[w.length-1]});if(A.some(k=>k<0))continue;let O=[...A].sort((k,w)=>k-w),b=[...a];O.forEach((k,w)=>{a[k]=b[A[w]]}),f.delete(S)}return a}if(Pe(u)){let a=M(p);if(m.has(a))return null;let S=Te(u);if(ae(S)===0)return u;let x=h(S,[...p,"c"]),A=s.get(a),O=A!==void 0?{className:A}:void 0;return Array.isArray(x)?Ee(u,O,...x):Ee(u,O,x)}return u},R=h(e,[]);return y||f.size>0?null:R}import{jsx as wr}from"react/jsx-runtime";var hn=new Set,bn=new Set,xn=new Set,wn="authored.";function Le({id:e,children:t,variants:n,onFormSubmit:r,goal:i,className:l,reportBaselineText:d=!0}){var mt,pt;let o=D(),m=z(),s=ut(null),y=lt(()=>mn(t),[t]),f=n?Object.keys(n).join("|"):"",h=lt(()=>v({fp:y!=null?y:"0000000000000000",forms:!!r,compose:!0,content:ae(t)===1},f!==""?{authored:f.split("|"),children:!0}:{}),[y,t,r,f]),R=()=>{var U;let C=s.current;if(!C||!d)return null;let P=Sn(C);return P.skeleton?(U=at(P.skeleton,t))!=null?U:L(v({},P.skeleton),{editable:!1,nodes:P.skeleton.nodes.map(re=>L(v({},re),{restylable:!1}))}):{status:P.reason}},{config:c,arm:u,palette:p,vocabulary:g,source:a}=rn(e,{baselineText:d?()=>{var C,P;return(P=(C=s.current)==null?void 0:C.textContent)!=null?P:null}:void 0,render:()=>h,skeleton:R}),S=u!==""?(mt=c==null?void 0:c.blocks)==null?void 0:mt[u]:void 0,x=u!==""?(pt=c==null?void 0:c.compose)==null?void 0:pt[u]:void 0,A=(S!==void 0&&vn(S)||x!==void 0&&vn(x.tree))&&!r;j(()=>{!A||!G()||hn.has(e)||(hn.add(e),console.warn(`[sentient] AdaptiveSlot "${e}" was served a form arm but has no onFormSubmit handler \u2014 rendering its baseline children instead. Pass onFormSubmit to render generated forms.`))},[A,e]);let O=C=>{!o||a==="override"||(a!=="seeded"&&o.componentGoal(e,C),o.goal(C,{metadata:{componentId:e,arm:u},weight:1,stepIndex:0}))},b=t,k=!1,w=u.startsWith(wn)?u.slice(wn.length):null;if((c==null?void 0:c.blocked)==="variant_history")k=!0;else if(w!==null)n&&Object.prototype.hasOwnProperty.call(n,w)?b=n[w]:k=!0;else if(x!==void 0){let C=A?null:nt(x,{palette:p,vocabulary:g,onFormSubmit:r,onFormGoal:O});C===null?k=!0:b=C}else if(S!==void 0){let C=A?null:pe(S,{palette:p,vocabulary:g,onFormSubmit:r,onFormGoal:O});C===null?k=!0:b=C}else if((c==null?void 0:c.edits)!==void 0&&a!=="none"){let C=c.edits,P=C.fp===y?yn(t,C.edits,C.leafToNode):null;P===null?k=!0:b=P}else if((c==null?void 0:c.content)!==void 0&&a!=="none"){let C=gn(t,c.content);C===null?k=!0:b=C}let _=k&&S===void 0&&x===void 0&&(c==null?void 0:c.edits)===void 0&&w===null&&(c==null?void 0:c.blocked)===void 0;j(()=>{(c==null?void 0:c.blocked)!=="variant_history"||!G()||xn.has(e)||(xn.add(e),console.warn(`[sentient] <Adaptive id="${e}"> has results from its earlier variants experiment, so it is showing your original until you migrate it: Components \u2192 "${e}" \u2192 Migrate. Deploying code never switches an experiment.`))},[c==null?void 0:c.blocked,e]);let E=w!==null&&!k?w:null;j(()=>{var ye;if(!E||!d||!o)return;let C=s.current;if(!C)return;let P=Sn(C),U=P.skeleton?at(P.skeleton,n==null?void 0:n[E]):null,re=(ye=C.textContent)==null?void 0:ye.trim();o.reportSlots([],void 0,void 0,{[e]:[v(v({key:E},re?{text:re}:{}),U?{skeleton:U}:{})]})},[E,o,e]);let N=k&&(c==null?void 0:c.edits)!==void 0&&(a==="preloaded"||a==="client");j(()=>{var C;!N||!(c!=null&&c.edits)||(C=o==null?void 0:o.reportDrift)==null||C.call(o,e,c.edits.fp,y,c.edits.fp===y?"unaddressable":"fp_mismatch")},[N,e,y,o]);let T=b===t;j(()=>{var P;if(!(c!=null&&c.needsSkeleton)||!T)return;let C=R();C&&((P=o==null?void 0:o.reportSkeleton)==null||P.call(o,e,C))},[c==null?void 0:c.needsSkeleton,T,e,o]),j(()=>{if(!T)return;let C=$t(e);if(!C)return;let P=R();Bt(C,P&&"status"in P?{status:P.status}:{skeleton:P})},[e,T]),j(()=>{!_||!G()||bn.has(e)||(bn.add(e),console.warn(`[sentient] <Adaptive id="${e}"> was served a text version, but its children have several separate texts or none Sentient can reach \u2014 rendering the original instead. Regenerate the version (new versions edit each text in place), or put a single text inline.`))},[_,e]);let K=c!=null&&c.blocks?Object.keys(c.blocks).sort().join("|"):"";j(()=>ue({id:e,arms:K===""?void 0:K.split("|")}),[e,K]);let W=ut(null);j(()=>{!o||a==="none"||a==="seeded"||a==="override"||u===""||k||W.current!==u&&(W.current=u,ee(o,m,e,u))},[o,m,e,u,a,k]);let q=a!=="none"&&a!=="seeded"&&!k,Z=q?u:"",ne=i===void 0?null:typeof i=="string"?i:JSON.stringify(i);j(()=>{if(!o||!i||a==="override")return;let C=s.current;if(!C)return;let P=Q(i),U=H(i),re=!1;return X(C,B(i),{fireGoal:()=>{re||(re=!0,q&&(U!==void 0?o.componentGoal(e,P,{value:U}):o.componentGoal(e,P)),o.goal(P,v({metadata:{componentId:e,arm:Z},weight:1,stepIndex:0},U!==void 0?{value:U}:{})))},fireStep:(ye,yt,Nn)=>{q&&o.componentGoal(e,ye,{reward:yt}),o.goal(ye,{metadata:{componentId:e,arm:Z},weight:yt,stepIndex:Nn})}},P)},[o,e,ne,u,a,k,q,Z]);let J=ut(null);j(()=>{let C=s.current;if(C){if(J.current===null){J.current=u;return}J.current!==u&&(J.current=u,xr(C))}},[u]);let In=lt(()=>v({"data-sentient-slot":e},u!==""?{"data-sentient-arm":u}:{}),[e,u]);return wr("div",L(v({ref:s,className:l},In),{children:b}))}import{jsx as De}from"react/jsx-runtime";function Cr(e){var s;let{client:t,variantId:n,content:r,ref:i}=_e(e.id,e.variants,{goal:e.goal,funnel:e.funnel,microSignalGoals:e.microSignalGoals,agentData:e.agentData,agentDataByVariant:e.agentDataByVariant,cursorSignal:!0}),[l,d]=Ar(!1);if(Rr(()=>{d(!0)},[]),e.clientOnly&&(!l||!t)||!n)return null;let o=(s=e.variants[n])!=null?s:null,m=o===null?r:null;return G()&&o===null&&m===null&&console.warn(`[sentient] <Adaptive id="${e.id}"> was assigned variant "${n}" but no matching key exists in props.variants. If this is a dashboard-managed text variant, use <AdaptiveText id="${e.id}"> instead.`),De("div",{ref:i,"data-sentient-id":e.id,"data-sentient-variant":n,children:o!=null?o:m})}var _r=kr(Cr,(e,t)=>{if(e.id!==t.id||e.goal!==t.goal&&JSON.stringify(e.goal)!==JSON.stringify(t.goal)||e.microSignalGoals!==t.microSignalGoals||e.funnel!==t.funnel||e.clientOnly!==t.clientOnly||e.agentData!==t.agentData||e.agentDataByVariant!==t.agentDataByVariant)return!1;if(e.variants===t.variants)return!0;let n=Object.keys(e.variants),r=Object.keys(t.variants);return n.length!==r.length?!1:n.every(i=>i in t.variants&&Object.is(e.variants[i],t.variants[i]))});function Or(e){if(e.variants===void 0)return De(Le,v({},e));let t=e;if(t.children!=null){G()&&Er(t);let n=t,{funnel:r,microSignalGoals:i,agentData:l,agentDataByVariant:d,clientOnly:o,variants:m}=n,s=be(n,["funnel","microSignalGoals","agentData","agentDataByVariant","clientOnly","variants"]);return De(Le,L(v({},s),{children:t.children,variants:m}))}return De(_r,v({},t))}var kn=new Set;function Er(e){let t=["funnel","microSignalGoals","agentData","agentDataByVariant","clientOnly"].filter(n=>e[n]!==void 0);t.length===0||kn.has(e.id)||(kn.add(e.id),console.warn(`[sentient] <Adaptive id="${e.id}"> has both variants and children, so it runs as one experiment with your original and generated versions. These props only apply to a variants-only component and are ignored here: ${t.join(", ")}.`))}import{useEffect as Ie,useMemo as Pr,useRef as ct,useState as Rn,useSyncExternalStore as Gr}from"react";import{jsx as Lr}from"react/jsx-runtime";function Tr({id:e,default:t,component:n="span",className:r,goal:i}){var O;let l=D(),d=z(),o=Re(),m=ke(),s=ct(null),y=ct(null),f=Gr($,()=>me(e),()=>null),[h,R]=Rn(()=>{var b,k;return(k=(b=l==null?void 0:l.getAssignment(e,m))==null?void 0:b.content)!=null?k:null}),[c,u]=Rn(()=>{var b,k;return(k=(b=l==null?void 0:l.getAssignment(e,m))==null?void 0:b.variantId)!=null?k:null});Ie(()=>{if(f||!l)return;let b=l.getAssignment(e,m);if((b==null?void 0:b.content)!==void 0){u(b.variantId),R(b.content);return}let k=!1;return l.assign(e).then(w=>{if(!k){if(!w){G()&&console.warn(`[sentient] <AdaptiveText id="${e}"> assignment failed \u2014 showing default text.`);return}u(w.variantId),w.content&&R(w.content)}}),()=>{k=!0}},[l,e,m,f]),Ie(()=>{f||!l||!c||!d||s.current!==c&&(s.current=c,l.track({projectId:d,componentId:e,variantId:c,eventType:"variant_assigned",payload:{}}),o==null||o(e,c))},[l,c,d,e,o,f]);let p=i===void 0?"":typeof i=="string"?i:JSON.stringify(i),g=Pr(()=>i===void 0?null:B(i),[p]),a=i===void 0?null:typeof i=="string"?i:g.type,S=ct(!1);Ie(()=>{S.current=!1},[c,p]),Ie(()=>{if(f||!l||!c||!d||!g||!a)return;let b=y.current;if(!b)return;let k=H(g);return X(b,g,{fireGoal:()=>{S.current||(S.current=!0,l.track({projectId:d,componentId:e,variantId:c,eventType:"goal_achieved",goalType:a,payload:v({reward:1},k!==void 0?{goalValue:k}:{})}),l.goal(a,v({metadata:{componentId:e,variantId:c},weight:1,stepIndex:0},k!==void 0?{value:k}:{})))},fireStep:(w,_,E)=>{l.track({projectId:d,componentId:e,variantId:c,eventType:"goal_achieved",goalType:w,payload:{reward:_}}),l.goal(w,{metadata:{},weight:_,stepIndex:E})}})},[l,c,d,e,g,a,f]);let x=h!=null?h:t;if(f){let b=l==null?void 0:l.getAssignment(e,m);x=b&&b.variantId===f&&(O=b.content)!=null?O:t}return Lr(n,{ref:b=>{y.current=b},className:r,children:x})}import{useCallback as Dr,useRef as Ir}from"react";function dt(e){let t=D(),n=Ir(new Set);return Dr((r,i)=>{var l,d;if(!me(e)){if(i!=null&&i.once){if(n.current.has(r))return;n.current.add(r)}t==null||t.componentGoal(e,r,i),t==null||t.goal(r,v(v(v({metadata:(l=i==null?void 0:i.metadata)!=null?l:{},weight:(d=i==null?void 0:i.reward)!=null?d:1,stepIndex:0},(i==null?void 0:i.value)!==void 0?{value:i.value}:{}),(i==null?void 0:i.currency)!==void 0?{currency:i.currency}:{}),(i==null?void 0:i.externalId)!==void 0?{externalId:i.externalId}:{}))}},[t,e])}import{useEffect as Nr,useRef as An}from"react";function Vr(e,t={}){let m=t,{componentId:n}=m,r=be(m,["componentId"]),i=D(),l=dt(n!=null?n:""),d=An(!1),o=An(r);o.current=r,Nr(()=>{if(!i||d.current)return;d.current=!0;let{metadata:s,reward:y,value:f,currency:h,externalId:R}=o.current;if(n){l(e,o.current);return}i.goal(e,v(v(v({metadata:s!=null?s:{},weight:y!=null?y:1,stepIndex:0},f!==void 0?{value:f}:{}),h!==void 0?{currency:h}:{}),R!==void 0?{externalId:R}:{}))},[i,n,e,l])}import{renderPrePaintScript as Fr}from"@sentientui/core";import{confidenceBand as Mr}from"@sentientui/policy";import{jsx as jr}from"react/jsx-runtime";function Cn(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function $r(e){return e.persona?'(function(){try{var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+Cn(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+Cn(Mr(e.persona.confidence))+");}catch(e){}})();":Fr(e.apiKey)}function Br(e){return jr("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:$r(e)}})}import{useEffect as Fe,useMemo as gt,useRef as zr}from"react";import{validateSlotDecl as qr}from"@sentientui/policy";import{useEffect as ft,useReducer as Kr,useState as Wr,useSyncExternalStore as _n}from"react";import{armOfResult as Ne,baselineResultFor as Jr}from"@sentientui/core";import{confidenceBand as Ur}from"@sentientui/policy";function Ve(e,t){let n=D(),r=Ae(),[,i]=Kr(f=>f+1,0),l=_n($,()=>{var f;return typeof window!="undefined"?(f=window.__sentient_slot_overrides)==null?void 0:f[e]:void 0},()=>{}),d=l===void 0?r[e]:void 0,o=l===void 0&&d===void 0&&n?n.getSlotResult(e):null,m=(n==null?void 0:n.isLocal)===!0&&l===void 0&&d===void 0&&o===null;ft(()=>{if(!m||!n)return;let f=!1;return n.decide({slots:[t]}).then(h=>{!f&&h&&i()}),()=>{f=!0}},[n,e,m]);let s=(()=>{if(l!==void 0)return{result:l,arm:Ne(l),source:"override"};if(d!==void 0)return{result:d,arm:Ne(d),source:"preloaded"};if(o!==null){let h=n!=null&&n.isSlotDecided?n.isSlotDecided(e):!0;return{result:o,arm:Ne(o),source:h?"client":"seeded"}}let f=Jr(t);return{result:f,arm:Ne(f),source:"baseline"}})(),y=s.source==="preloaded"||s.source==="override";return ft(()=>{var h;if(!n||n.isLocal===!0||y||!n.decideSlots)return;let f=(h=n.onSlotsChanged)==null?void 0:h.call(n,i);return n.decideSlots([t]),()=>{var R;(R=n.cancelSlots)==null||R.call(n,[e]),f==null||f()}},[n,e,y]),s}function Hr(){var t;if(typeof window=="undefined")return null;let e=window.__sentient_persona_override;if(e!=null&&e.persona)return{persona:e.persona,confidence:(t=e.confidence)!=null?t:1};try{let n=new URLSearchParams(window.location.search).get("sentient_persona");if(n)return{persona:n,confidence:1}}catch(n){}return null}function Xr(){let e=D(),t=zt();_n($,Ct,()=>0);let[n,r]=Wr(!1);ft(()=>r(!0),[]);let i=o=>({persona:o.persona,confidence:o.confidence,band:Ur(o.confidence)});if(!n)return t?i(t):null;let l=Hr();if(l)return i(l);if(t)return i(t);let d=e?e.getPersona():null;return d?i(d):null}var On=new Set;function Zr(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[\\"]/g,"\\$&")}function Yr(e,t,n){let r=D(),i=z(),l=JSON.stringify(t),d=gt(()=>({id:e,dims:t}),[e,l]),{result:o,arm:m,source:s}=Ve(e,d),y=gt(()=>typeof o=="string"?{}:o,[m]);if(G()&&!On.has(e)){On.add(e);let u=qr({id:e,dims:Object.fromEntries(Object.entries(t).map(([g,a])=>[g,[...a]]))}),p=Object.values(t).reduce((g,a)=>g*a.length,1);u.ok?p>4&&console.warn(`[sentient] useAdaptiveTokens("${e}") declares ${p} combinations \u2014 more than the recommended 4. Each extra combination needs more traffic to learn; consider fewer dims/values.`):console.warn(`[sentient] useAdaptiveTokens("${e}"): invalid declaration \u2014 ${u.reason}. Serving baseline.`)}let f=(n==null?void 0:n.goal)===void 0?null:typeof n.goal=="string"?n.goal:JSON.stringify(n.goal);Fe(()=>ue({id:e,dims:t}),[e]);let h=zr(null);Fe(()=>{!r||s==="baseline"||s==="seeded"||s==="override"||h.current===m||(h.current=m,ee(r,i,e,m))},[r,i,e,m,s]);let R=n==null?void 0:n.funnel;Fe(()=>{var u;!r||!R||s==="override"||le(r,i,e,R,B((u=n==null?void 0:n.goal)!=null?u:"click"))},[r,i,e,R,f,s]),Fe(()=>{if(!r||!(n!=null&&n.goal)||s==="override"||s==="baseline"||s==="seeded")return;let u=document.querySelector(`[data-sentient-slot="${Zr(e)}"]`);if(!u){G()&&console.warn(`[sentient] useAdaptiveTokens("${e}"): a goal is declared but no element carries the returned props \u2014 spread {...props} on the slot's element.`);return}let p=Q(n.goal),g=H(n.goal),a=!1;return X(u,B(n.goal),{fireGoal:()=>{a||(a=!0,g!==void 0?r.componentGoal(e,p,{value:g}):r.componentGoal(e,p),r.goal(p,v({metadata:{componentId:e,arm:m},weight:1,stepIndex:0},g!==void 0?{value:g}:{})))},fireStep:(S,x,A)=>{r.componentGoal(e,S,{reward:x}),r.goal(S,{metadata:{componentId:e,arm:m},weight:x,stepIndex:A})}},p)},[r,e,f,m,s]);let c=gt(()=>{let u={"data-sentient-slot":e};for(let[p,g]of Object.entries(y))u[`data-${p}`]=g;return u},[e,y]);return{tokens:y,props:c}}import{useCallback as Qr,useEffect as ei,useMemo as ti}from"react";var En=new Set;function ni(e,t){var R;if(G()&&!t.goal)throw new Error(`[sentient] useAdaptive("${e}"): a goal is required \u2014 without one the optimizer accumulates exposures with no rewards and cannot learn. Pass e.g. goal: 'buy_click'.`);let{client:n,variantIds:r,variantId:i,isOverride:l,goalLabel:d,ref:o,nodeRef:m}=_e(e,t.variants,{goal:t.goal,funnel:t.funnel,microSignalGoals:t.microSignalGoals}),s=(R=i!=null?i:r[0])!=null?R:"",y=t.variants[s];ei(()=>{if(!G()||!n)return;let c=setTimeout(()=>{!m.current&&!En.has(e)&&(En.add(e),console.warn(`[sentient] useAdaptive("${e}"): bind was never attached \u2014 spread {...bind} on the rendered element, otherwise exposure and goal tracking cannot work and the optimizer learns nothing.`))},0);return()=>clearTimeout(c)},[n,e]);let f=Qr((c,u)=>{var g,a;if(l)return;let p=c!=null?c:d;p&&(n==null||n.componentGoal(e,p,u),n==null||n.goal(p,v(v(v({metadata:(g=u==null?void 0:u.metadata)!=null?g:{},weight:(a=u==null?void 0:u.reward)!=null?a:1,stepIndex:0},(u==null?void 0:u.value)!==void 0?{value:u.value}:{}),(u==null?void 0:u.currency)!==void 0?{currency:u.currency}:{}),(u==null?void 0:u.externalId)!==void 0?{externalId:u.externalId}:{})))},[n,e,d,l]),h=ti(()=>({ref:o,"data-sentient-id":e,"data-sentient-variant":s}),[o,e,s]);return{variant:s,value:y,bind:h,fireGoal:f}}import{Children as ri,isValidElement as ii,useEffect as Me,useMemo as Pn,useRef as Gn}from"react";import{jsx as si}from"react/jsx-runtime";var $e=new Set;function oi(e){var g;let t=D(),n=z(),r=Gn(null),i=Object.keys(e.arrangements).join(" "),l=Pn(()=>Object.keys(e.arrangements),[i]),d=Pn(()=>v({id:e.id,arms:l},e.baseline!==void 0?{baseline:e.baseline}:{}),[e.id,l,e.baseline]),{arm:o,source:m}=Ve(e.id,d);G()&&e.baseline!==void 0&&e.baseline!==l[0]&&!$e.has(e.id+":baseline")&&($e.add(e.id+":baseline"),console.warn(`[sentient] <AdaptiveGroup id="${e.id}">: baseline "${e.baseline}" is not the first-declared arrangement ("${l[0]}"). The first arrangement should usually be the page's real incumbent (the holdout sees it).`));let s=ri.toArray(e.children).filter(ii),y=new Map;for(let a of s)y.set(String((g=a.key)!=null?g:"").replace(/^\.\$/,""),a);let f=e.arrangements[o],h=f!==void 0&&f.length===s.length&&f.every(a=>y.has(a));G()&&f!==void 0&&!h&&!$e.has(e.id+":keys")&&($e.add(e.id+":keys"),console.warn(`[sentient] <AdaptiveGroup id="${e.id}">: arrangement "${o}" [${f.join(", ")}] does not match the children's keys \u2014 rendering declaration order (fail-safe).`));let R=h?f.map(a=>y.get(a)):s;Me(()=>ue({id:e.id,arms:Object.keys(e.arrangements)}),[e.id]);let c=Gn(null);Me(()=>{!t||m==="baseline"||m==="seeded"||m==="override"||c.current===o||(c.current=o,ee(t,n,e.id,o))},[t,n,e.id,o,m]);let u=e.funnel;Me(()=>{var a;!t||!u||m==="override"||le(t,n,e.id,u,B((a=e.goal)!=null?a:"click"))},[t,n,e.id,u,m]);let p=e.goal===void 0?null:typeof e.goal=="string"?e.goal:JSON.stringify(e.goal);return Me(()=>{if(!t||e.goal===void 0||m==="override"||m==="baseline"||m==="seeded")return;let a=r.current;if(!a)return;let S=Q(e.goal),x=H(e.goal),A=!1;return X(a,B(e.goal),{fireGoal:()=>{A||(A=!0,x!==void 0?t.componentGoal(e.id,S,{value:x}):t.componentGoal(e.id,S),t.goal(S,v({metadata:{componentId:e.id,arm:o},weight:1,stepIndex:0},x!==void 0?{value:x}:{})))},fireStep:(O,b,k)=>{t.componentGoal(e.id,O,{reward:b}),t.goal(O,{metadata:{componentId:e.id,arm:o},weight:b,stepIndex:k})}},S)},[t,e.id,p,o,m]),si("div",{ref:r,"data-sentient-id":e.id,"data-sentient-variant":o,children:R})}import{deriveSessionSegment as ai}from"@sentientui/core";var li=["page","blocks","layoutOrder"],Tn=new Map;function ui(e,t){Tn.set(e,t)}function Ln(e){return Tn.get(e)}function ci(e){var i,l;let t=(l=(i=e.content)!=null?i:Ln(e.page))!=null?l:{},n={};for(let[d,o]of Object.entries(t))li.includes(d)||(n[d]=o);let r=L(v({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(r.layoutOrder=e.layoutOrder),r}function di(e){return`<script type="application/ld+json">${Dn(e)}</script>`}function Dn(e){return JSON.stringify(v({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function fi(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,r]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(r,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
|
+
var Vn=Object.defineProperty,Fn=Object.defineProperties;var Mn=Object.getOwnPropertyDescriptors;var he=Object.getOwnPropertySymbols;var St=Object.prototype.hasOwnProperty,ht=Object.prototype.propertyIsEnumerable;var vt=(e,t,n)=>t in e?Vn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))St.call(t,n)&&vt(e,n,t[n]);if(he)for(var n of he(t))ht.call(t,n)&&vt(e,n,t[n]);return e},L=(e,t)=>Fn(e,Mn(t));var be=(e,t)=>{var n={};for(var r in e)St.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&he)for(var r of he(e))t.indexOf(r)<0&&ht.call(e,r)&&(n[r]=e[r]);return n};import{createContext as Un,useContext as F,useEffect as Y,useMemo as Jt,useRef as qe,useState as we,useSyncExternalStore as Hn}from"react";import{deriveSessionSegment as Xn,init as zn}from"@sentientui/core";var bt=new Map,xe=new Map;function xt(e,t){let n=xe.get(e);return n||(n=new Set,xe.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&xe.delete(e)}}function wt(e,t){bt.set(e,t);let n=xe.get(e);if(n)for(let r of n)try{r(t)}catch(i){}}function Be(e){var t;return(t=bt.get(e))!=null?t:null}var $n={on:!1,listeners:new Set};function kt(){if(typeof window=="undefined")return $n;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function je(){return kt().on}function Rt(e){let t=kt().listeners;return t.add(e),()=>{t.delete(e)}}function At(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,r,i)=>e.assign(t,n,r,i),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var Ke="sentient:overrides-changed";function Ct(){var e;return typeof window=="undefined"?0:(e=window.__sentient_overrides_version)!=null?e:0}function We(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(Ke))}function $(e){return typeof window=="undefined"?()=>{}:(window.addEventListener(Ke,e),()=>window.removeEventListener(Ke,e))}function _t(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function G(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}function B(e){return typeof e=="string"?{type:"click"}:e}function Q(e){return typeof e=="string"?e:e.type}function H(e){if(typeof e!="string"&&(e.type==="click"||e.type==="form_submit"||e.type==="scroll_depth"))return e.value}var Je=new Set,Ue=!1;function Ot(e){if(Je.has(e))return!0;if(Je.add(e),!Ue){Ue=!0;let t=()=>{Ue=!1,Je.clear()};if(typeof MessageChannel=="function"){let n=new MessageChannel;n.port1.onmessage=()=>{n.port1.close(),n.port2.close(),t()},n.port2.postMessage(0)}else setTimeout(t,0)}return!1}function Bn(e){if(!(e instanceof Element))return!1;let t=e.tagName.toLowerCase();return t==="a"||t==="button"?!0:e.getAttribute("role")==="button"}function Et(e,t,n){if(n){try{let i=e;for(;i&&i!==t;){if(i.matches(n))return!0;i=i.parentElement}}catch(i){}return!1}let r=e;for(;r&&r!==t;){if(Bn(r))return!0;r=r.parentElement}return!1}function X(e,t,n,r){if(t.type==="weighted_composite"){let s=new Set,y=[];return t.steps.forEach(({goal:f,name:h,weight:R},c)=>{let u=(p=!1)=>{s.has(c)||p&&r!==void 0&&Ot(`step\0${h}\0${R}\0${c}`)||(s.add(c),n.fireStep(h,R,c))};if(f.type==="click"){let p=g=>{let a=g.target;a instanceof Element&&Et(a,e,f.selector)&&u()};e.addEventListener("click",p),y.push(()=>e.removeEventListener("click",p));return}if(f.type==="form_submit"){let p=g=>{g.target instanceof HTMLFormElement&&e.contains(g.target)&&u()};e.addEventListener("submit",p),y.push(()=>e.removeEventListener("submit",p));return}if(f.type==="scroll_depth"){let p=Math.max(0,Math.min(1,f.threshold)),g=new IntersectionObserver(a=>{for(let S of a)if(S.intersectionRatio>=p){u(!0),g.disconnect();break}},{threshold:[p]});g.observe(e),y.push(()=>g.disconnect())}}),()=>{for(let f of y)f()}}let i=t.type==="composite"?t.all:[t],l=new Set(i.map((s,y)=>y)),d=()=>{r!==void 0&&Ot(r)||n.fireGoal()},o=(s,y=!1)=>{l.delete(s),l.size===0&&(y?d():n.fireGoal())},m=[];return i.forEach((s,y)=>{if(s.type==="click"){let f=h=>{let R=h.target;R instanceof Element&&Et(R,e,s.selector)&&(t.type==="composite"?o(y):n.fireGoal())};e.addEventListener("click",f),m.push(()=>e.removeEventListener("click",f));return}if(s.type==="form_submit"){let f=h=>{h.target instanceof HTMLFormElement&&e.contains(h.target)&&(t.type==="composite"?o(y):n.fireGoal())};e.addEventListener("submit",f),m.push(()=>e.removeEventListener("submit",f));return}if(s.type==="scroll_depth"){let f=Math.max(0,Math.min(1,s.threshold)),h=new IntersectionObserver(R=>{for(let c of R)if(c.intersectionRatio>=f){t.type==="composite"?o(y,!0):d(),h.disconnect();break}},{threshold:[f]});h.observe(e),m.push(()=>h.disconnect());return}}),()=>{for(let s of m)s()}}var Pt=new Set,Gt=new Set;function le(e,t,n,r,i){let l=`${r}|${n}`;if(Gt.has(l))return;Gt.add(l);let d=i.type==="weighted_composite"&&!Pt.has(r);d&&Pt.add(r),e.track({projectId:t,componentId:n,eventType:"funnel_declared",payload:d?{funnelId:r,steps:i.steps.map(o=>({goalId:o.name,weight:o.weight}))}:{funnelId:r}})}function ee(e,t,n,r){e.track({projectId:t,componentId:n,variantId:r,eventType:"variant_assigned",payload:{}})}var jn={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function ie(){if(typeof window=="undefined")return jn;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function ve(){ie().version+=1;for(let e of ie().listeners)e()}var Tt=()=>{};function Lt(e){return G()?(ie().components.set(e.id,e),ve(),()=>{ie().components.delete(e.id),ve()}):Tt}function ue(e){return G()?(ie().slots.set(e.id,e),ve(),()=>{ie().slots.delete(e.id),ve()}):Tt}function He(e){G()&&(ie().sections=[...e],ve())}var Dt="0.35.3",Xe=Dt!=="0.0.0-dev"?{name:"react",version:Dt}:void 0;function Kn(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function ce(e,t){Kn()[e]=t}function It(e){window.__sentient_vocabulary_override=e}function Nt(){var e;return typeof window=="undefined"?null:(e=window.__sentient_vocabulary_override)!=null?e:null}function Wn(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function de(e,t){Wn()[e]=t}var Vt="sentient_editor",Ft="sentient_preview_cell",Mt="sentient_refresh_region",ze="sentient-cell-preview-bar",oe="__preview__",fe=null;function $t(e){if((fe==null?void 0:fe.slotId)!==e)return null;let t=fe;return fe=null,t}function Bt(e,t){fetch(`${e.base}/editor/region-skeleton`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json"},body:JSON.stringify(v({slotId:e.slotId},t))}).then(n=>ge(n.ok?"Region refreshed \u2014 you can regenerate its versions now.":"Couldn\u2019t refresh this region \u2014 reopen the link from your dashboard.")).catch(()=>ge("Couldn\u2019t refresh this region \u2014 check your connection and reopen the link from your dashboard."))}function jt(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(ze))return;let t,n,r;try{let m=new URLSearchParams(window.location.search);t=m.get(Vt),n=m.get(Ft),r=m.get(Mt)}catch(m){return}if(t&&r){fe={slotId:r,token:t,base:(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"")},ce(r,{kind:"arms"}),de(r,oe),We();return}if(!t||!n)return;let i=n.lastIndexOf("~");if(i<=0)return;let l=n.slice(0,i),d=n.slice(i+1),o=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");fetch(`${o}/editor/cell-preview?slotId=${encodeURIComponent(l)}&persona=${encodeURIComponent(d)}`,{headers:{authorization:`Bearer ${t}`}}).then(async m=>{if(!m.ok){ge(m.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let s=await m.json();if(s.vocabulary&&Array.isArray(s.vocabulary.entries)&&It(s.vocabulary),s.compose!=null)ce(l,{kind:"arms",compose:{[oe]:s.compose}}),de(l,oe);else if(s.edits!=null&&typeof s.skeletonFp=="string"&&Array.isArray(s.leafToNode))ce(l,{kind:"arms",edits:{edits:s.edits,fp:s.skeletonFp,leafToNode:s.leafToNode}}),de(l,oe);else if(s.blocks!=null)ce(l,{kind:"arms",blocks:{[oe]:s.blocks}}),de(l,oe);else if(s.content!=null)ce(l,{kind:"arms",content:s.content}),de(l,oe);else{ge("Nothing to preview in that square yet.");return}We(),ge(`Previewing \u201C${s.slotName}\u201D for ${s.personaDisplay}${s.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var y;try{(y=document.querySelector(`[data-sentient-slot="${l}"]`))==null||y.scrollIntoView({block:"center"})}catch(f){}},300)}).catch(()=>ge("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function ge(e){var i;if(document.getElementById(ze))return;let t=document.createElement("div");t.id=ze,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let r=document.createElement("button");r.textContent="Exit preview",Object.assign(r.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),r.onclick=()=>{let l=new URL(window.location.href);l.searchParams.delete(Vt),l.searchParams.delete(Ft),l.searchParams.delete(Mt),window.location.assign(l.toString())},t.append(n,r),((i=document.body)!=null?i:document.documentElement).append(t)}var Jn="sentient_editor",Kt=!1;function Wt(e){if(Kt||typeof window=="undefined")return;let t=null;try{t=new URLSearchParams(window.location.search).get(Jn)}catch(i){return}if(!t)return;Kt=!0;let n=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),r=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:i})=>fetch(`${n}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(i(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?r():window.addEventListener("load",r,{once:!0})}import{jsx as tr}from"react/jsx-runtime";function qn(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return Xn({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var Ut="https://api.sentient-ui.com/v1",V=Un({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:Ut,debug:!1});function Zn(e){let[t,n]=we(!1),r=qe(e);r.current=e;let{cookie:i,value:l,event:d}=e!=null?e:{},o=typeof(e==null?void 0:e.check)=="function";return Y(()=>{let m=()=>{var h;let y=r.current;if(!y)return!1;if(y.check)return y.check()===!0;if(!y.cookie||typeof document=="undefined")return!1;let f=`${y.cookie}=${(h=y.value)!=null?h:"accepted"}`;return document.cookie.split("; ").some(R=>R.trim()===f)};if(n(m()),!d)return;let s=()=>{n(m())};return window.addEventListener(d,s),()=>window.removeEventListener(d,s)},[i,l,d,o]),t}function Yn(e){var c,u;let[t,n]=we(null),[r]=we(()=>{var p;return(p=e.sessionSegment)!=null?p:qn()}),[i,l]=we(je());Y(()=>Rt(()=>l(je())),[]),Y(()=>{jt(e.apiBaseUrl),Wt(e.apiBaseUrl)},[]);let d=Zn(e.consentFrom),o=e.consentFrom?e.consent===!0||d:e.consent,m=qe(null);Y(()=>{var A;if(o===!1&&!e.preConsentBehavior){(A=m.current)==null||A.destroy(),m.current=null,n(null);return}let p=v({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:r,consent:o,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},Xe?{sdk:Xe}:{}),g=!1,a=null,S=null,x=O=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:b})=>{g||(S=b(O,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:O})=>{g||(a=O(L(v({},p),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),m.current=a,n(a),x(a))}):(a=zn(p),m.current=a,n(a),x(a)),()=>{g=!0,S==null||S(),a==null||a.dispose()}},[o]),Y(()=>{if(!t)return;let p=!1,g=async()=>{if(p)return;let S;try{S=await t.fetchWeights()}catch(x){return}if(!p)for(let x of S){let A={componentId:x.componentId,updatedAt:x.updatedAt,variants:x.variants.map(O=>{var b;return{variantId:O.variantId,pulls:O.pulls,avgReward:(b=O.avgReward)!=null?b:0}})};wt(x.componentId,A)}};g();let a=setInterval(()=>{g()},6e4);return()=>{p=!0,clearInterval(a)}},[t]);let s=(c=e.ssrFallback)!=null?c:"first",y=((u=e.apiBaseUrl)!=null?u:Ut).replace(/\/$/,""),f=qe(null);Y(()=>{var a;if(typeof process!="undefined"&&((a=process.env)==null?void 0:a.NODE_ENV)==="production")return;let p={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:y},g=f.current;if(f.current=p,g!==null)for(let S of["apiKey","context","country","persona","apiBaseUrl"])Object.is(g[S],p[S])||console.warn(`[sentient] AdaptiveProvider: \`${S}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,y]),Y(()=>{var p;typeof process!="undefined"&&((p=process.env)==null?void 0:p.NODE_ENV)==="production"||_t({apiKey:e.apiKey,apiBaseUrl:y,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,y]),Y(()=>{let p=e.initialLayoutOrder;if(p&&p.length>0){He(p);return}e.declaredSections&&e.declaredSections.length>0&&He(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),Y(()=>{if(!G())return;let p=e.declaredSections;if(!p||p.length===0||typeof document=="undefined")return;let g=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),S=>S.getAttribute("data-sentient-id"))),a=p.filter(S=>!g.has(S));a.length>0&&console.warn(`[SentientUI] Declared section${a.length>1?"s":""} ${a.map(S=>`"${S}"`).join(", ")} ${a.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let h=Jt(()=>t&&i?At(t):t,[t,i]),R=Jt(()=>{var p,g,a,S,x,A,O,b;return{client:h,apiKey:e.apiKey,initialAssignments:(p=e.initialAssignments)!=null?p:{},sessionSegment:r,ssrFallback:s,onAssignment:e.onAssignment,initialLayoutOrder:(g=e.initialLayoutOrder)!=null?g:null,initialSlots:(a=e.initialSlots)!=null?a:{},initialSlotConfig:(S=e.initialSlotConfig)!=null?S:{},initialPalette:(x=e.initialPalette)!=null?x:null,initialVocabulary:(A=e.initialVocabulary)!=null?A:null,initialPersona:(O=e.initialPersona)!=null?O:null,apiBaseUrl:y,debug:(b=e.debug)!=null?b:!1}},[h,e.apiKey,e.initialAssignments,r,s,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,y,e.debug]);return tr(V.Provider,{value:R,children:e.children})}function D(){return F(V).client}function z(){return F(V).apiKey}function Ze(){return F(V).initialAssignments}function ke(){return F(V).sessionSegment}function Ht(){return F(V).ssrFallback}function Re(){return F(V).onAssignment}function Xt(){return F(V).debug}function Qn(){let e=F(V).initialLayoutOrder,t=Hn($,()=>{var n;return typeof window=="undefined"?null:(n=window.__sentient_layout_override)!=null?n:null},()=>null);return t!=null?t:e}function Ae(){return F(V).initialSlots}function zt(){return F(V).initialPersona}function qt(){return F(V).initialSlotConfig}function Zt(){return F(V).initialPalette}function Yt(){return F(V).initialVocabulary}function er(){return F(V).apiBaseUrl}import{memo as kr,useEffect as Rr,useState as Ar}from"react";import{useCallback as ir,useEffect as se,useMemo as en,useRef as Se,useState as or}from"react";import{attachMicroSignalDetectors as sr}from"@sentientui/core";import{useEffect as Ce,useRef as Qt,useState as nr,useSyncExternalStore as rr}from"react";import{pickFromWeights as Ye}from"@sentientui/policy";function me(e){var n;if(typeof window=="undefined")return null;let t=(n=window.__sentient_overrides)==null?void 0:n[e];if(t)return t;if(!window.location.search)return null;try{let r=new URLSearchParams(window.location.search);for(let i of r.getAll("sentient_variant")){let l=i.indexOf(":");if(l!==-1&&i.slice(0,l)===e)return i.slice(l+1)}}catch(r){}return null}function Qe(e,t,n,r){let i=Ze(),l=Ht(),d=D(),o=ke(),m=Re(),s=Xt(),y=Qt(null),f=rr($,()=>me(e),()=>null),h=f&&t.includes(f)?f:null,R=Qt(null);Ce(()=>{s&&h&&R.current!==h&&(R.current=h,console.info(`[sentient] override active: ${e} -> ${h}`))},[s,h,e]);let[c,u]=nr(()=>{var S,x;if(h)return{variantId:h,content:null,isLoading:!1,settled:!0};if(!d){let A=i[e];return A&&t.includes(A)?{variantId:A,content:null,isLoading:!1,settled:!0}:l==="first"&&t.length>0?{variantId:t[0],content:null,isLoading:!1,settled:!1}:{variantId:null,content:null,isLoading:!0,settled:!1}}let g=d.getAssignment(e,o);if(g&&(t.includes(g.variantId)||g.content))return{variantId:g.variantId,content:(S=g.content)!=null?S:null,isLoading:!1,settled:!0};let a=Be(e);if(a){let A=Ye(a.variants,t);if(A)return{variantId:A,content:null,isLoading:!1,settled:!0}}return{variantId:(x=t[0])!=null?x:null,content:null,isLoading:!1,settled:!1}}),p=g=>{m&&y.current!==g&&(y.current=g,m(e,g))};return Ce(()=>{var S;if(h||!d)return;let g=d.getAssignment(e,o);if(g&&(t.includes(g.variantId)||g.content)){u({variantId:g.variantId,content:(S=g.content)!=null?S:null,isLoading:!1,settled:!0}),p(g.variantId);return}let a=Be(e);if(a&&c.settled&&c.variantId&&c.variantId===Ye(a.variants,t)){p(c.variantId);return}u(x=>{var A;return x.variantId?x:{variantId:(A=t[0])!=null?A:null,content:null,isLoading:!1,settled:!1}})},[h,d,e,o]),Ce(()=>{if(h||!d)return;let g=d.getAssignment(e,o);if(g&&t.includes(g.variantId))return;let a=!1;return d.assign(e,t,n,r).then(S=>{var x;a||S&&(!t.includes(S.variantId)&&!S.content||(u({variantId:S.variantId,content:(x=S.content)!=null?x:null,isLoading:!1,settled:!0}),p(S.variantId)))}),()=>{a=!0}},[h,d,e,o]),Ce(()=>{if(!h&&d)return xt(e,g=>{var x;let a=d.getAssignment(e,o);if(a&&(t.includes(a.variantId)||a.content)){u({variantId:a.variantId,content:(x=a.content)!=null?x:null,isLoading:!1,settled:!0}),p(a.variantId);return}let S=Ye(g.variants,t);S&&(u({variantId:S,content:null,isLoading:!1,settled:!0}),p(S))})},[h,d,e,o]),h?{variantId:h,content:null,isLoading:!1,settled:!0,isOverride:!0}:c}function _e(e,t,n){let r=D(),i=z(),l=Object.keys(t).join("\0"),d=en(()=>Object.keys(t),[l]),{variantId:o,content:m,isOverride:s=!1,settled:y}=Qe(e,d,n.agentData,n.agentDataByVariant),[f,h]=or(null),R=Se(null),c=ir(_=>{R.current=_,h(_)},[]),u=n.goal,p=typeof u=="string"?u:JSON.stringify(u),g=en(()=>u?B(u):null,[p]),a=u?Q(u):"";se(()=>Lt({id:e,variantIds:d,goal:a}),[e,d,a]);let S=Se(null);se(()=>{s||y&&(!r||!o||!i||!f||S.current!==o&&(S.current=o,ee(r,i,e,o)))},[r,o,i,e,f,s,y]);let x=Se(!1),A=Se(new Set);se(()=>{x.current=!1,A.current=new Set},[o,g]);let O=n.funnel;se(()=>{s||!y||!r||!O||!g||le(r,i,e,O,g)},[r,i,e,O,g,s,y]);let b=n.cursorSignal===!0;se(()=>{if(!b||s||!y||!r||!o||!f)return;let _=null,E=0,N=()=>{E=Date.now(),_=setTimeout(()=>{r.track({projectId:i,componentId:e,variantId:o,eventType:"cursor_signal",payload:{hoverDuration:Date.now()-E}}),_=null},800)},T=()=>{_!==null&&(clearTimeout(_),_=null)};return f.addEventListener("mouseenter",N),f.addEventListener("mouseleave",T),()=>{f.removeEventListener("mouseenter",N),f.removeEventListener("mouseleave",T),_!==null&&clearTimeout(_)}},[b,r,o,i,e,f,s,y]);let k=Se(n.microSignalGoals);k.current=n.microSignalGoals;let w=n.microSignalGoals?JSON.stringify(n.microSignalGoals):"";return se(()=>{if(s||!y||!r||!o||!f)return;let _=Date.now();return sr((E,N={})=>{var Z,ne,J;r.track({projectId:i,componentId:e,variantId:o,eventType:"micro_signal",payload:v({signalType:E},N)});let T=(Z=k.current)==null?void 0:Z[E];if(!T||A.current.has(E))return;A.current.add(E);let K=typeof T=="string"?T:T.name,W=typeof T=="string"?1:(ne=T.weight)!=null?ne:1,q=typeof T=="string"?0:(J=T.stepIndex)!=null?J:0;r.goal(K,{metadata:v({signalType:E},N),weight:W,stepIndex:q})},f,_)},[r,o,i,e,f,w,s,y]),se(()=>{if(s||!y||!r||!o||!f||!g)return;let _=H(g);return X(f,g,{fireGoal:()=>{x.current||(x.current=!0,r.track({projectId:i,componentId:e,variantId:o,eventType:"goal_achieved",goalType:a,payload:v({reward:1},_!==void 0?{goalValue:_}:{})}),r.goal(a,v({metadata:{componentId:e,variantId:o},weight:1,stepIndex:0},_!==void 0?{value:_}:{})))},fireStep:(E,N,T)=>{r.track({projectId:i,componentId:e,variantId:o,eventType:"goal_achieved",goalType:E,payload:{reward:N}}),r.goal(E,{metadata:{},weight:N,stepIndex:T})}},a)},[r,o,i,e,f,g,a,s,y]),{client:r,variantIds:d,variantId:o,content:m,settled:y,isOverride:s,goalLabel:a,ref:c,nodeRef:R}}import{useEffect as j,useMemo as lt,useRef as ut}from"react";import{containsFormBlock as vn,reveal as xr}from"@sentientui/core";import{captureRegionSkeleton as Sn}from"@sentientui/core/region";import{useCallback as ar,useEffect as tn,useRef as et,useSyncExternalStore as Oe}from"react";import{armOfResult as lr}from"@sentientui/core";var nn=new Set;function rn(e,t){var x,A,O;let n=D(),r=et(t==null?void 0:t.baselineText);r.current=t==null?void 0:t.baselineText;let i=et(t==null?void 0:t.render);i.current=t==null?void 0:t.render;let l=et(t==null?void 0:t.skeleton);l.current=t==null?void 0:t.skeleton;let d=Ae(),o=qt(),m=Zt(),s=Yt(),y=Oe($,()=>{var b;return typeof window!="undefined"?(b=window.__sentient_slot_config_overrides)==null?void 0:b[e]:void 0},()=>{}),f=Oe($,()=>{var b;return typeof window!="undefined"?(b=window.__sentient_slot_overrides)==null?void 0:b[e]:void 0},()=>{}),h=b=>b==null?"":lr(b),R=ar(b=>{var k,w;return(w=(k=n==null?void 0:n.onSlotsChanged)==null?void 0:k.call(n,b))!=null?w:(()=>{})},[n]);Oe(R,()=>{var b;return(b=n==null?void 0:n.getSlotConfig(e))!=null?b:null},()=>null),Oe(R,()=>h(n==null?void 0:n.getSlotResult(e)),()=>"");let c=y===void 0?o[e]:void 0,u=y===void 0&&c===void 0&&n?n.getSlotConfig(e):null,p=(x=m!=null?m:n==null?void 0:n.getSitePalette())!=null?x:null,g=(O=s!=null?s:(A=n==null?void 0:n.getStyleVocabulary)==null?void 0:A.call(n))!=null?O:null,a=(()=>{var b,k,w;if(y!==void 0)return{config:y,arm:h(f),palette:p,vocabulary:(b=Nt())!=null?b:g,source:"override"};if(c!==void 0)return{config:c,arm:h((k=d[e])!=null?k:n==null?void 0:n.getSlotResult(e)),palette:p,vocabulary:g,source:"preloaded"};if(u!==null){let _=n!=null&&n.isSlotDecided?n.isSlotDecided(e):!0;return{config:u,arm:h((w=n==null?void 0:n.getSlotResult(e))!=null?w:d[e]),palette:p,vocabulary:g,source:_?"client":"seeded"}}return{config:null,arm:"",palette:p,vocabulary:g,source:"none"}})(),S=a.source==="preloaded"||a.source==="override";return tn(()=>{var K,W,q,Z,ne;if(!n||n.isLocal===!0||S)return;let b=a.source==="none",k=b&&(W=(K=r.current)==null?void 0:K.call(r))!=null?W:null,w=k!=null&&k!==""?{[e]:k}:void 0,_=(q=i.current)==null?void 0:q.call(i),E=b&&(ne=(Z=l.current)==null?void 0:Z.call(l))!=null?ne:null,N=v(v({},_?{render:{[e]:_}}:{}),E?{skeletons:{[e]:E}}:{}),T=Object.keys(N).length>0;return n.requestSlots?T?n.requestSlots([e],w,N):w?n.requestSlots([e],w):n.requestSlots([e]):b&&(E?n.reportSlots([e],w!=null?w:{},{[e]:E}):w?n.reportSlots([e],w):n.reportSlots([e])),()=>{var J;return(J=n.cancelSlots)==null?void 0:J.call(n,[e])}},[n,S,a.source,e]),tn(()=>{!G()||(n==null?void 0:n.isLocal)!==!0||a.source!=="none"||nn.has(e)||(nn.add(e),console.warn(`[sentient] <Adaptive id="${e}"> is rendering its baseline children: in local/keyless mode <Adaptive> serves ONLY what you pass as \`initialSlotConfig\` (there is no registry to decide from). Pass initialSlotConfig/initialSlots to <AdaptiveProvider> to preview arms locally.`))},[n,a.source,e]),a}import{cloneElement as ur,Fragment as on}from"react";import{jsx as I,jsxs as un}from"react/jsx-runtime";var te={none:"0",sm:"8px",md:"16px",lg:"24px"},tt={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch",between:"space-between"},cn={sm:"0.875em",md:"1em",lg:"1.25em"},cr={sm:"1.25em",md:"1.5em",lg:"2em"},sn={sm:"6px 14px",md:"10px 20px",lg:"14px 28px"},an={sm:"8px",md:"16px",lg:"32px"},dr={square:"1 / 1",landscape:"4 / 3",wide:"16 / 9"},fr={normal:"400",medium:"500",bold:"700"};function ln(e,t){return v(v({},e==="muted"?t!=null&&t.muted?{color:t.muted}:{opacity:.7}:{}),e==="accent"?v({fontWeight:600},t!=null&&t.accent?{color:t.accent}:{}):{})}function dn(e,t,n){var i,l,d,o;let r=t==null?void 0:t.accent;return L(v({display:"inline-block",padding:(i=sn[n!=null?n:"md"])!=null?i:sn.md,borderRadius:(l=t==null?void 0:t.radius)!=null?l:"8px",font:"inherit"},n?{fontSize:cn[n]}:{}),{textDecoration:e==="ghost"?"underline":"none",cursor:"pointer",background:e==="primary"?(d=t==null?void 0:t.primaryBg)!=null?d:"#111827":"transparent",color:e==="primary"?(o=t==null?void 0:t.primaryText)!=null?o:"#ffffff":r!=null?r:"inherit",border:e==="secondary"?`1px solid ${r!=null?r:"currentColor"}`:"none"})}function gr({node:e,opts:t}){var i,l,d,o,m;let n=(i=e.emphasis)!=null?i:"primary",r={padding:"8px 10px",font:"inherit",border:`1px solid ${(d=(l=t.palette)==null?void 0:l.border)!=null?d:"currentColor"}`,borderRadius:(m=(o=t.palette)==null?void 0:o.radius)!=null?m:"8px"};return un("form",{onSubmit:s=>{var h,R,c;s.preventDefault();let y=new FormData(s.currentTarget),f={};for(let u of e.fields)f[u.name]=String((h=y.get(u.name))!=null?h:"");(R=t.onFormGoal)==null||R.call(t,e.submitGoal);try{(c=t.onFormSubmit)==null||c.call(t,f)}catch(u){}},style:{display:"flex",flexDirection:"column",gap:"12px"},children:[e.fields.map(s=>{var y,f;return un("label",{style:{display:"flex",flexDirection:"column",gap:"4px",font:"inherit"},children:[s.label,s.kind==="textarea"?I("textarea",{name:s.name,required:s.required,placeholder:s.placeholder,rows:3,style:r}):s.kind==="select"?I("select",{name:s.name,required:s.required,style:r,children:((y=s.options)!=null?y:[]).map(h=>I("option",{value:h,children:h},h))}):I("input",{name:s.name,type:(f=s.inputType)!=null?f:"text",required:s.required,placeholder:s.placeholder,style:r})]},s.name)}),I("button",{type:"submit",style:dn(n,t.palette),children:e.submitLabel})]})}function mr(e,t){var r,i;let n=e.like;return n?(i=(r=t.vocabulary)==null?void 0:r.entries.find(l=>l.id===n))==null?void 0:i.classes:void 0}function fn(e,t){var r;let n=e?(r=t.vocabulary)==null?void 0:r.entries.find(i=>i.id===e):void 0;return n!=null&&n.computed.inheritsColor?n.computed.color:void 0}function pe(e,t){var i;let n=pr(e,t),r=fn(e.like,t);return n&&r?ur(n,{style:L(v({},(i=n.props.style)!=null?i:{}),{color:r})}):n}function pr(e,t){var n,r,i,l,d,o,m,s,y,f,h,R,c,u,p,g,a,S,x,A,O,b,k;try{let w=mr(e,t);switch(e.type){case"stack":{let _=(r=te[(n=e.gap)!=null?n:"md"])!=null?r:te.md,E=e.surface==="raised"&&!w,N=(i=e.pad)!=null?i:E?"md":void 0;return I("div",L(v({},w?{className:w}:{}),{style:v(v(v(v(v({display:"flex",flexDirection:e.direction,gap:_},e.align?{alignItems:tt[e.align]}:{}),e.justify?{justifyContent:tt[e.justify]}:{}),e.wrap?{flexWrap:"wrap"}:{}),N?{padding:(l=te[N])!=null?l:te.md}:{}),E?L(v(v({},(d=t.palette)!=null&&d.surface?{background:t.palette.surface}:{}),(o=t.palette)!=null&&o.surface&&((m=t.palette)!=null&&m.surfaceText)?{color:t.palette.surfaceText}:{}),{border:`1px solid ${(y=(s=t.palette)==null?void 0:s.border)!=null?y:"currentColor"}`,borderRadius:(h=(f=t.palette)==null?void 0:f.radius)!=null?h:"8px"}):{}),children:((R=e.children)!=null?R:[]).map((T,K)=>{let W=pe(T,t);return W===null?null:I(on,{children:W},K)})}))}case"grid":{let _=(u=te[(c=e.gap)!=null?c:"md"])!=null?u:te.md;return I("div",L(v({},w?{className:w}:{}),{style:v(v({display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(max(200px, calc((100% - ${e.columns-1} * ${_}) / ${e.columns})), 1fr))`,gap:_},e.align?{alignItems:tt[e.align]}:{}),e.pad?{padding:(p=te[e.pad])!=null?p:te.md}:{}),children:((g=e.children)!=null?g:[]).map((E,N)=>{let T=pe(E,t);return T===null?null:I(on,{children:T},N)})}))}case"text":return w?I("p",{className:w,style:e.maxWidth==="measure"?{maxWidth:"65ch"}:void 0,children:e.value}):I("p",{style:v(v(v(v(v({margin:0},e.size?{fontSize:cn[e.size]}:{}),e.weight?{fontWeight:fr[e.weight]}:{}),e.align?{textAlign:e.align}:{}),e.maxWidth==="measure"?{maxWidth:"65ch"}:{}),ln(e.tone,t.palette)),children:e.value});case"heading":{let _=`h${e.level}`;return w?I(_,{className:w,style:e.maxWidth==="measure"?{maxWidth:"65ch"}:void 0,children:e.value}):I(_,{style:v(v({margin:0,fontSize:cr[(a=e.size)!=null?a:"md"]},e.align?{textAlign:e.align}:{}),e.maxWidth==="measure"?{maxWidth:"65ch"}:{}),children:e.value})}case"button":{let _=(S=e.emphasis)!=null?S:"primary";return I("a",L(v(v({href:e.href},e.tag?{"data-sentient-tag":e.tag}:{}),w?{className:w}:{style:dn(_,t.palette,e.size)}),{children:e.label}))}case"link":return I("a",L(v(v({href:e.href},e.tag?{"data-sentient-tag":e.tag}:{}),w?{className:w}:{style:{color:"inherit",textDecoration:"underline"}}),{children:e.label}));case"image":return I("img",L(v({src:e.src,alt:e.alt},w?{className:w}:{}),{style:v(v({display:"block",maxWidth:"100%"},e.ratio&&e.ratio!=="auto"?{aspectRatio:dr[e.ratio],width:"100%"}:{}),e.fit?{objectFit:e.fit}:{})}));case"badge":return w?I("span",{className:w,children:e.value}):I("span",{style:v({display:"inline-block",padding:"2px 10px",borderRadius:"999px",fontSize:"0.75em",border:`1px solid ${(A=(x=t.palette)==null?void 0:x.border)!=null?A:"currentColor"}`},ln(e.tone,t.palette)),children:e.value});case"spacer":return I("div",{style:{height:(O=an[e.size])!=null?O:an.md}});case"divider":return I("hr",{style:{border:"none",borderTop:`1px solid ${(k=(b=t.palette)==null?void 0:b.border)!=null?k:"currentColor"}`,margin:0,width:"100%"}});case"form":return I(gr,{node:e,opts:t});default:return null}}catch(w){return null}}function nt(e,t){var l,d,o,m;let n=pe(e.tree,t);if(n===null)return null;let r=(l=e.surface)!=null&&l.like?(o=(d=t.vocabulary)==null?void 0:d.entries.find(s=>s.id===e.surface.like))==null?void 0:o.classes:void 0,i=fn((m=e.surface)==null?void 0:m.like,t);return r?I("div",L(v({className:r},i?{style:{color:i}}:{}),{children:n})):n}import{cloneElement as Ee,isValidElement as Pe}from"react";import{normalizeLeafText as yr,skeletonFingerprint as vr}from"@sentientui/core/region";function Ge(e){return typeof e=="string"&&e.trim()!==""||typeof e=="number"}function Te(e){let t=e.props;if(t.dangerouslySetInnerHTML==null)return t.children}function ae(e){return Ge(e)?1:Array.isArray(e)?e.reduce((t,n)=>t+ae(n),0):Pe(e)?ae(Te(e)):0}function Sr(e,t){return Array.isArray(t)?Ee(e,void 0,...t):Ee(e,void 0,t)}function rt(e,t){if(Ge(e))return t;if(Array.isArray(e))return e.map(n=>rt(n,t));if(Pe(e)){let n=Te(e);return ae(n)===0?e:Sr(e,rt(n,t))}return e}function gn(e,t){return ae(e)===1?rt(e,t):null}var M=e=>e.join("/");function it(e,t,n){if(Ge(e)){n.leafPaths.push(t),n.texts.push(yr(String(e)));return}if(Array.isArray(e)){e.forEach((r,i)=>it(r,[...t,i],n));return}Pe(e)&&(n.elements.set(M(t),e),it(Te(e),[...t,"c"],n))}function st(e){let t={leafPaths:[],texts:[],elements:new Map};return it(e,[],t),t}function hr(e){return st(e).texts}function mn(e){let t=hr(e);return t.length===0?null:vr(t)}function br(e){let t=[];return e.forEach((n,r)=>{n==="c"&&t.push(e.slice(0,r))}),t}function pn(e,t){let n=t.reduce((i,l)=>Math.max(i,l+1),0),r=[];for(let i=0;i<n;i++){let l=t.flatMap((o,m)=>o===i?[br(e.leafPaths[m])]:[]);if(l.length===0){r.push(null);continue}let d=l[0];for(let o of l.slice(1)){let m=new Set(o.map(M));d=d.filter(s=>m.has(M(s)))}r.push(d.length>0?d[d.length-1]:null)}return r}function ot(e){var n;let t=(n=e==null?void 0:e.props)==null?void 0:n.className;return typeof t=="string"?t:void 0}function at(e,t){let n=st(t);if(n.texts.length!==e.leaves.length||n.texts.some((l,d)=>l!==e.leaves[d]))return null;let r=pn(n,e.leafToNode),i=e.nodes.map((l,d)=>{let o=r[d],m=o?n.elements.get(M(o)):void 0,s=!!m&&(typeof m.type=="string"||ot(m)!==void 0);return L(v({},l),{restylable:s})});return L(v({},e),{nodes:i})}function yn(e,t,n){var c;let r=st(e);if(r.leafPaths.length!==n.length)return null;let i=n.reduce((u,p)=>Math.max(u,p+1),0);for(let u of Object.keys(t.nodes))if(!/^\d+$/.test(u)||Number(u)>=i)return null;let l=pn(r,n),d=new Map;n.forEach((u,p)=>{d.has(u)||d.set(u,p)});let o=new Map(r.leafPaths.map((u,p)=>[M(u),p])),m=new Set,s=new Map,y=!1;for(let[u,p]of Object.entries(t.nodes)){let g=Number(u),a=l[g];if(p.hidden&&(a?m.add(M(a)):y=!0),p.like!==void 0){let S=l[p.like],x=a?r.elements.get(M(a)):void 0,A=S?ot(r.elements.get(M(S))):void 0;!a||A===void 0||ot(x)===void 0?y=!0:s.set(M(a),A)}}let f=new Map(Object.entries((c=t.order)!=null?c:{})),h=(u,p)=>{var g;if(Ge(u)){let a=o.get(M(p));if(a===void 0)return u;let S=n[a],x=(g=t.nodes[String(S)])==null?void 0:g.text;return x===void 0?u:d.get(S)===a?x:""}if(Array.isArray(u)){let a=u.map((S,x)=>h(S,[...p,x]));for(let[S,x]of f){let A=x.map(k=>{let w=l[k];return!w||w.length!==p.length+1||M(w.slice(0,-1))!==M(p)?-1:w[w.length-1]});if(A.some(k=>k<0))continue;let O=[...A].sort((k,w)=>k-w),b=[...a];O.forEach((k,w)=>{a[k]=b[A[w]]}),f.delete(S)}return a}if(Pe(u)){let a=M(p);if(m.has(a))return null;let S=Te(u);if(ae(S)===0)return u;let x=h(S,[...p,"c"]),A=s.get(a),O=A!==void 0?{className:A}:void 0;return Array.isArray(x)?Ee(u,O,...x):Ee(u,O,x)}return u},R=h(e,[]);return y||f.size>0?null:R}import{jsx as wr}from"react/jsx-runtime";var hn=new Set,bn=new Set,xn=new Set,wn="authored.";function Le({id:e,children:t,variants:n,onFormSubmit:r,goal:i,className:l,reportBaselineText:d=!0}){var mt,pt;let o=D(),m=z(),s=ut(null),y=lt(()=>mn(t),[t]),f=n?Object.keys(n).join("|"):"",h=lt(()=>v({fp:y!=null?y:"0000000000000000",forms:!!r,compose:!0,content:ae(t)===1},f!==""?{authored:f.split("|"),children:!0}:{}),[y,t,r,f]),R=()=>{var U;let C=s.current;if(!C||!d)return null;let P=Sn(C);return P.skeleton?(U=at(P.skeleton,t))!=null?U:L(v({},P.skeleton),{editable:!1,nodes:P.skeleton.nodes.map(re=>L(v({},re),{restylable:!1}))}):{status:P.reason}},{config:c,arm:u,palette:p,vocabulary:g,source:a}=rn(e,{baselineText:d?()=>{var C,P;return(P=(C=s.current)==null?void 0:C.textContent)!=null?P:null}:void 0,render:()=>h,skeleton:R}),S=u!==""?(mt=c==null?void 0:c.blocks)==null?void 0:mt[u]:void 0,x=u!==""?(pt=c==null?void 0:c.compose)==null?void 0:pt[u]:void 0,A=(S!==void 0&&vn(S)||x!==void 0&&vn(x.tree))&&!r;j(()=>{!A||!G()||hn.has(e)||(hn.add(e),console.warn(`[sentient] AdaptiveSlot "${e}" was served a form arm but has no onFormSubmit handler \u2014 rendering its baseline children instead. Pass onFormSubmit to render generated forms.`))},[A,e]);let O=C=>{!o||a==="override"||(a!=="seeded"&&o.componentGoal(e,C),o.goal(C,{metadata:{componentId:e,arm:u},weight:1,stepIndex:0}))},b=t,k=!1,w=u.startsWith(wn)?u.slice(wn.length):null;if((c==null?void 0:c.blocked)==="variant_history")k=!0;else if(w!==null)n&&Object.prototype.hasOwnProperty.call(n,w)?b=n[w]:k=!0;else if(x!==void 0){let C=A?null:nt(x,{palette:p,vocabulary:g,onFormSubmit:r,onFormGoal:O});C===null?k=!0:b=C}else if(S!==void 0){let C=A?null:pe(S,{palette:p,vocabulary:g,onFormSubmit:r,onFormGoal:O});C===null?k=!0:b=C}else if((c==null?void 0:c.edits)!==void 0&&a!=="none"){let C=c.edits,P=C.fp===y?yn(t,C.edits,C.leafToNode):null;P===null?k=!0:b=P}else if((c==null?void 0:c.content)!==void 0&&a!=="none"){let C=gn(t,c.content);C===null?k=!0:b=C}let _=k&&S===void 0&&x===void 0&&(c==null?void 0:c.edits)===void 0&&w===null&&(c==null?void 0:c.blocked)===void 0;j(()=>{(c==null?void 0:c.blocked)!=="variant_history"||!G()||xn.has(e)||(xn.add(e),console.warn(`[sentient] <Adaptive id="${e}"> has results from its earlier variants experiment, so it is showing your original until you migrate it: Components \u2192 "${e}" \u2192 Migrate. Deploying code never switches an experiment.`))},[c==null?void 0:c.blocked,e]);let E=w!==null&&!k?w:null;j(()=>{var ye;if(!E||!d||!o)return;let C=s.current;if(!C)return;let P=Sn(C),U=P.skeleton?at(P.skeleton,n==null?void 0:n[E]):null,re=(ye=C.textContent)==null?void 0:ye.trim();o.reportSlots([],void 0,void 0,{[e]:[v(v({key:E},re?{text:re}:{}),U?{skeleton:U}:{})]})},[E,o,e]);let N=k&&(c==null?void 0:c.edits)!==void 0&&(a==="preloaded"||a==="client");j(()=>{var C;!N||!(c!=null&&c.edits)||(C=o==null?void 0:o.reportDrift)==null||C.call(o,e,c.edits.fp,y,c.edits.fp===y?"unaddressable":"fp_mismatch")},[N,e,y,o]);let T=b===t;j(()=>{var P;if(!(c!=null&&c.needsSkeleton)||!T)return;let C=R();C&&((P=o==null?void 0:o.reportSkeleton)==null||P.call(o,e,C))},[c==null?void 0:c.needsSkeleton,T,e,o]),j(()=>{if(!T)return;let C=$t(e);if(!C)return;let P=R();Bt(C,P&&"status"in P?{status:P.status}:{skeleton:P})},[e,T]),j(()=>{!_||!G()||bn.has(e)||(bn.add(e),console.warn(`[sentient] <Adaptive id="${e}"> was served a text version, but its children have several separate texts or none Sentient can reach \u2014 rendering the original instead. Regenerate the version (new versions edit each text in place), or put a single text inline.`))},[_,e]);let K=c!=null&&c.blocks?Object.keys(c.blocks).sort().join("|"):"";j(()=>ue({id:e,arms:K===""?void 0:K.split("|")}),[e,K]);let W=ut(null);j(()=>{!o||a==="none"||a==="seeded"||a==="override"||u===""||k||W.current!==u&&(W.current=u,ee(o,m,e,u))},[o,m,e,u,a,k]);let q=a!=="none"&&a!=="seeded"&&!k,Z=q?u:"",ne=i===void 0?null:typeof i=="string"?i:JSON.stringify(i);j(()=>{if(!o||!i||a==="override")return;let C=s.current;if(!C)return;let P=Q(i),U=H(i),re=!1;return X(C,B(i),{fireGoal:()=>{re||(re=!0,q&&(U!==void 0?o.componentGoal(e,P,{value:U}):o.componentGoal(e,P)),o.goal(P,v({metadata:{componentId:e,arm:Z},weight:1,stepIndex:0},U!==void 0?{value:U}:{})))},fireStep:(ye,yt,Nn)=>{q&&o.componentGoal(e,ye,{reward:yt}),o.goal(ye,{metadata:{componentId:e,arm:Z},weight:yt,stepIndex:Nn})}},P)},[o,e,ne,u,a,k,q,Z]);let J=ut(null);j(()=>{let C=s.current;if(C){if(J.current===null){J.current=u;return}J.current!==u&&(J.current=u,xr(C))}},[u]);let In=lt(()=>v({"data-sentient-slot":e},u!==""?{"data-sentient-arm":u}:{}),[e,u]);return wr("div",L(v({ref:s,className:l},In),{children:b}))}import{jsx as De}from"react/jsx-runtime";function Cr(e){var s;let{client:t,variantId:n,content:r,ref:i}=_e(e.id,e.variants,{goal:e.goal,funnel:e.funnel,microSignalGoals:e.microSignalGoals,agentData:e.agentData,agentDataByVariant:e.agentDataByVariant,cursorSignal:!0}),[l,d]=Ar(!1);if(Rr(()=>{d(!0)},[]),e.clientOnly&&(!l||!t)||!n)return null;let o=(s=e.variants[n])!=null?s:null,m=o===null?r:null;return G()&&o===null&&m===null&&console.warn(`[sentient] <Adaptive id="${e.id}"> was assigned variant "${n}" but no matching key exists in props.variants. If this is a dashboard-managed text variant, use <AdaptiveText id="${e.id}"> instead.`),De("div",{ref:i,"data-sentient-id":e.id,"data-sentient-variant":n,children:o!=null?o:m})}var _r=kr(Cr,(e,t)=>{if(e.id!==t.id||e.goal!==t.goal&&JSON.stringify(e.goal)!==JSON.stringify(t.goal)||e.microSignalGoals!==t.microSignalGoals||e.funnel!==t.funnel||e.clientOnly!==t.clientOnly||e.agentData!==t.agentData||e.agentDataByVariant!==t.agentDataByVariant)return!1;if(e.variants===t.variants)return!0;let n=Object.keys(e.variants),r=Object.keys(t.variants);return n.length!==r.length?!1:n.every(i=>i in t.variants&&Object.is(e.variants[i],t.variants[i]))});function Or(e){if(e.variants===void 0)return De(Le,v({},e));let t=e;if(t.children!=null){G()&&Er(t);let n=t,{funnel:r,microSignalGoals:i,agentData:l,agentDataByVariant:d,clientOnly:o,variants:m}=n,s=be(n,["funnel","microSignalGoals","agentData","agentDataByVariant","clientOnly","variants"]);return De(Le,L(v({},s),{children:t.children,variants:m}))}return De(_r,v({},t))}var kn=new Set;function Er(e){let t=["funnel","microSignalGoals","agentData","agentDataByVariant","clientOnly"].filter(n=>e[n]!==void 0);t.length===0||kn.has(e.id)||(kn.add(e.id),console.warn(`[sentient] <Adaptive id="${e.id}"> has both variants and children, so it runs as one experiment with your original and generated versions. These props only apply to a variants-only component and are ignored here: ${t.join(", ")}.`))}import{useEffect as Ie,useMemo as Pr,useRef as ct,useState as Rn,useSyncExternalStore as Gr}from"react";import{jsx as Lr}from"react/jsx-runtime";function Tr({id:e,default:t,component:n="span",className:r,goal:i}){var O;let l=D(),d=z(),o=Re(),m=ke(),s=ct(null),y=ct(null),f=Gr($,()=>me(e),()=>null),[h,R]=Rn(()=>{var b,k;return(k=(b=l==null?void 0:l.getAssignment(e,m))==null?void 0:b.content)!=null?k:null}),[c,u]=Rn(()=>{var b,k;return(k=(b=l==null?void 0:l.getAssignment(e,m))==null?void 0:b.variantId)!=null?k:null});Ie(()=>{if(f||!l)return;let b=l.getAssignment(e,m);if((b==null?void 0:b.content)!==void 0){u(b.variantId),R(b.content);return}let k=!1;return l.assign(e).then(w=>{if(!k){if(!w){G()&&console.warn(`[sentient] <AdaptiveText id="${e}"> assignment failed \u2014 showing default text.`);return}u(w.variantId),w.content&&R(w.content)}}),()=>{k=!0}},[l,e,m,f]),Ie(()=>{f||!l||!c||!d||s.current!==c&&(s.current=c,l.track({projectId:d,componentId:e,variantId:c,eventType:"variant_assigned",payload:{}}),o==null||o(e,c))},[l,c,d,e,o,f]);let p=i===void 0?"":typeof i=="string"?i:JSON.stringify(i),g=Pr(()=>i===void 0?null:B(i),[p]),a=i===void 0?null:typeof i=="string"?i:g.type,S=ct(!1);Ie(()=>{S.current=!1},[c,p]),Ie(()=>{if(f||!l||!c||!d||!g||!a)return;let b=y.current;if(!b)return;let k=H(g);return X(b,g,{fireGoal:()=>{S.current||(S.current=!0,l.track({projectId:d,componentId:e,variantId:c,eventType:"goal_achieved",goalType:a,payload:v({reward:1},k!==void 0?{goalValue:k}:{})}),l.goal(a,v({metadata:{componentId:e,variantId:c},weight:1,stepIndex:0},k!==void 0?{value:k}:{})))},fireStep:(w,_,E)=>{l.track({projectId:d,componentId:e,variantId:c,eventType:"goal_achieved",goalType:w,payload:{reward:_}}),l.goal(w,{metadata:{},weight:_,stepIndex:E})}})},[l,c,d,e,g,a,f]);let x=h!=null?h:t;if(f){let b=l==null?void 0:l.getAssignment(e,m);x=b&&b.variantId===f&&(O=b.content)!=null?O:t}return Lr(n,{ref:b=>{y.current=b},className:r,children:x})}import{useCallback as Dr,useRef as Ir}from"react";function dt(e){let t=D(),n=Ir(new Set);return Dr((r,i)=>{var l,d;if(!me(e)){if(i!=null&&i.once){if(n.current.has(r))return;n.current.add(r)}t==null||t.componentGoal(e,r,i),t==null||t.goal(r,v(v(v({metadata:(l=i==null?void 0:i.metadata)!=null?l:{},weight:(d=i==null?void 0:i.reward)!=null?d:1,stepIndex:0},(i==null?void 0:i.value)!==void 0?{value:i.value}:{}),(i==null?void 0:i.currency)!==void 0?{currency:i.currency}:{}),(i==null?void 0:i.externalId)!==void 0?{externalId:i.externalId}:{}))}},[t,e])}import{useEffect as Nr,useRef as An}from"react";function Vr(e,t={}){let m=t,{componentId:n}=m,r=be(m,["componentId"]),i=D(),l=dt(n!=null?n:""),d=An(!1),o=An(r);o.current=r,Nr(()=>{if(!i||d.current)return;d.current=!0;let{metadata:s,reward:y,value:f,currency:h,externalId:R}=o.current;if(n){l(e,o.current);return}i.goal(e,v(v(v({metadata:s!=null?s:{},weight:y!=null?y:1,stepIndex:0},f!==void 0?{value:f}:{}),h!==void 0?{currency:h}:{}),R!==void 0?{externalId:R}:{}))},[i,n,e,l])}import{renderPrePaintScript as Fr}from"@sentientui/core";import{confidenceBand as Mr}from"@sentientui/policy";import{jsx as jr}from"react/jsx-runtime";function Cn(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function $r(e){return e.persona?'(function(){try{var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+Cn(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+Cn(Mr(e.persona.confidence))+");}catch(e){}})();":Fr(e.apiKey)}function Br(e){return jr("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:$r(e)}})}import{useEffect as Fe,useMemo as gt,useRef as zr}from"react";import{validateSlotDecl as qr}from"@sentientui/policy";import{useEffect as ft,useReducer as Kr,useState as Wr,useSyncExternalStore as _n}from"react";import{armOfResult as Ne,baselineResultFor as Jr}from"@sentientui/core";import{confidenceBand as Ur}from"@sentientui/policy";function Ve(e,t){let n=D(),r=Ae(),[,i]=Kr(f=>f+1,0),l=_n($,()=>{var f;return typeof window!="undefined"?(f=window.__sentient_slot_overrides)==null?void 0:f[e]:void 0},()=>{}),d=l===void 0?r[e]:void 0,o=l===void 0&&d===void 0&&n?n.getSlotResult(e):null,m=(n==null?void 0:n.isLocal)===!0&&l===void 0&&d===void 0&&o===null;ft(()=>{if(!m||!n)return;let f=!1;return n.decide({slots:[t]}).then(h=>{!f&&h&&i()}),()=>{f=!0}},[n,e,m]);let s=(()=>{if(l!==void 0)return{result:l,arm:Ne(l),source:"override"};if(d!==void 0)return{result:d,arm:Ne(d),source:"preloaded"};if(o!==null){let h=n!=null&&n.isSlotDecided?n.isSlotDecided(e):!0;return{result:o,arm:Ne(o),source:h?"client":"seeded"}}let f=Jr(t);return{result:f,arm:Ne(f),source:"baseline"}})(),y=s.source==="preloaded"||s.source==="override";return ft(()=>{var h;if(!n||n.isLocal===!0||y||!n.decideSlots)return;let f=(h=n.onSlotsChanged)==null?void 0:h.call(n,i);return n.decideSlots([t]),()=>{var R;(R=n.cancelSlots)==null||R.call(n,[e]),f==null||f()}},[n,e,y]),s}function Hr(){var t;if(typeof window=="undefined")return null;let e=window.__sentient_persona_override;if(e!=null&&e.persona)return{persona:e.persona,confidence:(t=e.confidence)!=null?t:1};try{let n=new URLSearchParams(window.location.search).get("sentient_persona");if(n)return{persona:n,confidence:1}}catch(n){}return null}function Xr(){let e=D(),t=zt();_n($,Ct,()=>0);let[n,r]=Wr(!1);ft(()=>r(!0),[]);let i=o=>({persona:o.persona,confidence:o.confidence,band:Ur(o.confidence)});if(!n)return t?i(t):null;let l=Hr();if(l)return i(l);if(t)return i(t);let d=e?e.getPersona():null;return d?i(d):null}var On=new Set;function Zr(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[\\"]/g,"\\$&")}function Yr(e,t,n){let r=D(),i=z(),l=JSON.stringify(t),d=gt(()=>({id:e,dims:t}),[e,l]),{result:o,arm:m,source:s}=Ve(e,d),y=gt(()=>typeof o=="string"?{}:o,[m]);if(G()&&!On.has(e)){On.add(e);let u=qr({id:e,dims:Object.fromEntries(Object.entries(t).map(([g,a])=>[g,[...a]]))}),p=Object.values(t).reduce((g,a)=>g*a.length,1);u.ok?p>4&&console.warn(`[sentient] useAdaptiveTokens("${e}") declares ${p} combinations \u2014 more than the recommended 4. Each extra combination needs more traffic to learn; consider fewer dims/values.`):console.warn(`[sentient] useAdaptiveTokens("${e}"): invalid declaration \u2014 ${u.reason}. Serving baseline.`)}let f=(n==null?void 0:n.goal)===void 0?null:typeof n.goal=="string"?n.goal:JSON.stringify(n.goal);Fe(()=>ue({id:e,dims:t}),[e]);let h=zr(null);Fe(()=>{!r||s==="baseline"||s==="seeded"||s==="override"||h.current===m||(h.current=m,ee(r,i,e,m))},[r,i,e,m,s]);let R=n==null?void 0:n.funnel;Fe(()=>{var u;!r||!R||s==="override"||le(r,i,e,R,B((u=n==null?void 0:n.goal)!=null?u:"click"))},[r,i,e,R,f,s]),Fe(()=>{if(!r||!(n!=null&&n.goal)||s==="override"||s==="baseline"||s==="seeded")return;let u=document.querySelector(`[data-sentient-slot="${Zr(e)}"]`);if(!u){G()&&console.warn(`[sentient] useAdaptiveTokens("${e}"): a goal is declared but no element carries the returned props \u2014 spread {...props} on the slot's element.`);return}let p=Q(n.goal),g=H(n.goal),a=!1;return X(u,B(n.goal),{fireGoal:()=>{a||(a=!0,g!==void 0?r.componentGoal(e,p,{value:g}):r.componentGoal(e,p),r.goal(p,v({metadata:{componentId:e,arm:m},weight:1,stepIndex:0},g!==void 0?{value:g}:{})))},fireStep:(S,x,A)=>{r.componentGoal(e,S,{reward:x}),r.goal(S,{metadata:{componentId:e,arm:m},weight:x,stepIndex:A})}},p)},[r,e,f,m,s]);let c=gt(()=>{let u={"data-sentient-slot":e};for(let[p,g]of Object.entries(y))u[`data-${p}`]=g;return u},[e,y]);return{tokens:y,props:c}}import{useCallback as Qr,useEffect as ei,useMemo as ti}from"react";var En=new Set;function ni(e,t){var R;if(G()&&!t.goal)throw new Error(`[sentient] useAdaptive("${e}"): a goal is required \u2014 without one the optimizer accumulates exposures with no rewards and cannot learn. Pass e.g. goal: 'buy_click'.`);let{client:n,variantIds:r,variantId:i,isOverride:l,goalLabel:d,ref:o,nodeRef:m}=_e(e,t.variants,{goal:t.goal,funnel:t.funnel,microSignalGoals:t.microSignalGoals}),s=(R=i!=null?i:r[0])!=null?R:"",y=t.variants[s];ei(()=>{if(!G()||!n)return;let c=setTimeout(()=>{!m.current&&!En.has(e)&&(En.add(e),console.warn(`[sentient] useAdaptive("${e}"): bind was never attached \u2014 spread {...bind} on the rendered element, otherwise exposure and goal tracking cannot work and the optimizer learns nothing.`))},0);return()=>clearTimeout(c)},[n,e]);let f=Qr((c,u)=>{var g,a;if(l)return;let p=c!=null?c:d;p&&(n==null||n.componentGoal(e,p,u),n==null||n.goal(p,v(v(v({metadata:(g=u==null?void 0:u.metadata)!=null?g:{},weight:(a=u==null?void 0:u.reward)!=null?a:1,stepIndex:0},(u==null?void 0:u.value)!==void 0?{value:u.value}:{}),(u==null?void 0:u.currency)!==void 0?{currency:u.currency}:{}),(u==null?void 0:u.externalId)!==void 0?{externalId:u.externalId}:{})))},[n,e,d,l]),h=ti(()=>({ref:o,"data-sentient-id":e,"data-sentient-variant":s}),[o,e,s]);return{variant:s,value:y,bind:h,fireGoal:f}}import{Children as ri,isValidElement as ii,useEffect as Me,useMemo as Pn,useRef as Gn}from"react";import{jsx as si}from"react/jsx-runtime";var $e=new Set;function oi(e){var g;let t=D(),n=z(),r=Gn(null),i=Object.keys(e.arrangements).join(" "),l=Pn(()=>Object.keys(e.arrangements),[i]),d=Pn(()=>v({id:e.id,arms:l},e.baseline!==void 0?{baseline:e.baseline}:{}),[e.id,l,e.baseline]),{arm:o,source:m}=Ve(e.id,d);G()&&e.baseline!==void 0&&e.baseline!==l[0]&&!$e.has(e.id+":baseline")&&($e.add(e.id+":baseline"),console.warn(`[sentient] <AdaptiveGroup id="${e.id}">: baseline "${e.baseline}" is not the first-declared arrangement ("${l[0]}"). The first arrangement should usually be the page's real incumbent (the holdout sees it).`));let s=ri.toArray(e.children).filter(ii),y=new Map;for(let a of s)y.set(String((g=a.key)!=null?g:"").replace(/^\.\$/,""),a);let f=e.arrangements[o],h=f!==void 0&&f.length===s.length&&f.every(a=>y.has(a));G()&&f!==void 0&&!h&&!$e.has(e.id+":keys")&&($e.add(e.id+":keys"),console.warn(`[sentient] <AdaptiveGroup id="${e.id}">: arrangement "${o}" [${f.join(", ")}] does not match the children's keys \u2014 rendering declaration order (fail-safe).`));let R=h?f.map(a=>y.get(a)):s;Me(()=>ue({id:e.id,arms:Object.keys(e.arrangements)}),[e.id]);let c=Gn(null);Me(()=>{!t||m==="baseline"||m==="seeded"||m==="override"||c.current===o||(c.current=o,ee(t,n,e.id,o))},[t,n,e.id,o,m]);let u=e.funnel;Me(()=>{var a;!t||!u||m==="override"||le(t,n,e.id,u,B((a=e.goal)!=null?a:"click"))},[t,n,e.id,u,m]);let p=e.goal===void 0?null:typeof e.goal=="string"?e.goal:JSON.stringify(e.goal);return Me(()=>{if(!t||e.goal===void 0||m==="override"||m==="baseline"||m==="seeded")return;let a=r.current;if(!a)return;let S=Q(e.goal),x=H(e.goal),A=!1;return X(a,B(e.goal),{fireGoal:()=>{A||(A=!0,x!==void 0?t.componentGoal(e.id,S,{value:x}):t.componentGoal(e.id,S),t.goal(S,v({metadata:{componentId:e.id,arm:o},weight:1,stepIndex:0},x!==void 0?{value:x}:{})))},fireStep:(O,b,k)=>{t.componentGoal(e.id,O,{reward:b}),t.goal(O,{metadata:{componentId:e.id,arm:o},weight:b,stepIndex:k})}},S)},[t,e.id,p,o,m]),si("div",{ref:r,"data-sentient-id":e.id,"data-sentient-variant":o,children:R})}import{deriveSessionSegment as ai}from"@sentientui/core";var li=["page","blocks","layoutOrder"],Tn=new Map;function ui(e,t){Tn.set(e,t)}function Ln(e){return Tn.get(e)}function ci(e){var i,l;let t=(l=(i=e.content)!=null?i:Ln(e.page))!=null?l:{},n={};for(let[d,o]of Object.entries(t))li.includes(d)||(n[d]=o);let r=L(v({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(r.layoutOrder=e.layoutOrder),r}function di(e){return`<script type="application/ld+json">${Dn(e)}</script>`}function Dn(e){return JSON.stringify(v({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function fi(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,r]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(r,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(`
|
|
3
3
|
`).trimEnd()+`
|
|
4
4
|
`}import{grantConsent as sa}from"@sentientui/core";export{Or as Adaptive,oi as AdaptiveGroup,Yn as AdaptiveProvider,Le as AdaptiveSlot,Tr as AdaptiveText,Br as SentientPersonaScript,ci as buildAgentFeed,ui as defineAgentContent,ai as detectSegment,Ln as getAgentContent,sa as grantConsent,di as renderAgentJsonLd,Dn as renderAgentJsonLdBody,fi as renderAgentMarkdown,pe as renderBlocks,nt as renderCompose,ni as useAdaptive,er as useAdaptiveApiBaseUrl,dt as useAdaptiveGoal,Xr as useAdaptivePersona,Yr as useAdaptiveTokens,Qe as useAssignment,Ze as useInitialAssignments,Qn as useLayoutOrder,Vr as usePageGoal,D as useSentient};
|
|
5
5
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -269,7 +269,7 @@ type PreloadComponent = {
|
|
|
269
269
|
id: string;
|
|
270
270
|
variantIds: string[];
|
|
271
271
|
};
|
|
272
|
-
type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onAssignment' | 'initialSlots' | 'initialSlotConfig' | 'initialPalette' | 'initialPersona' | 'initialLayoutOrder' | 'declaredSections' | 'sessionSegment' | 'consentFrom'> & {
|
|
272
|
+
type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onAssignment' | 'initialSlots' | 'initialSlotConfig' | 'initialPalette' | 'initialVocabulary' | 'initialPersona' | 'initialLayoutOrder' | 'declaredSections' | 'sessionSegment' | 'consentFrom'> & {
|
|
273
273
|
/**
|
|
274
274
|
* Cookie-based consent source — see `AdaptiveProviderProps.consentFrom`.
|
|
275
275
|
*
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var ve=Object.defineProperty,Se=Object.defineProperties;var ke=Object.getOwnPropertyDescriptors;var F=Object.getOwnPropertySymbols;var te=Object.prototype.hasOwnProperty,ne=Object.prototype.propertyIsEnumerable;var ee=(e,t,n)=>t in e?ve(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,u=(e,t)=>{for(var n in t||(t={}))te.call(t,n)&&ee(e,n,t[n]);if(F)for(var n of F(t))ne.call(t,n)&&ee(e,n,t[n]);return e},A=(e,t)=>Se(e,ke(t));var se=(e,t)=>{var n={};for(var s in e)te.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&F)for(var s of F(e))t.indexOf(s)<0&&ne.call(e,s)&&(n[s]=e[s]);return n};import{deriveSessionSegment as Ce,extractTrackedParams as Ke,matchedAgentToken as Ue}from"@sentientui/core";import{cookies as _e,headers as Te}from"next/headers";import{renderPrePaintScript as Re}from"@sentientui/core";import{confidenceBand as be}from"@sentientui/policy";import{jsx as Pe}from"react/jsx-runtime";function re(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function Ie(e){return e.persona?'(function(){try{var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",'+re(e.persona.persona)+');d.setAttribute("data-sentient-confidence",'+re(be(e.persona.confidence))+");}catch(e){}})();":Re(e.apiKey)}function oe(e){return Pe("script",{"data-sentient-persona-script":"",nonce:e.nonce,dangerouslySetInnerHTML:{__html:Ie(e)}})}import{preloadAssignments as we,readSessionCookie as Fe}from"@sentientui/core/server";import{preloadDecisions as ze}from"@sentientui/core/server";function ie(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function ae(e,t){var r,o,i;let n=(i=(o=Fe(t.cookies,t.apiKey))!=null?o:(r=t.createSessionId)==null?void 0:r.call(t))!=null?i:ie();return{assignments:await we(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,origin:t.origin,userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,clickIds:t.clickIds,doNotTrack:t.doNotTrack,timeoutMs:t.timeoutMs,persona:t.persona}),sessionId:n}}async function ce(e){var i,l,v,S,p,I,k,P,a,g;let{preloadDecisions:t,readSessionCookie:n}=await import("@sentientui/core/server"),s=(v=(l=n(e.cookies,e.apiKey))!=null?l:(i=e.createSessionId)==null?void 0:i.call(e))!=null?v:ie();if(!(typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"))){let m={layoutOrder:(S=e.sections)!=null?S:[],assignments:{},slots:{},persona:"unknown",confidence:0,sessionId:s};try{let f=await import("@sentientui/core/local");if(!f.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."),m;let c=f.createLocalEngine({sessionId:s}).decide({sections:e.sections,components:(p=e.components)!=null?p:[],slots:(I=e.slots)!=null?I:[]});return{layoutOrder:(P=(k=c.layoutOrder)!=null?k:e.sections)!=null?P:[],assignments:c.assignments,slots:c.slots,persona:c.persona,confidence:c.confidence,sessionId:s}}catch(f){return m}}let o=await t({sections:e.sections,components:(a=e.components)!=null?a:[],slots:(g=e.slots)!=null?g:[],slotsFrom:e.slotsFrom,registrySlotIds:e.registrySlotIds},s,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,clickIds:e.clickIds,doNotTrack:e.doNotTrack,timeoutMs:e.timeoutMs,persona:e.persona});return A(u({},o),{sessionId:s})}import{AdaptiveRootClient as Be}from"./adaptive-root-client.js";var Le=["page","blocks","layoutOrder"],de=new Map;function Oe(e,t){de.set(e,t)}function xe(e){return de.get(e)}function D(e){var r,o;let t=(o=(r=e.content)!=null?r:xe(e.page))!=null?o:{},n={};for(let[i,l]of Object.entries(t))Le.includes(i)||(n[i]=l);let s=A(u({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(s.layoutOrder=e.layoutOrder),s}function le(e){return JSON.stringify(u({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function ge(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
|
|
3
|
+
`}function pe(e,t={}){var s,r;let n=(s=t.fetchImpl)!=null?s:fetch;try{n(`${e.baseUrl}/crawler-events`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({path:e.path,botName:e.botName,userAgent:(r=e.userAgent)!=null?r:null,source:"ssr"})}).catch(()=>{})}catch(o){}}import{matchedAgentToken as Ne}from"@sentientui/core";function De(e,t){return e.pathname.endsWith(".md")||t.toLowerCase().includes("text/markdown")}function Ee(e){return async t=>{var l;let n=new URL(t.url),s=(l=t.headers.get("accept"))!=null?l:"",r=t.headers.get("user-agent"),o=n.pathname.replace(/\.(md|json)$/,"");if(e.onRead)try{Promise.resolve(e.onRead({path:o,userAgent:r,botName:Ne(r!=null?r:"")})).catch(()=>{})}catch(v){}let i=await e.getFeed(t);return De(n,s)?new Response(ge(i),{headers:{"content-type":"text/markdown; charset=utf-8"}}):new Response(JSON.stringify(i),{headers:{"content-type":"application/json; charset=utf-8"}})}}import{matchedAgentToken as At,uaTokenMatch as yt,agentIntent as ht,classifiedAgents as vt}from"@sentientui/core";import{Fragment as ue,jsx as E,jsxs as me}from"react/jsx-runtime";var Me="https://api.sentient-ui.com/v1";function Je(e){return Object.entries(e).map(([t,n])=>{var s;return{id:t,variant:typeof n=="string"?n:(s=n==null?void 0:n.variantId)!=null?s:""}})}async function gt(e){var q,H,W,G,z,Y,Q,Z;let X=e,{components:t=[],sections:n,slots:s,registrySlotIds:r,appOrigin:o,searchParams:i,initialAssignments:l,ssrSessionId:v,timeoutMs:S,agentFeed:p,captureAgents:I,nonce:k,children:P}=X,a=se(X,["components","sections","slots","registrySlotIds","appOrigin","searchParams","initialAssignments","ssrSessionId","timeoutMs","agentFeed","captureAgents","nonce","children"]),g=await Te(),m=g.get("host");!o&&process.env.NODE_ENV==="production"&&!m&&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 f=o!=null?o:process.env.NODE_ENV==="production"?`https://${m!=null?m:"localhost"}`:"http://localhost:3001",c=(q=g.get("user-agent"))!=null?q:void 0,L=(H=g.get("referer"))!=null?H:void 0,{utmParams:C,clickIds:K}=Ke(i!=null?i:{}),fe=g.get("dnt")==="1"||g.get("sec-gpc")==="1",Ae=Ce({userAgent:c,referer:L,appOrigin:f}),O=await _e(),y=a.consentFrom,x=(z=a.consent)!=null?z:y!=null&&y.cookie?((W=O.get(y.cookie))==null?void 0:W.value)===((G=y.value)!=null?G:"accepted"):void 0,ye=fe||x===!1||y!=null&&x!==!0,N=a.apiBaseUrl?a.apiBaseUrl.replace(/\/$/,""):Me,U=(Q=(Y=p==null?void 0:p.path)!=null?Y:g.get("x-pathname"))!=null?Q:"/",_=Ue(c!=null?c:"");I!==!1&&_&&pe({baseUrl:N,apiKey:a.apiKey,path:U,botName:_,userAgent:c});let h,R=null,T,B,M,J,b=null,w,j=!!(r!=null&&r.length);if(l)h=l,w=v;else if(ye)h={};else if(n&&n.length>0||s&&s.length>0||j){let d=await ce(A(u({sections:n!=null?n:[],components:t,slots:s},j?{slotsFrom:"registry",registrySlotIds:r}:{}),{cookies:O,apiKey:a.apiKey,baseUrl:N,origin:f,userAgent:c,referer:L,utmParams:C,clickIds:K,timeoutMs:S,persona:a.persona}));h=d.assignments,R=d.layoutOrder,T=d.slots,B=d.slotConfig,M=d.palette,J=d.vocabulary,b=d.persona!==void 0?{persona:d.persona,confidence:(Z=d.confidence)!=null?Z:0}:null,w=d.sessionId}else{let d=await ae(t,{cookies:O,apiKey:a.apiKey,baseUrl:N,origin:f,userAgent:c,referer:L,utmParams:C,clickIds:K,timeoutMs:S,persona:a.persona});h=d.assignments,w=d.sessionId}let $=E(oe,{apiKey:a.apiKey,persona:b,nonce:k}),V=E(Be,A(u({},a),{consent:x,initialAssignments:h,initialLayoutOrder:R,declaredSections:n,initialSlots:T,initialSlotConfig:B,initialPalette:M,initialVocabulary:J,initialPersona:b!=null?b:void 0,sessionSegment:Ae,ssrSessionId:w,children:P}));if(!p)return me(ue,{children:[$,V]});let he=D({page:U,blocks:Je(h),layoutOrder:R!=null?R:void 0,content:p.content});return me(ue,{children:[$,E("script",{type:"application/ld+json",nonce:k,dangerouslySetInnerHTML:{__html:le(he)}}),V]})}export{gt as AdaptiveRoot,ht as agentIntent,D as buildAgentFeedFor,vt as classifiedAgents,Ee as createAgentFeed,Oe as defineAgentContent,At as matchedAgentToken,yt 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, extractTrackedParams, matchedAgentToken } from '@sentientui/core';\nimport type { SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX, ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type LoadAdaptiveDecisionResult,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\n// Re-exported from core on the SERVER entry (this module is server-only — it\n// imports next/headers). Lets server components do agent detection with just the\n// `@sentientui/react` package, no direct core dependency. Do NOT add this to the\n// package's client index: re-exporting a plain function through a 'use client'\n// module turns it into a client reference that throws when called during SSR.\nexport { matchedAgentToken, uaTokenMatch, agentIntent, classifiedAgents } from '@sentientui/core';\nexport type { AgentIntent } from '@sentientui/core';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\nexport type AdaptiveRootProps = Omit<\n AdaptiveProviderProps,\n // Every provider prop AdaptiveRoot itself resolves and passes AFTER the\n // {...providerProps} spread must be omitted here: a caller-supplied value\n // would typecheck but be silently clobbered by the spread order\n // (initialLayoutOrder, declaredSections and sessionSegment were missing\n // from this list and suffered exactly that).\n | 'initialAssignments'\n | 'onAssignment'\n | 'initialSlots'\n | 'initialSlotConfig'\n | 'initialPalette'\n | 'initialPersona'\n | 'initialLayoutOrder'\n | 'declaredSections'\n | 'sessionSegment'\n | 'consentFrom'\n> & {\n /**\n * Cookie-based consent source — see `AdaptiveProviderProps.consentFrom`.\n *\n * Narrowed to the cookie 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?: Omit<NonNullable<AdaptiveProviderProps['consentFrom']>, 'check'>;\n /**\n * Code-variant components to assign server-side (SEO-safe). Optional — an\n * `<Adaptive>` works without an entry here and assigns after mount.\n *\n * List only ids this tree actually renders. Each one is assigned on every\n * request, rendered or not, and every assignment logs an impression (or a\n * holdout exposure). An id the page never renders therefore accrues trials\n * that cannot convert, and in a root layout that happens on every route.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * Give each section's rendered element `data-sentient-id=\"<sectionId>\"` —\n * the only markup a section needs — so the DOM graph scanner can register\n * it under the same id. Without it the server never learns what the section\n * IS, types it `generic`, and serves the identity order to every persona —\n * the integration looks live but cannot personalize. The provider warns\n * about unresolvable ids in development. Correct a section the content\n * classifier mistypes with `sectionTypes`, not extra markup.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n * // …and in the tree: <section data-sentient-id=\"pricing\">\n */\n sections?: string[];\n /**\n * Adaptive-slot declarations used by `useAdaptiveTokens` / `AdaptiveGroup`\n * in this tree. Declaring them here decides them in the same SSR\n * round trip, so their values serialize into the server HTML.\n */\n slots?: SlotDeclInput[];\n /**\n * The generated-mode `<Adaptive id>`s THIS page renders. Declaring them\n * decides their published versions in the same SSR round trip\n * (`/v1/decide` registry mode) and serializes the served content into the\n * server HTML, so the first paint shows the version rather than the\n * original children until the client-side decide answers. Without it a\n * registry slot renders its children first and swaps after mount.\n *\n * Scoped to exactly these ids on purpose: an unscoped registry decide\n * records a close-out trial for every published slot on every page.\n *\n * @example registrySlotIds={['hero-headline', 'pricing-cta']}\n */\n registrySlotIds?: string[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /**\n * The page's `searchParams` prop (or an equivalent query string /\n * URLSearchParams). Server Components cannot read the request URL from\n * `headers()`, so without this the SSR-minted session carries no `utm_*`\n * params and no ad click IDs (gclid, fbclid, ttclid, …) — campaign\n * attribution only lands after client hydration, and never for visits the\n * client SDK doesn't get to finish (bounce before hydrate). Pass it on\n * landing pages that receive ad traffic:\n *\n * ```tsx\n * export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {\n * return <AdaptiveRoot ... searchParams={await searchParams}>...</AdaptiveRoot>;\n * }\n * ```\n */\n searchParams?: Record<string, string | string[] | undefined> | URLSearchParams | string;\n /** Override: when set no network fetch is made. Useful for tests. */\n initialAssignments?: ServerAssignments;\n /**\n * Milliseconds to wait for the API before rendering default variants.\n * Defaults to 1000. The hot path typically returns in well under 150 ms;\n * the full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host. Lower it if your API is\n * co-located and warm.\n */\n timeoutMs?: number;\n /**\n * When set, AdaptiveRoot emits a server-rendered inline JSON-LD block\n * describing the page's winning variants, layout order, and developer-supplied\n * content — readable by passive AI crawlers (which do not run JS). Invisible to\n * humans (a JSON-LD script renders no visible DOM). Omit to emit nothing.\n */\n agentFeed?: {\n /** Page path for the feed. Falls back to the `x-pathname` request header, then '/'. */\n path?: string;\n /** Structured page content. Falls back to the `defineAgentContent` registry for this path. */\n content?: Record<string, unknown>;\n };\n /**\n * When true (default), a known AI-agent fetch (matched by user-agent —\n * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side\n * to your agent analytics. Machine telemetry only (no cookie, no session);\n * fire-and-forget, never affects render. Set false to opt out.\n */\n captureAgents?: boolean;\n /**\n * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.\n * Pass through from Next.js middleware / `headers()` when using a strict CSP.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout. Declared on the page (not the root\n * // layout) because hero_cta renders only here; see the `components` prop.\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components = [],\n sections,\n slots,\n registrySlotIds,\n appOrigin,\n searchParams,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n captureAgents,\n nonce,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Landing-URL attribution (utm_* + ad click IDs). Only available when the\n // page passes its searchParams down — headers() never carries the request's\n // own query string, and the Referer is the PREVIOUS page, not this one.\n const { utmParams, clickIds } = extractTrackedParams(searchParams ?? {});\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `consent: false` must gate the SERVER too, not just the client. Without\n // this the SSR decide/assign still ran and still minted a session row for a\n // visitor who had not consented — contradicting the documented contract\n // (\"no SDK is initialised, no cookies are written, no events are sent\") and\n // forcing sites to hide AdaptiveRoot behind a conditional render, which is\n // what made consent-after-load cost a full server round trip.\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n // This is a Server Component and already has the request cookies, so resolve\n // a cookie-based `consentFrom` here rather than making the app read the same\n // cookie again just to pass `consent` — naming it twice only invites drift.\n // An already-consented visitor therefore gets SSR variant assignment (zero\n // layout shift) with no extra code.\n //\n // An explicit `consent` prop always wins — it is the escape hatch for apps\n // that track consent elsewhere. (No `check()` form here: see the prop type.)\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n const consent =\n providerProps.consent ??\n (cf?.cookie\n ? cookieStore.get(cf.cookie)?.value === (cf.value ?? 'accepted')\n : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n\n // SSR preload MUST hit the same API host the client will use, otherwise the\n // SSR-minted session lives on the wrong host and the client's first /assign\n // misses it and re-mints — silently breaking SSR→client continuity for any\n // non-default / self-hosted deployment. The client derives its base from\n // apiBaseUrl too (see provider.tsx), so thread the same value here.\n const baseUrl = providerProps.apiBaseUrl\n ? providerProps.apiBaseUrl.replace(/\\/$/, '')\n : DEFAULT_API_BASE_URL;\n\n // Server-side agent-fetch capture (spec: nextjs-agent-fetch-capture). JS-less\n // assistants (GPTBot / ChatGPT-User / Claude-User / PerplexityBot / …) never\n // run client JS, but they trigger SSR — so AdaptiveRoot sees their UA here.\n // Fire-and-forget; never blocks or breaks render. `agentPath` is reused by the\n // agentFeed JSON-LD below.\n const agentPath = agentFeed?.path ?? headerStore.get('x-pathname') ?? '/';\n const agentBot = matchedAgentToken(userAgent ?? '');\n if (captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialSlotConfig: LoadAdaptiveDecisionResult['slotConfig'];\n let initialPalette: LoadAdaptiveDecisionResult['palette'];\n let initialPersona: { persona: string; confidence: number } | null = null;\n let ssrSessionId: string | undefined;\n\n // Registry mode only when ids were declared: an unscoped registry decide\n // records a close-out trial for every published slot on every page.\n const registry = !!registrySlotIds?.length;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (skipSsr) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0) || registry) {\n // `loadAdaptiveDecision` accepted `registrySlotIds` long before AdaptiveRoot\n // passed them, so an `<Adaptive id>` under AdaptiveRoot showed its original\n // children on first paint until the client-side decide returned.\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n ...(registry ? { slotsFrom: 'registry' as const, registrySlotIds } : {}),\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialSlotConfig = decision.slotConfig;\n initialPalette = decision.palette;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n const personaScript = (\n <SentientPersonaScript apiKey={providerProps.apiKey} persona={initialPersona} nonce={nonce} />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // Forward the server-resolved value so a consented visitor's client does\n // not start gated and re-resolve the same cookie on mount.\n consent={consent}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n // Declared regardless of what came back, so devtools can preview layout on\n // a page whose decision was gated or timed out.\n declaredSections={sections}\n initialSlots={initialSlots}\n // 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 initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) {\n return (\n <>\n {personaScript}\n {client}\n </>\n );\n }\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const feed = buildAgentFeed({\n page: agentPath,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX } from 'react';\nimport { renderPrePaintScript } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element {\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\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 /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"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","names":["deriveSessionSegment","extractTrackedParams","matchedAgentToken","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","_i","components","sections","slots","registrySlotIds","appOrigin","searchParams","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","utmParams","clickIds","extractTrackedParams","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","skipSsr","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialLayoutOrder","initialSlots","initialSlotConfig","initialPalette","initialPersona","ssrSessionId","registry","decision","loadAdaptiveDecision","__spreadProps","__spreadValues","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","feed","buildAgentFeed","renderAgentJsonLdBody"]}
|
|
1
|
+
{"version":3,"sources":["../../src/next/adaptive-root.tsx","../../src/persona-script.tsx","../../src/server.ts","../../src/agent-feed.ts","../../src/next/log-agent-fetch.ts","../../src/next/agent-feed-route.ts"],"sourcesContent":["import { deriveSessionSegment, extractTrackedParams, matchedAgentToken } from '@sentientui/core';\nimport type { SlotDeclInput, SlotResult } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX, ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport { SentientPersonaScript } from '../persona-script.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type LoadAdaptiveDecisionResult,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\nimport { logAgentFetch } from './log-agent-fetch.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\n// Re-exported from core on the SERVER entry (this module is server-only — it\n// imports next/headers). Lets server components do agent detection with just the\n// `@sentientui/react` package, no direct core dependency. Do NOT add this to the\n// package's client index: re-exporting a plain function through a 'use client'\n// module turns it into a client reference that throws when called during SSR.\nexport { matchedAgentToken, uaTokenMatch, agentIntent, classifiedAgents } from '@sentientui/core';\nexport type { AgentIntent } from '@sentientui/core';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\nexport type AdaptiveRootProps = Omit<\n AdaptiveProviderProps,\n // Every provider prop AdaptiveRoot itself resolves and passes AFTER the\n // {...providerProps} spread must be omitted here: a caller-supplied value\n // would typecheck but be silently clobbered by the spread order\n // (initialLayoutOrder, declaredSections and sessionSegment were missing\n // from this list and suffered exactly that).\n | 'initialAssignments'\n | 'onAssignment'\n | 'initialSlots'\n | 'initialSlotConfig'\n | 'initialPalette'\n | 'initialVocabulary'\n | 'initialPersona'\n | 'initialLayoutOrder'\n | 'declaredSections'\n | 'sessionSegment'\n | 'consentFrom'\n> & {\n /**\n * Cookie-based consent source — see `AdaptiveProviderProps.consentFrom`.\n *\n * Narrowed to the cookie 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?: Omit<NonNullable<AdaptiveProviderProps['consentFrom']>, 'check'>;\n /**\n * Code-variant components to assign server-side (SEO-safe). Optional — an\n * `<Adaptive>` works without an entry here and assigns after mount.\n *\n * List only ids this tree actually renders. Each one is assigned on every\n * request, rendered or not, and every assignment logs an impression (or a\n * holdout exposure). An id the page never renders therefore accrues trials\n * that cannot convert, and in a root layout that happens on every route.\n */\n components?: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * Give each section's rendered element `data-sentient-id=\"<sectionId>\"` —\n * the only markup a section needs — so the DOM graph scanner can register\n * it under the same id. Without it the server never learns what the section\n * IS, types it `generic`, and serves the identity order to every persona —\n * the integration looks live but cannot personalize. The provider warns\n * about unresolvable ids in development. Correct a section the content\n * classifier mistypes with `sectionTypes`, not extra markup.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n * // …and in the tree: <section data-sentient-id=\"pricing\">\n */\n sections?: string[];\n /**\n * Adaptive-slot declarations used by `useAdaptiveTokens` / `AdaptiveGroup`\n * in this tree. Declaring them here decides them in the same SSR\n * round trip, so their values serialize into the server HTML.\n */\n slots?: SlotDeclInput[];\n /**\n * The generated-mode `<Adaptive id>`s THIS page renders. Declaring them\n * decides their published versions in the same SSR round trip\n * (`/v1/decide` registry mode) and serializes the served content into the\n * server HTML, so the first paint shows the version rather than the\n * original children until the client-side decide answers. Without it a\n * registry slot renders its children first and swaps after mount.\n *\n * Scoped to exactly these ids on purpose: an unscoped registry decide\n * records a close-out trial for every published slot on every page.\n *\n * @example registrySlotIds={['hero-headline', 'pricing-cta']}\n */\n registrySlotIds?: string[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /**\n * The page's `searchParams` prop (or an equivalent query string /\n * URLSearchParams). Server Components cannot read the request URL from\n * `headers()`, so without this the SSR-minted session carries no `utm_*`\n * params and no ad click IDs (gclid, fbclid, ttclid, …) — campaign\n * attribution only lands after client hydration, and never for visits the\n * client SDK doesn't get to finish (bounce before hydrate). Pass it on\n * landing pages that receive ad traffic:\n *\n * ```tsx\n * export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {\n * return <AdaptiveRoot ... searchParams={await searchParams}>...</AdaptiveRoot>;\n * }\n * ```\n */\n searchParams?: Record<string, string | string[] | undefined> | URLSearchParams | string;\n /** Override: when set no network fetch is made. Useful for tests. */\n initialAssignments?: ServerAssignments;\n /**\n * Milliseconds to wait for the API before rendering default variants.\n * Defaults to 1000. The hot path typically returns in well under 150 ms;\n * the full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host. Lower it if your API is\n * co-located and warm.\n */\n timeoutMs?: number;\n /**\n * When set, AdaptiveRoot emits a server-rendered inline JSON-LD block\n * describing the page's winning variants, layout order, and developer-supplied\n * content — readable by passive AI crawlers (which do not run JS). Invisible to\n * humans (a JSON-LD script renders no visible DOM). Omit to emit nothing.\n */\n agentFeed?: {\n /** Page path for the feed. Falls back to the `x-pathname` request header, then '/'. */\n path?: string;\n /** Structured page content. Falls back to the `defineAgentContent` registry for this path. */\n content?: Record<string, unknown>;\n };\n /**\n * When true (default), a known AI-agent fetch (matched by user-agent —\n * GPTBot, ChatGPT-User, Claude-User, PerplexityBot, …) is logged server-side\n * to your agent analytics. Machine telemetry only (no cookie, no session);\n * fire-and-forget, never affects render. Set false to opt out.\n */\n captureAgents?: boolean;\n /**\n * CSP nonce for the inline persona (and optional agent JSON-LD) scripts.\n * Pass through from Next.js middleware / `headers()` when using a strict CSP.\n */\n nonce?: string;\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout. Declared on the page (not the root\n * // layout) because hero_cta renders only here; see the `components` prop.\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components = [],\n sections,\n slots,\n registrySlotIds,\n appOrigin,\n searchParams,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n captureAgents,\n nonce,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n // Landing-URL attribution (utm_* + ad click IDs). Only available when the\n // page passes its searchParams down — headers() never carries the request's\n // own query string, and the Referer is the PREVIOUS page, not this one.\n const { utmParams, clickIds } = extractTrackedParams(searchParams ?? {});\n // Honor a tracking opt-out at SSR: `DNT: 1` or the legally-enforceable\n // `Sec-GPC: 1`. When set we skip the session upsert + assign/decide so no\n // session row is minted for the visitor (audit P4) — matching the client SDK,\n // which already no-ops for these signals.\n const doNotTrack = headerStore.get('dnt') === '1' || headerStore.get('sec-gpc') === '1';\n // `consent: false` must gate the SERVER too, not just the client. Without\n // this the SSR decide/assign still ran and still minted a session row for a\n // visitor who had not consented — contradicting the documented contract\n // (\"no SDK is initialised, no cookies are written, no events are sent\") and\n // forcing sites to hide AdaptiveRoot behind a conditional render, which is\n // what made consent-after-load cost a full server round trip.\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n // This is a Server Component and already has the request cookies, so resolve\n // a cookie-based `consentFrom` here rather than making the app read the same\n // cookie again just to pass `consent` — naming it twice only invites drift.\n // An already-consented visitor therefore gets SSR variant assignment (zero\n // layout shift) with no extra code.\n //\n // An explicit `consent` prop always wins — it is the escape hatch for apps\n // that track consent elsewhere. (No `check()` form here: see the prop type.)\n //\n // Consent gates the SERVER too, not just the client: without it the SSR\n // decide/assign still ran and still minted a session row for a visitor who\n // had not consented, contradicting the documented contract (\"no SDK is\n // initialised, no cookies are written, no events are sent\").\n const cf = providerProps.consentFrom;\n const consent =\n providerProps.consent ??\n (cf?.cookie\n ? cookieStore.get(cf.cookie)?.value === (cf.value ?? 'accepted')\n : undefined);\n const skipSsr = doNotTrack || consent === false || (cf != null && consent !== true);\n\n // SSR preload MUST hit the same API host the client will use, otherwise the\n // SSR-minted session lives on the wrong host and the client's first /assign\n // misses it and re-mints — silently breaking SSR→client continuity for any\n // non-default / self-hosted deployment. The client derives its base from\n // apiBaseUrl too (see provider.tsx), so thread the same value here.\n const baseUrl = providerProps.apiBaseUrl\n ? providerProps.apiBaseUrl.replace(/\\/$/, '')\n : DEFAULT_API_BASE_URL;\n\n // Server-side agent-fetch capture (spec: nextjs-agent-fetch-capture). JS-less\n // assistants (GPTBot / ChatGPT-User / Claude-User / PerplexityBot / …) never\n // run client JS, but they trigger SSR — so AdaptiveRoot sees their UA here.\n // Fire-and-forget; never blocks or breaks render. `agentPath` is reused by the\n // agentFeed JSON-LD below.\n const agentPath = agentFeed?.path ?? headerStore.get('x-pathname') ?? '/';\n const agentBot = matchedAgentToken(userAgent ?? '');\n if (captureAgents !== false && agentBot) {\n logAgentFetch({ baseUrl, apiKey: providerProps.apiKey, path: agentPath, botName: agentBot, userAgent });\n }\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let initialSlots: Record<string, SlotResult> | undefined;\n let initialSlotConfig: LoadAdaptiveDecisionResult['slotConfig'];\n let initialPalette: LoadAdaptiveDecisionResult['palette'];\n let initialVocabulary: LoadAdaptiveDecisionResult['vocabulary'];\n let initialPersona: { persona: string; confidence: number } | null = null;\n let ssrSessionId: string | undefined;\n\n // Registry mode only when ids were declared: an unscoped registry decide\n // records a close-out trial for every published slot on every page.\n const registry = !!registrySlotIds?.length;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (skipSsr) {\n // Nothing server-side: no decide, no assign, no session. Components fall\n // back to `ssrFallback`, and the client starts only if the visitor later\n // consents — via the `consent` prop or grantConsent(), neither of which\n // needs a page reload.\n initialAssignments = {};\n } else if ((sections && sections.length > 0) || (slots && slots.length > 0) || registry) {\n // `loadAdaptiveDecision` accepted `registrySlotIds` long before AdaptiveRoot\n // passed them, so an `<Adaptive id>` under AdaptiveRoot showed its original\n // children on first paint until the client-side decide returned.\n const decision = await loadAdaptiveDecision({\n sections: sections ?? [],\n components,\n slots,\n ...(registry ? { slotsFrom: 'registry' as const, registrySlotIds } : {}),\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n initialSlots = decision.slots;\n initialSlotConfig = decision.slotConfig;\n initialPalette = decision.palette;\n // The site styles the served Redesign trees borrow. Without forwarding\n // them, SSR sites (Bodyshop, 2026-09-24) rendered an approved redesign\n // with no site classes at all — black palette buttons and near-invisible\n // text on a navy card — because the client never re-decides a preloaded\n // slot and so never receives them either.\n initialVocabulary = decision.vocabulary;\n initialPersona =\n decision.persona !== undefined\n ? { persona: decision.persona, confidence: decision.confidence ?? 0 }\n : null;\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl,\n origin: resolvedOrigin,\n userAgent,\n referer,\n utmParams,\n clickIds,\n // doNotTrack is deliberately not passed: it is necessarily false on this\n // branch — a DNT/GPC or consent-gated request already took the skipSsr\n // arm above and never reaches this loader.\n timeoutMs,\n persona: providerProps.persona,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n // Single-writer inline script — ALWAYS the first child, before any markup\n // that CSS keyed on the persona attributes could style.\n const personaScript = (\n <SentientPersonaScript apiKey={providerProps.apiKey} persona={initialPersona} nonce={nonce} />\n );\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n // Forward the server-resolved value so a consented visitor's client does\n // not start gated and re-resolve the same cookie on mount.\n consent={consent}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n // Declared regardless of what came back, so devtools can preview layout on\n // a page whose decision was gated or timed out.\n declaredSections={sections}\n initialSlots={initialSlots}\n // Registry-mode preload: the hook treats a preloaded slot config as\n // settled, so the client does not decide the same slot a second time.\n initialSlotConfig={initialSlotConfig}\n initialPalette={initialPalette}\n initialVocabulary={initialVocabulary}\n initialPersona={initialPersona ?? undefined}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) {\n return (\n <>\n {personaScript}\n {client}\n </>\n );\n }\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const feed = buildAgentFeed({\n page: agentPath,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n {personaScript}\n <script\n type=\"application/ld+json\"\n nonce={nonce}\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport type { JSX } from 'react';\nimport { renderPrePaintScript } from '@sentientui/core';\nimport { confidenceBand } from '@sentientui/policy';\n\nexport type SentientPersonaScriptProps = {\n /** Publishable API key — selects the localStorage snapshot in the fallback path. */\n apiKey: string;\n /**\n * CSP nonce for the inline pre-paint script. Pass the same nonce your\n * `Content-Security-Policy` `script-src` allows (e.g. from Next.js middleware).\n * Required for strict CSP deployments that block `'unsafe-inline'`.\n */\n nonce?: string;\n /**\n * SSR-decided persona (from `loadAdaptiveDecision`). When present the\n * script embeds the literal values; when absent it reads the local\n * decision snapshot (SPA / return-visit path).\n */\n persona?: { persona: string; confidence: number } | null;\n};\n\n/** JSON string literal that is also safe inside an inline <script> element. */\nfunction inlineJsString(value: string): string {\n return JSON.stringify(value).replace(/</g, '\\\\u003c');\n}\n\n/** Exported for tests. Builds the inline JS (concatenation only — no backticks). */\nexport function personaScriptBody(props: SentientPersonaScriptProps): string {\n if (props.persona) {\n return (\n '(function(){try{var d=document.documentElement;' +\n 'if(d.hasAttribute(\"data-sentient-persona\"))return;' +\n 'd.setAttribute(\"data-sentient-persona\",' + inlineJsString(props.persona.persona) + ');' +\n 'd.setAttribute(\"data-sentient-confidence\",' + inlineJsString(confidenceBand(props.persona.confidence)) + ');' +\n '}catch(e){}})();'\n );\n }\n return renderPrePaintScript(props.apiKey);\n}\n\n/**\n * Single writer of the Rung-1a `<html>` attributes\n * (`data-sentient-persona`, `data-sentient-confidence`), executed pre-paint.\n *\n * `AdaptiveRoot` renders this automatically as its first child. For Pages\n * Router / Remix, render it yourself in `_document` / the root layout.\n *\n * IMPORTANT (install docs): add `suppressHydrationWarning` to your `<html>`\n * element — this script mutates documentElement before React hydrates it\n * (the same pattern next-themes uses). The client SDK adopts the attributes\n * as truth and never rewrites them mid-session.\n */\nexport function SentientPersonaScript(props: SentientPersonaScriptProps): JSX.Element {\n return (\n <script\n data-sentient-persona-script=\"\"\n nonce={props.nonce}\n dangerouslySetInnerHTML={{ __html: personaScriptBody(props) }}\n />\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /**\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 /** Set true when the request carries `DNT: 1` or `Sec-GPC: 1` — skips the SSR session upsert + assignment so no session is minted for an opted-out visitor (audit P4). `AdaptiveRoot` sets this automatically from the request headers. */\n doNotTrack?: boolean;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1000 (typical decide is well under 150 ms; the full budget is only reached on a cold start or a distant API). */\n timeoutMs?: number;\n /**\n * Declared persona — the role your app already knows for this visitor (e.g.\n * from your auth context: 'admin', 'evaluator'). Must be a key in the\n * project's persona vocabulary; unrecognized values are ignored server-side.\n * Never a user id or email.\n */\n persona?: string;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n // apiKey is not optional here: the client writes the per-project suffixed\n // cookie, so an un-keyed read missed every returning visitor and minted a\n // fresh orphan session per SSR request (see readSessionCookie in core).\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult, SlotDeclInput, SlotResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /**\n * Section IDs in default order. Passed to /v1/decide as the candidate\n * layout. Optional since 0.13.0 — slot-only pages may omit it (at least\n * one of `sections`/`components`/`slots` must be non-empty).\n */\n sections?: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n /** Adaptive-slot declarations (useAdaptiveTokens / AdaptiveGroup) to decide server-side. */\n slots?: import('@sentientui/core/server').SlotDeclInput[];\n /** 'registry' serves the project's published slot definitions (`<Adaptive id>`)\n * and is the only way `slotConfig`/`palette` come back. Default 'request'.\n * Requires `registrySlotIds`. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: the `<Adaptive id>`s THIS page renders — the decide is\n * scoped to exactly these. Required with `slotsFrom: 'registry'`; without it\n * the call downgrades to request mode (with a console.error) instead of\n * recording a close-out trial for every published slot on every page.\n */\n registrySlotIds?: string[];\n};\n\n/**\n * SSR helper for pages with a declared section layout and/or adaptive slots.\n * Calls `/v1/decide` instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n *\n * Keyless: with no valid `pk_` key this never fetches (no timeout burn).\n * Under the `development` export condition the decision is computed by the\n * deterministic local engine with the same sessionId the client will adopt —\n * server and client agree by construction. In production the engine resolves\n * to a stub and defaults are returned with one console.error.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n // Keyed read — the client's cookie name is suffixed per project (see\n // loadAdaptiveAssignments above). Works for keyless too: with no pk_ key the\n // client writes the bare legacy name, which the un-suffixed read falls back to.\n const sessionId =\n readSessionCookie(options.cookies, options.apiKey) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const keyValid = typeof options.apiKey === 'string' && options.apiKey.startsWith('pk_');\n if (!keyValid) {\n const fallback: LoadAdaptiveDecisionResult = {\n layoutOrder: options.sections ?? [],\n assignments: {},\n slots: {},\n persona: 'unknown',\n confidence: 0,\n sessionId,\n };\n try {\n const mod = (await import('@sentientui/core/local')) as unknown as {\n LOCAL_ENGINE_AVAILABLE: boolean;\n createLocalEngine(opts: { sessionId: string }): {\n decide(input: {\n sections?: string[];\n components?: Array<{ id: string; variantIds?: string[] }>;\n slots?: LoadAdaptiveDecisionOptions['slots'];\n }): {\n layoutOrder: string[] | null;\n assignments: Record<string, string>;\n slots: Record<string, string | Record<string, string>>;\n persona: string;\n confidence: number;\n };\n };\n };\n if (!mod.LOCAL_ENGINE_AVAILABLE) {\n // Pinned message — must byte-match PROD_KEYLESS_ERROR in @sentientui/core.\n console.error(\n '[sentient] No API key configured — nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.',\n );\n return fallback;\n }\n const outcome = mod.createLocalEngine({ sessionId }).decide({\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n });\n return {\n layoutOrder: outcome.layoutOrder ?? options.sections ?? [],\n assignments: outcome.assignments,\n slots: outcome.slots,\n persona: outcome.persona,\n confidence: outcome.confidence,\n sessionId,\n };\n } catch {\n return fallback;\n }\n }\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n slots: options.slots ?? [],\n slotsFrom: options.slotsFrom,\n registrySlotIds: options.registrySlotIds,\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n utmParams: options.utmParams,\n clickIds: options.clickIds,\n doNotTrack: options.doNotTrack,\n timeoutMs: options.timeoutMs,\n persona: options.persona,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","// Fire-and-forget server-side log of a known AI-agent fetch to crawler_requests\n// (via POST /v1/crawler-events). Machine telemetry — no cookie, no session.\n// MUST NOT throw or be awaited into the render path.\nexport type AgentFetchLog = {\n baseUrl: string; // API base ending in /v1\n apiKey: string; // public pk_ key\n path: string;\n botName: string;\n userAgent?: string;\n};\n\nexport function logAgentFetch(entry: AgentFetchLog, deps: { fetchImpl?: typeof fetch } = {}): void {\n const doFetch = deps.fetchImpl ?? fetch;\n try {\n void doFetch(`${entry.baseUrl}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${entry.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent ?? null,\n source: 'ssr',\n }),\n }).catch(() => {});\n } catch {\n /* never break render */\n }\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n"],"mappings":"+lBAAA,OAAS,wBAAAA,GAAsB,wBAAAC,GAAsB,qBAAAC,OAAyB,mBAE9E,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCCjC,OAAS,wBAAAC,OAA4B,mBACrC,OAAS,kBAAAC,OAAsB,qBAoD3B,cAAAC,OAAA,oBAhCJ,SAASC,GAAeC,EAAuB,CAC7C,OAAO,KAAK,UAAUA,CAAK,EAAE,QAAQ,KAAM,SAAS,CACtD,CAGO,SAASC,GAAkBC,EAA2C,CAC3E,OAAIA,EAAM,QAEN,2IAE4CH,GAAeG,EAAM,QAAQ,OAAO,EAAI,+CACrCH,GAAeF,GAAeK,EAAM,QAAQ,UAAU,CAAC,EAAI,qBAIvGN,GAAqBM,EAAM,MAAM,CAC1C,CAcO,SAASC,GAAsBD,EAAgD,CACpF,OACEJ,GAAC,UACC,+BAA6B,GAC7B,MAAOI,EAAM,MACb,wBAAyB,CAAE,OAAQD,GAAkBC,CAAK,CAAE,EAC9D,CAEJ,CC3DA,OACE,sBAAAE,GACA,qBAAAC,OAGK,0BAuFP,OAAS,oBAAAC,OAAwB,0BAxCjC,SAASC,IAA2B,CAClC,OAAI,OAAO,QAAW,aAAe,OAAO,OAAO,YAAe,WACzD,OAAO,WAAW,EAEpB,OAAO,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,EAAG,EAAE,CAAC,EACrE,CAOA,eAAsBC,GACpBC,EACAC,EACwC,CAtE1C,IAAAC,EAAAC,EAAAC,EA0EE,IAAMC,GACJD,GAAAD,EAAAG,GAAkBL,EAAQ,QAASA,EAAQ,MAAM,IAAjD,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,GAAiB,EAenB,MAAO,CAAE,YAbW,MAAMS,GAAmBP,EAAYK,EAAW,CAClE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,UAAWA,EAAQ,UACnB,SAAUA,EAAQ,SAClB,WAAYA,EAAQ,WACpB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,CAAC,EAEqB,UAAAI,CAAU,CAClC,CA8CA,eAAsBG,GACpBP,EACqC,CA7IvC,IAAAC,EAAAC,EAAAC,EAAAK,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EA8IE,GAAM,CAAE,iBAAAC,EAAkB,kBAAAV,CAAkB,EAAI,KAAM,QAAO,yBAAyB,EAKhFD,GACJD,GAAAD,EAAAG,EAAkBL,EAAQ,QAASA,EAAQ,MAAM,IAAjD,KAAAE,GACAD,EAAAD,EAAQ,kBAAR,YAAAC,EAAA,KAAAD,KADA,KAAAG,EAEAN,GAAiB,EAGnB,GAAI,EADa,OAAOG,EAAQ,QAAW,UAAYA,EAAQ,OAAO,WAAW,KAAK,GACvE,CACb,IAAMgB,EAAuC,CAC3C,aAAaR,EAAAR,EAAQ,WAAR,KAAAQ,EAAoB,CAAC,EAClC,YAAa,CAAC,EACd,MAAO,CAAC,EACR,QAAS,UACT,WAAY,EACZ,UAAAJ,CACF,EACA,GAAI,CACF,IAAMa,EAAO,KAAM,QAAO,wBAAwB,EAgBlD,GAAI,CAACA,EAAI,uBAEP,eAAQ,MACN,mJACF,EACOD,EAET,IAAME,EAAUD,EAAI,kBAAkB,CAAE,UAAAb,CAAU,CAAC,EAAE,OAAO,CAC1D,SAAUJ,EAAQ,SAClB,YAAYS,EAAAT,EAAQ,aAAR,KAAAS,EAAsB,CAAC,EACnC,OAAOC,EAAAV,EAAQ,QAAR,KAAAU,EAAiB,CAAC,CAC3B,CAAC,EACD,MAAO,CACL,aAAaE,GAAAD,EAAAO,EAAQ,cAAR,KAAAP,EAAuBX,EAAQ,WAA/B,KAAAY,EAA2C,CAAC,EACzD,YAAaM,EAAQ,YACrB,MAAOA,EAAQ,MACf,QAASA,EAAQ,QACjB,WAAYA,EAAQ,WACpB,UAAAd,CACF,CACF,OAAQe,EAAA,CACN,OAAOH,CACT,CACF,CAEA,IAAMI,EAAS,MAAML,EACnB,CACE,SAAUf,EAAQ,SAClB,YAAYa,EAAAb,EAAQ,aAAR,KAAAa,EAAsB,CAAC,EACnC,OAAOC,EAAAd,EAAQ,QAAR,KAAAc,EAAiB,CAAC,EACzB,UAAWd,EAAQ,UACnB,gBAAiBA,EAAQ,eAC3B,EACAI,EACA,CACE,OAAQJ,EAAQ,OAChB,QAASA,EAAQ,QACjB,OAAQA,EAAQ,OAChB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,QACjB,UAAWA,EAAQ,UACnB,SAAUA,EAAQ,SAClB,WAAYA,EAAQ,WACpB,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,CACF,EAEA,OAAOqB,EAAAC,EAAA,GAAKF,GAAL,CAAa,UAAAhB,CAAU,EAChC,CFtNA,OAAS,sBAAAmB,OAA0B,4BGgBnC,IAAMC,GAAkB,CAAC,OAAQ,SAAU,aAAa,EAElDC,GAAW,IAAI,IAMd,SAASC,GAAmBC,EAAcC,EAAwC,CACvFH,GAAS,IAAIE,EAAMC,CAAO,CAC5B,CAGO,SAASC,GAAgBF,EAAmD,CACjF,OAAOF,GAAS,IAAIE,CAAI,CAC1B,CAYO,SAASG,EAAeC,EAKjB,CA9Dd,IAAAC,EAAAC,EA+DE,IAAMC,GAAWD,GAAAD,EAAAD,EAAM,UAAN,KAAAC,EAAiBG,GAAgBJ,EAAM,IAAI,IAA3C,KAAAE,EAAgD,CAAC,EAC5DG,EAAgC,CAAC,EACvC,OAAW,CAACC,EAAGC,CAAC,IAAK,OAAO,QAAQJ,CAAQ,EACpCK,GAAsC,SAASF,CAAC,IAAGD,EAAKC,CAAC,EAAIC,GAErE,IAAME,EAAkBC,EAAAC,EAAA,GACnBN,GADmB,CAEtB,KAAML,EAAM,KACZ,OAAQA,EAAM,MAChB,GACA,OAAIA,EAAM,cAAaS,EAAK,YAAcT,EAAM,aACzCS,CACT,CAgBO,SAASG,GAAsBC,EAAyB,CAC7D,OAAO,KAAK,UAAUC,EAAA,CAAE,WAAY,qBAAsB,QAAS,WAAcD,EAAM,EACpF,QAAQ,KAAM,SAAS,CAC5B,CAGO,SAASE,GAAoBF,EAAyB,CAC3D,IAAMG,EAAkB,CAAC,EACrBH,EAAK,OAAOG,EAAM,KAAK,KAAKH,EAAK,KAAK,GAAI,EAAE,EAC5CA,EAAK,SAASG,EAAM,KAAK,OAAOH,EAAK,OAAO,EAAG,EAAE,EAErD,OAAW,CAACI,EAAGC,CAAC,IAAK,OAAO,QAAQL,CAAI,EAClC,CAAC,OAAQ,QAAS,UAAW,SAAU,aAAa,EAAE,SAASI,CAAC,GACpED,EAAM,KAAK,MAAMC,CAAC,GAAI,GAAI,UAAW,KAAK,UAAUC,EAAG,KAAM,CAAC,EAAG,MAAO,EAAE,EAG5E,GAAIL,EAAK,OAAO,OAAS,EAAG,CAC1BG,EAAM,KAAK,YAAa,EAAE,EAC1B,QAAWG,KAAKN,EAAK,OACnBG,EAAM,KAAK,OAAOG,EAAE,EAAE,uBAAkBA,EAAE,OAAO,IAAI,EACjDA,EAAE,UAAY,QAChBH,EAAM,KAAK,GAAI,YAAa,KAAK,UAAUG,EAAE,QAAS,KAAM,CAAC,EAAG,OAAO,EAG3EH,EAAM,KAAK,EAAE,CACf,CAEA,OAAOA,EAAM,KAAK;AAAA,CAAI,EAAE,QAAQ,EAAI;AAAA,CACtC,CC5GO,SAASI,GAAcC,EAAsBC,EAAqC,CAAC,EAAS,CAXnG,IAAAC,EAAAC,EAYE,IAAMC,GAAUF,EAAAD,EAAK,YAAL,KAAAC,EAAkB,MAClC,GAAI,CACGE,EAAQ,GAAGJ,EAAM,OAAO,kBAAmB,CAC9C,OAAQ,OACR,QAAS,CAAE,eAAgB,mBAAoB,cAAe,UAAUA,EAAM,MAAM,EAAG,EACvF,KAAM,KAAK,UAAU,CACnB,KAAMA,EAAM,KACZ,QAASA,EAAM,QACf,WAAWG,EAAAH,EAAM,YAAN,KAAAG,EAAmB,KAC9B,OAAQ,KACV,CAAC,CACH,CAAC,EAAE,MAAM,IAAM,CAAC,CAAC,CACnB,OAAQE,EAAA,CAER,CACF,CCfA,OAAS,qBAAAC,OAAyB,mBAgBlC,SAASC,GAAcC,EAAUC,EAAyB,CACxD,OAAOD,EAAI,SAAS,SAAS,KAAK,GAAKC,EAAO,YAAY,EAAE,SAAS,eAAe,CACtF,CAEO,SAASC,GACdC,EACyC,CACzC,MAAO,OAAOC,GAAwC,CAnCxD,IAAAC,EAoCI,IAAML,EAAM,IAAI,IAAII,EAAQ,GAAG,EACzBH,GAASI,EAAAD,EAAQ,QAAQ,IAAI,QAAQ,IAA5B,KAAAC,EAAiC,GAC1CC,EAAYF,EAAQ,QAAQ,IAAI,YAAY,EAE5CG,EAAOP,EAAI,SAAS,QAAQ,eAAgB,EAAE,EAEpD,GAAIG,EAAO,OACT,GAAI,CACG,QAAQ,QACXA,EAAO,OAAO,CAAE,KAAAI,EAAM,UAAAD,EAAW,QAASE,GAAkBF,GAAA,KAAAA,EAAa,EAAE,CAAE,CAAC,CAChF,EAAE,MAAM,IAAM,CAAC,CAAC,CAClB,OAAQG,EAAA,CAER,CAGF,IAAMC,EAAO,MAAMP,EAAO,QAAQC,CAAO,EAEzC,OAAIL,GAAcC,EAAKC,CAAM,EACpB,IAAI,SAASU,GAAoBD,CAAI,EAAG,CAC7C,QAAS,CAAE,eAAgB,8BAA+B,CAC5D,CAAC,EAEI,IAAI,SAAS,KAAK,UAAUA,CAAI,EAAG,CACxC,QAAS,CAAE,eAAgB,iCAAkC,CAC/D,CAAC,CACH,CACF,CLrCA,OAAS,qBAAAE,GAAmB,gBAAAC,GAAc,eAAAC,GAAa,oBAAAC,OAAwB,mBAkW3E,OA8BE,YAAAC,GA9BF,OAAAC,EA8BE,QAAAC,OA9BF,oBA9VJ,IAAMC,GAAuB,iCA0I7B,SAASC,GAAoBC,EAA8C,CACzE,OAAO,OAAO,QAAQA,CAAsC,EAAE,IAAI,CAAC,CAACC,EAAIC,CAAC,IAAG,CAzK9E,IAAAC,EAyKkF,OAC9E,GAAAF,EACA,QAAS,OAAOC,GAAM,SAAWA,GAAMC,EAAAD,GAAA,YAAAA,EAA8B,YAA9B,KAAAC,EAA2C,EACpF,EAAE,CACJ,CAgCA,eAAsBC,GAAaC,EAAgD,CA7MnF,IAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EAAAC,EA8ME,IAeIV,EAAAE,EAdF,YAAAS,EAAa,CAAC,EACd,SAAAC,EACA,MAAAC,EACA,gBAAAC,EACA,UAAAC,EACA,aAAAC,EACA,mBAAoBC,EACpB,aAAcC,EACd,UAAAC,EACA,UAAAC,EACA,cAAAC,EACA,MAAAC,EACA,SAAAC,CA3NJ,EA6NMvB,EADCwB,EAAAC,GACDzB,EADC,CAbH,aACA,WACA,QACA,kBACA,YACA,eACA,qBACA,eACA,YACA,YACA,gBACA,QACA,aAII0B,EAAc,MAAMC,GAAQ,EAC5BC,EAAOF,EAAY,IAAI,MAAM,EAC/B,CAACX,GAAa,QAAQ,IAAI,WAAa,cAAgB,CAACa,GAC1D,QAAQ,MACN,8LAEF,EAEF,IAAMC,EAAiBd,GAAA,KAAAA,EACpB,QAAQ,IAAI,WAAa,aACtB,WAAWa,GAAA,KAAAA,EAAQ,WAAW,GAC9B,wBACAE,GAAY3B,EAAAuB,EAAY,IAAI,YAAY,IAA5B,KAAAvB,EAAiC,OAC7C4B,GAAU3B,EAAAsB,EAAY,IAAI,SAAS,IAAzB,KAAAtB,EAA8B,OAIxC,CAAE,UAAA4B,EAAW,SAAAC,CAAS,EAAIC,GAAqBlB,GAAA,KAAAA,EAAgB,CAAC,CAAC,EAKjEmB,GAAaT,EAAY,IAAI,KAAK,IAAM,KAAOA,EAAY,IAAI,SAAS,IAAM,IAO9EU,GAAiBC,GAAqB,CAAE,UAAAP,EAAW,QAAAC,EAAS,UAAWF,CAAe,CAAC,EACvFS,EAAc,MAAMC,GAAQ,EAe5BC,EAAKhB,EAAc,YACnBiB,GACJlC,EAAAiB,EAAc,UAAd,KAAAjB,EACCiC,GAAA,MAAAA,EAAI,SACDnC,EAAAiC,EAAY,IAAIE,EAAG,MAAM,IAAzB,YAAAnC,EAA4B,WAAWC,EAAAkC,EAAG,QAAH,KAAAlC,EAAY,YACnD,OACAoC,GAAUP,IAAcM,IAAY,IAAUD,GAAM,MAAQC,IAAY,GAOxEE,EAAUnB,EAAc,WAC1BA,EAAc,WAAW,QAAQ,MAAO,EAAE,EAC1C7B,GAOEiD,GAAYnC,GAAAD,EAAAY,GAAA,YAAAA,EAAW,OAAX,KAAAZ,EAAmBkB,EAAY,IAAI,YAAY,IAA/C,KAAAjB,EAAoD,IAChEoC,EAAWC,GAAkBhB,GAAA,KAAAA,EAAa,EAAE,EAC9CT,IAAkB,IAASwB,GAC7BE,GAAc,CAAE,QAAAJ,EAAS,OAAQnB,EAAc,OAAQ,KAAMoB,EAAW,QAASC,EAAU,UAAAf,CAAU,CAAC,EAGxG,IAAIkB,EACAC,EAAsC,KACtCC,EACAC,EACAC,EACAC,EACAC,EAAiE,KACjEC,EAIEC,EAAW,CAAC,EAAC1C,GAAA,MAAAA,EAAiB,QAEpC,GAAIG,EACF+B,EAAqB/B,EACrBsC,EAAerC,UACNwB,GAKTM,EAAqB,CAAC,UACZpC,GAAYA,EAAS,OAAS,GAAOC,GAASA,EAAM,OAAS,GAAM2C,EAAU,CAIvF,IAAMC,EAAW,MAAMC,GAAqBC,EAAAC,EAAA,CAC1C,SAAUhD,GAAA,KAAAA,EAAY,CAAC,EACvB,WAAAD,EACA,MAAAE,GACI2C,EAAW,CAAE,UAAW,WAAqB,gBAAA1C,CAAgB,EAAI,CAAC,GAJ5B,CAK1C,QAASwB,EACT,OAAQd,EAAc,OACtB,QAAAmB,EACA,OAAQd,EACR,UAAAC,EACA,QAAAC,EACA,UAAAC,EACA,SAAAC,EAIA,UAAAd,EACA,QAASK,EAAc,OACzB,EAAC,EACDwB,EAAqBS,EAAS,YAC9BR,EAAqBQ,EAAS,YAC9BP,EAAeO,EAAS,MACxBN,EAAoBM,EAAS,WAC7BL,EAAiBK,EAAS,QAM1BJ,EAAoBI,EAAS,WAC7BH,EACEG,EAAS,UAAY,OACjB,CAAE,QAASA,EAAS,QAAS,YAAY/C,EAAA+C,EAAS,aAAT,KAAA/C,EAAuB,CAAE,EAClE,KACN6C,EAAeE,EAAS,SAC1B,KAAO,CACL,IAAMI,EAAS,MAAMC,GAAwBnD,EAAY,CACvD,QAAS2B,EACT,OAAQd,EAAc,OACtB,QAAAmB,EACA,OAAQd,EACR,UAAAC,EACA,QAAAC,EACA,UAAAC,EACA,SAAAC,EAIA,UAAAd,EACA,QAASK,EAAc,OACzB,CAAC,EACDwB,EAAqBa,EAAO,YAC5BN,EAAeM,EAAO,SACxB,CAIA,IAAME,EACJtE,EAACuE,GAAA,CAAsB,OAAQxC,EAAc,OAAQ,QAAS8B,EAAgB,MAAOhC,EAAO,EAGxF2C,EACJxE,EAACyE,GAAAP,EAAAC,EAAA,GACKpC,GADL,CAIC,QAASiB,EACT,mBAAoBO,EACpB,mBAAoBC,EAGpB,iBAAkBrC,EAClB,aAAcsC,EAGd,kBAAmBC,EACnB,eAAgBC,EAChB,kBAAmBC,EACnB,eAAgBC,GAAA,KAAAA,EAAkB,OAClC,eAAgBlB,GAChB,aAAcmB,EAEb,SAAAhC,GACH,EAGF,GAAI,CAACH,EACH,OACE1B,GAAAF,GAAA,CACG,UAAAuE,EACAE,GACH,EAOJ,IAAME,GAAOC,EAAe,CAC1B,KAAMxB,EACN,OAAQhD,GAAoBoD,CAAkB,EAC9C,YAAaC,GAAA,KAAAA,EAAsB,OACnC,QAAS7B,EAAU,OACrB,CAAC,EAED,OACE1B,GAAAF,GAAA,CACG,UAAAuE,EACDtE,EAAC,UACC,KAAK,sBACL,MAAO6B,EACP,wBAAyB,CAAE,OAAQ+C,GAAsBF,EAAI,CAAE,EACjE,EACCF,GACH,CAEJ","names":["deriveSessionSegment","extractTrackedParams","matchedAgentToken","cookies","headers","renderPrePaintScript","confidenceBand","jsx","inlineJsString","value","personaScriptBody","props","SentientPersonaScript","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","_e","_f","_g","_h","_i","_j","preloadDecisions","fallback","mod","outcome","e","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","logAgentFetch","entry","deps","_a","_b","doFetch","e","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","uaTokenMatch","agentIntent","classifiedAgents","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","_f","_g","_h","_i","components","sections","slots","registrySlotIds","appOrigin","searchParams","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","captureAgents","nonce","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","utmParams","clickIds","extractTrackedParams","doNotTrack","sessionSegment","deriveSessionSegment","cookieStore","cookies","cf","consent","skipSsr","baseUrl","agentPath","agentBot","matchedAgentToken","logAgentFetch","initialAssignments","initialLayoutOrder","initialSlots","initialSlotConfig","initialPalette","initialVocabulary","initialPersona","ssrSessionId","registry","decision","loadAdaptiveDecision","__spreadProps","__spreadValues","result","loadAdaptiveAssignments","personaScript","SentientPersonaScript","client","AdaptiveRootClient","feed","buildAgentFeed","renderAgentJsonLdBody"]}
|
package/dist/testing/react.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
"use strict";var de=Object.create;var k=Object.defineProperty,ue=Object.defineProperties,fe=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyDescriptors,pe=Object.getOwnPropertyNames,M=Object.getOwnPropertySymbols,me=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty,ve=Object.prototype.propertyIsEnumerable;var $=(e,t,n)=>t in e?k(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))K.call(t,n)&&$(e,n,t[n]);if(M)for(var n of M(t))ve.call(t,n)&&$(e,n,t[n]);return e},B=(e,t)=>ue(e,ge(t));var ye=(e,t)=>{for(var n in t)k(e,n,{get:t[n],enumerable:!0})},U=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of pe(t))!K.call(e,o)&&o!==n&&k(e,o,{get:()=>t[o],enumerable:!(i=fe(t,o))||i.enumerable});return e};var V=(e,t,n)=>(n=e!=null?de(me(e)):{},U(t||!e||!e.__esModule?k(n,"default",{value:e,enumerable:!0}):n,e)),_e=e=>U(k({},"__esModule",{value:!0}),e);var Le={};ye(Le,{renderWithSentient:()=>Te});module.exports=_e(Le);var le=require("@testing-library/react");var s=require("react"),O=require("@sentientui/core");var Se=new Map,he=new Map;function z(e,t){Se.set(e,t);let n=he.get(e);if(n)for(let i of n)try{i(t)}catch(o){}}var we={on:!1,listeners:new Set};function j(){if(typeof window=="undefined")return we;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function T(){return j().on}function H(e){let t=j().listeners;return t.add(e),()=>{t.delete(e)}}function J(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,i,o)=>e.assign(t,n,i,o),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var be="sentient:overrides-changed";function E(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(be))}function q(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function A(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Ce={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function L(){if(typeof window=="undefined")return Ce;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function xe(){L().version+=1;for(let e of L().listeners)e()}function D(e){A()&&(L().sections=[...e],xe())}var X="0.35.2",G=X!=="0.0.0-dev"?{name:"react",version:X}:void 0;function Re(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function b(e,t){Re()[e]=t}function Q(e){window.__sentient_vocabulary_override=e}function ke(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function C(e,t){ke()[e]=t}var Y="sentient_editor",Z="sentient_preview_cell",ee="sentient_refresh_region",N="sentient-cell-preview-bar",w="__preview__",Ee=null;function te(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(N))return;let t,n,i;try{let u=new URLSearchParams(window.location.search);t=u.get(Y),n=u.get(Z),i=u.get(ee)}catch(u){return}if(t&&i){Ee={slotId:i,token:t,base:(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"")},b(i,{kind:"arms"}),C(i,w),E();return}if(!t||!n)return;let o=n.lastIndexOf("~");if(o<=0)return;let c=n.slice(0,o),y=n.slice(o+1),_=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");fetch(`${_}/editor/cell-preview?slotId=${encodeURIComponent(c)}&persona=${encodeURIComponent(y)}`,{headers:{authorization:`Bearer ${t}`}}).then(async u=>{if(!u.ok){P(u.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let a=await u.json();if(a.vocabulary&&Array.isArray(a.vocabulary.entries)&&Q(a.vocabulary),a.compose!=null)b(c,{kind:"arms",compose:{[w]:a.compose}}),C(c,w);else if(a.edits!=null&&typeof a.skeletonFp=="string"&&Array.isArray(a.leafToNode))b(c,{kind:"arms",edits:{edits:a.edits,fp:a.skeletonFp,leafToNode:a.leafToNode}}),C(c,w);else if(a.blocks!=null)b(c,{kind:"arms",blocks:{[w]:a.blocks}}),C(c,w);else if(a.content!=null)b(c,{kind:"arms",content:a.content}),C(c,w);else{P("Nothing to preview in that square yet.");return}E(),P(`Previewing \u201C${a.slotName}\u201D for ${a.personaDisplay}${a.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var f;try{(f=document.querySelector(`[data-sentient-slot="${c}"]`))==null||f.scrollIntoView({block:"center"})}catch(x){}},300)}).catch(()=>P("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function P(e){var o;if(document.getElementById(N))return;let t=document.createElement("div");t.id=N,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.textContent="Exit preview",Object.assign(i.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),i.onclick=()=>{let c=new URL(window.location.href);c.searchParams.delete(Y),c.searchParams.delete(Z),c.searchParams.delete(ee),window.location.assign(c.toString())},t.append(n,i),((o=document.body)!=null?o:document.documentElement).append(t)}var Ae="sentient_editor",ne=!1;function ie(e){if(ne||typeof window=="undefined")return;let t=null;try{t=new URLSearchParams(window.location.search).get(Ae)}catch(o){return}if(!t)return;ne=!0;let n=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),i=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:o})=>fetch(`${n}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(o(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?i():window.addEventListener("load",i,{once:!0})}var se=require("react/jsx-runtime");function Pe(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return(0,O.deriveSessionSegment)({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var oe="https://api.sentient-ui.com/v1",Oe=(0,s.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:oe,debug:!1});function Ie(e){let[t,n]=(0,s.useState)(!1),i=(0,s.useRef)(e);i.current=e;let{cookie:o,value:c,event:y}=e!=null?e:{},_=typeof(e==null?void 0:e.check)=="function";return(0,s.useEffect)(()=>{let u=()=>{var R;let f=i.current;if(!f)return!1;if(f.check)return f.check()===!0;if(!f.cookie||typeof document=="undefined")return!1;let x=`${f.cookie}=${(R=f.value)!=null?R:"accepted"}`;return document.cookie.split("; ").some(I=>I.trim()===x)};if(n(u()),!y)return;let a=()=>{n(u())};return window.addEventListener(y,a),()=>window.removeEventListener(y,a)},[o,c,y,_]),t}function re(e){var W,F;let[t,n]=(0,s.useState)(null),[i]=(0,s.useState)(()=>{var r;return(r=e.sessionSegment)!=null?r:Pe()}),[o,c]=(0,s.useState)(T());(0,s.useEffect)(()=>H(()=>c(T())),[]),(0,s.useEffect)(()=>{te(e.apiBaseUrl),ie(e.apiBaseUrl)},[]);let y=Ie(e.consentFrom),_=e.consentFrom?e.consent===!0||y:e.consent,u=(0,s.useRef)(null);(0,s.useEffect)(()=>{var S;if(_===!1&&!e.preConsentBehavior){(S=u.current)==null||S.destroy(),u.current=null,n(null);return}let r=v({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:_,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},G?{sdk:G}:{}),g=!1,l=null,d=null,p=m=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:h})=>{g||(d=h(m,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:m})=>{g||(l=m(B(v({},r),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),u.current=l,n(l),p(l))}):(l=(0,O.init)(r),u.current=l,n(l),p(l)),()=>{g=!0,d==null||d(),l==null||l.dispose()}},[_]),(0,s.useEffect)(()=>{if(!t)return;let r=!1,g=async()=>{if(r)return;let d;try{d=await t.fetchWeights()}catch(p){return}if(!r)for(let p of d){let S={componentId:p.componentId,updatedAt:p.updatedAt,variants:p.variants.map(m=>{var h;return{variantId:m.variantId,pulls:m.pulls,avgReward:(h=m.avgReward)!=null?h:0}})};z(p.componentId,S)}};g();let l=setInterval(()=>{g()},6e4);return()=>{r=!0,clearInterval(l)}},[t]);let a=(W=e.ssrFallback)!=null?W:"first",f=((F=e.apiBaseUrl)!=null?F:oe).replace(/\/$/,""),x=(0,s.useRef)(null);(0,s.useEffect)(()=>{var l;if(typeof process!="undefined"&&((l=process.env)==null?void 0:l.NODE_ENV)==="production")return;let r={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:f},g=x.current;if(x.current=r,g!==null)for(let d of["apiKey","context","country","persona","apiBaseUrl"])Object.is(g[d],r[d])||console.warn(`[sentient] AdaptiveProvider: \`${d}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,f]),(0,s.useEffect)(()=>{var r;typeof process!="undefined"&&((r=process.env)==null?void 0:r.NODE_ENV)==="production"||q({apiKey:e.apiKey,apiBaseUrl:f,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,f]),(0,s.useEffect)(()=>{let r=e.initialLayoutOrder;if(r&&r.length>0){D(r);return}e.declaredSections&&e.declaredSections.length>0&&D(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),(0,s.useEffect)(()=>{if(!A())return;let r=e.declaredSections;if(!r||r.length===0||typeof document=="undefined")return;let g=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),d=>d.getAttribute("data-sentient-id"))),l=r.filter(d=>!g.has(d));l.length>0&&console.warn(`[SentientUI] Declared section${l.length>1?"s":""} ${l.map(d=>`"${d}"`).join(", ")} ${l.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let R=(0,s.useMemo)(()=>t&&o?J(t):t,[t,o]),I=(0,s.useMemo)(()=>{var r,g,l,d,p,S,m,h;return{client:R,apiKey:e.apiKey,initialAssignments:(r=e.initialAssignments)!=null?r:{},sessionSegment:i,ssrFallback:a,onAssignment:e.onAssignment,initialLayoutOrder:(g=e.initialLayoutOrder)!=null?g:null,initialSlots:(l=e.initialSlots)!=null?l:{},initialSlotConfig:(d=e.initialSlotConfig)!=null?d:{},initialPalette:(p=e.initialPalette)!=null?p:null,initialVocabulary:(S=e.initialVocabulary)!=null?S:null,initialPersona:(m=e.initialPersona)!=null?m:null,apiBaseUrl:f,debug:(h=e.debug)!=null?h:!1}},[R,e.apiKey,e.initialAssignments,i,a,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,f,e.debug]);return(0,se.jsx)(Oe.Provider,{value:I,children:e.children})}function Ve(e){return e<.3?"low":e<.7?"medium":"high"}function ae(e={}){var n,i,o;let t=window;if(t.__sentient_overrides=v({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=v({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=v({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let c=document.documentElement;c.setAttribute("data-sentient-persona",e.persona),c.setAttribute("data-sentient-confidence",Ve((o=e.confidence)!=null?o:1))}catch(c){}}else delete t.__sentient_persona_override;E()}var ce=require("react/jsx-runtime");function Te(e,t={},n){return ae(t),(0,le.render)((0,ce.jsx)(re,{apiKey:"pk_test",consent:!1,children:e}),n)}0&&(module.exports={renderWithSentient});
|
|
2
|
+
"use strict";var de=Object.create;var k=Object.defineProperty,ue=Object.defineProperties,fe=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyDescriptors,pe=Object.getOwnPropertyNames,M=Object.getOwnPropertySymbols,me=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty,ve=Object.prototype.propertyIsEnumerable;var $=(e,t,n)=>t in e?k(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))K.call(t,n)&&$(e,n,t[n]);if(M)for(var n of M(t))ve.call(t,n)&&$(e,n,t[n]);return e},B=(e,t)=>ue(e,ge(t));var ye=(e,t)=>{for(var n in t)k(e,n,{get:t[n],enumerable:!0})},U=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of pe(t))!K.call(e,o)&&o!==n&&k(e,o,{get:()=>t[o],enumerable:!(i=fe(t,o))||i.enumerable});return e};var V=(e,t,n)=>(n=e!=null?de(me(e)):{},U(t||!e||!e.__esModule?k(n,"default",{value:e,enumerable:!0}):n,e)),_e=e=>U(k({},"__esModule",{value:!0}),e);var Le={};ye(Le,{renderWithSentient:()=>Te});module.exports=_e(Le);var le=require("@testing-library/react");var s=require("react"),O=require("@sentientui/core");var Se=new Map,he=new Map;function z(e,t){Se.set(e,t);let n=he.get(e);if(n)for(let i of n)try{i(t)}catch(o){}}var we={on:!1,listeners:new Set};function j(){if(typeof window=="undefined")return we;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function T(){return j().on}function H(e){let t=j().listeners;return t.add(e),()=>{t.delete(e)}}function J(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,i,o)=>e.assign(t,n,i,o),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var be="sentient:overrides-changed";function E(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(be))}function q(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function A(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Ce={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function L(){if(typeof window=="undefined")return Ce;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function xe(){L().version+=1;for(let e of L().listeners)e()}function D(e){A()&&(L().sections=[...e],xe())}var X="0.35.3",G=X!=="0.0.0-dev"?{name:"react",version:X}:void 0;function Re(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function b(e,t){Re()[e]=t}function Q(e){window.__sentient_vocabulary_override=e}function ke(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function C(e,t){ke()[e]=t}var Y="sentient_editor",Z="sentient_preview_cell",ee="sentient_refresh_region",N="sentient-cell-preview-bar",w="__preview__",Ee=null;function te(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(N))return;let t,n,i;try{let u=new URLSearchParams(window.location.search);t=u.get(Y),n=u.get(Z),i=u.get(ee)}catch(u){return}if(t&&i){Ee={slotId:i,token:t,base:(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"")},b(i,{kind:"arms"}),C(i,w),E();return}if(!t||!n)return;let o=n.lastIndexOf("~");if(o<=0)return;let c=n.slice(0,o),y=n.slice(o+1),_=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");fetch(`${_}/editor/cell-preview?slotId=${encodeURIComponent(c)}&persona=${encodeURIComponent(y)}`,{headers:{authorization:`Bearer ${t}`}}).then(async u=>{if(!u.ok){P(u.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let a=await u.json();if(a.vocabulary&&Array.isArray(a.vocabulary.entries)&&Q(a.vocabulary),a.compose!=null)b(c,{kind:"arms",compose:{[w]:a.compose}}),C(c,w);else if(a.edits!=null&&typeof a.skeletonFp=="string"&&Array.isArray(a.leafToNode))b(c,{kind:"arms",edits:{edits:a.edits,fp:a.skeletonFp,leafToNode:a.leafToNode}}),C(c,w);else if(a.blocks!=null)b(c,{kind:"arms",blocks:{[w]:a.blocks}}),C(c,w);else if(a.content!=null)b(c,{kind:"arms",content:a.content}),C(c,w);else{P("Nothing to preview in that square yet.");return}E(),P(`Previewing \u201C${a.slotName}\u201D for ${a.personaDisplay}${a.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var f;try{(f=document.querySelector(`[data-sentient-slot="${c}"]`))==null||f.scrollIntoView({block:"center"})}catch(x){}},300)}).catch(()=>P("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function P(e){var o;if(document.getElementById(N))return;let t=document.createElement("div");t.id=N,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.textContent="Exit preview",Object.assign(i.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),i.onclick=()=>{let c=new URL(window.location.href);c.searchParams.delete(Y),c.searchParams.delete(Z),c.searchParams.delete(ee),window.location.assign(c.toString())},t.append(n,i),((o=document.body)!=null?o:document.documentElement).append(t)}var Ae="sentient_editor",ne=!1;function ie(e){if(ne||typeof window=="undefined")return;let t=null;try{t=new URLSearchParams(window.location.search).get(Ae)}catch(o){return}if(!t)return;ne=!0;let n=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),i=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:o})=>fetch(`${n}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(o(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?i():window.addEventListener("load",i,{once:!0})}var se=require("react/jsx-runtime");function Pe(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return(0,O.deriveSessionSegment)({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var oe="https://api.sentient-ui.com/v1",Oe=(0,s.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:oe,debug:!1});function Ie(e){let[t,n]=(0,s.useState)(!1),i=(0,s.useRef)(e);i.current=e;let{cookie:o,value:c,event:y}=e!=null?e:{},_=typeof(e==null?void 0:e.check)=="function";return(0,s.useEffect)(()=>{let u=()=>{var R;let f=i.current;if(!f)return!1;if(f.check)return f.check()===!0;if(!f.cookie||typeof document=="undefined")return!1;let x=`${f.cookie}=${(R=f.value)!=null?R:"accepted"}`;return document.cookie.split("; ").some(I=>I.trim()===x)};if(n(u()),!y)return;let a=()=>{n(u())};return window.addEventListener(y,a),()=>window.removeEventListener(y,a)},[o,c,y,_]),t}function re(e){var W,F;let[t,n]=(0,s.useState)(null),[i]=(0,s.useState)(()=>{var r;return(r=e.sessionSegment)!=null?r:Pe()}),[o,c]=(0,s.useState)(T());(0,s.useEffect)(()=>H(()=>c(T())),[]),(0,s.useEffect)(()=>{te(e.apiBaseUrl),ie(e.apiBaseUrl)},[]);let y=Ie(e.consentFrom),_=e.consentFrom?e.consent===!0||y:e.consent,u=(0,s.useRef)(null);(0,s.useEffect)(()=>{var S;if(_===!1&&!e.preConsentBehavior){(S=u.current)==null||S.destroy(),u.current=null,n(null);return}let r=v({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:_,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},G?{sdk:G}:{}),g=!1,l=null,d=null,p=m=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:h})=>{g||(d=h(m,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:m})=>{g||(l=m(B(v({},r),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),u.current=l,n(l),p(l))}):(l=(0,O.init)(r),u.current=l,n(l),p(l)),()=>{g=!0,d==null||d(),l==null||l.dispose()}},[_]),(0,s.useEffect)(()=>{if(!t)return;let r=!1,g=async()=>{if(r)return;let d;try{d=await t.fetchWeights()}catch(p){return}if(!r)for(let p of d){let S={componentId:p.componentId,updatedAt:p.updatedAt,variants:p.variants.map(m=>{var h;return{variantId:m.variantId,pulls:m.pulls,avgReward:(h=m.avgReward)!=null?h:0}})};z(p.componentId,S)}};g();let l=setInterval(()=>{g()},6e4);return()=>{r=!0,clearInterval(l)}},[t]);let a=(W=e.ssrFallback)!=null?W:"first",f=((F=e.apiBaseUrl)!=null?F:oe).replace(/\/$/,""),x=(0,s.useRef)(null);(0,s.useEffect)(()=>{var l;if(typeof process!="undefined"&&((l=process.env)==null?void 0:l.NODE_ENV)==="production")return;let r={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:f},g=x.current;if(x.current=r,g!==null)for(let d of["apiKey","context","country","persona","apiBaseUrl"])Object.is(g[d],r[d])||console.warn(`[sentient] AdaptiveProvider: \`${d}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,f]),(0,s.useEffect)(()=>{var r;typeof process!="undefined"&&((r=process.env)==null?void 0:r.NODE_ENV)==="production"||q({apiKey:e.apiKey,apiBaseUrl:f,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,f]),(0,s.useEffect)(()=>{let r=e.initialLayoutOrder;if(r&&r.length>0){D(r);return}e.declaredSections&&e.declaredSections.length>0&&D(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),(0,s.useEffect)(()=>{if(!A())return;let r=e.declaredSections;if(!r||r.length===0||typeof document=="undefined")return;let g=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),d=>d.getAttribute("data-sentient-id"))),l=r.filter(d=>!g.has(d));l.length>0&&console.warn(`[SentientUI] Declared section${l.length>1?"s":""} ${l.map(d=>`"${d}"`).join(", ")} ${l.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let R=(0,s.useMemo)(()=>t&&o?J(t):t,[t,o]),I=(0,s.useMemo)(()=>{var r,g,l,d,p,S,m,h;return{client:R,apiKey:e.apiKey,initialAssignments:(r=e.initialAssignments)!=null?r:{},sessionSegment:i,ssrFallback:a,onAssignment:e.onAssignment,initialLayoutOrder:(g=e.initialLayoutOrder)!=null?g:null,initialSlots:(l=e.initialSlots)!=null?l:{},initialSlotConfig:(d=e.initialSlotConfig)!=null?d:{},initialPalette:(p=e.initialPalette)!=null?p:null,initialVocabulary:(S=e.initialVocabulary)!=null?S:null,initialPersona:(m=e.initialPersona)!=null?m:null,apiBaseUrl:f,debug:(h=e.debug)!=null?h:!1}},[R,e.apiKey,e.initialAssignments,i,a,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,f,e.debug]);return(0,se.jsx)(Oe.Provider,{value:I,children:e.children})}function Ve(e){return e<.3?"low":e<.7?"medium":"high"}function ae(e={}){var n,i,o;let t=window;if(t.__sentient_overrides=v({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=v({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=v({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let c=document.documentElement;c.setAttribute("data-sentient-persona",e.persona),c.setAttribute("data-sentient-confidence",Ve((o=e.confidence)!=null?o:1))}catch(c){}}else delete t.__sentient_persona_override;E()}var ce=require("react/jsx-runtime");function Te(e,t={},n){return ae(t),(0,le.render)((0,ce.jsx)(re,{apiKey:"pk_test",consent:!1,children:e}),n)}0&&(module.exports={renderWithSentient});
|
|
3
3
|
//# sourceMappingURL=react.js.map
|
package/dist/testing/react.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
'use client';
|
|
2
|
-
var re=Object.defineProperty,se=Object.defineProperties;var ae=Object.getOwnPropertyDescriptors;var F=Object.getOwnPropertySymbols;var le=Object.prototype.hasOwnProperty,ce=Object.prototype.propertyIsEnumerable;var M=(e,t,n)=>t in e?re(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,m=(e,t)=>{for(var n in t||(t={}))le.call(t,n)&&M(e,n,t[n]);if(F)for(var n of F(t))ce.call(t,n)&&M(e,n,t[n]);return e},$=(e,t)=>se(e,ae(t));import{render as Ae}from"@testing-library/react";import{createContext as he,useContext as Xe,useEffect as v,useMemo as te,useRef as G,useState as P,useSyncExternalStore as Qe}from"react";import{deriveSessionSegment as we,init as be}from"@sentientui/core";var de=new Map,ue=new Map;function K(e,t){de.set(e,t);let n=ue.get(e);if(n)for(let i of n)try{i(t)}catch(l){}}var fe={on:!1,listeners:new Set};function B(){if(typeof window=="undefined")return fe;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function I(){return B().on}function U(e){let t=B().listeners;return t.add(e),()=>{t.delete(e)}}function z(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,i,l)=>e.assign(t,n,i,l),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var ge="sentient:overrides-changed";function k(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(ge))}function j(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function E(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var pe={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function V(){if(typeof window=="undefined")return pe;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function me(){V().version+=1;for(let e of V().listeners)e()}function T(e){E()&&(V().sections=[...e],me())}var H="0.35.2",L=H!=="0.0.0-dev"?{name:"react",version:H}:void 0;function ve(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function b(e,t){ve()[e]=t}function J(e){window.__sentient_vocabulary_override=e}function ye(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function C(e,t){ye()[e]=t}var q="sentient_editor",X="sentient_preview_cell",Q="sentient_refresh_region",D="sentient-cell-preview-bar",w="__preview__",_e=null;function Y(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(D))return;let t,n,i;try{let d=new URLSearchParams(window.location.search);t=d.get(q),n=d.get(X),i=d.get(Q)}catch(d){return}if(t&&i){_e={slotId:i,token:t,base:(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"")},b(i,{kind:"arms"}),C(i,w),k();return}if(!t||!n)return;let l=n.lastIndexOf("~");if(l<=0)return;let a=n.slice(0,l),y=n.slice(l+1),_=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");fetch(`${_}/editor/cell-preview?slotId=${encodeURIComponent(a)}&persona=${encodeURIComponent(y)}`,{headers:{authorization:`Bearer ${t}`}}).then(async d=>{if(!d.ok){A(d.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let r=await d.json();if(r.vocabulary&&Array.isArray(r.vocabulary.entries)&&J(r.vocabulary),r.compose!=null)b(a,{kind:"arms",compose:{[w]:r.compose}}),C(a,w);else if(r.edits!=null&&typeof r.skeletonFp=="string"&&Array.isArray(r.leafToNode))b(a,{kind:"arms",edits:{edits:r.edits,fp:r.skeletonFp,leafToNode:r.leafToNode}}),C(a,w);else if(r.blocks!=null)b(a,{kind:"arms",blocks:{[w]:r.blocks}}),C(a,w);else if(r.content!=null)b(a,{kind:"arms",content:r.content}),C(a,w);else{A("Nothing to preview in that square yet.");return}k(),A(`Previewing \u201C${r.slotName}\u201D for ${r.personaDisplay}${r.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var u;try{(u=document.querySelector(`[data-sentient-slot="${a}"]`))==null||u.scrollIntoView({block:"center"})}catch(x){}},300)}).catch(()=>A("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function A(e){var l;if(document.getElementById(D))return;let t=document.createElement("div");t.id=D,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.textContent="Exit preview",Object.assign(i.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),i.onclick=()=>{let a=new URL(window.location.href);a.searchParams.delete(q),a.searchParams.delete(X),a.searchParams.delete(Q),window.location.assign(a.toString())},t.append(n,i),((l=document.body)!=null?l:document.documentElement).append(t)}var Se="sentient_editor",Z=!1;function ee(e){if(Z||typeof window=="undefined")return;let t=null;try{t=new URLSearchParams(window.location.search).get(Se)}catch(l){return}if(!t)return;Z=!0;let n=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),i=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:l})=>fetch(`${n}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(l(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?i():window.addEventListener("load",i,{once:!0})}import{jsx as ke}from"react/jsx-runtime";function Ce(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return we({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var ne="https://api.sentient-ui.com/v1",xe=he({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:ne,debug:!1});function Re(e){let[t,n]=P(!1),i=G(e);i.current=e;let{cookie:l,value:a,event:y}=e!=null?e:{},_=typeof(e==null?void 0:e.check)=="function";return v(()=>{let d=()=>{var R;let u=i.current;if(!u)return!1;if(u.check)return u.check()===!0;if(!u.cookie||typeof document=="undefined")return!1;let x=`${u.cookie}=${(R=u.value)!=null?R:"accepted"}`;return document.cookie.split("; ").some(O=>O.trim()===x)};if(n(d()),!y)return;let r=()=>{n(d())};return window.addEventListener(y,r),()=>window.removeEventListener(y,r)},[l,a,y,_]),t}function ie(e){var N,W;let[t,n]=P(null),[i]=P(()=>{var o;return(o=e.sessionSegment)!=null?o:Ce()}),[l,a]=P(I());v(()=>U(()=>a(I())),[]),v(()=>{Y(e.apiBaseUrl),ee(e.apiBaseUrl)},[]);let y=Re(e.consentFrom),_=e.consentFrom?e.consent===!0||y:e.consent,d=G(null);v(()=>{var S;if(_===!1&&!e.preConsentBehavior){(S=d.current)==null||S.destroy(),d.current=null,n(null);return}let o=m({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:_,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},L?{sdk:L}:{}),f=!1,s=null,c=null,g=p=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:h})=>{f||(c=h(p,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:p})=>{f||(s=p($(m({},o),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),d.current=s,n(s),g(s))}):(s=be(o),d.current=s,n(s),g(s)),()=>{f=!0,c==null||c(),s==null||s.dispose()}},[_]),v(()=>{if(!t)return;let o=!1,f=async()=>{if(o)return;let c;try{c=await t.fetchWeights()}catch(g){return}if(!o)for(let g of c){let S={componentId:g.componentId,updatedAt:g.updatedAt,variants:g.variants.map(p=>{var h;return{variantId:p.variantId,pulls:p.pulls,avgReward:(h=p.avgReward)!=null?h:0}})};K(g.componentId,S)}};f();let s=setInterval(()=>{f()},6e4);return()=>{o=!0,clearInterval(s)}},[t]);let r=(N=e.ssrFallback)!=null?N:"first",u=((W=e.apiBaseUrl)!=null?W:ne).replace(/\/$/,""),x=G(null);v(()=>{var s;if(typeof process!="undefined"&&((s=process.env)==null?void 0:s.NODE_ENV)==="production")return;let o={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:u},f=x.current;if(x.current=o,f!==null)for(let c of["apiKey","context","country","persona","apiBaseUrl"])Object.is(f[c],o[c])||console.warn(`[sentient] AdaptiveProvider: \`${c}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,u]),v(()=>{var o;typeof process!="undefined"&&((o=process.env)==null?void 0:o.NODE_ENV)==="production"||j({apiKey:e.apiKey,apiBaseUrl:u,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,u]),v(()=>{let o=e.initialLayoutOrder;if(o&&o.length>0){T(o);return}e.declaredSections&&e.declaredSections.length>0&&T(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),v(()=>{if(!E())return;let o=e.declaredSections;if(!o||o.length===0||typeof document=="undefined")return;let f=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),c=>c.getAttribute("data-sentient-id"))),s=o.filter(c=>!f.has(c));s.length>0&&console.warn(`[SentientUI] Declared section${s.length>1?"s":""} ${s.map(c=>`"${c}"`).join(", ")} ${s.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let R=te(()=>t&&l?z(t):t,[t,l]),O=te(()=>{var o,f,s,c,g,S,p,h;return{client:R,apiKey:e.apiKey,initialAssignments:(o=e.initialAssignments)!=null?o:{},sessionSegment:i,ssrFallback:r,onAssignment:e.onAssignment,initialLayoutOrder:(f=e.initialLayoutOrder)!=null?f:null,initialSlots:(s=e.initialSlots)!=null?s:{},initialSlotConfig:(c=e.initialSlotConfig)!=null?c:{},initialPalette:(g=e.initialPalette)!=null?g:null,initialVocabulary:(S=e.initialVocabulary)!=null?S:null,initialPersona:(p=e.initialPersona)!=null?p:null,apiBaseUrl:u,debug:(h=e.debug)!=null?h:!1}},[R,e.apiKey,e.initialAssignments,i,r,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,u,e.debug]);return ke(xe.Provider,{value:O,children:e.children})}function Ee(e){return e<.3?"low":e<.7?"medium":"high"}function oe(e={}){var n,i,l;let t=window;if(t.__sentient_overrides=m({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=m({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=m({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let a=document.documentElement;a.setAttribute("data-sentient-persona",e.persona),a.setAttribute("data-sentient-confidence",Ee((l=e.confidence)!=null?l:1))}catch(a){}}else delete t.__sentient_persona_override;k()}import{jsx as Pe}from"react/jsx-runtime";function vt(e,t={},n){return oe(t),Ae(Pe(ie,{apiKey:"pk_test",consent:!1,children:e}),n)}export{vt as renderWithSentient};
|
|
2
|
+
var re=Object.defineProperty,se=Object.defineProperties;var ae=Object.getOwnPropertyDescriptors;var F=Object.getOwnPropertySymbols;var le=Object.prototype.hasOwnProperty,ce=Object.prototype.propertyIsEnumerable;var M=(e,t,n)=>t in e?re(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,m=(e,t)=>{for(var n in t||(t={}))le.call(t,n)&&M(e,n,t[n]);if(F)for(var n of F(t))ce.call(t,n)&&M(e,n,t[n]);return e},$=(e,t)=>se(e,ae(t));import{render as Ae}from"@testing-library/react";import{createContext as he,useContext as Xe,useEffect as v,useMemo as te,useRef as G,useState as P,useSyncExternalStore as Qe}from"react";import{deriveSessionSegment as we,init as be}from"@sentientui/core";var de=new Map,ue=new Map;function K(e,t){de.set(e,t);let n=ue.get(e);if(n)for(let i of n)try{i(t)}catch(l){}}var fe={on:!1,listeners:new Set};function B(){if(typeof window=="undefined")return fe;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function I(){return B().on}function U(e){let t=B().listeners;return t.add(e),()=>{t.delete(e)}}function z(e){return{isLocal:e.isLocal,track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},fetchWeights:()=>Promise.resolve([]),getAssignment:(t,n)=>e.getAssignment(t,n),assign:(t,n,i,l)=>e.assign(t,n,i,l),decide:()=>Promise.resolve(null),getSlotResult:t=>e.getSlotResult(t),getSlotConfig:t=>e.getSlotConfig(t),getSitePalette:()=>e.getSitePalette(),reportSlots:t=>e.reportSlots(t),getPersona:()=>e.getPersona(),getGraph:()=>e.getGraph(),flush:()=>e.flush(),dispose:()=>e.dispose(),destroy:()=>e.destroy()}}var ge="sentient:overrides-changed";function k(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(ge))}function j(e){typeof window!="undefined"&&(window.__sentient_devtools_config=e)}function E(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var pe={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function V(){if(typeof window=="undefined")return pe;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function me(){V().version+=1;for(let e of V().listeners)e()}function T(e){E()&&(V().sections=[...e],me())}var H="0.35.3",L=H!=="0.0.0-dev"?{name:"react",version:H}:void 0;function ve(){let e=window;return e.__sentient_slot_config_overrides||(e.__sentient_slot_config_overrides={}),e.__sentient_slot_config_overrides}function b(e,t){ve()[e]=t}function J(e){window.__sentient_vocabulary_override=e}function ye(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function C(e,t){ye()[e]=t}var q="sentient_editor",X="sentient_preview_cell",Q="sentient_refresh_region",D="sentient-cell-preview-bar",w="__preview__",_e=null;function Y(e){if(typeof window=="undefined"||typeof document=="undefined"||document.getElementById(D))return;let t,n,i;try{let d=new URLSearchParams(window.location.search);t=d.get(q),n=d.get(X),i=d.get(Q)}catch(d){return}if(t&&i){_e={slotId:i,token:t,base:(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"")},b(i,{kind:"arms"}),C(i,w),k();return}if(!t||!n)return;let l=n.lastIndexOf("~");if(l<=0)return;let a=n.slice(0,l),y=n.slice(l+1),_=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,"");fetch(`${_}/editor/cell-preview?slotId=${encodeURIComponent(a)}&persona=${encodeURIComponent(y)}`,{headers:{authorization:`Bearer ${t}`}}).then(async d=>{if(!d.ok){A(d.status===401?"This preview link has expired \u2014 reopen it from your dashboard.":"Couldn\u2019t load this preview \u2014 reopen it from your dashboard.");return}let r=await d.json();if(r.vocabulary&&Array.isArray(r.vocabulary.entries)&&J(r.vocabulary),r.compose!=null)b(a,{kind:"arms",compose:{[w]:r.compose}}),C(a,w);else if(r.edits!=null&&typeof r.skeletonFp=="string"&&Array.isArray(r.leafToNode))b(a,{kind:"arms",edits:{edits:r.edits,fp:r.skeletonFp,leafToNode:r.leafToNode}}),C(a,w);else if(r.blocks!=null)b(a,{kind:"arms",blocks:{[w]:r.blocks}}),C(a,w);else if(r.content!=null)b(a,{kind:"arms",content:r.content}),C(a,w);else{A("Nothing to preview in that square yet.");return}k(),A(`Previewing \u201C${r.slotName}\u201D for ${r.personaDisplay}${r.status==="review"?" \u2014 waiting for your approval":""}. Nothing is being tracked.`),setTimeout(()=>{var u;try{(u=document.querySelector(`[data-sentient-slot="${a}"]`))==null||u.scrollIntoView({block:"center"})}catch(x){}},300)}).catch(()=>A("Couldn\u2019t load this preview \u2014 check your connection and reopen it from your dashboard."))}function A(e){var l;if(document.getElementById(D))return;let t=document.createElement("div");t.id=D,Object.assign(t.style,{position:"fixed",bottom:"16px",left:"50%",transform:"translateX(-50%)",zIndex:"2147483647",display:"flex",alignItems:"center",gap:"10px",padding:"10px 14px",borderRadius:"12px",maxWidth:"90vw",background:"#111827",color:"#fff",font:"13px system-ui, sans-serif",border:"1px solid rgba(139,92,246,0.6)",boxShadow:"0 10px 34px rgba(0,0,0,0.45)"});let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.textContent="Exit preview",Object.assign(i.style,{padding:"4px 10px",borderRadius:"999px",border:"1px solid rgba(255,255,255,0.35)",background:"transparent",color:"#fff",font:"12px system-ui, sans-serif",cursor:"pointer"}),i.onclick=()=>{let a=new URL(window.location.href);a.searchParams.delete(q),a.searchParams.delete(X),a.searchParams.delete(Q),window.location.assign(a.toString())},t.append(n,i),((l=document.body)!=null?l:document.documentElement).append(t)}var Se="sentient_editor",Z=!1;function ee(e){if(Z||typeof window=="undefined")return;let t=null;try{t=new URLSearchParams(window.location.search).get(Se)}catch(l){return}if(!t)return;Z=!0;let n=(e!=null?e:"https://api.sentient-ui.com/v1").replace(/\/$/,""),i=()=>{window.setTimeout(()=>{import("@sentientui/core/style-sample").then(({sampleStyleVocabulary:l})=>fetch(`${n}/editor/style-vocabulary`,{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify(l(document))})).catch(()=>{})},1e3)};document.readyState==="complete"?i():window.addEventListener("load",i,{once:!0})}import{jsx as ke}from"react/jsx-runtime";function Ce(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{return we({userAgent:(e=navigator.userAgent)!=null?e:"",referer:(t=document.referrer)!=null?t:"",appOrigin:window.location.origin})}catch(n){return"desktop:direct"}}var ne="https://api.sentient-ui.com/v1",xe=he({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null,initialSlots:{},initialSlotConfig:{},initialPalette:null,initialVocabulary:null,initialPersona:null,apiBaseUrl:ne,debug:!1});function Re(e){let[t,n]=P(!1),i=G(e);i.current=e;let{cookie:l,value:a,event:y}=e!=null?e:{},_=typeof(e==null?void 0:e.check)=="function";return v(()=>{let d=()=>{var R;let u=i.current;if(!u)return!1;if(u.check)return u.check()===!0;if(!u.cookie||typeof document=="undefined")return!1;let x=`${u.cookie}=${(R=u.value)!=null?R:"accepted"}`;return document.cookie.split("; ").some(O=>O.trim()===x)};if(n(d()),!y)return;let r=()=>{n(d())};return window.addEventListener(y,r),()=>window.removeEventListener(y,r)},[l,a,y,_]),t}function ie(e){var N,W;let[t,n]=P(null),[i]=P(()=>{var o;return(o=e.sessionSegment)!=null?o:Ce()}),[l,a]=P(I());v(()=>U(()=>a(I())),[]),v(()=>{Y(e.apiBaseUrl),ee(e.apiBaseUrl)},[]);let y=Re(e.consentFrom),_=e.consentFrom?e.consent===!0||y:e.consent,d=G(null);v(()=>{var S;if(_===!1&&!e.preConsentBehavior){(S=d.current)==null||S.destroy(),d.current=null,n(null);return}let o=m({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:i,consent:_,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country,persona:e.persona,localMode:e.localMode,initialSlots:e.initialSlots,initialSlotConfig:e.initialSlotConfig,initialPalette:e.initialPalette,initialVocabulary:e.initialVocabulary,initialPersona:e.initialPersona,ingestUrl:e.apiBaseUrl?`${e.apiBaseUrl.replace(/\/$/,"")}/events`:void 0},L?{sdk:L}:{}),f=!1,s=null,c=null,g=p=>{e.engagement!==!1&&import("@sentientui/core/engagement").then(({startEngagementCapture:h})=>{f||(c=h(p,{apiKey:e.apiKey,sectionTypes:e.sectionTypes,apiBase:e.apiBaseUrl?e.apiBaseUrl.replace(/\/$/,""):void 0}))})};return e.enableGraph!==!1?import("@sentientui/core/graph").then(({init:p})=>{f||(s=p($(m({},o),{graph:!0,captureDomText:e.captureDomText===!0,sectionTypes:e.sectionTypes})),d.current=s,n(s),g(s))}):(s=be(o),d.current=s,n(s),g(s)),()=>{f=!0,c==null||c(),s==null||s.dispose()}},[_]),v(()=>{if(!t)return;let o=!1,f=async()=>{if(o)return;let c;try{c=await t.fetchWeights()}catch(g){return}if(!o)for(let g of c){let S={componentId:g.componentId,updatedAt:g.updatedAt,variants:g.variants.map(p=>{var h;return{variantId:p.variantId,pulls:p.pulls,avgReward:(h=p.avgReward)!=null?h:0}})};K(g.componentId,S)}};f();let s=setInterval(()=>{f()},6e4);return()=>{o=!0,clearInterval(s)}},[t]);let r=(N=e.ssrFallback)!=null?N:"first",u=((W=e.apiBaseUrl)!=null?W:ne).replace(/\/$/,""),x=G(null);v(()=>{var s;if(typeof process!="undefined"&&((s=process.env)==null?void 0:s.NODE_ENV)==="production")return;let o={apiKey:e.apiKey,context:e.context,country:e.country,persona:e.persona,apiBaseUrl:u},f=x.current;if(x.current=o,f!==null)for(let c of["apiKey","context","country","persona","apiBaseUrl"])Object.is(f[c],o[c])||console.warn(`[sentient] AdaptiveProvider: \`${c}\` changed after initialisation, but the SDK client is stable for the session and only re-inits on \`consent\` \u2014 the new value is ignored. Remount the provider (e.g. via a changing \`key\` prop) to apply it.`)},[e.apiKey,e.context,e.country,e.persona,u]),v(()=>{var o;typeof process!="undefined"&&((o=process.env)==null?void 0:o.NODE_ENV)==="production"||j({apiKey:e.apiKey,apiBaseUrl:u,isLocal:(t==null?void 0:t.isLocal)===!0})},[t,e.apiKey,u]),v(()=>{let o=e.initialLayoutOrder;if(o&&o.length>0){T(o);return}e.declaredSections&&e.declaredSections.length>0&&T(e.declaredSections)},[e.initialLayoutOrder,e.declaredSections]),v(()=>{if(!E())return;let o=e.declaredSections;if(!o||o.length===0||typeof document=="undefined")return;let f=new Set(Array.from(document.querySelectorAll("[data-sentient-id]"),c=>c.getAttribute("data-sentient-id"))),s=o.filter(c=>!f.has(c));s.length>0&&console.warn(`[SentientUI] Declared section${s.length>1?"s":""} ${s.map(c=>`"${c}"`).join(", ")} ${s.length>1?"have":"has"} no matching data-sentient-id element, so the layout engine cannot learn what they are and will serve the same order to every persona. Add data-sentient-id="<sectionId>" to each section's element.`)},[e.declaredSections]);let R=te(()=>t&&l?z(t):t,[t,l]),O=te(()=>{var o,f,s,c,g,S,p,h;return{client:R,apiKey:e.apiKey,initialAssignments:(o=e.initialAssignments)!=null?o:{},sessionSegment:i,ssrFallback:r,onAssignment:e.onAssignment,initialLayoutOrder:(f=e.initialLayoutOrder)!=null?f:null,initialSlots:(s=e.initialSlots)!=null?s:{},initialSlotConfig:(c=e.initialSlotConfig)!=null?c:{},initialPalette:(g=e.initialPalette)!=null?g:null,initialVocabulary:(S=e.initialVocabulary)!=null?S:null,initialPersona:(p=e.initialPersona)!=null?p:null,apiBaseUrl:u,debug:(h=e.debug)!=null?h:!1}},[R,e.apiKey,e.initialAssignments,i,r,e.onAssignment,e.initialLayoutOrder,e.initialSlots,e.initialSlotConfig,e.initialPalette,e.initialVocabulary,e.initialPersona,u,e.debug]);return ke(xe.Provider,{value:O,children:e.children})}function Ee(e){return e<.3?"low":e<.7?"medium":"high"}function oe(e={}){var n,i,l;let t=window;if(t.__sentient_overrides=m({},(n=e.variants)!=null?n:{}),e.layout?t.__sentient_layout_override=e.layout:delete t.__sentient_layout_override,e.slots?t.__sentient_slot_overrides=m({},e.slots):delete t.__sentient_slot_overrides,e.slotConfig?t.__sentient_slot_config_overrides=m({},e.slotConfig):delete t.__sentient_slot_config_overrides,e.persona){t.__sentient_persona_override={persona:e.persona,confidence:(i=e.confidence)!=null?i:1};try{let a=document.documentElement;a.setAttribute("data-sentient-persona",e.persona),a.setAttribute("data-sentient-confidence",Ee((l=e.confidence)!=null?l:1))}catch(a){}}else delete t.__sentient_persona_override;k()}import{jsx as Pe}from"react/jsx-runtime";function vt(e,t={},n){return oe(t),Ae(Pe(ie,{apiKey:"pk_test",consent:!1,children:e}),n)}export{vt as renderWithSentient};
|
|
3
3
|
//# sourceMappingURL=react.mjs.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sentientui/react",
|
|
3
|
-
"version": "0.35.
|
|
3
|
+
"version": "0.35.3",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -75,8 +75,8 @@
|
|
|
75
75
|
"llms.txt"
|
|
76
76
|
],
|
|
77
77
|
"dependencies": {
|
|
78
|
-
"@sentientui/
|
|
79
|
-
"@sentientui/
|
|
78
|
+
"@sentientui/policy": "0.12.0",
|
|
79
|
+
"@sentientui/core": "0.34.3"
|
|
80
80
|
},
|
|
81
81
|
"peerDependencies": {
|
|
82
82
|
"@testing-library/react": ">=14.0.0",
|