@sentientui/snippet 0.2.0 → 0.2.2
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 +3 -3
- package/dist/snippet.global.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ page is left exactly as it was.
|
|
|
17
17
|
};
|
|
18
18
|
</script>
|
|
19
19
|
<script
|
|
20
|
-
src="https://unpkg.com/@sentientui/snippet@0.1
|
|
20
|
+
src="https://unpkg.com/@sentientui/snippet@0.2.1/dist/snippet.global.js"
|
|
21
21
|
defer
|
|
22
22
|
crossorigin="anonymous"
|
|
23
23
|
integrity="sha384-REPLACE_WITH_RELEASE_HASH"
|
|
@@ -25,8 +25,8 @@ page is left exactly as it was.
|
|
|
25
25
|
```
|
|
26
26
|
|
|
27
27
|
Pin the exact version and add Subresource Integrity — compute the hash from the published file:
|
|
28
|
-
`openssl dgst -sha384 -binary dist/snippet.global.js | openssl base64 -A
|
|
29
|
-
|
|
28
|
+
`openssl dgst -sha384 -binary dist/snippet.global.js | openssl base64 -A`. Or self-host the
|
|
29
|
+
file and skip the CDN entirely.
|
|
30
30
|
|
|
31
31
|
```css
|
|
32
32
|
#hero[data-tone='urgent'] .cta { font-weight: 700; }
|
package/dist/snippet.global.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var SentientSnippet=(()=>{var de=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var Ee=(e,t)=>()=>(e&&(t=e(e=0)),t);var De=(e,t)=>{for(var n in t)de(e,n,{get:t[n],enumerable:!0})},He=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Fe(t))!Ve.call(e,o)&&o!==n&&de(e,o,{get:()=>t[o],enumerable:!(r=Ye(t,o))||r.enumerable});return e};var Xe=e=>He(de({},"__esModule",{value:!0}),e);var Qe,Ze,et,Te,tt,nt,Re,S,fe,Y=Ee(()=>{"use strict";Qe=Object.defineProperty,Ze=Object.defineProperties,et=Object.getOwnPropertyDescriptors,Te=Object.getOwnPropertySymbols,tt=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable,Re=(e,t,n)=>t in e?Qe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,S=(e,t)=>{for(var n in t||(t={}))tt.call(t,n)&&Re(e,n,t[n]);if(Te)for(var n of Te(t))nt.call(t,n)&&Re(e,n,t[n]);return e},fe=(e,t)=>Ze(e,et(t))});var Me={};De(Me,{LOCAL_ENGINE_AVAILABLE:()=>rt,createLocalEngine:()=>ot});function ot(e){throw new Error("[sentient] createLocalEngine is not available in production builds. The local engine only exists under the `development` export condition.")}var rt,$e=Ee(()=>{"use strict";Y();rt=!1});var jt={};De(jt,{applyPersonaAttributes:()=>H,applySlotAttributes:()=>X,parseSnippetConfig:()=>le,run:()=>ze,version:()=>Tt});Y();function te(e){return Object.keys(e).sort().map(t=>`${t}=${e[t]}`).join("|")}function Ne(e){if(e.length===0)return null;let t={};for(let n of e.split("|")){let r=n.indexOf("=");if(r<=0||r!==n.lastIndexOf("=")||r===n.length-1)return null;let o=n.slice(0,r);if(o in t)return null;t[o]=n.slice(r+1)}return t}function pe(e){var t,n,r;if(e.arms)return typeof e.baseline=="string"?e.baseline:(t=e.arms[0])!=null?t:"";if(e.baseline!==void 0&&typeof e.baseline=="object")return te(e.baseline);if(typeof e.baseline=="string")return e.baseline;let o={};for(let[u,s]of Object.entries((n=e.dims)!=null?n:{}))o[u]=(r=s[0])!=null?r:"";return te(o)}function je(e,t){var n,r;return e.dims!=null?(r=(n=Ne(t))!=null?n:Ne(pe(e)))!=null?r:{}:t}function B(e){return e>=.3?e<.7?"medium":"high":"low"}var Ce=["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 ge(e){return Le(e)!==null}function Le(e){var t;if(!e)return null;let n=e.toLowerCase();return(t=Ce.find(r=>n.includes(r.toLowerCase())))!=null?t:null}function me(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 he(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(o){}let r=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(r)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(r)?"social":"referral"}catch(n){return"direct"}}function ye(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function ve(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function ne(e){return S(S(S({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function re(e){let t=ne(e);return je(t,pe(t))}function be(e){return typeof e=="string"?e:te(e)}Y();var at="_snt_uid",W="_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 lt(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(r){}}function ut(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 ft(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function pt(e){try{sessionStorage.removeItem(e)}catch(t){}}function gt(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function mt(e){try{localStorage.removeItem(e)}catch(t){}}function ht(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var yt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Be(e){var t,n,r,o,u,s;if(typeof window=="undefined")return yt;let i=(t=e==null?void 0:e.cookieName)!=null?t:at,d=((n=e==null?void 0:e.cookieTTLDays)!=null?n:365)*24*60*60,c=(s=(u=(o=(r=it(i))!=null?r:ut(W))!=null?o:dt(W))!=null?u:e==null?void 0:e.ssrSessionId)!=null?s:st();lt(i,c,d);let f=ct(W,c),m=gt(i),w=f?!1:ft(W,c),k=!f&&!m&&!w;return{getSessionId:()=>c,isEphemeral:()=>k,destroy:()=>{c=null,ht(i),mt(W),pt(W)}}}var vt={push:()=>{},flush:()=>{},destroy:()=>{}};function bt(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let r=JSON.parse(n);return Array.isArray(r)?(localStorage.removeItem(t),r.slice(-e)):[]}catch(n){return[]}}function we(e,t,n){try{let r=[...(()=>{try{let o=localStorage.getItem(n);if(!o)return[];let u=JSON.parse(o);return Array.isArray(u)?u:[]}catch(o){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(r))}catch(r){}}function wt(e){var t,n,r;if(typeof window=="undefined")return vt;let o=(t=e.flushIntervalMs)!=null?t:5e3,u=(n=e.maxBatchSize)!=null?n:20,s=(r=e.maxRetrySize)!=null?r:100,i=e.ingestUrl,d=e.apiKey,c=`_snt_retry_${d.slice(0,12)}`,f=[],m=new Set,w=[],k=p=>{for(let g of p)y.delete(g),!m.has(g)&&(m.add(g),w.push(g));for(;w.length>500;){let g=w.shift();g&&m.delete(g)}},y=new Set,j=p=>{m.has(p.id)||y.has(p.id)||(y.add(p.id),f.push(p))},G=bt(s,c);for(let p of G)j(p);let I=0,b=0,Q=p=>{if(p.length===0)return;let g=JSON.stringify(p),O=p.map(l=>l.id),D;try{D=fetch(i,{method:"POST",keepalive:!0,body:g,headers:{"Content-Type":"application/json",Authorization:`Bearer ${d}`}})}catch(l){we(p,s,c);for(let h of O)y.delete(h);b++,I=Date.now()+Math.min(6e4,1e3*2**Math.min(b,6));return}let a=l=>{if(l.ok||l.status>=400&&l.status<500&&l.status!==429){k(O),b=0,I=0;return}we(p,s,c);for(let h of O)y.delete(h);b++,I=Date.now()+Math.min(6e4,1e3*2**Math.min(b,6))};D instanceof Promise?D.then(a).catch(()=>{we(p,s,c);for(let l of O)y.delete(l);b++,I=Date.now()+Math.min(6e4,1e3*2**Math.min(b,6))}):a(D)},Z=typeof TextEncoder!="undefined"?new TextEncoder:null,ee=p=>Z?Z.encode(p).length:p.length,P=p=>{let g=[],O=2;for(let D of p){let a=ee(JSON.stringify(D))+1;if(g.length>0&&O+a>57344||g.length>=u)break;g.push(D),O+=a}return g},E=()=>{try{if(Date.now()<I)return;for(;f.length>0;){let p=f.filter(O=>!m.has(O.id));if(f.length=0,p.length===0)break;let g=P(p);if(g.length===0)break;g.length<p.length&&f.push(...p.slice(g.length)),Q(g)}}catch(p){}},A=!0,v=null;v=setInterval(()=>{A&&E()},o);let J=()=>{document.visibilityState==="hidden"&&E()},M=()=>{E()};return document.addEventListener("visibilitychange",J),window.addEventListener("beforeunload",M),{push(p){j(p),f.length>=u&&E()},flush:E,destroy(){A=!1,v!==null&&(clearInterval(v),v=null),document.removeEventListener("visibilitychange",J),window.removeEventListener("beforeunload",M),E()}}}var Ae="_snt_asgn_";function oe(e,t){return`${e}:${t}`}function St(e,t){return`${Ae}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ue(e){let t=e.slice(Ae.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(r){return null}}function Se(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(Ae)&&e.push(n)}return e}catch(e){return[]}}function kt(e=18e5){let t=new Map,n=r=>r.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let r of Se())try{let o=localStorage.getItem(r);if(!o)continue;let u=JSON.parse(o);if(n(u)){localStorage.removeItem(r);continue}let s=Ue(r);if(!s)continue;t.set(oe(s.componentId,s.segment),u)}catch(o){}})(),{get(r,o){let u=t.get(oe(r,o));return u?n(u)?(t.delete(oe(r,o)),null):u:null},set(r,o,u){let s=oe(r,o);t.set(s,u);try{localStorage.setItem(St(r,o),JSON.stringify(u))}catch(i){}},invalidate(r){let o=`${r}:`;for(let u of[...t.keys()])u.startsWith(o)&&t.delete(u);for(let u of Se()){let s=Ue(u);if((s==null?void 0:s.componentId)===r)try{localStorage.removeItem(u)}catch(i){}}},clear(){t.clear();for(let r of Se())try{localStorage.removeItem(r)}catch(o){}}}}var Oe="_snt_snap:",It=["low","medium","high"];function ie(e){try{let t=localStorage.getItem(Oe+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"||!It.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 V(e,t){try{localStorage.setItem(Oe+e,JSON.stringify(t))}catch(n){}}var Ie="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ge="[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,ae=!1;function At(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Ot(e){var t;let n=Be({ssrSessionId:e.ssrSessionId}),r=(t=n.getSessionId())!=null?t:"local",o=At(),u=Promise.resolve().then(()=>($e(),Me)).then(d=>{let c=d;return c.LOCAL_ENGINE_AVAILABLE?(Ke||(Ke=!0,console.info(Ge)),c):(ae||(ae=!0,console.error(Ie)),null)}).catch(()=>(ae||(ae=!0,console.error(Ie)),null)),s=null;function i(d){let c=document.documentElement;c.dataset.sentientPersona===void 0&&(c.dataset.sentientPersona=d.persona,c.dataset.sentientConfidence=B(d.confidence))}return{isLocal:!0,async decide(d){var c,f,m;let w=await u;if(!w)return null;let k=w.createLocalEngine({sessionId:r,forcedPersona:o}).decide(d);return s=fe(S({},k),{layoutOrder:(f=(c=k.layoutOrder)!=null?c:s==null?void 0:s.layoutOrder)!=null?f:null,slots:S(S({},(m=s==null?void 0:s.slots)!=null?m:{}),k.slots)}),V(e.apiKey||"local",{v:1,persona:s.persona,band:B(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),i(k),k},getSlotResult(d){var c,f,m;return(m=(f=s==null?void 0:s.slots[d])!=null?f:(c=e.initialSlots)==null?void 0:c[d])!=null?m:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:B(s.confidence)}:null},async assign(d,c){var f;let m=await u;return!m||!c||c.length===0?c!=null&&c[0]?{variantId:c[0],assignmentTtlMs:0}:null:{variantId:(f=m.createLocalEngine({sessionId:r,forcedPersona:o}).decide({components:[{id:d,variantIds:c}]}).assignments[d])!=null?f:c[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>n.destroy()}}var We="https://api.sentient-ui.com/v1/events",se=new Map,xt=null;function ke(){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 F={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 _t(){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 Je(e){return e.replace(/\/events\/?$/,"")}function qe(){return[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(e=>e==="1"||e==="yes")}function Pt(e){var t;let n=Je((t=e.ingestUrl)!=null?t:We),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},o={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(i,d,c){try{let f=new URLSearchParams({componentId:i});for(let w of d!=null?d:[])f.append("variantIds[]",w);let m=await fetch(`${n}/winner?${f.toString()}`,{headers:r});return m.ok?{variantId:(await m.json()).variantId,assignmentTtlMs:0}:d!=null&&d[0]?{variantId:d[0],assignmentTtlMs:0}:null}catch(f){return d!=null&&d[0]?{variantId:d[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}},u={track:i=>o.track(i),goal:(i,d,c,f)=>o.goal(i,d,c,f),componentGoal:(i,d,c)=>o.componentGoal(i,d,c),identify:i=>o.identify(i),getAssignment:(i,d)=>o.getAssignment(i,d),assign:(i,d,c,f)=>o.assign(i,d,c,f),decide:i=>o.decide(i),getSlotResult:i=>o.getSlotResult(i),getPersona:()=>o.getPersona(),fetchWeights:()=>o.fetchWeights(),getGraph:()=>o.getGraph(),destroy:()=>o.destroy()};function s(i){o=i}return{proxy:u,setInner:s}}function xe(e){var t,n,r,o,u,s,i,d,c;if(typeof window=="undefined")return F;xt=e.apiKey;let f=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!f&&e.localMode!==!1)return se.set(e.apiKey||"local",{config:e,upgrade:null}),Ot(e);let m=e.respectDoNotTrack!==!1&&qe();if(e.consent===!1||m){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."),F;let{proxy:a,setInner:l}=Pt(e);return se.set(e.apiKey,{config:e,upgrade:m?null:l}),a}return se.set(e.apiKey,{config:e,upgrade:null}),F}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."),F;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),F;let w=(t=e.ingestUrl)!=null?t:We,k=Date.now(),y=Be({ssrSessionId:e.ssrSessionId}),j=kt(),G=wt({ingestUrl:w,apiKey:e.apiKey}),I=Je(w),b={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},Q=me((n=navigator.userAgent)!=null?n:""),Z=typeof window!="undefined"?window.location.origin:void 0,ee=he((r=document.referrer)!=null?r:"",Z),P=(o=e.sessionSegment)!=null?o:`${Q}:${ee}`,E=new Map,A=new Map,v=null,J=a=>{for(let l of a)A.has(l.id)||A.set(l.id,re(l))};if(e.initialSlots)for(let[a,l]of Object.entries(e.initialSlots))A.set(a,l);let M=ie(e.apiKey);if(M)for(let[a,l]of Object.entries(M.slots))A.has(a)||A.set(a,l);let p={low:.15,medium:.5,high:.85};if(e.initialPersona)v=S({},e.initialPersona);else{let a=document.documentElement.dataset;a.sentientPersona?v={persona:a.sentientPersona,confidence:(s=p[(u=a.sentientConfidence)!=null?u:"low"])!=null?s:.15}:M&&(v={persona:M.persona,confidence:(i=p[M.band])!=null?i:.15})}if(e.initialAssignments)for(let[a,l]of Object.entries(e.initialAssignments))j.set(a,P,{variantId:l,assignedAt:Date.now(),segment:P,confidence:1});let g=Promise.resolve(),O=y.getSessionId();if(O){let a=ye((d=document.referrer)!=null?d:""),l=S(S({sessionId:O,deviceClass:Q,trafficSource:ee,referrerDomain:a,utmParams:_t(),timeOfDay:ve(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:y.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||ge((c=navigator.userAgent)!=null?c:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{g=fetch(`${I}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(l),headers:b}).then(h=>{h.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(h){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:G});let D={goal(a,l={},h=1,T=0){let _=y.getSessionId();if(!_)return;let x=ke();g.then(()=>{fetch(`${I}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:_,name:a,metadata:l,weight:h,stepIndex:T,goalId:x}),headers:b}).catch(()=>{})})},componentGoal(a,l,h){var T,_,x;let $=y.getSessionId();if(!$)return;let R=j.get(a,P),N=R?null:(T=A.get(a))!=null?T:null;if(!R&&N===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 U=R?R.variantId:be(N),C={id:ke(),sessionId:$,projectId:e.apiKey,componentId:a,variantId:U,eventType:"goal_achieved",goalType:l,payload:S({reward:(_=h==null?void 0:h.reward)!=null?_:1},(x=h==null?void 0:h.metadata)!=null?x:{}),timestamp:Date.now(),timeInSession:Date.now()-k};e.debug&&console.log("[sentient] componentGoal",C),g.then(()=>G.push(C))},identify(a){let l=y.getSessionId();l&&g.then(()=>{fetch(`${I}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:l,userId:a,ephemeral:y.isEphemeral()}),headers:b}).catch(()=>{})})},track(a){let l=y.getSessionId();if(!l)return;let h=fe(S({},a),{id:ke(),sessionId:l,timestamp:Date.now(),timeInSession:Date.now()-k});e.debug&&console.log("[sentient] track",h),g.then(()=>G.push(h))},getAssignment(a,l){return j.get(a,l)},async assign(a,l,h,T){let _=y.getSessionId();if(!_)return null;let x=j.get(a,P);if(x&&(l!=null&&l.length||x.content!==void 0))return{variantId:x.variantId,assignmentTtlMs:0,content:x.content};let $=E.get(a);if($)return $;let R=(async()=>{await g;try{let N={sessionId:_,componentId:a,variantIds:l};T!==void 0?N.agentDataByVariant=T:h!==void 0&&(N.agentData=h);let U=await fetch(`${I}/assign`,{method:"POST",body:JSON.stringify(N),headers:b});if(!U.ok)return null;let C=await U.json();return j.set(a,P,{variantId:C.variantId,assignedAt:Date.now(),segment:P,confidence:1,content:C.content}),C}catch(N){return null}finally{E.delete(a)}})();return E.set(a,R),R},async decide(a){var l,h,T,_,x,$,R,N,U,C;let _e=y.getSessionId();if(!_e)return null;let q=(l=a.slots)!=null?l:[];await g;try{let z={sessionId:_e};a.sections&&a.sections.length>0&&(z.sections=a.sections.map(L=>({id:L}))),z.components=(h=a.components)!=null?h:[],q.length>0&&(z.slots=q.map(ne));let Pe=await fetch(`${I}/decide`,{method:"POST",body:JSON.stringify(z),headers:b});if(!Pe.ok)return J(q),null;let K=await Pe.json(),ue={};for(let L of q)ue[L.id]=(_=(T=K.slots)==null?void 0:T[L.id])!=null?_:re(L);for(let[L,ce]of Object.entries(ue))A.set(L,ce);v={persona:(x=K.persona)!=null?x:"unknown",confidence:($=K.confidence)!=null?$:0};for(let[L,ce]of Object.entries((R=K.assignments)!=null?R:{}))j.set(L,P,{variantId:ce,assignedAt:Date.now(),segment:P,confidence:1});return V(e.apiKey,{v:1,persona:v.persona,band:B(v.confidence),slots:Object.fromEntries(A),layoutOrder:(N=K.layoutOrder)!=null?N:null,savedAt:Date.now()}),{layoutOrder:(U=K.layoutOrder)!=null?U:null,assignments:(C=K.assignments)!=null?C:{},slots:ue,persona:v.persona,confidence:v.confidence}}catch(z){return J(q),null}},getSlotResult(a){var l;return(l=A.get(a))!=null?l:null},getPersona(){return v?{persona:v.persona,confidence:v.confidence,band:B(v.confidence)}:null},async fetchWeights(){var a;try{let l=await fetch(`${I}/weights`,{headers:b});return l.ok?(a=(await l.json()).components)!=null?a:[]:[]}catch(l){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){G.destroy(),y.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(se.set(e.apiKey,{config:e,upgrade:null}),e.debug){let a=window;a.__sentient&&(a.__sentient.client=D)}return D}Y();var Et=["landing","ecommerce","saas","marketplace"];function Dt(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=Object.entries(e);if(t.length<1||t.length>4)return null;let n={};for(let[r,o]of t){if(!Array.isArray(o)||o.length<2||o.length>6||!o.every(u=>typeof u=="string"))return null;n[r]=o}return n}function le(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.apiKey!="string"||!t.apiKey.startsWith("pk_"))return null;let n=Et.includes(t.context)?t.context:"landing",r={};if(typeof t.slots=="object"&&t.slots!==null&&!Array.isArray(t.slots))for(let[o,u]of Object.entries(t.slots)){if(typeof u!="object"||u===null)continue;let s=u,i=Dt(s.dims);i&&(s.target!==void 0&&typeof s.target!="string"||(r[o]=s.target===void 0?{dims:i}:{dims:i,target:s.target}))}return{apiKey:t.apiKey,context:n,personaAttributes:t.personaAttributes===!0,slots:r}}function H(e,t,n){n.documentElement.setAttribute("data-sentient-persona",e),n.documentElement.setAttribute("data-sentient-confidence",t)}function X(e,t,n){var r;for(let[o,u]of Object.entries(t)){let s=e[o];if(!s||typeof s=="string")continue;let i=u.target?Array.from(n.querySelectorAll(u.target)):[n.documentElement];for(let d of i)for(let[c,f]of Object.entries(s))(r=u.dims[c])!=null&&r.includes(f)&&d.setAttribute(`data-${c}`,f)}}var Tt="0.1.0",Rt=5e3;function Nt(e,t){return Promise.race([e,new Promise(n=>setTimeout(()=>n(null),t))])}async function ze(){var e,t;try{let n=le(window.sentient);if(!n)return;let r=ie(n.apiKey);r&&(n.personaAttributes&&H(r.persona,r.band,document),X(r.slots,n.slots,document));let o=xe({apiKey:n.apiKey,context:n.context}),u=Object.entries(n.slots).map(([d,c])=>({id:d,dims:c.dims})),s=await Nt(o.decide({slots:u}),Rt);if(!s)return;let i=o.getPersona();n.personaAttributes&&i&&H(i.persona,i.band,document),X(s.slots,n.slots,document),V(n.apiKey,{v:1,persona:(e=i==null?void 0:i.persona)!=null?e:s.persona,band:(t=i==null?void 0:i.band)!=null?t:"low",slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()})}catch(n){}}typeof window!="undefined"&&window.sentient&&ze();return Xe(jt);})();
|
|
1
|
+
"use strict";var SentientSnippet=(()=>{var fe=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var He=Object.prototype.hasOwnProperty;var Pe=(e,t)=>()=>(e&&(t=e(e=0)),t);var De=(e,t)=>{for(var n in t)fe(e,n,{get:t[n],enumerable:!0})},Xe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ve(t))!He.call(e,o)&&o!==n&&fe(e,o,{get:()=>t[o],enumerable:!(r=Fe(t,o))||r.enumerable});return e};var Qe=e=>Xe(fe({},"__esModule",{value:!0}),e);var Ze,et,tt,Te,nt,rt,Re,S,pe,Y=Pe(()=>{"use strict";Ze=Object.defineProperty,et=Object.defineProperties,tt=Object.getOwnPropertyDescriptors,Te=Object.getOwnPropertySymbols,nt=Object.prototype.hasOwnProperty,rt=Object.prototype.propertyIsEnumerable,Re=(e,t,n)=>t in e?Ze(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,S=(e,t)=>{for(var n in t||(t={}))nt.call(t,n)&&Re(e,n,t[n]);if(Te)for(var n of Te(t))rt.call(t,n)&&Re(e,n,t[n]);return e},pe=(e,t)=>et(e,tt(t))});var Me={};De(Me,{LOCAL_ENGINE_AVAILABLE:()=>ot,createLocalEngine:()=>st});function st(e){throw new Error("[sentient] createLocalEngine is not available in production builds. The local engine only exists under the `development` export condition.")}var ot,$e=Pe(()=>{"use strict";Y();ot=!1});var Ct={};De(Ct,{applyPersonaAttributes:()=>H,applySlotAttributes:()=>X,parseSnippetConfig:()=>ue,run:()=>Ye,version:()=>Rt});Y();function te(e){return Object.keys(e).sort().map(t=>`${t}=${e[t]}`).join("|")}function Ne(e){if(e.length===0)return null;let t={};for(let n of e.split("|")){let r=n.indexOf("=");if(r<=0||r!==n.lastIndexOf("=")||r===n.length-1)return null;let o=n.slice(0,r);if(o in t)return null;t[o]=n.slice(r+1)}return t}function ge(e){var t,n,r;if(e.arms)return typeof e.baseline=="string"?e.baseline:(t=e.arms[0])!=null?t:"";if(e.baseline!==void 0&&typeof e.baseline=="object")return te(e.baseline);if(typeof e.baseline=="string")return e.baseline;let o={};for(let[u,a]of Object.entries((n=e.dims)!=null?n:{}))o[u]=(r=a[0])!=null?r:"";return te(o)}function je(e,t){var n,r;return e.dims!=null?(r=(n=Ne(t))!=null?n:Ne(ge(e)))!=null?r:{}:t}function G(e){return e>=.3?e<.7?"medium":"high":"low"}var Ce=["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 me(e){return Le(e)!==null}function Le(e){var t;if(!e)return null;let n=e.toLowerCase();return(t=Ce.find(r=>n.includes(r.toLowerCase())))!=null?t:null}function he(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 ye(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(o){}let r=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(r)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(r)?"social":"referral"}catch(n){return"direct"}}function ve(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function be(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function ne(e){return S(S(S({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function re(e){let t=ne(e);return je(t,ge(t))}function we(e){return typeof e=="string"?e:te(e)}Y();var at="_snt_uid",W="_snt_uid";function it(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function lt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function ut(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(r){}}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 ft(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function pt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function gt(e){try{sessionStorage.removeItem(e)}catch(t){}}function mt(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 yt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var vt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Be(e){var t,n,r,o,u,a;if(typeof window=="undefined")return vt;let i=(t=e==null?void 0:e.cookieName)!=null?t:at,d=((n=e==null?void 0:e.cookieTTLDays)!=null?n:365)*24*60*60,c=(a=(u=(o=(r=lt(i))!=null?r:ct(W))!=null?o:ft(W))!=null?u:e==null?void 0:e.ssrSessionId)!=null?a:it();ut(i,c,d);let f=dt(W,c),m=mt(i),w=f?!1:pt(W,c),k=!f&&!m&&!w;return{getSessionId:()=>c,isEphemeral:()=>k,destroy:()=>{c=null,yt(i),ht(W),gt(W)}}}function Ge(e){return`_snt_retry_${e.slice(0,12)}`}var bt={push:()=>{},flush:()=>{},destroy:()=>{}};function wt(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let r=JSON.parse(n);return Array.isArray(r)?(localStorage.removeItem(t),r.slice(-e)):[]}catch(n){return[]}}function Se(e,t,n){try{let r=[...(()=>{try{let o=localStorage.getItem(n);if(!o)return[];let u=JSON.parse(o);return Array.isArray(u)?u:[]}catch(o){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(r))}catch(r){}}function St(e){var t,n,r;if(typeof window=="undefined")return bt;let o=(t=e.flushIntervalMs)!=null?t:5e3,u=(n=e.maxBatchSize)!=null?n:20,a=(r=e.maxRetrySize)!=null?r:100,i=e.ingestUrl,d=e.apiKey,c=Ge(d),f=[],m=new Set,w=[],k=p=>{for(let g of p)y.delete(g),!m.has(g)&&(m.add(g),w.push(g));for(;w.length>500;){let g=w.shift();g&&m.delete(g)}},y=new Set,j=p=>{m.has(p.id)||y.has(p.id)||(y.add(p.id),f.push(p))},K=wt(a,c);for(let p of K)j(p);let I=0,b=0,Q=p=>{if(p.length===0)return;let g=JSON.stringify(p),O=p.map(l=>l.id),D;try{D=fetch(i,{method:"POST",keepalive:!0,body:g,headers:{"Content-Type":"application/json",Authorization:`Bearer ${d}`}})}catch(l){Se(p,a,c);for(let h of O)y.delete(h);b++,I=Date.now()+Math.min(6e4,1e3*2**Math.min(b,6));return}let s=l=>{if(l.ok||l.status>=400&&l.status<500&&l.status!==429){k(O),b=0,I=0;return}Se(p,a,c);for(let h of O)y.delete(h);b++,I=Date.now()+Math.min(6e4,1e3*2**Math.min(b,6))};D instanceof Promise?D.then(s).catch(()=>{Se(p,a,c);for(let l of O)y.delete(l);b++,I=Date.now()+Math.min(6e4,1e3*2**Math.min(b,6))}):s(D)},Z=typeof TextEncoder!="undefined"?new TextEncoder:null,ee=p=>Z?Z.encode(p).length:p.length,E=p=>{let g=[],O=2;for(let D of p){let s=ee(JSON.stringify(D))+1;if(g.length>0&&O+s>57344||g.length>=u)break;g.push(D),O+=s}return g},P=()=>{try{if(Date.now()<I)return;for(;f.length>0;){let p=f.filter(O=>!m.has(O.id));if(f.length=0,p.length===0)break;let g=E(p);if(g.length===0)break;g.length<p.length&&f.push(...p.slice(g.length)),Q(g)}}catch(p){}},A=!0,v=null;v=setInterval(()=>{A&&P()},o);let J=()=>{document.visibilityState==="hidden"&&P()},M=()=>{P()};return document.addEventListener("visibilitychange",J),window.addEventListener("beforeunload",M),{push(p){j(p),f.length>=u&&P()},flush:P,destroy(){A=!1,v!==null&&(clearInterval(v),v=null),document.removeEventListener("visibilitychange",J),window.removeEventListener("beforeunload",M),P()}}}var Oe="_snt_asgn_";function oe(e,t){return`${e}:${t}`}function kt(e,t){return`${Oe}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ke(e){let t=e.slice(Oe.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(r){return null}}function ke(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(Oe)&&e.push(n)}return e}catch(e){return[]}}function It(e=18e5){let t=new Map,n=r=>r.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let r of ke())try{let o=localStorage.getItem(r);if(!o)continue;let u=JSON.parse(o);if(n(u)){localStorage.removeItem(r);continue}let a=Ke(r);if(!a)continue;t.set(oe(a.componentId,a.segment),u)}catch(o){}})(),{get(r,o){let u=t.get(oe(r,o));return u?n(u)?(t.delete(oe(r,o)),null):u:null},set(r,o,u){let a=oe(r,o);t.set(a,u);try{localStorage.setItem(kt(r,o),JSON.stringify(u))}catch(i){}},invalidate(r){let o=`${r}:`;for(let u of[...t.keys()])u.startsWith(o)&&t.delete(u);for(let u of ke()){let a=Ke(u);if((a==null?void 0:a.componentId)===r)try{localStorage.removeItem(u)}catch(i){}}},clear(){t.clear();for(let r of ke())try{localStorage.removeItem(r)}catch(o){}}}}var ie="_snt_snap:",At=["low","medium","high"];function le(e){try{let t=localStorage.getItem(ie+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!At.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"?null:n}catch(t){return null}}function V(e,t){try{localStorage.setItem(ie+e,JSON.stringify(t))}catch(n){}}var Ae="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",We="[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.",Ue=!1,se=!1;function Ot(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function xt(e){var t;let n=Be({ssrSessionId:e.ssrSessionId}),r=(t=n.getSessionId())!=null?t:"local",o=Ot(),u=Promise.resolve().then(()=>($e(),Me)).then(d=>{let c=d;return c.LOCAL_ENGINE_AVAILABLE?(Ue||(Ue=!0,console.info(We)),c):(se||(se=!0,console.error(Ae)),null)}).catch(()=>(se||(se=!0,console.error(Ae)),null)),a=null;function i(d){let c=document.documentElement;c.dataset.sentientPersona===void 0&&(c.dataset.sentientPersona=d.persona,c.dataset.sentientConfidence=G(d.confidence))}return{isLocal:!0,async decide(d){var c,f,m;let w=await u;if(!w)return null;let k=w.createLocalEngine({sessionId:r,forcedPersona:o}).decide(d);return a=pe(S({},k),{layoutOrder:(f=(c=k.layoutOrder)!=null?c:a==null?void 0:a.layoutOrder)!=null?f:null,slots:S(S({},(m=a==null?void 0:a.slots)!=null?m:{}),k.slots)}),V(e.apiKey||"local",{v:1,persona:a.persona,band:G(a.confidence),slots:a.slots,layoutOrder:a.layoutOrder,savedAt:Date.now()}),i(k),k},getSlotResult(d){var c,f,m;return(m=(f=a==null?void 0:a.slots[d])!=null?f:(c=e.initialSlots)==null?void 0:c[d])!=null?m:null},getPersona(){return a?{persona:a.persona,confidence:a.confidence,band:G(a.confidence)}:null},async assign(d,c){var f;let m=await u;return!m||!c||c.length===0?c!=null&&c[0]?{variantId:c[0],assignmentTtlMs:0}:null:{variantId:(f=m.createLocalEngine({sessionId:r,forcedPersona:o}).decide({components:[{id:d,variantIds:c}]}).assignments[d])!=null?f:c[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>n.destroy()}}var Je="https://api.sentient-ui.com/v1/events",ae=new Map,_t=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 F={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function Et(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,r]of t)n.startsWith("utm_")&&(e[n]=r);return e}catch(e){return{}}}function qe(e){return e.replace(/\/events\/?$/,"")}function ze(){return[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(e=>e==="1"||e==="yes")}function Pt(e){var t;let n=qe((t=e.ingestUrl)!=null?t:Je),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},o={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(i,d,c){try{let f=new URLSearchParams({componentId:i});for(let w of d!=null?d:[])f.append("variantIds[]",w);let m=await fetch(`${n}/winner?${f.toString()}`,{headers:r});return m.ok?{variantId:(await m.json()).variantId,assignmentTtlMs:0}:d!=null&&d[0]?{variantId:d[0],assignmentTtlMs:0}:null}catch(f){return d!=null&&d[0]?{variantId:d[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},u={track:i=>o.track(i),goal:(i,d,c,f)=>o.goal(i,d,c,f),componentGoal:(i,d,c)=>o.componentGoal(i,d,c),identify:i=>o.identify(i),getAssignment:(i,d)=>o.getAssignment(i,d),assign:(i,d,c,f)=>o.assign(i,d,c,f),decide:i=>o.decide(i),getSlotResult:i=>o.getSlotResult(i),getPersona:()=>o.getPersona(),fetchWeights:()=>o.fetchWeights(),getGraph:()=>o.getGraph(),dispose:()=>o.dispose(),destroy:()=>o.destroy()};function a(i){o=i}return{proxy:u,setInner:a}}function xe(e){var t,n,r,o,u,a,i,d,c;if(typeof window=="undefined")return F;_t=e.apiKey;let f=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!f&&e.localMode!==!1)return ae.set(e.apiKey||"local",{config:e,upgrade:null}),xt(e);let m=e.respectDoNotTrack!==!1&&ze();if(e.consent===!1||m){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."),F;let{proxy:s,setInner:l}=Pt(e);return ae.set(e.apiKey,{config:e,upgrade:m?null:l}),s}return ae.set(e.apiKey,{config:e,upgrade:null}),F}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."),F;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),F;let w=(t=e.ingestUrl)!=null?t:Je,k=Date.now(),y=Be({ssrSessionId:e.ssrSessionId}),j=It(),K=St({ingestUrl:w,apiKey:e.apiKey}),I=qe(w),b={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},Q=he((n=navigator.userAgent)!=null?n:""),Z=typeof window!="undefined"?window.location.origin:void 0,ee=ye((r=document.referrer)!=null?r:"",Z),E=(o=e.sessionSegment)!=null?o:`${Q}:${ee}`,P=new Map,A=new Map,v=null,J=s=>{for(let l of s)A.has(l.id)||A.set(l.id,re(l))};if(e.initialSlots)for(let[s,l]of Object.entries(e.initialSlots))A.set(s,l);let M=le(e.apiKey);if(M)for(let[s,l]of Object.entries(M.slots))A.has(s)||A.set(s,l);let p={low:.15,medium:.5,high:.85};if(e.initialPersona)v=S({},e.initialPersona);else{let s=document.documentElement.dataset;s.sentientPersona?v={persona:s.sentientPersona,confidence:(a=p[(u=s.sentientConfidence)!=null?u:"low"])!=null?a:.15}:M&&(v={persona:M.persona,confidence:(i=p[M.band])!=null?i:.15})}if(e.initialAssignments)for(let[s,l]of Object.entries(e.initialAssignments))j.set(s,E,{variantId:l,assignedAt:Date.now(),segment:E,confidence:1});let g=Promise.resolve(),O=y.getSessionId();if(O){let s=ve((d=document.referrer)!=null?d:""),l=S(S({sessionId:O,deviceClass:Q,trafficSource:ee,referrerDomain:s,utmParams:Et(),timeOfDay:be(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:y.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||me((c=navigator.userAgent)!=null?c:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{g=fetch(`${I}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(l),headers:b}).then(h=>{h.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(h){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:K});let D={goal(s,l={},h=1,T=0){let _=y.getSessionId();if(!_)return;let x=Ie();g.then(()=>{fetch(`${I}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:_,name:s,metadata:l,weight:h,stepIndex:T,goalId:x}),headers:b}).catch(()=>{})})},componentGoal(s,l,h){var T,_,x;let $=y.getSessionId();if(!$)return;let R=j.get(s,E),N=R?null:(T=A.get(s))!=null?T:null;if(!R&&N===null){e.debug&&console.warn(`[sentient] componentGoal("${s}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let U=R?R.variantId:we(N),C={id:Ie(),sessionId:$,projectId:e.apiKey,componentId:s,variantId:U,eventType:"goal_achieved",goalType:l,payload:S({reward:(_=h==null?void 0:h.reward)!=null?_:1},(x=h==null?void 0:h.metadata)!=null?x:{}),timestamp:Date.now(),timeInSession:Date.now()-k};e.debug&&console.log("[sentient] componentGoal",C),g.then(()=>K.push(C))},identify(s){let l=y.getSessionId();l&&g.then(()=>{fetch(`${I}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:l,userId:s,ephemeral:y.isEphemeral()}),headers:b}).catch(()=>{})})},track(s){let l=y.getSessionId();if(!l)return;let h=pe(S({},s),{id:Ie(),sessionId:l,timestamp:Date.now(),timeInSession:Date.now()-k});e.debug&&console.log("[sentient] track",h),g.then(()=>K.push(h))},getAssignment(s,l){return j.get(s,l)},async assign(s,l,h,T){let _=y.getSessionId();if(!_)return null;let x=j.get(s,E);if(x&&(l!=null&&l.length||x.content!==void 0))return{variantId:x.variantId,assignmentTtlMs:0,content:x.content};let $=P.get(s);if($)return $;let R=(async()=>{await g;try{let N={sessionId:_,componentId:s,variantIds:l};T!==void 0?N.agentDataByVariant=T:h!==void 0&&(N.agentData=h);let U=await fetch(`${I}/assign`,{method:"POST",body:JSON.stringify(N),headers:b});if(!U.ok)return null;let C=await U.json();return j.set(s,E,{variantId:C.variantId,assignedAt:Date.now(),segment:E,confidence:1,content:C.content}),C}catch(N){return null}finally{P.delete(s)}})();return P.set(s,R),R},async decide(s){var l,h,T,_,x,$,R,N,U,C;let _e=y.getSessionId();if(!_e)return null;let q=(l=s.slots)!=null?l:[];await g;try{let z={sessionId:_e};s.sections&&s.sections.length>0&&(z.sections=s.sections.map(L=>({id:L}))),z.components=(h=s.components)!=null?h:[],q.length>0&&(z.slots=q.map(ne));let Ee=await fetch(`${I}/decide`,{method:"POST",body:JSON.stringify(z),headers:b});if(!Ee.ok)return J(q),null;let B=await Ee.json(),ce={};for(let L of q)ce[L.id]=(_=(T=B.slots)==null?void 0:T[L.id])!=null?_:re(L);for(let[L,de]of Object.entries(ce))A.set(L,de);v={persona:(x=B.persona)!=null?x:"unknown",confidence:($=B.confidence)!=null?$:0};for(let[L,de]of Object.entries((R=B.assignments)!=null?R:{}))j.set(L,E,{variantId:de,assignedAt:Date.now(),segment:E,confidence:1});return V(e.apiKey,{v:1,persona:v.persona,band:G(v.confidence),slots:Object.fromEntries(A),layoutOrder:(N=B.layoutOrder)!=null?N:null,savedAt:Date.now()}),{layoutOrder:(U=B.layoutOrder)!=null?U:null,assignments:(C=B.assignments)!=null?C:{},slots:ce,persona:v.persona,confidence:v.confidence}}catch(z){return J(q),null}},getSlotResult(s){var l;return(l=A.get(s))!=null?l:null},getPersona(){return v?{persona:v.persona,confidence:v.confidence,band:G(v.confidence)}:null},async fetchWeights(){var s;try{let l=await fetch(`${I}/weights`,{headers:b});return l.ok?(s=(await l.json()).components)!=null?s:[]:[]}catch(l){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){K.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){K.destroy(),y.destroy();try{localStorage.removeItem(ie+e.apiKey),localStorage.removeItem(Ge(e.apiKey))}catch(s){}e.debug&&console.log("[sentient] destroyed")}};if(ae.set(e.apiKey,{config:e,upgrade:null}),e.debug){let s=window;s.__sentient&&(s.__sentient.client=D)}return D}Y();var Dt=["landing","ecommerce","saas","marketplace"];function Tt(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=Object.entries(e);if(t.length<1||t.length>4)return null;let n={};for(let[r,o]of t){if(!Array.isArray(o)||o.length<2||o.length>6||!o.every(u=>typeof u=="string"))return null;n[r]=o}return n}function ue(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.apiKey!="string"||!t.apiKey.startsWith("pk_"))return null;let n=Dt.includes(t.context)?t.context:"landing",r={};if(typeof t.slots=="object"&&t.slots!==null&&!Array.isArray(t.slots))for(let[o,u]of Object.entries(t.slots)){if(typeof u!="object"||u===null)continue;let a=u,i=Tt(a.dims);i&&(a.target!==void 0&&typeof a.target!="string"||(r[o]=a.target===void 0?{dims:i}:{dims:i,target:a.target}))}return{apiKey:t.apiKey,context:n,personaAttributes:t.personaAttributes===!0,slots:r}}function H(e,t,n){n.documentElement.setAttribute("data-sentient-persona",e),n.documentElement.setAttribute("data-sentient-confidence",t)}function X(e,t,n){var r;for(let[o,u]of Object.entries(t)){let a=e[o];if(!a||typeof a=="string")continue;let i=u.target?Array.from(n.querySelectorAll(u.target)):[n.documentElement];for(let d of i)for(let[c,f]of Object.entries(a))(r=u.dims[c])!=null&&r.includes(f)&&d.setAttribute(`data-${c}`,f)}}var Rt="0.2.1",Nt=5e3;function jt(e,t){return Promise.race([e,new Promise(n=>setTimeout(()=>n(null),t))])}async function Ye(){var e,t;try{let n=ue(window.sentient);if(!n)return;let r=le(n.apiKey);r&&(n.personaAttributes&&H(r.persona,r.band,document),X(r.slots,n.slots,document));let o=xe({apiKey:n.apiKey,context:n.context}),u=Object.entries(n.slots).map(([d,c])=>({id:d,dims:c.dims})),a=await jt(o.decide({slots:u}),Nt);if(!a)return;let i=o.getPersona();n.personaAttributes&&i&&H(i.persona,i.band,document),X(a.slots,n.slots,document),V(n.apiKey,{v:1,persona:(e=i==null?void 0:i.persona)!=null?e:a.persona,band:(t=i==null?void 0:i.band)!=null?t:"low",slots:a.slots,layoutOrder:a.layoutOrder,savedAt:Date.now()})}catch(n){}}typeof window!="undefined"&&window.sentient&&Ye();return Qe(Ct);})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sentientui/snippet",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "SentientUI Style-rung snippet for non-React sites — persona attributes and adaptive style tokens from one script tag",
|
|
6
6
|
"type": "module",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"tsx": "^4.19.2",
|
|
17
17
|
"typescript": "^5.7.2",
|
|
18
18
|
"vitest": "^2.1.8",
|
|
19
|
-
"@sentientui/core": "0.
|
|
19
|
+
"@sentientui/core": "0.12.0"
|
|
20
20
|
},
|
|
21
21
|
"scripts": {
|
|
22
22
|
"build": "tsup",
|