@sentientui/core 0.16.7 → 0.16.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var ze=Object.create;var re=Object.defineProperty,qe=Object.defineProperties,Xe=Object.getOwnPropertyDescriptor,Ze=Object.getOwnPropertyDescriptors,et=Object.getOwnPropertyNames,Te=Object.getOwnPropertySymbols,tt=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable;var Le=(e,t,n)=>t in e?re(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,S=(e,t)=>{for(var n in t||(t={}))Pe.call(t,n)&&Le(e,n,t[n]);if(Te)for(var n of Te(t))nt.call(t,n)&&Le(e,n,t[n]);return e},Q=(e,t)=>qe(e,Ze(t));var ot=(e,t)=>{for(var n in t)re(e,n,{get:t[n],enumerable:!0})},Me=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of et(t))!Pe.call(e,c)&&c!==n&&re(e,c,{get:()=>t[c],enumerable:!(a=Xe(t,c))||a.enumerable});return e};var rt=(e,t,n)=>(n=e!=null?ze(tt(e)):{},Me(t||!e||!e.__esModule?re(n,"default",{value:e,enumerable:!0}):n,e)),st=e=>Me(re({},"__esModule",{value:!0}),e);var Dt={};ot(Dt,{LOCAL_MODE_BANNER:()=>Re,PROD_KEYLESS_ERROR:()=>ve,SNAPSHOT_STORAGE_KEY_PREFIX:()=>J,agentUaList:()=>Ie,armOfResult:()=>me,attachMicroSignalDetectors:()=>Fe,baselineResultFor:()=>Y,baselineSlots:()=>Be,deriveSessionSegment:()=>Ge,detectDeviceClass:()=>ie,detectTimeOfDay:()=>ce,detectTrafficSource:()=>ae,grantConsent:()=>At,init:()=>He,isDoNotTrackEnabled:()=>_e,matchedAgentToken:()=>Ce,readSnapshot:()=>ye,referrerDomainFromReferer:()=>le,renderPrePaintScript:()=>$e,toWireSlot:()=>de,uaTokenMatch:()=>se,writeSnapshot:()=>z});module.exports=st(Dt);function ge(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(t+="-");return t}}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 it="_snt_uid",at=365,V="_snt_uid";function lt(){return ge()}function ct(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function dt(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(a){}}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=/`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function St(e){try{localStorage.removeItem(e)}catch(t){}}function ht(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var vt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function pe(e){var g,f,w,x,P,b;if(typeof window=="undefined")return vt;let t=(g=e==null?void 0:e.cookieName)!=null?g:it,a=((f=e==null?void 0:e.cookieTTLDays)!=null?f:at)*24*60*60,c=I=>I&&I.length>0?I:null,s=(b=(P=(x=(w=c(ct(t)))!=null?w:c(ut(V)))!=null?x:c(pt(V)))!=null?P:c(e==null?void 0:e.ssrSessionId))!=null?b:lt();dt(t,s,a);let l=gt(V,s),o=yt(t),r=l?!1:ft(V,s),d=!l&&!o&&!r;return{getSessionId:()=>s,isEphemeral:()=>d,destroy:()=>{s=null,ht(t),St(V),mt(V)}}}function be(e){return`_snt_retry_${e.slice(0,12)}`}var wt={push:()=>{},flush:()=>{},destroy:()=>{}};function bt(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 we(e,t,n){try{let a=(()=>{try{let l=localStorage.getItem(n);if(!l)return[];let o=JSON.parse(l);return Array.isArray(o)?o:[]}catch(l){return[]}})(),c=new Map;for(let l of a)c.set(l.id,l);for(let l of e)c.set(l.id,l);let s=[...c.values()].slice(-t);localStorage.setItem(n,JSON.stringify(s))}catch(a){}}function Et(e,t){try{let n=localStorage.getItem(t);if(!n)return;let a=JSON.parse(n);if(!Array.isArray(a))return;let c=new Set(e),s=a.filter(l=>!c.has(l.id));if(s.length===a.length)return;s.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(s))}catch(n){}}function Ne(e){var Z,ee,te;if(typeof window=="undefined")return wt;let t=(Z=e.flushIntervalMs)!=null?Z:5e3,n=(ee=e.maxBatchSize)!=null?ee:20,a=(te=e.maxRetrySize)!=null?te:100,c=e.ingestUrl,s=e.apiKey,l=be(s),o=[],r=new Set,d=[],g=p=>{for(let m of p)f.delete(m),!r.has(m)&&(r.add(m),d.push(m));for(;d.length>500;){let m=d.shift();m&&r.delete(m)}Et(p,l)},f=new Set,w=p=>{r.has(p.id)||f.has(p.id)||(f.add(p.id),o.push(p))},x=p=>{for(let m of p)r.has(m.id)||(f.add(m.id),o.push(m))},P=bt(a,l);for(let p of P)w(p);let b=0,I=0,D=p=>{if(p.length===0)return;let m=JSON.stringify(p),N=p.map(i=>i.id),T;try{T=fetch(c,{method:"POST",keepalive:!0,body:m,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(i){we(p,a,l),x(p),I++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(I,6));return}let K=i=>{if(i.ok||i.status>=400&&i.status<500&&i.status!==429){g(N),I=0,b=0;return}we(p,a,l),x(p),I++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(I,6))};T instanceof Promise?T.then(K).catch(()=>{we(p,a,l),x(p),I++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(I,6))}):K(T)},h=typeof TextEncoder!="undefined"?new TextEncoder:null,ue=p=>h?h.encode(p).length:p.length,$=p=>{let m=[],N=2;for(let T of p){let K=ue(JSON.stringify(T))+1;if(m.length>0&&N+K>57344||m.length>=n)break;m.push(T),N+=K}return m},M=()=>{try{if(Date.now()<b)return;for(;o.length>0&&!(Date.now()<b);){let p=o.filter(N=>!r.has(N.id));if(o.length=0,p.length===0)break;let m=$(p);if(m.length===0)break;m.length<p.length&&o.push(...p.slice(m.length)),D(m)}}catch(p){}},O=!0,W=null;W=setInterval(()=>{O&&M()},t);let U=()=>{document.visibilityState==="hidden"&&M()},X=()=>{M()};return document.addEventListener("visibilitychange",U),window.addEventListener("pagehide",X),{push(p){w(p),o.length>=n&&M()},flush:M,destroy(){O=!1,W!==null&&(clearInterval(W),W=null),document.removeEventListener("visibilitychange",U),window.removeEventListener("pagehide",X),M()}}}var xe="_snt_asgn_";function fe(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function xt(e,t){return`${xe}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ue(e){let t=e.slice(xe.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 Ee(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(xe)&&e.push(n)}return e}catch(e){return[]}}function Ke(e=18e5){let t=new Map,n=c=>c.assignedAt+(c.ttlMs&&c.ttlMs>0?c.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let c of Ee())try{let s=localStorage.getItem(c);if(!s)continue;let l=JSON.parse(s);if(n(l)){localStorage.removeItem(c);continue}let o=Ue(c);if(!o)continue;t.set(fe(o.componentId,o.segment),l)}catch(s){}})(),{get(c,s){let l=t.get(fe(c,s));return l?n(l)?(t.delete(fe(c,s)),null):l:null},set(c,s,l){let o=fe(c,s);t.set(o,l);try{localStorage.setItem(xt(c,s),JSON.stringify(l))}catch(r){}},invalidate(c){let s=`${encodeURIComponent(c)}:`;for(let l of[...t.keys()])l.startsWith(s)&&t.delete(l);for(let l of Ee()){let o=Ue(l);if((o==null?void 0:o.componentId)===c)try{localStorage.removeItem(l)}catch(r){}}},clear(){t.clear();for(let c of Ee())try{localStorage.removeItem(c)}catch(s){}}}}var Ie=["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 se(e){return Ce(e)!==null}function Ce(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ie.find(a=>t.includes(a.toLowerCase())))!=null?n:null}function ie(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 ae(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(c){}let a=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(a)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(a)?"social":"referral"}catch(n){return"direct"}}function le(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function ce(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ge(e){let t=It("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function It(e,t){var s,l,o,r,d,g,f;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:"",c=(d=t==null?void 0:t.now)!=null?d:new Date;return{sessionId:e,ephemeral:!1,utmParams:(g=t==null?void 0:t.utmParams)!=null?g:{},deviceClass:n?ie(n):"desktop",trafficSource:a?ae(a,t==null?void 0:t.appOrigin):"direct",referrerDomain:le(a),timeOfDay:ce(c),dayOfWeek:(f=["sun","mon","tue","wed","thu","fri","sat"][c.getDay()])!=null?f:"sun",automation:(t==null?void 0:t.webdriver)===!0||se(n)}}var H=require("@sentientui/policy");function de(e){return S(S(S({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=de(e);return(0,H.slotResultFor)(t,(0,H.slotBaselineArm)(t))}function Be(e){let t={};for(let n of e)t[n.id]=Y(n);return t}function me(e){return typeof e=="string"?e:(0,H.canonicalArm)(e)}var J="_snt_snap:",Ct=["low","medium","high"];function ye(e){try{let t=localStorage.getItem(J+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 z(e,t){try{localStorage.setItem(J+e,JSON.stringify(t))}catch(n){}}function $e(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){}})();'}var Ae=require("@sentientui/policy");var he=require("@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.",We=!1,Se=!1;function Rt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function je(e){var o;let t=pe({ssrSessionId:e.ssrSessionId}),n=(o=t.getSessionId())!=null?o:"local",a=Rt(),c=import("@sentientui/core/local").then(r=>{let d=r;return d.LOCAL_ENGINE_AVAILABLE?(We||(We=!0,console.info(Re)),d):(Se||(Se=!0,console.error(ve)),null)}).catch(()=>(Se||(Se=!0,console.error(ve)),null)),s=null;function l(r){let d=document.documentElement;d.dataset.sentientPersona===void 0&&(d.dataset.sentientPersona=r.persona,d.dataset.sentientConfidence=(0,he.confidenceBand)(r.confidence))}return{isLocal:!0,async decide(r){var f,w,x;let d=await c;if(!d)return null;let g=d.createLocalEngine({sessionId:n,forcedPersona:a}).decide(r);return s=Q(S({},g),{layoutOrder:(w=(f=g.layoutOrder)!=null?f:s==null?void 0:s.layoutOrder)!=null?w:null,slots:S(S({},(x=s==null?void 0:s.slots)!=null?x:{}),g.slots)}),z(e.apiKey||"local",{v:1,persona:s.persona,band:(0,he.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),l(g),g},getSlotResult(r){var d,g,f;return(f=(g=s==null?void 0:s.slots[r])!=null?g:(d=e.initialSlots)==null?void 0:d[r])!=null?f:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,he.confidenceBand)(s.confidence)}:null},async assign(r,d){var w;let g=await c;return!g||!d||d.length===0?d!=null&&d[0]?{variantId:d[0],assignmentTtlMs:0}:null:{variantId:(w=g.createLocalEngine({sessionId:n,forcedPersona:a}).decide({components:[{id:r,variantIds:d}]}).assignments[r])!=null?w:d[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function Fe(e,t,n,a){let c=[];{let o=!1,r=[],d=()=>{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",d),c.push(()=>t.removeEventListener("click",d))}{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,d=r?r.toString().length:0;e("text_copy",{selectionLength:d})};document.addEventListener("copy",l),c.push(()=>document.removeEventListener("copy",l))}{let s=!1,l=!1,o=null,r=()=>{o!==null&&(clearTimeout(o),o=null)},d=()=>{s||!l||(r(),o=setTimeout(()=>{!s&&l&&(s=!0,e("scroll_hesitation"))},3e3))},g=()=>{r(),d()},f=x=>{for(let P of x)l=P.intersectionRatio>.3,l?d():r()},w=new IntersectionObserver(f,{threshold:[.3]});w.observe(t),window.addEventListener("scroll",g,{passive:!0}),c.push(()=>{w.disconnect(),window.removeEventListener("scroll",g),r()})}if((a==null?void 0:a.tabLoss)!==!1){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),c.push(()=>document.removeEventListener("visibilitychange",o))}return()=>{for(let s of c)s()}}var Je="https://api.sentient-ui.com/v1/events",R=new Map,Qe=null;function ke(){return ge()}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 kt(){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 Ve(e){return e.replace(/\/events\/?$/,"")}function _e(){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){var o;if(typeof window=="undefined")return;let t=e!=null?e:Qe;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=R.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:a,upgrade:c}=n;if(!c||a.respectDoNotTrack!==!1&&_e())return;let s=He(Q(S({},a),{consent:!0}));c(s);let l=(o=R.get(t))==null?void 0:o.dispose;R.set(t,{config:Q(S({},a),{consent:!0}),upgrade:null,dispose:l})}function _t(e){var l;let t=Ve((l=e.ingestUrl)!=null?l:Je),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},a={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(o,r,d){try{let g=new URLSearchParams({componentId:o});for(let x of r!=null?r:[])g.append("variantIds[]",x);let f=await fetch(`${t}/winner?${g.toString()}`,{headers:n});return f.ok?{variantId:(await f.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:()=>{}},c={track:o=>a.track(o),goal:(o,r,d,g)=>a.goal(o,r,d,g),componentGoal:(o,r,d)=>a.componentGoal(o,r,d),identify:o=>a.identify(o),getAssignment:(o,r)=>a.getAssignment(o,r),assign:(o,r,d,g)=>a.assign(o,r,d,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:c,setInner:s}}function He(e){var X,Z,ee,te,p,m,N,T,K;if(typeof window=="undefined")return q;Qe=e.apiKey;let t=R.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(i){}let n=e.respectDoNotTrack!==!1&&_e(),a=e.consent===!1||n,c=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!c&&e.localMode!==!1)return a?(R.set(e.apiKey||"local",{config:e,upgrade:null}),q):(R.set(e.apiKey||"local",{config:e,upgrade:null}),je(e));if(a){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:i,setInner:u}=_t(e);return R.set(e.apiKey,{config:e,upgrade:n?null:u}),i}return R.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 s=(X=e.ingestUrl)!=null?X:Je,l=Date.now(),o=pe({ssrSessionId:e.ssrSessionId}),r=Ke(),d=Ne({ingestUrl:s,apiKey:e.apiKey}),g=Ve(s),f={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},w=ie((Z=navigator.userAgent)!=null?Z:""),x=typeof window!="undefined"?window.location.origin:void 0,P=ae((ee=document.referrer)!=null?ee:"",x),b=(te=e.sessionSegment)!=null?te:`${w}:${P}`,I=new Map,D=new Map,h=null,ue=i=>{for(let u of i)D.has(u.id)||D.set(u.id,Y(u))};if(e.initialSlots)for(let[i,u]of Object.entries(e.initialSlots))D.set(i,u);let $=ye(e.apiKey);if($)for(let[i,u]of Object.entries($.slots))D.has(i)||D.set(i,u);let M={low:.15,medium:.5,high:.85};if(e.initialPersona)h=S({},e.initialPersona);else{let i=document.documentElement.dataset;i.sentientPersona?h={persona:i.sentientPersona,confidence:(m=M[(p=i.sentientConfidence)!=null?p:"low"])!=null?m:.15}:$&&(h={persona:$.persona,confidence:(N=M[$.band])!=null?N:.15})}if(e.initialAssignments)for(let[i,u]of Object.entries(e.initialAssignments))r.set(i,b,{variantId:u,assignedAt:Date.now(),segment:b,confidence:1});let O=Promise.resolve(),W=o.getSessionId();if(W){let i=le((T=document.referrer)!=null?T:""),u=S(S({sessionId:W,deviceClass:w,trafficSource:P,referrerDomain:i,utmParams:kt(),timeOfDay:ce(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||se((K=navigator.userAgent)!=null?K:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{O=fetch(`${g}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(u),headers:f}).then(y=>{y.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(y){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:d});let U={goal(i,u={},y=1,L=0){let C=o.getSessionId();if(!C)return;let E=ke();O.then(()=>{fetch(`${g}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:C,name:i,metadata:u,weight:y,stepIndex:L,goalId:E}),headers:f}).catch(()=>{})})},componentGoal(i,u,y){var k,B,A;let L=o.getSessionId();if(!L)return;let C=r.get(i,b),E=C?null:(k=D.get(i))!=null?k:null;if(!C&&E===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 j=C?C.variantId:me(E),G={id:ke(),sessionId:L,projectId:e.apiKey,componentId:i,variantId:j,eventType:"goal_achieved",goalType:u,payload:S({reward:(B=y==null?void 0:y.reward)!=null?B:1},(A=y==null?void 0:y.metadata)!=null?A:{}),timestamp:Date.now(),timeInSession:Date.now()-l};e.debug&&console.log("[sentient] componentGoal",G),O.then(()=>d.push(G))},identify(i){let u=o.getSessionId();u&&O.then(()=>{fetch(`${g}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:u,userId:i,ephemeral:o.isEphemeral()}),headers:f}).catch(()=>{})})},track(i){let u=o.getSessionId();if(!u)return;let y=Q(S({},i),{id:ke(),sessionId:u,timestamp:Date.now(),timeInSession:Date.now()-l});e.debug&&console.log("[sentient] track",y),O.then(()=>d.push(y))},getAssignment(i,u){return r.get(i,u)},async assign(i,u,y,L){let C=o.getSessionId();if(!C)return null;let E=r.get(i,b);if(E&&(u!=null&&u.length||E.content!==void 0)){let k=E.ttlMs&&E.ttlMs>0?Math.max(0,E.assignedAt+E.ttlMs-Date.now()):0;return{variantId:E.variantId,assignmentTtlMs:k,content:E.content}}let j=I.get(i);if(j)return j;let G=(async()=>{await O;try{let k={sessionId:C,componentId:i,variantIds:u};L!==void 0?k.agentDataByVariant=L:y!==void 0&&(k.agentData=y);let B=await fetch(`${g}/assign`,{method:"POST",body:JSON.stringify(k),headers:f});if(!B.ok)return null;let A=await B.json();return r.set(i,b,S({variantId:A.variantId,assignedAt:Date.now(),segment:b,confidence:1,content:A.content},A.assignmentTtlMs&&A.assignmentTtlMs>0?{ttlMs:A.assignmentTtlMs}:{})),A}catch(k){return null}finally{I.delete(i)}})();return I.set(i,G),G},async decide(i){var L,C,E,j,G,k,B,A,De;let u=o.getSessionId();if(!u)return null;let y=(L=i.slots)!=null?L:[];await O;try{let F={sessionId:u};i.sections&&i.sections.length>0&&(F.sections=i.sections.map(_=>({id:_}))),F.components=(C=i.components)!=null?C:[],y.length>0&&(F.slots=y.map(de)),i.slotsFrom==="registry"&&(F.slotsFrom="registry"),i.v&&(F.v=i.v);let Oe=await fetch(`${g}/decide`,{method:"POST",body:JSON.stringify(F),headers:f});if(!Oe.ok)return ue(y),null;let v=await Oe.json(),ne={};for(let _ of y)ne[_.id]=(j=(E=v.slots)==null?void 0:E[_.id])!=null?j:Y(_);if(v.slots)for(let[_,oe]of Object.entries(v.slots))_ in ne||(ne[_]=oe);for(let[_,oe]of Object.entries(ne))D.set(_,oe);let Ye=h!=null&&h.persona!=="unknown";v.persona&&!(v.persona==="unknown"&&Ye)?h={persona:v.persona,confidence:(G=v.confidence)!=null?G:0}:h||(h={persona:"unknown",confidence:0});for(let[_,oe]of Object.entries((k=v.assignments)!=null?k:{}))r.set(_,b,{variantId:oe,assignedAt:Date.now(),segment:b,confidence:1});return z(e.apiKey,S({v:1,persona:h.persona,band:(0,Ae.confidenceBand)(h.confidence),slots:Object.fromEntries(D),layoutOrder:(B=v.layoutOrder)!=null?B:null,savedAt:Date.now()},v.slotConfig?{slotConfig:v.slotConfig}:{})),S(S(S({layoutOrder:(A=v.layoutOrder)!=null?A:null,assignments:(De=v.assignments)!=null?De:{},slots:ne,persona:h.persona,confidence:h.confidence},v.slotConfig?{slotConfig:v.slotConfig}:{}),v.goals?{goals:v.goals}:{}),v.sectionMap?{sectionMap:v.sectionMap}:{})}catch(F){return ue(y),null}},getSlotResult(i){var u;return(u=D.get(i))!=null?u:null},getPersona(){return h?{persona:h.persona,confidence:h.confidence,band:(0,Ae.confidenceBand)(h.confidence)}:null},async fetchWeights(){var i;try{let u=await fetch(`${g}/weights`,{headers:f});return u.ok?(i=(await u.json()).components)!=null?i:[]:[]}catch(u){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var i;d.destroy(),((i=R.get(e.apiKey))==null?void 0:i.dispose)===U.dispose&&R.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var i;d.destroy(),o.destroy(),((i=R.get(e.apiKey))==null?void 0:i.dispose)===U.dispose&&R.delete(e.apiKey);try{localStorage.removeItem(J+e.apiKey),localStorage.removeItem(be(e.apiKey))}catch(u){}e.debug&&console.log("[sentient] destroyed")}};if(R.set(e.apiKey,{config:e,upgrade:null,dispose:U.dispose}),e.debug){let i=window;i.__sentient&&(i.__sentient.client=U)}return U}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 Ye=Object.create;var oe=Object.defineProperty,qe=Object.defineProperties,Xe=Object.getOwnPropertyDescriptor,Ze=Object.getOwnPropertyDescriptors,et=Object.getOwnPropertyNames,Oe=Object.getOwnPropertySymbols,tt=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty,nt=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,v=(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))nt.call(t,n)&&Te(e,n,t[n]);return e},Q=(e,t)=>qe(e,Ze(t));var ot=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Le=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let f of et(t))!Pe.call(e,f)&&f!==n&&oe(e,f,{get:()=>t[f],enumerable:!(i=Xe(t,f))||i.enumerable});return e};var rt=(e,t,n)=>(n=e!=null?Ye(tt(e)):{},Le(t||!e||!e.__esModule?oe(n,"default",{value:e,enumerable:!0}):n,e)),st=e=>Le(oe({},"__esModule",{value:!0}),e);var Ot={};ot(Ot,{AGENT_INTENTS:()=>ye,LOCAL_MODE_BANNER:()=>Ce,PROD_KEYLESS_ERROR:()=>be,SNAPSHOT_STORAGE_KEY_PREFIX:()=>J,agentIntent:()=>Ue,agentUaList:()=>re,armOfResult:()=>Se,attachMicroSignalDetectors:()=>Fe,baselineResultFor:()=>z,baselineSlots:()=>Be,classifiedAgents:()=>Ke,deriveSessionSegment:()=>Ge,detectDeviceClass:()=>ie,detectTimeOfDay:()=>ce,detectTrafficSource:()=>ae,grantConsent:()=>_t,init:()=>ze,isDoNotTrackEnabled:()=>ke,matchedAgentToken:()=>Ie,readSnapshot:()=>he,referrerDomainFromReferer:()=>le,renderPrePaintScript:()=>$e,toWireSlot:()=>de,uaTokenMatch:()=>se,writeSnapshot:()=>H});module.exports=st(Ot);function ge(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(t+="-");return t}}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)})}function pe(e){return e?`_${e.slice(0,12)}`:""}var it="_snt_uid",at=365,lt="_snt_uid";function ct(){return ge()}function dt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function ut(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(i){}}function gt(e){try{return localStorage.getItem(e)}catch(t){return null}}function pt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function ft(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function mt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function yt(e){try{sessionStorage.removeItem(e)}catch(t){}}function St(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function ht(e){try{localStorage.removeItem(e)}catch(t){}}function vt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var wt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function fe(e){var m,x,L,b,I,C;if(typeof window=="undefined")return wt;let t=pe(e==null?void 0:e.apiKey),n=(m=e==null?void 0:e.cookieName)!=null?m:`${it}${t}`,i=`${lt}${t}`,c=((x=e==null?void 0:e.cookieTTLDays)!=null?x:at)*24*60*60,u=h=>h&&h.length>0?h:null,r=(C=(I=(b=(L=u(dt(n)))!=null?L:u(gt(i)))!=null?b:u(ft(i)))!=null?I:u(e==null?void 0:e.ssrSessionId))!=null?C:ct();ut(n,r,c);let s=pt(i,r),o=St(n),l=s?!1:mt(i,r),d=!s&&!o&&!l;return{getSessionId:()=>r,isEphemeral:()=>d,destroy:()=>{r=null,vt(n),ht(i),yt(i)}}}function Ee(e){return`_snt_retry_${e.slice(0,12)}`}var bt={push:()=>{},flush:()=>{},destroy:()=>{}};function xt(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let i=JSON.parse(n);return Array.isArray(i)?(localStorage.removeItem(t),i.slice(-e)):[]}catch(n){return[]}}function xe(e,t,n){try{let i=(()=>{try{let u=localStorage.getItem(n);if(!u)return[];let r=JSON.parse(u);return Array.isArray(r)?r:[]}catch(u){return[]}})(),f=new Map;for(let u of i)f.set(u.id,u);for(let u of e)f.set(u.id,u);let c=[...f.values()].slice(-t);localStorage.setItem(n,JSON.stringify(c))}catch(i){}}function Et(e,t){try{let n=localStorage.getItem(t);if(!n)return;let i=JSON.parse(n);if(!Array.isArray(i))return;let f=new Set(e),c=i.filter(u=>!f.has(u.id));if(c.length===i.length)return;c.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(c))}catch(n){}}function Me(e){var X,Z,ee;if(typeof window=="undefined")return bt;let t=(X=e.flushIntervalMs)!=null?X:5e3,n=(Z=e.maxBatchSize)!=null?Z:20,i=(ee=e.maxRetrySize)!=null?ee:100,f=e.ingestUrl,c=e.apiKey,u=Ee(c),r=[],s=new Set,o=[],l=p=>{for(let y of p)d.delete(y),!s.has(y)&&(s.add(y),o.push(y));for(;o.length>500;){let y=o.shift();y&&s.delete(y)}Et(p,u)},d=new Set,m=p=>{s.has(p.id)||d.has(p.id)||(d.add(p.id),r.push(p))},x=p=>{for(let y of p)s.has(y.id)||(d.add(y.id),r.push(y))},L=xt(i,u);for(let p of L)m(p);let b=0,I=0,C=p=>{if(p.length===0)return;let y=JSON.stringify(p),N=p.map(a=>a.id),T;try{T=fetch(f,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`}})}catch(a){xe(p,i,u),x(p),I++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(I,6));return}let K=a=>{if(a.ok||a.status>=400&&a.status<500&&a.status!==429){l(N),I=0,b=0;return}xe(p,i,u),x(p),I++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(I,6))};T instanceof Promise?T.then(K).catch(()=>{xe(p,i,u),x(p),I++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(I,6))}):K(T)},h=typeof TextEncoder!="undefined"?new TextEncoder:null,ue=p=>h?h.encode(p).length:p.length,$=p=>{let y=[],N=2;for(let T of p){let K=ue(JSON.stringify(T))+1;if(y.length>0&&N+K>57344||y.length>=n)break;y.push(T),N+=K}return y},M=()=>{try{if(Date.now()<b)return;for(;r.length>0&&!(Date.now()<b);){let p=r.filter(N=>!s.has(N.id));if(r.length=0,p.length===0)break;let y=$(p);if(y.length===0)break;y.length<p.length&&r.push(...p.slice(y.length)),C(y)}}catch(p){}},O=!0,W=null;W=setInterval(()=>{O&&M()},t);let U=()=>{document.visibilityState==="hidden"&&M()},q=()=>{M()};return document.addEventListener("visibilitychange",U),window.addEventListener("pagehide",q),{push(p){m(p),r.length>=n&&M()},flush:M,destroy(){O=!1,W!==null&&(clearInterval(W),W=null),document.removeEventListener("visibilitychange",U),window.removeEventListener("pagehide",q),M()}}}var It=1800*1e3;function me(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ne(e=It,t){let n=new Map,i=`_snt_asgn${pe(t)}_`,f=(o,l)=>`${i}${encodeURIComponent(o)}:${encodeURIComponent(l)}`,c=o=>{let l=o.slice(i.length),d=l.indexOf(":");if(d<0)return null;try{return{componentId:decodeURIComponent(l.slice(0,d)),segment:decodeURIComponent(l.slice(d+1))}}catch(m){return null}},u=()=>{try{let o=[];for(let l=0;l<localStorage.length;l++){let d=localStorage.key(l);d!=null&&d.startsWith(i)&&o.push(d)}return o}catch(o){return[]}},r=o=>o.assignedAt+(o.ttlMs&&o.ttlMs>0?o.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let o of u())try{let l=localStorage.getItem(o);if(!l)continue;let d=JSON.parse(l);if(r(d)){localStorage.removeItem(o);continue}let m=c(o);if(!m)continue;n.set(me(m.componentId,m.segment),d)}catch(l){}})(),{get(o,l){let d=n.get(me(o,l));return d?r(d)?(n.delete(me(o,l)),null):d:null},set(o,l,d){let m=me(o,l);n.set(m,d);try{localStorage.setItem(f(o,l),JSON.stringify(d))}catch(x){}},invalidate(o){let l=`${encodeURIComponent(o)}:`;for(let d of[...n.keys()])d.startsWith(l)&&n.delete(d);for(let d of u()){let m=c(d);if((m==null?void 0:m.componentId)===o)try{localStorage.removeItem(d)}catch(x){}}},clear(){n.clear();for(let o of u())try{localStorage.removeItem(o)}catch(l){}}}}var re=["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 se(e){return Ie(e)!==null}function Ie(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=re.find(i=>t.includes(i.toLowerCase())))!=null?n:null}var ye={GPTBot:"training","ChatGPT-User":"user","OAI-SearchBot":"search",ClaudeBot:"training","Claude-User":"user","Claude-SearchBot":"search",PerplexityBot:"search","Perplexity-User":"user","Google-Extended":"training","Applebot-Extended":"training","Meta-ExternalAgent":"training",Bytespider:"training",CCBot:"training",Amazonbot:"other","cohere-ai":"training",Diffbot:"other"};function Ue(e){if(!e)return"other";let t=re.find(n=>n.toLowerCase()===e.toLowerCase());return t&&ye[t]||"other"}function Ke(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of re)e[(t=ye[n])!=null?t:"other"].push(n);return e}function ie(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 ae(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(f){}let i=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(i)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(i)?"social":"referral"}catch(n){return"direct"}}function le(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function ce(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ge(e){let t=Ct("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Ct(e,t){var c,u,r,s,o,l,d;let n=(u=(c=t==null?void 0:t.userAgent)==null?void 0:c.trim())!=null?u:"",i=(s=(r=t==null?void 0:t.referer)==null?void 0:r.trim())!=null?s:"",f=(o=t==null?void 0:t.now)!=null?o:new Date;return{sessionId:e,ephemeral:!1,utmParams:(l=t==null?void 0:t.utmParams)!=null?l:{},deviceClass:n?ie(n):"desktop",trafficSource:i?ae(i,t==null?void 0:t.appOrigin):"direct",referrerDomain:le(i),timeOfDay:ce(f),dayOfWeek:(d=["sun","mon","tue","wed","thu","fri","sat"][f.getDay()])!=null?d:"sun",automation:(t==null?void 0:t.webdriver)===!0||se(n)}}var V=require("@sentientui/policy");function de(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 z(e){let t=de(e);return(0,V.slotResultFor)(t,(0,V.slotBaselineArm)(t))}function Be(e){let t={};for(let n of e)t[n.id]=z(n);return t}function Se(e){return typeof e=="string"?e:(0,V.canonicalArm)(e)}var J="_snt_snap:",At=["low","medium","high"];function he(e){try{let t=localStorage.getItem(J+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"||!At.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 H(e,t){try{localStorage.setItem(J+e,JSON.stringify(t))}catch(n){}}function $e(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){}})();'}var Re=require("@sentientui/policy");var we=require("@sentientui/policy");var be="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ce="[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.",We=!1,ve=!1;function Rt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function je(e){var r;let t=fe({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(r=t.getSessionId())!=null?r:"local",i=Rt(),f=import("@sentientui/core/local").then(s=>{let o=s;return o.LOCAL_ENGINE_AVAILABLE?(We||(We=!0,console.info(Ce)),o):(ve||(ve=!0,console.error(be)),null)}).catch(()=>(ve||(ve=!0,console.error(be)),null)),c=null;function u(s){let o=document.documentElement;o.dataset.sentientPersona===void 0&&(o.dataset.sentientPersona=s.persona,o.dataset.sentientConfidence=(0,we.confidenceBand)(s.confidence))}return{isLocal:!0,async decide(s){var d,m,x;let o=await f;if(!o)return null;let l=o.createLocalEngine({sessionId:n,forcedPersona:i}).decide(s);return c=Q(v({},l),{layoutOrder:(m=(d=l.layoutOrder)!=null?d:c==null?void 0:c.layoutOrder)!=null?m:null,slots:v(v({},(x=c==null?void 0:c.slots)!=null?x:{}),l.slots)}),H(e.apiKey||"local",{v:1,persona:c.persona,band:(0,we.confidenceBand)(c.confidence),slots:c.slots,layoutOrder:c.layoutOrder,savedAt:Date.now()}),u(l),l},getSlotResult(s){var o,l,d;return(d=(l=c==null?void 0:c.slots[s])!=null?l:(o=e.initialSlots)==null?void 0:o[s])!=null?d:null},getPersona(){return c?{persona:c.persona,confidence:c.confidence,band:(0,we.confidenceBand)(c.confidence)}:null},async assign(s,o){var m;let l=await f;return!l||!o||o.length===0?o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null:{variantId:(m=l.createLocalEngine({sessionId:n,forcedPersona:i}).decide({components:[{id:s,variantIds:o}]}).assignments[s])!=null?m:o[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function Fe(e,t,n,i){let f=[];{let r=!1,s=[],o=()=>{if(r)return;let l=Date.now();for(s.push(l);s.length>0&&l-s[0]>500;)s.shift();s.length>=3&&(r=!0,e("rage_click"))};t.addEventListener("click",o),f.push(()=>t.removeEventListener("click",o))}{let c=!1,u=r=>{if(c||!(r.target instanceof Node)||!t.contains(r.target)&&t!==r.target)return;c=!0;let s=typeof window!="undefined"?window.getSelection():null,o=s?s.toString().length:0;e("text_copy",{selectionLength:o})};document.addEventListener("copy",u),f.push(()=>document.removeEventListener("copy",u))}{let c=!1,u=!1,r=null,s=()=>{r!==null&&(clearTimeout(r),r=null)},o=()=>{c||!u||(s(),r=setTimeout(()=>{!c&&u&&(c=!0,e("scroll_hesitation"))},3e3))},l=()=>{s(),o()},d=x=>{for(let L of x)u=L.intersectionRatio>.3,u?o():s()},m=new IntersectionObserver(d,{threshold:[.3]});m.observe(t),window.addEventListener("scroll",l,{passive:!0}),f.push(()=>{m.disconnect(),window.removeEventListener("scroll",l),s()})}if((i==null?void 0:i.tabLoss)!==!1){let c=!1,u=n!=null?n:Date.now(),r=()=>{if(c||document.visibilityState!=="hidden")return;let s=Date.now()-u;s<15e3&&(c=!0,e("tab_loss",{timeOnPage:s}))};document.addEventListener("visibilitychange",r),f.push(()=>document.removeEventListener("visibilitychange",r))}return()=>{for(let c of f)c()}}var Je="https://api.sentient-ui.com/v1/events",R=new Map,Qe=null;function Ae(){return ge()}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 kt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,i]of t)n.startsWith("utm_")&&(e[n]=i);return e}catch(e){return{}}}function Ve(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 _t(e){var r;if(typeof window=="undefined")return;let t=e!=null?e:Qe;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=R.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:i,upgrade:f}=n;if(!f||i.respectDoNotTrack!==!1&&ke())return;let c=ze(Q(v({},i),{consent:!0}));f(c);let u=(r=R.get(t))==null?void 0:r.dispose;R.set(t,{config:Q(v({},i),{consent:!0}),upgrade:null,dispose:u})}function Dt(e){var u;let t=Ve((u=e.ingestUrl)!=null?u:Je),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},i={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(r,s,o){try{let l=new URLSearchParams({componentId:r});for(let x of s!=null?s:[])l.append("variantIds[]",x);let d=await fetch(`${t}/winner?${l.toString()}`,{headers:n});return d.ok?{variantId:(await d.json()).variantId,assignmentTtlMs:0}:s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}catch(l){return s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},f={track:r=>i.track(r),goal:(r,s,o,l)=>i.goal(r,s,o,l),componentGoal:(r,s,o)=>i.componentGoal(r,s,o),identify:r=>i.identify(r),getAssignment:(r,s)=>i.getAssignment(r,s),assign:(r,s,o,l)=>i.assign(r,s,o,l),decide:r=>i.decide(r),getSlotResult:r=>i.getSlotResult(r),getPersona:()=>i.getPersona(),fetchWeights:()=>i.fetchWeights(),getGraph:()=>i.getGraph(),dispose:()=>i.dispose(),destroy:()=>i.destroy()};function c(r){i=r}return{proxy:f,setInner:c}}function ze(e){var q,X,Z,ee,p,y,N,T,K;if(typeof window=="undefined")return Y;Qe=e.apiKey;let t=R.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(a){}let n=e.respectDoNotTrack!==!1&&ke(),i=e.consent===!1||n,f=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!f&&e.localMode!==!1)return i?(R.set(e.apiKey||"local",{config:e,upgrade:null}),Y):(R.set(e.apiKey||"local",{config:e,upgrade:null}),je(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."),Y;let{proxy:a,setInner:g}=Dt(e);return R.set(e.apiKey,{config:e,upgrade:n?null:g}),a}return R.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 c=(q=e.ingestUrl)!=null?q:Je,u=Date.now(),r=fe({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),s=Ne(void 0,e.apiKey),o=Me({ingestUrl:c,apiKey:e.apiKey}),l=Ve(c),d={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},m=ie((X=navigator.userAgent)!=null?X:""),x=typeof window!="undefined"?window.location.origin:void 0,L=ae((Z=document.referrer)!=null?Z:"",x),b=(ee=e.sessionSegment)!=null?ee:`${m}:${L}`,I=new Map,C=new Map,h=null,ue=a=>{for(let g of a)C.has(g.id)||C.set(g.id,z(g))};if(e.initialSlots)for(let[a,g]of Object.entries(e.initialSlots))C.set(a,g);let $=he(e.apiKey);if($)for(let[a,g]of Object.entries($.slots))C.has(a)||C.set(a,g);let M={low:.15,medium:.5,high:.85};if(e.initialPersona)h=v({},e.initialPersona);else{let a=document.documentElement.dataset;a.sentientPersona?h={persona:a.sentientPersona,confidence:(y=M[(p=a.sentientConfidence)!=null?p:"low"])!=null?y:.15}:$&&(h={persona:$.persona,confidence:(N=M[$.band])!=null?N:.15})}if(e.initialAssignments)for(let[a,g]of Object.entries(e.initialAssignments))s.set(a,b,{variantId:g,assignedAt:Date.now(),segment:b,confidence:1});let O=Promise.resolve(),W=r.getSessionId();if(W){let a=le((T=document.referrer)!=null?T:""),g=v(v({sessionId:W,deviceClass:m,trafficSource:L,referrerDomain:a,utmParams:kt(),timeOfDay:ce(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:r.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||se((K=navigator.userAgent)!=null?K:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{O=fetch(`${l}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(g),headers:d}).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:o});let U={goal(a,g={},S=1,P=0){let A=r.getSessionId();if(!A)return;let E=Ae();O.then(()=>{fetch(`${l}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:A,name:a,metadata:g,weight:S,stepIndex:P,goalId:E}),headers:d}).catch(()=>{})})},componentGoal(a,g,S){var k,B,_;let P=r.getSessionId();if(!P)return;let A=s.get(a,b),E=A?null:(k=C.get(a))!=null?k:null;if(!A&&E===null){e.debug&&console.warn(`[sentient] componentGoal("${a}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let j=A?A.variantId:Se(E),G={id:Ae(),sessionId:P,projectId:e.apiKey,componentId:a,variantId:j,eventType:"goal_achieved",goalType:g,payload:v({reward:(B=S==null?void 0:S.reward)!=null?B:1},(_=S==null?void 0:S.metadata)!=null?_:{}),timestamp:Date.now(),timeInSession:Date.now()-u};e.debug&&console.log("[sentient] componentGoal",G),O.then(()=>o.push(G))},identify(a){let g=r.getSessionId();g&&O.then(()=>{fetch(`${l}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:g,userId:a,ephemeral:r.isEphemeral()}),headers:d}).catch(()=>{})})},track(a){let g=r.getSessionId();if(!g)return;let S=Q(v({},a),{id:Ae(),sessionId:g,timestamp:Date.now(),timeInSession:Date.now()-u});e.debug&&console.log("[sentient] track",S),O.then(()=>o.push(S))},getAssignment(a,g){return s.get(a,g)},async assign(a,g,S,P){let A=r.getSessionId();if(!A)return null;let E=s.get(a,b);if(E&&(g!=null&&g.length||E.content!==void 0)){let k=E.ttlMs&&E.ttlMs>0?Math.max(0,E.assignedAt+E.ttlMs-Date.now()):0;return{variantId:E.variantId,assignmentTtlMs:k,content:E.content}}let j=I.get(a);if(j)return j;let G=(async()=>{await O;try{let k={sessionId:A,componentId:a,variantIds:g};P!==void 0?k.agentDataByVariant=P:S!==void 0&&(k.agentData=S);let B=await fetch(`${l}/assign`,{method:"POST",body:JSON.stringify(k),headers:d});if(!B.ok)return null;let _=await B.json();return s.set(a,b,v({variantId:_.variantId,assignedAt:Date.now(),segment:b,confidence:1,content:_.content},_.assignmentTtlMs&&_.assignmentTtlMs>0?{ttlMs:_.assignmentTtlMs}:{})),_}catch(k){return null}finally{I.delete(a)}})();return I.set(a,G),G},async decide(a){var P,A,E,j,G,k,B,_,_e;let g=r.getSessionId();if(!g)return null;let S=(P=a.slots)!=null?P:[];await O;try{let F={sessionId:g};a.sections&&a.sections.length>0&&(F.sections=a.sections.map(D=>({id:D}))),F.components=(A=a.components)!=null?A:[],S.length>0&&(F.slots=S.map(de)),a.slotsFrom==="registry"&&(F.slotsFrom="registry"),a.v&&(F.v=a.v);let De=await fetch(`${l}/decide`,{method:"POST",body:JSON.stringify(F),headers:d});if(!De.ok)return ue(S),null;let w=await De.json(),te={};for(let D of S)te[D.id]=(j=(E=w.slots)==null?void 0:E[D.id])!=null?j:z(D);if(w.slots)for(let[D,ne]of Object.entries(w.slots))D in te||(te[D]=ne);for(let[D,ne]of Object.entries(te))C.set(D,ne);let He=h!=null&&h.persona!=="unknown";w.persona&&!(w.persona==="unknown"&&He)?h={persona:w.persona,confidence:(G=w.confidence)!=null?G:0}:h||(h={persona:"unknown",confidence:0});for(let[D,ne]of Object.entries((k=w.assignments)!=null?k:{}))s.set(D,b,{variantId:ne,assignedAt:Date.now(),segment:b,confidence:1});return H(e.apiKey,v({v:1,persona:h.persona,band:(0,Re.confidenceBand)(h.confidence),slots:Object.fromEntries(C),layoutOrder:(B=w.layoutOrder)!=null?B:null,savedAt:Date.now()},w.slotConfig?{slotConfig:w.slotConfig}:{})),v(v(v({layoutOrder:(_=w.layoutOrder)!=null?_:null,assignments:(_e=w.assignments)!=null?_e:{},slots:te,persona:h.persona,confidence:h.confidence},w.slotConfig?{slotConfig:w.slotConfig}:{}),w.goals?{goals:w.goals}:{}),w.sectionMap?{sectionMap:w.sectionMap}:{})}catch(F){return ue(S),null}},getSlotResult(a){var g;return(g=C.get(a))!=null?g:null},getPersona(){return h?{persona:h.persona,confidence:h.confidence,band:(0,Re.confidenceBand)(h.confidence)}:null},async fetchWeights(){var a;try{let g=await fetch(`${l}/weights`,{headers:d});return g.ok?(a=(await g.json()).components)!=null?a:[]:[]}catch(g){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var a;o.destroy(),((a=R.get(e.apiKey))==null?void 0:a.dispose)===U.dispose&&R.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var a;o.destroy(),r.destroy(),((a=R.get(e.apiKey))==null?void 0:a.dispose)===U.dispose&&R.delete(e.apiKey);try{localStorage.removeItem(J+e.apiKey),localStorage.removeItem(Ee(e.apiKey))}catch(g){}e.debug&&console.log("[sentient] destroyed")}};if(R.set(e.apiKey,{config:e,upgrade:null,dispose:U.dispose}),e.debug){let a=window;a.__sentient&&(a.__sentient.client=U)}return U}0&&(module.exports={AGENT_INTENTS,LOCAL_MODE_BANNER,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,agentIntent,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,toWireSlot,uaTokenMatch,writeSnapshot});
2
2
  //# sourceMappingURL=index.js.map