@sentientui/core 0.12.0 → 0.12.1
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/chunk-ZALZC4AD.mjs +1 -0
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index-server.d.cts +9 -0
- package/dist/index-server.d.ts +9 -0
- package/dist/index-server.js +1 -1
- package/dist/index-server.mjs +1 -1
- package/dist/index.d.cts +5 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-G6ZN7Q63.mjs +0 -1
|
@@ -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 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};
|
package/dist/index-graph.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Ye=Object.create;var Z=Object.defineProperty,Ve=Object.defineProperties,qe=Object.getOwnPropertyDescriptor,Xe=Object.getOwnPropertyDescriptors,Ze=Object.getOwnPropertyNames,Oe=Object.getOwnPropertySymbols,et=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty,tt=Object.prototype.propertyIsEnumerable;var De=(e,t,n)=>t in e?Z(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,b=(e,t)=>{for(var n in t||(t={}))ke.call(t,n)&&De(e,n,t[n]);if(Oe)for(var n of Oe(t))tt.call(t,n)&&De(e,n,t[n]);return e},K=(e,t)=>Ve(e,Xe(t));var nt=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},Ne=(e,t,n,d)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of Ze(t))!ke.call(e,c)&&c!==n&&Z(e,c,{get:()=>t[c],enumerable:!(d=qe(t,c))||d.enumerable});return e};var ot=(e,t,n)=>(n=e!=null?Ye(et(e)):{},Ne(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e)),rt=e=>Ne(Z({},"__esModule",{value:!0}),e);var Ht={};nt(Ht,{deriveSessionSegment:()=>Se,detectDeviceClass:()=>B,detectTimeOfDay:()=>W,detectTrafficSource:()=>j,init:()=>zt,referrerDomainFromReferer:()=>F});module.exports=rt(Ht);var st="_snt_uid";var $="_snt_uid";function it(){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 at(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function ct(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(d){}}function dt(e){try{return localStorage.getItem(e)}catch(t){return null}}function lt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function ut(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function gt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function pt(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 mt(e){try{localStorage.removeItem(e)}catch(t){}}function yt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var ht={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function re(e){var r,u,f,m,p,S;if(typeof window=="undefined")return ht;let t=(r=e==null?void 0:e.cookieName)!=null?r:st,d=((u=e==null?void 0:e.cookieTTLDays)!=null?u:365)*24*60*60,c=(S=(p=(m=(f=at(t))!=null?f:dt($))!=null?m:ut($))!=null?p:e==null?void 0:e.ssrSessionId)!=null?S:it();ct(t,c,d);let o=lt($,c),i=ft(t),a=o?!1:gt($,c),s=!o&&!i&&!a;return{getSessionId:()=>c,isEphemeral:()=>s,destroy:()=>{c=null,yt(t),mt($),pt($)}}}function me(e){return`_snt_retry_${e.slice(0,12)}`}var St={push:()=>{},flush:()=>{},destroy:()=>{}};function vt(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let d=JSON.parse(n);return Array.isArray(d)?(localStorage.removeItem(t),d.slice(-e)):[]}catch(n){return[]}}function fe(e,t,n){try{let c=[...(()=>{try{let o=localStorage.getItem(n);if(!o)return[];let i=JSON.parse(o);return Array.isArray(i)?i:[]}catch(o){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(c))}catch(d){}}function Pe(e){var Y,V,q;if(typeof window=="undefined")return St;let t=(Y=e.flushIntervalMs)!=null?Y:5e3,n=(V=e.maxBatchSize)!=null?V:20,d=(q=e.maxRetrySize)!=null?q:100,c=e.ingestUrl,o=e.apiKey,i=me(o),a=[],s=new Set,r=[],u=y=>{for(let E of y)f.delete(E),!s.has(E)&&(s.add(E),r.push(E));for(;r.length>500;){let E=r.shift();E&&s.delete(E)}},f=new Set,m=y=>{s.has(y.id)||f.has(y.id)||(f.add(y.id),a.push(y))},p=vt(d,i);for(let y of p)m(y);let S=0,v=0,w=y=>{if(y.length===0)return;let E=JSON.stringify(y),x=y.map(g=>g.id),_;try{_=fetch(c,{method:"POST",keepalive:!0,body:E,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}})}catch(g){fe(y,d,i);for(let h of x)f.delete(h);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6));return}let l=g=>{if(g.ok||g.status>=400&&g.status<500&&g.status!==429){u(x),v=0,S=0;return}fe(y,d,i);for(let h of x)f.delete(h);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};_ instanceof Promise?_.then(l).catch(()=>{fe(y,d,i);for(let g of x)f.delete(g);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):l(_)},k=typeof TextEncoder!="undefined"?new TextEncoder:null,L=y=>k?k.encode(y).length:y.length,oe=y=>{let E=[],x=2;for(let _ of y){let l=L(JSON.stringify(_))+1;if(E.length>0&&x+l>57344||E.length>=n)break;E.push(_),x+=l}return E},I=()=>{try{if(Date.now()<S)return;for(;a.length>0;){let y=a.filter(x=>!s.has(x.id));if(a.length=0,y.length===0)break;let E=oe(y);if(E.length===0)break;E.length<y.length&&a.push(...y.slice(E.length)),w(E)}}catch(y){}},z=!0,M=null;M=setInterval(()=>{z&&I()},t);let H=()=>{document.visibilityState==="hidden"&&I()},Q=()=>{I()};return document.addEventListener("visibilitychange",H),window.addEventListener("beforeunload",Q),{push(y){m(y),a.length>=n&&I()},flush:I,destroy(){z=!1,M!==null&&(clearInterval(M),M=null),document.removeEventListener("visibilitychange",H),window.removeEventListener("beforeunload",Q),I()}}}var he="_snt_asgn_";function se(e,t){return`${e}:${t}`}function Et(e,t){return`${he}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Le(e){let t=e.slice(he.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(d){return null}}function ye(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(he)&&e.push(n)}return e}catch(e){return[]}}function Me(e=18e5){let t=new Map,n=c=>c.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let c of ye())try{let o=localStorage.getItem(c);if(!o)continue;let i=JSON.parse(o);if(n(i)){localStorage.removeItem(c);continue}let a=Le(c);if(!a)continue;t.set(se(a.componentId,a.segment),i)}catch(o){}})(),{get(c,o){let i=t.get(se(c,o));return i?n(i)?(t.delete(se(c,o)),null):i:null},set(c,o,i){let a=se(c,o);t.set(a,i);try{localStorage.setItem(Et(c,o),JSON.stringify(i))}catch(s){}},invalidate(c){let o=`${c}:`;for(let i of[...t.keys()])i.startsWith(o)&&t.delete(i);for(let i of ye()){let a=Le(i);if((a==null?void 0:a.componentId)===c)try{localStorage.removeItem(i)}catch(s){}}},clear(){t.clear();for(let c of ye())try{localStorage.removeItem(c)}catch(o){}}}}var Ue=["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 ie(e){return Ge(e)!==null}function Ge(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ue.find(d=>t.includes(d.toLowerCase())))!=null?n:null}function B(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(c){}let d=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(d)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(d)?"social":"referral"}catch(n){return"direct"}}function F(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function W(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Se(e){let t=wt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function wt(e,t){var o,i,a,s,r,u,f;let n=(i=(o=t==null?void 0:t.userAgent)==null?void 0:o.trim())!=null?i:"",d=(s=(a=t==null?void 0:t.referer)==null?void 0:a.trim())!=null?s:"",c=(r=t==null?void 0:t.now)!=null?r:new Date;return{sessionId:e,ephemeral:!1,utmParams:(u=t==null?void 0:t.utmParams)!=null?u:{},deviceClass:n?B(n):"desktop",trafficSource:d?j(d,t==null?void 0:t.appOrigin):"direct",referrerDomain:F(d),timeOfDay:W(c),dayOfWeek:(f=["sun","mon","tue","wed","thu","fri","sat"][c.getDay()])!=null?f:"sun",automation:(t==null?void 0:t.webdriver)===!0||ie(n)}}var J=require("@sentientui/policy");function ae(e){return b(b(b({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 ce(e){let t=ae(e);return(0,J.slotResultFor)(t,(0,J.slotBaselineArm)(t))}function ve(e){return typeof e=="string"?e:(0,J.canonicalArm)(e)}var ee="_snt_snap:",bt=["low","medium","high"];function Ee(e){try{let t=localStorage.getItem(ee+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 te(e,t){try{localStorage.setItem(ee+e,JSON.stringify(t))}catch(n){}}var Ie=require("@sentientui/policy");var le=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.",$e="[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,de=!1;function It(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Be(e){var a;let t=re({ssrSessionId:e.ssrSessionId}),n=(a=t.getSessionId())!=null?a:"local",d=It(),c=import("@sentientui/core/local").then(s=>{let r=s;return r.LOCAL_ENGINE_AVAILABLE?(Ke||(Ke=!0,console.info($e)),r):(de||(de=!0,console.error(we)),null)}).catch(()=>(de||(de=!0,console.error(we)),null)),o=null;function i(s){let r=document.documentElement;r.dataset.sentientPersona===void 0&&(r.dataset.sentientPersona=s.persona,r.dataset.sentientConfidence=(0,le.confidenceBand)(s.confidence))}return{isLocal:!0,async decide(s){var f,m,p;let r=await c;if(!r)return null;let u=r.createLocalEngine({sessionId:n,forcedPersona:d}).decide(s);return o=K(b({},u),{layoutOrder:(m=(f=u.layoutOrder)!=null?f:o==null?void 0:o.layoutOrder)!=null?m:null,slots:b(b({},(p=o==null?void 0:o.slots)!=null?p:{}),u.slots)}),te(e.apiKey||"local",{v:1,persona:o.persona,band:(0,le.confidenceBand)(o.confidence),slots:o.slots,layoutOrder:o.layoutOrder,savedAt:Date.now()}),i(u),u},getSlotResult(s){var r,u,f;return(f=(u=o==null?void 0:o.slots[s])!=null?u:(r=e.initialSlots)==null?void 0:r[s])!=null?f:null},getPersona(){return o?{persona:o.persona,confidence:o.confidence,band:(0,le.confidenceBand)(o.confidence)}:null},async assign(s,r){var m;let u=await c;return!u||!r||r.length===0?r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null:{variantId:(m=u.createLocalEngine({sessionId:n,forcedPersona:d}).decide({components:[{id:s,variantIds:r}]}).assignments[s])!=null?m:r[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var je="https://api.sentient-ui.com/v1/events",ue=new Map,Ct=null;function be(){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 ne={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,d]of t)n.startsWith("utm_")&&(e[n]=d);return e}catch(e){return{}}}function Fe(e){return e.replace(/\/events\/?$/,"")}function At(){return[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 i;let t=Fe((i=e.ingestUrl)!=null?i:je),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(a,s,r){try{let u=new URLSearchParams({componentId:a});for(let p of s!=null?s:[])u.append("variantIds[]",p);let f=await fetch(`${t}/winner?${u.toString()}`,{headers:n});return f.ok?{variantId:(await f.json()).variantId,assignmentTtlMs:0}:s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}catch(u){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:()=>{}},c={track:a=>d.track(a),goal:(a,s,r,u)=>d.goal(a,s,r,u),componentGoal:(a,s,r)=>d.componentGoal(a,s,r),identify:a=>d.identify(a),getAssignment:(a,s)=>d.getAssignment(a,s),assign:(a,s,r,u)=>d.assign(a,s,r,u),decide:a=>d.decide(a),getSlotResult:a=>d.getSlotResult(a),getPersona:()=>d.getPersona(),fetchWeights:()=>d.fetchWeights(),getGraph:()=>d.getGraph(),dispose:()=>d.dispose(),destroy:()=>d.destroy()};function o(a){d=a}return{proxy:c,setInner:o}}function We(e){var H,Q,Y,V,q,y,E,x,_;if(typeof window=="undefined")return ne;Ct=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return ue.set(e.apiKey||"local",{config:e,upgrade:null}),Be(e);let n=e.respectDoNotTrack!==!1&&At();if(e.consent===!1||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."),ne;let{proxy:l,setInner:g}=_t(e);return ue.set(e.apiKey,{config:e,upgrade:n?null:g}),l}return ue.set(e.apiKey,{config:e,upgrade:null}),ne}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."),ne;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),ne;let d=(H=e.ingestUrl)!=null?H:je,c=Date.now(),o=re({ssrSessionId:e.ssrSessionId}),i=Me(),a=Pe({ingestUrl:d,apiKey:e.apiKey}),s=Fe(d),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u=B((Q=navigator.userAgent)!=null?Q:""),f=typeof window!="undefined"?window.location.origin:void 0,m=j((Y=document.referrer)!=null?Y:"",f),p=(V=e.sessionSegment)!=null?V:`${u}:${m}`,S=new Map,v=new Map,w=null,k=l=>{for(let g of l)v.has(g.id)||v.set(g.id,ce(g))};if(e.initialSlots)for(let[l,g]of Object.entries(e.initialSlots))v.set(l,g);let L=Ee(e.apiKey);if(L)for(let[l,g]of Object.entries(L.slots))v.has(l)||v.set(l,g);let oe={low:.15,medium:.5,high:.85};if(e.initialPersona)w=b({},e.initialPersona);else{let l=document.documentElement.dataset;l.sentientPersona?w={persona:l.sentientPersona,confidence:(y=oe[(q=l.sentientConfidence)!=null?q:"low"])!=null?y:.15}:L&&(w={persona:L.persona,confidence:(E=oe[L.band])!=null?E:.15})}if(e.initialAssignments)for(let[l,g]of Object.entries(e.initialAssignments))i.set(l,p,{variantId:g,assignedAt:Date.now(),segment:p,confidence:1});let I=Promise.resolve(),z=o.getSessionId();if(z){let l=F((x=document.referrer)!=null?x:""),g=b(b({sessionId:z,deviceClass:u,trafficSource:m,referrerDomain:l,utmParams:xt(),timeOfDay:W(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||ie((_=navigator.userAgent)!=null?_:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{I=fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(g),headers:r}).then(h=>{h.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(h){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:a});let M={goal(l,g={},h=1,T=0){let C=o.getSessionId();if(!C)return;let A=be();I.then(()=>{fetch(`${s}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:C,name:l,metadata:g,weight:h,stepIndex:T,goalId:A}),headers:r}).catch(()=>{})})},componentGoal(l,g,h){var R,P,O;let T=o.getSessionId();if(!T)return;let C=i.get(l,p),A=C?null:(R=v.get(l))!=null?R:null;if(!C&&A===null){e.debug&&console.warn(`[sentient] componentGoal("${l}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let U=C?C.variantId:ve(A),N={id:be(),sessionId:T,projectId:e.apiKey,componentId:l,variantId:U,eventType:"goal_achieved",goalType:g,payload:b({reward:(P=h==null?void 0:h.reward)!=null?P:1},(O=h==null?void 0:h.metadata)!=null?O:{}),timestamp:Date.now(),timeInSession:Date.now()-c};e.debug&&console.log("[sentient] componentGoal",N),I.then(()=>a.push(N))},identify(l){let g=o.getSessionId();g&&I.then(()=>{fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:g,userId:l,ephemeral:o.isEphemeral()}),headers:r}).catch(()=>{})})},track(l){let g=o.getSessionId();if(!g)return;let h=K(b({},l),{id:be(),sessionId:g,timestamp:Date.now(),timeInSession:Date.now()-c});e.debug&&console.log("[sentient] track",h),I.then(()=>a.push(h))},getAssignment(l,g){return i.get(l,g)},async assign(l,g,h,T){let C=o.getSessionId();if(!C)return null;let A=i.get(l,p);if(A&&(g!=null&&g.length||A.content!==void 0))return{variantId:A.variantId,assignmentTtlMs:0,content:A.content};let U=S.get(l);if(U)return U;let N=(async()=>{await I;try{let R={sessionId:C,componentId:l,variantIds:g};T!==void 0?R.agentDataByVariant=T:h!==void 0&&(R.agentData=h);let P=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify(R),headers:r});if(!P.ok)return null;let O=await P.json();return i.set(l,p,{variantId:O.variantId,assignedAt:Date.now(),segment:p,confidence:1,content:O.content}),O}catch(R){return null}finally{S.delete(l)}})();return S.set(l,N),N},async decide(l){var T,C,A,U,N,R,P,O,_e,Te;let g=o.getSessionId();if(!g)return null;let h=(T=l.slots)!=null?T:[];await I;try{let X={sessionId:g};l.sections&&l.sections.length>0&&(X.sections=l.sections.map(D=>({id:D}))),X.components=(C=l.components)!=null?C:[],h.length>0&&(X.slots=h.map(ae));let Re=await fetch(`${s}/decide`,{method:"POST",body:JSON.stringify(X),headers:r});if(!Re.ok)return k(h),null;let G=await Re.json(),ge={};for(let D of h)ge[D.id]=(U=(A=G.slots)==null?void 0:A[D.id])!=null?U:ce(D);for(let[D,pe]of Object.entries(ge))v.set(D,pe);w={persona:(N=G.persona)!=null?N:"unknown",confidence:(R=G.confidence)!=null?R:0};for(let[D,pe]of Object.entries((P=G.assignments)!=null?P:{}))i.set(D,p,{variantId:pe,assignedAt:Date.now(),segment:p,confidence:1});return te(e.apiKey,{v:1,persona:w.persona,band:(0,Ie.confidenceBand)(w.confidence),slots:Object.fromEntries(v),layoutOrder:(O=G.layoutOrder)!=null?O:null,savedAt:Date.now()}),{layoutOrder:(_e=G.layoutOrder)!=null?_e:null,assignments:(Te=G.assignments)!=null?Te:{},slots:ge,persona:w.persona,confidence:w.confidence}}catch(X){return k(h),null}},getSlotResult(l){var g;return(g=v.get(l))!=null?g:null},getPersona(){return w?{persona:w.persona,confidence:w.confidence,band:(0,Ie.confidenceBand)(w.confidence)}:null},async fetchWeights(){var l;try{let g=await fetch(`${s}/weights`,{headers:r});return g.ok?(l=(await g.json()).components)!=null?l:[]:[]}catch(g){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){a.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){a.destroy(),o.destroy();try{localStorage.removeItem(ee+e.apiKey),localStorage.removeItem(me(e.apiKey))}catch(l){}e.debug&&console.log("[sentient] destroyed")}};if(ue.set(e.apiKey,{config:e,upgrade:null}),e.debug){let l=window;l.__sentient&&(l.__sentient.client=M)}return M}var Tt=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Rt="h1, h2, h3",Ot={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function Ce(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Dt(e){var t,n,d;try{let c=e;for(let o of Object.keys(c)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let i=c[o],a=(d=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?d:(n=i==null?void 0:i.type)==null?void 0:n.name;if(a&&a.length>1)return a}}catch(c){}}function kt(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function Nt(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function Pt(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function Lt(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function xe(e,t){var d,c,o;let n=e.querySelector(Rt);return{componentId:Pt(e),semanticType:Nt(e),ariaLabel:(d=e.getAttribute("aria-label"))!=null?d:void 0,headingText:(o=(c=n==null?void 0:n.textContent)==null?void 0:c.trim())!=null?o:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Lt(e),reactComponentName:Dt(e),dataAttributes:kt(e)}}function Je(e){var o;let t=[],n=new Set,d="__root__",c=new Map;for(let[i,a]of e){let s=i.parentElement,r=d;for(;s;){if(e.has(s)){r=e.get(s);let f=e.get(i),m=`${r}->${f}`;!n.has(m)&&r!==f&&(n.add(m),t.push({fromComponentId:r,toComponentId:f,weight:.6}));break}s=s.parentElement}let u=(o=c.get(r))!=null?o:[];u.push(i),c.set(r,u)}for(let i of c.values())if(!(i.length<2))for(let a=0;a<i.length;a++)for(let s=a+1;s<i.length;s++){let r=e.get(i[a]),u=e.get(i[s]);if(r===u)continue;let f=`${r}->${u}::sib`,m=`${u}->${r}::sib`;n.has(f)||(n.add(f),t.push({fromComponentId:r,toComponentId:u,weight:.3})),n.has(m)||(n.add(m),t.push({fromComponentId:u,toComponentId:r,weight:.3}))}return t}function Mt(e){let t=[],n=new Set,d=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(i=>{if(i instanceof Element&&!n.has(i)){n.add(i);let a=xe(i,e);t.push(a),d.set(i,a.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(i=>{if(!(i instanceof Element)||n.has(i))return;let a=i.hasAttribute("aria-label"),s=i.hasAttribute("data-sentient-id");if(!a&&!s)return;n.add(i);let r=xe(i,e);t.push(r),d.set(i,r.componentId)}),{nodes:t,edges:Je(d)}}function ze(){if(typeof window=="undefined")return Ot;let e=null,t=0,n=null,d=a=>{try{let s=window.getComputedStyle(a),r=parseFloat(s.fontSize)||12,u=parseFloat(s.zIndex)||0,f=a.getBoundingClientRect(),m=Math.max(f.top,0),p=window.innerHeight||1,S=1/(m/p+1),v=Ce(r,12,48)*.4+Ce(S,0,1)*.4+Ce(u,0,100)*.2;return Math.max(0,Math.min(1,v))}catch(s){return .5}};return{scan:()=>new Promise(a=>{let s=()=>{let{nodes:r,edges:u}=Mt(d);a({nodes:r,edges:u,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(s,{timeout:100}):s()}catch(r){s()}}),observe:a=>{n=a;try{e=new MutationObserver(s=>{let r=[],u=new Map;for(let f of s)f.type==="childList"&&f.addedNodes.forEach(m=>{if(!(m instanceof Element)||!Tt.has(m.tagName))return;let p=m.hasAttribute("data-sentient-id"),S=m.hasAttribute("aria-label");if(!p&&!S)return;let v=xe(m,d);r.push(v),u.set(m,v.componentId)});r.length>0&&n&&n({nodes:r,edges:Je(u),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(s){}},getProminenceScore:d,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(a){}t=0,n=null}}}var Ae="_snt_graph_nodes",He="_snt_graph_edges",Ut={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function Gt(e){var t;return(t=Ut[e])!=null?t:[]}function Kt(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function $t(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var Bt=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function jt(e){return Bt.has(e)?e:"generic"}function Ft(e,t,n){let d=`${e}:${t}:${n.join(",")}`,c=5381;for(let o=0;o<d.length;o++)c=(c<<5)+c+d.charCodeAt(o)&4294967295;return(c>>>0).toString(16).padStart(8,"0")}function Qe(e){let t=new Map,n=new Map,d=()=>{typeof window!="undefined"&&$t(Ae,[...t.values()])},c=o=>{var i;try{let a=JSON.parse(o);t.clear();for(let s of(i=a.pageNodes)!=null?i:[])t.set(s.componentId,s)}catch(a){}};if(typeof window!="undefined"){let o=Kt(Ae,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(He)}catch(i){}}return{addPageNode(o){t.set(o.componentId,o),d()},addStructuralEdge(o){let i=`${o.fromComponentId}->${o.toComponentId}`;n.set(i,o)},syncOnce(){var i,a;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let s=new Map;for(let p of o){let S=(i=s.get(p.semanticType))!=null?i:[];S.push(p),s.set(p.semanticType,S)}let r=[],u=new Set;for(let p of o)for(let S of Gt(p.semanticType)){let v=(a=s.get(S))!=null?a:[];for(let w of v){if(w.componentId===p.componentId)continue;let k=`semantic:${p.componentId}->${w.componentId}`;u.has(k)||(u.add(k),r.push({fromComponentId:p.componentId,toComponentId:w.componentId,type:"semantic",weight:.4,confidence:.9}))}}let f=new Set(o.map(p=>p.componentId));for(let p of n.values()){if(!f.has(p.fromComponentId)||!f.has(p.toComponentId))continue;let S=`structural:${p.fromComponentId}->${p.toComponentId}`;u.has(S)||(u.add(S),r.push({fromComponentId:p.fromComponentId,toComponentId:p.toComponentId,type:"structural",weight:p.weight,confidence:1}))}let m={pageUrl:window.location.href,nodes:o.map(p=>{let S=jt(p.semanticType);return{componentId:p.componentId,semanticType:S,answers:p.answers,contentHash:Ft(p.componentId,S,p.answers),prominenceScore:p.prominenceScore,depthInPage:p.depth}}),edges:r};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:b({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(m)}).catch(()=>{})}catch(s){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:c,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(Ae),localStorage.removeItem(He)}catch(o){}}}}var Wt="https://api.sentient-ui.com/v1/events";function Jt(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function zt(e){var a;let t=We(e);if(!e.graph||typeof window=="undefined")return t;let n=ze(),d=(a=e.ingestUrl)!=null?a:Wt,c=Qe({syncUrl:d.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Jt()});try{let s=localStorage.getItem("_snt_graph_nodes");s&&c.restore(JSON.stringify({pageNodes:JSON.parse(s)}))}catch(s){}n.scan().then(s=>{for(let r of s.nodes)c.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});for(let r of s.edges)c.addStructuralEdge(r);c.syncOnce()});let o=null,i=()=>{o!==null&&clearTimeout(o),o=setTimeout(()=>{o=null,c.syncOnce()},500)};return n.observe(s=>{for(let r of s.nodes)c.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});for(let r of s.edges)c.addStructuralEdge(r);i()}),K(b({},t),{getGraph:()=>c.snapshot(),dispose:()=>{o!==null&&clearTimeout(o),n.destroy(),c.destroy(),t.dispose()},destroy:()=>{o!==null&&clearTimeout(o),n.destroy(),c.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer});
|
|
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});
|
package/dist/index-graph.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{j as
|
|
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};
|
package/dist/index-server.d.cts
CHANGED
|
@@ -21,6 +21,15 @@ type ServerAssignConfig = {
|
|
|
21
21
|
/** From `Referer` request header. */
|
|
22
22
|
referer?: string;
|
|
23
23
|
utmParams?: Record<string, string>;
|
|
24
|
+
/**
|
|
25
|
+
* Set true when the request carries a tracking opt-out — `DNT: 1` or
|
|
26
|
+
* `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the
|
|
27
|
+
* assign/decide call entirely: the page renders defaults/baseline and no
|
|
28
|
+
* session row is minted for the visitor (audit P4). The client SDK already
|
|
29
|
+
* no-ops for these visitors; this keeps the server from minting a session +
|
|
30
|
+
* assignment on every page view before the client can.
|
|
31
|
+
*/
|
|
32
|
+
doNotTrack?: boolean;
|
|
24
33
|
/**
|
|
25
34
|
* Milliseconds to wait for the API before returning default variants.
|
|
26
35
|
* Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path
|
package/dist/index-server.d.ts
CHANGED
|
@@ -21,6 +21,15 @@ type ServerAssignConfig = {
|
|
|
21
21
|
/** From `Referer` request header. */
|
|
22
22
|
referer?: string;
|
|
23
23
|
utmParams?: Record<string, string>;
|
|
24
|
+
/**
|
|
25
|
+
* Set true when the request carries a tracking opt-out — `DNT: 1` or
|
|
26
|
+
* `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the
|
|
27
|
+
* assign/decide call entirely: the page renders defaults/baseline and no
|
|
28
|
+
* session row is minted for the visitor (audit P4). The client SDK already
|
|
29
|
+
* no-ops for these visitors; this keeps the server from minting a session +
|
|
30
|
+
* assignment on every page view before the client can.
|
|
31
|
+
*/
|
|
32
|
+
doNotTrack?: boolean;
|
|
24
33
|
/**
|
|
25
34
|
* Milliseconds to wait for the API before returning default variants.
|
|
26
35
|
* Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path
|
package/dist/index-server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var R=Object.defineProperty,z=Object.defineProperties,G=Object.getOwnPropertyDescriptor,K=Object.getOwnPropertyDescriptors,q=Object.getOwnPropertyNames,$=Object.getOwnPropertySymbols;var M=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable;var B=(t,e,r)=>e in t?R(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,p=(t,e)=>{for(var r in e||(e={}))M.call(e,r)&&B(t,r,e[r]);if($)for(var r of $(e))H.call(e,r)&&B(t,r,e[r]);return t},L=(t,e)=>z(t,K(e));var Q=(t,e)=>{for(var r in e)R(t,r,{get:e[r],enumerable:!0})},V=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of q(e))!M.call(t,i)&&i!==r&&R(t,i,{get:()=>e[i],enumerable:!(s=G(e,i))||s.enumerable});return t};var X=t=>V(R({},"__esModule",{value:!0}),t);var te={};Q(te,{buildSessionUpsertPayload:()=>y,deriveSessionSegment:()=>_,detectDeviceClass:()=>A,detectTimeOfDay:()=>v,detectTrafficSource:()=>w,preloadAssignments:()=>
|
|
1
|
+
"use strict";var R=Object.defineProperty,z=Object.defineProperties,G=Object.getOwnPropertyDescriptor,K=Object.getOwnPropertyDescriptors,q=Object.getOwnPropertyNames,$=Object.getOwnPropertySymbols;var M=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable;var B=(t,e,r)=>e in t?R(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,p=(t,e)=>{for(var r in e||(e={}))M.call(e,r)&&B(t,r,e[r]);if($)for(var r of $(e))H.call(e,r)&&B(t,r,e[r]);return t},L=(t,e)=>z(t,K(e));var Q=(t,e)=>{for(var r in e)R(t,r,{get:e[r],enumerable:!0})},V=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of q(e))!M.call(t,i)&&i!==r&&R(t,i,{get:()=>e[i],enumerable:!(s=G(e,i))||s.enumerable});return t};var X=t=>V(R({},"__esModule",{value:!0}),t);var te={};Q(te,{buildSessionUpsertPayload:()=>y,deriveSessionSegment:()=>_,detectDeviceClass:()=>A,detectTimeOfDay:()=>v,detectTrafficSource:()=>w,preloadAssignments:()=>F,preloadDecisions:()=>J,readSessionCookie:()=>W,referrerDomainFromReferer:()=>x});module.exports=X(te);var Y=["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 Z(t){return ee(t)!==null}function ee(t){var r;if(!t)return null;let e=t.toLowerCase();return(r=Y.find(s=>e.includes(s.toLowerCase())))!=null?r:null}function A(t){let e=t.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(e)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(e)?"mobile":"desktop"}function w(t,e){if(!t)return"direct";try{let r=new URL(t);if(e)try{if(new URL(e).host===r.host)return"direct"}catch(i){}let s=r.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(s)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(s)?"social":"referral"}catch(r){return"direct"}}function x(t){if(!t)return null;try{return new URL(t).hostname}catch(e){return null}}function v(t){let e=t.getHours();return e<6?"night":e<12?"morning":e<18?"afternoon":"evening"}function _(t){let e=y("__segment__",t);return`${e.deviceClass}:${e.trafficSource}`}function y(t,e){var c,u,g,d,n,l,a;let r=(u=(c=e==null?void 0:e.userAgent)==null?void 0:c.trim())!=null?u:"",s=(d=(g=e==null?void 0:e.referer)==null?void 0:g.trim())!=null?d:"",i=(n=e==null?void 0:e.now)!=null?n:new Date;return{sessionId:t,ephemeral:!1,utmParams:(l=e==null?void 0:e.utmParams)!=null?l:{},deviceClass:r?A(r):"desktop",trafficSource:s?w(s,e==null?void 0:e.appOrigin):"direct",referrerDomain:x(s),timeOfDay:v(i),dayOfWeek:(a=["sun","mon","tue","wed","thu","fri","sat"][i.getDay()])!=null?a:"sun",automation:(e==null?void 0:e.webdriver)===!0||Z(r)}}var S=require("@sentientui/policy");function O(t){return p(p(p({id:t.id},t.arms?{arms:[...t.arms]}:{}),t.dims?{dims:Object.fromEntries(Object.entries(t.dims).map(([e,r])=>[e,[...r]]))}:{}),t.baseline!==void 0?{baseline:t.baseline}:{})}function U(t){let e=O(t);return(0,S.slotResultFor)(e,(0,S.slotBaselineArm)(e))}function N(t){let e={};for(let r of t)e[r.id]=U(r);return e}var E=1e3;function D(t,e,r){let s=new AbortController,i=setTimeout(()=>s.abort(),r);return fetch(t,L(p({},e),{signal:s.signal})).finally(()=>clearTimeout(i))}async function F(t,e,r){var d;if(r.doNotTrack)return{};let s=(d=r.timeoutMs)!=null?d:E,i={"Content-Type":"application/json",Authorization:`Bearer ${r.apiKey}`};r.origin&&(i.Origin=r.origin);let c=y(e,{userAgent:r.userAgent,referer:r.referer,utmParams:r.utmParams,appOrigin:r.origin});try{let n=await D(`${r.baseUrl}/sessions`,{method:"POST",headers:i,body:JSON.stringify(c)},s);if(n.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");else if(!n.ok){let l=await n.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${n.status})`,l)}}catch(n){console.error("[SentientUI] preloadAssignments: session upsert threw",n)}let u=await Promise.allSettled(t.map(async({id:n,variantIds:l})=>{let a=await D(`${r.baseUrl}/assign`,{method:"POST",headers:i,body:JSON.stringify({sessionId:e,componentId:n,variantIds:l})},s);if(!a.ok){let h=await a.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${n}" (${a.status})`,h),null}let b=await a.json();return{id:n,variantId:b.variantId}})),g={};for(let n of u)n.status==="fulfilled"&&n.value&&(g[n.value.id]=n.value.variantId);return g}function W(t){var e,r;return(r=(e=t.get("_snt_uid"))==null?void 0:e.value)!=null?r:null}async function J(t,e,r){var d,n,l,a,b,h,P,k,I,T,C;let s=(d=r.timeoutMs)!=null?d:E,i=(n=t.slots)!=null?n:[],c={layoutOrder:(l=t.sections)!=null?l:[],assignments:{},slots:N(i),persona:"unknown",confidence:0};if(r.doNotTrack)return c;let u={"Content-Type":"application/json",Authorization:`Bearer ${r.apiKey}`};r.origin&&(u.Origin=r.origin);let g=y(e,{userAgent:r.userAgent,referer:r.referer,utmParams:r.utmParams,appOrigin:r.origin});try{let o=await D(`${r.baseUrl}/sessions`,{method:"POST",headers:u,body:JSON.stringify(g)},s);if(!o.ok){let m=await o.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${o.status})`,m)}}catch(o){console.error("[SentientUI] preloadDecisions: session upsert threw",o)}try{let o=await D(`${r.baseUrl}/decide`,{method:"POST",headers:u,body:JSON.stringify(p({sessionId:e,sections:((a=t.sections)!=null?a:[]).map(f=>({id:f})),components:t.components},i.length>0?{slots:i.map(O)}:{}))},s);if(!o.ok){let f=await o.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${o.status})`,f),c}let m=await o.json(),j={};for(let f of i)j[f.id]=(h=(b=m.slots)==null?void 0:b[f.id])!=null?h:U(f);return{layoutOrder:(k=(P=m.layoutOrder)!=null?P:t.sections)!=null?k:[],assignments:(I=m.assignments)!=null?I:{},slots:j,persona:(T=m.persona)!=null?T:"unknown",confidence:(C=m.confidence)!=null?C:0}}catch(o){return console.error("[SentientUI] preloadDecisions: decide threw",o),c}}0&&(module.exports={buildSessionUpsertPayload,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,preloadAssignments,preloadDecisions,readSessionCookie,referrerDomainFromReferer});
|
package/dist/index-server.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as
|
|
1
|
+
import{d as x,e as j,f as $,g as C,h as M,i as f,j as U,k as D,l as P}from"./chunk-SVYHTU5Z.mjs";import{a as A,b as T}from"./chunk-HGGX55FR.mjs";var k=1e3;function b(r,n,e){let i=new AbortController,o=setTimeout(()=>i.abort(),e);return fetch(r,T(A({},n),{signal:i.signal})).finally(()=>clearTimeout(o))}async function N(r,n,e){var p;if(e.doNotTrack)return{};let i=(p=e.timeoutMs)!=null?p:k,o={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};e.origin&&(o.Origin=e.origin);let u=f(n,{userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,appOrigin:e.origin});try{let s=await b(`${e.baseUrl}/sessions`,{method:"POST",headers:o,body:JSON.stringify(u)},i);if(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");else if(!s.ok){let d=await s.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${s.status})`,d)}}catch(s){console.error("[SentientUI] preloadAssignments: session upsert threw",s)}let g=await Promise.allSettled(r.map(async({id:s,variantIds:d})=>{let a=await b(`${e.baseUrl}/assign`,{method:"POST",headers:o,body:JSON.stringify({sessionId:n,componentId:s,variantIds:d})},i);if(!a.ok){let y=await a.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${s}" (${a.status})`,y),null}let S=await a.json();return{id:s,variantId:S.variantId}})),m={};for(let s of g)s.status==="fulfilled"&&s.value&&(m[s.value.id]=s.value.variantId);return m}function B(r){var n,e;return(e=(n=r.get("_snt_uid"))==null?void 0:n.value)!=null?e:null}async function J(r,n,e){var p,s,d,a,S,y,R,h,v,w,I;let i=(p=e.timeoutMs)!=null?p:k,o=(s=r.slots)!=null?s:[],u={layoutOrder:(d=r.sections)!=null?d:[],assignments:{},slots:P(o),persona:"unknown",confidence:0};if(e.doNotTrack)return u;let g={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};e.origin&&(g.Origin=e.origin);let m=f(n,{userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,appOrigin:e.origin});try{let t=await b(`${e.baseUrl}/sessions`,{method:"POST",headers:g,body:JSON.stringify(m)},i);if(!t.ok){let l=await t.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${t.status})`,l)}}catch(t){console.error("[SentientUI] preloadDecisions: session upsert threw",t)}try{let t=await b(`${e.baseUrl}/decide`,{method:"POST",headers:g,body:JSON.stringify(A({sessionId:n,sections:((a=r.sections)!=null?a:[]).map(c=>({id:c})),components:r.components},o.length>0?{slots:o.map(U)}:{}))},i);if(!t.ok){let c=await t.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${t.status})`,c),u}let l=await t.json(),O={};for(let c of o)O[c.id]=(y=(S=l.slots)==null?void 0:S[c.id])!=null?y:D(c);return{layoutOrder:(h=(R=l.layoutOrder)!=null?R:r.sections)!=null?h:[],assignments:(v=l.assignments)!=null?v:{},slots:O,persona:(w=l.persona)!=null?w:"unknown",confidence:(I=l.confidence)!=null?I:0}}catch(t){return console.error("[SentientUI] preloadDecisions: decide threw",t),u}}export{f as buildSessionUpsertPayload,M as deriveSessionSegment,x as detectDeviceClass,C as detectTimeOfDay,j as detectTrafficSource,N as preloadAssignments,J as preloadDecisions,B as readSessionCookie,$ as referrerDomainFromReferer};
|
package/dist/index.d.cts
CHANGED
|
@@ -347,10 +347,11 @@ type SentientClient = {
|
|
|
347
347
|
};
|
|
348
348
|
|
|
349
349
|
/**
|
|
350
|
-
* Detects whether the visitor has
|
|
351
|
-
*
|
|
352
|
-
*
|
|
353
|
-
*
|
|
350
|
+
* Detects whether the visitor has signalled a tracking opt-out. Honors Global
|
|
351
|
+
* Privacy Control (`navigator.globalPrivacyControl`) — the legally-enforceable
|
|
352
|
+
* CCPA/CPRA signal — as well as Do Not Track (`navigator.doNotTrack`, the legacy
|
|
353
|
+
* `window.doNotTrack` on older Firefox, and `navigator.msDoNotTrack` on old
|
|
354
|
+
* IE/Edge). GPC is a boolean; DNT is opt-out only when explicitly `'1'`/`'yes'`.
|
|
354
355
|
*/
|
|
355
356
|
declare function isDoNotTrackEnabled(): boolean;
|
|
356
357
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -347,10 +347,11 @@ type SentientClient = {
|
|
|
347
347
|
};
|
|
348
348
|
|
|
349
349
|
/**
|
|
350
|
-
* Detects whether the visitor has
|
|
351
|
-
*
|
|
352
|
-
*
|
|
353
|
-
*
|
|
350
|
+
* Detects whether the visitor has signalled a tracking opt-out. Honors Global
|
|
351
|
+
* Privacy Control (`navigator.globalPrivacyControl`) — the legally-enforceable
|
|
352
|
+
* CCPA/CPRA signal — as well as Do Not Track (`navigator.doNotTrack`, the legacy
|
|
353
|
+
* `window.doNotTrack` on older Firefox, and `navigator.msDoNotTrack` on old
|
|
354
|
+
* IE/Edge). GPC is a boolean; DNT is opt-out only when explicitly `'1'`/`'yes'`.
|
|
354
355
|
*/
|
|
355
356
|
declare function isDoNotTrackEnabled(): boolean;
|
|
356
357
|
/**
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var Ye=Object.create;var Z=Object.defineProperty,ze=Object.defineProperties,He=Object.getOwnPropertyDescriptor,Ve=Object.getOwnPropertyDescriptors,Xe=Object.getOwnPropertyNames,Oe=Object.getOwnPropertySymbols,qe=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty,Ze=Object.prototype.propertyIsEnumerable;var Ce=(e,t,n)=>t in e?Z(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,w=(e,t)=>{for(var n in t||(t={}))Te.call(t,n)&&Ce(e,n,t[n]);if(Oe)for(var n of Oe(t))Ze.call(t,n)&&Ce(e,n,t[n]);return e},G=(e,t)=>ze(e,Ve(t));var et=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},Pe=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of Xe(t))!Te.call(e,d)&&d!==n&&Z(e,d,{get:()=>t[d],enumerable:!(i=He(t,d))||i.enumerable});return e};var tt=(e,t,n)=>(n=e!=null?Ye(qe(e)):{},Pe(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e)),nt=e=>Pe(Z({},"__esModule",{value:!0}),e);var _t={};et(_t,{LOCAL_MODE_BANNER:()=>xe,PROD_KEYLESS_ERROR:()=>pe,SNAPSHOT_STORAGE_KEY_PREFIX:()=>K,agentUaList:()=>be,armOfResult:()=>de,attachMicroSignalDetectors:()=>We,baselineResultFor:()=>W,baselineSlots:()=>Ke,deriveSessionSegment:()=>Ue,detectDeviceClass:()=>te,detectTimeOfDay:()=>oe,detectTrafficSource:()=>ne,grantConsent:()=>xt,init:()=>Qe,isDoNotTrackEnabled:()=>Re,matchedAgentToken:()=>Ee,readSnapshot:()=>ue,referrerDomainFromReferer:()=>re,renderPrePaintScript:()=>Ge,toWireSlot:()=>se,uaTokenMatch:()=>ee,writeSnapshot:()=>j});module.exports=nt(_t);var rt="_snt_uid";var B="_snt_uid";function ot(){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 st(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function it(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(i){}}function at(e){try{return localStorage.getItem(e)}catch(t){return null}}function lt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function ct(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function dt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function ut(e){try{sessionStorage.removeItem(e)}catch(t){}}function gt(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 ft(e){try{localStorage.removeItem(e)}catch(t){}}function pt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var mt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function le(e){var l,g,m,h,S,b;if(typeof window=="undefined")return mt;let t=(l=e==null?void 0:e.cookieName)!=null?l:rt,i=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,d=(b=(S=(h=(m=st(t))!=null?m:at(B))!=null?h:ct(B))!=null?S:e==null?void 0:e.ssrSessionId)!=null?b:ot();it(t,d,i);let r=lt(B,d),c=gt(t),s=r?!1:dt(B,d),o=!r&&!c&&!s;return{getSessionId:()=>d,isEphemeral:()=>o,destroy:()=>{d=null,pt(t),ft(B),ut(B)}}}function he(e){return`_snt_retry_${e.slice(0,12)}`}var yt={push:()=>{},flush:()=>{},destroy:()=>{}};function St(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 Se(e,t,n){try{let d=[...(()=>{try{let r=localStorage.getItem(n);if(!r)return[];let c=JSON.parse(r);return Array.isArray(c)?c:[]}catch(r){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(d))}catch(i){}}function Le(e){var H,V,X;if(typeof window=="undefined")return yt;let t=(H=e.flushIntervalMs)!=null?H:5e3,n=(V=e.maxBatchSize)!=null?V:20,i=(X=e.maxRetrySize)!=null?X:100,d=e.ingestUrl,r=e.apiKey,c=he(r),s=[],o=new Set,l=[],g=f=>{for(let y of f)m.delete(y),!o.has(y)&&(o.add(y),l.push(y));for(;l.length>500;){let y=l.shift();y&&o.delete(y)}},m=new Set,h=f=>{o.has(f.id)||m.has(f.id)||(m.add(f.id),s.push(f))},S=St(i,c);for(let f of S)h(f);let b=0,v=0,E=f=>{if(f.length===0)return;let y=JSON.stringify(f),_=f.map(u=>u.id),k;try{k=fetch(d,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}})}catch(u){Se(f,i,c);for(let p of _)m.delete(p);v++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6));return}let a=u=>{if(u.ok||u.status>=400&&u.status<500&&u.status!==429){g(_),v=0,b=0;return}Se(f,i,c);for(let p of _)m.delete(p);v++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};k instanceof Promise?k.then(a).catch(()=>{Se(f,i,c);for(let u of _)m.delete(u);v++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):a(k)},J=typeof TextEncoder!="undefined"?new TextEncoder:null,L=f=>J?J.encode(f).length:f.length,ae=f=>{let y=[],_=2;for(let k of f){let a=L(JSON.stringify(k))+1;if(y.length>0&&_+a>57344||y.length>=n)break;y.push(k),_+=a}return y},x=()=>{try{if(Date.now()<b)return;for(;s.length>0;){let f=s.filter(_=>!o.has(_.id));if(s.length=0,f.length===0)break;let y=ae(f);if(y.length===0)break;y.length<f.length&&s.push(...f.slice(y.length)),E(y)}}catch(f){}},Q=!0,N=null;N=setInterval(()=>{Q&&x()},t);let Y=()=>{document.visibilityState==="hidden"&&x()},z=()=>{x()};return document.addEventListener("visibilitychange",Y),window.addEventListener("beforeunload",z),{push(f){h(f),s.length>=n&&x()},flush:x,destroy(){Q=!1,N!==null&&(clearInterval(N),N=null),document.removeEventListener("visibilitychange",Y),window.removeEventListener("beforeunload",z),x()}}}var we="_snt_asgn_";function ce(e,t){return`${e}:${t}`}function ht(e,t){return`${we}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ne(e){let t=e.slice(we.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(i){return null}}function ve(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(we)&&e.push(n)}return e}catch(e){return[]}}function Me(e=18e5){let t=new Map,n=d=>d.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let d of ve())try{let r=localStorage.getItem(d);if(!r)continue;let c=JSON.parse(r);if(n(c)){localStorage.removeItem(d);continue}let s=Ne(d);if(!s)continue;t.set(ce(s.componentId,s.segment),c)}catch(r){}})(),{get(d,r){let c=t.get(ce(d,r));return c?n(c)?(t.delete(ce(d,r)),null):c:null},set(d,r,c){let s=ce(d,r);t.set(s,c);try{localStorage.setItem(ht(d,r),JSON.stringify(c))}catch(o){}},invalidate(d){let r=`${d}:`;for(let c of[...t.keys()])c.startsWith(r)&&t.delete(c);for(let c of ve()){let s=Ne(c);if((s==null?void 0:s.componentId)===d)try{localStorage.removeItem(c)}catch(o){}}},clear(){t.clear();for(let d of ve())try{localStorage.removeItem(d)}catch(r){}}}}var be=["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 ee(e){return Ee(e)!==null}function Ee(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=be.find(i=>t.includes(i.toLowerCase())))!=null?n:null}function te(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 ne(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 i=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(i)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(i)?"social":"referral"}catch(n){return"direct"}}function re(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function oe(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ue(e){let t=vt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function vt(e,t){var r,c,s,o,l,g,m;let n=(c=(r=t==null?void 0:t.userAgent)==null?void 0:r.trim())!=null?c:"",i=(o=(s=t==null?void 0:t.referer)==null?void 0:s.trim())!=null?o:"",d=(l=t==null?void 0:t.now)!=null?l:new Date;return{sessionId:e,ephemeral:!1,utmParams:(g=t==null?void 0:t.utmParams)!=null?g:{},deviceClass:n?te(n):"desktop",trafficSource:i?ne(i,t==null?void 0:t.appOrigin):"direct",referrerDomain:re(i),timeOfDay:oe(d),dayOfWeek:(m=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?m:"sun",automation:(t==null?void 0:t.webdriver)===!0||ee(n)}}var $=require("@sentientui/policy");function se(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 W(e){let t=se(e);return(0,$.slotResultFor)(t,(0,$.slotBaselineArm)(t))}function Ke(e){let t={};for(let n of e)t[n.id]=W(n);return t}function de(e){return typeof e=="string"?e:(0,$.canonicalArm)(e)}var K="_snt_snap:",wt=["low","medium","high"];function ue(e){try{let t=localStorage.getItem(K+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"||!wt.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 j(e,t){try{localStorage.setItem(K+e,JSON.stringify(t))}catch(n){}}function Ge(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(K+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 fe=require("@sentientui/policy");var pe="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",xe="[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,ge=!1;function bt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function $e(e){var s;let t=le({ssrSessionId:e.ssrSessionId}),n=(s=t.getSessionId())!=null?s:"local",i=bt(),d=import("@sentientui/core/local").then(o=>{let l=o;return l.LOCAL_ENGINE_AVAILABLE?(Be||(Be=!0,console.info(xe)),l):(ge||(ge=!0,console.error(pe)),null)}).catch(()=>(ge||(ge=!0,console.error(pe)),null)),r=null;function c(o){let l=document.documentElement;l.dataset.sentientPersona===void 0&&(l.dataset.sentientPersona=o.persona,l.dataset.sentientConfidence=(0,fe.confidenceBand)(o.confidence))}return{isLocal:!0,async decide(o){var m,h,S;let l=await d;if(!l)return null;let g=l.createLocalEngine({sessionId:n,forcedPersona:i}).decide(o);return r=G(w({},g),{layoutOrder:(h=(m=g.layoutOrder)!=null?m:r==null?void 0:r.layoutOrder)!=null?h:null,slots:w(w({},(S=r==null?void 0:r.slots)!=null?S:{}),g.slots)}),j(e.apiKey||"local",{v:1,persona:r.persona,band:(0,fe.confidenceBand)(r.confidence),slots:r.slots,layoutOrder:r.layoutOrder,savedAt:Date.now()}),c(g),g},getSlotResult(o){var l,g,m;return(m=(g=r==null?void 0:r.slots[o])!=null?g:(l=e.initialSlots)==null?void 0:l[o])!=null?m:null},getPersona(){return r?{persona:r.persona,confidence:r.confidence,band:(0,fe.confidenceBand)(r.confidence)}:null},async assign(o,l){var h;let g=await d;return!g||!l||l.length===0?l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null:{variantId:(h=g.createLocalEngine({sessionId:n,forcedPersona:i}).decide({components:[{id:o,variantIds:l}]}).assignments[o])!=null?h:l[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function We(e,t,n){var d;let i=[];{let s=!1,o=[],l=()=>{if(s)return;let g=Date.now();for(o.push(g);o.length>0&&g-o[0]>500;)o.shift();o.length>=3&&(s=!0,e("rage_click"))};t.addEventListener("click",l),i.push(()=>t.removeEventListener("click",l))}{let r=!1,c=s=>{if(r||!(s.target instanceof Node)||!t.contains(s.target)&&t!==s.target)return;r=!0;let o=typeof window!="undefined"?window.getSelection():null,l=o?o.toString().length:0;e("text_copy",{selectionLength:l})};document.addEventListener("copy",c),i.push(()=>document.removeEventListener("copy",c))}{let r=!1,c=!1,s=null,o=()=>{s!==null&&(clearTimeout(s),s=null)},l=()=>{r||!c||(o(),s=setTimeout(()=>{!r&&c&&(r=!0,e("scroll_hesitation"))},3e3))},g=()=>{o(),l()},m=S=>{for(let b of S)c=b.intersectionRatio>.3,c?l():o()};typeof process!="undefined"&&((d=process.env)==null?void 0:d.NODE_ENV)!=="production"&&(window.__lastIOCallback=m);let h=new IntersectionObserver(m,{threshold:[.3]});h.observe(t),window.addEventListener("scroll",g,{passive:!0}),i.push(()=>{h.disconnect(),window.removeEventListener("scroll",g),o()})}{let r=!1,c=n!=null?n:Date.now(),s=()=>{if(r||document.visibilityState!=="hidden")return;let o=Date.now()-c;o<15e3&&(r=!0,e("tab_loss",{timeOnPage:o}))};document.addEventListener("visibilitychange",s),i.push(()=>document.removeEventListener("visibilitychange",s))}return()=>{for(let r of i)r()}}var je="https://api.sentient-ui.com/v1/events",F=new Map,Fe=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 ie={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 Et(){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 Je(e){return e.replace(/\/events\/?$/,"")}function Re(){return[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 xt(e){if(typeof window=="undefined")return;let t=e!=null?e:Fe;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=F.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:i,upgrade:d}=n;if(!d||i.respectDoNotTrack!==!1&&Re())return;let r=Qe(G(w({},i),{consent:!0}));d(r),F.set(t,{config:G(w({},i),{consent:!0}),upgrade:null})}function It(e){var c;let t=Je((c=e.ingestUrl)!=null?c:je),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},i={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(s,o,l){try{let g=new URLSearchParams({componentId:s});for(let S of o!=null?o:[])g.append("variantIds[]",S);let m=await fetch(`${t}/winner?${g.toString()}`,{headers:n});return m.ok?{variantId:(await m.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:s=>i.track(s),goal:(s,o,l,g)=>i.goal(s,o,l,g),componentGoal:(s,o,l)=>i.componentGoal(s,o,l),identify:s=>i.identify(s),getAssignment:(s,o)=>i.getAssignment(s,o),assign:(s,o,l,g)=>i.assign(s,o,l,g),decide:s=>i.decide(s),getSlotResult:s=>i.getSlotResult(s),getPersona:()=>i.getPersona(),fetchWeights:()=>i.fetchWeights(),getGraph:()=>i.getGraph(),dispose:()=>i.dispose(),destroy:()=>i.destroy()};function r(s){i=s}return{proxy:d,setInner:r}}function Qe(e){var Y,z,H,V,X,f,y,_,k;if(typeof window=="undefined")return ie;Fe=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return F.set(e.apiKey||"local",{config:e,upgrade:null}),$e(e);let n=e.respectDoNotTrack!==!1&&Re();if(e.consent===!1||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."),ie;let{proxy:a,setInner:u}=It(e);return F.set(e.apiKey,{config:e,upgrade:n?null:u}),a}return F.set(e.apiKey,{config:e,upgrade:null}),ie}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."),ie;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),ie;let i=(Y=e.ingestUrl)!=null?Y:je,d=Date.now(),r=le({ssrSessionId:e.ssrSessionId}),c=Me(),s=Le({ingestUrl:i,apiKey:e.apiKey}),o=Je(i),l={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=te((z=navigator.userAgent)!=null?z:""),m=typeof window!="undefined"?window.location.origin:void 0,h=ne((H=document.referrer)!=null?H:"",m),S=(V=e.sessionSegment)!=null?V:`${g}:${h}`,b=new Map,v=new Map,E=null,J=a=>{for(let u of a)v.has(u.id)||v.set(u.id,W(u))};if(e.initialSlots)for(let[a,u]of Object.entries(e.initialSlots))v.set(a,u);let L=ue(e.apiKey);if(L)for(let[a,u]of Object.entries(L.slots))v.has(a)||v.set(a,u);let ae={low:.15,medium:.5,high:.85};if(e.initialPersona)E=w({},e.initialPersona);else{let a=document.documentElement.dataset;a.sentientPersona?E={persona:a.sentientPersona,confidence:(f=ae[(X=a.sentientConfidence)!=null?X:"low"])!=null?f:.15}:L&&(E={persona:L.persona,confidence:(y=ae[L.band])!=null?y:.15})}if(e.initialAssignments)for(let[a,u]of Object.entries(e.initialAssignments))c.set(a,S,{variantId:u,assignedAt:Date.now(),segment:S,confidence:1});let x=Promise.resolve(),Q=r.getSessionId();if(Q){let a=re((_=document.referrer)!=null?_:""),u=w(w({sessionId:Q,deviceClass:g,trafficSource:h,referrerDomain:a,utmParams:Et(),timeOfDay:oe(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:r.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||ee((k=navigator.userAgent)!=null?k:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{x=fetch(`${o}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(u),headers:l}).then(p=>{p.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(p){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:s});let N={goal(a,u={},p=1,A=0){let I=r.getSessionId();if(!I)return;let R=Ie();x.then(()=>{fetch(`${o}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:I,name:a,metadata:u,weight:p,stepIndex:A,goalId:R}),headers:l}).catch(()=>{})})},componentGoal(a,u,p){var D,P,O;let A=r.getSessionId();if(!A)return;let I=c.get(a,S),R=I?null:(D=v.get(a))!=null?D:null;if(!I&&R===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 M=I?I.variantId:de(R),T={id:Ie(),sessionId:A,projectId:e.apiKey,componentId:a,variantId:M,eventType:"goal_achieved",goalType:u,payload:w({reward:(P=p==null?void 0:p.reward)!=null?P:1},(O=p==null?void 0:p.metadata)!=null?O:{}),timestamp:Date.now(),timeInSession:Date.now()-d};e.debug&&console.log("[sentient] componentGoal",T),x.then(()=>s.push(T))},identify(a){let u=r.getSessionId();u&&x.then(()=>{fetch(`${o}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:u,userId:a,ephemeral:r.isEphemeral()}),headers:l}).catch(()=>{})})},track(a){let u=r.getSessionId();if(!u)return;let p=G(w({},a),{id:Ie(),sessionId:u,timestamp:Date.now(),timeInSession:Date.now()-d});e.debug&&console.log("[sentient] track",p),x.then(()=>s.push(p))},getAssignment(a,u){return c.get(a,u)},async assign(a,u,p,A){let I=r.getSessionId();if(!I)return null;let R=c.get(a,S);if(R&&(u!=null&&u.length||R.content!==void 0))return{variantId:R.variantId,assignmentTtlMs:0,content:R.content};let M=b.get(a);if(M)return M;let T=(async()=>{await x;try{let D={sessionId:I,componentId:a,variantIds:u};A!==void 0?D.agentDataByVariant=A:p!==void 0&&(D.agentData=p);let P=await fetch(`${o}/assign`,{method:"POST",body:JSON.stringify(D),headers:l});if(!P.ok)return null;let O=await P.json();return c.set(a,S,{variantId:O.variantId,assignedAt:Date.now(),segment:S,confidence:1,content:O.content}),O}catch(D){return null}finally{b.delete(a)}})();return b.set(a,T),T},async decide(a){var A,I,R,M,T,D,P,O,ke,Ae;let u=r.getSessionId();if(!u)return null;let p=(A=a.slots)!=null?A:[];await x;try{let q={sessionId:u};a.sections&&a.sections.length>0&&(q.sections=a.sections.map(C=>({id:C}))),q.components=(I=a.components)!=null?I:[],p.length>0&&(q.slots=p.map(se));let De=await fetch(`${o}/decide`,{method:"POST",body:JSON.stringify(q),headers:l});if(!De.ok)return J(p),null;let U=await De.json(),me={};for(let C of p)me[C.id]=(M=(R=U.slots)==null?void 0:R[C.id])!=null?M:W(C);for(let[C,ye]of Object.entries(me))v.set(C,ye);E={persona:(T=U.persona)!=null?T:"unknown",confidence:(D=U.confidence)!=null?D:0};for(let[C,ye]of Object.entries((P=U.assignments)!=null?P:{}))c.set(C,S,{variantId:ye,assignedAt:Date.now(),segment:S,confidence:1});return j(e.apiKey,{v:1,persona:E.persona,band:(0,_e.confidenceBand)(E.confidence),slots:Object.fromEntries(v),layoutOrder:(O=U.layoutOrder)!=null?O:null,savedAt:Date.now()}),{layoutOrder:(ke=U.layoutOrder)!=null?ke:null,assignments:(Ae=U.assignments)!=null?Ae:{},slots:me,persona:E.persona,confidence:E.confidence}}catch(q){return J(p),null}},getSlotResult(a){var u;return(u=v.get(a))!=null?u:null},getPersona(){return E?{persona:E.persona,confidence:E.confidence,band:(0,_e.confidenceBand)(E.confidence)}:null},async fetchWeights(){var a;try{let u=await fetch(`${o}/weights`,{headers:l});return u.ok?(a=(await u.json()).components)!=null?a:[]:[]}catch(u){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){s.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){s.destroy(),r.destroy();try{localStorage.removeItem(K+e.apiKey),localStorage.removeItem(he(e.apiKey))}catch(a){}e.debug&&console.log("[sentient] destroyed")}};if(F.set(e.apiKey,{config:e,upgrade:null}),e.debug){let a=window;a.__sentient&&(a.__sentient.client=N)}return N}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 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});
|
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-
|
|
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};
|
package/package.json
CHANGED
package/dist/chunk-G6ZN7Q63.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as re,d as ie,e as ae,f as le,g as ce,j as de,k as Z,m as ue}from"./chunk-SVYHTU5Z.mjs";import{a as A,b as K}from"./chunk-HGGX55FR.mjs";var Le="_snt_uid";var G="_snt_uid";function Ne(){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 Me(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Ue(e,t,r){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${r}; SameSite=strict; path=/`}catch(d){}}function Ke(e){try{return localStorage.getItem(e)}catch(t){return null}}function Ge(e,t){try{return localStorage.setItem(e,t),!0}catch(r){return!1}}function $e(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function Be(e,t){try{return sessionStorage.setItem(e,t),!0}catch(r){return!1}}function We(e){try{sessionStorage.removeItem(e)}catch(t){}}function je(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 Fe(e){try{localStorage.removeItem(e)}catch(t){}}function Je(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Qe={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ee(e){var a,g,m,h,S,E;if(typeof window=="undefined")return Qe;let t=(a=e==null?void 0:e.cookieName)!=null?a:Le,d=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,u=(E=(S=(h=(m=Me(t))!=null?m:Ke(G))!=null?h:$e(G))!=null?S:e==null?void 0:e.ssrSessionId)!=null?E:Ne();Ue(t,u,d);let n=Ge(G,u),c=je(t),o=n?!1:Be(G,u),s=!n&&!c&&!o;return{getSessionId:()=>u,isEphemeral:()=>s,destroy:()=>{u=null,Je(t),Fe(G),We(G)}}}function pe(e){return`_snt_retry_${e.slice(0,12)}`}var Ye={push:()=>{},flush:()=>{},destroy:()=>{}};function Ve(e,t){try{let r=localStorage.getItem(t);if(!r)return[];let d=JSON.parse(r);return Array.isArray(d)?(localStorage.removeItem(t),d.slice(-e)):[]}catch(r){return[]}}function ge(e,t,r){try{let u=[...(()=>{try{let n=localStorage.getItem(r);if(!n)return[];let c=JSON.parse(n);return Array.isArray(c)?c:[]}catch(n){return[]}})(),...e].slice(-t);localStorage.setItem(r,JSON.stringify(u))}catch(d){}}function Ie(e){var Q,Y,V;if(typeof window=="undefined")return Ye;let t=(Q=e.flushIntervalMs)!=null?Q:5e3,r=(Y=e.maxBatchSize)!=null?Y:20,d=(V=e.maxRetrySize)!=null?V:100,u=e.ingestUrl,n=e.apiKey,c=pe(n),o=[],s=new Set,a=[],g=p=>{for(let y of p)m.delete(y),!s.has(y)&&(s.add(y),a.push(y));for(;a.length>500;){let y=a.shift();y&&s.delete(y)}},m=new Set,h=p=>{s.has(p.id)||m.has(p.id)||(m.add(p.id),o.push(p))},S=Ve(d,c);for(let p of S)h(p);let E=0,v=0,w=p=>{if(p.length===0)return;let y=JSON.stringify(p),_=p.map(l=>l.id),k;try{k=fetch(u,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})}catch(l){ge(p,d,c);for(let f of _)m.delete(f);v++,E=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6));return}let i=l=>{if(l.ok||l.status>=400&&l.status<500&&l.status!==429){g(_),v=0,E=0;return}ge(p,d,c);for(let f of _)m.delete(f);v++,E=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};k instanceof Promise?k.then(i).catch(()=>{ge(p,d,c);for(let l of _)m.delete(l);v++,E=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):i(k)},W=typeof TextEncoder!="undefined"?new TextEncoder:null,L=p=>W?W.encode(p).length:p.length,q=p=>{let y=[],_=2;for(let k of p){let i=L(JSON.stringify(k))+1;if(y.length>0&&_+i>57344||y.length>=r)break;y.push(k),_+=i}return y},b=()=>{try{if(Date.now()<E)return;for(;o.length>0;){let p=o.filter(_=>!s.has(_.id));if(o.length=0,p.length===0)break;let y=q(p);if(y.length===0)break;y.length<p.length&&o.push(...p.slice(y.length)),w(y)}}catch(p){}},j=!0,N=null;N=setInterval(()=>{j&&b()},t);let F=()=>{document.visibilityState==="hidden"&&b()},J=()=>{b()};return document.addEventListener("visibilitychange",F),window.addEventListener("beforeunload",J),{push(p){h(p),o.length>=r&&b()},flush:b,destroy(){j=!1,N!==null&&(clearInterval(N),N=null),document.removeEventListener("visibilitychange",F),window.removeEventListener("beforeunload",J),b()}}}var me="_snt_asgn_";function te(e,t){return`${e}:${t}`}function ze(e,t){return`${me}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function _e(e){let t=e.slice(me.length),r=t.indexOf(":");if(r<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,r)),segment:decodeURIComponent(t.slice(r+1))}}catch(d){return null}}function fe(){try{let e=[];for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r!=null&&r.startsWith(me)&&e.push(r)}return e}catch(e){return[]}}function xe(e=18e5){let t=new Map,r=u=>u.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let u of fe())try{let n=localStorage.getItem(u);if(!n)continue;let c=JSON.parse(n);if(r(c)){localStorage.removeItem(u);continue}let o=_e(u);if(!o)continue;t.set(te(o.componentId,o.segment),c)}catch(n){}})(),{get(u,n){let c=t.get(te(u,n));return c?r(c)?(t.delete(te(u,n)),null):c:null},set(u,n,c){let o=te(u,n);t.set(o,c);try{localStorage.setItem(ze(u,n),JSON.stringify(c))}catch(s){}},invalidate(u){let n=`${u}:`;for(let c of[...t.keys()])c.startsWith(n)&&t.delete(c);for(let c of fe()){let o=_e(c);if((o==null?void 0:o.componentId)===u)try{localStorage.removeItem(c)}catch(s){}}},clear(){t.clear();for(let u of fe())try{localStorage.removeItem(u)}catch(n){}}}}var $="_snt_snap:",He=["low","medium","high"];function ye(e){try{let t=localStorage.getItem($+e);if(!t)return null;let r=JSON.parse(t);return!r||typeof r!="object"||r.v!==1||typeof r.persona!="string"||typeof r.band!="string"||!He.includes(r.band)||typeof r.slots!="object"||r.slots===null||Array.isArray(r.slots)||!(r.layoutOrder===null||Array.isArray(r.layoutOrder))||typeof r.savedAt!="number"?null:r}catch(t){return null}}function H(e,t){try{localStorage.setItem($+e,JSON.stringify(t))}catch(r){}}function Xe(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){}})();'}import{confidenceBand as Oe}from"@sentientui/policy";import{confidenceBand as Se}from"@sentientui/policy";var he="[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,ne=!1;function qe(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Re(e){var o;let t=ee({ssrSessionId:e.ssrSessionId}),r=(o=t.getSessionId())!=null?o:"local",d=qe(),u=import("@sentientui/core/local").then(s=>{let a=s;return a.LOCAL_ENGINE_AVAILABLE?(Ae||(Ae=!0,console.info(ke)),a):(ne||(ne=!0,console.error(he)),null)}).catch(()=>(ne||(ne=!0,console.error(he)),null)),n=null;function c(s){let a=document.documentElement;a.dataset.sentientPersona===void 0&&(a.dataset.sentientPersona=s.persona,a.dataset.sentientConfidence=Se(s.confidence))}return{isLocal:!0,async decide(s){var m,h,S;let a=await u;if(!a)return null;let g=a.createLocalEngine({sessionId:r,forcedPersona:d}).decide(s);return n=K(A({},g),{layoutOrder:(h=(m=g.layoutOrder)!=null?m:n==null?void 0:n.layoutOrder)!=null?h:null,slots:A(A({},(S=n==null?void 0:n.slots)!=null?S:{}),g.slots)}),H(e.apiKey||"local",{v:1,persona:n.persona,band:Se(n.confidence),slots:n.slots,layoutOrder:n.layoutOrder,savedAt:Date.now()}),c(g),g},getSlotResult(s){var a,g,m;return(m=(g=n==null?void 0:n.slots[s])!=null?g:(a=e.initialSlots)==null?void 0:a[s])!=null?m:null},getPersona(){return n?{persona:n.persona,confidence:n.confidence,band:Se(n.confidence)}:null},async assign(s,a){var h;let g=await u;return!g||!a||a.length===0?a!=null&&a[0]?{variantId:a[0],assignmentTtlMs:0}:null:{variantId:(h=g.createLocalEngine({sessionId:r,forcedPersona:d}).decide({components:[{id:s,variantIds:a}]}).assignments[s])!=null?h:a[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function Ze(e,t,r){var u;let d=[];{let o=!1,s=[],a=()=>{if(o)return;let g=Date.now();for(s.push(g);s.length>0&&g-s[0]>500;)s.shift();s.length>=3&&(o=!0,e("rage_click"))};t.addEventListener("click",a),d.push(()=>t.removeEventListener("click",a))}{let n=!1,c=o=>{if(n||!(o.target instanceof Node)||!t.contains(o.target)&&t!==o.target)return;n=!0;let s=typeof window!="undefined"?window.getSelection():null,a=s?s.toString().length:0;e("text_copy",{selectionLength:a})};document.addEventListener("copy",c),d.push(()=>document.removeEventListener("copy",c))}{let n=!1,c=!1,o=null,s=()=>{o!==null&&(clearTimeout(o),o=null)},a=()=>{n||!c||(s(),o=setTimeout(()=>{!n&&c&&(n=!0,e("scroll_hesitation"))},3e3))},g=()=>{s(),a()},m=S=>{for(let E of S)c=E.intersectionRatio>.3,c?a():s()};typeof process!="undefined"&&((u=process.env)==null?void 0:u.NODE_ENV)!=="production"&&(window.__lastIOCallback=m);let h=new IntersectionObserver(m,{threshold:[.3]});h.observe(t),window.addEventListener("scroll",g,{passive:!0}),d.push(()=>{h.disconnect(),window.removeEventListener("scroll",g),s()})}{let n=!1,c=r!=null?r:Date.now(),o=()=>{if(n||document.visibilityState!=="hidden")return;let s=Date.now()-c;s<15e3&&(n=!0,e("tab_loss",{timeOnPage:s}))};document.addEventListener("visibilitychange",o),d.push(()=>document.removeEventListener("visibilitychange",o))}return()=>{for(let n of d)n()}}var De="https://api.sentient-ui.com/v1/events",B=new Map,Te=null;function ve(){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 X={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 et(){try{let e={},t=new URLSearchParams(window.location.search);for(let[r,d]of t)r.startsWith("utm_")&&(e[r]=d);return e}catch(e){return{}}}function Ce(e){return e.replace(/\/events\/?$/,"")}function Pe(){return[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 xt(e){if(typeof window=="undefined")return;let t=e!=null?e:Te;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let r=B.get(t);if(!r){console.warn("[sentient] grantConsent() called before init()");return}let{config:d,upgrade:u}=r;if(!u||d.respectDoNotTrack!==!1&&Pe())return;let n=nt(K(A({},d),{consent:!0}));u(n),B.set(t,{config:K(A({},d),{consent:!0}),upgrade:null})}function tt(e){var c;let t=Ce((c=e.ingestUrl)!=null?c:De),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(o,s,a){try{let g=new URLSearchParams({componentId:o});for(let S of s!=null?s:[])g.append("variantIds[]",S);let m=await fetch(`${t}/winner?${g.toString()}`,{headers:r});return m.ok?{variantId:(await m.json()).variantId,assignmentTtlMs:0}:s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}catch(g){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:()=>{}},u={track:o=>d.track(o),goal:(o,s,a,g)=>d.goal(o,s,a,g),componentGoal:(o,s,a)=>d.componentGoal(o,s,a),identify:o=>d.identify(o),getAssignment:(o,s)=>d.getAssignment(o,s),assign:(o,s,a,g)=>d.assign(o,s,a,g),decide:o=>d.decide(o),getSlotResult:o=>d.getSlotResult(o),getPersona:()=>d.getPersona(),fetchWeights:()=>d.fetchWeights(),getGraph:()=>d.getGraph(),dispose:()=>d.dispose(),destroy:()=>d.destroy()};function n(o){d=o}return{proxy:u,setInner:n}}function nt(e){var F,J,Q,Y,V,p,y,_,k;if(typeof window=="undefined")return X;Te=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return B.set(e.apiKey||"local",{config:e,upgrade:null}),Re(e);let r=e.respectDoNotTrack!==!1&&Pe();if(e.consent===!1||r){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."),X;let{proxy:i,setInner:l}=tt(e);return B.set(e.apiKey,{config:e,upgrade:r?null:l}),i}return B.set(e.apiKey,{config:e,upgrade:null}),X}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."),X;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),X;let d=(F=e.ingestUrl)!=null?F:De,u=Date.now(),n=ee({ssrSessionId:e.ssrSessionId}),c=xe(),o=Ie({ingestUrl:d,apiKey:e.apiKey}),s=Ce(d),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=ie((J=navigator.userAgent)!=null?J:""),m=typeof window!="undefined"?window.location.origin:void 0,h=ae((Q=document.referrer)!=null?Q:"",m),S=(Y=e.sessionSegment)!=null?Y:`${g}:${h}`,E=new Map,v=new Map,w=null,W=i=>{for(let l of i)v.has(l.id)||v.set(l.id,Z(l))};if(e.initialSlots)for(let[i,l]of Object.entries(e.initialSlots))v.set(i,l);let L=ye(e.apiKey);if(L)for(let[i,l]of Object.entries(L.slots))v.has(i)||v.set(i,l);let q={low:.15,medium:.5,high:.85};if(e.initialPersona)w=A({},e.initialPersona);else{let i=document.documentElement.dataset;i.sentientPersona?w={persona:i.sentientPersona,confidence:(p=q[(V=i.sentientConfidence)!=null?V:"low"])!=null?p:.15}:L&&(w={persona:L.persona,confidence:(y=q[L.band])!=null?y:.15})}if(e.initialAssignments)for(let[i,l]of Object.entries(e.initialAssignments))c.set(i,S,{variantId:l,assignedAt:Date.now(),segment:S,confidence:1});let b=Promise.resolve(),j=n.getSessionId();if(j){let i=le((_=document.referrer)!=null?_:""),l=A(A({sessionId:j,deviceClass:g,trafficSource:h,referrerDomain:i,utmParams:et(),timeOfDay:ce(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:n.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||re((k=navigator.userAgent)!=null?k:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{b=fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(l),headers:a}).then(f=>{f.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(f){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:o});let N={goal(i,l={},f=1,R=0){let I=n.getSessionId();if(!I)return;let x=ve();b.then(()=>{fetch(`${s}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:I,name:i,metadata:l,weight:f,stepIndex:R,goalId:x}),headers:a}).catch(()=>{})})},componentGoal(i,l,f){var O,P,D;let R=n.getSessionId();if(!R)return;let I=c.get(i,S),x=I?null:(O=v.get(i))!=null?O:null;if(!I&&x===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 M=I?I.variantId:ue(x),C={id:ve(),sessionId:R,projectId:e.apiKey,componentId:i,variantId:M,eventType:"goal_achieved",goalType:l,payload:A({reward:(P=f==null?void 0:f.reward)!=null?P:1},(D=f==null?void 0:f.metadata)!=null?D:{}),timestamp:Date.now(),timeInSession:Date.now()-u};e.debug&&console.log("[sentient] componentGoal",C),b.then(()=>o.push(C))},identify(i){let l=n.getSessionId();l&&b.then(()=>{fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:l,userId:i,ephemeral:n.isEphemeral()}),headers:a}).catch(()=>{})})},track(i){let l=n.getSessionId();if(!l)return;let f=K(A({},i),{id:ve(),sessionId:l,timestamp:Date.now(),timeInSession:Date.now()-u});e.debug&&console.log("[sentient] track",f),b.then(()=>o.push(f))},getAssignment(i,l){return c.get(i,l)},async assign(i,l,f,R){let I=n.getSessionId();if(!I)return null;let x=c.get(i,S);if(x&&(l!=null&&l.length||x.content!==void 0))return{variantId:x.variantId,assignmentTtlMs:0,content:x.content};let M=E.get(i);if(M)return M;let C=(async()=>{await b;try{let O={sessionId:I,componentId:i,variantIds:l};R!==void 0?O.agentDataByVariant=R:f!==void 0&&(O.agentData=f);let P=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify(O),headers:a});if(!P.ok)return null;let D=await P.json();return c.set(i,S,{variantId:D.variantId,assignedAt:Date.now(),segment:S,confidence:1,content:D.content}),D}catch(O){return null}finally{E.delete(i)}})();return E.set(i,C),C},async decide(i){var R,I,x,M,C,O,P,D,Ee,we;let l=n.getSessionId();if(!l)return null;let f=(R=i.slots)!=null?R:[];await b;try{let z={sessionId:l};i.sections&&i.sections.length>0&&(z.sections=i.sections.map(T=>({id:T}))),z.components=(I=i.components)!=null?I:[],f.length>0&&(z.slots=f.map(de));let be=await fetch(`${s}/decide`,{method:"POST",body:JSON.stringify(z),headers:a});if(!be.ok)return W(f),null;let U=await be.json(),se={};for(let T of f)se[T.id]=(M=(x=U.slots)==null?void 0:x[T.id])!=null?M:Z(T);for(let[T,oe]of Object.entries(se))v.set(T,oe);w={persona:(C=U.persona)!=null?C:"unknown",confidence:(O=U.confidence)!=null?O:0};for(let[T,oe]of Object.entries((P=U.assignments)!=null?P:{}))c.set(T,S,{variantId:oe,assignedAt:Date.now(),segment:S,confidence:1});return H(e.apiKey,{v:1,persona:w.persona,band:Oe(w.confidence),slots:Object.fromEntries(v),layoutOrder:(D=U.layoutOrder)!=null?D:null,savedAt:Date.now()}),{layoutOrder:(Ee=U.layoutOrder)!=null?Ee:null,assignments:(we=U.assignments)!=null?we:{},slots:se,persona:w.persona,confidence:w.confidence}}catch(z){return W(f),null}},getSlotResult(i){var l;return(l=v.get(i))!=null?l:null},getPersona(){return w?{persona:w.persona,confidence:w.confidence,band:Oe(w.confidence)}:null},async fetchWeights(){var i;try{let l=await fetch(`${s}/weights`,{headers:a});return l.ok?(i=(await l.json()).components)!=null?i:[]:[]}catch(l){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){o.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){o.destroy(),n.destroy();try{localStorage.removeItem($+e.apiKey),localStorage.removeItem(pe(e.apiKey))}catch(i){}e.debug&&console.log("[sentient] destroyed")}};if(B.set(e.apiKey,{config:e,upgrade:null}),e.debug){let i=window;i.__sentient&&(i.__sentient.client=N)}return N}export{$ as a,ye as b,H as c,Xe as d,he as e,ke as f,Ze as g,Pe as h,xt as i,nt as j};
|