@sentientui/core 0.18.1 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-RQXFTO7P.mjs +2 -0
- package/dist/chunk-RQXFTO7P.mjs.map +1 -0
- package/dist/{index-NJvfP1vo.d.ts → index-C-VCLqSk.d.ts} +9 -1
- package/dist/{index-D41GE3Cq.d.cts → index-DeTm1xvY.d.cts} +9 -1
- package/dist/index-engagement.js +1 -1
- package/dist/index-engagement.js.map +1 -1
- package/dist/index-engagement.mjs +1 -1
- package/dist/index-graph.d.cts +2 -2
- package/dist/index-graph.d.ts +2 -2
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.js.map +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index-local.d.cts +1 -1
- package/dist/index-local.d.ts +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-XYWLTGAO.mjs +0 -2
- package/dist/chunk-XYWLTGAO.mjs.map +0 -1
package/dist/index-graph.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var at=Object.create;var de=Object.defineProperty,ct=Object.defineProperties,dt=Object.getOwnPropertyDescriptor,lt=Object.getOwnPropertyDescriptors,ut=Object.getOwnPropertyNames,Ne=Object.getOwnPropertySymbols,pt=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty,gt=Object.prototype.propertyIsEnumerable;var Me=(e,t,n)=>t in e?de(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,x=(e,t)=>{for(var n in t||(t={}))Le.call(t,n)&&Me(e,n,t[n]);if(Ne)for(var n of Ne(t))gt.call(t,n)&&Me(e,n,t[n]);return e},q=(e,t)=>ct(e,lt(t));var ft=(e,t)=>{for(var n in t)de(e,n,{get:t[n],enumerable:!0})},Ge=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of ut(t))!Le.call(e,u)&&u!==n&&de(e,u,{get:()=>t[u],enumerable:!(s=dt(t,u))||s.enumerable});return e};var mt=(e,t,n)=>(n=e!=null?at(pt(e)):{},Ge(t||!e||!e.__esModule?de(n,"default",{value:e,enumerable:!0}):n,e)),yt=e=>Ge(de({},"__esModule",{value:!0}),e);var vn={};ft(vn,{deriveSessionSegment:()=>Ce,detectDeviceClass:()=>ee,detectTimeOfDay:()=>re,detectTrafficSource:()=>te,init:()=>bn,referrerDomainFromReferer:()=>ne,sanitizePageUrl:()=>Oe});module.exports=yt(vn);function ue(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(t+="-");return t}}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function H(e){return e?`_${e.slice(0,12)}`:""}var ht="_snt_uid",St=365,bt="_snt_uid";function vt(){return ue()}function wt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function It(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(s){}}function xt(e){try{return localStorage.getItem(e)}catch(t){return null}}function Et(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function Ct(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function At(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Tt(e){try{sessionStorage.removeItem(e)}catch(t){}}function Rt(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function kt(e){try{localStorage.removeItem(e)}catch(t){}}function _t(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Ot={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function pe(e){var f,g,m,b,w,R;if(typeof window=="undefined")return Ot;let t=H(e==null?void 0:e.apiKey),n=(f=e==null?void 0:e.cookieName)!=null?f:`${ht}${t}`,s=`${bt}${t}`,l=((g=e==null?void 0:e.cookieTTLDays)!=null?g:St)*24*60*60,i=C=>C&&C.length>0?C:null,d=(R=(w=(b=(m=i(wt(n)))!=null?m:i(xt(s)))!=null?b:i(Ct(s)))!=null?w:i(e==null?void 0:e.ssrSessionId))!=null?R:vt();It(n,d,l);let o=Et(s,d),r=Rt(n),a=o?!1:At(s,d),c=!o&&!r&&!a;return{getSessionId:()=>d,isEphemeral:()=>c,destroy:()=>{d=null,_t(n),kt(s),Tt(s)}}}function X(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function ge(e){if(e.ok===!0)return"delivered";let{status:t}=e;return typeof t!="number"?"retry":t>=200&&t<300?"delivered":t>=400&&t<500&&t!==429?"dropped":"retry"}function fe(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let s=JSON.parse(n);return Array.isArray(s)?(localStorage.removeItem(e),s.slice(-t)):[]}catch(n){return[]}}function Z(e,t,n){try{let s=(()=>{try{let l=localStorage.getItem(n);if(!l)return[];let i=JSON.parse(l);return Array.isArray(i)?i:[]}catch(l){return[]}})(),u=new Map;for(let l of s)u.set(l.id,l);for(let l of e)u.set(l.id,l);localStorage.setItem(n,JSON.stringify([...u.values()].slice(-t)))}catch(s){}}function me(e,t){try{let n=localStorage.getItem(t);if(!n)return;let s=JSON.parse(n);if(!Array.isArray(s))return;let u=new Set(e),l=s.filter(i=>!u.has(i.id));if(l.length===s.length)return;l.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(l))}catch(n){}}var Dt=500,Pt=56*1024;function xe(e){return`_snt_retry_${e.slice(0,12)}`}var Nt={push:()=>{},flush:()=>{},destroy:()=>{}};function Ke(e){var W,z,se;if(typeof window=="undefined")return Nt;let t=(W=e.flushIntervalMs)!=null?W:5e3,n=(z=e.maxBatchSize)!=null?z:20,s=(se=e.maxRetrySize)!=null?se:100,u=e.ingestUrl,l=e.apiKey,i=xe(l),d=[],o=new Set,r=[],a=S=>{for(let I of S)c.delete(I),!o.has(I)&&(o.add(I),r.push(I));for(;r.length>Dt;){let I=r.shift();I&&o.delete(I)}me(S,i)},c=new Set,f=S=>{o.has(S.id)||c.has(S.id)||(c.add(S.id),d.push(S))},g=S=>{for(let I of S)o.has(I.id)||(c.add(I.id),d.push(I))},m=fe(i,s);for(let S of m)f(S);let b=0,w=0,R=S=>{if(S.length===0)return;let I=JSON.stringify(S),F=S.map(V=>V.id),K;try{K=fetch(u,{method:"POST",keepalive:!0,body:I,headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`}})}catch(V){Z(S,s,i),g(S),w++,b=Date.now()+X(w);return}let Q=V=>{if(ge(V)!=="retry"){a(F),w=0,b=0;return}Z(S,s,i),g(S),w++,b=Date.now()+X(w)};K instanceof Promise?K.then(Q).catch(()=>{Z(S,s,i),g(S),w++,b=Date.now()+X(w)}):Q(K)},C=typeof TextEncoder!="undefined"?new TextEncoder:null,A=S=>C?C.encode(S).length:S.length,J=S=>{let I=[],F=2;for(let K of S){let Q=A(JSON.stringify(K))+1;if(I.length>0&&F+Q>Pt||I.length>=n)break;I.push(K),F+=Q}return I},_=()=>{try{if(Date.now()<b)return;for(;d.length>0&&!(Date.now()<b);){let S=d.filter(F=>!o.has(F.id));if(d.length=0,S.length===0)break;let I=J(S);if(I.length===0)break;I.length<S.length&&d.push(...S.slice(I.length)),R(I)}}catch(S){}},h=!0,E=null;E=setInterval(()=>{h&&_()},t);let j=()=>{document.visibilityState==="hidden"&&_()},N=()=>{_()};return document.addEventListener("visibilitychange",j),window.addEventListener("pagehide",N),{push(S){f(S),d.length>=n&&_()},flush:_,destroy(){h=!1,E!==null&&(clearInterval(E),E=null),document.removeEventListener("visibilitychange",j),window.removeEventListener("pagehide",N),_()}}}var Mt=200;function Ee(e){return`_snt_goal_retry_${e.slice(0,12)}`}var Lt={send:()=>{},flush:()=>{},destroy:()=>{}};function Ue(e){var A,J,_;if(typeof window=="undefined")return Lt;let t=(A=e.flushIntervalMs)!=null?A:5e3,n=(J=e.maxRetrySize)!=null?J:100,s=(_=e.maxPerFlush)!=null?_:5,u=Ee(e.apiKey),l=[],i=new Set,d=new Set,o=[],r=0,a=0,c=!1,f=h=>{for(i.delete(h.id),d.has(h.id)||(d.add(h.id),o.push(h.id));o.length>Mt;){let E=o.shift();E&&d.delete(E)}me([h.id],u)},g=h=>{Z([h],n,u),!d.has(h.id)&&!i.has(h.id)&&(i.add(h.id),l.push(h)),a++,r=Date.now()+X(a)},m=h=>{let E;try{E=fetch(e.url,{method:"POST",keepalive:!0,body:h.body,headers:e.headers})}catch(N){g(h);return}let j=N=>{var z;let W=ge(N);if(W==="retry"){g(h);return}W==="dropped"&&((z=e.onDrop)==null||z.call(e,h,N.status)),f(h),a=0,r=0};E instanceof Promise?E.then(j).catch(()=>g(h)):j(E)},b=()=>{try{if(c||Date.now()<r)return;let h=0;for(;l.length>0&&h<s&&!(Date.now()<r);){let E=l.shift();i.delete(E.id),!d.has(E.id)&&(h++,m(E))}}catch(h){}};for(let h of fe(u,n))i.has(h.id)||(i.add(h.id),l.push(h));let w=setInterval(b,t),R=()=>{document.visibilityState==="hidden"&&b()},C=()=>b();return document.addEventListener("visibilitychange",R),window.addEventListener("pagehide",C),{send(h){if(!c&&!(d.has(h.id)||i.has(h.id))){if(Date.now()<r){i.add(h.id),l.push(h);return}m(h)}},flush:b,destroy(){clearInterval(w),document.removeEventListener("visibilitychange",R),window.removeEventListener("pagehide",C),b(),c=!0}}}var Gt=1800*1e3;function ye(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function $e(e=Gt,t){let n=new Map,s=`_snt_asgn${H(t)}_`,u=(r,a)=>`${s}${encodeURIComponent(r)}:${encodeURIComponent(a)}`,l=r=>{let a=r.slice(s.length),c=a.indexOf(":");if(c<0)return null;try{return{componentId:decodeURIComponent(a.slice(0,c)),segment:decodeURIComponent(a.slice(c+1))}}catch(f){return null}},i=()=>{try{let r=[];for(let a=0;a<localStorage.length;a++){let c=localStorage.key(a);c!=null&&c.startsWith(s)&&r.push(c)}return r}catch(r){return[]}},d=r=>r.assignedAt+(r.ttlMs&&r.ttlMs>0?r.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let r of i())try{let a=localStorage.getItem(r);if(!a)continue;let c=JSON.parse(a);if(d(c)){localStorage.removeItem(r);continue}let f=l(r);if(!f)continue;n.set(ye(f.componentId,f.segment),c)}catch(a){}})(),{get(r,a){let c=n.get(ye(r,a));return c?d(c)?(n.delete(ye(r,a)),null):c:null},set(r,a,c){let f=ye(r,a);n.set(f,c);try{localStorage.setItem(u(r,a),JSON.stringify(c))}catch(g){}},invalidate(r){let a=`${encodeURIComponent(r)}:`;for(let c of[...n.keys()])c.startsWith(a)&&n.delete(c);for(let c of i()){let f=l(c);if((f==null?void 0:f.componentId)===r)try{localStorage.removeItem(c)}catch(g){}}},clear(){n.clear();for(let r of i())try{localStorage.removeItem(r)}catch(a){}}}}var Be=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function he(e){return Fe(e)!==null}function Fe(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Be.find(s=>t.includes(s.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(u){}let s=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(s)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(s)?"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 Ce(e){let t=Kt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Kt(e,t){var l,i,d,o,r,a,c;let n=(i=(l=t==null?void 0:t.userAgent)==null?void 0:l.trim())!=null?i:"",s=(o=(d=t==null?void 0:t.referer)==null?void 0:d.trim())!=null?o:"",u=(r=t==null?void 0:t.now)!=null?r:new Date;return{sessionId:e,ephemeral:!1,utmParams:(a=t==null?void 0:t.utmParams)!=null?a:{},deviceClass:n?ee(n):"desktop",trafficSource:s?te(s,t==null?void 0:t.appOrigin):"direct",referrerDomain:ne(s),timeOfDay:re(u),dayOfWeek:(c=["sun","mon","tue","wed","thu","fri","sat"][u.getDay()])!=null?c:"sun",automation:(t==null?void 0:t.webdriver)===!0||he(n)}}var oe=require("@sentientui/policy");function Ae(e){return x(x(x({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 Te(e){let t=Ae(e);return(0,oe.slotResultFor)(t,(0,oe.slotBaselineArm)(t))}function je(e){return typeof e=="string"?e:(0,oe.canonicalArm)(e)}var Se="_snt_snap:",Ut=["low","medium","high"];function We(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"||!Ut.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function be(e,t){try{localStorage.setItem(Se+e,JSON.stringify(t))}catch(n){}}var ke=require("@sentientui/policy");var we=require("@sentientui/policy");var ze="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",$t="[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.",Qe=!1,ve=!1;function Bt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function qe(e){var d;let t=pe({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(d=t.getSessionId())!=null?d:"local",s=Bt(),u=import("@sentientui/core/local").then(o=>{let r=o;return r.LOCAL_ENGINE_AVAILABLE?(Qe||(Qe=!0,console.info($t)),r):(ve||(ve=!0,console.error(ze)),null)}).catch(()=>(ve||(ve=!0,console.error(ze)),null)),l=null;function i(o){let r=document.documentElement;r.dataset.sentientPersona===void 0&&(r.dataset.sentientPersona=o.persona,r.dataset.sentientConfidence=(0,we.confidenceBand)(o.confidence))}return{isLocal:!0,async decide(o){var c,f,g;let r=await u;if(!r)return null;let a=r.createLocalEngine({sessionId:n,forcedPersona:s}).decide(o);return l=q(x({},a),{layoutOrder:(f=(c=a.layoutOrder)!=null?c:l==null?void 0:l.layoutOrder)!=null?f:null,slots:x(x({},(g=l==null?void 0:l.slots)!=null?g:{}),a.slots)}),be(e.apiKey||"local",{v:1,persona:l.persona,band:(0,we.confidenceBand)(l.confidence),slots:l.slots,layoutOrder:l.layoutOrder,savedAt:Date.now()}),i(a),a},getSlotResult(o){var r,a,c;return(c=(a=l==null?void 0:l.slots[o])!=null?a:(r=e.initialSlots)==null?void 0:r[o])!=null?c:null},getPersona(){return l?{persona:l.persona,confidence:l.confidence,band:(0,we.confidenceBand)(l.confidence)}:null},async assign(o,r){var f;let a=await u;return!a||!r||r.length===0?r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null:{variantId:(f=a.createLocalEngine({sessionId:n,forcedPersona:s}).decide({components:[{id:o,variantIds:r}]}).assignments[o])!=null?f:r[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var Je="https://api.sentient-ui.com/v1/events",B=new Map,Ft=null;function jt(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}function Re(){return ue()}var le={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 Wt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,s]of t)n.startsWith("utm_")&&(e[n]=s);return e}catch(e){return{}}}function Ve(e){return e.replace(/\/events\/?$/,"")}function _e(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function zt(e){var d;let t=e.preConsentBehavior==="statistical_winner",n=Ve((d=e.ingestUrl)!=null?d:Je),s={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(o,r,a){if(!t)return null;try{let c=new URLSearchParams({componentId:o});for(let m of r!=null?r:[])c.append("variantIds[]",m);let f=await fetch(`${n}/winner?${c.toString()}`,{headers:s});return f.ok?{variantId:(await f.json()).variantId,assignmentTtlMs:0}:r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}catch(c){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:()=>{}},l={track:o=>u.track(o),goal:((o,r,a,c)=>u.goal(o,r,a,c)),componentGoal:(o,r,a)=>u.componentGoal(o,r,a),identify:o=>u.identify(o),getAssignment:(o,r)=>u.getAssignment(o,r),assign:(o,r,a,c)=>u.assign(o,r,a,c),decide:o=>u.decide(o),getSlotResult:o=>u.getSlotResult(o),getPersona:()=>u.getPersona(),fetchWeights:()=>u.fetchWeights(),getGraph:()=>u.getGraph(),dispose:()=>u.dispose(),destroy:()=>u.destroy()};function i(o){u=o}return{proxy:l,setInner:i}}function Ye(e){var W,z,se,S,I,F,K,Q,V;if(typeof window=="undefined")return le;Ft=e.apiKey;let t=B.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(p){}let n=e.respectDoNotTrack!==!1&&_e(),s=e.consent===!1||n,u=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!u&&e.localMode!==!1)return s?(B.set(e.apiKey||"local",{config:e,upgrade:null}),le):(B.set(e.apiKey||"local",{config:e,upgrade:null}),qe(e));if(s){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return e.preConsentBehavior==="statistical_winner"&&console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),B.set(e.apiKey,{config:e,upgrade:null}),le;let{proxy:p,setInner:y}=zt(e);return B.set(e.apiKey,{config:e,upgrade:n?null:y}),p}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."),le;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),le;let l=(W=e.ingestUrl)!=null?W:Je,i=Date.now(),d=pe({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),o=$e(void 0,e.apiKey),r=Ke({ingestUrl:l,apiKey:e.apiKey}),a=Ve(l),c={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},f=Ue({url:`${a}/goals`,apiKey:e.apiKey,headers:c,onDrop:(p,y)=>{e.debug&&console.warn(`[sentient] goal dropped (HTTP ${y}) \u2014 this will not be retried. `+(y===400?"The session was not found: call init() and let the session upsert complete before firing goals.":y===401||y===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),p)}}),g=ee((z=navigator.userAgent)!=null?z:""),m=typeof window!="undefined"?window.location.origin:void 0,b=te((se=document.referrer)!=null?se:"",m),w=(S=e.sessionSegment)!=null?S:`${g}:${b}`,R=new Map,C=new Map,A=null,J=p=>{for(let y of p)C.has(y.id)||C.set(y.id,Te(y))};if(e.initialSlots)for(let[p,y]of Object.entries(e.initialSlots))C.set(p,y);let _=We(e.apiKey);if(_)for(let[p,y]of Object.entries(_.slots))C.has(p)||C.set(p,y);let h={low:.15,medium:.5,high:.85};if(e.initialPersona)A=x({},e.initialPersona);else{let p=document.documentElement.dataset;p.sentientPersona?A={persona:p.sentientPersona,confidence:(F=h[(I=p.sentientConfidence)!=null?I:"low"])!=null?F:.15}:_&&(A={persona:_.persona,confidence:(K=h[_.band])!=null?K:.15})}if(e.initialAssignments)for(let[p,y]of Object.entries(e.initialAssignments))o.set(p,w,{variantId:y,assignedAt:Date.now(),segment:w,confidence:1});let E=Promise.resolve(),j=d.getSessionId();if(j){let p=ne((Q=document.referrer)!=null?Q:""),y=x(x({sessionId:j,deviceClass:g,trafficSource:b,referrerDomain:p,utmParams:Wt(),timeOfDay:re(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:d.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||he((V=navigator.userAgent)!=null?V:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{E=fetch(`${a}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(y),headers:c}).then(v=>{v.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(v){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:r});let N={goal(p,y={},v=1,U=0){var G,O,ie;let P=d.getSessionId();if(!P)return;let T=jt(y)?y:{metadata:y},$=Re(),L={sessionId:P,name:p,metadata:(G=T.metadata)!=null?G:{},weight:(O=T.weight)!=null?O:v,stepIndex:(ie=T.stepIndex)!=null?ie:U,goalId:$,value:T.value,currency:T.currency,externalId:T.externalId};e.debug&&console.log("[sentient] goal",L);let D={id:$,body:JSON.stringify(L)};E.then(()=>f.send(D))},componentGoal(p,y,v){var D,G,O;let U=d.getSessionId();if(!U)return;let P=o.get(p,w),T=P?null:(D=C.get(p))!=null?D:null;if(!P&&T===null){e.debug&&console.warn(`[sentient] componentGoal("${p}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let $=P?P.variantId:je(T),L={id:Re(),sessionId:U,projectId:e.apiKey,componentId:p,variantId:$,eventType:"goal_achieved",goalType:y,payload:x({reward:(G=v==null?void 0:v.reward)!=null?G:1,goalValue:v==null?void 0:v.value,currency:v==null?void 0:v.currency},(O=v==null?void 0:v.metadata)!=null?O:{}),timestamp:Date.now(),timeInSession:Date.now()-i};e.debug&&console.log("[sentient] componentGoal",L),E.then(()=>r.push(L))},identify(p){let y=d.getSessionId();y&&E.then(()=>{fetch(`${a}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:y,userId:p,ephemeral:d.isEphemeral()}),headers:c}).catch(()=>{})})},track(p){let y=d.getSessionId();if(!y)return;let v=q(x({},p),{id:Re(),sessionId:y,timestamp:Date.now(),timeInSession:Date.now()-i});e.debug&&console.log("[sentient] track",v),E.then(()=>r.push(v))},getAssignment(p,y){return o.get(p,y)},async assign(p,y,v,U){let P=d.getSessionId();if(!P)return null;let T=o.get(p,w);if(T&&(y!=null&&y.length||T.content!==void 0)){let D=T.ttlMs&&T.ttlMs>0?Math.max(0,T.assignedAt+T.ttlMs-Date.now()):0;return{variantId:T.variantId,assignmentTtlMs:D,content:T.content}}let $=R.get(p);if($)return $;let L=(async()=>{await E;try{let D={sessionId:P,componentId:p,variantIds:y};U!==void 0?D.agentDataByVariant=U:v!==void 0&&(D.agentData=v);let G=await fetch(`${a}/assign`,{method:"POST",body:JSON.stringify(D),headers:c});if(!G.ok)return null;let O=await G.json();return o.set(p,w,x({variantId:O.variantId,assignedAt:Date.now(),segment:w,confidence:1,content:O.content},O.assignmentTtlMs&&O.assignmentTtlMs>0?{ttlMs:O.assignmentTtlMs}:{})),O}catch(D){return null}finally{R.delete(p)}})();return R.set(p,L),L},async decide(p){var U,P,T,$,L,D,G,O,ie;let y=d.getSessionId();if(!y)return null;let v=(U=p.slots)!=null?U:[];await E;try{let Y={sessionId:y};p.sections&&p.sections.length>0&&(Y.sections=p.sections.map(M=>({id:M}))),Y.components=(P=p.components)!=null?P:[],v.length>0&&(Y.slots=v.map(Ae)),p.slotsFrom==="registry"&&(Y.slotsFrom="registry"),p.v&&(Y.v=p.v);let Pe=await fetch(`${a}/decide`,{method:"POST",body:JSON.stringify(Y),headers:c});if(!Pe.ok)return J(v),null;let k=await Pe.json(),ae={};for(let M of v)ae[M.id]=($=(T=k.slots)==null?void 0:T[M.id])!=null?$:Te(M);if(k.slots)for(let[M,ce]of Object.entries(k.slots))M in ae||(ae[M]=ce);for(let[M,ce]of Object.entries(ae))C.set(M,ce);let it=A!=null&&A.persona!=="unknown";k.persona&&!(k.persona==="unknown"&&it)?A={persona:k.persona,confidence:(L=k.confidence)!=null?L:0}:A||(A={persona:"unknown",confidence:0});for(let[M,ce]of Object.entries((D=k.assignments)!=null?D:{}))o.set(M,w,{variantId:ce,assignedAt:Date.now(),segment:w,confidence:1});return be(e.apiKey,x({v:1,persona:A.persona,band:(0,ke.confidenceBand)(A.confidence),slots:Object.fromEntries(C),layoutOrder:(G=k.layoutOrder)!=null?G:null,savedAt:Date.now()},k.slotConfig?{slotConfig:k.slotConfig}:{})),x(x(x({layoutOrder:(O=k.layoutOrder)!=null?O:null,assignments:(ie=k.assignments)!=null?ie:{},slots:ae,persona:A.persona,confidence:A.confidence},k.slotConfig?{slotConfig:k.slotConfig}:{}),k.goals?{goals:k.goals}:{}),k.sectionMap?{sectionMap:k.sectionMap}:{})}catch(Y){return J(v),null}},getSlotResult(p){var y;return(y=C.get(p))!=null?y:null},getPersona(){return A?{persona:A.persona,confidence:A.confidence,band:(0,ke.confidenceBand)(A.confidence)}:null},async fetchWeights(){var p;try{let y=await fetch(`${a}/weights`,{headers:c});return y.ok?(p=(await y.json()).components)!=null?p:[]:[]}catch(y){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var p;r.destroy(),f.destroy(),((p=B.get(e.apiKey))==null?void 0:p.dispose)===N.dispose&&B.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var p;r.destroy(),f.destroy(),d.destroy(),((p=B.get(e.apiKey))==null?void 0:p.dispose)===N.dispose&&B.delete(e.apiKey);try{localStorage.removeItem(Se+e.apiKey),localStorage.removeItem(xe(e.apiKey)),localStorage.removeItem(Ee(e.apiKey))}catch(y){}e.debug&&console.log("[sentient] destroyed")}};if(B.set(e.apiKey,{config:e,upgrade:null,dispose:N.dispose}),e.debug){let p=window;p.__sentient&&(p.__sentient.client=N)}return N}var He="_snt_graph_edges",Qt={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function qt(e){var t;return(t=Qt[e])!=null?t:[]}function Jt(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function Vt(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var Yt=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function Ht(e){return Yt.has(e)?e:"generic"}function Oe(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function Xt(e,t,n){let s=`${e}:${t}:${n.join(",")}`,u=5381;for(let l=0;l<s.length;l++)u=(u<<5)+u+s.charCodeAt(l)&4294967295;return(u>>>0).toString(16).padStart(8,"0")}function Xe(e){let t=new Map,n=new Map,s=`_snt_graph_nodes${H(e==null?void 0:e.apiKey)}`,u=()=>{typeof window!="undefined"&&Vt(s,[...t.values()])},l=i=>{var d;try{let o=JSON.parse(i);t.clear();for(let r of(d=o.pageNodes)!=null?d:[])t.set(r.componentId,r)}catch(o){}};if(typeof window!="undefined"){let i=Jt(s,[]);for(let d of i)t.set(d.componentId,d);try{localStorage.removeItem(He)}catch(d){}}return{addPageNode(i){t.set(i.componentId,i),u()},addStructuralEdge(i){let d=`${i.fromComponentId}->${i.toComponentId}`;n.set(d,i)},syncOnce(){var d,o;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let i=[...t.values()];if(i.length!==0)try{let r=new Map;for(let m of i){let b=(d=r.get(m.semanticType))!=null?d:[];b.push(m),r.set(m.semanticType,b)}let a=[],c=new Set;for(let m of i)for(let b of qt(m.semanticType)){let w=(o=r.get(b))!=null?o:[];for(let R of w){if(R.componentId===m.componentId)continue;let C=`semantic:${m.componentId}->${R.componentId}`;c.has(C)||(c.add(C),a.push({fromComponentId:m.componentId,toComponentId:R.componentId,type:"semantic",weight:.4,confidence:.9}))}}let f=new Set(i.map(m=>m.componentId));for(let m of n.values()){if(!f.has(m.fromComponentId)||!f.has(m.toComponentId))continue;let b=`structural:${m.fromComponentId}->${m.toComponentId}`;c.has(b)||(c.add(b),a.push({fromComponentId:m.fromComponentId,toComponentId:m.toComponentId,type:"structural",weight:m.weight,confidence:1}))}let g=q(x(x({pageUrl:Oe(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:i.map(m=>{let b=Ht(m.semanticType);return{componentId:m.componentId,semanticType:b,answers:m.answers,contentHash:Xt(m.componentId,b,m.answers),prominenceScore:m.prominenceScore,depthInPage:m.depth}}),edges:a});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:x({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(g)}).catch(()=>{})}catch(r){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:l,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(s),localStorage.removeItem(He)}catch(i){}}}}var Ze=["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"],Zt=[["pricing",/\b(pricing|price|plans?|subscriptions?|per month|\/mo|tier)\b/i],["faq",/\b(faq|frequently asked|common questions?)\b/i],["comparison",/\b(compare|comparison|versus|vs\.)\b/i],["social_proof",/\b(testimonial|reviews?|trusted by|loved by|customers?|logos|rated|case stud)\b/i],["trust",/\b(security|guarantee|privacy|compliance|secure|gdpr|soc ?2|encrypt)\b/i],["features",/\b(features?|how it works|benefits?|capabilit|what you get)\b/i]],en=[["pricing",/(?:[$€£]\s?\d[\d,.]*\s*(?:\/|per\s)\s*(?:mo|month|yr|year|seat|user))|(?:\b(?:starter|basic|pro|growth|premium|enterprise)\b[^.]{0,60}[$€£]\s?\d)/i],["social_proof",/(?:★{2,})|(?:\b\d(?:\.\d)?\s*(?:out of|\/)\s*5\b)|(?:\brated\b)|(?:["“][^"”]{20,160}["”]\s*[—–-]\s*[A-Z][a-z]+)/],["trust",/\b(?:money[- ]back guarantee|refund(?:s)? within|encrypted|soc ?2|iso ?27001|gdpr[- ]compliant|cancel anytime)\b/i],["comparison",/\b(?:vs|versus)\b\.?[^.!?]{0,80}\b(?:compare|comparison|plans?|features?|alternative)\b|\bhow (?:we|it) compares?\b/i]];function tn(e){var n;let t=e.querySelector("h1, h2, h3");return((n=t==null?void 0:t.textContent)!=null?n:"").slice(0,160)}function nn(e){if(e.tag==="nav"||e.tag==="footer")return{type:"navigation",strength:"weak"};let t=`${e.idClass} ${e.headingText}`.toLowerCase();for(let[n,s]of Zt)if(s.test(t))return{type:n,strength:"strong"};for(let[n,s]of en)if(s.test(e.bodyText))return{type:n,strength:"strong"};return e.actionCount>=1&&e.textLength>0&&e.textLength<200?{type:"cta",strength:"weak"}:e.tag==="header"?{type:"hero",strength:"weak"}:/\b(hero|headline|banner)\b/i.test(t)?{type:"hero",strength:"weak"}:{type:"generic",strength:"weak"}}function rn(e){var n,s;let t=((n=e.textContent)!=null?n:"").replace(/\s+/g," ").trim();return{tag:e.tagName.toLowerCase(),idClass:`${e.id} ${String((s=e.className)!=null?s:"")}`,headingText:tn(e),bodyText:t.slice(0,2e3),actionCount:e.querySelectorAll('a, button, [role="button"]').length,textLength:t.length}}function et(e){return nn(rn(e)).type}var on=new Set(["SECTION","ARTICLE","MAIN","DIV"]),sn="h1, h2, h3",tt=30,an=1500,cn={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function nt(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function dn(e){var t,n,s;try{let u=e;for(let l of Object.keys(u)){if(!l.startsWith("__reactFiber")&&!l.startsWith("__reactInternalInstance"))continue;let i=u[l],d=(s=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?s:(n=i==null?void 0:i.type)==null?void 0:n.name;if(d&&d.length>1)return d}}catch(u){}}function ln(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var rt=new Set(Ze);function un(e){let t=e.getAttribute("data-sentient-type");if(t&&rt.has(t))return t;let n=e.getAttribute("role");return n&&rt.has(n)?n:et(e)}function pn(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)&4294967295;return(t>>>0).toString(16).padStart(8,"0")}function gn(e){let t=[],n=e;for(;n;){let s=n.parentElement;if(!s){t.push(n.tagName.toLowerCase());break}let u=Array.prototype.indexOf.call(s.children,n);t.push(`${n.tagName.toLowerCase()}[${u}]`),n=s}return t.reverse().join("/")}function fn(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${pn(gn(e))}`}function mn(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function De(e,t){var s,u,l;let n=e.querySelector(sn);return{componentId:fn(e),semanticType:un(e),ariaLabel:(s=e.getAttribute("aria-label"))!=null?s:void 0,headingText:(l=(u=n==null?void 0:n.textContent)==null?void 0:u.trim())!=null?l:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:mn(e),reactComponentName:dn(e),dataAttributes:ln(e)}}function ot(e){var l;let t=[],n=new Set,s="__root__",u=new Map;for(let[i,d]of e){let o=i.parentElement,r=s;for(;o;){if(e.has(o)){r=e.get(o);let c=e.get(i),f=`${r}->${c}`;!n.has(f)&&r!==c&&(n.add(f),t.push({fromComponentId:r,toComponentId:c,weight:.6}));break}o=o.parentElement}let a=(l=u.get(r))!=null?l:[];a.push(i),u.set(r,a)}for(let i of u.values()){if(i.length<2)continue;let d=i.length>tt?i.slice(0,tt):i;for(let o=0;o<d.length;o++)for(let r=o+1;r<d.length;r++){if(t.length>=an)return t;let a=e.get(d[o]),c=e.get(d[r]);if(a===c)continue;let f=`${a}->${c}::sib`,g=`${c}->${a}::sib`;n.has(f)||(n.add(f),t.push({fromComponentId:a,toComponentId:c,weight:.3})),n.has(g)||(n.add(g),t.push({fromComponentId:c,toComponentId:a,weight:.3}))}}return t}function yn(e){let t=[],n=new Set,s=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(i=>{if(i instanceof Element&&!n.has(i)){n.add(i);let d=De(i,e);t.push(d),s.set(i,d.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(i=>{if(!(i instanceof Element)||n.has(i))return;let d=i.hasAttribute("aria-label"),o=i.hasAttribute("data-sentient-id");if(!d&&!o)return;n.add(i);let r=De(i,e);t.push(r),s.set(i,r.componentId)}),{nodes:t,edges:ot(s),elementToId:s}}function st(){if(typeof window=="undefined")return cn;let e=null,t=0,n=null,s=new Map,u=o=>{try{let r=window.getComputedStyle(o),a=parseFloat(r.fontSize)||12,c=parseFloat(r.zIndex)||0,f=o.getBoundingClientRect(),g=Math.max(f.top,0),m=window.innerHeight||1,b=1/(g/m+1),w=nt(a,12,48)*.4+b*.4+nt(c,0,100)*.2;return Math.max(0,Math.min(1,w))}catch(r){return .5}};return{scan:()=>new Promise(o=>{let r=()=>{let{nodes:a,edges:c,elementToId:f}=yn(u);s.clear();for(let[g,m]of f)s.set(g,m);o({nodes:a,edges:c,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(r,{timeout:100}):r()}catch(a){r()}}),observe:o=>{n=o;try{e=new MutationObserver(r=>{let a=[],c=new Set;for(let g of r)g.type==="childList"&&g.addedNodes.forEach(m=>{if(!(m instanceof Element)||!on.has(m.tagName))return;let b=m.hasAttribute("data-sentient-id"),w=m.hasAttribute("aria-label");if(!b&&!w)return;let R=De(m,u);a.push(R),c.add(R.componentId),s.set(m,R.componentId)});if(a.length===0||!n)return;for(let g of[...s.keys()])g.isConnected||s.delete(g);let f=ot(s).filter(g=>c.has(g.fromComponentId)||c.has(g.toComponentId));n({nodes:a,edges:f,addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(r){}},getProminenceScore:u,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(o){}t=0,n=null,s.clear()}}}var hn="https://api.sentient-ui.com/v1/events";function Sn(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}var Ie=new Map;function bn(e){var c;let t=Ye(e),n=e.respectDoNotTrack!==!1&&_e(),s=e.consent===!1||n;if(!e.graph||!e.apiKey||s||typeof window=="undefined")return t;let u=Ie.get(e.apiKey);if(u)try{u()}catch(f){}let l=st(),i=(c=e.ingestUrl)!=null?c:hn,d=Xe({syncUrl:i.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Sn()});l.scan().then(f=>{for(let g of f.nodes)d.addPageNode({id:g.componentId,componentId:g.componentId,semanticType:g.semanticType,answers:e.captureDomText&&g.headingText?[g.headingText]:[],prominenceScore:g.prominenceScore,depth:g.depth});for(let g of f.edges)d.addStructuralEdge(g);d.syncOnce()});let o=null,r=()=>{o!==null&&clearTimeout(o),o=setTimeout(()=>{o=null,d.syncOnce()},500)};l.observe(f=>{for(let g of f.nodes)d.addPageNode({id:g.componentId,componentId:g.componentId,semanticType:g.semanticType,answers:e.captureDomText&&g.headingText?[g.headingText]:[],prominenceScore:g.prominenceScore,depth:g.depth});for(let g of f.edges)d.addStructuralEdge(g);r()});let a=()=>{o!==null&&(clearTimeout(o),o=null),l.destroy(),d.destroy(),Ie.get(e.apiKey)===a&&Ie.delete(e.apiKey)};return Ie.set(e.apiKey,a),q(x({},t),{getGraph:()=>d.snapshot(),dispose:()=>{a(),t.dispose()},destroy:()=>{a(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer,sanitizePageUrl});
|
|
1
|
+
"use strict";var dt=Object.create;var le=Object.defineProperty,lt=Object.defineProperties,ut=Object.getOwnPropertyDescriptor,pt=Object.getOwnPropertyDescriptors,gt=Object.getOwnPropertyNames,Le=Object.getOwnPropertySymbols,ft=Object.getPrototypeOf,Ke=Object.prototype.hasOwnProperty,mt=Object.prototype.propertyIsEnumerable;var Ge=(e,t,n)=>t in e?le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,x=(e,t)=>{for(var n in t||(t={}))Ke.call(t,n)&&Ge(e,n,t[n]);if(Le)for(var n of Le(t))mt.call(t,n)&&Ge(e,n,t[n]);return e},J=(e,t)=>lt(e,pt(t));var yt=(e,t)=>{for(var n in t)le(e,n,{get:t[n],enumerable:!0})},Ue=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of gt(t))!Ke.call(e,u)&&u!==n&&le(e,u,{get:()=>t[u],enumerable:!(r=ut(t,u))||r.enumerable});return e};var ht=(e,t,n)=>(n=e!=null?dt(ft(e)):{},Ue(t||!e||!e.__esModule?le(n,"default",{value:e,enumerable:!0}):n,e)),St=e=>Ue(le({},"__esModule",{value:!0}),e);var xn={};yt(xn,{deriveSessionSegment:()=>Ae,detectDeviceClass:()=>ee,detectTimeOfDay:()=>oe,detectTrafficSource:()=>te,init:()=>In,referrerDomainFromReferer:()=>ne,sanitizePageUrl:()=>Pe});module.exports=St(xn);function pe(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(t+="-");return t}}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Y(e){return e?`_${e.slice(0,12)}`:""}var vt="_snt_uid",bt=365,wt="_snt_uid";function It(){return pe()}function xt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Et(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(r){}}function Ct(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 Tt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function kt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Rt(e){try{sessionStorage.removeItem(e)}catch(t){}}function _t(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function Ot(e){try{localStorage.removeItem(e)}catch(t){}}function Dt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Pt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ge(e){var f,g,m,v,w,k;if(typeof window=="undefined")return Pt;let t=Y(e==null?void 0:e.apiKey),n=(f=e==null?void 0:e.cookieName)!=null?f:`${vt}${t}`,r=`${wt}${t}`,d=((g=e==null?void 0:e.cookieTTLDays)!=null?g:bt)*24*60*60,i=C=>C&&C.length>0?C:null,l=(k=(w=(v=(m=i(xt(n)))!=null?m:i(Ct(r)))!=null?v:i(Tt(r)))!=null?w:i(e==null?void 0:e.ssrSessionId))!=null?k:It();Et(n,l,d);let s=At(r,l),o=_t(n),a=s?!1:kt(r,l),c=!s&&!o&&!a;return{getSessionId:()=>l,isEphemeral:()=>c,destroy:()=>{l=null,Dt(n),Ot(r),Rt(r)}}}function X(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function fe(e){if(e.ok===!0)return"delivered";let{status:t}=e;return typeof t!="number"?"retry":t>=200&&t<300?"delivered":t>=400&&t<500&&t!==429?"dropped":"retry"}function me(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let r=JSON.parse(n);return Array.isArray(r)?(localStorage.removeItem(e),r.slice(-t)):[]}catch(n){return[]}}function Z(e,t,n){try{let r=(()=>{try{let d=localStorage.getItem(n);if(!d)return[];let i=JSON.parse(d);return Array.isArray(i)?i:[]}catch(d){return[]}})(),u=new Map;for(let d of r)u.set(d.id,d);for(let d of e)u.set(d.id,d);localStorage.setItem(n,JSON.stringify([...u.values()].slice(-t)))}catch(r){}}function ye(e,t){try{let n=localStorage.getItem(t);if(!n)return;let r=JSON.parse(n);if(!Array.isArray(r))return;let u=new Set(e),d=r.filter(i=>!u.has(i.id));if(d.length===r.length)return;d.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(d))}catch(n){}}var Nt=500,Mt=56*1024;function Ee(e){return`_snt_retry_${e.slice(0,12)}`}var Lt={push:()=>{},flush:()=>{},destroy:()=>{}};function $e(e){var N,Q,se;if(typeof window=="undefined")return Lt;let t=(N=e.flushIntervalMs)!=null?N:5e3,n=(Q=e.maxBatchSize)!=null?Q:20,r=(se=e.maxRetrySize)!=null?se:100,u=e.ingestUrl,d=e.apiKey,i=Ee(d),l=[],s=new Set,o=[],a=S=>{for(let I of S)c.delete(I),!s.has(I)&&(s.add(I),o.push(I));for(;o.length>Nt;){let I=o.shift();I&&s.delete(I)}ye(S,i)},c=new Set,f=S=>{s.has(S.id)||c.has(S.id)||(c.add(S.id),l.push(S))},g=S=>{for(let I of S)s.has(I.id)||(c.add(I.id),l.push(I))},m=me(i,r);for(let S of m)f(S);let v=0,w=0,k=S=>{if(S.length===0)return;let I=JSON.stringify(S),W=S.map(V=>V.id),K;try{K=fetch(u,{method:"POST",keepalive:!0,body:I,headers:{"Content-Type":"application/json",Authorization:`Bearer ${d}`}})}catch(V){Z(S,r,i),g(S),w++,v=Date.now()+X(w);return}let q=V=>{if(fe(V)!=="retry"){a(W),w=0,v=0;return}Z(S,r,i),g(S),w++,v=Date.now()+X(w)};K instanceof Promise?K.then(q).catch(()=>{Z(S,r,i),g(S),w++,v=Date.now()+X(w)}):q(K)},C=typeof TextEncoder!="undefined"?new TextEncoder:null,T=S=>C?C.encode(S).length:S.length,H=S=>{let I=[],W=2;for(let K of S){let q=T(JSON.stringify(K))+1;if(I.length>0&&W+q>Mt||I.length>=n)break;I.push(K),W+=q}return I},_=()=>{try{if(Date.now()<v)return;for(;l.length>0&&!(Date.now()<v);){let S=l.filter(W=>!s.has(W.id));if(l.length=0,S.length===0)break;let I=H(S);if(I.length===0)break;I.length<S.length&&l.push(...S.slice(I.length)),k(I)}}catch(S){}},h=!0,E=null;E=setInterval(()=>{h&&_()},t);let z=()=>{document.visibilityState==="hidden"&&_()},L=()=>{_()};return document.addEventListener("visibilitychange",z),window.addEventListener("pagehide",L),{push(S){f(S),l.length>=n&&_()},flush:_,destroy(){h=!1,E!==null&&(clearInterval(E),E=null),document.removeEventListener("visibilitychange",z),window.removeEventListener("pagehide",L),_()}}}var Gt=200;function Ce(e){return`_snt_goal_retry_${e.slice(0,12)}`}var Kt={send:()=>{},flush:()=>{},destroy:()=>{}};function Be(e){var T,H,_;if(typeof window=="undefined")return Kt;let t=(T=e.flushIntervalMs)!=null?T:5e3,n=(H=e.maxRetrySize)!=null?H:100,r=(_=e.maxPerFlush)!=null?_:5,u=Ce(e.apiKey),d=[],i=new Set,l=new Set,s=[],o=0,a=0,c=!1,f=h=>{for(i.delete(h.id),l.has(h.id)||(l.add(h.id),s.push(h.id));s.length>Gt;){let E=s.shift();E&&l.delete(E)}ye([h.id],u)},g=h=>{Z([h],n,u),!l.has(h.id)&&!i.has(h.id)&&(i.add(h.id),d.push(h)),a++,o=Date.now()+X(a)},m=h=>{let E;try{E=fetch(e.url,{method:"POST",keepalive:!0,body:h.body,headers:e.headers})}catch(L){g(h);return}let z=L=>{var Q;let N=fe(L);if(N==="retry"){g(h);return}N==="dropped"&&((Q=e.onDrop)==null||Q.call(e,h,L.status)),f(h),a=0,o=0};E instanceof Promise?E.then(z).catch(()=>g(h)):z(E)},v=()=>{try{if(c||Date.now()<o)return;let h=0;for(;d.length>0&&h<r&&!(Date.now()<o);){let E=d.shift();i.delete(E.id),!l.has(E.id)&&(h++,m(E))}}catch(h){}};for(let h of me(u,n))i.has(h.id)||(i.add(h.id),d.push(h));let w=setInterval(v,t),k=()=>{document.visibilityState==="hidden"&&v()},C=()=>v();return document.addEventListener("visibilitychange",k),window.addEventListener("pagehide",C),{send(h){if(!c&&!(l.has(h.id)||i.has(h.id))){if(Date.now()<o){i.add(h.id),d.push(h);return}m(h)}},flush:v,destroy(){clearInterval(w),document.removeEventListener("visibilitychange",k),window.removeEventListener("pagehide",C),v(),c=!0}}}var Ut=1800*1e3;function he(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Fe(e=Ut,t){let n=new Map,r=`_snt_asgn${Y(t)}_`,u=(o,a)=>`${r}${encodeURIComponent(o)}:${encodeURIComponent(a)}`,d=o=>{let a=o.slice(r.length),c=a.indexOf(":");if(c<0)return null;try{return{componentId:decodeURIComponent(a.slice(0,c)),segment:decodeURIComponent(a.slice(c+1))}}catch(f){return null}},i=()=>{try{let o=[];for(let a=0;a<localStorage.length;a++){let c=localStorage.key(a);c!=null&&c.startsWith(r)&&o.push(c)}return o}catch(o){return[]}},l=o=>o.assignedAt+(o.ttlMs&&o.ttlMs>0?o.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let o of i())try{let a=localStorage.getItem(o);if(!a)continue;let c=JSON.parse(a);if(l(c)){localStorage.removeItem(o);continue}let f=d(o);if(!f)continue;n.set(he(f.componentId,f.segment),c)}catch(a){}})(),{get(o,a){let c=n.get(he(o,a));return c?l(c)?(n.delete(he(o,a)),null):c:null},set(o,a,c){let f=he(o,a);n.set(f,c);try{localStorage.setItem(u(o,a),JSON.stringify(c))}catch(g){}},invalidate(o){let a=`${encodeURIComponent(o)}:`;for(let c of[...n.keys()])c.startsWith(a)&&n.delete(c);for(let c of i()){let f=d(c);if((f==null?void 0:f.componentId)===o)try{localStorage.removeItem(c)}catch(g){}}},clear(){n.clear();for(let o of i())try{localStorage.removeItem(o)}catch(a){}}}}var je=["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 We(e)!==null}function We(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=je.find(r=>t.includes(r.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(u){}let r=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(r)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(r)?"social":"referral"}catch(n){return"direct"}}function ne(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function oe(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ae(e){let t=$t("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function $t(e,t){var d,i,l,s,o,a,c;let n=(i=(d=t==null?void 0:t.userAgent)==null?void 0:d.trim())!=null?i:"",r=(s=(l=t==null?void 0:t.referer)==null?void 0:l.trim())!=null?s:"",u=(o=t==null?void 0:t.now)!=null?o:new Date;return{sessionId:e,ephemeral:!1,utmParams:(a=t==null?void 0:t.utmParams)!=null?a:{},deviceClass:n?ee(n):"desktop",trafficSource:r?te(r,t==null?void 0:t.appOrigin):"direct",referrerDomain:ne(r),timeOfDay:oe(u),dayOfWeek:(c=["sun","mon","tue","wed","thu","fri","sat"][u.getDay()])!=null?c:"sun",automation:(t==null?void 0:t.webdriver)===!0||Se(n)}}var re=require("@sentientui/policy");function Te(e){return x(x(x({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 ke(e){let t=Te(e);return(0,re.slotResultFor)(t,(0,re.slotBaselineArm)(t))}function ze(e){return typeof e=="string"?e:(0,re.canonicalArm)(e)}var ve="_snt_snap:",Bt=["low","medium","high"];function Qe(e){try{let t=localStorage.getItem(ve+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!Bt.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function be(e,t){try{localStorage.setItem(ve+e,JSON.stringify(t))}catch(n){}}var _e=require("@sentientui/policy");var Ie=require("@sentientui/policy");var qe="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ft="[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.",Je=!1,we=!1;function jt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function He(e){var l;let t=ge({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(l=t.getSessionId())!=null?l:"local",r=jt(),u=import("@sentientui/core/local").then(s=>{let o=s;return o.LOCAL_ENGINE_AVAILABLE?(Je||(Je=!0,console.info(Ft)),o):(we||(we=!0,console.error(qe)),null)}).catch(()=>(we||(we=!0,console.error(qe)),null)),d=null;function i(s){let o=document.documentElement;o.dataset.sentientPersona===void 0&&(o.dataset.sentientPersona=s.persona,o.dataset.sentientConfidence=(0,Ie.confidenceBand)(s.confidence))}return{isLocal:!0,async decide(s){var c,f,g;let o=await u;if(!o)return null;let a=o.createLocalEngine({sessionId:n,forcedPersona:r}).decide(s);return d=J(x({},a),{layoutOrder:(f=(c=a.layoutOrder)!=null?c:d==null?void 0:d.layoutOrder)!=null?f:null,slots:x(x({},(g=d==null?void 0:d.slots)!=null?g:{}),a.slots)}),be(e.apiKey||"local",{v:1,persona:d.persona,band:(0,Ie.confidenceBand)(d.confidence),slots:d.slots,layoutOrder:d.layoutOrder,savedAt:Date.now()}),i(a),a},getSlotResult(s){var o,a,c;return(c=(a=d==null?void 0:d.slots[s])!=null?a:(o=e.initialSlots)==null?void 0:o[s])!=null?c:null},getPersona(){return d?{persona:d.persona,confidence:d.confidence,band:(0,Ie.confidenceBand)(d.confidence)}:null},async assign(s,o){var f;let a=await u;return!a||!o||o.length===0?o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null:{variantId:(f=a.createLocalEngine({sessionId:n,forcedPersona:r}).decide({components:[{id:s,variantIds:o}]}).assignments[s])!=null?f:o[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var Ve="https://api.sentient-ui.com/v1/events",j=new Map,Wt=null;function zt(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}function Re(){return pe()}function Oe(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function Qt(e,t){let n=typeof window=="undefined"?null:window.history;if(!n)return;let r,u=()=>{let d=Oe();!d||d===r||(r=d,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}))};for(let d of["pushState","replaceState"]){let i=n[d];n[d]=function(...l){let s=i.apply(this,l);return u(),s}}window.addEventListener("popstate",u),u()}var ue={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 qt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,r]of t)n.startsWith("utm_")&&(e[n]=r);return e}catch(e){return{}}}function Ye(e){return e.replace(/\/events\/?$/,"")}function De(){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 Jt(e){var l;let t=e.preConsentBehavior==="statistical_winner",n=Ye((l=e.ingestUrl)!=null?l:Ve),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(s,o,a){if(!t)return null;try{let c=new URLSearchParams({componentId:s});for(let m of o!=null?o:[])c.append("variantIds[]",m);let f=await fetch(`${n}/winner?${c.toString()}`,{headers:r});return f.ok?{variantId:(await f.json()).variantId,assignmentTtlMs:0}:o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}catch(c){return o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},d={track:s=>u.track(s),goal:((s,o,a,c)=>u.goal(s,o,a,c)),componentGoal:(s,o,a)=>u.componentGoal(s,o,a),identify:s=>u.identify(s),getAssignment:(s,o)=>u.getAssignment(s,o),assign:(s,o,a,c)=>u.assign(s,o,a,c),decide:s=>u.decide(s),getSlotResult:s=>u.getSlotResult(s),getPersona:()=>u.getPersona(),fetchWeights:()=>u.fetchWeights(),getGraph:()=>u.getGraph(),dispose:()=>u.dispose(),destroy:()=>u.destroy()};function i(s){u=s}return{proxy:d,setInner:i}}function Xe(e){var Q,se,S,I,W,K,q,V,Me;if(typeof window=="undefined")return ue;Wt=e.apiKey;let t=j.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(p){}let n=e.respectDoNotTrack!==!1&&De(),r=e.consent===!1||n,u=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!u&&e.localMode!==!1)return r?(j.set(e.apiKey||"local",{config:e,upgrade:null}),ue):(j.set(e.apiKey||"local",{config:e,upgrade:null}),He(e));if(r){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return e.preConsentBehavior==="statistical_winner"&&console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),j.set(e.apiKey,{config:e,upgrade:null}),ue;let{proxy:p,setInner:y}=Jt(e);return j.set(e.apiKey,{config:e,upgrade:n?null:y}),p}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."),ue;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),ue;let d=(Q=e.ingestUrl)!=null?Q:Ve,i=Date.now(),l=ge({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),s=Fe(void 0,e.apiKey),o=$e({ingestUrl:d,apiKey:e.apiKey}),a=Ye(d),c={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},f=Be({url:`${a}/goals`,apiKey:e.apiKey,headers:c,onDrop:(p,y)=>{e.debug&&console.warn(`[sentient] goal dropped (HTTP ${y}) \u2014 this will not be retried. `+(y===400?"The session was not found: call init() and let the session upsert complete before firing goals.":y===401||y===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),p)}}),g=ee((se=navigator.userAgent)!=null?se:""),m=typeof window!="undefined"?window.location.origin:void 0,v=te((S=document.referrer)!=null?S:"",m),w=(I=e.sessionSegment)!=null?I:`${g}:${v}`,k=new Map,C=new Map,T=null,H=p=>{for(let y of p)C.has(y.id)||C.set(y.id,ke(y))};if(e.initialSlots)for(let[p,y]of Object.entries(e.initialSlots))C.set(p,y);let _=Qe(e.apiKey);if(_)for(let[p,y]of Object.entries(_.slots))C.has(p)||C.set(p,y);let h={low:.15,medium:.5,high:.85};if(e.initialPersona)T=x({},e.initialPersona);else{let p=document.documentElement.dataset;p.sentientPersona?T={persona:p.sentientPersona,confidence:(K=h[(W=p.sentientConfidence)!=null?W:"low"])!=null?K:.15}:_&&(T={persona:_.persona,confidence:(q=h[_.band])!=null?q:.15})}if(e.initialAssignments)for(let[p,y]of Object.entries(e.initialAssignments))s.set(p,w,{variantId:y,assignedAt:Date.now(),segment:w,confidence:1});let E=Promise.resolve(),z=l.getSessionId();if(z){let p=ne((V=document.referrer)!=null?V:""),y=x(x({sessionId:z,deviceClass:g,trafficSource:v,referrerDomain:p,utmParams:qt(),timeOfDay:oe(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:l.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Se((Me=navigator.userAgent)!=null?Me:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{E=fetch(`${a}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(y),headers:c}).then(b=>{b.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(b){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:o});let L=new Set,N={goal(p,y={},b=1,U=0){var D,ie,F,ae;let P=l.getSessionId();if(!P)return;let A=zt(y)?y:{metadata:y},$=`${p}\0${(D=A.externalId)!=null?D:""}`;if(L.has($)){e.debug&&console.log(`[sentient] goal("${p}") already recorded for this action \u2014 not sent twice`);return}L.add($),L.size===1&&setTimeout(()=>L.clear(),0);let G=Re(),O={sessionId:P,name:p,metadata:(ie=A.metadata)!=null?ie:{},weight:(F=A.weight)!=null?F:b,stepIndex:(ae=A.stepIndex)!=null?ae:U,goalId:G,value:A.value,currency:A.currency,externalId:A.externalId};e.debug&&console.log("[sentient] goal",O);let B={id:G,body:JSON.stringify(O)};E.then(()=>f.send(B))},componentGoal(p,y,b){var O,B,D;let U=l.getSessionId();if(!U)return;let P=s.get(p,w),A=P?null:(O=C.get(p))!=null?O:null;if(!P&&A===null){e.debug&&console.warn(`[sentient] componentGoal("${p}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let $=P?P.variantId:ze(A),G={id:Re(),sessionId:U,projectId:e.apiKey,componentId:p,variantId:$,eventType:"goal_achieved",goalType:y,payload:x({reward:(B=b==null?void 0:b.reward)!=null?B:1,goalValue:b==null?void 0:b.value,currency:b==null?void 0:b.currency},(D=b==null?void 0:b.metadata)!=null?D:{}),timestamp:Date.now(),timeInSession:Date.now()-i,path:Oe()};e.debug&&console.log("[sentient] componentGoal",G),E.then(()=>o.push(G))},identify(p){let y=l.getSessionId();y&&E.then(()=>{fetch(`${a}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:y,userId:p,ephemeral:l.isEphemeral()}),headers:c}).catch(()=>{})})},track(p){let y=l.getSessionId();if(!y)return;let b=J(x({path:Oe()},p),{id:Re(),sessionId:y,timestamp:Date.now(),timeInSession:Date.now()-i});e.debug&&console.log("[sentient] track",b),E.then(()=>o.push(b))},getAssignment(p,y){return s.get(p,y)},async assign(p,y,b,U){let P=l.getSessionId();if(!P)return null;let A=s.get(p,w);if(A&&(y!=null&&y.length||A.content!==void 0)){let O=A.ttlMs&&A.ttlMs>0?Math.max(0,A.assignedAt+A.ttlMs-Date.now()):0;return{variantId:A.variantId,assignmentTtlMs:O,content:A.content}}let $=k.get(p);if($)return $;let G=(async()=>{await E;try{let O={sessionId:P,componentId:p,variantIds:y};U!==void 0?O.agentDataByVariant=U:b!==void 0&&(O.agentData=b);let B=await fetch(`${a}/assign`,{method:"POST",body:JSON.stringify(O),headers:c});if(!B.ok)return null;let D=await B.json();return s.set(p,w,x({variantId:D.variantId,assignedAt:Date.now(),segment:w,confidence:1,content:D.content},D.assignmentTtlMs&&D.assignmentTtlMs>0?{ttlMs:D.assignmentTtlMs}:{})),D}catch(O){return null}finally{k.delete(p)}})();return k.set(p,G),G},async decide(p){var U,P,A,$,G,O,B,D,ie;let y=l.getSessionId();if(!y)return null;let b=(U=p.slots)!=null?U:[];await E;try{let F={sessionId:y};p.sections&&p.sections.length>0&&(F.sections=p.sections.map(M=>({id:M}))),F.components=(P=p.components)!=null?P:[],b.length>0&&(F.slots=b.map(Te)),p.slotsFrom==="registry"&&(F.slotsFrom="registry"),p.v&&(F.v=p.v);let ae=await fetch(`${a}/decide`,{method:"POST",body:JSON.stringify(F),headers:c});if(!ae.ok)return H(b),null;let R=await ae.json(),ce={};for(let M of b)ce[M.id]=($=(A=R.slots)==null?void 0:A[M.id])!=null?$:ke(M);if(R.slots)for(let[M,de]of Object.entries(R.slots))M in ce||(ce[M]=de);for(let[M,de]of Object.entries(ce))C.set(M,de);let ct=T!=null&&T.persona!=="unknown";R.persona&&!(R.persona==="unknown"&&ct)?T={persona:R.persona,confidence:(G=R.confidence)!=null?G:0}:T||(T={persona:"unknown",confidence:0});for(let[M,de]of Object.entries((O=R.assignments)!=null?O:{}))s.set(M,w,{variantId:de,assignedAt:Date.now(),segment:w,confidence:1});return be(e.apiKey,x({v:1,persona:T.persona,band:(0,_e.confidenceBand)(T.confidence),slots:Object.fromEntries(C),layoutOrder:(B=R.layoutOrder)!=null?B:null,savedAt:Date.now()},R.slotConfig?{slotConfig:R.slotConfig}:{})),x(x(x({layoutOrder:(D=R.layoutOrder)!=null?D:null,assignments:(ie=R.assignments)!=null?ie:{},slots:ce,persona:T.persona,confidence:T.confidence},R.slotConfig?{slotConfig:R.slotConfig}:{}),R.goals?{goals:R.goals}:{}),R.sectionMap?{sectionMap:R.sectionMap}:{})}catch(F){return H(b),null}},getSlotResult(p){var y;return(y=C.get(p))!=null?y:null},getPersona(){return T?{persona:T.persona,confidence:T.confidence,band:(0,_e.confidenceBand)(T.confidence)}:null},async fetchWeights(){var p;try{let y=await fetch(`${a}/weights`,{headers:c});return y.ok?(p=(await y.json()).components)!=null?p:[]:[]}catch(y){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var p;o.destroy(),f.destroy(),((p=j.get(e.apiKey))==null?void 0:p.dispose)===N.dispose&&j.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var p;o.destroy(),f.destroy(),l.destroy(),((p=j.get(e.apiKey))==null?void 0:p.dispose)===N.dispose&&j.delete(e.apiKey);try{localStorage.removeItem(ve+e.apiKey),localStorage.removeItem(Ee(e.apiKey)),localStorage.removeItem(Ce(e.apiKey))}catch(y){}e.debug&&console.log("[sentient] destroyed")}};if(j.set(e.apiKey,{config:e,upgrade:null,dispose:N.dispose}),Qt(N,e.apiKey),e.debug){let p=window;p.__sentient&&(p.__sentient.client=N)}return N}var Ze="_snt_graph_edges",Ht={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function Vt(e){var t;return(t=Ht[e])!=null?t:[]}function Yt(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function Xt(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var Zt=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function en(e){return Zt.has(e)?e:"generic"}function Pe(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function tn(e,t,n){let r=`${e}:${t}:${n.join(",")}`,u=5381;for(let d=0;d<r.length;d++)u=(u<<5)+u+r.charCodeAt(d)&4294967295;return(u>>>0).toString(16).padStart(8,"0")}function et(e){let t=new Map,n=new Map,r=`_snt_graph_nodes${Y(e==null?void 0:e.apiKey)}`,u=()=>{typeof window!="undefined"&&Xt(r,[...t.values()])},d=i=>{var l;try{let s=JSON.parse(i);t.clear();for(let o of(l=s.pageNodes)!=null?l:[])t.set(o.componentId,o)}catch(s){}};if(typeof window!="undefined"){let i=Yt(r,[]);for(let l of i)t.set(l.componentId,l);try{localStorage.removeItem(Ze)}catch(l){}}return{addPageNode(i){t.set(i.componentId,i),u()},addStructuralEdge(i){let l=`${i.fromComponentId}->${i.toComponentId}`;n.set(l,i)},syncOnce(){var l,s;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let i=[...t.values()];if(i.length!==0)try{let o=new Map;for(let m of i){let v=(l=o.get(m.semanticType))!=null?l:[];v.push(m),o.set(m.semanticType,v)}let a=[],c=new Set;for(let m of i)for(let v of Vt(m.semanticType)){let w=(s=o.get(v))!=null?s:[];for(let k of w){if(k.componentId===m.componentId)continue;let C=`semantic:${m.componentId}->${k.componentId}`;c.has(C)||(c.add(C),a.push({fromComponentId:m.componentId,toComponentId:k.componentId,type:"semantic",weight:.4,confidence:.9}))}}let f=new Set(i.map(m=>m.componentId));for(let m of n.values()){if(!f.has(m.fromComponentId)||!f.has(m.toComponentId))continue;let v=`structural:${m.fromComponentId}->${m.toComponentId}`;c.has(v)||(c.add(v),a.push({fromComponentId:m.fromComponentId,toComponentId:m.toComponentId,type:"structural",weight:m.weight,confidence:1}))}let g=J(x(x({pageUrl:Pe(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:i.map(m=>{let v=en(m.semanticType);return{componentId:m.componentId,semanticType:v,answers:m.answers,contentHash:tn(m.componentId,v,m.answers),prominenceScore:m.prominenceScore,depthInPage:m.depth}}),edges:a});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:x({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(g)}).catch(()=>{})}catch(o){}},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(r),localStorage.removeItem(Ze)}catch(i){}}}}var tt=["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"],nn=[["pricing",/\b(pricing|price|plans?|subscriptions?|per month|\/mo|tier)\b/i],["faq",/\b(faq|frequently asked|common questions?)\b/i],["comparison",/\b(compare|comparison|versus|vs\.)\b/i],["social_proof",/\b(testimonial|reviews?|trusted by|loved by|customers?|logos|rated|case stud)\b/i],["trust",/\b(security|guarantee|privacy|compliance|secure|gdpr|soc ?2|encrypt)\b/i],["features",/\b(features?|how it works|benefits?|capabilit|what you get)\b/i]],on=[["pricing",/(?:[$€£]\s?\d[\d,.]*\s*(?:\/|per\s)\s*(?:mo|month|yr|year|seat|user))|(?:\b(?:starter|basic|pro|growth|premium|enterprise)\b[^.]{0,60}[$€£]\s?\d)/i],["social_proof",/(?:★{2,})|(?:\b\d(?:\.\d)?\s*(?:out of|\/)\s*5\b)|(?:\brated\b)|(?:["“][^"”]{20,160}["”]\s*[—–-]\s*[A-Z][a-z]+)/],["trust",/\b(?:money[- ]back guarantee|refund(?:s)? within|encrypted|soc ?2|iso ?27001|gdpr[- ]compliant|cancel anytime)\b/i],["comparison",/\b(?:vs|versus)\b\.?[^.!?]{0,80}\b(?:compare|comparison|plans?|features?|alternative)\b|\bhow (?:we|it) compares?\b/i]];function rn(e){var n;let t=e.querySelector("h1, h2, h3");return((n=t==null?void 0:t.textContent)!=null?n:"").slice(0,160)}function sn(e){if(e.tag==="nav"||e.tag==="footer")return{type:"navigation",strength:"weak"};let t=`${e.idClass} ${e.headingText}`.toLowerCase();for(let[n,r]of nn)if(r.test(t))return{type:n,strength:"strong"};for(let[n,r]of on)if(r.test(e.bodyText))return{type:n,strength:"strong"};return e.actionCount>=1&&e.textLength>0&&e.textLength<200?{type:"cta",strength:"weak"}:e.tag==="header"?{type:"hero",strength:"weak"}:/\b(hero|headline|banner)\b/i.test(t)?{type:"hero",strength:"weak"}:{type:"generic",strength:"weak"}}function an(e){var n,r;let t=((n=e.textContent)!=null?n:"").replace(/\s+/g," ").trim();return{tag:e.tagName.toLowerCase(),idClass:`${e.id} ${String((r=e.className)!=null?r:"")}`,headingText:rn(e),bodyText:t.slice(0,2e3),actionCount:e.querySelectorAll('a, button, [role="button"]').length,textLength:t.length}}function nt(e){return sn(an(e)).type}var cn=new Set(["SECTION","ARTICLE","MAIN","DIV"]),dn="h1, h2, h3",ot=30,ln=1500,un={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function rt(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function pn(e){var t,n,r;try{let u=e;for(let d of Object.keys(u)){if(!d.startsWith("__reactFiber")&&!d.startsWith("__reactInternalInstance"))continue;let i=u[d],l=(r=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?r:(n=i==null?void 0:i.type)==null?void 0:n.name;if(l&&l.length>1)return l}}catch(u){}}function gn(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var st=new Set(tt);function fn(e){let t=e.getAttribute("data-sentient-type");if(t&&st.has(t))return t;let n=e.getAttribute("role");return n&&st.has(n)?n:nt(e)}function mn(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)&4294967295;return(t>>>0).toString(16).padStart(8,"0")}function yn(e){let t=[],n=e;for(;n;){let r=n.parentElement;if(!r){t.push(n.tagName.toLowerCase());break}let u=Array.prototype.indexOf.call(r.children,n);t.push(`${n.tagName.toLowerCase()}[${u}]`),n=r}return t.reverse().join("/")}function hn(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${mn(yn(e))}`}function Sn(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function Ne(e,t){var r,u,d;let n=e.querySelector(dn);return{componentId:hn(e),semanticType:fn(e),ariaLabel:(r=e.getAttribute("aria-label"))!=null?r:void 0,headingText:(d=(u=n==null?void 0:n.textContent)==null?void 0:u.trim())!=null?d:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Sn(e),reactComponentName:pn(e),dataAttributes:gn(e)}}function it(e){var d;let t=[],n=new Set,r="__root__",u=new Map;for(let[i,l]of e){let s=i.parentElement,o=r;for(;s;){if(e.has(s)){o=e.get(s);let c=e.get(i),f=`${o}->${c}`;!n.has(f)&&o!==c&&(n.add(f),t.push({fromComponentId:o,toComponentId:c,weight:.6}));break}s=s.parentElement}let a=(d=u.get(o))!=null?d:[];a.push(i),u.set(o,a)}for(let i of u.values()){if(i.length<2)continue;let l=i.length>ot?i.slice(0,ot):i;for(let s=0;s<l.length;s++)for(let o=s+1;o<l.length;o++){if(t.length>=ln)return t;let a=e.get(l[s]),c=e.get(l[o]);if(a===c)continue;let f=`${a}->${c}::sib`,g=`${c}->${a}::sib`;n.has(f)||(n.add(f),t.push({fromComponentId:a,toComponentId:c,weight:.3})),n.has(g)||(n.add(g),t.push({fromComponentId:c,toComponentId:a,weight:.3}))}}return t}function vn(e){let t=[],n=new Set,r=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(i=>{if(i instanceof Element&&!n.has(i)){n.add(i);let l=Ne(i,e);t.push(l),r.set(i,l.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(i=>{if(!(i instanceof Element)||n.has(i))return;let l=i.hasAttribute("aria-label"),s=i.hasAttribute("data-sentient-id");if(!l&&!s)return;n.add(i);let o=Ne(i,e);t.push(o),r.set(i,o.componentId)}),{nodes:t,edges:it(r),elementToId:r}}function at(){if(typeof window=="undefined")return un;let e=null,t=0,n=null,r=new Map,u=s=>{try{let o=window.getComputedStyle(s),a=parseFloat(o.fontSize)||12,c=parseFloat(o.zIndex)||0,f=s.getBoundingClientRect(),g=Math.max(f.top,0),m=window.innerHeight||1,v=1/(g/m+1),w=rt(a,12,48)*.4+v*.4+rt(c,0,100)*.2;return Math.max(0,Math.min(1,w))}catch(o){return .5}};return{scan:()=>new Promise(s=>{let o=()=>{let{nodes:a,edges:c,elementToId:f}=vn(u);r.clear();for(let[g,m]of f)r.set(g,m);s({nodes:a,edges:c,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(o,{timeout:100}):o()}catch(a){o()}}),observe:s=>{n=s;try{e=new MutationObserver(o=>{let a=[],c=new Set;for(let g of o)g.type==="childList"&&g.addedNodes.forEach(m=>{if(!(m instanceof Element)||!cn.has(m.tagName))return;let v=m.hasAttribute("data-sentient-id"),w=m.hasAttribute("aria-label");if(!v&&!w)return;let k=Ne(m,u);a.push(k),c.add(k.componentId),r.set(m,k.componentId)});if(a.length===0||!n)return;for(let g of[...r.keys()])g.isConnected||r.delete(g);let f=it(r).filter(g=>c.has(g.fromComponentId)||c.has(g.toComponentId));n({nodes:a,edges:f,addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(o){}},getProminenceScore:u,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(s){}t=0,n=null,r.clear()}}}var bn="https://api.sentient-ui.com/v1/events";function wn(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}var xe=new Map;function In(e){var c;let t=Xe(e),n=e.respectDoNotTrack!==!1&&De(),r=e.consent===!1||n;if(!e.graph||!e.apiKey||r||typeof window=="undefined")return t;let u=xe.get(e.apiKey);if(u)try{u()}catch(f){}let d=at(),i=(c=e.ingestUrl)!=null?c:bn,l=et({syncUrl:i.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:wn()});d.scan().then(f=>{for(let g of f.nodes)l.addPageNode({id:g.componentId,componentId:g.componentId,semanticType:g.semanticType,answers:e.captureDomText&&g.headingText?[g.headingText]:[],prominenceScore:g.prominenceScore,depth:g.depth});for(let g of f.edges)l.addStructuralEdge(g);l.syncOnce()});let s=null,o=()=>{s!==null&&clearTimeout(s),s=setTimeout(()=>{s=null,l.syncOnce()},500)};d.observe(f=>{for(let g of f.nodes)l.addPageNode({id:g.componentId,componentId:g.componentId,semanticType:g.semanticType,answers:e.captureDomText&&g.headingText?[g.headingText]:[],prominenceScore:g.prominenceScore,depth:g.depth});for(let g of f.edges)l.addStructuralEdge(g);o()});let a=()=>{s!==null&&(clearTimeout(s),s=null),d.destroy(),l.destroy(),xe.get(e.apiKey)===a&&xe.delete(e.apiKey)};return xe.set(e.apiKey,a),J(x({},t),{getGraph:()=>l.snapshot(),dispose:()=>{a(),t.dispose()},destroy:()=>{a(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer,sanitizePageUrl});
|
|
2
2
|
//# sourceMappingURL=index-graph.js.map
|