@sentientui/snippet 0.2.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/README.md ADDED
@@ -0,0 +1,38 @@
1
+ # @sentientui/snippet
2
+
3
+ Style-rung [SentientUI](https://sentient-ui.com) for sites that are not built with React.
4
+ One script tag: visitor-type attributes on `<html>` plus learned `data-*` style tokens on the
5
+ elements you declare. Plain CSS does the rest. No DOM reordering, ever; if anything fails, your
6
+ page is left exactly as it was.
7
+
8
+ ```html
9
+ <script>
10
+ window.sentient = {
11
+ apiKey: 'pk_your_key', // sentient-ui.com → Settings
12
+ context: 'landing', // 'landing' | 'ecommerce' | 'saas' | 'marketplace'
13
+ personaAttributes: true, // sets data-sentient-persona / -confidence on <html>
14
+ slots: {
15
+ hero: { dims: { tone: ['calm', 'urgent'] }, target: '#hero' },
16
+ },
17
+ };
18
+ </script>
19
+ <script
20
+ src="https://unpkg.com/@sentientui/snippet@0.1.0/dist/snippet.global.js"
21
+ defer
22
+ crossorigin="anonymous"
23
+ integrity="sha384-REPLACE_WITH_RELEASE_HASH"
24
+ ></script>
25
+ ```
26
+
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` (each release's hash
29
+ is included in the release notes). Or self-host the file and skip the CDN entirely.
30
+
31
+ ```css
32
+ #hero[data-tone='urgent'] .cta { font-weight: 700; }
33
+ html[data-sentient-persona='deal_seeker'] .discount-banner { display: block; }
34
+ ```
35
+
36
+ The first value of each dim is your baseline (what you show today). Decisions are locked per
37
+ session and learned per visitor type on the SentientUI API: Visit 1 learns, Visit 2 converts.
38
+ Bundle ≤ 15 KB gzip. MIT.
@@ -0,0 +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);})();
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@sentientui/snippet",
3
+ "version": "0.2.0",
4
+ "private": false,
5
+ "description": "SentientUI Style-rung snippet for non-React sites — persona attributes and adaptive style tokens from one script tag",
6
+ "type": "module",
7
+ "main": "./dist/snippet.global.js",
8
+ "files": [
9
+ "dist",
10
+ "README.md"
11
+ ],
12
+ "devDependencies": {
13
+ "@types/node": "^22.10.2",
14
+ "jsdom": "^25.0.1",
15
+ "tsup": "^8.3.5",
16
+ "tsx": "^4.19.2",
17
+ "typescript": "^5.7.2",
18
+ "vitest": "^2.1.8",
19
+ "@sentientui/core": "0.11.0"
20
+ },
21
+ "scripts": {
22
+ "build": "tsup",
23
+ "test": "vitest run",
24
+ "typecheck": "tsc --noEmit",
25
+ "size-check": "tsx scripts/size-check.ts",
26
+ "lint": "eslint src"
27
+ }
28
+ }