@sentientui/core 0.12.1 → 0.13.0

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.
@@ -0,0 +1 @@
1
+ import{b as ie,d as ae,e as le,f as ce,g as de,j as ue,k as ne,m as ge}from"./chunk-SVYHTU5Z.mjs";import{a as w,b as j}from"./chunk-HGGX55FR.mjs";var Ne="_snt_uid";var F="_snt_uid";function Me(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function Ue(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Ke(e,t,o){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${o}; SameSite=strict; path=/`}catch(c){}}function Ge(e){try{return localStorage.getItem(e)}catch(t){return null}}function $e(e,t){try{return localStorage.setItem(e,t),!0}catch(o){return!1}}function Be(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function We(e,t){try{return sessionStorage.setItem(e,t),!0}catch(o){return!1}}function je(e){try{sessionStorage.removeItem(e)}catch(t){}}function Fe(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function Je(e){try{localStorage.removeItem(e)}catch(t){}}function Qe(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Ye={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function oe(e){var l,g,f,h,b,S;if(typeof window=="undefined")return Ye;let t=(l=e==null?void 0:e.cookieName)!=null?l:Ne,c=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,u=(S=(b=(h=(f=Ue(t))!=null?f:Ge(F))!=null?h:Be(F))!=null?b:e==null?void 0:e.ssrSessionId)!=null?S:Me();Ke(t,u,c);let i=$e(F,u),a=Fe(t),s=i?!1:We(F,u),n=!i&&!a&&!s;return{getSessionId:()=>u,isEphemeral:()=>n,destroy:()=>{u=null,Qe(t),Je(F),je(F)}}}function fe(e){return`_snt_retry_${e.slice(0,12)}`}var Ve={push:()=>{},flush:()=>{},destroy:()=>{}};function ze(e,t){try{let o=localStorage.getItem(t);if(!o)return[];let c=JSON.parse(o);return Array.isArray(c)?(localStorage.removeItem(t),c.slice(-e)):[]}catch(o){return[]}}function pe(e,t,o){try{let u=[...(()=>{try{let i=localStorage.getItem(o);if(!i)return[];let a=JSON.parse(i);return Array.isArray(a)?a:[]}catch(i){return[]}})(),...e].slice(-t);localStorage.setItem(o,JSON.stringify(u))}catch(c){}}function xe(e){var z,H,q;if(typeof window=="undefined")return Ve;let t=(z=e.flushIntervalMs)!=null?z:5e3,o=(H=e.maxBatchSize)!=null?H:20,c=(q=e.maxRetrySize)!=null?q:100,u=e.ingestUrl,i=e.apiKey,a=fe(i),s=[],n=new Set,l=[],g=p=>{for(let y of p)f.delete(y),!n.has(y)&&(n.add(y),l.push(y));for(;l.length>500;){let y=l.shift();y&&n.delete(y)}},f=new Set,h=p=>{n.has(p.id)||f.has(p.id)||(f.add(p.id),s.push(p))},b=ze(c,a);for(let p of b)h(p);let S=0,A=0,k=p=>{if(p.length===0)return;let y=JSON.stringify(p),x=p.map(r=>r.id),O;try{O=fetch(u,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`}})}catch(r){pe(p,c,a);for(let d of x)f.delete(d);A++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(A,6));return}let N=r=>{if(r.ok||r.status>=400&&r.status<500&&r.status!==429){g(x),A=0,S=0;return}pe(p,c,a);for(let d of x)f.delete(d);A++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(A,6))};O instanceof Promise?O.then(N).catch(()=>{pe(p,c,a);for(let r of x)f.delete(r);A++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(A,6))}):N(O)},v=typeof TextEncoder!="undefined"?new TextEncoder:null,te=p=>v?v.encode(p).length:p.length,K=p=>{let y=[],x=2;for(let O of p){let N=te(JSON.stringify(O))+1;if(y.length>0&&x+N>57344||y.length>=o)break;y.push(O),x+=N}return y},P=()=>{try{if(Date.now()<S)return;for(;s.length>0;){let p=s.filter(x=>!n.has(x.id));if(s.length=0,p.length===0)break;let y=K(p);if(y.length===0)break;y.length<p.length&&s.push(...p.slice(y.length)),k(y)}}catch(p){}},R=!0,G=null;G=setInterval(()=>{R&&P()},t);let Y=()=>{document.visibilityState==="hidden"&&P()},V=()=>{P()};return document.addEventListener("visibilitychange",Y),window.addEventListener("beforeunload",V),{push(p){h(p),s.length>=o&&P()},flush:P,destroy(){R=!1,G!==null&&(clearInterval(G),G=null),document.removeEventListener("visibilitychange",Y),window.removeEventListener("beforeunload",V),P()}}}var ye="_snt_asgn_";function se(e,t){return`${e}:${t}`}function He(e,t){return`${ye}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function _e(e){let t=e.slice(ye.length),o=t.indexOf(":");if(o<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,o)),segment:decodeURIComponent(t.slice(o+1))}}catch(c){return null}}function me(){try{let e=[];for(let t=0;t<localStorage.length;t++){let o=localStorage.key(t);o!=null&&o.startsWith(ye)&&e.push(o)}return e}catch(e){return[]}}function Ce(e=18e5){let t=new Map,o=u=>u.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let u of me())try{let i=localStorage.getItem(u);if(!i)continue;let a=JSON.parse(i);if(o(a)){localStorage.removeItem(u);continue}let s=_e(u);if(!s)continue;t.set(se(s.componentId,s.segment),a)}catch(i){}})(),{get(u,i){let a=t.get(se(u,i));return a?o(a)?(t.delete(se(u,i)),null):a:null},set(u,i,a){let s=se(u,i);t.set(s,a);try{localStorage.setItem(He(u,i),JSON.stringify(a))}catch(n){}},invalidate(u){let i=`${u}:`;for(let a of[...t.keys()])a.startsWith(i)&&t.delete(a);for(let a of me()){let s=_e(a);if((s==null?void 0:s.componentId)===u)try{localStorage.removeItem(a)}catch(n){}}},clear(){t.clear();for(let u of me())try{localStorage.removeItem(u)}catch(i){}}}}var J="_snt_snap:",qe=["low","medium","high"];function Se(e){try{let t=localStorage.getItem(J+e);if(!t)return null;let o=JSON.parse(t);return!o||typeof o!="object"||o.v!==1||typeof o.persona!="string"||typeof o.band!="string"||!qe.includes(o.band)||typeof o.slots!="object"||o.slots===null||Array.isArray(o.slots)||!(o.layoutOrder===null||Array.isArray(o.layoutOrder))||typeof o.savedAt!="number"||!(o.slotConfig===void 0||typeof o.slotConfig=="object"&&o.slotConfig!==null&&!Array.isArray(o.slotConfig))?null:o}catch(t){return null}}function ee(e,t){try{localStorage.setItem(J+e,JSON.stringify(t))}catch(o){}}function Xe(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(J+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}import{confidenceBand as Oe}from"@sentientui/policy";import{confidenceBand as he}from"@sentientui/policy";var ve="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",ke="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",Ae=!1,re=!1;function Ze(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Re(e){var s;let t=oe({ssrSessionId:e.ssrSessionId}),o=(s=t.getSessionId())!=null?s:"local",c=Ze(),u=import("@sentientui/core/local").then(n=>{let l=n;return l.LOCAL_ENGINE_AVAILABLE?(Ae||(Ae=!0,console.info(ke)),l):(re||(re=!0,console.error(ve)),null)}).catch(()=>(re||(re=!0,console.error(ve)),null)),i=null;function a(n){let l=document.documentElement;l.dataset.sentientPersona===void 0&&(l.dataset.sentientPersona=n.persona,l.dataset.sentientConfidence=he(n.confidence))}return{isLocal:!0,async decide(n){var f,h,b;let l=await u;if(!l)return null;let g=l.createLocalEngine({sessionId:o,forcedPersona:c}).decide(n);return i=j(w({},g),{layoutOrder:(h=(f=g.layoutOrder)!=null?f:i==null?void 0:i.layoutOrder)!=null?h:null,slots:w(w({},(b=i==null?void 0:i.slots)!=null?b:{}),g.slots)}),ee(e.apiKey||"local",{v:1,persona:i.persona,band:he(i.confidence),slots:i.slots,layoutOrder:i.layoutOrder,savedAt:Date.now()}),a(g),g},getSlotResult(n){var l,g,f;return(f=(g=i==null?void 0:i.slots[n])!=null?g:(l=e.initialSlots)==null?void 0:l[n])!=null?f:null},getPersona(){return i?{persona:i.persona,confidence:i.confidence,band:he(i.confidence)}:null},async assign(n,l){var h;let g=await u;return!g||!l||l.length===0?l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null:{variantId:(h=g.createLocalEngine({sessionId:o,forcedPersona:c}).decide({components:[{id:n,variantIds:l}]}).assignments[n])!=null?h:l[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function et(e,t,o){var u;let c=[];{let s=!1,n=[],l=()=>{if(s)return;let g=Date.now();for(n.push(g);n.length>0&&g-n[0]>500;)n.shift();n.length>=3&&(s=!0,e("rage_click"))};t.addEventListener("click",l),c.push(()=>t.removeEventListener("click",l))}{let i=!1,a=s=>{if(i||!(s.target instanceof Node)||!t.contains(s.target)&&t!==s.target)return;i=!0;let n=typeof window!="undefined"?window.getSelection():null,l=n?n.toString().length:0;e("text_copy",{selectionLength:l})};document.addEventListener("copy",a),c.push(()=>document.removeEventListener("copy",a))}{let i=!1,a=!1,s=null,n=()=>{s!==null&&(clearTimeout(s),s=null)},l=()=>{i||!a||(n(),s=setTimeout(()=>{!i&&a&&(i=!0,e("scroll_hesitation"))},3e3))},g=()=>{n(),l()},f=b=>{for(let S of b)a=S.intersectionRatio>.3,a?l():n()};typeof process!="undefined"&&((u=process.env)==null?void 0:u.NODE_ENV)!=="production"&&(window.__lastIOCallback=f);let h=new IntersectionObserver(f,{threshold:[.3]});h.observe(t),window.addEventListener("scroll",g,{passive:!0}),c.push(()=>{h.disconnect(),window.removeEventListener("scroll",g),n()})}{let i=!1,a=o!=null?o:Date.now(),s=()=>{if(i||document.visibilityState!=="hidden")return;let n=Date.now()-a;n<15e3&&(i=!0,e("tab_loss",{timeOnPage:n}))};document.addEventListener("visibilitychange",s),c.push(()=>document.removeEventListener("visibilitychange",s))}return()=>{for(let i of c)i()}}var De="https://api.sentient-ui.com/v1/events",B=new Map,Te=null;function Ee(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var Q={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function tt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[o,c]of t)o.startsWith("utm_")&&(e[o]=c);return e}catch(e){return{}}}function Pe(e){return e.replace(/\/events\/?$/,"")}function Le(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function Ct(e){if(typeof window=="undefined")return;let t=e!=null?e:Te;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let o=B.get(t);if(!o){console.warn("[sentient] grantConsent() called before init()");return}let{config:c,upgrade:u}=o;if(!u||c.respectDoNotTrack!==!1&&Le())return;let i=ot(j(w({},c),{consent:!0}));u(i),B.set(t,{config:j(w({},c),{consent:!0}),upgrade:null})}function nt(e){var a;let t=Pe((a=e.ingestUrl)!=null?a:De),o={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},c={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(s,n,l){try{let g=new URLSearchParams({componentId:s});for(let b of n!=null?n:[])g.append("variantIds[]",b);let f=await fetch(`${t}/winner?${g.toString()}`,{headers:o});return f.ok?{variantId:(await f.json()).variantId,assignmentTtlMs:0}:n!=null&&n[0]?{variantId:n[0],assignmentTtlMs:0}:null}catch(g){return n!=null&&n[0]?{variantId:n[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},u={track:s=>c.track(s),goal:(s,n,l,g)=>c.goal(s,n,l,g),componentGoal:(s,n,l)=>c.componentGoal(s,n,l),identify:s=>c.identify(s),getAssignment:(s,n)=>c.getAssignment(s,n),assign:(s,n,l,g)=>c.assign(s,n,l,g),decide:s=>c.decide(s),getSlotResult:s=>c.getSlotResult(s),getPersona:()=>c.getPersona(),fetchWeights:()=>c.fetchWeights(),getGraph:()=>c.getGraph(),dispose:()=>c.dispose(),destroy:()=>c.destroy()};function i(s){c=s}return{proxy:u,setInner:i}}function ot(e){var V,z,H,q,p,y,x,O,N;if(typeof window=="undefined")return Q;Te=e.apiKey;let t=e.respectDoNotTrack!==!1&&Le(),o=e.consent===!1||t,c=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!c&&e.localMode!==!1)return o?(B.set(e.apiKey||"local",{config:e,upgrade:null}),Q):(B.set(e.apiKey||"local",{config:e,upgrade:null}),Re(e));if(o){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),Q;let{proxy:r,setInner:d}=nt(e);return B.set(e.apiKey,{config:e,upgrade:t?null:d}),r}return B.set(e.apiKey,{config:e,upgrade:null}),Q}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),Q;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),Q;let u=(V=e.ingestUrl)!=null?V:De,i=Date.now(),a=oe({ssrSessionId:e.ssrSessionId}),s=Ce(),n=xe({ingestUrl:u,apiKey:e.apiKey}),l=Pe(u),g={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},f=ae((z=navigator.userAgent)!=null?z:""),h=typeof window!="undefined"?window.location.origin:void 0,b=le((H=document.referrer)!=null?H:"",h),S=(q=e.sessionSegment)!=null?q:`${f}:${b}`,A=new Map,k=new Map,v=null,te=r=>{for(let d of r)k.has(d.id)||k.set(d.id,ne(d))};if(e.initialSlots)for(let[r,d]of Object.entries(e.initialSlots))k.set(r,d);let K=Se(e.apiKey);if(K)for(let[r,d]of Object.entries(K.slots))k.has(r)||k.set(r,d);let P={low:.15,medium:.5,high:.85};if(e.initialPersona)v=w({},e.initialPersona);else{let r=document.documentElement.dataset;r.sentientPersona?v={persona:r.sentientPersona,confidence:(y=P[(p=r.sentientConfidence)!=null?p:"low"])!=null?y:.15}:K&&(v={persona:K.persona,confidence:(x=P[K.band])!=null?x:.15})}if(e.initialAssignments)for(let[r,d]of Object.entries(e.initialAssignments))s.set(r,S,{variantId:d,assignedAt:Date.now(),segment:S,confidence:1});let R=Promise.resolve(),G=a.getSessionId();if(G){let r=ce((O=document.referrer)!=null?O:""),d=w(w({sessionId:G,deviceClass:f,trafficSource:b,referrerDomain:r,utmParams:tt(),timeOfDay:de(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:a.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||ie((N=navigator.userAgent)!=null?N:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{R=fetch(`${l}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(d),headers:g}).then(m=>{m.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(m){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:n});let Y={goal(r,d={},m=1,D=0){let I=a.getSessionId();if(!I)return;let _=Ee();R.then(()=>{fetch(`${l}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:I,name:r,metadata:d,weight:m,stepIndex:D,goalId:_}),headers:g}).catch(()=>{})})},componentGoal(r,d,m){var T,U,L;let D=a.getSessionId();if(!D)return;let I=s.get(r,S),_=I?null:(T=k.get(r))!=null?T:null;if(!I&&_===null){e.debug&&console.warn(`[sentient] componentGoal("${r}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let $=I?I.variantId:ge(_),M={id:Ee(),sessionId:D,projectId:e.apiKey,componentId:r,variantId:$,eventType:"goal_achieved",goalType:d,payload:w({reward:(U=m==null?void 0:m.reward)!=null?U:1},(L=m==null?void 0:m.metadata)!=null?L:{}),timestamp:Date.now(),timeInSession:Date.now()-i};e.debug&&console.log("[sentient] componentGoal",M),R.then(()=>n.push(M))},identify(r){let d=a.getSessionId();d&&R.then(()=>{fetch(`${l}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:d,userId:r,ephemeral:a.isEphemeral()}),headers:g}).catch(()=>{})})},track(r){let d=a.getSessionId();if(!d)return;let m=j(w({},r),{id:Ee(),sessionId:d,timestamp:Date.now(),timeInSession:Date.now()-i});e.debug&&console.log("[sentient] track",m),R.then(()=>n.push(m))},getAssignment(r,d){return s.get(r,d)},async assign(r,d,m,D){let I=a.getSessionId();if(!I)return null;let _=s.get(r,S);if(_&&(d!=null&&d.length||_.content!==void 0))return{variantId:_.variantId,assignmentTtlMs:0,content:_.content};let $=A.get(r);if($)return $;let M=(async()=>{await R;try{let T={sessionId:I,componentId:r,variantIds:d};D!==void 0?T.agentDataByVariant=D:m!==void 0&&(T.agentData=m);let U=await fetch(`${l}/assign`,{method:"POST",body:JSON.stringify(T),headers:g});if(!U.ok)return null;let L=await U.json();return s.set(r,S,{variantId:L.variantId,assignedAt:Date.now(),segment:S,confidence:1,content:L.content}),L}catch(T){return null}finally{A.delete(r)}})();return A.set(r,M),M},async decide(r){var D,I,_,$,M,T,U,L,we,be;let d=a.getSessionId();if(!d)return null;let m=(D=r.slots)!=null?D:[];await R;try{let W={sessionId:d};r.sections&&r.sections.length>0&&(W.sections=r.sections.map(C=>({id:C}))),W.components=(I=r.components)!=null?I:[],m.length>0&&(W.slots=m.map(ue)),r.slotsFrom==="registry"&&(W.slotsFrom="registry");let Ie=await fetch(`${l}/decide`,{method:"POST",body:JSON.stringify(W),headers:g});if(!Ie.ok)return te(m),null;let E=await Ie.json(),X={};for(let C of m)X[C.id]=($=(_=E.slots)==null?void 0:_[C.id])!=null?$:ne(C);if(E.slots)for(let[C,Z]of Object.entries(E.slots))C in X||(X[C]=Z);for(let[C,Z]of Object.entries(X))k.set(C,Z);v={persona:(M=E.persona)!=null?M:"unknown",confidence:(T=E.confidence)!=null?T:0};for(let[C,Z]of Object.entries((U=E.assignments)!=null?U:{}))s.set(C,S,{variantId:Z,assignedAt:Date.now(),segment:S,confidence:1});return ee(e.apiKey,w({v:1,persona:v.persona,band:Oe(v.confidence),slots:Object.fromEntries(k),layoutOrder:(L=E.layoutOrder)!=null?L:null,savedAt:Date.now()},E.slotConfig?{slotConfig:E.slotConfig}:{})),w(w({layoutOrder:(we=E.layoutOrder)!=null?we:null,assignments:(be=E.assignments)!=null?be:{},slots:X,persona:v.persona,confidence:v.confidence},E.slotConfig?{slotConfig:E.slotConfig}:{}),E.goals?{goals:E.goals}:{})}catch(W){return te(m),null}},getSlotResult(r){var d;return(d=k.get(r))!=null?d:null},getPersona(){return v?{persona:v.persona,confidence:v.confidence,band:Oe(v.confidence)}:null},async fetchWeights(){var r;try{let d=await fetch(`${l}/weights`,{headers:g});return d.ok?(r=(await d.json()).components)!=null?r:[]:[]}catch(d){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){n.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){n.destroy(),a.destroy();try{localStorage.removeItem(J+e.apiKey),localStorage.removeItem(fe(e.apiKey))}catch(r){}e.debug&&console.log("[sentient] destroyed")}};if(B.set(e.apiKey,{config:e,upgrade:null}),e.debug){let r=window;r.__sentient&&(r.__sentient.client=Y)}return Y}export{J as a,Se as b,ee as c,Xe as d,ve as e,ke as f,et as g,Le as h,Ct as i,ot as j};
@@ -1 +1 @@
1
- "use strict";var qe=Object.create;var te=Object.defineProperty,Xe=Object.defineProperties,Ze=Object.getOwnPropertyDescriptor,et=Object.getOwnPropertyDescriptors,tt=Object.getOwnPropertyNames,De=Object.getOwnPropertySymbols,nt=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty,ot=Object.prototype.propertyIsEnumerable;var Ne=(e,t,n)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,w=(e,t)=>{for(var n in t||(t={}))Pe.call(t,n)&&Ne(e,n,t[n]);if(De)for(var n of De(t))ot.call(t,n)&&Ne(e,n,t[n]);return e},B=(e,t)=>Xe(e,et(t));var rt=(e,t)=>{for(var n in t)te(e,n,{get:t[n],enumerable:!0})},Le=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of tt(t))!Pe.call(e,d)&&d!==n&&te(e,d,{get:()=>t[d],enumerable:!(c=Ze(t,d))||c.enumerable});return e};var st=(e,t,n)=>(n=e!=null?qe(nt(e)):{},Le(t||!e||!e.__esModule?te(n,"default",{value:e,enumerable:!0}):n,e)),it=e=>Le(te({},"__esModule",{value:!0}),e);var Qt={};rt(Qt,{deriveSessionSegment:()=>ve,detectDeviceClass:()=>F,detectTimeOfDay:()=>z,detectTrafficSource:()=>W,init:()=>Ht,referrerDomainFromReferer:()=>J});module.exports=it(Qt);var at="_snt_uid";var j="_snt_uid";function ct(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function dt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function lt(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(c){}}function ut(e){try{return localStorage.getItem(e)}catch(t){return null}}function gt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function pt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ft(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function mt(e){try{sessionStorage.removeItem(e)}catch(t){}}function yt(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function ht(e){try{localStorage.removeItem(e)}catch(t){}}function St(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var vt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ie(e){var a,l,g,y,f,m;if(typeof window=="undefined")return vt;let t=(a=e==null?void 0:e.cookieName)!=null?a:at,c=((l=e==null?void 0:e.cookieTTLDays)!=null?l:365)*24*60*60,d=(m=(f=(y=(g=dt(t))!=null?g:ut(j))!=null?y:pt(j))!=null?f:e==null?void 0:e.ssrSessionId)!=null?m:ct();lt(t,d,c);let s=gt(j,d),o=yt(t),r=s?!1:ft(j,d),i=!s&&!o&&!r;return{getSessionId:()=>d,isEphemeral:()=>i,destroy:()=>{d=null,St(t),ht(j),mt(j)}}}function ye(e){return`_snt_retry_${e.slice(0,12)}`}var Et={push:()=>{},flush:()=>{},destroy:()=>{}};function bt(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let c=JSON.parse(n);return Array.isArray(c)?(localStorage.removeItem(t),c.slice(-e)):[]}catch(n){return[]}}function me(e,t,n){try{let d=[...(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let o=JSON.parse(s);return Array.isArray(o)?o:[]}catch(s){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(d))}catch(c){}}function Me(e){var q,X,Z;if(typeof window=="undefined")return Et;let t=(q=e.flushIntervalMs)!=null?q:5e3,n=(X=e.maxBatchSize)!=null?X:20,c=(Z=e.maxRetrySize)!=null?Z:100,d=e.ingestUrl,s=e.apiKey,o=ye(s),r=[],i=new Set,a=[],l=h=>{for(let v of h)g.delete(v),!i.has(v)&&(i.add(v),a.push(v));for(;a.length>500;){let v=a.shift();v&&i.delete(v)}},g=new Set,y=h=>{i.has(h.id)||g.has(h.id)||(g.add(h.id),r.push(h))},f=bt(c,o);for(let h of f)y(h);let m=0,E=0,I=h=>{if(h.length===0)return;let v=JSON.stringify(h),x=h.map(u=>u.id),T;try{T=fetch(d,{method:"POST",keepalive:!0,body:v,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(u){me(h,c,o);for(let p of x)g.delete(p);E++,m=Date.now()+Math.min(6e4,1e3*2**Math.min(E,6));return}let P=u=>{if(u.ok||u.status>=400&&u.status<500&&u.status!==429){l(x),E=0,m=0;return}me(h,c,o);for(let p of x)g.delete(p);E++,m=Date.now()+Math.min(6e4,1e3*2**Math.min(E,6))};T instanceof Promise?T.then(P).catch(()=>{me(h,c,o);for(let u of x)g.delete(u);E++,m=Date.now()+Math.min(6e4,1e3*2**Math.min(E,6))}):P(T)},b=typeof TextEncoder!="undefined"?new TextEncoder:null,se=h=>b?b.encode(h).length:h.length,U=h=>{let v=[],x=2;for(let T of h){let P=se(JSON.stringify(T))+1;if(v.length>0&&x+P>57344||v.length>=n)break;v.push(T),x+=P}return v},k=()=>{try{if(Date.now()<m)return;for(;r.length>0;){let h=r.filter(x=>!i.has(x.id));if(r.length=0,h.length===0)break;let v=U(h);if(v.length===0)break;v.length<h.length&&r.push(...h.slice(v.length)),I(v)}}catch(h){}},_=!0,G=null;G=setInterval(()=>{_&&k()},t);let Y=()=>{document.visibilityState==="hidden"&&k()},V=()=>{k()};return document.addEventListener("visibilitychange",Y),window.addEventListener("beforeunload",V),{push(h){y(h),r.length>=n&&k()},flush:k,destroy(){_=!1,G!==null&&(clearInterval(G),G=null),document.removeEventListener("visibilitychange",Y),window.removeEventListener("beforeunload",V),k()}}}var Se="_snt_asgn_";function ae(e,t){return`${e}:${t}`}function wt(e,t){return`${Se}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ue(e){let t=e.slice(Se.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(c){return null}}function he(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(Se)&&e.push(n)}return e}catch(e){return[]}}function Ge(e=18e5){let t=new Map,n=d=>d.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let d of he())try{let s=localStorage.getItem(d);if(!s)continue;let o=JSON.parse(s);if(n(o)){localStorage.removeItem(d);continue}let r=Ue(d);if(!r)continue;t.set(ae(r.componentId,r.segment),o)}catch(s){}})(),{get(d,s){let o=t.get(ae(d,s));return o?n(o)?(t.delete(ae(d,s)),null):o:null},set(d,s,o){let r=ae(d,s);t.set(r,o);try{localStorage.setItem(wt(d,s),JSON.stringify(o))}catch(i){}},invalidate(d){let s=`${d}:`;for(let o of[...t.keys()])o.startsWith(s)&&t.delete(o);for(let o of he()){let r=Ue(o);if((r==null?void 0:r.componentId)===d)try{localStorage.removeItem(o)}catch(i){}}},clear(){t.clear();for(let d of he())try{localStorage.removeItem(d)}catch(s){}}}}var Ke=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function ce(e){return $e(e)!==null}function $e(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ke.find(c=>t.includes(c.toLowerCase())))!=null?n:null}function F(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function W(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(d){}let c=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(c)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(c)?"social":"referral"}catch(n){return"direct"}}function J(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function z(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function ve(e){let t=It("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function It(e,t){var s,o,r,i,a,l,g;let n=(o=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?o:"",c=(i=(r=t==null?void 0:t.referer)==null?void 0:r.trim())!=null?i:"",d=(a=t==null?void 0:t.now)!=null?a:new Date;return{sessionId:e,ephemeral:!1,utmParams:(l=t==null?void 0:t.utmParams)!=null?l:{},deviceClass:n?F(n):"desktop",trafficSource:c?W(c,t==null?void 0:t.appOrigin):"direct",referrerDomain:J(c),timeOfDay:z(d),dayOfWeek:(g=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?g:"sun",automation:(t==null?void 0:t.webdriver)===!0||ce(n)}}var H=require("@sentientui/policy");function de(e){return w(w(w({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function le(e){let t=de(e);return(0,H.slotResultFor)(t,(0,H.slotBaselineArm)(t))}function Ee(e){return typeof e=="string"?e:(0,H.canonicalArm)(e)}var ne="_snt_snap:",Ct=["low","medium","high"];function be(e){try{let t=localStorage.getItem(ne+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!Ct.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"?null:n}catch(t){return null}}function oe(e,t){try{localStorage.setItem(ne+e,JSON.stringify(t))}catch(n){}}var Ce=require("@sentientui/policy");var ge=require("@sentientui/policy");var we="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",je="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",Be=!1,ue=!1;function xt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Fe(e){var r;let t=ie({ssrSessionId:e.ssrSessionId}),n=(r=t.getSessionId())!=null?r:"local",c=xt(),d=import("@sentientui/core/local").then(i=>{let a=i;return a.LOCAL_ENGINE_AVAILABLE?(Be||(Be=!0,console.info(je)),a):(ue||(ue=!0,console.error(we)),null)}).catch(()=>(ue||(ue=!0,console.error(we)),null)),s=null;function o(i){let a=document.documentElement;a.dataset.sentientPersona===void 0&&(a.dataset.sentientPersona=i.persona,a.dataset.sentientConfidence=(0,ge.confidenceBand)(i.confidence))}return{isLocal:!0,async decide(i){var g,y,f;let a=await d;if(!a)return null;let l=a.createLocalEngine({sessionId:n,forcedPersona:c}).decide(i);return s=B(w({},l),{layoutOrder:(y=(g=l.layoutOrder)!=null?g:s==null?void 0:s.layoutOrder)!=null?y:null,slots:w(w({},(f=s==null?void 0:s.slots)!=null?f:{}),l.slots)}),oe(e.apiKey||"local",{v:1,persona:s.persona,band:(0,ge.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),o(l),l},getSlotResult(i){var a,l,g;return(g=(l=s==null?void 0:s.slots[i])!=null?l:(a=e.initialSlots)==null?void 0:a[i])!=null?g:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,ge.confidenceBand)(s.confidence)}:null},async assign(i,a){var y;let l=await d;return!l||!a||a.length===0?a!=null&&a[0]?{variantId:a[0],assignmentTtlMs:0}:null:{variantId:(y=l.createLocalEngine({sessionId:n,forcedPersona:c}).decide({components:[{id:i,variantIds:a}]}).assignments[i])!=null?y:a[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var We="https://api.sentient-ui.com/v1/events",re=new Map,At=null;function Ie(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var Q={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function _t(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,c]of t)n.startsWith("utm_")&&(e[n]=c);return e}catch(e){return{}}}function Je(e){return e.replace(/\/events\/?$/,"")}function xe(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function Tt(e){var o;let t=Je((o=e.ingestUrl)!=null?o:We),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},c={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(r,i,a){try{let l=new URLSearchParams({componentId:r});for(let f of i!=null?i:[])l.append("variantIds[]",f);let g=await fetch(`${t}/winner?${l.toString()}`,{headers:n});return g.ok?{variantId:(await g.json()).variantId,assignmentTtlMs:0}:i!=null&&i[0]?{variantId:i[0],assignmentTtlMs:0}:null}catch(l){return i!=null&&i[0]?{variantId:i[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},d={track:r=>c.track(r),goal:(r,i,a,l)=>c.goal(r,i,a,l),componentGoal:(r,i,a)=>c.componentGoal(r,i,a),identify:r=>c.identify(r),getAssignment:(r,i)=>c.getAssignment(r,i),assign:(r,i,a,l)=>c.assign(r,i,a,l),decide:r=>c.decide(r),getSlotResult:r=>c.getSlotResult(r),getPersona:()=>c.getPersona(),fetchWeights:()=>c.fetchWeights(),getGraph:()=>c.getGraph(),dispose:()=>c.dispose(),destroy:()=>c.destroy()};function s(r){c=r}return{proxy:d,setInner:s}}function ze(e){var V,q,X,Z,h,v,x,T,P;if(typeof window=="undefined")return Q;At=e.apiKey;let t=e.respectDoNotTrack!==!1&&xe(),n=e.consent===!1||t,c=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!c&&e.localMode!==!1)return n?(re.set(e.apiKey||"local",{config:e,upgrade:null}),Q):(re.set(e.apiKey||"local",{config:e,upgrade:null}),Fe(e));if(n){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),Q;let{proxy:u,setInner:p}=Tt(e);return re.set(e.apiKey,{config:e,upgrade:t?null:p}),u}return re.set(e.apiKey,{config:e,upgrade:null}),Q}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),Q;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),Q;let d=(V=e.ingestUrl)!=null?V:We,s=Date.now(),o=ie({ssrSessionId:e.ssrSessionId}),r=Ge(),i=Me({ingestUrl:d,apiKey:e.apiKey}),a=Je(d),l={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=F((q=navigator.userAgent)!=null?q:""),y=typeof window!="undefined"?window.location.origin:void 0,f=W((X=document.referrer)!=null?X:"",y),m=(Z=e.sessionSegment)!=null?Z:`${g}:${f}`,E=new Map,I=new Map,b=null,se=u=>{for(let p of u)I.has(p.id)||I.set(p.id,le(p))};if(e.initialSlots)for(let[u,p]of Object.entries(e.initialSlots))I.set(u,p);let U=be(e.apiKey);if(U)for(let[u,p]of Object.entries(U.slots))I.has(u)||I.set(u,p);let k={low:.15,medium:.5,high:.85};if(e.initialPersona)b=w({},e.initialPersona);else{let u=document.documentElement.dataset;u.sentientPersona?b={persona:u.sentientPersona,confidence:(v=k[(h=u.sentientConfidence)!=null?h:"low"])!=null?v:.15}:U&&(b={persona:U.persona,confidence:(x=k[U.band])!=null?x:.15})}if(e.initialAssignments)for(let[u,p]of Object.entries(e.initialAssignments))r.set(u,m,{variantId:p,assignedAt:Date.now(),segment:m,confidence:1});let _=Promise.resolve(),G=o.getSessionId();if(G){let u=J((T=document.referrer)!=null?T:""),p=w(w({sessionId:G,deviceClass:g,trafficSource:f,referrerDomain:u,utmParams:_t(),timeOfDay:z(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||ce((P=navigator.userAgent)!=null?P:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{_=fetch(`${a}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(p),headers:l}).then(S=>{S.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(S){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:i});let Y={goal(u,p={},S=1,R=0){let C=o.getSessionId();if(!C)return;let A=Ie();_.then(()=>{fetch(`${a}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:C,name:u,metadata:p,weight:S,stepIndex:R,goalId:A}),headers:l}).catch(()=>{})})},componentGoal(u,p,S){var O,M,D;let R=o.getSessionId();if(!R)return;let C=r.get(u,m),A=C?null:(O=I.get(u))!=null?O:null;if(!C&&A===null){e.debug&&console.warn(`[sentient] componentGoal("${u}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let K=C?C.variantId:Ee(A),L={id:Ie(),sessionId:R,projectId:e.apiKey,componentId:u,variantId:K,eventType:"goal_achieved",goalType:p,payload:w({reward:(M=S==null?void 0:S.reward)!=null?M:1},(D=S==null?void 0:S.metadata)!=null?D:{}),timestamp:Date.now(),timeInSession:Date.now()-s};e.debug&&console.log("[sentient] componentGoal",L),_.then(()=>i.push(L))},identify(u){let p=o.getSessionId();p&&_.then(()=>{fetch(`${a}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:p,userId:u,ephemeral:o.isEphemeral()}),headers:l}).catch(()=>{})})},track(u){let p=o.getSessionId();if(!p)return;let S=B(w({},u),{id:Ie(),sessionId:p,timestamp:Date.now(),timeInSession:Date.now()-s});e.debug&&console.log("[sentient] track",S),_.then(()=>i.push(S))},getAssignment(u,p){return r.get(u,p)},async assign(u,p,S,R){let C=o.getSessionId();if(!C)return null;let A=r.get(u,m);if(A&&(p!=null&&p.length||A.content!==void 0))return{variantId:A.variantId,assignmentTtlMs:0,content:A.content};let K=E.get(u);if(K)return K;let L=(async()=>{await _;try{let O={sessionId:C,componentId:u,variantIds:p};R!==void 0?O.agentDataByVariant=R:S!==void 0&&(O.agentData=S);let M=await fetch(`${a}/assign`,{method:"POST",body:JSON.stringify(O),headers:l});if(!M.ok)return null;let D=await M.json();return r.set(u,m,{variantId:D.variantId,assignedAt:Date.now(),segment:m,confidence:1,content:D.content}),D}catch(O){return null}finally{E.delete(u)}})();return E.set(u,L),L},async decide(u){var R,C,A,K,L,O,M,D,Re,Oe;let p=o.getSessionId();if(!p)return null;let S=(R=u.slots)!=null?R:[];await _;try{let ee={sessionId:p};u.sections&&u.sections.length>0&&(ee.sections=u.sections.map(N=>({id:N}))),ee.components=(C=u.components)!=null?C:[],S.length>0&&(ee.slots=S.map(de));let ke=await fetch(`${a}/decide`,{method:"POST",body:JSON.stringify(ee),headers:l});if(!ke.ok)return se(S),null;let $=await ke.json(),pe={};for(let N of S)pe[N.id]=(K=(A=$.slots)==null?void 0:A[N.id])!=null?K:le(N);for(let[N,fe]of Object.entries(pe))I.set(N,fe);b={persona:(L=$.persona)!=null?L:"unknown",confidence:(O=$.confidence)!=null?O:0};for(let[N,fe]of Object.entries((M=$.assignments)!=null?M:{}))r.set(N,m,{variantId:fe,assignedAt:Date.now(),segment:m,confidence:1});return oe(e.apiKey,{v:1,persona:b.persona,band:(0,Ce.confidenceBand)(b.confidence),slots:Object.fromEntries(I),layoutOrder:(D=$.layoutOrder)!=null?D:null,savedAt:Date.now()}),{layoutOrder:(Re=$.layoutOrder)!=null?Re:null,assignments:(Oe=$.assignments)!=null?Oe:{},slots:pe,persona:b.persona,confidence:b.confidence}}catch(ee){return se(S),null}},getSlotResult(u){var p;return(p=I.get(u))!=null?p:null},getPersona(){return b?{persona:b.persona,confidence:b.confidence,band:(0,Ce.confidenceBand)(b.confidence)}:null},async fetchWeights(){var u;try{let p=await fetch(`${a}/weights`,{headers:l});return p.ok?(u=(await p.json()).components)!=null?u:[]:[]}catch(p){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){i.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){i.destroy(),o.destroy();try{localStorage.removeItem(ne+e.apiKey),localStorage.removeItem(ye(e.apiKey))}catch(u){}e.debug&&console.log("[sentient] destroyed")}};if(re.set(e.apiKey,{config:e,upgrade:null}),e.debug){let u=window;u.__sentient&&(u.__sentient.client=Y)}return Y}var Rt=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Ot="h1, h2, h3",kt={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function Ae(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Dt(e){var t,n,c;try{let d=e;for(let s of Object.keys(d)){if(!s.startsWith("__reactFiber")&&!s.startsWith("__reactInternalInstance"))continue;let o=d[s],r=(c=(t=o==null?void 0:o.type)==null?void 0:t.displayName)!=null?c:(n=o==null?void 0:o.type)==null?void 0:n.name;if(r&&r.length>1)return r}}catch(d){}}function Nt(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function Pt(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function Lt(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function Mt(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function _e(e,t){var c,d,s;let n=e.querySelector(Ot);return{componentId:Lt(e),semanticType:Pt(e),ariaLabel:(c=e.getAttribute("aria-label"))!=null?c:void 0,headingText:(s=(d=n==null?void 0:n.textContent)==null?void 0:d.trim())!=null?s:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Mt(e),reactComponentName:Dt(e),dataAttributes:Nt(e)}}function He(e){var s;let t=[],n=new Set,c="__root__",d=new Map;for(let[o,r]of e){let i=o.parentElement,a=c;for(;i;){if(e.has(i)){a=e.get(i);let g=e.get(o),y=`${a}->${g}`;!n.has(y)&&a!==g&&(n.add(y),t.push({fromComponentId:a,toComponentId:g,weight:.6}));break}i=i.parentElement}let l=(s=d.get(a))!=null?s:[];l.push(o),d.set(a,l)}for(let o of d.values())if(!(o.length<2))for(let r=0;r<o.length;r++)for(let i=r+1;i<o.length;i++){let a=e.get(o[r]),l=e.get(o[i]);if(a===l)continue;let g=`${a}->${l}::sib`,y=`${l}->${a}::sib`;n.has(g)||(n.add(g),t.push({fromComponentId:a,toComponentId:l,weight:.3})),n.has(y)||(n.add(y),t.push({fromComponentId:l,toComponentId:a,weight:.3}))}return t}function Ut(e){let t=[],n=new Set,c=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(o=>{if(o instanceof Element&&!n.has(o)){n.add(o);let r=_e(o,e);t.push(r),c.set(o,r.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(o=>{if(!(o instanceof Element)||n.has(o))return;let r=o.hasAttribute("aria-label"),i=o.hasAttribute("data-sentient-id");if(!r&&!i)return;n.add(o);let a=_e(o,e);t.push(a),c.set(o,a.componentId)}),{nodes:t,edges:He(c)}}function Qe(){if(typeof window=="undefined")return kt;let e=null,t=0,n=null,c=r=>{try{let i=window.getComputedStyle(r),a=parseFloat(i.fontSize)||12,l=parseFloat(i.zIndex)||0,g=r.getBoundingClientRect(),y=Math.max(g.top,0),f=window.innerHeight||1,m=1/(y/f+1),E=Ae(a,12,48)*.4+Ae(m,0,1)*.4+Ae(l,0,100)*.2;return Math.max(0,Math.min(1,E))}catch(i){return .5}};return{scan:()=>new Promise(r=>{let i=()=>{let{nodes:a,edges:l}=Ut(c);r({nodes:a,edges:l,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(i,{timeout:100}):i()}catch(a){i()}}),observe:r=>{n=r;try{e=new MutationObserver(i=>{let a=[],l=new Map;for(let g of i)g.type==="childList"&&g.addedNodes.forEach(y=>{if(!(y instanceof Element)||!Rt.has(y.tagName))return;let f=y.hasAttribute("data-sentient-id"),m=y.hasAttribute("aria-label");if(!f&&!m)return;let E=_e(y,c);a.push(E),l.set(y,E.componentId)});a.length>0&&n&&n({nodes:a,edges:He(l),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(i){}},getProminenceScore:c,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(r){}t=0,n=null}}}var Te="_snt_graph_nodes",Ye="_snt_graph_edges",Gt={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function Kt(e){var t;return(t=Gt[e])!=null?t:[]}function $t(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function Bt(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var jt=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function Ft(e){return jt.has(e)?e:"generic"}function Wt(e,t,n){let c=`${e}:${t}:${n.join(",")}`,d=5381;for(let s=0;s<c.length;s++)d=(d<<5)+d+c.charCodeAt(s)&4294967295;return(d>>>0).toString(16).padStart(8,"0")}function Ve(e){let t=new Map,n=new Map,c=()=>{typeof window!="undefined"&&Bt(Te,[...t.values()])},d=s=>{var o;try{let r=JSON.parse(s);t.clear();for(let i of(o=r.pageNodes)!=null?o:[])t.set(i.componentId,i)}catch(r){}};if(typeof window!="undefined"){let s=$t(Te,[]);for(let o of s)t.set(o.componentId,o);try{localStorage.removeItem(Ye)}catch(o){}}return{addPageNode(s){t.set(s.componentId,s),c()},addStructuralEdge(s){let o=`${s.fromComponentId}->${s.toComponentId}`;n.set(o,s)},syncOnce(){var o,r;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let s=[...t.values()];if(s.length!==0)try{let i=new Map;for(let f of s){let m=(o=i.get(f.semanticType))!=null?o:[];m.push(f),i.set(f.semanticType,m)}let a=[],l=new Set;for(let f of s)for(let m of Kt(f.semanticType)){let E=(r=i.get(m))!=null?r:[];for(let I of E){if(I.componentId===f.componentId)continue;let b=`semantic:${f.componentId}->${I.componentId}`;l.has(b)||(l.add(b),a.push({fromComponentId:f.componentId,toComponentId:I.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(s.map(f=>f.componentId));for(let f of n.values()){if(!g.has(f.fromComponentId)||!g.has(f.toComponentId))continue;let m=`structural:${f.fromComponentId}->${f.toComponentId}`;l.has(m)||(l.add(m),a.push({fromComponentId:f.fromComponentId,toComponentId:f.toComponentId,type:"structural",weight:f.weight,confidence:1}))}let y={pageUrl:window.location.href,nodes:s.map(f=>{let m=Ft(f.semanticType);return{componentId:f.componentId,semanticType:m,answers:f.answers,contentHash:Wt(f.componentId,m,f.answers),prominenceScore:f.prominenceScore,depthInPage:f.depth}}),edges:a};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:w({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(y)}).catch(()=>{})}catch(i){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:d,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(Te),localStorage.removeItem(Ye)}catch(s){}}}}var Jt="https://api.sentient-ui.com/v1/events";function zt(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function Ht(e){var a;let t=ze(e),n=e.respectDoNotTrack!==!1&&xe(),c=e.consent===!1||n;if(!e.graph||c||typeof window=="undefined")return t;let d=Qe(),s=(a=e.ingestUrl)!=null?a:Jt,o=Ve({syncUrl:s.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:zt()});try{let l=localStorage.getItem("_snt_graph_nodes");l&&o.restore(JSON.stringify({pageNodes:JSON.parse(l)}))}catch(l){}d.scan().then(l=>{for(let g of l.nodes)o.addPageNode({id:g.componentId,componentId:g.componentId,semanticType:g.semanticType,answers:g.headingText?[g.headingText]:[],prominenceScore:g.prominenceScore,depth:g.depth});for(let g of l.edges)o.addStructuralEdge(g);o.syncOnce()});let r=null,i=()=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{r=null,o.syncOnce()},500)};return d.observe(l=>{for(let g of l.nodes)o.addPageNode({id:g.componentId,componentId:g.componentId,semanticType:g.semanticType,answers:g.headingText?[g.headingText]:[],prominenceScore:g.prominenceScore,depth:g.depth});for(let g of l.edges)o.addStructuralEdge(g);i()}),B(w({},t),{getGraph:()=>o.snapshot(),dispose:()=>{r!==null&&clearTimeout(r),d.destroy(),o.destroy(),t.dispose()},destroy:()=>{r!==null&&clearTimeout(r),d.destroy(),o.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer});
1
+ "use strict";var qe=Object.create;var oe=Object.defineProperty,Xe=Object.defineProperties,Ze=Object.getOwnPropertyDescriptor,et=Object.getOwnPropertyDescriptors,tt=Object.getOwnPropertyNames,De=Object.getOwnPropertySymbols,nt=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty,ot=Object.prototype.propertyIsEnumerable;var Ne=(e,t,n)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,E=(e,t)=>{for(var n in t||(t={}))Pe.call(t,n)&&Ne(e,n,t[n]);if(De)for(var n of De(t))ot.call(t,n)&&Ne(e,n,t[n]);return e},j=(e,t)=>Xe(e,et(t));var rt=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Le=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of tt(t))!Pe.call(e,d)&&d!==n&&oe(e,d,{get:()=>t[d],enumerable:!(c=Ze(t,d))||c.enumerable});return e};var st=(e,t,n)=>(n=e!=null?qe(nt(e)):{},Le(t||!e||!e.__esModule?oe(n,"default",{value:e,enumerable:!0}):n,e)),it=e=>Le(oe({},"__esModule",{value:!0}),e);var Qt={};rt(Qt,{deriveSessionSegment:()=>ve,detectDeviceClass:()=>W,detectTimeOfDay:()=>H,detectTrafficSource:()=>J,init:()=>Ht,referrerDomainFromReferer:()=>z});module.exports=it(Qt);var at="_snt_uid";var F="_snt_uid";function ct(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function dt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function lt(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(c){}}function ut(e){try{return localStorage.getItem(e)}catch(t){return null}}function gt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function pt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ft(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function mt(e){try{sessionStorage.removeItem(e)}catch(t){}}function yt(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function ht(e){try{localStorage.removeItem(e)}catch(t){}}function St(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var vt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ce(e){var a,l,g,y,f,m;if(typeof window=="undefined")return vt;let t=(a=e==null?void 0:e.cookieName)!=null?a:at,c=((l=e==null?void 0:e.cookieTTLDays)!=null?l:365)*24*60*60,d=(m=(f=(y=(g=dt(t))!=null?g:ut(F))!=null?y:pt(F))!=null?f:e==null?void 0:e.ssrSessionId)!=null?m:ct();lt(t,d,c);let s=gt(F,d),o=yt(t),r=s?!1:ft(F,d),i=!s&&!o&&!r;return{getSessionId:()=>d,isEphemeral:()=>i,destroy:()=>{d=null,St(t),ht(F),mt(F)}}}function ye(e){return`_snt_retry_${e.slice(0,12)}`}var Et={push:()=>{},flush:()=>{},destroy:()=>{}};function bt(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let c=JSON.parse(n);return Array.isArray(c)?(localStorage.removeItem(t),c.slice(-e)):[]}catch(n){return[]}}function me(e,t,n){try{let d=[...(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let o=JSON.parse(s);return Array.isArray(o)?o:[]}catch(s){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(d))}catch(c){}}function Me(e){var X,Z,ee;if(typeof window=="undefined")return Et;let t=(X=e.flushIntervalMs)!=null?X:5e3,n=(Z=e.maxBatchSize)!=null?Z:20,c=(ee=e.maxRetrySize)!=null?ee:100,d=e.ingestUrl,s=e.apiKey,o=ye(s),r=[],i=new Set,a=[],l=h=>{for(let v of h)g.delete(v),!i.has(v)&&(i.add(v),a.push(v));for(;a.length>500;){let v=a.shift();v&&i.delete(v)}},g=new Set,y=h=>{i.has(h.id)||g.has(h.id)||(g.add(h.id),r.push(h))},f=bt(c,o);for(let h of f)y(h);let m=0,b=0,I=h=>{if(h.length===0)return;let v=JSON.stringify(h),A=h.map(u=>u.id),O;try{O=fetch(d,{method:"POST",keepalive:!0,body:v,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(u){me(h,c,o);for(let p of A)g.delete(p);b++,m=Date.now()+Math.min(6e4,1e3*2**Math.min(b,6));return}let L=u=>{if(u.ok||u.status>=400&&u.status<500&&u.status!==429){l(A),b=0,m=0;return}me(h,c,o);for(let p of A)g.delete(p);b++,m=Date.now()+Math.min(6e4,1e3*2**Math.min(b,6))};O instanceof Promise?O.then(L).catch(()=>{me(h,c,o);for(let u of A)g.delete(u);b++,m=Date.now()+Math.min(6e4,1e3*2**Math.min(b,6))}):L(O)},w=typeof TextEncoder!="undefined"?new TextEncoder:null,ae=h=>w?w.encode(h).length:h.length,G=h=>{let v=[],A=2;for(let O of h){let L=ae(JSON.stringify(O))+1;if(v.length>0&&A+L>57344||v.length>=n)break;v.push(O),A+=L}return v},N=()=>{try{if(Date.now()<m)return;for(;r.length>0;){let h=r.filter(A=>!i.has(A.id));if(r.length=0,h.length===0)break;let v=G(h);if(v.length===0)break;v.length<h.length&&r.push(...h.slice(v.length)),I(v)}}catch(h){}},R=!0,K=null;K=setInterval(()=>{R&&N()},t);let V=()=>{document.visibilityState==="hidden"&&N()},q=()=>{N()};return document.addEventListener("visibilitychange",V),window.addEventListener("beforeunload",q),{push(h){y(h),r.length>=n&&N()},flush:N,destroy(){R=!1,K!==null&&(clearInterval(K),K=null),document.removeEventListener("visibilitychange",V),window.removeEventListener("beforeunload",q),N()}}}var Se="_snt_asgn_";function de(e,t){return`${e}:${t}`}function wt(e,t){return`${Se}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ue(e){let t=e.slice(Se.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(c){return null}}function he(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(Se)&&e.push(n)}return e}catch(e){return[]}}function Ge(e=18e5){let t=new Map,n=d=>d.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let d of he())try{let s=localStorage.getItem(d);if(!s)continue;let o=JSON.parse(s);if(n(o)){localStorage.removeItem(d);continue}let r=Ue(d);if(!r)continue;t.set(de(r.componentId,r.segment),o)}catch(s){}})(),{get(d,s){let o=t.get(de(d,s));return o?n(o)?(t.delete(de(d,s)),null):o:null},set(d,s,o){let r=de(d,s);t.set(r,o);try{localStorage.setItem(wt(d,s),JSON.stringify(o))}catch(i){}},invalidate(d){let s=`${d}:`;for(let o of[...t.keys()])o.startsWith(s)&&t.delete(o);for(let o of he()){let r=Ue(o);if((r==null?void 0:r.componentId)===d)try{localStorage.removeItem(o)}catch(i){}}},clear(){t.clear();for(let d of he())try{localStorage.removeItem(d)}catch(s){}}}}var Ke=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function le(e){return $e(e)!==null}function $e(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ke.find(c=>t.includes(c.toLowerCase())))!=null?n:null}function W(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function J(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(d){}let c=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(c)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(c)?"social":"referral"}catch(n){return"direct"}}function z(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function H(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function ve(e){let t=It("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function It(e,t){var s,o,r,i,a,l,g;let n=(o=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?o:"",c=(i=(r=t==null?void 0:t.referer)==null?void 0:r.trim())!=null?i:"",d=(a=t==null?void 0:t.now)!=null?a:new Date;return{sessionId:e,ephemeral:!1,utmParams:(l=t==null?void 0:t.utmParams)!=null?l:{},deviceClass:n?W(n):"desktop",trafficSource:c?J(c,t==null?void 0:t.appOrigin):"direct",referrerDomain:z(c),timeOfDay:H(d),dayOfWeek:(g=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?g:"sun",automation:(t==null?void 0:t.webdriver)===!0||le(n)}}var Q=require("@sentientui/policy");function ue(e){return E(E(E({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function ge(e){let t=ue(e);return(0,Q.slotResultFor)(t,(0,Q.slotBaselineArm)(t))}function Ee(e){return typeof e=="string"?e:(0,Q.canonicalArm)(e)}var re="_snt_snap:",Ct=["low","medium","high"];function be(e){try{let t=localStorage.getItem(re+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!Ct.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function se(e,t){try{localStorage.setItem(re+e,JSON.stringify(t))}catch(n){}}var Ce=require("@sentientui/policy");var fe=require("@sentientui/policy");var we="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",je="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",Be=!1,pe=!1;function xt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Fe(e){var r;let t=ce({ssrSessionId:e.ssrSessionId}),n=(r=t.getSessionId())!=null?r:"local",c=xt(),d=import("@sentientui/core/local").then(i=>{let a=i;return a.LOCAL_ENGINE_AVAILABLE?(Be||(Be=!0,console.info(je)),a):(pe||(pe=!0,console.error(we)),null)}).catch(()=>(pe||(pe=!0,console.error(we)),null)),s=null;function o(i){let a=document.documentElement;a.dataset.sentientPersona===void 0&&(a.dataset.sentientPersona=i.persona,a.dataset.sentientConfidence=(0,fe.confidenceBand)(i.confidence))}return{isLocal:!0,async decide(i){var g,y,f;let a=await d;if(!a)return null;let l=a.createLocalEngine({sessionId:n,forcedPersona:c}).decide(i);return s=j(E({},l),{layoutOrder:(y=(g=l.layoutOrder)!=null?g:s==null?void 0:s.layoutOrder)!=null?y:null,slots:E(E({},(f=s==null?void 0:s.slots)!=null?f:{}),l.slots)}),se(e.apiKey||"local",{v:1,persona:s.persona,band:(0,fe.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),o(l),l},getSlotResult(i){var a,l,g;return(g=(l=s==null?void 0:s.slots[i])!=null?l:(a=e.initialSlots)==null?void 0:a[i])!=null?g:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,fe.confidenceBand)(s.confidence)}:null},async assign(i,a){var y;let l=await d;return!l||!a||a.length===0?a!=null&&a[0]?{variantId:a[0],assignmentTtlMs:0}:null:{variantId:(y=l.createLocalEngine({sessionId:n,forcedPersona:c}).decide({components:[{id:i,variantIds:a}]}).assignments[i])!=null?y:a[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var We="https://api.sentient-ui.com/v1/events",ie=new Map,At=null;function Ie(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var Y={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function _t(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,c]of t)n.startsWith("utm_")&&(e[n]=c);return e}catch(e){return{}}}function Je(e){return e.replace(/\/events\/?$/,"")}function xe(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function Tt(e){var o;let t=Je((o=e.ingestUrl)!=null?o:We),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},c={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(r,i,a){try{let l=new URLSearchParams({componentId:r});for(let f of i!=null?i:[])l.append("variantIds[]",f);let g=await fetch(`${t}/winner?${l.toString()}`,{headers:n});return g.ok?{variantId:(await g.json()).variantId,assignmentTtlMs:0}:i!=null&&i[0]?{variantId:i[0],assignmentTtlMs:0}:null}catch(l){return i!=null&&i[0]?{variantId:i[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},d={track:r=>c.track(r),goal:(r,i,a,l)=>c.goal(r,i,a,l),componentGoal:(r,i,a)=>c.componentGoal(r,i,a),identify:r=>c.identify(r),getAssignment:(r,i)=>c.getAssignment(r,i),assign:(r,i,a,l)=>c.assign(r,i,a,l),decide:r=>c.decide(r),getSlotResult:r=>c.getSlotResult(r),getPersona:()=>c.getPersona(),fetchWeights:()=>c.fetchWeights(),getGraph:()=>c.getGraph(),dispose:()=>c.dispose(),destroy:()=>c.destroy()};function s(r){c=r}return{proxy:d,setInner:s}}function ze(e){var q,X,Z,ee,h,v,A,O,L;if(typeof window=="undefined")return Y;At=e.apiKey;let t=e.respectDoNotTrack!==!1&&xe(),n=e.consent===!1||t,c=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!c&&e.localMode!==!1)return n?(ie.set(e.apiKey||"local",{config:e,upgrade:null}),Y):(ie.set(e.apiKey||"local",{config:e,upgrade:null}),Fe(e));if(n){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),Y;let{proxy:u,setInner:p}=Tt(e);return ie.set(e.apiKey,{config:e,upgrade:t?null:p}),u}return ie.set(e.apiKey,{config:e,upgrade:null}),Y}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),Y;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),Y;let d=(q=e.ingestUrl)!=null?q:We,s=Date.now(),o=ce({ssrSessionId:e.ssrSessionId}),r=Ge(),i=Me({ingestUrl:d,apiKey:e.apiKey}),a=Je(d),l={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=W((X=navigator.userAgent)!=null?X:""),y=typeof window!="undefined"?window.location.origin:void 0,f=J((Z=document.referrer)!=null?Z:"",y),m=(ee=e.sessionSegment)!=null?ee:`${g}:${f}`,b=new Map,I=new Map,w=null,ae=u=>{for(let p of u)I.has(p.id)||I.set(p.id,ge(p))};if(e.initialSlots)for(let[u,p]of Object.entries(e.initialSlots))I.set(u,p);let G=be(e.apiKey);if(G)for(let[u,p]of Object.entries(G.slots))I.has(u)||I.set(u,p);let N={low:.15,medium:.5,high:.85};if(e.initialPersona)w=E({},e.initialPersona);else{let u=document.documentElement.dataset;u.sentientPersona?w={persona:u.sentientPersona,confidence:(v=N[(h=u.sentientConfidence)!=null?h:"low"])!=null?v:.15}:G&&(w={persona:G.persona,confidence:(A=N[G.band])!=null?A:.15})}if(e.initialAssignments)for(let[u,p]of Object.entries(e.initialAssignments))r.set(u,m,{variantId:p,assignedAt:Date.now(),segment:m,confidence:1});let R=Promise.resolve(),K=o.getSessionId();if(K){let u=z((O=document.referrer)!=null?O:""),p=E(E({sessionId:K,deviceClass:g,trafficSource:f,referrerDomain:u,utmParams:_t(),timeOfDay:H(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||le((L=navigator.userAgent)!=null?L:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{R=fetch(`${a}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(p),headers:l}).then(S=>{S.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(S){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:i});let V={goal(u,p={},S=1,k=0){let x=o.getSessionId();if(!x)return;let _=Ie();R.then(()=>{fetch(`${a}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:x,name:u,metadata:p,weight:S,stepIndex:k,goalId:_}),headers:l}).catch(()=>{})})},componentGoal(u,p,S){var D,U,P;let k=o.getSessionId();if(!k)return;let x=r.get(u,m),_=x?null:(D=I.get(u))!=null?D:null;if(!x&&_===null){e.debug&&console.warn(`[sentient] componentGoal("${u}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let $=x?x.variantId:Ee(_),M={id:Ie(),sessionId:k,projectId:e.apiKey,componentId:u,variantId:$,eventType:"goal_achieved",goalType:p,payload:E({reward:(U=S==null?void 0:S.reward)!=null?U:1},(P=S==null?void 0:S.metadata)!=null?P:{}),timestamp:Date.now(),timeInSession:Date.now()-s};e.debug&&console.log("[sentient] componentGoal",M),R.then(()=>i.push(M))},identify(u){let p=o.getSessionId();p&&R.then(()=>{fetch(`${a}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:p,userId:u,ephemeral:o.isEphemeral()}),headers:l}).catch(()=>{})})},track(u){let p=o.getSessionId();if(!p)return;let S=j(E({},u),{id:Ie(),sessionId:p,timestamp:Date.now(),timeInSession:Date.now()-s});e.debug&&console.log("[sentient] track",S),R.then(()=>i.push(S))},getAssignment(u,p){return r.get(u,p)},async assign(u,p,S,k){let x=o.getSessionId();if(!x)return null;let _=r.get(u,m);if(_&&(p!=null&&p.length||_.content!==void 0))return{variantId:_.variantId,assignmentTtlMs:0,content:_.content};let $=b.get(u);if($)return $;let M=(async()=>{await R;try{let D={sessionId:x,componentId:u,variantIds:p};k!==void 0?D.agentDataByVariant=k:S!==void 0&&(D.agentData=S);let U=await fetch(`${a}/assign`,{method:"POST",body:JSON.stringify(D),headers:l});if(!U.ok)return null;let P=await U.json();return r.set(u,m,{variantId:P.variantId,assignedAt:Date.now(),segment:m,confidence:1,content:P.content}),P}catch(D){return null}finally{b.delete(u)}})();return b.set(u,M),M},async decide(u){var k,x,_,$,M,D,U,P,Re,Oe;let p=o.getSessionId();if(!p)return null;let S=(k=u.slots)!=null?k:[];await R;try{let B={sessionId:p};u.sections&&u.sections.length>0&&(B.sections=u.sections.map(T=>({id:T}))),B.components=(x=u.components)!=null?x:[],S.length>0&&(B.slots=S.map(ue)),u.slotsFrom==="registry"&&(B.slotsFrom="registry");let ke=await fetch(`${a}/decide`,{method:"POST",body:JSON.stringify(B),headers:l});if(!ke.ok)return ae(S),null;let C=await ke.json(),te={};for(let T of S)te[T.id]=($=(_=C.slots)==null?void 0:_[T.id])!=null?$:ge(T);if(C.slots)for(let[T,ne]of Object.entries(C.slots))T in te||(te[T]=ne);for(let[T,ne]of Object.entries(te))I.set(T,ne);w={persona:(M=C.persona)!=null?M:"unknown",confidence:(D=C.confidence)!=null?D:0};for(let[T,ne]of Object.entries((U=C.assignments)!=null?U:{}))r.set(T,m,{variantId:ne,assignedAt:Date.now(),segment:m,confidence:1});return se(e.apiKey,E({v:1,persona:w.persona,band:(0,Ce.confidenceBand)(w.confidence),slots:Object.fromEntries(I),layoutOrder:(P=C.layoutOrder)!=null?P:null,savedAt:Date.now()},C.slotConfig?{slotConfig:C.slotConfig}:{})),E(E({layoutOrder:(Re=C.layoutOrder)!=null?Re:null,assignments:(Oe=C.assignments)!=null?Oe:{},slots:te,persona:w.persona,confidence:w.confidence},C.slotConfig?{slotConfig:C.slotConfig}:{}),C.goals?{goals:C.goals}:{})}catch(B){return ae(S),null}},getSlotResult(u){var p;return(p=I.get(u))!=null?p:null},getPersona(){return w?{persona:w.persona,confidence:w.confidence,band:(0,Ce.confidenceBand)(w.confidence)}:null},async fetchWeights(){var u;try{let p=await fetch(`${a}/weights`,{headers:l});return p.ok?(u=(await p.json()).components)!=null?u:[]:[]}catch(p){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){i.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){i.destroy(),o.destroy();try{localStorage.removeItem(re+e.apiKey),localStorage.removeItem(ye(e.apiKey))}catch(u){}e.debug&&console.log("[sentient] destroyed")}};if(ie.set(e.apiKey,{config:e,upgrade:null}),e.debug){let u=window;u.__sentient&&(u.__sentient.client=V)}return V}var Rt=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Ot="h1, h2, h3",kt={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function Ae(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Dt(e){var t,n,c;try{let d=e;for(let s of Object.keys(d)){if(!s.startsWith("__reactFiber")&&!s.startsWith("__reactInternalInstance"))continue;let o=d[s],r=(c=(t=o==null?void 0:o.type)==null?void 0:t.displayName)!=null?c:(n=o==null?void 0:o.type)==null?void 0:n.name;if(r&&r.length>1)return r}}catch(d){}}function Nt(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function Pt(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function Lt(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function Mt(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function _e(e,t){var c,d,s;let n=e.querySelector(Ot);return{componentId:Lt(e),semanticType:Pt(e),ariaLabel:(c=e.getAttribute("aria-label"))!=null?c:void 0,headingText:(s=(d=n==null?void 0:n.textContent)==null?void 0:d.trim())!=null?s:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Mt(e),reactComponentName:Dt(e),dataAttributes:Nt(e)}}function He(e){var s;let t=[],n=new Set,c="__root__",d=new Map;for(let[o,r]of e){let i=o.parentElement,a=c;for(;i;){if(e.has(i)){a=e.get(i);let g=e.get(o),y=`${a}->${g}`;!n.has(y)&&a!==g&&(n.add(y),t.push({fromComponentId:a,toComponentId:g,weight:.6}));break}i=i.parentElement}let l=(s=d.get(a))!=null?s:[];l.push(o),d.set(a,l)}for(let o of d.values())if(!(o.length<2))for(let r=0;r<o.length;r++)for(let i=r+1;i<o.length;i++){let a=e.get(o[r]),l=e.get(o[i]);if(a===l)continue;let g=`${a}->${l}::sib`,y=`${l}->${a}::sib`;n.has(g)||(n.add(g),t.push({fromComponentId:a,toComponentId:l,weight:.3})),n.has(y)||(n.add(y),t.push({fromComponentId:l,toComponentId:a,weight:.3}))}return t}function Ut(e){let t=[],n=new Set,c=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(o=>{if(o instanceof Element&&!n.has(o)){n.add(o);let r=_e(o,e);t.push(r),c.set(o,r.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(o=>{if(!(o instanceof Element)||n.has(o))return;let r=o.hasAttribute("aria-label"),i=o.hasAttribute("data-sentient-id");if(!r&&!i)return;n.add(o);let a=_e(o,e);t.push(a),c.set(o,a.componentId)}),{nodes:t,edges:He(c)}}function Qe(){if(typeof window=="undefined")return kt;let e=null,t=0,n=null,c=r=>{try{let i=window.getComputedStyle(r),a=parseFloat(i.fontSize)||12,l=parseFloat(i.zIndex)||0,g=r.getBoundingClientRect(),y=Math.max(g.top,0),f=window.innerHeight||1,m=1/(y/f+1),b=Ae(a,12,48)*.4+Ae(m,0,1)*.4+Ae(l,0,100)*.2;return Math.max(0,Math.min(1,b))}catch(i){return .5}};return{scan:()=>new Promise(r=>{let i=()=>{let{nodes:a,edges:l}=Ut(c);r({nodes:a,edges:l,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(i,{timeout:100}):i()}catch(a){i()}}),observe:r=>{n=r;try{e=new MutationObserver(i=>{let a=[],l=new Map;for(let g of i)g.type==="childList"&&g.addedNodes.forEach(y=>{if(!(y instanceof Element)||!Rt.has(y.tagName))return;let f=y.hasAttribute("data-sentient-id"),m=y.hasAttribute("aria-label");if(!f&&!m)return;let b=_e(y,c);a.push(b),l.set(y,b.componentId)});a.length>0&&n&&n({nodes:a,edges:He(l),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(i){}},getProminenceScore:c,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(r){}t=0,n=null}}}var Te="_snt_graph_nodes",Ye="_snt_graph_edges",Gt={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function Kt(e){var t;return(t=Gt[e])!=null?t:[]}function $t(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function Bt(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var jt=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function Ft(e){return jt.has(e)?e:"generic"}function Wt(e,t,n){let c=`${e}:${t}:${n.join(",")}`,d=5381;for(let s=0;s<c.length;s++)d=(d<<5)+d+c.charCodeAt(s)&4294967295;return(d>>>0).toString(16).padStart(8,"0")}function Ve(e){let t=new Map,n=new Map,c=()=>{typeof window!="undefined"&&Bt(Te,[...t.values()])},d=s=>{var o;try{let r=JSON.parse(s);t.clear();for(let i of(o=r.pageNodes)!=null?o:[])t.set(i.componentId,i)}catch(r){}};if(typeof window!="undefined"){let s=$t(Te,[]);for(let o of s)t.set(o.componentId,o);try{localStorage.removeItem(Ye)}catch(o){}}return{addPageNode(s){t.set(s.componentId,s),c()},addStructuralEdge(s){let o=`${s.fromComponentId}->${s.toComponentId}`;n.set(o,s)},syncOnce(){var o,r;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let s=[...t.values()];if(s.length!==0)try{let i=new Map;for(let f of s){let m=(o=i.get(f.semanticType))!=null?o:[];m.push(f),i.set(f.semanticType,m)}let a=[],l=new Set;for(let f of s)for(let m of Kt(f.semanticType)){let b=(r=i.get(m))!=null?r:[];for(let I of b){if(I.componentId===f.componentId)continue;let w=`semantic:${f.componentId}->${I.componentId}`;l.has(w)||(l.add(w),a.push({fromComponentId:f.componentId,toComponentId:I.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(s.map(f=>f.componentId));for(let f of n.values()){if(!g.has(f.fromComponentId)||!g.has(f.toComponentId))continue;let m=`structural:${f.fromComponentId}->${f.toComponentId}`;l.has(m)||(l.add(m),a.push({fromComponentId:f.fromComponentId,toComponentId:f.toComponentId,type:"structural",weight:f.weight,confidence:1}))}let y={pageUrl:window.location.href,nodes:s.map(f=>{let m=Ft(f.semanticType);return{componentId:f.componentId,semanticType:m,answers:f.answers,contentHash:Wt(f.componentId,m,f.answers),prominenceScore:f.prominenceScore,depthInPage:f.depth}}),edges:a};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:E({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(y)}).catch(()=>{})}catch(i){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:d,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(Te),localStorage.removeItem(Ye)}catch(s){}}}}var Jt="https://api.sentient-ui.com/v1/events";function zt(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function Ht(e){var a;let t=ze(e),n=e.respectDoNotTrack!==!1&&xe(),c=e.consent===!1||n;if(!e.graph||c||typeof window=="undefined")return t;let d=Qe(),s=(a=e.ingestUrl)!=null?a:Jt,o=Ve({syncUrl:s.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:zt()});try{let l=localStorage.getItem("_snt_graph_nodes");l&&o.restore(JSON.stringify({pageNodes:JSON.parse(l)}))}catch(l){}d.scan().then(l=>{for(let g of l.nodes)o.addPageNode({id:g.componentId,componentId:g.componentId,semanticType:g.semanticType,answers:g.headingText?[g.headingText]:[],prominenceScore:g.prominenceScore,depth:g.depth});for(let g of l.edges)o.addStructuralEdge(g);o.syncOnce()});let r=null,i=()=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{r=null,o.syncOnce()},500)};return d.observe(l=>{for(let g of l.nodes)o.addPageNode({id:g.componentId,componentId:g.componentId,semanticType:g.semanticType,answers:g.headingText?[g.headingText]:[],prominenceScore:g.prominenceScore,depth:g.depth});for(let g of l.edges)o.addStructuralEdge(g);i()}),j(E({},t),{getGraph:()=>o.snapshot(),dispose:()=>{r!==null&&clearTimeout(r),d.destroy(),o.destroy(),t.dispose()},destroy:()=>{r!==null&&clearTimeout(r),d.destroy(),o.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer});
@@ -1 +1 @@
1
- import{h as v,j as w}from"./chunk-ZALZC4AD.mjs";import{d as _,e as O,f as R,g as M,h as D}from"./chunk-SVYHTU5Z.mjs";import{a as h,b}from"./chunk-HGGX55FR.mjs";var P=new Set(["SECTION","ARTICLE","MAIN","DIV"]),k="h1, h2, h3",G={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function S(e,t,o){return o<=t?0:Math.max(0,Math.min(1,(e-t)/(o-t)))}function $(e){var t,o,g;try{let u=e;for(let s of Object.keys(u)){if(!s.startsWith("__reactFiber")&&!s.startsWith("__reactInternalInstance"))continue;let n=u[s],r=(g=(t=n==null?void 0:n.type)==null?void 0:t.displayName)!=null?g:(o=n==null?void 0:n.type)==null?void 0:o.name;if(r&&r.length>1)return r}}catch(u){}}function L(e){let t={};for(let o of Array.from(e.attributes))o.name.startsWith("data-")&&(t[o.name]=o.value);return t}function U(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let o=e.getAttribute("role");return o||"generic"}function j(e){var t,o;return(o=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?o:e.tagName.toLowerCase()}function F(e){let t=0,o=e.parentElement;for(;o;)t++,o=o.parentElement;return t}function I(e,t){var g,u,s;let o=e.querySelector(k);return{componentId:j(e),semanticType:U(e),ariaLabel:(g=e.getAttribute("aria-label"))!=null?g:void 0,headingText:(s=(u=o==null?void 0:o.textContent)==null?void 0:u.trim())!=null?s:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:F(e),reactComponentName:$(e),dataAttributes:L(e)}}function N(e){var s;let t=[],o=new Set,g="__root__",u=new Map;for(let[n,r]of e){let i=n.parentElement,c=g;for(;i;){if(e.has(i)){c=e.get(i);let a=e.get(n),m=`${c}->${a}`;!o.has(m)&&c!==a&&(o.add(m),t.push({fromComponentId:c,toComponentId:a,weight:.6}));break}i=i.parentElement}let d=(s=u.get(c))!=null?s:[];d.push(n),u.set(c,d)}for(let n of u.values())if(!(n.length<2))for(let r=0;r<n.length;r++)for(let i=r+1;i<n.length;i++){let c=e.get(n[r]),d=e.get(n[i]);if(c===d)continue;let a=`${c}->${d}::sib`,m=`${d}->${c}::sib`;o.has(a)||(o.add(a),t.push({fromComponentId:c,toComponentId:d,weight:.3})),o.has(m)||(o.add(m),t.push({fromComponentId:d,toComponentId:c,weight:.3}))}return t}function K(e){let t=[],o=new Set,g=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(n=>{if(n instanceof Element&&!o.has(n)){o.add(n);let r=I(n,e);t.push(r),g.set(n,r.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(n=>{if(!(n instanceof Element)||o.has(n))return;let r=n.hasAttribute("aria-label"),i=n.hasAttribute("data-sentient-id");if(!r&&!i)return;o.add(n);let c=I(n,e);t.push(c),g.set(n,c.componentId)}),{nodes:t,edges:N(g)}}function A(){if(typeof window=="undefined")return G;let e=null,t=0,o=null,g=r=>{try{let i=window.getComputedStyle(r),c=parseFloat(i.fontSize)||12,d=parseFloat(i.zIndex)||0,a=r.getBoundingClientRect(),m=Math.max(a.top,0),p=window.innerHeight||1,l=1/(m/p+1),f=S(c,12,48)*.4+S(l,0,1)*.4+S(d,0,100)*.2;return Math.max(0,Math.min(1,f))}catch(i){return .5}};return{scan:()=>new Promise(r=>{let i=()=>{let{nodes:c,edges:d}=K(g);r({nodes:c,edges:d,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(i,{timeout:100}):i()}catch(c){i()}}),observe:r=>{o=r;try{e=new MutationObserver(i=>{let c=[],d=new Map;for(let a of i)a.type==="childList"&&a.addedNodes.forEach(m=>{if(!(m instanceof Element)||!P.has(m.tagName))return;let p=m.hasAttribute("data-sentient-id"),l=m.hasAttribute("aria-label");if(!p&&!l)return;let f=I(m,g);c.push(f),d.set(m,f.componentId)});c.length>0&&o&&o({nodes:c,edges:N(d),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(i){}},getProminenceScore:g,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(r){}t=0,o=null}}}var E="_snt_graph_nodes",T="_snt_graph_edges",q={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function z(e){var t;return(t=q[e])!=null?t:[]}function B(e,t){try{let o=localStorage.getItem(e);return o?JSON.parse(o):t}catch(o){return t}}function H(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(o){}}var J=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function V(e){return J.has(e)?e:"generic"}function W(e,t,o){let g=`${e}:${t}:${o.join(",")}`,u=5381;for(let s=0;s<g.length;s++)u=(u<<5)+u+g.charCodeAt(s)&4294967295;return(u>>>0).toString(16).padStart(8,"0")}function x(e){let t=new Map,o=new Map,g=()=>{typeof window!="undefined"&&H(E,[...t.values()])},u=s=>{var n;try{let r=JSON.parse(s);t.clear();for(let i of(n=r.pageNodes)!=null?n:[])t.set(i.componentId,i)}catch(r){}};if(typeof window!="undefined"){let s=B(E,[]);for(let n of s)t.set(n.componentId,n);try{localStorage.removeItem(T)}catch(n){}}return{addPageNode(s){t.set(s.componentId,s),g()},addStructuralEdge(s){let n=`${s.fromComponentId}->${s.toComponentId}`;o.set(n,s)},syncOnce(){var n,r;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let s=[...t.values()];if(s.length!==0)try{let i=new Map;for(let p of s){let l=(n=i.get(p.semanticType))!=null?n:[];l.push(p),i.set(p.semanticType,l)}let c=[],d=new Set;for(let p of s)for(let l of z(p.semanticType)){let f=(r=i.get(l))!=null?r:[];for(let y of f){if(y.componentId===p.componentId)continue;let C=`semantic:${p.componentId}->${y.componentId}`;d.has(C)||(d.add(C),c.push({fromComponentId:p.componentId,toComponentId:y.componentId,type:"semantic",weight:.4,confidence:.9}))}}let a=new Set(s.map(p=>p.componentId));for(let p of o.values()){if(!a.has(p.fromComponentId)||!a.has(p.toComponentId))continue;let l=`structural:${p.fromComponentId}->${p.toComponentId}`;d.has(l)||(d.add(l),c.push({fromComponentId:p.fromComponentId,toComponentId:p.toComponentId,type:"structural",weight:p.weight,confidence:1}))}let m={pageUrl:window.location.href,nodes:s.map(p=>{let l=V(p.semanticType);return{componentId:p.componentId,semanticType:l,answers:p.answers,contentHash:W(p.componentId,l,p.answers),prominenceScore:p.prominenceScore,depthInPage:p.depth}}),edges:c};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:h({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(m)}).catch(()=>{})}catch(i){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:u,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(E),localStorage.removeItem(T)}catch(s){}}}}var Y="https://api.sentient-ui.com/v1/events";function Q(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function re(e){var c;let t=w(e),o=e.respectDoNotTrack!==!1&&v(),g=e.consent===!1||o;if(!e.graph||g||typeof window=="undefined")return t;let u=A(),s=(c=e.ingestUrl)!=null?c:Y,n=x({syncUrl:s.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Q()});try{let d=localStorage.getItem("_snt_graph_nodes");d&&n.restore(JSON.stringify({pageNodes:JSON.parse(d)}))}catch(d){}u.scan().then(d=>{for(let a of d.nodes)n.addPageNode({id:a.componentId,componentId:a.componentId,semanticType:a.semanticType,answers:a.headingText?[a.headingText]:[],prominenceScore:a.prominenceScore,depth:a.depth});for(let a of d.edges)n.addStructuralEdge(a);n.syncOnce()});let r=null,i=()=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{r=null,n.syncOnce()},500)};return u.observe(d=>{for(let a of d.nodes)n.addPageNode({id:a.componentId,componentId:a.componentId,semanticType:a.semanticType,answers:a.headingText?[a.headingText]:[],prominenceScore:a.prominenceScore,depth:a.depth});for(let a of d.edges)n.addStructuralEdge(a);i()}),b(h({},t),{getGraph:()=>n.snapshot(),dispose:()=>{r!==null&&clearTimeout(r),u.destroy(),n.destroy(),t.dispose()},destroy:()=>{r!==null&&clearTimeout(r),u.destroy(),n.destroy(),t.destroy()}})}export{D as deriveSessionSegment,_ as detectDeviceClass,M as detectTimeOfDay,O as detectTrafficSource,re as init,R as referrerDomainFromReferer};
1
+ import{h as v,j as w}from"./chunk-D35W3ODA.mjs";import{d as _,e as O,f as R,g as M,h as D}from"./chunk-SVYHTU5Z.mjs";import{a as h,b}from"./chunk-HGGX55FR.mjs";var P=new Set(["SECTION","ARTICLE","MAIN","DIV"]),k="h1, h2, h3",G={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function S(e,t,o){return o<=t?0:Math.max(0,Math.min(1,(e-t)/(o-t)))}function $(e){var t,o,g;try{let u=e;for(let s of Object.keys(u)){if(!s.startsWith("__reactFiber")&&!s.startsWith("__reactInternalInstance"))continue;let n=u[s],r=(g=(t=n==null?void 0:n.type)==null?void 0:t.displayName)!=null?g:(o=n==null?void 0:n.type)==null?void 0:o.name;if(r&&r.length>1)return r}}catch(u){}}function L(e){let t={};for(let o of Array.from(e.attributes))o.name.startsWith("data-")&&(t[o.name]=o.value);return t}function U(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let o=e.getAttribute("role");return o||"generic"}function j(e){var t,o;return(o=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?o:e.tagName.toLowerCase()}function F(e){let t=0,o=e.parentElement;for(;o;)t++,o=o.parentElement;return t}function I(e,t){var g,u,s;let o=e.querySelector(k);return{componentId:j(e),semanticType:U(e),ariaLabel:(g=e.getAttribute("aria-label"))!=null?g:void 0,headingText:(s=(u=o==null?void 0:o.textContent)==null?void 0:u.trim())!=null?s:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:F(e),reactComponentName:$(e),dataAttributes:L(e)}}function N(e){var s;let t=[],o=new Set,g="__root__",u=new Map;for(let[n,r]of e){let i=n.parentElement,c=g;for(;i;){if(e.has(i)){c=e.get(i);let a=e.get(n),m=`${c}->${a}`;!o.has(m)&&c!==a&&(o.add(m),t.push({fromComponentId:c,toComponentId:a,weight:.6}));break}i=i.parentElement}let d=(s=u.get(c))!=null?s:[];d.push(n),u.set(c,d)}for(let n of u.values())if(!(n.length<2))for(let r=0;r<n.length;r++)for(let i=r+1;i<n.length;i++){let c=e.get(n[r]),d=e.get(n[i]);if(c===d)continue;let a=`${c}->${d}::sib`,m=`${d}->${c}::sib`;o.has(a)||(o.add(a),t.push({fromComponentId:c,toComponentId:d,weight:.3})),o.has(m)||(o.add(m),t.push({fromComponentId:d,toComponentId:c,weight:.3}))}return t}function K(e){let t=[],o=new Set,g=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(n=>{if(n instanceof Element&&!o.has(n)){o.add(n);let r=I(n,e);t.push(r),g.set(n,r.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(n=>{if(!(n instanceof Element)||o.has(n))return;let r=n.hasAttribute("aria-label"),i=n.hasAttribute("data-sentient-id");if(!r&&!i)return;o.add(n);let c=I(n,e);t.push(c),g.set(n,c.componentId)}),{nodes:t,edges:N(g)}}function A(){if(typeof window=="undefined")return G;let e=null,t=0,o=null,g=r=>{try{let i=window.getComputedStyle(r),c=parseFloat(i.fontSize)||12,d=parseFloat(i.zIndex)||0,a=r.getBoundingClientRect(),m=Math.max(a.top,0),p=window.innerHeight||1,l=1/(m/p+1),f=S(c,12,48)*.4+S(l,0,1)*.4+S(d,0,100)*.2;return Math.max(0,Math.min(1,f))}catch(i){return .5}};return{scan:()=>new Promise(r=>{let i=()=>{let{nodes:c,edges:d}=K(g);r({nodes:c,edges:d,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(i,{timeout:100}):i()}catch(c){i()}}),observe:r=>{o=r;try{e=new MutationObserver(i=>{let c=[],d=new Map;for(let a of i)a.type==="childList"&&a.addedNodes.forEach(m=>{if(!(m instanceof Element)||!P.has(m.tagName))return;let p=m.hasAttribute("data-sentient-id"),l=m.hasAttribute("aria-label");if(!p&&!l)return;let f=I(m,g);c.push(f),d.set(m,f.componentId)});c.length>0&&o&&o({nodes:c,edges:N(d),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(i){}},getProminenceScore:g,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(r){}t=0,o=null}}}var E="_snt_graph_nodes",T="_snt_graph_edges",q={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function z(e){var t;return(t=q[e])!=null?t:[]}function B(e,t){try{let o=localStorage.getItem(e);return o?JSON.parse(o):t}catch(o){return t}}function H(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(o){}}var J=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function V(e){return J.has(e)?e:"generic"}function W(e,t,o){let g=`${e}:${t}:${o.join(",")}`,u=5381;for(let s=0;s<g.length;s++)u=(u<<5)+u+g.charCodeAt(s)&4294967295;return(u>>>0).toString(16).padStart(8,"0")}function x(e){let t=new Map,o=new Map,g=()=>{typeof window!="undefined"&&H(E,[...t.values()])},u=s=>{var n;try{let r=JSON.parse(s);t.clear();for(let i of(n=r.pageNodes)!=null?n:[])t.set(i.componentId,i)}catch(r){}};if(typeof window!="undefined"){let s=B(E,[]);for(let n of s)t.set(n.componentId,n);try{localStorage.removeItem(T)}catch(n){}}return{addPageNode(s){t.set(s.componentId,s),g()},addStructuralEdge(s){let n=`${s.fromComponentId}->${s.toComponentId}`;o.set(n,s)},syncOnce(){var n,r;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let s=[...t.values()];if(s.length!==0)try{let i=new Map;for(let p of s){let l=(n=i.get(p.semanticType))!=null?n:[];l.push(p),i.set(p.semanticType,l)}let c=[],d=new Set;for(let p of s)for(let l of z(p.semanticType)){let f=(r=i.get(l))!=null?r:[];for(let y of f){if(y.componentId===p.componentId)continue;let C=`semantic:${p.componentId}->${y.componentId}`;d.has(C)||(d.add(C),c.push({fromComponentId:p.componentId,toComponentId:y.componentId,type:"semantic",weight:.4,confidence:.9}))}}let a=new Set(s.map(p=>p.componentId));for(let p of o.values()){if(!a.has(p.fromComponentId)||!a.has(p.toComponentId))continue;let l=`structural:${p.fromComponentId}->${p.toComponentId}`;d.has(l)||(d.add(l),c.push({fromComponentId:p.fromComponentId,toComponentId:p.toComponentId,type:"structural",weight:p.weight,confidence:1}))}let m={pageUrl:window.location.href,nodes:s.map(p=>{let l=V(p.semanticType);return{componentId:p.componentId,semanticType:l,answers:p.answers,contentHash:W(p.componentId,l,p.answers),prominenceScore:p.prominenceScore,depthInPage:p.depth}}),edges:c};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:h({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(m)}).catch(()=>{})}catch(i){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:u,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(E),localStorage.removeItem(T)}catch(s){}}}}var Y="https://api.sentient-ui.com/v1/events";function Q(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function re(e){var c;let t=w(e),o=e.respectDoNotTrack!==!1&&v(),g=e.consent===!1||o;if(!e.graph||g||typeof window=="undefined")return t;let u=A(),s=(c=e.ingestUrl)!=null?c:Y,n=x({syncUrl:s.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Q()});try{let d=localStorage.getItem("_snt_graph_nodes");d&&n.restore(JSON.stringify({pageNodes:JSON.parse(d)}))}catch(d){}u.scan().then(d=>{for(let a of d.nodes)n.addPageNode({id:a.componentId,componentId:a.componentId,semanticType:a.semanticType,answers:a.headingText?[a.headingText]:[],prominenceScore:a.prominenceScore,depth:a.depth});for(let a of d.edges)n.addStructuralEdge(a);n.syncOnce()});let r=null,i=()=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{r=null,n.syncOnce()},500)};return u.observe(d=>{for(let a of d.nodes)n.addPageNode({id:a.componentId,componentId:a.componentId,semanticType:a.semanticType,answers:a.headingText?[a.headingText]:[],prominenceScore:a.prominenceScore,depth:a.depth});for(let a of d.edges)n.addStructuralEdge(a);i()}),b(h({},t),{getGraph:()=>n.snapshot(),dispose:()=>{r!==null&&clearTimeout(r),u.destroy(),n.destroy(),t.dispose()},destroy:()=>{r!==null&&clearTimeout(r),u.destroy(),n.destroy(),t.destroy()}})}export{D as deriveSessionSegment,_ as detectDeviceClass,M as detectTimeOfDay,O as detectTrafficSource,re as init,R as referrerDomainFromReferer};
package/dist/index.d.cts CHANGED
@@ -135,9 +135,6 @@ type GraphClient = {
135
135
  destroy(): void;
136
136
  };
137
137
 
138
- declare const PROD_KEYLESS_ERROR = "[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.";
139
- declare const LOCAL_MODE_BANNER = "[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.";
140
-
141
138
  /**
142
139
  * Decision snapshot: the SPA / return-visit pre-paint source. Written after
143
140
  * every successful decide; read by the inline pre-paint script (before any
@@ -145,6 +142,44 @@ declare const LOCAL_MODE_BANNER = "[sentient] Local mode \u2014 decisions are si
145
142
  */
146
143
 
147
144
  declare const SNAPSHOT_STORAGE_KEY_PREFIX = "_snt_snap:";
145
+ /** Bounded, declarative operations a registry arm may apply to its element.
146
+ * The style set is a fixed whitelist (validated server-side); no arbitrary CSS,
147
+ * HTML, or JS ever. `text` is applied via textContent; https-only URLs. */
148
+ type SlotOps = {
149
+ text?: string;
150
+ style?: Record<string, string>;
151
+ hidden?: boolean;
152
+ href?: string;
153
+ imageSrc?: string;
154
+ imageAlt?: string;
155
+ };
156
+ /** Versioned compound locator: resolve id → dataAttr → selector, then verify
157
+ * against fingerprint. Lets a slot survive DOM/markup drift. */
158
+ type CompoundLocator = {
159
+ v?: number;
160
+ id?: string;
161
+ dataAttr?: {
162
+ name: string;
163
+ value: string;
164
+ };
165
+ selector?: string;
166
+ urlMatch?: string;
167
+ fingerprint?: {
168
+ tag?: string;
169
+ text?: string;
170
+ };
171
+ semanticId?: string;
172
+ };
173
+ /** Registry-mode apply info per slot: where to apply and what to set. Stored so
174
+ * a returning visitor's pre-paint can reapply it. `target` is the Phase-2 bare
175
+ * selector; `locator` (Phase 3) is the compound locator, preferred when present. */
176
+ type SlotConfigEntry = {
177
+ kind: 'tokens' | 'arms';
178
+ target?: string;
179
+ locator?: CompoundLocator;
180
+ content?: string;
181
+ ops?: SlotOps;
182
+ };
148
183
  type DecisionSnapshot = {
149
184
  v: 1;
150
185
  persona: string;
@@ -152,6 +187,7 @@ type DecisionSnapshot = {
152
187
  slots: Record<string, SlotResult>;
153
188
  layoutOrder: string[] | null;
154
189
  savedAt: number;
190
+ slotConfig?: Record<string, SlotConfigEntry>;
155
191
  };
156
192
  /** Returns null on missing, corrupt, or wrong-version data — never throws. */
157
193
  declare function readSnapshot(apiKey: string): DecisionSnapshot | null;
@@ -170,6 +206,9 @@ declare function writeSnapshot(apiKey: string, snap: DecisionSnapshot): void;
170
206
  */
171
207
  declare function renderPrePaintScript(apiKey: string): string;
172
208
 
209
+ declare const PROD_KEYLESS_ERROR = "[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.";
210
+ declare const LOCAL_MODE_BANNER = "[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.";
211
+
173
212
  type MicroSignalEmitter = (signalType: 'rage_click' | 'text_copy' | 'scroll_hesitation' | 'tab_loss', extra?: Record<string, unknown>) => void;
174
213
  type MicroSignalType = Parameters<MicroSignalEmitter>[0];
175
214
  /**
@@ -263,12 +302,23 @@ type AssignResult = {
263
302
  content?: string;
264
303
  };
265
304
 
305
+ /** An editor-defined goal delivered with a registry-mode decision, for the
306
+ * snippet to install delegated listeners from. */
307
+ type GoalDefinition = {
308
+ goalId: string;
309
+ event: 'click' | 'form_submit' | 'url_reached';
310
+ locator?: CompoundLocator;
311
+ urlPattern?: string;
312
+ slotId?: string;
313
+ };
266
314
  type DecideOutcome = {
267
315
  layoutOrder: string[] | null;
268
316
  assignments: Record<string, string>;
269
317
  slots: Record<string, SlotResult>;
270
318
  persona: string;
271
319
  confidence: number;
320
+ slotConfig?: Record<string, SlotConfigEntry>;
321
+ goals?: GoalDefinition[];
272
322
  };
273
323
  type DecideInput = {
274
324
  sections?: string[];
@@ -277,6 +327,7 @@ type DecideInput = {
277
327
  variantIds?: string[];
278
328
  }>;
279
329
  slots?: SlotDeclInput[];
330
+ slotsFrom?: 'request' | 'registry';
280
331
  };
281
332
  type WeightEntry = {
282
333
  variantId: string;
@@ -366,4 +417,4 @@ declare function grantConsent(apiKey?: string): void;
366
417
  */
367
418
  declare function init(config: SentientConfig): SentientClient;
368
419
 
369
- export { type AssignResult, type Assignment, type AssignmentCache, type ComponentGoalOptions, type ComponentWeightEntry, type ContentAddedEvent, type DOMScanner, type DecideInput, type DecideOutcome, type DecisionSnapshot, type EventQueue, type EventType, type GraphClient, type GraphConfig, type GraphSnapshot, LOCAL_MODE_BANNER, type MicroSignalEmitter, type MicroSignalType, PROD_KEYLESS_ERROR, type PageNode, type QueueConfig, SNAPSHOT_STORAGE_KEY_PREFIX, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type SessionConfig, type SessionManager, SlotDeclInput, type WeightEntry, attachMicroSignalDetectors, grantConsent, init, isDoNotTrackEnabled, readSnapshot, renderPrePaintScript, writeSnapshot };
420
+ export { type AssignResult, type Assignment, type AssignmentCache, type ComponentGoalOptions, type ComponentWeightEntry, type CompoundLocator, type ContentAddedEvent, type DOMScanner, type DecideInput, type DecideOutcome, type DecisionSnapshot, type EventQueue, type EventType, type GoalDefinition, type GraphClient, type GraphConfig, type GraphSnapshot, LOCAL_MODE_BANNER, type MicroSignalEmitter, type MicroSignalType, PROD_KEYLESS_ERROR, type PageNode, type QueueConfig, SNAPSHOT_STORAGE_KEY_PREFIX, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type SessionConfig, type SessionManager, type SlotConfigEntry, SlotDeclInput, type SlotOps, type WeightEntry, attachMicroSignalDetectors, grantConsent, init, isDoNotTrackEnabled, readSnapshot, renderPrePaintScript, writeSnapshot };
package/dist/index.d.ts CHANGED
@@ -135,9 +135,6 @@ type GraphClient = {
135
135
  destroy(): void;
136
136
  };
137
137
 
138
- declare const PROD_KEYLESS_ERROR = "[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.";
139
- declare const LOCAL_MODE_BANNER = "[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.";
140
-
141
138
  /**
142
139
  * Decision snapshot: the SPA / return-visit pre-paint source. Written after
143
140
  * every successful decide; read by the inline pre-paint script (before any
@@ -145,6 +142,44 @@ declare const LOCAL_MODE_BANNER = "[sentient] Local mode \u2014 decisions are si
145
142
  */
146
143
 
147
144
  declare const SNAPSHOT_STORAGE_KEY_PREFIX = "_snt_snap:";
145
+ /** Bounded, declarative operations a registry arm may apply to its element.
146
+ * The style set is a fixed whitelist (validated server-side); no arbitrary CSS,
147
+ * HTML, or JS ever. `text` is applied via textContent; https-only URLs. */
148
+ type SlotOps = {
149
+ text?: string;
150
+ style?: Record<string, string>;
151
+ hidden?: boolean;
152
+ href?: string;
153
+ imageSrc?: string;
154
+ imageAlt?: string;
155
+ };
156
+ /** Versioned compound locator: resolve id → dataAttr → selector, then verify
157
+ * against fingerprint. Lets a slot survive DOM/markup drift. */
158
+ type CompoundLocator = {
159
+ v?: number;
160
+ id?: string;
161
+ dataAttr?: {
162
+ name: string;
163
+ value: string;
164
+ };
165
+ selector?: string;
166
+ urlMatch?: string;
167
+ fingerprint?: {
168
+ tag?: string;
169
+ text?: string;
170
+ };
171
+ semanticId?: string;
172
+ };
173
+ /** Registry-mode apply info per slot: where to apply and what to set. Stored so
174
+ * a returning visitor's pre-paint can reapply it. `target` is the Phase-2 bare
175
+ * selector; `locator` (Phase 3) is the compound locator, preferred when present. */
176
+ type SlotConfigEntry = {
177
+ kind: 'tokens' | 'arms';
178
+ target?: string;
179
+ locator?: CompoundLocator;
180
+ content?: string;
181
+ ops?: SlotOps;
182
+ };
148
183
  type DecisionSnapshot = {
149
184
  v: 1;
150
185
  persona: string;
@@ -152,6 +187,7 @@ type DecisionSnapshot = {
152
187
  slots: Record<string, SlotResult>;
153
188
  layoutOrder: string[] | null;
154
189
  savedAt: number;
190
+ slotConfig?: Record<string, SlotConfigEntry>;
155
191
  };
156
192
  /** Returns null on missing, corrupt, or wrong-version data — never throws. */
157
193
  declare function readSnapshot(apiKey: string): DecisionSnapshot | null;
@@ -170,6 +206,9 @@ declare function writeSnapshot(apiKey: string, snap: DecisionSnapshot): void;
170
206
  */
171
207
  declare function renderPrePaintScript(apiKey: string): string;
172
208
 
209
+ declare const PROD_KEYLESS_ERROR = "[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.";
210
+ declare const LOCAL_MODE_BANNER = "[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.";
211
+
173
212
  type MicroSignalEmitter = (signalType: 'rage_click' | 'text_copy' | 'scroll_hesitation' | 'tab_loss', extra?: Record<string, unknown>) => void;
174
213
  type MicroSignalType = Parameters<MicroSignalEmitter>[0];
175
214
  /**
@@ -263,12 +302,23 @@ type AssignResult = {
263
302
  content?: string;
264
303
  };
265
304
 
305
+ /** An editor-defined goal delivered with a registry-mode decision, for the
306
+ * snippet to install delegated listeners from. */
307
+ type GoalDefinition = {
308
+ goalId: string;
309
+ event: 'click' | 'form_submit' | 'url_reached';
310
+ locator?: CompoundLocator;
311
+ urlPattern?: string;
312
+ slotId?: string;
313
+ };
266
314
  type DecideOutcome = {
267
315
  layoutOrder: string[] | null;
268
316
  assignments: Record<string, string>;
269
317
  slots: Record<string, SlotResult>;
270
318
  persona: string;
271
319
  confidence: number;
320
+ slotConfig?: Record<string, SlotConfigEntry>;
321
+ goals?: GoalDefinition[];
272
322
  };
273
323
  type DecideInput = {
274
324
  sections?: string[];
@@ -277,6 +327,7 @@ type DecideInput = {
277
327
  variantIds?: string[];
278
328
  }>;
279
329
  slots?: SlotDeclInput[];
330
+ slotsFrom?: 'request' | 'registry';
280
331
  };
281
332
  type WeightEntry = {
282
333
  variantId: string;
@@ -366,4 +417,4 @@ declare function grantConsent(apiKey?: string): void;
366
417
  */
367
418
  declare function init(config: SentientConfig): SentientClient;
368
419
 
369
- export { type AssignResult, type Assignment, type AssignmentCache, type ComponentGoalOptions, type ComponentWeightEntry, type ContentAddedEvent, type DOMScanner, type DecideInput, type DecideOutcome, type DecisionSnapshot, type EventQueue, type EventType, type GraphClient, type GraphConfig, type GraphSnapshot, LOCAL_MODE_BANNER, type MicroSignalEmitter, type MicroSignalType, PROD_KEYLESS_ERROR, type PageNode, type QueueConfig, SNAPSHOT_STORAGE_KEY_PREFIX, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type SessionConfig, type SessionManager, SlotDeclInput, type WeightEntry, attachMicroSignalDetectors, grantConsent, init, isDoNotTrackEnabled, readSnapshot, renderPrePaintScript, writeSnapshot };
420
+ export { type AssignResult, type Assignment, type AssignmentCache, type ComponentGoalOptions, type ComponentWeightEntry, type CompoundLocator, type ContentAddedEvent, type DOMScanner, type DecideInput, type DecideOutcome, type DecisionSnapshot, type EventQueue, type EventType, type GoalDefinition, type GraphClient, type GraphConfig, type GraphSnapshot, LOCAL_MODE_BANNER, type MicroSignalEmitter, type MicroSignalType, PROD_KEYLESS_ERROR, type PageNode, type QueueConfig, SNAPSHOT_STORAGE_KEY_PREFIX, type ScanResult, type ScannedNode, type SentientClient, type SentientConfig, type SentientEvent, type SessionConfig, type SessionManager, type SlotConfigEntry, SlotDeclInput, type SlotOps, type WeightEntry, attachMicroSignalDetectors, grantConsent, init, isDoNotTrackEnabled, readSnapshot, renderPrePaintScript, writeSnapshot };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var ze=Object.create;var te=Object.defineProperty,He=Object.defineProperties,Ve=Object.getOwnPropertyDescriptor,Xe=Object.getOwnPropertyDescriptors,qe=Object.getOwnPropertyNames,Ce=Object.getOwnPropertySymbols,Ze=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var Te=(e,t,n)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))Pe.call(t,n)&&Te(e,n,t[n]);if(Ce)for(var n of Ce(t))et.call(t,n)&&Te(e,n,t[n]);return e},j=(e,t)=>He(e,Xe(t));var tt=(e,t)=>{for(var n in t)te(e,n,{get:t[n],enumerable:!0})},Le=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of qe(t))!Pe.call(e,d)&&d!==n&&te(e,d,{get:()=>t[d],enumerable:!(a=Ve(t,d))||a.enumerable});return e};var nt=(e,t,n)=>(n=e!=null?ze(Ze(e)):{},Le(t||!e||!e.__esModule?te(n,"default",{value:e,enumerable:!0}):n,e)),rt=e=>Le(te({},"__esModule",{value:!0}),e);var Rt={};tt(Rt,{LOCAL_MODE_BANNER:()=>Ie,PROD_KEYLESS_ERROR:()=>me,SNAPSHOT_STORAGE_KEY_PREFIX:()=>$,agentUaList:()=>Ee,armOfResult:()=>ue,attachMicroSignalDetectors:()=>je,baselineResultFor:()=>Q,baselineSlots:()=>Ge,deriveSessionSegment:()=>Ke,detectDeviceClass:()=>re,detectTimeOfDay:()=>ie,detectTrafficSource:()=>oe,grantConsent:()=>It,init:()=>Ye,isDoNotTrackEnabled:()=>ke,matchedAgentToken:()=>xe,readSnapshot:()=>ge,referrerDomainFromReferer:()=>se,renderPrePaintScript:()=>Be,toWireSlot:()=>ae,uaTokenMatch:()=>ne,writeSnapshot:()=>Y});module.exports=rt(Rt);var ot="_snt_uid";var F="_snt_uid";function st(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function it(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function at(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(a){}}function lt(e){try{return localStorage.getItem(e)}catch(t){return null}}function ct(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function dt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ut(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function gt(e){try{sessionStorage.removeItem(e)}catch(t){}}function ft(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function pt(e){try{localStorage.removeItem(e)}catch(t){}}function mt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var yt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ce(e){var c,g,p,h,b,S;if(typeof window=="undefined")return yt;let t=(c=e==null?void 0:e.cookieName)!=null?c:ot,a=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,d=(S=(b=(h=(p=it(t))!=null?p:lt(F))!=null?h:dt(F))!=null?b:e==null?void 0:e.ssrSessionId)!=null?S:st();at(t,d,a);let s=ct(F,d),l=ft(t),o=s?!1:ut(F,d),r=!s&&!l&&!o;return{getSessionId:()=>d,isEphemeral:()=>r,destroy:()=>{d=null,mt(t),pt(F),gt(F)}}}function ve(e){return`_snt_retry_${e.slice(0,12)}`}var St={push:()=>{},flush:()=>{},destroy:()=>{}};function ht(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let a=JSON.parse(n);return Array.isArray(a)?(localStorage.removeItem(t),a.slice(-e)):[]}catch(n){return[]}}function he(e,t,n){try{let d=[...(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let l=JSON.parse(s);return Array.isArray(l)?l:[]}catch(s){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(d))}catch(a){}}function Ne(e){var X,q,Z;if(typeof window=="undefined")return St;let t=(X=e.flushIntervalMs)!=null?X:5e3,n=(q=e.maxBatchSize)!=null?q:20,a=(Z=e.maxRetrySize)!=null?Z:100,d=e.ingestUrl,s=e.apiKey,l=ve(s),o=[],r=new Set,c=[],g=f=>{for(let y of f)p.delete(y),!r.has(y)&&(r.add(y),c.push(y));for(;c.length>500;){let y=c.shift();y&&r.delete(y)}},p=new Set,h=f=>{r.has(f.id)||p.has(f.id)||(p.add(f.id),o.push(f))},b=ht(a,l);for(let f of b)h(f);let S=0,_=0,R=f=>{if(f.length===0)return;let y=JSON.stringify(f),x=f.map(i=>i.id),A;try{A=fetch(d,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(i){he(f,a,l);for(let u of x)p.delete(u);_++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(_,6));return}let L=i=>{if(i.ok||i.status>=400&&i.status<500&&i.status!==429){g(x),_=0,S=0;return}he(f,a,l);for(let u of x)p.delete(u);_++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(_,6))};A instanceof Promise?A.then(L).catch(()=>{he(f,a,l);for(let i of x)p.delete(i);_++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(_,6))}):L(A)},w=typeof TextEncoder!="undefined"?new TextEncoder:null,le=f=>w?w.encode(f).length:f.length,U=f=>{let y=[],x=2;for(let A of f){let L=le(JSON.stringify(A))+1;if(y.length>0&&x+L>57344||y.length>=n)break;y.push(A),x+=L}return y},C=()=>{try{if(Date.now()<S)return;for(;o.length>0;){let f=o.filter(x=>!r.has(x.id));if(o.length=0,f.length===0)break;let y=U(f);if(y.length===0)break;y.length<f.length&&o.push(...f.slice(y.length)),R(y)}}catch(f){}},k=!0,K=null;K=setInterval(()=>{k&&C()},t);let H=()=>{document.visibilityState==="hidden"&&C()},V=()=>{C()};return document.addEventListener("visibilitychange",H),window.addEventListener("beforeunload",V),{push(f){h(f),o.length>=n&&C()},flush:C,destroy(){k=!1,K!==null&&(clearInterval(K),K=null),document.removeEventListener("visibilitychange",H),window.removeEventListener("beforeunload",V),C()}}}var be="_snt_asgn_";function de(e,t){return`${e}:${t}`}function vt(e,t){return`${be}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Me(e){let t=e.slice(be.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(a){return null}}function we(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(be)&&e.push(n)}return e}catch(e){return[]}}function Ue(e=18e5){let t=new Map,n=d=>d.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let d of we())try{let s=localStorage.getItem(d);if(!s)continue;let l=JSON.parse(s);if(n(l)){localStorage.removeItem(d);continue}let o=Me(d);if(!o)continue;t.set(de(o.componentId,o.segment),l)}catch(s){}})(),{get(d,s){let l=t.get(de(d,s));return l?n(l)?(t.delete(de(d,s)),null):l:null},set(d,s,l){let o=de(d,s);t.set(o,l);try{localStorage.setItem(vt(d,s),JSON.stringify(l))}catch(r){}},invalidate(d){let s=`${d}:`;for(let l of[...t.keys()])l.startsWith(s)&&t.delete(l);for(let l of we()){let o=Me(l);if((o==null?void 0:o.componentId)===d)try{localStorage.removeItem(l)}catch(r){}}},clear(){t.clear();for(let d of we())try{localStorage.removeItem(d)}catch(s){}}}}var Ee=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function ne(e){return xe(e)!==null}function xe(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ee.find(a=>t.includes(a.toLowerCase())))!=null?n:null}function re(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function oe(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(d){}let a=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(a)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(a)?"social":"referral"}catch(n){return"direct"}}function se(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function ie(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ke(e){let t=wt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function wt(e,t){var s,l,o,r,c,g,p;let n=(l=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?l:"",a=(r=(o=t==null?void 0:t.referer)==null?void 0:o.trim())!=null?r:"",d=(c=t==null?void 0:t.now)!=null?c:new Date;return{sessionId:e,ephemeral:!1,utmParams:(g=t==null?void 0:t.utmParams)!=null?g:{},deviceClass:n?re(n):"desktop",trafficSource:a?oe(a,t==null?void 0:t.appOrigin):"direct",referrerDomain:se(a),timeOfDay:ie(d),dayOfWeek:(p=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?p:"sun",automation:(t==null?void 0:t.webdriver)===!0||ne(n)}}var J=require("@sentientui/policy");function ae(e){return v(v(v({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function Q(e){let t=ae(e);return(0,J.slotResultFor)(t,(0,J.slotBaselineArm)(t))}function Ge(e){let t={};for(let n of e)t[n.id]=Q(n);return t}function ue(e){return typeof e=="string"?e:(0,J.canonicalArm)(e)}var $="_snt_snap:",bt=["low","medium","high"];function ge(e){try{let t=localStorage.getItem($+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!bt.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"?null:n}catch(t){return null}}function Y(e,t){try{localStorage.setItem($+e,JSON.stringify(t))}catch(n){}}function Be(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify($+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}var Re=require("@sentientui/policy");var pe=require("@sentientui/policy");var me="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ie="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",$e=!1,fe=!1;function Et(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function We(e){var o;let t=ce({ssrSessionId:e.ssrSessionId}),n=(o=t.getSessionId())!=null?o:"local",a=Et(),d=import("@sentientui/core/local").then(r=>{let c=r;return c.LOCAL_ENGINE_AVAILABLE?($e||($e=!0,console.info(Ie)),c):(fe||(fe=!0,console.error(me)),null)}).catch(()=>(fe||(fe=!0,console.error(me)),null)),s=null;function l(r){let c=document.documentElement;c.dataset.sentientPersona===void 0&&(c.dataset.sentientPersona=r.persona,c.dataset.sentientConfidence=(0,pe.confidenceBand)(r.confidence))}return{isLocal:!0,async decide(r){var p,h,b;let c=await d;if(!c)return null;let g=c.createLocalEngine({sessionId:n,forcedPersona:a}).decide(r);return s=j(v({},g),{layoutOrder:(h=(p=g.layoutOrder)!=null?p:s==null?void 0:s.layoutOrder)!=null?h:null,slots:v(v({},(b=s==null?void 0:s.slots)!=null?b:{}),g.slots)}),Y(e.apiKey||"local",{v:1,persona:s.persona,band:(0,pe.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),l(g),g},getSlotResult(r){var c,g,p;return(p=(g=s==null?void 0:s.slots[r])!=null?g:(c=e.initialSlots)==null?void 0:c[r])!=null?p:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,pe.confidenceBand)(s.confidence)}:null},async assign(r,c){var h;let g=await d;return!g||!c||c.length===0?c!=null&&c[0]?{variantId:c[0],assignmentTtlMs:0}:null:{variantId:(h=g.createLocalEngine({sessionId:n,forcedPersona:a}).decide({components:[{id:r,variantIds:c}]}).assignments[r])!=null?h:c[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function je(e,t,n){var d;let a=[];{let o=!1,r=[],c=()=>{if(o)return;let g=Date.now();for(r.push(g);r.length>0&&g-r[0]>500;)r.shift();r.length>=3&&(o=!0,e("rage_click"))};t.addEventListener("click",c),a.push(()=>t.removeEventListener("click",c))}{let s=!1,l=o=>{if(s||!(o.target instanceof Node)||!t.contains(o.target)&&t!==o.target)return;s=!0;let r=typeof window!="undefined"?window.getSelection():null,c=r?r.toString().length:0;e("text_copy",{selectionLength:c})};document.addEventListener("copy",l),a.push(()=>document.removeEventListener("copy",l))}{let s=!1,l=!1,o=null,r=()=>{o!==null&&(clearTimeout(o),o=null)},c=()=>{s||!l||(r(),o=setTimeout(()=>{!s&&l&&(s=!0,e("scroll_hesitation"))},3e3))},g=()=>{r(),c()},p=b=>{for(let S of b)l=S.intersectionRatio>.3,l?c():r()};typeof process!="undefined"&&((d=process.env)==null?void 0:d.NODE_ENV)!=="production"&&(window.__lastIOCallback=p);let h=new IntersectionObserver(p,{threshold:[.3]});h.observe(t),window.addEventListener("scroll",g,{passive:!0}),a.push(()=>{h.disconnect(),window.removeEventListener("scroll",g),r()})}{let s=!1,l=n!=null?n:Date.now(),o=()=>{if(s||document.visibilityState!=="hidden")return;let r=Date.now()-l;r<15e3&&(s=!0,e("tab_loss",{timeOnPage:r}))};document.addEventListener("visibilitychange",o),a.push(()=>document.removeEventListener("visibilitychange",o))}return()=>{for(let s of a)s()}}var Fe="https://api.sentient-ui.com/v1/events",W=new Map,Je=null;function _e(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var z={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function xt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,a]of t)n.startsWith("utm_")&&(e[n]=a);return e}catch(e){return{}}}function Qe(e){return e.replace(/\/events\/?$/,"")}function ke(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function It(e){if(typeof window=="undefined")return;let t=e!=null?e:Je;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=W.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:a,upgrade:d}=n;if(!d||a.respectDoNotTrack!==!1&&ke())return;let s=Ye(j(v({},a),{consent:!0}));d(s),W.set(t,{config:j(v({},a),{consent:!0}),upgrade:null})}function _t(e){var l;let t=Qe((l=e.ingestUrl)!=null?l:Fe),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},a={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(o,r,c){try{let g=new URLSearchParams({componentId:o});for(let b of r!=null?r:[])g.append("variantIds[]",b);let p=await fetch(`${t}/winner?${g.toString()}`,{headers:n});return p.ok?{variantId:(await p.json()).variantId,assignmentTtlMs:0}:r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}catch(g){return r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},d={track:o=>a.track(o),goal:(o,r,c,g)=>a.goal(o,r,c,g),componentGoal:(o,r,c)=>a.componentGoal(o,r,c),identify:o=>a.identify(o),getAssignment:(o,r)=>a.getAssignment(o,r),assign:(o,r,c,g)=>a.assign(o,r,c,g),decide:o=>a.decide(o),getSlotResult:o=>a.getSlotResult(o),getPersona:()=>a.getPersona(),fetchWeights:()=>a.fetchWeights(),getGraph:()=>a.getGraph(),dispose:()=>a.dispose(),destroy:()=>a.destroy()};function s(o){a=o}return{proxy:d,setInner:s}}function Ye(e){var V,X,q,Z,f,y,x,A,L;if(typeof window=="undefined")return z;Je=e.apiKey;let t=e.respectDoNotTrack!==!1&&ke(),n=e.consent===!1||t,a=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!a&&e.localMode!==!1)return n?(W.set(e.apiKey||"local",{config:e,upgrade:null}),z):(W.set(e.apiKey||"local",{config:e,upgrade:null}),We(e));if(n){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),z;let{proxy:i,setInner:u}=_t(e);return W.set(e.apiKey,{config:e,upgrade:t?null:u}),i}return W.set(e.apiKey,{config:e,upgrade:null}),z}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),z;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),z;let d=(V=e.ingestUrl)!=null?V:Fe,s=Date.now(),l=ce({ssrSessionId:e.ssrSessionId}),o=Ue(),r=Ne({ingestUrl:d,apiKey:e.apiKey}),c=Qe(d),g={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},p=re((X=navigator.userAgent)!=null?X:""),h=typeof window!="undefined"?window.location.origin:void 0,b=oe((q=document.referrer)!=null?q:"",h),S=(Z=e.sessionSegment)!=null?Z:`${p}:${b}`,_=new Map,R=new Map,w=null,le=i=>{for(let u of i)R.has(u.id)||R.set(u.id,Q(u))};if(e.initialSlots)for(let[i,u]of Object.entries(e.initialSlots))R.set(i,u);let U=ge(e.apiKey);if(U)for(let[i,u]of Object.entries(U.slots))R.has(i)||R.set(i,u);let C={low:.15,medium:.5,high:.85};if(e.initialPersona)w=v({},e.initialPersona);else{let i=document.documentElement.dataset;i.sentientPersona?w={persona:i.sentientPersona,confidence:(y=C[(f=i.sentientConfidence)!=null?f:"low"])!=null?y:.15}:U&&(w={persona:U.persona,confidence:(x=C[U.band])!=null?x:.15})}if(e.initialAssignments)for(let[i,u]of Object.entries(e.initialAssignments))o.set(i,S,{variantId:u,assignedAt:Date.now(),segment:S,confidence:1});let k=Promise.resolve(),K=l.getSessionId();if(K){let i=se((A=document.referrer)!=null?A:""),u=v(v({sessionId:K,deviceClass:p,trafficSource:b,referrerDomain:i,utmParams:xt(),timeOfDay:ie(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:l.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||ne((L=navigator.userAgent)!=null?L:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{k=fetch(`${c}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(u),headers:g}).then(m=>{m.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(m){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:r});let H={goal(i,u={},m=1,D=0){let E=l.getSessionId();if(!E)return;let I=_e();k.then(()=>{fetch(`${c}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:E,name:i,metadata:u,weight:m,stepIndex:D,goalId:I}),headers:g}).catch(()=>{})})},componentGoal(i,u,m){var O,M,T;let D=l.getSessionId();if(!D)return;let E=o.get(i,S),I=E?null:(O=R.get(i))!=null?O:null;if(!E&&I===null){e.debug&&console.warn(`[sentient] componentGoal("${i}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let G=E?E.variantId:ue(I),N={id:_e(),sessionId:D,projectId:e.apiKey,componentId:i,variantId:G,eventType:"goal_achieved",goalType:u,payload:v({reward:(M=m==null?void 0:m.reward)!=null?M:1},(T=m==null?void 0:m.metadata)!=null?T:{}),timestamp:Date.now(),timeInSession:Date.now()-s};e.debug&&console.log("[sentient] componentGoal",N),k.then(()=>r.push(N))},identify(i){let u=l.getSessionId();u&&k.then(()=>{fetch(`${c}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:u,userId:i,ephemeral:l.isEphemeral()}),headers:g}).catch(()=>{})})},track(i){let u=l.getSessionId();if(!u)return;let m=j(v({},i),{id:_e(),sessionId:u,timestamp:Date.now(),timeInSession:Date.now()-s});e.debug&&console.log("[sentient] track",m),k.then(()=>r.push(m))},getAssignment(i,u){return o.get(i,u)},async assign(i,u,m,D){let E=l.getSessionId();if(!E)return null;let I=o.get(i,S);if(I&&(u!=null&&u.length||I.content!==void 0))return{variantId:I.variantId,assignmentTtlMs:0,content:I.content};let G=_.get(i);if(G)return G;let N=(async()=>{await k;try{let O={sessionId:E,componentId:i,variantIds:u};D!==void 0?O.agentDataByVariant=D:m!==void 0&&(O.agentData=m);let M=await fetch(`${c}/assign`,{method:"POST",body:JSON.stringify(O),headers:g});if(!M.ok)return null;let T=await M.json();return o.set(i,S,{variantId:T.variantId,assignedAt:Date.now(),segment:S,confidence:1,content:T.content}),T}catch(O){return null}finally{_.delete(i)}})();return _.set(i,N),N},async decide(i){var D,E,I,G,N,O,M,T,Ae,De;let u=l.getSessionId();if(!u)return null;let m=(D=i.slots)!=null?D:[];await k;try{let ee={sessionId:u};i.sections&&i.sections.length>0&&(ee.sections=i.sections.map(P=>({id:P}))),ee.components=(E=i.components)!=null?E:[],m.length>0&&(ee.slots=m.map(ae));let Oe=await fetch(`${c}/decide`,{method:"POST",body:JSON.stringify(ee),headers:g});if(!Oe.ok)return le(m),null;let B=await Oe.json(),ye={};for(let P of m)ye[P.id]=(G=(I=B.slots)==null?void 0:I[P.id])!=null?G:Q(P);for(let[P,Se]of Object.entries(ye))R.set(P,Se);w={persona:(N=B.persona)!=null?N:"unknown",confidence:(O=B.confidence)!=null?O:0};for(let[P,Se]of Object.entries((M=B.assignments)!=null?M:{}))o.set(P,S,{variantId:Se,assignedAt:Date.now(),segment:S,confidence:1});return Y(e.apiKey,{v:1,persona:w.persona,band:(0,Re.confidenceBand)(w.confidence),slots:Object.fromEntries(R),layoutOrder:(T=B.layoutOrder)!=null?T:null,savedAt:Date.now()}),{layoutOrder:(Ae=B.layoutOrder)!=null?Ae:null,assignments:(De=B.assignments)!=null?De:{},slots:ye,persona:w.persona,confidence:w.confidence}}catch(ee){return le(m),null}},getSlotResult(i){var u;return(u=R.get(i))!=null?u:null},getPersona(){return w?{persona:w.persona,confidence:w.confidence,band:(0,Re.confidenceBand)(w.confidence)}:null},async fetchWeights(){var i;try{let u=await fetch(`${c}/weights`,{headers:g});return u.ok?(i=(await u.json()).components)!=null?i:[]:[]}catch(u){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){r.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){r.destroy(),l.destroy();try{localStorage.removeItem($+e.apiKey),localStorage.removeItem(ve(e.apiKey))}catch(i){}e.debug&&console.log("[sentient] destroyed")}};if(W.set(e.apiKey,{config:e,upgrade:null}),e.debug){let i=window;i.__sentient&&(i.__sentient.client=H)}return H}0&&(module.exports={LOCAL_MODE_BANNER,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,toWireSlot,uaTokenMatch,writeSnapshot});
1
+ "use strict";var ze=Object.create;var oe=Object.defineProperty,He=Object.defineProperties,Ve=Object.getOwnPropertyDescriptor,qe=Object.getOwnPropertyDescriptors,Xe=Object.getOwnPropertyNames,Oe=Object.getOwnPropertySymbols,Ze=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var Te=(e,t,n)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,h=(e,t)=>{for(var n in t||(t={}))Pe.call(t,n)&&Te(e,n,t[n]);if(Oe)for(var n of Oe(t))et.call(t,n)&&Te(e,n,t[n]);return e},F=(e,t)=>He(e,qe(t));var tt=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Le=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of Xe(t))!Pe.call(e,d)&&d!==n&&oe(e,d,{get:()=>t[d],enumerable:!(a=Ve(t,d))||a.enumerable});return e};var nt=(e,t,n)=>(n=e!=null?ze(Ze(e)):{},Le(t||!e||!e.__esModule?oe(n,"default",{value:e,enumerable:!0}):n,e)),ot=e=>Le(oe({},"__esModule",{value:!0}),e);var _t={};tt(_t,{LOCAL_MODE_BANNER:()=>Ie,PROD_KEYLESS_ERROR:()=>Se,SNAPSHOT_STORAGE_KEY_PREFIX:()=>$,agentUaList:()=>Ee,armOfResult:()=>fe,attachMicroSignalDetectors:()=>je,baselineResultFor:()=>Y,baselineSlots:()=>Ge,deriveSessionSegment:()=>Ke,detectDeviceClass:()=>se,detectTimeOfDay:()=>le,detectTrafficSource:()=>ie,grantConsent:()=>It,init:()=>Ye,isDoNotTrackEnabled:()=>Re,matchedAgentToken:()=>xe,readSnapshot:()=>pe,referrerDomainFromReferer:()=>ae,renderPrePaintScript:()=>Be,toWireSlot:()=>ce,uaTokenMatch:()=>re,writeSnapshot:()=>z});module.exports=ot(_t);var rt="_snt_uid";var J="_snt_uid";function st(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function it(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function at(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(a){}}function lt(e){try{return localStorage.getItem(e)}catch(t){return null}}function ct(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function dt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ut(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function gt(e){try{sessionStorage.removeItem(e)}catch(t){}}function ft(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function pt(e){try{localStorage.removeItem(e)}catch(t){}}function mt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var yt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ue(e){var c,g,p,v,E,S;if(typeof window=="undefined")return yt;let t=(c=e==null?void 0:e.cookieName)!=null?c:rt,a=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,d=(S=(E=(v=(p=it(t))!=null?p:lt(J))!=null?v:dt(J))!=null?E:e==null?void 0:e.ssrSessionId)!=null?S:st();at(t,d,a);let s=ct(J,d),l=ft(t),r=s?!1:ut(J,d),o=!s&&!l&&!r;return{getSessionId:()=>d,isEphemeral:()=>o,destroy:()=>{d=null,mt(t),pt(J),gt(J)}}}function ve(e){return`_snt_retry_${e.slice(0,12)}`}var St={push:()=>{},flush:()=>{},destroy:()=>{}};function ht(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let a=JSON.parse(n);return Array.isArray(a)?(localStorage.removeItem(t),a.slice(-e)):[]}catch(n){return[]}}function he(e,t,n){try{let d=[...(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let l=JSON.parse(s);return Array.isArray(l)?l:[]}catch(s){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(d))}catch(a){}}function Ne(e){var X,Z,ee;if(typeof window=="undefined")return St;let t=(X=e.flushIntervalMs)!=null?X:5e3,n=(Z=e.maxBatchSize)!=null?Z:20,a=(ee=e.maxRetrySize)!=null?ee:100,d=e.ingestUrl,s=e.apiKey,l=ve(s),r=[],o=new Set,c=[],g=f=>{for(let y of f)p.delete(y),!o.has(y)&&(o.add(y),c.push(y));for(;c.length>500;){let y=c.shift();y&&o.delete(y)}},p=new Set,v=f=>{o.has(f.id)||p.has(f.id)||(p.add(f.id),r.push(f))},E=ht(a,l);for(let f of E)v(f);let S=0,R=0,k=f=>{if(f.length===0)return;let y=JSON.stringify(f),I=f.map(i=>i.id),D;try{D=fetch(d,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(i){he(f,a,l);for(let u of I)p.delete(u);R++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6));return}let N=i=>{if(i.ok||i.status>=400&&i.status<500&&i.status!==429){g(I),R=0,S=0;return}he(f,a,l);for(let u of I)p.delete(u);R++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6))};D instanceof Promise?D.then(N).catch(()=>{he(f,a,l);for(let i of I)p.delete(i);R++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(R,6))}):N(D)},w=typeof TextEncoder!="undefined"?new TextEncoder:null,de=f=>w?w.encode(f).length:f.length,K=f=>{let y=[],I=2;for(let D of f){let N=de(JSON.stringify(D))+1;if(y.length>0&&I+N>57344||y.length>=n)break;y.push(D),I+=N}return y},P=()=>{try{if(Date.now()<S)return;for(;r.length>0;){let f=r.filter(I=>!o.has(I.id));if(r.length=0,f.length===0)break;let y=K(f);if(y.length===0)break;y.length<f.length&&r.push(...f.slice(y.length)),k(y)}}catch(f){}},A=!0,G=null;G=setInterval(()=>{A&&P()},t);let V=()=>{document.visibilityState==="hidden"&&P()},q=()=>{P()};return document.addEventListener("visibilitychange",V),window.addEventListener("beforeunload",q),{push(f){v(f),r.length>=n&&P()},flush:P,destroy(){A=!1,G!==null&&(clearInterval(G),G=null),document.removeEventListener("visibilitychange",V),window.removeEventListener("beforeunload",q),P()}}}var be="_snt_asgn_";function ge(e,t){return`${e}:${t}`}function vt(e,t){return`${be}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Me(e){let t=e.slice(be.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(a){return null}}function we(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(be)&&e.push(n)}return e}catch(e){return[]}}function Ue(e=18e5){let t=new Map,n=d=>d.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let d of we())try{let s=localStorage.getItem(d);if(!s)continue;let l=JSON.parse(s);if(n(l)){localStorage.removeItem(d);continue}let r=Me(d);if(!r)continue;t.set(ge(r.componentId,r.segment),l)}catch(s){}})(),{get(d,s){let l=t.get(ge(d,s));return l?n(l)?(t.delete(ge(d,s)),null):l:null},set(d,s,l){let r=ge(d,s);t.set(r,l);try{localStorage.setItem(vt(d,s),JSON.stringify(l))}catch(o){}},invalidate(d){let s=`${d}:`;for(let l of[...t.keys()])l.startsWith(s)&&t.delete(l);for(let l of we()){let r=Me(l);if((r==null?void 0:r.componentId)===d)try{localStorage.removeItem(l)}catch(o){}}},clear(){t.clear();for(let d of we())try{localStorage.removeItem(d)}catch(s){}}}}var Ee=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function re(e){return xe(e)!==null}function xe(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ee.find(a=>t.includes(a.toLowerCase())))!=null?n:null}function se(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function ie(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(d){}let a=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(a)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(a)?"social":"referral"}catch(n){return"direct"}}function ae(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function le(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ke(e){let t=wt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function wt(e,t){var s,l,r,o,c,g,p;let n=(l=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?l:"",a=(o=(r=t==null?void 0:t.referer)==null?void 0:r.trim())!=null?o:"",d=(c=t==null?void 0:t.now)!=null?c:new Date;return{sessionId:e,ephemeral:!1,utmParams:(g=t==null?void 0:t.utmParams)!=null?g:{},deviceClass:n?se(n):"desktop",trafficSource:a?ie(a,t==null?void 0:t.appOrigin):"direct",referrerDomain:ae(a),timeOfDay:le(d),dayOfWeek:(p=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?p:"sun",automation:(t==null?void 0:t.webdriver)===!0||re(n)}}var Q=require("@sentientui/policy");function ce(e){return h(h(h({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function Y(e){let t=ce(e);return(0,Q.slotResultFor)(t,(0,Q.slotBaselineArm)(t))}function Ge(e){let t={};for(let n of e)t[n.id]=Y(n);return t}function fe(e){return typeof e=="string"?e:(0,Q.canonicalArm)(e)}var $="_snt_snap:",bt=["low","medium","high"];function pe(e){try{let t=localStorage.getItem($+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!bt.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function z(e,t){try{localStorage.setItem($+e,JSON.stringify(t))}catch(n){}}function Be(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify($+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}var _e=require("@sentientui/policy");var ye=require("@sentientui/policy");var Se="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ie="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",$e=!1,me=!1;function Et(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function We(e){var r;let t=ue({ssrSessionId:e.ssrSessionId}),n=(r=t.getSessionId())!=null?r:"local",a=Et(),d=import("@sentientui/core/local").then(o=>{let c=o;return c.LOCAL_ENGINE_AVAILABLE?($e||($e=!0,console.info(Ie)),c):(me||(me=!0,console.error(Se)),null)}).catch(()=>(me||(me=!0,console.error(Se)),null)),s=null;function l(o){let c=document.documentElement;c.dataset.sentientPersona===void 0&&(c.dataset.sentientPersona=o.persona,c.dataset.sentientConfidence=(0,ye.confidenceBand)(o.confidence))}return{isLocal:!0,async decide(o){var p,v,E;let c=await d;if(!c)return null;let g=c.createLocalEngine({sessionId:n,forcedPersona:a}).decide(o);return s=F(h({},g),{layoutOrder:(v=(p=g.layoutOrder)!=null?p:s==null?void 0:s.layoutOrder)!=null?v:null,slots:h(h({},(E=s==null?void 0:s.slots)!=null?E:{}),g.slots)}),z(e.apiKey||"local",{v:1,persona:s.persona,band:(0,ye.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),l(g),g},getSlotResult(o){var c,g,p;return(p=(g=s==null?void 0:s.slots[o])!=null?g:(c=e.initialSlots)==null?void 0:c[o])!=null?p:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,ye.confidenceBand)(s.confidence)}:null},async assign(o,c){var v;let g=await d;return!g||!c||c.length===0?c!=null&&c[0]?{variantId:c[0],assignmentTtlMs:0}:null:{variantId:(v=g.createLocalEngine({sessionId:n,forcedPersona:a}).decide({components:[{id:o,variantIds:c}]}).assignments[o])!=null?v:c[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function je(e,t,n){var d;let a=[];{let r=!1,o=[],c=()=>{if(r)return;let g=Date.now();for(o.push(g);o.length>0&&g-o[0]>500;)o.shift();o.length>=3&&(r=!0,e("rage_click"))};t.addEventListener("click",c),a.push(()=>t.removeEventListener("click",c))}{let s=!1,l=r=>{if(s||!(r.target instanceof Node)||!t.contains(r.target)&&t!==r.target)return;s=!0;let o=typeof window!="undefined"?window.getSelection():null,c=o?o.toString().length:0;e("text_copy",{selectionLength:c})};document.addEventListener("copy",l),a.push(()=>document.removeEventListener("copy",l))}{let s=!1,l=!1,r=null,o=()=>{r!==null&&(clearTimeout(r),r=null)},c=()=>{s||!l||(o(),r=setTimeout(()=>{!s&&l&&(s=!0,e("scroll_hesitation"))},3e3))},g=()=>{o(),c()},p=E=>{for(let S of E)l=S.intersectionRatio>.3,l?c():o()};typeof process!="undefined"&&((d=process.env)==null?void 0:d.NODE_ENV)!=="production"&&(window.__lastIOCallback=p);let v=new IntersectionObserver(p,{threshold:[.3]});v.observe(t),window.addEventListener("scroll",g,{passive:!0}),a.push(()=>{v.disconnect(),window.removeEventListener("scroll",g),o()})}{let s=!1,l=n!=null?n:Date.now(),r=()=>{if(s||document.visibilityState!=="hidden")return;let o=Date.now()-l;o<15e3&&(s=!0,e("tab_loss",{timeOnPage:o}))};document.addEventListener("visibilitychange",r),a.push(()=>document.removeEventListener("visibilitychange",r))}return()=>{for(let s of a)s()}}var Fe="https://api.sentient-ui.com/v1/events",W=new Map,Je=null;function Ce(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var H={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function xt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,a]of t)n.startsWith("utm_")&&(e[n]=a);return e}catch(e){return{}}}function Qe(e){return e.replace(/\/events\/?$/,"")}function Re(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function It(e){if(typeof window=="undefined")return;let t=e!=null?e:Je;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=W.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:a,upgrade:d}=n;if(!d||a.respectDoNotTrack!==!1&&Re())return;let s=Ye(F(h({},a),{consent:!0}));d(s),W.set(t,{config:F(h({},a),{consent:!0}),upgrade:null})}function Ct(e){var l;let t=Qe((l=e.ingestUrl)!=null?l:Fe),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},a={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(r,o,c){try{let g=new URLSearchParams({componentId:r});for(let E of o!=null?o:[])g.append("variantIds[]",E);let p=await fetch(`${t}/winner?${g.toString()}`,{headers:n});return p.ok?{variantId:(await p.json()).variantId,assignmentTtlMs:0}:o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}catch(g){return o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},d={track:r=>a.track(r),goal:(r,o,c,g)=>a.goal(r,o,c,g),componentGoal:(r,o,c)=>a.componentGoal(r,o,c),identify:r=>a.identify(r),getAssignment:(r,o)=>a.getAssignment(r,o),assign:(r,o,c,g)=>a.assign(r,o,c,g),decide:r=>a.decide(r),getSlotResult:r=>a.getSlotResult(r),getPersona:()=>a.getPersona(),fetchWeights:()=>a.fetchWeights(),getGraph:()=>a.getGraph(),dispose:()=>a.dispose(),destroy:()=>a.destroy()};function s(r){a=r}return{proxy:d,setInner:s}}function Ye(e){var q,X,Z,ee,f,y,I,D,N;if(typeof window=="undefined")return H;Je=e.apiKey;let t=e.respectDoNotTrack!==!1&&Re(),n=e.consent===!1||t,a=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!a&&e.localMode!==!1)return n?(W.set(e.apiKey||"local",{config:e,upgrade:null}),H):(W.set(e.apiKey||"local",{config:e,upgrade:null}),We(e));if(n){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),H;let{proxy:i,setInner:u}=Ct(e);return W.set(e.apiKey,{config:e,upgrade:t?null:u}),i}return W.set(e.apiKey,{config:e,upgrade:null}),H}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),H;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),H;let d=(q=e.ingestUrl)!=null?q:Fe,s=Date.now(),l=ue({ssrSessionId:e.ssrSessionId}),r=Ue(),o=Ne({ingestUrl:d,apiKey:e.apiKey}),c=Qe(d),g={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},p=se((X=navigator.userAgent)!=null?X:""),v=typeof window!="undefined"?window.location.origin:void 0,E=ie((Z=document.referrer)!=null?Z:"",v),S=(ee=e.sessionSegment)!=null?ee:`${p}:${E}`,R=new Map,k=new Map,w=null,de=i=>{for(let u of i)k.has(u.id)||k.set(u.id,Y(u))};if(e.initialSlots)for(let[i,u]of Object.entries(e.initialSlots))k.set(i,u);let K=pe(e.apiKey);if(K)for(let[i,u]of Object.entries(K.slots))k.has(i)||k.set(i,u);let P={low:.15,medium:.5,high:.85};if(e.initialPersona)w=h({},e.initialPersona);else{let i=document.documentElement.dataset;i.sentientPersona?w={persona:i.sentientPersona,confidence:(y=P[(f=i.sentientConfidence)!=null?f:"low"])!=null?y:.15}:K&&(w={persona:K.persona,confidence:(I=P[K.band])!=null?I:.15})}if(e.initialAssignments)for(let[i,u]of Object.entries(e.initialAssignments))r.set(i,S,{variantId:u,assignedAt:Date.now(),segment:S,confidence:1});let A=Promise.resolve(),G=l.getSessionId();if(G){let i=ae((D=document.referrer)!=null?D:""),u=h(h({sessionId:G,deviceClass:p,trafficSource:E,referrerDomain:i,utmParams:xt(),timeOfDay:le(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:l.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||re((N=navigator.userAgent)!=null?N:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{A=fetch(`${c}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(u),headers:g}).then(m=>{m.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(m){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:o});let V={goal(i,u={},m=1,O=0){let x=l.getSessionId();if(!x)return;let C=Ce();A.then(()=>{fetch(`${c}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:x,name:i,metadata:u,weight:m,stepIndex:O,goalId:C}),headers:g}).catch(()=>{})})},componentGoal(i,u,m){var T,U,L;let O=l.getSessionId();if(!O)return;let x=r.get(i,S),C=x?null:(T=k.get(i))!=null?T:null;if(!x&&C===null){e.debug&&console.warn(`[sentient] componentGoal("${i}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let B=x?x.variantId:fe(C),M={id:Ce(),sessionId:O,projectId:e.apiKey,componentId:i,variantId:B,eventType:"goal_achieved",goalType:u,payload:h({reward:(U=m==null?void 0:m.reward)!=null?U:1},(L=m==null?void 0:m.metadata)!=null?L:{}),timestamp:Date.now(),timeInSession:Date.now()-s};e.debug&&console.log("[sentient] componentGoal",M),A.then(()=>o.push(M))},identify(i){let u=l.getSessionId();u&&A.then(()=>{fetch(`${c}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:u,userId:i,ephemeral:l.isEphemeral()}),headers:g}).catch(()=>{})})},track(i){let u=l.getSessionId();if(!u)return;let m=F(h({},i),{id:Ce(),sessionId:u,timestamp:Date.now(),timeInSession:Date.now()-s});e.debug&&console.log("[sentient] track",m),A.then(()=>o.push(m))},getAssignment(i,u){return r.get(i,u)},async assign(i,u,m,O){let x=l.getSessionId();if(!x)return null;let C=r.get(i,S);if(C&&(u!=null&&u.length||C.content!==void 0))return{variantId:C.variantId,assignmentTtlMs:0,content:C.content};let B=R.get(i);if(B)return B;let M=(async()=>{await A;try{let T={sessionId:x,componentId:i,variantIds:u};O!==void 0?T.agentDataByVariant=O:m!==void 0&&(T.agentData=m);let U=await fetch(`${c}/assign`,{method:"POST",body:JSON.stringify(T),headers:g});if(!U.ok)return null;let L=await U.json();return r.set(i,S,{variantId:L.variantId,assignedAt:Date.now(),segment:S,confidence:1,content:L.content}),L}catch(T){return null}finally{R.delete(i)}})();return R.set(i,M),M},async decide(i){var O,x,C,B,M,T,U,L,ke,Ae;let u=l.getSessionId();if(!u)return null;let m=(O=i.slots)!=null?O:[];await A;try{let j={sessionId:u};i.sections&&i.sections.length>0&&(j.sections=i.sections.map(_=>({id:_}))),j.components=(x=i.components)!=null?x:[],m.length>0&&(j.slots=m.map(ce)),i.slotsFrom==="registry"&&(j.slotsFrom="registry");let De=await fetch(`${c}/decide`,{method:"POST",body:JSON.stringify(j),headers:g});if(!De.ok)return de(m),null;let b=await De.json(),te={};for(let _ of m)te[_.id]=(B=(C=b.slots)==null?void 0:C[_.id])!=null?B:Y(_);if(b.slots)for(let[_,ne]of Object.entries(b.slots))_ in te||(te[_]=ne);for(let[_,ne]of Object.entries(te))k.set(_,ne);w={persona:(M=b.persona)!=null?M:"unknown",confidence:(T=b.confidence)!=null?T:0};for(let[_,ne]of Object.entries((U=b.assignments)!=null?U:{}))r.set(_,S,{variantId:ne,assignedAt:Date.now(),segment:S,confidence:1});return z(e.apiKey,h({v:1,persona:w.persona,band:(0,_e.confidenceBand)(w.confidence),slots:Object.fromEntries(k),layoutOrder:(L=b.layoutOrder)!=null?L:null,savedAt:Date.now()},b.slotConfig?{slotConfig:b.slotConfig}:{})),h(h({layoutOrder:(ke=b.layoutOrder)!=null?ke:null,assignments:(Ae=b.assignments)!=null?Ae:{},slots:te,persona:w.persona,confidence:w.confidence},b.slotConfig?{slotConfig:b.slotConfig}:{}),b.goals?{goals:b.goals}:{})}catch(j){return de(m),null}},getSlotResult(i){var u;return(u=k.get(i))!=null?u:null},getPersona(){return w?{persona:w.persona,confidence:w.confidence,band:(0,_e.confidenceBand)(w.confidence)}:null},async fetchWeights(){var i;try{let u=await fetch(`${c}/weights`,{headers:g});return u.ok?(i=(await u.json()).components)!=null?i:[]:[]}catch(u){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){o.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){o.destroy(),l.destroy();try{localStorage.removeItem($+e.apiKey),localStorage.removeItem(ve(e.apiKey))}catch(i){}e.debug&&console.log("[sentient] destroyed")}};if(W.set(e.apiKey,{config:e,upgrade:null}),e.debug){let i=window;i.__sentient&&(i.__sentient.client=V)}return V}0&&(module.exports={LOCAL_MODE_BANNER,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,toWireSlot,uaTokenMatch,writeSnapshot});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{a as m,b as n,c as o,d as p,e as q,f as r,g as s,h as t,i as u,j as v}from"./chunk-ZALZC4AD.mjs";import{a,b,c,d,e,f,g,h,j as i,k as j,l as k,m as l}from"./chunk-SVYHTU5Z.mjs";import"./chunk-HGGX55FR.mjs";export{r as LOCAL_MODE_BANNER,q as PROD_KEYLESS_ERROR,m as SNAPSHOT_STORAGE_KEY_PREFIX,a as agentUaList,l as armOfResult,s as attachMicroSignalDetectors,j as baselineResultFor,k as baselineSlots,h as deriveSessionSegment,d as detectDeviceClass,g as detectTimeOfDay,e as detectTrafficSource,u as grantConsent,v as init,t as isDoNotTrackEnabled,c as matchedAgentToken,n as readSnapshot,f as referrerDomainFromReferer,p as renderPrePaintScript,i as toWireSlot,b as uaTokenMatch,o as writeSnapshot};
1
+ import{a as m,b as n,c as o,d as p,e as q,f as r,g as s,h as t,i as u,j as v}from"./chunk-D35W3ODA.mjs";import{a,b,c,d,e,f,g,h,j as i,k as j,l as k,m as l}from"./chunk-SVYHTU5Z.mjs";import"./chunk-HGGX55FR.mjs";export{r as LOCAL_MODE_BANNER,q as PROD_KEYLESS_ERROR,m as SNAPSHOT_STORAGE_KEY_PREFIX,a as agentUaList,l as armOfResult,s as attachMicroSignalDetectors,j as baselineResultFor,k as baselineSlots,h as deriveSessionSegment,d as detectDeviceClass,g as detectTimeOfDay,e as detectTrafficSource,u as grantConsent,v as init,t as isDoNotTrackEnabled,c as matchedAgentToken,n as readSnapshot,f as referrerDomainFromReferer,p as renderPrePaintScript,i as toWireSlot,b as uaTokenMatch,o as writeSnapshot};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentientui/core",
3
- "version": "0.12.1",
3
+ "version": "0.13.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1 +0,0 @@
1
- import{b as ie,d as ae,e as le,f as ce,g as de,j as ue,k as ee,m as ge}from"./chunk-SVYHTU5Z.mjs";import{a as _,b as W}from"./chunk-HGGX55FR.mjs";var Ne="_snt_uid";var j="_snt_uid";function Me(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function Ue(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Ke(e,t,i){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${i}; SameSite=strict; path=/`}catch(c){}}function Ge(e){try{return localStorage.getItem(e)}catch(t){return null}}function $e(e,t){try{return localStorage.setItem(e,t),!0}catch(i){return!1}}function Be(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function We(e,t){try{return sessionStorage.setItem(e,t),!0}catch(i){return!1}}function je(e){try{sessionStorage.removeItem(e)}catch(t){}}function Fe(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function Je(e){try{localStorage.removeItem(e)}catch(t){}}function Qe(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Ye={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function te(e){var l,g,f,h,E,S;if(typeof window=="undefined")return Ye;let t=(l=e==null?void 0:e.cookieName)!=null?l:Ne,c=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,u=(S=(E=(h=(f=Ue(t))!=null?f:Ge(j))!=null?h:Be(j))!=null?E:e==null?void 0:e.ssrSessionId)!=null?S:Me();Ke(t,u,c);let s=$e(j,u),a=Fe(t),o=s?!1:We(j,u),n=!s&&!a&&!o;return{getSessionId:()=>u,isEphemeral:()=>n,destroy:()=>{u=null,Qe(t),Je(j),je(j)}}}function fe(e){return`_snt_retry_${e.slice(0,12)}`}var Ve={push:()=>{},flush:()=>{},destroy:()=>{}};function ze(e,t){try{let i=localStorage.getItem(t);if(!i)return[];let c=JSON.parse(i);return Array.isArray(c)?(localStorage.removeItem(t),c.slice(-e)):[]}catch(i){return[]}}function pe(e,t,i){try{let u=[...(()=>{try{let s=localStorage.getItem(i);if(!s)return[];let a=JSON.parse(s);return Array.isArray(a)?a:[]}catch(s){return[]}})(),...e].slice(-t);localStorage.setItem(i,JSON.stringify(u))}catch(c){}}function _e(e){var V,z,H;if(typeof window=="undefined")return Ve;let t=(V=e.flushIntervalMs)!=null?V:5e3,i=(z=e.maxBatchSize)!=null?z:20,c=(H=e.maxRetrySize)!=null?H:100,u=e.ingestUrl,s=e.apiKey,a=fe(s),o=[],n=new Set,l=[],g=p=>{for(let y of p)f.delete(y),!n.has(y)&&(n.add(y),l.push(y));for(;l.length>500;){let y=l.shift();y&&n.delete(y)}},f=new Set,h=p=>{n.has(p.id)||f.has(p.id)||(f.add(p.id),o.push(p))},E=ze(c,a);for(let p of E)h(p);let S=0,x=0,A=p=>{if(p.length===0)return;let y=JSON.stringify(p),b=p.map(r=>r.id),R;try{R=fetch(u,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(r){pe(p,c,a);for(let d of b)f.delete(d);x++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(x,6));return}let L=r=>{if(r.ok||r.status>=400&&r.status<500&&r.status!==429){g(b),x=0,S=0;return}pe(p,c,a);for(let d of b)f.delete(d);x++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(x,6))};R instanceof Promise?R.then(L).catch(()=>{pe(p,c,a);for(let r of b)f.delete(r);x++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(x,6))}):L(R)},v=typeof TextEncoder!="undefined"?new TextEncoder:null,Z=p=>v?v.encode(p).length:p.length,U=p=>{let y=[],b=2;for(let R of p){let L=Z(JSON.stringify(R))+1;if(y.length>0&&b+L>57344||y.length>=i)break;y.push(R),b+=L}return y},T=()=>{try{if(Date.now()<S)return;for(;o.length>0;){let p=o.filter(b=>!n.has(b.id));if(o.length=0,p.length===0)break;let y=U(p);if(y.length===0)break;y.length<p.length&&o.push(...p.slice(y.length)),A(y)}}catch(p){}},k=!0,K=null;K=setInterval(()=>{k&&T()},t);let Q=()=>{document.visibilityState==="hidden"&&T()},Y=()=>{T()};return document.addEventListener("visibilitychange",Q),window.addEventListener("beforeunload",Y),{push(p){h(p),o.length>=i&&T()},flush:T,destroy(){k=!1,K!==null&&(clearInterval(K),K=null),document.removeEventListener("visibilitychange",Q),window.removeEventListener("beforeunload",Y),T()}}}var ye="_snt_asgn_";function ne(e,t){return`${e}:${t}`}function He(e,t){return`${ye}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function xe(e){let t=e.slice(ye.length),i=t.indexOf(":");if(i<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,i)),segment:decodeURIComponent(t.slice(i+1))}}catch(c){return null}}function me(){try{let e=[];for(let t=0;t<localStorage.length;t++){let i=localStorage.key(t);i!=null&&i.startsWith(ye)&&e.push(i)}return e}catch(e){return[]}}function Ae(e=18e5){let t=new Map,i=u=>u.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let u of me())try{let s=localStorage.getItem(u);if(!s)continue;let a=JSON.parse(s);if(i(a)){localStorage.removeItem(u);continue}let o=xe(u);if(!o)continue;t.set(ne(o.componentId,o.segment),a)}catch(s){}})(),{get(u,s){let a=t.get(ne(u,s));return a?i(a)?(t.delete(ne(u,s)),null):a:null},set(u,s,a){let o=ne(u,s);t.set(o,a);try{localStorage.setItem(He(u,s),JSON.stringify(a))}catch(n){}},invalidate(u){let s=`${u}:`;for(let a of[...t.keys()])a.startsWith(s)&&t.delete(a);for(let a of me()){let o=xe(a);if((o==null?void 0:o.componentId)===u)try{localStorage.removeItem(a)}catch(n){}}},clear(){t.clear();for(let u of me())try{localStorage.removeItem(u)}catch(s){}}}}var F="_snt_snap:",Xe=["low","medium","high"];function Se(e){try{let t=localStorage.getItem(F+e);if(!t)return null;let i=JSON.parse(t);return!i||typeof i!="object"||i.v!==1||typeof i.persona!="string"||typeof i.band!="string"||!Xe.includes(i.band)||typeof i.slots!="object"||i.slots===null||Array.isArray(i.slots)||!(i.layoutOrder===null||Array.isArray(i.layoutOrder))||typeof i.savedAt!="number"?null:i}catch(t){return null}}function q(e,t){try{localStorage.setItem(F+e,JSON.stringify(t))}catch(i){}}function qe(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(F+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}import{confidenceBand as De}from"@sentientui/policy";import{confidenceBand as he}from"@sentientui/policy";var ve="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Re="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",ke=!1,oe=!1;function Ze(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Oe(e){var o;let t=te({ssrSessionId:e.ssrSessionId}),i=(o=t.getSessionId())!=null?o:"local",c=Ze(),u=import("@sentientui/core/local").then(n=>{let l=n;return l.LOCAL_ENGINE_AVAILABLE?(ke||(ke=!0,console.info(Re)),l):(oe||(oe=!0,console.error(ve)),null)}).catch(()=>(oe||(oe=!0,console.error(ve)),null)),s=null;function a(n){let l=document.documentElement;l.dataset.sentientPersona===void 0&&(l.dataset.sentientPersona=n.persona,l.dataset.sentientConfidence=he(n.confidence))}return{isLocal:!0,async decide(n){var f,h,E;let l=await u;if(!l)return null;let g=l.createLocalEngine({sessionId:i,forcedPersona:c}).decide(n);return s=W(_({},g),{layoutOrder:(h=(f=g.layoutOrder)!=null?f:s==null?void 0:s.layoutOrder)!=null?h:null,slots:_(_({},(E=s==null?void 0:s.slots)!=null?E:{}),g.slots)}),q(e.apiKey||"local",{v:1,persona:s.persona,band:he(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),a(g),g},getSlotResult(n){var l,g,f;return(f=(g=s==null?void 0:s.slots[n])!=null?g:(l=e.initialSlots)==null?void 0:l[n])!=null?f:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:he(s.confidence)}:null},async assign(n,l){var h;let g=await u;return!g||!l||l.length===0?l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null:{variantId:(h=g.createLocalEngine({sessionId:i,forcedPersona:c}).decide({components:[{id:n,variantIds:l}]}).assignments[n])!=null?h:l[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function et(e,t,i){var u;let c=[];{let o=!1,n=[],l=()=>{if(o)return;let g=Date.now();for(n.push(g);n.length>0&&g-n[0]>500;)n.shift();n.length>=3&&(o=!0,e("rage_click"))};t.addEventListener("click",l),c.push(()=>t.removeEventListener("click",l))}{let s=!1,a=o=>{if(s||!(o.target instanceof Node)||!t.contains(o.target)&&t!==o.target)return;s=!0;let n=typeof window!="undefined"?window.getSelection():null,l=n?n.toString().length:0;e("text_copy",{selectionLength:l})};document.addEventListener("copy",a),c.push(()=>document.removeEventListener("copy",a))}{let s=!1,a=!1,o=null,n=()=>{o!==null&&(clearTimeout(o),o=null)},l=()=>{s||!a||(n(),o=setTimeout(()=>{!s&&a&&(s=!0,e("scroll_hesitation"))},3e3))},g=()=>{n(),l()},f=E=>{for(let S of E)a=S.intersectionRatio>.3,a?l():n()};typeof process!="undefined"&&((u=process.env)==null?void 0:u.NODE_ENV)!=="production"&&(window.__lastIOCallback=f);let h=new IntersectionObserver(f,{threshold:[.3]});h.observe(t),window.addEventListener("scroll",g,{passive:!0}),c.push(()=>{h.disconnect(),window.removeEventListener("scroll",g),n()})}{let s=!1,a=i!=null?i:Date.now(),o=()=>{if(s||document.visibilityState!=="hidden")return;let n=Date.now()-a;n<15e3&&(s=!0,e("tab_loss",{timeOnPage:n}))};document.addEventListener("visibilitychange",o),c.push(()=>document.removeEventListener("visibilitychange",o))}return()=>{for(let s of c)s()}}var Te="https://api.sentient-ui.com/v1/events",B=new Map,Ce=null;function Ee(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var J={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function tt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[i,c]of t)i.startsWith("utm_")&&(e[i]=c);return e}catch(e){return{}}}function Pe(e){return e.replace(/\/events\/?$/,"")}function Le(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function At(e){if(typeof window=="undefined")return;let t=e!=null?e:Ce;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let i=B.get(t);if(!i){console.warn("[sentient] grantConsent() called before init()");return}let{config:c,upgrade:u}=i;if(!u||c.respectDoNotTrack!==!1&&Le())return;let s=ot(W(_({},c),{consent:!0}));u(s),B.set(t,{config:W(_({},c),{consent:!0}),upgrade:null})}function nt(e){var a;let t=Pe((a=e.ingestUrl)!=null?a:Te),i={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},c={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(o,n,l){try{let g=new URLSearchParams({componentId:o});for(let E of n!=null?n:[])g.append("variantIds[]",E);let f=await fetch(`${t}/winner?${g.toString()}`,{headers:i});return f.ok?{variantId:(await f.json()).variantId,assignmentTtlMs:0}:n!=null&&n[0]?{variantId:n[0],assignmentTtlMs:0}:null}catch(g){return n!=null&&n[0]?{variantId:n[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},u={track:o=>c.track(o),goal:(o,n,l,g)=>c.goal(o,n,l,g),componentGoal:(o,n,l)=>c.componentGoal(o,n,l),identify:o=>c.identify(o),getAssignment:(o,n)=>c.getAssignment(o,n),assign:(o,n,l,g)=>c.assign(o,n,l,g),decide:o=>c.decide(o),getSlotResult:o=>c.getSlotResult(o),getPersona:()=>c.getPersona(),fetchWeights:()=>c.fetchWeights(),getGraph:()=>c.getGraph(),dispose:()=>c.dispose(),destroy:()=>c.destroy()};function s(o){c=o}return{proxy:u,setInner:s}}function ot(e){var Y,V,z,H,p,y,b,R,L;if(typeof window=="undefined")return J;Ce=e.apiKey;let t=e.respectDoNotTrack!==!1&&Le(),i=e.consent===!1||t,c=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!c&&e.localMode!==!1)return i?(B.set(e.apiKey||"local",{config:e,upgrade:null}),J):(B.set(e.apiKey||"local",{config:e,upgrade:null}),Oe(e));if(i){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),J;let{proxy:r,setInner:d}=nt(e);return B.set(e.apiKey,{config:e,upgrade:t?null:d}),r}return B.set(e.apiKey,{config:e,upgrade:null}),J}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),J;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),J;let u=(Y=e.ingestUrl)!=null?Y:Te,s=Date.now(),a=te({ssrSessionId:e.ssrSessionId}),o=Ae(),n=_e({ingestUrl:u,apiKey:e.apiKey}),l=Pe(u),g={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},f=ae((V=navigator.userAgent)!=null?V:""),h=typeof window!="undefined"?window.location.origin:void 0,E=le((z=document.referrer)!=null?z:"",h),S=(H=e.sessionSegment)!=null?H:`${f}:${E}`,x=new Map,A=new Map,v=null,Z=r=>{for(let d of r)A.has(d.id)||A.set(d.id,ee(d))};if(e.initialSlots)for(let[r,d]of Object.entries(e.initialSlots))A.set(r,d);let U=Se(e.apiKey);if(U)for(let[r,d]of Object.entries(U.slots))A.has(r)||A.set(r,d);let T={low:.15,medium:.5,high:.85};if(e.initialPersona)v=_({},e.initialPersona);else{let r=document.documentElement.dataset;r.sentientPersona?v={persona:r.sentientPersona,confidence:(y=T[(p=r.sentientConfidence)!=null?p:"low"])!=null?y:.15}:U&&(v={persona:U.persona,confidence:(b=T[U.band])!=null?b:.15})}if(e.initialAssignments)for(let[r,d]of Object.entries(e.initialAssignments))o.set(r,S,{variantId:d,assignedAt:Date.now(),segment:S,confidence:1});let k=Promise.resolve(),K=a.getSessionId();if(K){let r=ce((R=document.referrer)!=null?R:""),d=_(_({sessionId:K,deviceClass:f,trafficSource:E,referrerDomain:r,utmParams:tt(),timeOfDay:de(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:a.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||ie((L=navigator.userAgent)!=null?L:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{k=fetch(`${l}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(d),headers:g}).then(m=>{m.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(m){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:n});let Q={goal(r,d={},m=1,O=0){let w=a.getSessionId();if(!w)return;let I=Ee();k.then(()=>{fetch(`${l}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:w,name:r,metadata:d,weight:m,stepIndex:O,goalId:I}),headers:g}).catch(()=>{})})},componentGoal(r,d,m){var D,M,C;let O=a.getSessionId();if(!O)return;let w=o.get(r,S),I=w?null:(D=A.get(r))!=null?D:null;if(!w&&I===null){e.debug&&console.warn(`[sentient] componentGoal("${r}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let G=w?w.variantId:ge(I),N={id:Ee(),sessionId:O,projectId:e.apiKey,componentId:r,variantId:G,eventType:"goal_achieved",goalType:d,payload:_({reward:(M=m==null?void 0:m.reward)!=null?M:1},(C=m==null?void 0:m.metadata)!=null?C:{}),timestamp:Date.now(),timeInSession:Date.now()-s};e.debug&&console.log("[sentient] componentGoal",N),k.then(()=>n.push(N))},identify(r){let d=a.getSessionId();d&&k.then(()=>{fetch(`${l}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:d,userId:r,ephemeral:a.isEphemeral()}),headers:g}).catch(()=>{})})},track(r){let d=a.getSessionId();if(!d)return;let m=W(_({},r),{id:Ee(),sessionId:d,timestamp:Date.now(),timeInSession:Date.now()-s});e.debug&&console.log("[sentient] track",m),k.then(()=>n.push(m))},getAssignment(r,d){return o.get(r,d)},async assign(r,d,m,O){let w=a.getSessionId();if(!w)return null;let I=o.get(r,S);if(I&&(d!=null&&d.length||I.content!==void 0))return{variantId:I.variantId,assignmentTtlMs:0,content:I.content};let G=x.get(r);if(G)return G;let N=(async()=>{await k;try{let D={sessionId:w,componentId:r,variantIds:d};O!==void 0?D.agentDataByVariant=O:m!==void 0&&(D.agentData=m);let M=await fetch(`${l}/assign`,{method:"POST",body:JSON.stringify(D),headers:g});if(!M.ok)return null;let C=await M.json();return o.set(r,S,{variantId:C.variantId,assignedAt:Date.now(),segment:S,confidence:1,content:C.content}),C}catch(D){return null}finally{x.delete(r)}})();return x.set(r,N),N},async decide(r){var O,w,I,G,N,D,M,C,we,be;let d=a.getSessionId();if(!d)return null;let m=(O=r.slots)!=null?O:[];await k;try{let X={sessionId:d};r.sections&&r.sections.length>0&&(X.sections=r.sections.map(P=>({id:P}))),X.components=(w=r.components)!=null?w:[],m.length>0&&(X.slots=m.map(ue));let Ie=await fetch(`${l}/decide`,{method:"POST",body:JSON.stringify(X),headers:g});if(!Ie.ok)return Z(m),null;let $=await Ie.json(),se={};for(let P of m)se[P.id]=(G=(I=$.slots)==null?void 0:I[P.id])!=null?G:ee(P);for(let[P,re]of Object.entries(se))A.set(P,re);v={persona:(N=$.persona)!=null?N:"unknown",confidence:(D=$.confidence)!=null?D:0};for(let[P,re]of Object.entries((M=$.assignments)!=null?M:{}))o.set(P,S,{variantId:re,assignedAt:Date.now(),segment:S,confidence:1});return q(e.apiKey,{v:1,persona:v.persona,band:De(v.confidence),slots:Object.fromEntries(A),layoutOrder:(C=$.layoutOrder)!=null?C:null,savedAt:Date.now()}),{layoutOrder:(we=$.layoutOrder)!=null?we:null,assignments:(be=$.assignments)!=null?be:{},slots:se,persona:v.persona,confidence:v.confidence}}catch(X){return Z(m),null}},getSlotResult(r){var d;return(d=A.get(r))!=null?d:null},getPersona(){return v?{persona:v.persona,confidence:v.confidence,band:De(v.confidence)}:null},async fetchWeights(){var r;try{let d=await fetch(`${l}/weights`,{headers:g});return d.ok?(r=(await d.json()).components)!=null?r:[]:[]}catch(d){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){n.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){n.destroy(),a.destroy();try{localStorage.removeItem(F+e.apiKey),localStorage.removeItem(fe(e.apiKey))}catch(r){}e.debug&&console.log("[sentient] destroyed")}};if(B.set(e.apiKey,{config:e,upgrade:null}),e.debug){let r=window;r.__sentient&&(r.__sentient.client=Q)}return Q}export{F as a,Se as b,q as c,qe as d,ve as e,Re as f,et as g,Le as h,At as i,ot as j};