@sentientui/core 0.11.2 → 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/README.md CHANGED
@@ -33,7 +33,7 @@ client.componentGoal('hero_headline', 'trial_started');
33
33
  client.goal('trial_started', { plan: 'pro' });
34
34
  ```
35
35
 
36
- `init()` returns a no-op client during SSR (`typeof window === 'undefined'`), when `consent` is `false`, or when `apiKey` does not start with `pk_`. The hosted ingest URL (`https://api.sentient-ui.com/v1/events`) is built in — no URL configuration required.
36
+ `init()` returns a no-op client during SSR (`typeof window === 'undefined'`) or when `consent` is `false`. When `apiKey` does not start with `pk_`, it returns a no-op client in production builds, or the keyless local-mode client in development builds (see "Keyless local mode" below). The hosted ingest URL (`https://api.sentient-ui.com/v1/events`) is built in — no URL configuration required.
37
37
 
38
38
  ## API
39
39
 
@@ -44,7 +44,7 @@ client.goal('trial_started', { plan: 'pro' });
44
44
  | `apiKey` | `string` | Public API key (`pk_…`) from the SentientUI dashboard. |
45
45
  | `context` | `'landing' \| 'ecommerce' \| 'saas' \| 'marketplace'` | Local label only — echoed in `debug` logs, never sent to the server. Analytics grouping comes from the project's context type configured in the dashboard. |
46
46
  | `consent` | `boolean` *(default `true`)* | When `false`, returns a no-op client (no cookies, no events). **The default is `true`** — for GDPR-style opt-in, pass `false` until your banner is accepted (see `preConsentBehavior`). |
47
- | `preConsentBehavior` | `'defaults' \| 'statistical_winner'` | What to render while `consent` is `false`: site defaults, or the read-only statistical winner via `/v1/winner` (no session, no events). |
47
+ | `preConsentBehavior` | `'control' \| 'statistical_winner'` | What to render while `consent` is `false`: `'control'` (the default — shows `variantIds[0]`), or the read-only statistical winner via `/v1/winner` (no session, no events). |
48
48
  | `respectDoNotTrack` | `boolean` *(default `true`)* | Honors the browser DNT signal — overrides `consent: true` and blocks `grantConsent()`. |
49
49
  | `initialAssignments` | `Record<string, string>` | SSR-preloaded assignments. Seeds the cache so `assign()` returns without a network call for listed code variants. (Managed-text components still fetch once when the seed carries no content.) |
50
50
  | `sessionSegment` | `string` | Segment from SSR (`device:source`). Must match the value used in `preloadAssignments`. |
@@ -106,9 +106,13 @@ Synchronously returns the cached assignment, or `null` if not yet assigned. Use
106
106
 
107
107
  Returns the current `GraphSnapshot` (page nodes captured by the optional graph scanner — see "Optional: graph mode" below). Permanently returns an empty snapshot on the lean client; graph mode must be enabled at `init` time.
108
108
 
109
+ ### `client.dispose()`
110
+
111
+ Routine cleanup: stops the flush timer and unload listeners (with a final flush) but **keeps the visitor identity, decision snapshot, and retry bucket**. Use this when a component or provider that owns the client unmounts or re-initializes — the visitor must survive it. `<AdaptiveProvider>` calls it for you on cleanup.
112
+
109
113
  ### `client.destroy()`
110
114
 
111
- Flushes the event queue and **deletes the visitor identity** — the 365-day `_snt_uid` cookie and all local storage. This is a consent-revocation/forget-me teardown, not a page-unload cleanup: calling it on every unload makes each visit a brand-new visitor and defeats "Visit 1 learns, Visit 2 converts". For unload, do nothing — the SDK already flushes on `visibilitychange`/`beforeunload` automatically.
115
+ Everything `dispose()` does, plus **deletion of the visitor identity** — the 365-day `_snt_uid` cookie, local/session storage keys, the decision snapshot, and the persisted retry bucket. This is a consent-revocation/forget-me teardown, not a page-unload cleanup: calling it on every unload makes each visit a brand-new visitor and defeats "Visit 1 learns, Visit 2 converts". For unload, do nothing — the SDK already flushes on `visibilitychange`/`beforeunload` automatically.
112
116
 
113
117
  ## SSR helpers
114
118
 
@@ -204,7 +208,7 @@ import { init } from '@sentientui/core/graph';
204
208
  const client = init({ apiKey: 'pk_…', context: 'saas', graph: true });
205
209
  ```
206
210
 
207
- A client created by the lean `init` can never activate graph mode later (`getGraph()` stays empty). The lean bundle is ~8 KB gzip (CI budget: 10 KB); graph adds roughly another 8 KB.
211
+ A client created by the lean `init` can never activate graph mode later (`getGraph()` stays empty). The lean bundle is ~8 KB gzip (CI budget: 10 KB); graph adds ~3–4 KB gzip on top of the lean bundle (combined CI budget: 16 KB).
208
212
 
209
213
  > **Using `@sentientui/react`?** Don't import this entry yourself — pass the
210
214
  > `enableGraph` prop to `AdaptiveProvider` / `AdaptiveRoot` instead. The provider
@@ -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};
@@ -1 +1 @@
1
- "use strict";var Qe=Object.create;var Z=Object.defineProperty,Ve=Object.defineProperties,Ye=Object.getOwnPropertyDescriptor,qe=Object.getOwnPropertyDescriptors,Xe=Object.getOwnPropertyNames,Re=Object.getOwnPropertySymbols,Ze=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var Oe=(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={}))De.call(t,n)&&Oe(e,n,t[n]);if(Re)for(var n of Re(t))et.call(t,n)&&Oe(e,n,t[n]);return e},$=(e,t)=>Ve(e,qe(t));var tt=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},ke=(e,t,n,d)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of Xe(t))!De.call(e,c)&&c!==n&&Z(e,c,{get:()=>t[c],enumerable:!(d=Ye(t,c))||d.enumerable});return e};var nt=(e,t,n)=>(n=e!=null?Qe(Ze(e)):{},ke(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e)),ot=e=>ke(Z({},"__esModule",{value:!0}),e);var zt={};tt(zt,{deriveSessionSegment:()=>he,detectDeviceClass:()=>B,detectTimeOfDay:()=>F,detectTrafficSource:()=>j,init:()=>Jt,referrerDomainFromReferer:()=>W});module.exports=ot(zt);var rt="_snt_uid";var K="_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(d){}}function ct(e){try{return localStorage.getItem(e)}catch(t){return null}}function dt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function lt(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 pt(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 mt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var ht={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function oe(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:rt,d=((u=e==null?void 0:e.cookieTTLDays)!=null?u:365)*24*60*60,c=(S=(p=(m=(f=it(t))!=null?f:ct(K))!=null?m:lt(K))!=null?p:e==null?void 0:e.ssrSessionId)!=null?S:st();at(t,c,d);let o=dt(K,c),i=pt(t),a=o?!1:ut(K,c),s=!o&&!i&&!a;return{getSessionId:()=>c,isEphemeral:()=>s,destroy:()=>{c=null,mt(t),ft(K),gt(K)}}}var yt={push:()=>{},flush:()=>{},destroy:()=>{}};function St(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 pe(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 Ne(e){var V,Y,q;if(typeof window=="undefined")return yt;let t=(V=e.flushIntervalMs)!=null?V:5e3,n=(Y=e.maxBatchSize)!=null?Y:20,d=(q=e.maxRetrySize)!=null?q:100,c=e.ingestUrl,o=e.apiKey,i=`_snt_retry_${o.slice(0,12)}`,a=[],s=new Set,r=[],u=h=>{for(let w of h)f.delete(w),!s.has(w)&&(s.add(w),r.push(w));for(;r.length>500;){let w=r.shift();w&&s.delete(w)}},f=new Set,m=h=>{s.has(h.id)||f.has(h.id)||(f.add(h.id),a.push(h))},p=St(d,i);for(let h of p)m(h);let S=0,v=0,E=h=>{if(h.length===0)return;let w=JSON.stringify(h),x=h.map(g=>g.id),_;try{_=fetch(c,{method:"POST",keepalive:!0,body:w,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}})}catch(g){pe(h,d,i);for(let y of x)f.delete(y);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}pe(h,d,i);for(let y of x)f.delete(y);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};_ instanceof Promise?_.then(l).catch(()=>{pe(h,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=h=>k?k.encode(h).length:h.length,ne=h=>{let w=[],x=2;for(let _ of h){let l=L(JSON.stringify(_))+1;if(w.length>0&&x+l>57344||w.length>=n)break;w.push(_),x+=l}return w},I=()=>{try{if(Date.now()<S)return;for(;a.length>0;){let h=a.filter(x=>!s.has(x.id));if(a.length=0,h.length===0)break;let w=ne(h);if(w.length===0)break;w.length<h.length&&a.push(...h.slice(w.length)),E(w)}}catch(h){}},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(h){m(h),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 me="_snt_asgn_";function re(e,t){return`${e}:${t}`}function vt(e,t){return`${me}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Pe(e){let t=e.slice(me.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 fe(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(me)&&e.push(n)}return e}catch(e){return[]}}function Le(e=18e5){let t=new Map,n=c=>c.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let c of fe())try{let o=localStorage.getItem(c);if(!o)continue;let i=JSON.parse(o);if(n(i)){localStorage.removeItem(c);continue}let a=Pe(c);if(!a)continue;t.set(re(a.componentId,a.segment),i)}catch(o){}})(),{get(c,o){let i=t.get(re(c,o));return i?n(i)?(t.delete(re(c,o)),null):i:null},set(c,o,i){let a=re(c,o);t.set(a,i);try{localStorage.setItem(vt(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 fe()){let a=Pe(i);if((a==null?void 0:a.componentId)===c)try{localStorage.removeItem(i)}catch(s){}}},clear(){t.clear();for(let c of fe())try{localStorage.removeItem(c)}catch(o){}}}}var Me=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function se(e){return Ue(e)!==null}function Ue(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Me.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 W(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function F(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function he(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:W(d),timeOfDay:F(c),dayOfWeek:(f=["sun","mon","tue","wed","thu","fri","sat"][c.getDay()])!=null?f:"sun",automation:(t==null?void 0:t.webdriver)===!0||se(n)}}var J=require("@sentientui/policy");function ie(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 ae(e){let t=ie(e);return(0,J.slotResultFor)(t,(0,J.slotBaselineArm)(t))}function ye(e){return typeof e=="string"?e:(0,J.canonicalArm)(e)}var Se="_snt_snap:",Et=["low","medium","high"];function ve(e){try{let t=localStorage.getItem(Se+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"||!Et.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 ee(e,t){try{localStorage.setItem(Se+e,JSON.stringify(t))}catch(n){}}var be=require("@sentientui/policy");var de=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.",Ge=!1,ce=!1;function bt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Ke(e){var a;let t=oe({ssrSessionId:e.ssrSessionId}),n=(a=t.getSessionId())!=null?a:"local",d=bt(),c=import("@sentientui/core/local").then(s=>{let r=s;return r.LOCAL_ENGINE_AVAILABLE?(Ge||(Ge=!0,console.info($e)),r):(ce||(ce=!0,console.error(we)),null)}).catch(()=>(ce||(ce=!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,de.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=$(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)}),ee(e.apiKey||"local",{v:1,persona:o.persona,band:(0,de.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,de.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}),destroy:()=>t.destroy()}}var Be="https://api.sentient-ui.com/v1/events",le=new Map,It=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 te={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}),destroy:()=>{}};function Ct(){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 je(e){return e.replace(/\/events\/?$/,"")}function xt(){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 At(e){var i;let t=je((i=e.ingestUrl)!=null?i:Be),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}),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(),destroy:()=>d.destroy()};function o(a){d=a}return{proxy:c,setInner:o}}function We(e){var H,Q,V,Y,q,h,w,x,_;if(typeof window=="undefined")return te;It=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return le.set(e.apiKey||"local",{config:e,upgrade:null}),Ke(e);let n=e.respectDoNotTrack!==!1&&xt();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."),te;let{proxy:l,setInner:g}=At(e);return le.set(e.apiKey,{config:e,upgrade:n?null:g}),l}return le.set(e.apiKey,{config:e,upgrade:null}),te}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."),te;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),te;let d=(H=e.ingestUrl)!=null?H:Be,c=Date.now(),o=oe({ssrSessionId:e.ssrSessionId}),i=Le(),a=Ne({ingestUrl:d,apiKey:e.apiKey}),s=je(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((V=document.referrer)!=null?V:"",f),p=(Y=e.sessionSegment)!=null?Y:`${u}:${m}`,S=new Map,v=new Map,E=null,k=l=>{for(let g of l)v.has(g.id)||v.set(g.id,ae(g))};if(e.initialSlots)for(let[l,g]of Object.entries(e.initialSlots))v.set(l,g);let L=ve(e.apiKey);if(L)for(let[l,g]of Object.entries(L.slots))v.has(l)||v.set(l,g);let ne={low:.15,medium:.5,high:.85};if(e.initialPersona)E=b({},e.initialPersona);else{let l=document.documentElement.dataset;l.sentientPersona?E={persona:l.sentientPersona,confidence:(h=ne[(q=l.sentientConfidence)!=null?q:"low"])!=null?h:.15}:L&&(E={persona:L.persona,confidence:(w=ne[L.band])!=null?w:.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=W((x=document.referrer)!=null?x:""),g=b(b({sessionId:z,deviceClass:u,trafficSource:m,referrerDomain:l,utmParams:Ct(),timeOfDay:F(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||se((_=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(y=>{y.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(y){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:a});let M={goal(l,g={},y=1,T=0){let C=o.getSessionId();if(!C)return;let A=Ee();I.then(()=>{fetch(`${s}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:C,name:l,metadata:g,weight:y,stepIndex:T,goalId:A}),headers:r}).catch(()=>{})})},componentGoal(l,g,y){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:ye(A),N={id:Ee(),sessionId:T,projectId:e.apiKey,componentId:l,variantId:U,eventType:"goal_achieved",goalType:g,payload:b({reward:(P=y==null?void 0:y.reward)!=null?P:1},(O=y==null?void 0:y.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 y=$(b({},l),{id:Ee(),sessionId:g,timestamp:Date.now(),timeInSession:Date.now()-c});e.debug&&console.log("[sentient] track",y),I.then(()=>a.push(y))},getAssignment(l,g){return i.get(l,g)},async assign(l,g,y,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:y!==void 0&&(R.agentData=y);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,Ae,_e;let g=o.getSessionId();if(!g)return null;let y=(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:[],y.length>0&&(X.slots=y.map(ie));let Te=await fetch(`${s}/decide`,{method:"POST",body:JSON.stringify(X),headers:r});if(!Te.ok)return k(y),null;let G=await Te.json(),ue={};for(let D of y)ue[D.id]=(U=(A=G.slots)==null?void 0:A[D.id])!=null?U:ae(D);for(let[D,ge]of Object.entries(ue))v.set(D,ge);E={persona:(N=G.persona)!=null?N:"unknown",confidence:(R=G.confidence)!=null?R:0};for(let[D,ge]of Object.entries((P=G.assignments)!=null?P:{}))i.set(D,p,{variantId:ge,assignedAt:Date.now(),segment:p,confidence:1});return ee(e.apiKey,{v:1,persona:E.persona,band:(0,be.confidenceBand)(E.confidence),slots:Object.fromEntries(v),layoutOrder:(O=G.layoutOrder)!=null?O:null,savedAt:Date.now()}),{layoutOrder:(Ae=G.layoutOrder)!=null?Ae:null,assignments:(_e=G.assignments)!=null?_e:{},slots:ue,persona:E.persona,confidence:E.confidence}}catch(X){return k(y),null}},getSlotResult(l){var g;return(g=v.get(l))!=null?g:null},getPersona(){return E?{persona:E.persona,confidence:E.confidence,band:(0,be.confidenceBand)(E.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}},destroy(){a.destroy(),o.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(le.set(e.apiKey,{config:e,upgrade:null}),e.debug){let l=window;l.__sentient&&(l.__sentient.client=M)}return M}var _t=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Tt="h1, h2, h3",Rt={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function Ie(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Ot(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 Dt(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function kt(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function Nt(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function Pt(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function Ce(e,t){var d,c,o;let n=e.querySelector(Tt);return{componentId:Nt(e),semanticType:kt(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:Pt(e),reactComponentName:Ot(e),dataAttributes:Dt(e)}}function Fe(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 Lt(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=Ce(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=Ce(i,e);t.push(r),d.set(i,r.componentId)}),{nodes:t,edges:Fe(d)}}function Je(){if(typeof window=="undefined")return Rt;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=Ie(r,12,48)*.4+Ie(S,0,1)*.4+Ie(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}=Lt(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)||!_t.has(m.tagName))return;let p=m.hasAttribute("data-sentient-id"),S=m.hasAttribute("aria-label");if(!p&&!S)return;let v=Ce(m,d);r.push(v),u.set(m,v.componentId)});r.length>0&&n&&n({nodes:r,edges:Fe(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 xe="_snt_graph_nodes",ze="_snt_graph_edges",Mt={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function Ut(e){var t;return(t=Mt[e])!=null?t:[]}function Gt(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 Kt=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function Bt(e){return Kt.has(e)?e:"generic"}function jt(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 He(e){let t=new Map,n=new Map,d=()=>{typeof window!="undefined"&&$t(xe,[...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=Gt(xe,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(ze)}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 Ut(p.semanticType)){let v=(a=s.get(S))!=null?a:[];for(let E of v){if(E.componentId===p.componentId)continue;let k=`semantic:${p.componentId}->${E.componentId}`;u.has(k)||(u.add(k),r.push({fromComponentId:p.componentId,toComponentId:E.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=Bt(p.semanticType);return{componentId:p.componentId,semanticType:S,answers:p.answers,contentHash:jt(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(xe),localStorage.removeItem(ze)}catch(o){}}}}var Wt="https://api.sentient-ui.com/v1/events";function Ft(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function Jt(e){var a;let t=We(e);if(!e.graph||typeof window=="undefined")return t;let n=Je(),d=(a=e.ingestUrl)!=null?a:Wt,c=He({syncUrl:d.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Ft()});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()}),$(b({},t),{getGraph:()=>c.snapshot(),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});
@@ -1 +1 @@
1
- import{j as v}from"./chunk-X2URHWFL.mjs";import{d as x,e as _,f as O,g as R,h as M}from"./chunk-SVYHTU5Z.mjs";import{a as h,b}from"./chunk-HGGX55FR.mjs";var P=new Set(["SECTION","ARTICLE","MAIN","DIV"]),D="h1, h2, h3",G={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function S(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function k(e){var t,n,p;try{let d=e;for(let s of Object.keys(d)){if(!s.startsWith("__reactFiber")&&!s.startsWith("__reactInternalInstance"))continue;let r=d[s],i=(p=(t=r==null?void 0:r.type)==null?void 0:t.displayName)!=null?p:(n=r==null?void 0:r.type)==null?void 0:n.name;if(i&&i.length>1)return i}}catch(d){}}function $(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function L(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function U(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function j(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function I(e,t){var p,d,s;let n=e.querySelector(D);return{componentId:U(e),semanticType:L(e),ariaLabel:(p=e.getAttribute("aria-label"))!=null?p: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:j(e),reactComponentName:k(e),dataAttributes:$(e)}}function w(e){var s;let t=[],n=new Set,p="__root__",d=new Map;for(let[r,i]of e){let a=r.parentElement,o=p;for(;a;){if(e.has(a)){o=e.get(a);let m=e.get(r),g=`${o}->${m}`;!n.has(g)&&o!==m&&(n.add(g),t.push({fromComponentId:o,toComponentId:m,weight:.6}));break}a=a.parentElement}let u=(s=d.get(o))!=null?s:[];u.push(r),d.set(o,u)}for(let r of d.values())if(!(r.length<2))for(let i=0;i<r.length;i++)for(let a=i+1;a<r.length;a++){let o=e.get(r[i]),u=e.get(r[a]);if(o===u)continue;let m=`${o}->${u}::sib`,g=`${u}->${o}::sib`;n.has(m)||(n.add(m),t.push({fromComponentId:o,toComponentId:u,weight:.3})),n.has(g)||(n.add(g),t.push({fromComponentId:u,toComponentId:o,weight:.3}))}return t}function F(e){let t=[],n=new Set,p=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(r=>{if(r instanceof Element&&!n.has(r)){n.add(r);let i=I(r,e);t.push(i),p.set(r,i.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(r=>{if(!(r instanceof Element)||n.has(r))return;let i=r.hasAttribute("aria-label"),a=r.hasAttribute("data-sentient-id");if(!i&&!a)return;n.add(r);let o=I(r,e);t.push(o),p.set(r,o.componentId)}),{nodes:t,edges:w(p)}}function N(){if(typeof window=="undefined")return G;let e=null,t=0,n=null,p=i=>{try{let a=window.getComputedStyle(i),o=parseFloat(a.fontSize)||12,u=parseFloat(a.zIndex)||0,m=i.getBoundingClientRect(),g=Math.max(m.top,0),c=window.innerHeight||1,l=1/(g/c+1),f=S(o,12,48)*.4+S(l,0,1)*.4+S(u,0,100)*.2;return Math.max(0,Math.min(1,f))}catch(a){return .5}};return{scan:()=>new Promise(i=>{let a=()=>{let{nodes:o,edges:u}=F(p);i({nodes:o,edges:u,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(a,{timeout:100}):a()}catch(o){a()}}),observe:i=>{n=i;try{e=new MutationObserver(a=>{let o=[],u=new Map;for(let m of a)m.type==="childList"&&m.addedNodes.forEach(g=>{if(!(g instanceof Element)||!P.has(g.tagName))return;let c=g.hasAttribute("data-sentient-id"),l=g.hasAttribute("aria-label");if(!c&&!l)return;let f=I(g,p);o.push(f),u.set(g,f.componentId)});o.length>0&&n&&n({nodes:o,edges:w(u),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(a){}},getProminenceScore:p,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(i){}t=0,n=null}}}var C="_snt_graph_nodes",A="_snt_graph_edges",K={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function q(e){var t;return(t=K[e])!=null?t:[]}function z(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function H(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var J=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function B(e){return J.has(e)?e:"generic"}function V(e,t,n){let p=`${e}:${t}:${n.join(",")}`,d=5381;for(let s=0;s<p.length;s++)d=(d<<5)+d+p.charCodeAt(s)&4294967295;return(d>>>0).toString(16).padStart(8,"0")}function T(e){let t=new Map,n=new Map,p=()=>{typeof window!="undefined"&&H(C,[...t.values()])},d=s=>{var r;try{let i=JSON.parse(s);t.clear();for(let a of(r=i.pageNodes)!=null?r:[])t.set(a.componentId,a)}catch(i){}};if(typeof window!="undefined"){let s=z(C,[]);for(let r of s)t.set(r.componentId,r);try{localStorage.removeItem(A)}catch(r){}}return{addPageNode(s){t.set(s.componentId,s),p()},addStructuralEdge(s){let r=`${s.fromComponentId}->${s.toComponentId}`;n.set(r,s)},syncOnce(){var r,i;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let s=[...t.values()];if(s.length!==0)try{let a=new Map;for(let c of s){let l=(r=a.get(c.semanticType))!=null?r:[];l.push(c),a.set(c.semanticType,l)}let o=[],u=new Set;for(let c of s)for(let l of q(c.semanticType)){let f=(i=a.get(l))!=null?i:[];for(let y of f){if(y.componentId===c.componentId)continue;let E=`semantic:${c.componentId}->${y.componentId}`;u.has(E)||(u.add(E),o.push({fromComponentId:c.componentId,toComponentId:y.componentId,type:"semantic",weight:.4,confidence:.9}))}}let m=new Set(s.map(c=>c.componentId));for(let c of n.values()){if(!m.has(c.fromComponentId)||!m.has(c.toComponentId))continue;let l=`structural:${c.fromComponentId}->${c.toComponentId}`;u.has(l)||(u.add(l),o.push({fromComponentId:c.fromComponentId,toComponentId:c.toComponentId,type:"structural",weight:c.weight,confidence:1}))}let g={pageUrl:window.location.href,nodes:s.map(c=>{let l=B(c.semanticType);return{componentId:c.componentId,semanticType:l,answers:c.answers,contentHash:V(c.componentId,l,c.answers),prominenceScore:c.prominenceScore,depthInPage:c.depth}}),edges:o};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:h({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(g)}).catch(()=>{})}catch(a){}},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(C),localStorage.removeItem(A)}catch(s){}}}}var W="https://api.sentient-ui.com/v1/events";function Y(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function oe(e){var i;let t=v(e);if(!e.graph||typeof window=="undefined")return t;let n=N(),p=(i=e.ingestUrl)!=null?i:W,d=T({syncUrl:p.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Y()});try{let a=localStorage.getItem("_snt_graph_nodes");a&&d.restore(JSON.stringify({pageNodes:JSON.parse(a)}))}catch(a){}n.scan().then(a=>{for(let o of a.nodes)d.addPageNode({id:o.componentId,componentId:o.componentId,semanticType:o.semanticType,answers:o.headingText?[o.headingText]:[],prominenceScore:o.prominenceScore,depth:o.depth});for(let o of a.edges)d.addStructuralEdge(o);d.syncOnce()});let s=null,r=()=>{s!==null&&clearTimeout(s),s=setTimeout(()=>{s=null,d.syncOnce()},500)};return n.observe(a=>{for(let o of a.nodes)d.addPageNode({id:o.componentId,componentId:o.componentId,semanticType:o.semanticType,answers:o.headingText?[o.headingText]:[],prominenceScore:o.prominenceScore,depth:o.depth});for(let o of a.edges)d.addStructuralEdge(o);r()}),b(h({},t),{getGraph:()=>d.snapshot(),destroy:()=>{s!==null&&clearTimeout(s),n.destroy(),d.destroy(),t.destroy()}})}export{M as deriveSessionSegment,x as detectDeviceClass,R as detectTimeOfDay,_ as detectTrafficSource,oe as init,O as referrerDomainFromReferer};
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};
@@ -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
@@ -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
@@ -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:()=>W,preloadDecisions:()=>N,readSessionCookie:()=>J,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 d,c,g,u,n,l,a;let r=(c=(d=e==null?void 0:e.userAgent)==null?void 0:d.trim())!=null?c:"",s=(u=(g=e==null?void 0:e.referer)==null?void 0:g.trim())!=null?u:"",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 E(t){let e={};for(let r of t)e[r.id]=U(r);return e}var F=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 W(t,e,r){var u;let s=(u=r.timeoutMs)!=null?u:F,i={"Content-Type":"application/json",Authorization:`Bearer ${r.apiKey}`};r.origin&&(i.Origin=r.origin);let d=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(d)},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 c=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 c)n.status==="fulfilled"&&n.value&&(g[n.value.id]=n.value.variantId);return g}function J(t){var e,r;return(r=(e=t.get("_snt_uid"))==null?void 0:e.value)!=null?r:null}async function N(t,e,r){var u,n,l,a,b,h,P,I,C,k,T;let s=(u=r.timeoutMs)!=null?u:F,i=(n=t.slots)!=null?n:[],d={layoutOrder:(l=t.sections)!=null?l:[],assignments:{},slots:E(i),persona:"unknown",confidence:0},c={"Content-Type":"application/json",Authorization:`Bearer ${r.apiKey}`};r.origin&&(c.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:c,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:c,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),d}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:(I=(P=m.layoutOrder)!=null?P:t.sections)!=null?I:[],assignments:(C=m.assignments)!=null?C:{},slots:j,persona:(k=m.persona)!=null?k:"unknown",confidence:(T=m.confidence)!=null?T:0}}catch(o){return console.error("[SentientUI] preloadDecisions: decide threw",o),d}}0&&(module.exports={buildSessionUpsertPayload,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,preloadAssignments,preloadDecisions,readSessionCookie,referrerDomainFromReferer});
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});
@@ -1 +1 @@
1
- import{d as j,e as $,f as C,g as k,h as M,i as f,j as D,k as P,l as T}from"./chunk-SVYHTU5Z.mjs";import{a as A,b as U}from"./chunk-HGGX55FR.mjs";var x=1e3;function b(r,n,e){let i=new AbortController,o=setTimeout(()=>i.abort(),e);return fetch(r,U(A({},n),{signal:i.signal})).finally(()=>clearTimeout(o))}async function B(r,n,e){var g;let i=(g=e.timeoutMs)!=null?g:x,o={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};e.origin&&(o.Origin=e.origin);let p=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(p)},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 u=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 u)s.status==="fulfilled"&&s.value&&(m[s.value.id]=s.value.variantId);return m}function J(r){var n,e;return(e=(n=r.get("_snt_uid"))==null?void 0:n.value)!=null?e:null}async function N(r,n,e){var g,s,d,a,S,y,R,h,v,w,I;let i=(g=e.timeoutMs)!=null?g:x,o=(s=r.slots)!=null?s:[],p={layoutOrder:(d=r.sections)!=null?d:[],assignments:{},slots:T(o),persona:"unknown",confidence:0},u={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};e.origin&&(u.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:u,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:u,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(D)}:{}))},i);if(!t.ok){let c=await t.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${t.status})`,c),p}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:P(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),p}}export{f as buildSessionUpsertPayload,M as deriveSessionSegment,j as detectDeviceClass,k as detectTimeOfDay,$ as detectTrafficSource,B as preloadAssignments,N as preloadDecisions,J as readSessionCookie,C as referrerDomainFromReferer};
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
@@ -329,16 +329,29 @@ type SentientClient = {
329
329
  /** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */
330
330
  fetchWeights(): Promise<ComponentWeightEntry[]>;
331
331
  getGraph(): GraphSnapshot;
332
+ /**
333
+ * Routine teardown: stops timers/listeners and flushes pending events, but
334
+ * KEEPS the visitor identity, decision snapshot, and retry bucket. Use for
335
+ * component unmount / re-init (framework providers call this on cleanup).
336
+ */
337
+ dispose(): void;
338
+ /**
339
+ * Consent-revocation / forget-me teardown: everything `dispose()` does,
340
+ * plus deletion of the visitor identity (`_snt_uid`), the decision
341
+ * snapshot, and the persisted retry bucket. The next visit starts as a
342
+ * brand-new visitor.
343
+ */
332
344
  destroy(): void;
333
345
  /** True when this client is the keyless local-mode client (dev only). */
334
346
  readonly isLocal?: boolean;
335
347
  };
336
348
 
337
349
  /**
338
- * Detects whether the visitor has enabled the browser's Do Not Track signal.
339
- * Checks the standard `navigator.doNotTrack`, the legacy `window.doNotTrack`
340
- * (older Firefox), and `navigator.msDoNotTrack` (old IE/Edge). Returns `true`
341
- * only when one is explicitly set to opt out (`'1'` or `'yes'`).
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'`.
342
355
  */
343
356
  declare function isDoNotTrackEnabled(): boolean;
344
357
  /**
package/dist/index.d.ts CHANGED
@@ -329,16 +329,29 @@ type SentientClient = {
329
329
  /** Fetches current bandit weights for all components in this project. Used by the provider to keep live-weight polling fresh. */
330
330
  fetchWeights(): Promise<ComponentWeightEntry[]>;
331
331
  getGraph(): GraphSnapshot;
332
+ /**
333
+ * Routine teardown: stops timers/listeners and flushes pending events, but
334
+ * KEEPS the visitor identity, decision snapshot, and retry bucket. Use for
335
+ * component unmount / re-init (framework providers call this on cleanup).
336
+ */
337
+ dispose(): void;
338
+ /**
339
+ * Consent-revocation / forget-me teardown: everything `dispose()` does,
340
+ * plus deletion of the visitor identity (`_snt_uid`), the decision
341
+ * snapshot, and the persisted retry bucket. The next visit starts as a
342
+ * brand-new visitor.
343
+ */
332
344
  destroy(): void;
333
345
  /** True when this client is the keyless local-mode client (dev only). */
334
346
  readonly isLocal?: boolean;
335
347
  };
336
348
 
337
349
  /**
338
- * Detects whether the visitor has enabled the browser's Do Not Track signal.
339
- * Checks the standard `navigator.doNotTrack`, the legacy `window.doNotTrack`
340
- * (older Firefox), and `navigator.msDoNotTrack` (old IE/Edge). Returns `true`
341
- * only when one is explicitly set to opt out (`'1'` or `'yes'`).
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'`.
342
355
  */
343
356
  declare function isDoNotTrackEnabled(): boolean;
344
357
  /**
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var Qe=Object.create;var X=Object.defineProperty,Ye=Object.defineProperties,ze=Object.getOwnPropertyDescriptor,Ve=Object.getOwnPropertyDescriptors,He=Object.getOwnPropertyNames,Ae=Object.getOwnPropertySymbols,qe=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty,Xe=Object.prototype.propertyIsEnumerable;var Oe=(e,t,n)=>t in e?X(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,w=(e,t)=>{for(var n in t||(t={}))Ce.call(t,n)&&Oe(e,n,t[n]);if(Ae)for(var n of Ae(t))Xe.call(t,n)&&Oe(e,n,t[n]);return e},K=(e,t)=>Ye(e,Ve(t));var Ze=(e,t)=>{for(var n in t)X(e,n,{get:t[n],enumerable:!0})},Te=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of He(t))!Ce.call(e,d)&&d!==n&&X(e,d,{get:()=>t[d],enumerable:!(i=ze(t,d))||i.enumerable});return e};var et=(e,t,n)=>(n=e!=null?Qe(qe(e)):{},Te(t||!e||!e.__esModule?X(n,"default",{value:e,enumerable:!0}):n,e)),tt=e=>Te(X({},"__esModule",{value:!0}),e);var It={};Ze(It,{LOCAL_MODE_BANNER:()=>Ee,PROD_KEYLESS_ERROR:()=>pe,SNAPSHOT_STORAGE_KEY_PREFIX:()=>se,agentUaList:()=>we,armOfResult:()=>de,attachMicroSignalDetectors:()=>$e,baselineResultFor:()=>$,baselineSlots:()=>Ue,deriveSessionSegment:()=>Me,detectDeviceClass:()=>ee,detectTimeOfDay:()=>re,detectTrafficSource:()=>te,grantConsent:()=>Et,init:()=>Je,isDoNotTrackEnabled:()=>_e,matchedAgentToken:()=>be,readSnapshot:()=>ue,referrerDomainFromReferer:()=>ne,renderPrePaintScript:()=>Ke,toWireSlot:()=>oe,uaTokenMatch:()=>Z,writeSnapshot:()=>W});module.exports=tt(It);var nt="_snt_uid";var G="_snt_uid";function rt(){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 ot(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function st(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(i){}}function it(e){try{return localStorage.getItem(e)}catch(t){return null}}function at(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function lt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ct(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function dt(e){try{sessionStorage.removeItem(e)}catch(t){}}function ut(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 gt(e){try{localStorage.removeItem(e)}catch(t){}}function ft(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var pt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function le(e){var l,g,m,S,h,b;if(typeof window=="undefined")return pt;let t=(l=e==null?void 0:e.cookieName)!=null?l:nt,i=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,d=(b=(h=(S=(m=ot(t))!=null?m:it(G))!=null?S:lt(G))!=null?h:e==null?void 0:e.ssrSessionId)!=null?b:rt();st(t,d,i);let r=at(G,d),c=ut(t),s=r?!1:ct(G,d),o=!r&&!c&&!s;return{getSessionId:()=>d,isEphemeral:()=>o,destroy:()=>{d=null,ft(t),gt(G),dt(G)}}}var mt={push:()=>{},flush:()=>{},destroy:()=>{}};function yt(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 he(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 Pe(e){var z,V,H;if(typeof window=="undefined")return mt;let t=(z=e.flushIntervalMs)!=null?z:5e3,n=(V=e.maxBatchSize)!=null?V:20,i=(H=e.maxRetrySize)!=null?H:100,d=e.ingestUrl,r=e.apiKey,c=`_snt_retry_${r.slice(0,12)}`,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,S=f=>{o.has(f.id)||m.has(f.id)||(m.add(f.id),s.push(f))},h=yt(i,c);for(let f of h)S(f);let b=0,v=0,E=f=>{if(f.length===0)return;let y=JSON.stringify(f),_=f.map(u=>u.id),R;try{R=fetch(d,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`}})}catch(u){he(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}he(f,i,c);for(let p of _)m.delete(p);v++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};R instanceof Promise?R.then(a).catch(()=>{he(f,i,c);for(let u of _)m.delete(u);v++,b=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):a(R)},F=typeof TextEncoder!="undefined"?new TextEncoder:null,L=f=>F?F.encode(f).length:f.length,ae=f=>{let y=[],_=2;for(let R of f){let a=L(JSON.stringify(R))+1;if(y.length>0&&_+a>57344||y.length>=n)break;y.push(R),_+=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){}},J=!0,N=null;N=setInterval(()=>{J&&x()},t);let Q=()=>{document.visibilityState==="hidden"&&x()},Y=()=>{x()};return document.addEventListener("visibilitychange",Q),window.addEventListener("beforeunload",Y),{push(f){S(f),s.length>=n&&x()},flush:x,destroy(){J=!1,N!==null&&(clearInterval(N),N=null),document.removeEventListener("visibilitychange",Q),window.removeEventListener("beforeunload",Y),x()}}}var ve="_snt_asgn_";function ce(e,t){return`${e}:${t}`}function ht(e,t){return`${ve}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Le(e){let t=e.slice(ve.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 Se(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(ve)&&e.push(n)}return e}catch(e){return[]}}function Ne(e=18e5){let t=new Map,n=d=>d.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let d of Se())try{let r=localStorage.getItem(d);if(!r)continue;let c=JSON.parse(r);if(n(c)){localStorage.removeItem(d);continue}let s=Le(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 Se()){let s=Le(c);if((s==null?void 0:s.componentId)===d)try{localStorage.removeItem(c)}catch(o){}}},clear(){t.clear();for(let d of Se())try{localStorage.removeItem(d)}catch(r){}}}}var we=["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(e){return be(e)!==null}function be(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=we.find(i=>t.includes(i.toLowerCase())))!=null?n:null}function ee(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 te(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 ne(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function re(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Me(e){let t=St("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function St(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?ee(n):"desktop",trafficSource:i?te(i,t==null?void 0:t.appOrigin):"direct",referrerDomain:ne(i),timeOfDay:re(d),dayOfWeek:(m=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?m:"sun",automation:(t==null?void 0:t.webdriver)===!0||Z(n)}}var B=require("@sentientui/policy");function oe(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 $(e){let t=oe(e);return(0,B.slotResultFor)(t,(0,B.slotBaselineArm)(t))}function Ue(e){let t={};for(let n of e)t[n.id]=$(n);return t}function de(e){return typeof e=="string"?e:(0,B.canonicalArm)(e)}var se="_snt_snap:",vt=["low","medium","high"];function ue(e){try{let t=localStorage.getItem(se+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"||!vt.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 W(e,t){try{localStorage.setItem(se+e,JSON.stringify(t))}catch(n){}}function Ke(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(se+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 Ie=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.",Ee="[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.",Ge=!1,ge=!1;function wt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Be(e){var s;let t=le({ssrSessionId:e.ssrSessionId}),n=(s=t.getSessionId())!=null?s:"local",i=wt(),d=import("@sentientui/core/local").then(o=>{let l=o;return l.LOCAL_ENGINE_AVAILABLE?(Ge||(Ge=!0,console.info(Ee)),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,S,h;let l=await d;if(!l)return null;let g=l.createLocalEngine({sessionId:n,forcedPersona:i}).decide(o);return r=K(w({},g),{layoutOrder:(S=(m=g.layoutOrder)!=null?m:r==null?void 0:r.layoutOrder)!=null?S:null,slots:w(w({},(h=r==null?void 0:r.slots)!=null?h:{}),g.slots)}),W(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 S;let g=await d;return!g||!l||l.length===0?l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null:{variantId:(S=g.createLocalEngine({sessionId:n,forcedPersona:i}).decide({components:[{id:o,variantIds:l}]}).assignments[o])!=null?S:l[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>t.destroy()}}function $e(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=h=>{for(let b of h)c=b.intersectionRatio>.3,c?l():o()};typeof process!="undefined"&&((d=process.env)==null?void 0:d.NODE_ENV)!=="production"&&(window.__lastIOCallback=m);let S=new IntersectionObserver(m,{threshold:[.3]});S.observe(t),window.addEventListener("scroll",g,{passive:!0}),i.push(()=>{S.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 We="https://api.sentient-ui.com/v1/events",j=new Map,je=null;function xe(){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}),destroy:()=>{}};function bt(){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 Fe(e){return e.replace(/\/events\/?$/,"")}function _e(){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 Et(e){if(typeof window=="undefined")return;let t=e!=null?e:je;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=j.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:i,upgrade:d}=n;if(!d||i.respectDoNotTrack!==!1&&_e())return;let r=Je(K(w({},i),{consent:!0}));d(r),j.set(t,{config:K(w({},i),{consent:!0}),upgrade:null})}function xt(e){var c;let t=Fe((c=e.ingestUrl)!=null?c:We),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 h of o!=null?o:[])g.append("variantIds[]",h);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}),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(),destroy:()=>i.destroy()};function r(s){i=s}return{proxy:d,setInner:r}}function Je(e){var Q,Y,z,V,H,f,y,_,R;if(typeof window=="undefined")return ie;je=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return j.set(e.apiKey||"local",{config:e,upgrade:null}),Be(e);let n=e.respectDoNotTrack!==!1&&_e();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}=xt(e);return j.set(e.apiKey,{config:e,upgrade:n?null:u}),a}return j.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=(Q=e.ingestUrl)!=null?Q:We,d=Date.now(),r=le({ssrSessionId:e.ssrSessionId}),c=Ne(),s=Pe({ingestUrl:i,apiKey:e.apiKey}),o=Fe(i),l={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=ee((Y=navigator.userAgent)!=null?Y:""),m=typeof window!="undefined"?window.location.origin:void 0,S=te((z=document.referrer)!=null?z:"",m),h=(V=e.sessionSegment)!=null?V:`${g}:${S}`,b=new Map,v=new Map,E=null,F=a=>{for(let u of a)v.has(u.id)||v.set(u.id,$(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[(H=a.sentientConfidence)!=null?H:"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,h,{variantId:u,assignedAt:Date.now(),segment:h,confidence:1});let x=Promise.resolve(),J=r.getSessionId();if(J){let a=ne((_=document.referrer)!=null?_:""),u=w(w({sessionId:J,deviceClass:g,trafficSource:S,referrerDomain:a,utmParams:bt(),timeOfDay:re(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:r.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Z((R=navigator.userAgent)!=null?R:"")},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,D=0){let I=r.getSessionId();if(!I)return;let k=xe();x.then(()=>{fetch(`${o}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:I,name:a,metadata:u,weight:p,stepIndex:D,goalId:k}),headers:l}).catch(()=>{})})},componentGoal(a,u,p){var A,P,O;let D=r.getSessionId();if(!D)return;let I=c.get(a,h),k=I?null:(A=v.get(a))!=null?A:null;if(!I&&k===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(k),T={id:xe(),sessionId:D,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=K(w({},a),{id:xe(),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,D){let I=r.getSessionId();if(!I)return null;let k=c.get(a,h);if(k&&(u!=null&&u.length||k.content!==void 0))return{variantId:k.variantId,assignmentTtlMs:0,content:k.content};let M=b.get(a);if(M)return M;let T=(async()=>{await x;try{let A={sessionId:I,componentId:a,variantIds:u};D!==void 0?A.agentDataByVariant=D:p!==void 0&&(A.agentData=p);let P=await fetch(`${o}/assign`,{method:"POST",body:JSON.stringify(A),headers:l});if(!P.ok)return null;let O=await P.json();return c.set(a,h,{variantId:O.variantId,assignedAt:Date.now(),segment:h,confidence:1,content:O.content}),O}catch(A){return null}finally{b.delete(a)}})();return b.set(a,T),T},async decide(a){var D,I,k,M,T,A,P,O,ke,Re;let u=r.getSessionId();if(!u)return null;let p=(D=a.slots)!=null?D:[];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(oe));let De=await fetch(`${o}/decide`,{method:"POST",body:JSON.stringify(q),headers:l});if(!De.ok)return F(p),null;let U=await De.json(),me={};for(let C of p)me[C.id]=(M=(k=U.slots)==null?void 0:k[C.id])!=null?M:$(C);for(let[C,ye]of Object.entries(me))v.set(C,ye);E={persona:(T=U.persona)!=null?T:"unknown",confidence:(A=U.confidence)!=null?A:0};for(let[C,ye]of Object.entries((P=U.assignments)!=null?P:{}))c.set(C,h,{variantId:ye,assignedAt:Date.now(),segment:h,confidence:1});return W(e.apiKey,{v:1,persona:E.persona,band:(0,Ie.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:(Re=U.assignments)!=null?Re:{},slots:me,persona:E.persona,confidence:E.confidence}}catch(q){return F(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,Ie.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}},destroy(){s.destroy(),r.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(j.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-X2URHWFL.mjs";import{a,b,c,d,e,f,g,h,j as i,k as j,l as k,m as l}from"./chunk-SVYHTU5Z.mjs";import"./chunk-HGGX55FR.mjs";export{r as LOCAL_MODE_BANNER,q as PROD_KEYLESS_ERROR,m as SNAPSHOT_STORAGE_KEY_PREFIX,a as agentUaList,l as armOfResult,s as attachMicroSignalDetectors,j as baselineResultFor,k as baselineSlots,h as deriveSessionSegment,d as detectDeviceClass,g as detectTimeOfDay,e as detectTrafficSource,u as grantConsent,v as init,t as isDoNotTrackEnabled,c as matchedAgentToken,n as readSnapshot,f as referrerDomainFromReferer,p as renderPrePaintScript,i as toWireSlot,b as uaTokenMatch,o as writeSnapshot};
1
+ import{a as m,b as n,c as o,d as p,e as q,f as r,g as s,h as t,i as u,j as v}from"./chunk-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/llms.txt CHANGED
@@ -10,8 +10,10 @@
10
10
  ## Install (agent quickstart)
11
11
 
12
12
  - React app: `npx @sentientui/cli init` — detects the framework (Next App/Pages, Vite, Remix, CRA),
13
- installs @sentientui/react, wraps the app with the provider, writes .env.local, scaffolds an
14
- example. Works with NO API key (keyless local mode: deterministic simulated decisions).
13
+ installs @sentientui/react, writes .env.local, scaffolds an example. It does NOT edit your
14
+ layout: it prints the wrap snippet you must wrap the app with <AdaptiveRoot> (or
15
+ <AdaptiveProvider>) yourself, or nothing adapts and nothing is tracked. Works with NO API key
16
+ (keyless local mode: deterministic simulated decisions).
15
17
  Verify by opening the app with `?sentient_persona=buyer` vs `?sentient_persona=deal_seeker`.
16
18
  - Real learning: create a project at https://sentient-ui.com, put the pk_ key in
17
19
  NEXT_PUBLIC_SENTIENT_API_KEY, add the domain to allowed origins.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentientui/core",
3
- "version": "0.11.2",
3
+ "version": "0.12.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -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 X,m as ue}from"./chunk-SVYHTU5Z.mjs";import{a as k,b as K}from"./chunk-HGGX55FR.mjs";var Pe="_snt_uid";var G="_snt_uid";function Le(){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 Ne(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Me(e,t,r){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${r}; SameSite=strict; path=/`}catch(d){}}function Ue(e){try{return localStorage.getItem(e)}catch(t){return null}}function Ke(e,t){try{return localStorage.setItem(e,t),!0}catch(r){return!1}}function Ge(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function $e(e,t){try{return sessionStorage.setItem(e,t),!0}catch(r){return!1}}function Be(e){try{sessionStorage.removeItem(e)}catch(t){}}function We(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 Fe(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Je={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Z(e){var a,g,m,S,h,w;if(typeof window=="undefined")return Je;let t=(a=e==null?void 0:e.cookieName)!=null?a:Pe,d=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,u=(w=(h=(S=(m=Ne(t))!=null?m:Ue(G))!=null?S:Ge(G))!=null?h:e==null?void 0:e.ssrSessionId)!=null?w:Le();Me(t,u,d);let n=Ke(G,u),c=We(t),o=n?!1:$e(G,u),s=!n&&!c&&!o;return{getSessionId:()=>u,isEphemeral:()=>s,destroy:()=>{u=null,Fe(t),je(G),Be(G)}}}var Qe={push:()=>{},flush:()=>{},destroy:()=>{}};function Ye(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 be(e){var J,Q,Y;if(typeof window=="undefined")return Qe;let t=(J=e.flushIntervalMs)!=null?J:5e3,r=(Q=e.maxBatchSize)!=null?Q:20,d=(Y=e.maxRetrySize)!=null?Y:100,u=e.ingestUrl,n=e.apiKey,c=`_snt_retry_${n.slice(0,12)}`,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,S=p=>{s.has(p.id)||m.has(p.id)||(m.add(p.id),o.push(p))},h=Ye(d,c);for(let p of h)S(p);let w=0,v=0,E=p=>{if(p.length===0)return;let y=JSON.stringify(p),_=p.map(l=>l.id),A;try{A=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++,w=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,w=0;return}ge(p,d,c);for(let f of _)m.delete(f);v++,w=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};A instanceof Promise?A.then(i).catch(()=>{ge(p,d,c);for(let l of _)m.delete(l);v++,w=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):i(A)},B=typeof TextEncoder!="undefined"?new TextEncoder:null,L=p=>B?B.encode(p).length:p.length,q=p=>{let y=[],_=2;for(let A of p){let i=L(JSON.stringify(A))+1;if(y.length>0&&_+i>57344||y.length>=r)break;y.push(A),_+=i}return y},b=()=>{try{if(Date.now()<w)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)),E(y)}}catch(p){}},W=!0,N=null;N=setInterval(()=>{W&&b()},t);let j=()=>{document.visibilityState==="hidden"&&b()},F=()=>{b()};return document.addEventListener("visibilitychange",j),window.addEventListener("beforeunload",F),{push(p){S(p),o.length>=r&&b()},flush:b,destroy(){W=!1,N!==null&&(clearInterval(N),N=null),document.removeEventListener("visibilitychange",j),window.removeEventListener("beforeunload",F),b()}}}var fe="_snt_asgn_";function ee(e,t){return`${e}:${t}`}function Ve(e,t){return`${fe}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ie(e){let t=e.slice(fe.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 pe(){try{let e=[];for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r!=null&&r.startsWith(fe)&&e.push(r)}return e}catch(e){return[]}}function _e(e=18e5){let t=new Map,r=u=>u.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let u of pe())try{let n=localStorage.getItem(u);if(!n)continue;let c=JSON.parse(n);if(r(c)){localStorage.removeItem(u);continue}let o=Ie(u);if(!o)continue;t.set(ee(o.componentId,o.segment),c)}catch(n){}})(),{get(u,n){let c=t.get(ee(u,n));return c?r(c)?(t.delete(ee(u,n)),null):c:null},set(u,n,c){let o=ee(u,n);t.set(o,c);try{localStorage.setItem(Ve(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 pe()){let o=Ie(c);if((o==null?void 0:o.componentId)===u)try{localStorage.removeItem(c)}catch(s){}}},clear(){t.clear();for(let u of pe())try{localStorage.removeItem(u)}catch(n){}}}}var te="_snt_snap:",ze=["low","medium","high"];function me(e){try{let t=localStorage.getItem(te+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"||!ze.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 z(e,t){try{localStorage.setItem(te+e,JSON.stringify(t))}catch(r){}}function He(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(te+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 Re}from"@sentientui/policy";import{confidenceBand as ye}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.",xe=!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 Ae(e){var o;let t=Z({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?(xe||(xe=!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=ye(s.confidence))}return{isLocal:!0,async decide(s){var m,S,h;let a=await u;if(!a)return null;let g=a.createLocalEngine({sessionId:r,forcedPersona:d}).decide(s);return n=K(k({},g),{layoutOrder:(S=(m=g.layoutOrder)!=null?m:n==null?void 0:n.layoutOrder)!=null?S:null,slots:k(k({},(h=n==null?void 0:n.slots)!=null?h:{}),g.slots)}),z(e.apiKey||"local",{v:1,persona:n.persona,band:ye(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:ye(n.confidence)}:null},async assign(s,a){var S;let g=await u;return!g||!a||a.length===0?a!=null&&a[0]?{variantId:a[0],assignmentTtlMs:0}:null:{variantId:(S=g.createLocalEngine({sessionId:r,forcedPersona:d}).decide({components:[{id:s,variantIds:a}]}).assignments[s])!=null?S:a[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>t.destroy()}}function Xe(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=h=>{for(let w of h)c=w.intersectionRatio>.3,c?a():s()};typeof process!="undefined"&&((u=process.env)==null?void 0:u.NODE_ENV)!=="production"&&(window.__lastIOCallback=m);let S=new IntersectionObserver(m,{threshold:[.3]});S.observe(t),window.addEventListener("scroll",g,{passive:!0}),d.push(()=>{S.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",$=new Map,Oe=null;function Se(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var H={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Ze(){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 Te(e){return e.replace(/\/events\/?$/,"")}function Ce(){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){if(typeof window=="undefined")return;let t=e!=null?e:Oe;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let r=$.get(t);if(!r){console.warn("[sentient] grantConsent() called before init()");return}let{config:d,upgrade:u}=r;if(!u||d.respectDoNotTrack!==!1&&Ce())return;let n=tt(K(k({},d),{consent:!0}));u(n),$.set(t,{config:K(k({},d),{consent:!0}),upgrade:null})}function et(e){var c;let t=Te((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 h of s!=null?s:[])g.append("variantIds[]",h);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}),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(),destroy:()=>d.destroy()};function n(o){d=o}return{proxy:u,setInner:n}}function tt(e){var j,F,J,Q,Y,p,y,_,A;if(typeof window=="undefined")return H;Oe=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return $.set(e.apiKey||"local",{config:e,upgrade:null}),Ae(e);let r=e.respectDoNotTrack!==!1&&Ce();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."),H;let{proxy:i,setInner:l}=et(e);return $.set(e.apiKey,{config:e,upgrade:r?null:l}),i}return $.set(e.apiKey,{config:e,upgrade:null}),H}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),H;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),H;let d=(j=e.ingestUrl)!=null?j:De,u=Date.now(),n=Z({ssrSessionId:e.ssrSessionId}),c=_e(),o=be({ingestUrl:d,apiKey:e.apiKey}),s=Te(d),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=ie((F=navigator.userAgent)!=null?F:""),m=typeof window!="undefined"?window.location.origin:void 0,S=ae((J=document.referrer)!=null?J:"",m),h=(Q=e.sessionSegment)!=null?Q:`${g}:${S}`,w=new Map,v=new Map,E=null,B=i=>{for(let l of i)v.has(l.id)||v.set(l.id,X(l))};if(e.initialSlots)for(let[i,l]of Object.entries(e.initialSlots))v.set(i,l);let L=me(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)E=k({},e.initialPersona);else{let i=document.documentElement.dataset;i.sentientPersona?E={persona:i.sentientPersona,confidence:(p=q[(Y=i.sentientConfidence)!=null?Y:"low"])!=null?p:.15}:L&&(E={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,h,{variantId:l,assignedAt:Date.now(),segment:h,confidence:1});let b=Promise.resolve(),W=n.getSessionId();if(W){let i=le((_=document.referrer)!=null?_:""),l=k(k({sessionId:W,deviceClass:g,trafficSource:S,referrerDomain:i,utmParams:Ze(),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((A=navigator.userAgent)!=null?A:"")},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=Se();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 D,P,O;let R=n.getSessionId();if(!R)return;let I=c.get(i,h),x=I?null:(D=v.get(i))!=null?D: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:Se(),sessionId:R,projectId:e.apiKey,componentId:i,variantId:M,eventType:"goal_achieved",goalType:l,payload:k({reward:(P=f==null?void 0:f.reward)!=null?P:1},(O=f==null?void 0:f.metadata)!=null?O:{}),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(k({},i),{id:Se(),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,h);if(x&&(l!=null&&l.length||x.content!==void 0))return{variantId:x.variantId,assignmentTtlMs:0,content:x.content};let M=w.get(i);if(M)return M;let C=(async()=>{await b;try{let D={sessionId:I,componentId:i,variantIds:l};R!==void 0?D.agentDataByVariant=R:f!==void 0&&(D.agentData=f);let P=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify(D),headers:a});if(!P.ok)return null;let O=await P.json();return c.set(i,h,{variantId:O.variantId,assignedAt:Date.now(),segment:h,confidence:1,content:O.content}),O}catch(D){return null}finally{w.delete(i)}})();return w.set(i,C),C},async decide(i){var R,I,x,M,C,D,P,O,ve,we;let l=n.getSessionId();if(!l)return null;let f=(R=i.slots)!=null?R:[];await b;try{let V={sessionId:l};i.sections&&i.sections.length>0&&(V.sections=i.sections.map(T=>({id:T}))),V.components=(I=i.components)!=null?I:[],f.length>0&&(V.slots=f.map(de));let Ee=await fetch(`${s}/decide`,{method:"POST",body:JSON.stringify(V),headers:a});if(!Ee.ok)return B(f),null;let U=await Ee.json(),se={};for(let T of f)se[T.id]=(M=(x=U.slots)==null?void 0:x[T.id])!=null?M:X(T);for(let[T,oe]of Object.entries(se))v.set(T,oe);E={persona:(C=U.persona)!=null?C:"unknown",confidence:(D=U.confidence)!=null?D:0};for(let[T,oe]of Object.entries((P=U.assignments)!=null?P:{}))c.set(T,h,{variantId:oe,assignedAt:Date.now(),segment:h,confidence:1});return z(e.apiKey,{v:1,persona:E.persona,band:Re(E.confidence),slots:Object.fromEntries(v),layoutOrder:(O=U.layoutOrder)!=null?O:null,savedAt:Date.now()}),{layoutOrder:(ve=U.layoutOrder)!=null?ve:null,assignments:(we=U.assignments)!=null?we:{},slots:se,persona:E.persona,confidence:E.confidence}}catch(V){return B(f),null}},getSlotResult(i){var l;return(l=v.get(i))!=null?l:null},getPersona(){return E?{persona:E.persona,confidence:E.confidence,band:Re(E.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}},destroy(){o.destroy(),n.destroy(),e.debug&&console.log("[sentient] destroyed")}};if($.set(e.apiKey,{config:e,upgrade:null}),e.debug){let i=window;i.__sentient&&(i.__sentient.client=N)}return N}export{te as a,me as b,z as c,He as d,he as e,ke as f,Xe as g,Ce as h,_t as i,tt as j};