@sentientui/core 0.9.1 → 0.11.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 +57 -0
- package/dist/chunk-HGGX55FR.mjs +1 -0
- package/dist/chunk-SVYHTU5Z.mjs +1 -0
- package/dist/chunk-X2URHWFL.mjs +1 -0
- package/dist/index-graph.d.cts +2 -1
- package/dist/index-graph.d.ts +2 -1
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index-local-stub.d.cts +13 -0
- package/dist/index-local-stub.d.ts +13 -0
- package/dist/index-local-stub.js +1 -0
- package/dist/index-local-stub.mjs +1 -0
- package/dist/index-local.d.cts +30 -0
- package/dist/index-local.d.ts +30 -0
- package/dist/index-local.js +1 -0
- package/dist/index-local.mjs +1 -0
- package/dist/index-server.d.cts +14 -6
- package/dist/index-server.d.ts +14 -6
- package/dist/index-server.js +1 -1
- package/dist/index-server.mjs +1 -1
- package/dist/index.d.cts +96 -2
- package/dist/index.d.ts +96 -2
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{session-meta-D5IgJuRW.d.cts → session-meta-DU_3mY7U.d.cts} +32 -1
- package/dist/{session-meta-D5IgJuRW.d.ts → session-meta-DU_3mY7U.d.ts} +32 -1
- package/llms.txt +46 -0
- package/package.json +22 -3
- package/dist/chunk-6PD6FNO7.mjs +0 -1
- package/dist/chunk-CFXMEZCZ.mjs +0 -1
package/README.md
CHANGED
|
@@ -48,6 +48,9 @@ client.goal('trial_started', { plan: 'pro' });
|
|
|
48
48
|
| `sessionSegment` | `string` | Segment from SSR (`device:source`). Must match the value used in `preloadAssignments`. |
|
|
49
49
|
| `userId` | `string` | Optional cross-session identity. Persists portraits across sessions for the same user. |
|
|
50
50
|
| `debug` | `boolean` | Logs events to the console and exposes `window.__sentient`. |
|
|
51
|
+
| `localMode` | `'auto' \| boolean` | Keyless local engine. `'auto'` (default) enables it only under the `development` export condition; production builds without a key short-circuit to defaults with one `console.error`. |
|
|
52
|
+
| `initialSlots` | `Record<string, string \| Record<string, string>>` | SSR-preloaded slot results (from `preloadDecisions`/`loadAdaptiveDecision`). |
|
|
53
|
+
| `initialPersona` | `{ persona: string; confidence: number }` | SSR-preloaded persona, so client and server agree on first paint. |
|
|
51
54
|
|
|
52
55
|
### `client.assign(componentId, variantIds?)` → `Promise<AssignResult | null>`
|
|
53
56
|
|
|
@@ -133,6 +136,60 @@ Pass `initialAssignments` and the same `sessionSegment` to `init()` on the clien
|
|
|
133
136
|
|
|
134
137
|
For pages with a section layout, use `preloadDecisions` instead — same options, plus a `sections: string[]` request field. The return value carries both `assignments` and `layoutOrder`.
|
|
135
138
|
|
|
139
|
+
## decide() — slots, layout, and persona in one call
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
const outcome = await client.decide({
|
|
143
|
+
sections: ['hero', 'pricing', 'faq'], // optional page-order request
|
|
144
|
+
slots: [
|
|
145
|
+
{ id: 'hero', dims: { tone: ['calm', 'urgent'] } }, // token slot (first value = baseline)
|
|
146
|
+
{ id: 'pricing-area', arms: ['standard', 'social_first'] } // enumerated slot
|
|
147
|
+
],
|
|
148
|
+
});
|
|
149
|
+
// outcome: {
|
|
150
|
+
// layoutOrder: string[] | null,
|
|
151
|
+
// assignments: Record<string, string>,
|
|
152
|
+
// slots: { hero: { tone: 'urgent' }, 'pricing-area': 'social_first' },
|
|
153
|
+
// persona: 'buyer', confidence: 0.8,
|
|
154
|
+
// }
|
|
155
|
+
client.getSlotResult('hero'); // sync read of a decided slot
|
|
156
|
+
client.getPersona(); // { persona, confidence, band: 'low' | 'medium' | 'high' }
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Decisions are locked per session. Apply dims results as `data-<dim>` attributes and style them
|
|
160
|
+
with CSS. At least one of `sections` / `components` / `slots` must be present.
|
|
161
|
+
|
|
162
|
+
## Decision snapshot (pre-paint on return visits)
|
|
163
|
+
|
|
164
|
+
Every decide writes a snapshot (persona, confidence band, slot results, layout order) to
|
|
165
|
+
localStorage under `_snt_snap:<apiKey>`. On the next visit, apply it before paint:
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
import { readSnapshot, writeSnapshot, renderPrePaintScript } from '@sentientui/core';
|
|
169
|
+
|
|
170
|
+
// In your HTML head (server-rendered), inline this script to apply the snapshot pre-paint:
|
|
171
|
+
const inline = renderPrePaintScript('pk_your_key');
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
First visit renders your baseline; the return visit adapts with zero flicker — Visit 1 learns,
|
|
175
|
+
Visit 2 converts.
|
|
176
|
+
|
|
177
|
+
## Keyless local mode
|
|
178
|
+
|
|
179
|
+
Without a valid `pk_…` key, development builds simulate decisions locally — deterministic per
|
|
180
|
+
session, zero network — via the separate entry `@sentientui/core/local`:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
import { createLocalEngine } from '@sentientui/core/local';
|
|
184
|
+
|
|
185
|
+
const engine = createLocalEngine({ sessionId, forcedPersona: 'deal_seeker' });
|
|
186
|
+
const outcome = engine.decide({ slots: [{ id: 'hero', dims: { tone: ['calm', 'urgent'] } }] });
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
The local engine ships behind `development`/`production` export conditions — production bundles
|
|
190
|
+
physically contain none of it. Production without a key short-circuits to defaults and logs one
|
|
191
|
+
`console.error` per page. Force personas with `?sentient_persona=`.
|
|
192
|
+
|
|
136
193
|
## Optional: graph mode
|
|
137
194
|
|
|
138
195
|
`@sentientui/core/graph` is a separate, tree-shakable entry that activates the DOM scanner and graph sync (component-to-component edges + 2-hop reward propagation). Import it once, on the client, after `init()`:
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f=Object.defineProperty,g=Object.defineProperties;var h=Object.getOwnPropertyDescriptors;var d=Object.getOwnPropertySymbols;var i=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable;var e=(c,a,b)=>a in c?f(c,a,{enumerable:!0,configurable:!0,writable:!0,value:b}):c[a]=b,k=(c,a)=>{for(var b in a||(a={}))i.call(a,b)&&e(c,b,a[b]);if(d)for(var b of d(a))j.call(a,b)&&e(c,b,a[b]);return c},l=(c,a)=>g(c,h(a));export{k as a,l as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as i}from"./chunk-HGGX55FR.mjs";var f=["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 m(t){return b(t)!==null}function b(t){var r;if(!t)return null;let e=t.toLowerCase();return(r=f.find(n=>e.includes(n.toLowerCase())))!=null?r:null}function y(t){let e=t.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(e)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(e)?"mobile":"desktop"}function S(t,e){if(!t)return"direct";try{let r=new URL(t);if(e)try{if(new URL(e).host===r.host)return"direct"}catch(o){}let n=r.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(n)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(n)?"social":"referral"}catch(r){return"direct"}}function h(t){if(!t)return null;try{return new URL(t).hostname}catch(e){return null}}function x(t){let e=t.getHours();return e<6?"night":e<12?"morning":e<18?"afternoon":"evening"}function O(t){let e=p("__segment__",t);return`${e.deviceClass}:${e.trafficSource}`}function p(t,e){var s,a,l,u,c,g,d;let r=(a=(s=e==null?void 0:e.userAgent)==null?void 0:s.trim())!=null?a:"",n=(u=(l=e==null?void 0:e.referer)==null?void 0:l.trim())!=null?u:"",o=(c=e==null?void 0:e.now)!=null?c:new Date;return{sessionId:t,ephemeral:!1,utmParams:(g=e==null?void 0:e.utmParams)!=null?g:{},deviceClass:r?y(r):"desktop",trafficSource:n?S(n,e==null?void 0:e.appOrigin):"direct",referrerDomain:h(n),timeOfDay:x(o),dayOfWeek:(d=["sun","mon","tue","wed","thu","fri","sat"][o.getDay()])!=null?d:"sun",automation:(e==null?void 0:e.webdriver)===!0||m(r)}}import{canonicalArm as R,slotBaselineArm as D,slotResultFor as w}from"@sentientui/policy";function C(t){return i(i(i({id:t.id},t.arms?{arms:[...t.arms]}:{}),t.dims?{dims:Object.fromEntries(Object.entries(t.dims).map(([e,r])=>[e,[...r]]))}:{}),t.baseline!==void 0?{baseline:t.baseline}:{})}function k(t){let e=C(t);return w(e,D(e))}function A(t){let e={};for(let r of t)e[r.id]=k(r);return e}function v(t){return typeof t=="string"?t:R(t)}export{f as a,m as b,b as c,y as d,S as e,h as f,x as g,O as h,p as i,C as j,k,A as l,v as m};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as re,d as ie,e as ae,f as le,g as ce,j as de,k as X,m as ue}from"./chunk-SVYHTU5Z.mjs";import{a as k,b as K}from"./chunk-HGGX55FR.mjs";var Pe="_snt_uid";var G="_snt_uid";function Le(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function Ne(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Me(e,t,r){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${r}; SameSite=strict; path=/`}catch(d){}}function Ue(e){try{return localStorage.getItem(e)}catch(t){return null}}function Ke(e,t){try{return localStorage.setItem(e,t),!0}catch(r){return!1}}function Ge(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function $e(e,t){try{return sessionStorage.setItem(e,t),!0}catch(r){return!1}}function Be(e){try{sessionStorage.removeItem(e)}catch(t){}}function We(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function je(e){try{localStorage.removeItem(e)}catch(t){}}function Fe(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Je={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Z(e){var a,g,m,S,h,w;if(typeof window=="undefined")return Je;let t=(a=e==null?void 0:e.cookieName)!=null?a:Pe,d=((g=e==null?void 0:e.cookieTTLDays)!=null?g:365)*24*60*60,u=(w=(h=(S=(m=Ne(t))!=null?m:Ue(G))!=null?S:Ge(G))!=null?h:e==null?void 0:e.ssrSessionId)!=null?w:Le();Me(t,u,d);let n=Ke(G,u),c=We(t),o=n?!1:$e(G,u),s=!n&&!c&&!o;return{getSessionId:()=>u,isEphemeral:()=>s,destroy:()=>{u=null,Fe(t),je(G),Be(G)}}}var Qe={push:()=>{},flush:()=>{},destroy:()=>{}};function Ye(e,t){try{let r=localStorage.getItem(t);if(!r)return[];let d=JSON.parse(r);return Array.isArray(d)?(localStorage.removeItem(t),d.slice(-e)):[]}catch(r){return[]}}function ge(e,t,r){try{let u=[...(()=>{try{let n=localStorage.getItem(r);if(!n)return[];let c=JSON.parse(n);return Array.isArray(c)?c:[]}catch(n){return[]}})(),...e].slice(-t);localStorage.setItem(r,JSON.stringify(u))}catch(d){}}function be(e){var J,Q,Y;if(typeof window=="undefined")return Qe;let t=(J=e.flushIntervalMs)!=null?J:5e3,r=(Q=e.maxBatchSize)!=null?Q:20,d=(Y=e.maxRetrySize)!=null?Y:100,u=e.ingestUrl,n=e.apiKey,c=`_snt_retry_${n.slice(0,12)}`,o=[],s=new Set,a=[],g=p=>{for(let y of p)m.delete(y),!s.has(y)&&(s.add(y),a.push(y));for(;a.length>500;){let y=a.shift();y&&s.delete(y)}},m=new Set,S=p=>{s.has(p.id)||m.has(p.id)||(m.add(p.id),o.push(p))},h=Ye(d,c);for(let p of h)S(p);let w=0,v=0,E=p=>{if(p.length===0)return;let y=JSON.stringify(p),_=p.map(l=>l.id),A;try{A=fetch(u,{method:"POST",keepalive:!0,body:y,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})}catch(l){ge(p,d,c);for(let f of _)m.delete(f);v++,w=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6));return}let i=l=>{if(l.ok||l.status>=400&&l.status<500&&l.status!==429){g(_),v=0,w=0;return}ge(p,d,c);for(let f of _)m.delete(f);v++,w=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};A instanceof Promise?A.then(i).catch(()=>{ge(p,d,c);for(let l of _)m.delete(l);v++,w=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):i(A)},B=typeof TextEncoder!="undefined"?new TextEncoder:null,L=p=>B?B.encode(p).length:p.length,q=p=>{let y=[],_=2;for(let A of p){let i=L(JSON.stringify(A))+1;if(y.length>0&&_+i>57344||y.length>=r)break;y.push(A),_+=i}return y},b=()=>{try{if(Date.now()<w)return;for(;o.length>0;){let p=o.filter(_=>!s.has(_.id));if(o.length=0,p.length===0)break;let y=q(p);if(y.length===0)break;y.length<p.length&&o.push(...p.slice(y.length)),E(y)}}catch(p){}},W=!0,N=null;N=setInterval(()=>{W&&b()},t);let j=()=>{document.visibilityState==="hidden"&&b()},F=()=>{b()};return document.addEventListener("visibilitychange",j),window.addEventListener("beforeunload",F),{push(p){S(p),o.length>=r&&b()},flush:b,destroy(){W=!1,N!==null&&(clearInterval(N),N=null),document.removeEventListener("visibilitychange",j),window.removeEventListener("beforeunload",F),b()}}}var fe="_snt_asgn_";function ee(e,t){return`${e}:${t}`}function Ve(e,t){return`${fe}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ie(e){let t=e.slice(fe.length),r=t.indexOf(":");if(r<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,r)),segment:decodeURIComponent(t.slice(r+1))}}catch(d){return null}}function pe(){try{let e=[];for(let t=0;t<localStorage.length;t++){let r=localStorage.key(t);r!=null&&r.startsWith(fe)&&e.push(r)}return e}catch(e){return[]}}function _e(e=18e5){let t=new Map,r=u=>u.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let u of pe())try{let n=localStorage.getItem(u);if(!n)continue;let c=JSON.parse(n);if(r(c)){localStorage.removeItem(u);continue}let o=Ie(u);if(!o)continue;t.set(ee(o.componentId,o.segment),c)}catch(n){}})(),{get(u,n){let c=t.get(ee(u,n));return c?r(c)?(t.delete(ee(u,n)),null):c:null},set(u,n,c){let o=ee(u,n);t.set(o,c);try{localStorage.setItem(Ve(u,n),JSON.stringify(c))}catch(s){}},invalidate(u){let n=`${u}:`;for(let c of[...t.keys()])c.startsWith(n)&&t.delete(c);for(let c of pe()){let o=Ie(c);if((o==null?void 0:o.componentId)===u)try{localStorage.removeItem(c)}catch(s){}}},clear(){t.clear();for(let u of pe())try{localStorage.removeItem(u)}catch(n){}}}}var te="_snt_snap:",ze=["low","medium","high"];function me(e){try{let t=localStorage.getItem(te+e);if(!t)return null;let r=JSON.parse(t);return!r||typeof r!="object"||r.v!==1||typeof r.persona!="string"||typeof r.band!="string"||!ze.includes(r.band)||typeof r.slots!="object"||r.slots===null||Array.isArray(r.slots)||!(r.layoutOrder===null||Array.isArray(r.layoutOrder))||typeof r.savedAt!="number"?null:r}catch(t){return null}}function z(e,t){try{localStorage.setItem(te+e,JSON.stringify(t))}catch(r){}}function He(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(te+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}import{confidenceBand as Re}from"@sentientui/policy";import{confidenceBand as ye}from"@sentientui/policy";var he="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",ke="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",xe=!1,ne=!1;function qe(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Ae(e){var o;let t=Z({ssrSessionId:e.ssrSessionId}),r=(o=t.getSessionId())!=null?o:"local",d=qe(),u=import("@sentientui/core/local").then(s=>{let a=s;return a.LOCAL_ENGINE_AVAILABLE?(xe||(xe=!0,console.info(ke)),a):(ne||(ne=!0,console.error(he)),null)}).catch(()=>(ne||(ne=!0,console.error(he)),null)),n=null;function c(s){let a=document.documentElement;a.dataset.sentientPersona===void 0&&(a.dataset.sentientPersona=s.persona,a.dataset.sentientConfidence=ye(s.confidence))}return{isLocal:!0,async decide(s){var m,S,h;let a=await u;if(!a)return null;let g=a.createLocalEngine({sessionId:r,forcedPersona:d}).decide(s);return n=K(k({},g),{layoutOrder:(S=(m=g.layoutOrder)!=null?m:n==null?void 0:n.layoutOrder)!=null?S:null,slots:k(k({},(h=n==null?void 0:n.slots)!=null?h:{}),g.slots)}),z(e.apiKey||"local",{v:1,persona:n.persona,band:ye(n.confidence),slots:n.slots,layoutOrder:n.layoutOrder,savedAt:Date.now()}),c(g),g},getSlotResult(s){var a,g,m;return(m=(g=n==null?void 0:n.slots[s])!=null?g:(a=e.initialSlots)==null?void 0:a[s])!=null?m:null},getPersona(){return n?{persona:n.persona,confidence:n.confidence,band:ye(n.confidence)}:null},async assign(s,a){var S;let g=await u;return!g||!a||a.length===0?a!=null&&a[0]?{variantId:a[0],assignmentTtlMs:0}:null:{variantId:(S=g.createLocalEngine({sessionId:r,forcedPersona:d}).decide({components:[{id:s,variantIds:a}]}).assignments[s])!=null?S:a[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>t.destroy()}}function Xe(e,t,r){var u;let d=[];{let o=!1,s=[],a=()=>{if(o)return;let g=Date.now();for(s.push(g);s.length>0&&g-s[0]>500;)s.shift();s.length>=3&&(o=!0,e("rage_click"))};t.addEventListener("click",a),d.push(()=>t.removeEventListener("click",a))}{let n=!1,c=o=>{if(n||!(o.target instanceof Node)||!t.contains(o.target)&&t!==o.target)return;n=!0;let s=typeof window!="undefined"?window.getSelection():null,a=s?s.toString().length:0;e("text_copy",{selectionLength:a})};document.addEventListener("copy",c),d.push(()=>document.removeEventListener("copy",c))}{let n=!1,c=!1,o=null,s=()=>{o!==null&&(clearTimeout(o),o=null)},a=()=>{n||!c||(s(),o=setTimeout(()=>{!n&&c&&(n=!0,e("scroll_hesitation"))},3e3))},g=()=>{s(),a()},m=h=>{for(let w of h)c=w.intersectionRatio>.3,c?a():s()};typeof process!="undefined"&&((u=process.env)==null?void 0:u.NODE_ENV)!=="production"&&(window.__lastIOCallback=m);let S=new IntersectionObserver(m,{threshold:[.3]});S.observe(t),window.addEventListener("scroll",g,{passive:!0}),d.push(()=>{S.disconnect(),window.removeEventListener("scroll",g),s()})}{let n=!1,c=r!=null?r:Date.now(),o=()=>{if(n||document.visibilityState!=="hidden")return;let s=Date.now()-c;s<15e3&&(n=!0,e("tab_loss",{timeOnPage:s}))};document.addEventListener("visibilitychange",o),d.push(()=>document.removeEventListener("visibilitychange",o))}return()=>{for(let n of d)n()}}var De="https://api.sentient-ui.com/v1/events",$=new Map,Oe=null;function Se(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var H={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Ze(){try{let e={},t=new URLSearchParams(window.location.search);for(let[r,d]of t)r.startsWith("utm_")&&(e[r]=d);return e}catch(e){return{}}}function Te(e){return e.replace(/\/events\/?$/,"")}function Ce(){return[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function _t(e){if(typeof window=="undefined")return;let t=e!=null?e:Oe;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let r=$.get(t);if(!r){console.warn("[sentient] grantConsent() called before init()");return}let{config:d,upgrade:u}=r;if(!u||d.respectDoNotTrack!==!1&&Ce())return;let n=tt(K(k({},d),{consent:!0}));u(n),$.set(t,{config:K(k({},d),{consent:!0}),upgrade:null})}function et(e){var c;let t=Te((c=e.ingestUrl)!=null?c:De),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(o,s,a){try{let g=new URLSearchParams({componentId:o});for(let h of s!=null?s:[])g.append("variantIds[]",h);let m=await fetch(`${t}/winner?${g.toString()}`,{headers:r});return m.ok?{variantId:(await m.json()).variantId,assignmentTtlMs:0}:s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}catch(g){return s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}},u={track:o=>d.track(o),goal:(o,s,a,g)=>d.goal(o,s,a,g),componentGoal:(o,s,a)=>d.componentGoal(o,s,a),identify:o=>d.identify(o),getAssignment:(o,s)=>d.getAssignment(o,s),assign:(o,s,a,g)=>d.assign(o,s,a,g),decide:o=>d.decide(o),getSlotResult:o=>d.getSlotResult(o),getPersona:()=>d.getPersona(),fetchWeights:()=>d.fetchWeights(),getGraph:()=>d.getGraph(),destroy:()=>d.destroy()};function n(o){d=o}return{proxy:u,setInner:n}}function tt(e){var j,F,J,Q,Y,p,y,_,A;if(typeof window=="undefined")return H;Oe=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return $.set(e.apiKey||"local",{config:e,upgrade:null}),Ae(e);let r=e.respectDoNotTrack!==!1&&Ce();if(e.consent===!1||r){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),H;let{proxy:i,setInner:l}=et(e);return $.set(e.apiKey,{config:e,upgrade:r?null:l}),i}return $.set(e.apiKey,{config:e,upgrade:null}),H}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),H;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),H;let d=(j=e.ingestUrl)!=null?j:De,u=Date.now(),n=Z({ssrSessionId:e.ssrSessionId}),c=_e(),o=be({ingestUrl:d,apiKey:e.apiKey}),s=Te(d),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=ie((F=navigator.userAgent)!=null?F:""),m=typeof window!="undefined"?window.location.origin:void 0,S=ae((J=document.referrer)!=null?J:"",m),h=(Q=e.sessionSegment)!=null?Q:`${g}:${S}`,w=new Map,v=new Map,E=null,B=i=>{for(let l of i)v.has(l.id)||v.set(l.id,X(l))};if(e.initialSlots)for(let[i,l]of Object.entries(e.initialSlots))v.set(i,l);let L=me(e.apiKey);if(L)for(let[i,l]of Object.entries(L.slots))v.has(i)||v.set(i,l);let q={low:.15,medium:.5,high:.85};if(e.initialPersona)E=k({},e.initialPersona);else{let i=document.documentElement.dataset;i.sentientPersona?E={persona:i.sentientPersona,confidence:(p=q[(Y=i.sentientConfidence)!=null?Y:"low"])!=null?p:.15}:L&&(E={persona:L.persona,confidence:(y=q[L.band])!=null?y:.15})}if(e.initialAssignments)for(let[i,l]of Object.entries(e.initialAssignments))c.set(i,h,{variantId:l,assignedAt:Date.now(),segment:h,confidence:1});let b=Promise.resolve(),W=n.getSessionId();if(W){let i=le((_=document.referrer)!=null?_:""),l=k(k({sessionId:W,deviceClass:g,trafficSource:S,referrerDomain:i,utmParams:Ze(),timeOfDay:ce(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:n.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||re((A=navigator.userAgent)!=null?A:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{b=fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(l),headers:a}).then(f=>{f.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(f){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:o});let N={goal(i,l={},f=1,R=0){let I=n.getSessionId();if(!I)return;let x=Se();b.then(()=>{fetch(`${s}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:I,name:i,metadata:l,weight:f,stepIndex:R,goalId:x}),headers:a}).catch(()=>{})})},componentGoal(i,l,f){var D,P,O;let R=n.getSessionId();if(!R)return;let I=c.get(i,h),x=I?null:(D=v.get(i))!=null?D:null;if(!I&&x===null){e.debug&&console.warn(`[sentient] componentGoal("${i}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let M=I?I.variantId:ue(x),C={id:Se(),sessionId:R,projectId:e.apiKey,componentId:i,variantId:M,eventType:"goal_achieved",goalType:l,payload:k({reward:(P=f==null?void 0:f.reward)!=null?P:1},(O=f==null?void 0:f.metadata)!=null?O:{}),timestamp:Date.now(),timeInSession:Date.now()-u};e.debug&&console.log("[sentient] componentGoal",C),b.then(()=>o.push(C))},identify(i){let l=n.getSessionId();l&&b.then(()=>{fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:l,userId:i,ephemeral:n.isEphemeral()}),headers:a}).catch(()=>{})})},track(i){let l=n.getSessionId();if(!l)return;let f=K(k({},i),{id:Se(),sessionId:l,timestamp:Date.now(),timeInSession:Date.now()-u});e.debug&&console.log("[sentient] track",f),b.then(()=>o.push(f))},getAssignment(i,l){return c.get(i,l)},async assign(i,l,f,R){let I=n.getSessionId();if(!I)return null;let x=c.get(i,h);if(x&&(l!=null&&l.length||x.content!==void 0))return{variantId:x.variantId,assignmentTtlMs:0,content:x.content};let M=w.get(i);if(M)return M;let C=(async()=>{await b;try{let D={sessionId:I,componentId:i,variantIds:l};R!==void 0?D.agentDataByVariant=R:f!==void 0&&(D.agentData=f);let P=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify(D),headers:a});if(!P.ok)return null;let O=await P.json();return c.set(i,h,{variantId:O.variantId,assignedAt:Date.now(),segment:h,confidence:1,content:O.content}),O}catch(D){return null}finally{w.delete(i)}})();return w.set(i,C),C},async decide(i){var R,I,x,M,C,D,P,O,ve,we;let l=n.getSessionId();if(!l)return null;let f=(R=i.slots)!=null?R:[];await b;try{let V={sessionId:l};i.sections&&i.sections.length>0&&(V.sections=i.sections.map(T=>({id:T}))),V.components=(I=i.components)!=null?I:[],f.length>0&&(V.slots=f.map(de));let Ee=await fetch(`${s}/decide`,{method:"POST",body:JSON.stringify(V),headers:a});if(!Ee.ok)return B(f),null;let U=await Ee.json(),se={};for(let T of f)se[T.id]=(M=(x=U.slots)==null?void 0:x[T.id])!=null?M:X(T);for(let[T,oe]of Object.entries(se))v.set(T,oe);E={persona:(C=U.persona)!=null?C:"unknown",confidence:(D=U.confidence)!=null?D:0};for(let[T,oe]of Object.entries((P=U.assignments)!=null?P:{}))c.set(T,h,{variantId:oe,assignedAt:Date.now(),segment:h,confidence:1});return z(e.apiKey,{v:1,persona:E.persona,band:Re(E.confidence),slots:Object.fromEntries(v),layoutOrder:(O=U.layoutOrder)!=null?O:null,savedAt:Date.now()}),{layoutOrder:(ve=U.layoutOrder)!=null?ve:null,assignments:(we=U.assignments)!=null?we:{},slots:se,persona:E.persona,confidence:E.confidence}}catch(V){return B(f),null}},getSlotResult(i){var l;return(l=v.get(i))!=null?l:null},getPersona(){return E?{persona:E.persona,confidence:E.confidence,band:Re(E.confidence)}:null},async fetchWeights(){var i;try{let l=await fetch(`${s}/weights`,{headers:a});return l.ok?(i=(await l.json()).components)!=null?i:[]:[]}catch(l){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){o.destroy(),n.destroy(),e.debug&&console.log("[sentient] destroyed")}};if($.set(e.apiKey,{config:e,upgrade:null}),e.debug){let i=window;i.__sentient&&(i.__sentient.client=N)}return N}export{te as a,me as b,z as c,He as d,he as e,ke as f,Xe as g,Ce as h,_t as i,tt as j};
|
package/dist/index-graph.d.cts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { SentientConfig, SentientClient } from './index.cjs';
|
|
2
2
|
export { AssignResult, Assignment, AssignmentCache, ContentAddedEvent, DOMScanner, EventQueue, EventType, GraphClient, GraphConfig, GraphSnapshot, PageNode, QueueConfig, ScanResult, ScannedNode, SentientEvent, SessionConfig, SessionManager } from './index.cjs';
|
|
3
|
-
export {
|
|
3
|
+
export { g as deriveSessionSegment, h as detectDeviceClass, i as detectTimeOfDay, j as detectTrafficSource, r as referrerDomainFromReferer } from './session-meta-DU_3mY7U.cjs';
|
|
4
|
+
import '@sentientui/policy';
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Graph-capable entry point for @sentientui/core.
|
package/dist/index-graph.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { SentientConfig, SentientClient } from './index.js';
|
|
2
2
|
export { AssignResult, Assignment, AssignmentCache, ContentAddedEvent, DOMScanner, EventQueue, EventType, GraphClient, GraphConfig, GraphSnapshot, PageNode, QueueConfig, ScanResult, ScannedNode, SentientEvent, SessionConfig, SessionManager } from './index.js';
|
|
3
|
-
export {
|
|
3
|
+
export { g as deriveSessionSegment, h as detectDeviceClass, i as detectTimeOfDay, j as detectTrafficSource, r as referrerDomainFromReferer } from './session-meta-DU_3mY7U.js';
|
|
4
|
+
import '@sentientui/policy';
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Graph-capable entry point for @sentientui/core.
|
package/dist/index-graph.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var B=Object.defineProperty,ye=Object.defineProperties,Se=Object.getOwnPropertyDescriptor,ve=Object.getOwnPropertyDescriptors,we=Object.getOwnPropertyNames,te=Object.getOwnPropertySymbols;var oe=Object.prototype.hasOwnProperty,Ee=Object.prototype.propertyIsEnumerable;var ne=(e,t,n)=>t in e?B(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_=(e,t)=>{for(var n in t||(t={}))oe.call(t,n)&&ne(e,n,t[n]);if(te)for(var n of te(t))Ee.call(t,n)&&ne(e,n,t[n]);return e},W=(e,t)=>ye(e,ve(t));var Ie=(e,t)=>{for(var n in t)B(e,n,{get:t[n],enumerable:!0})},be=(e,t,n,d)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of we(t))!oe.call(e,s)&&s!==n&&B(e,s,{get:()=>t[s],enumerable:!(d=Se(t,s))||d.enumerable});return e};var Ce=e=>be(B({},"__esModule",{value:!0}),e);var lt={};Ie(lt,{deriveSessionSegment:()=>q,detectDeviceClass:()=>R,detectTimeOfDay:()=>P,detectTrafficSource:()=>M,init:()=>ut,referrerDomainFromReferer:()=>U});module.exports=Ce(lt);var xe="_snt_uid";var O="_snt_uid";function Te(){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 _e(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function ke(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(d){}}function Ae(e){try{return localStorage.getItem(e)}catch(t){return null}}function De(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function Ne(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function Oe(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Re(e){try{sessionStorage.removeItem(e)}catch(t){}}function Me(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 Ue(e){try{localStorage.removeItem(e)}catch(t){}}function Pe(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Le={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function re(e){var c,l,p,m,u,h;if(typeof window=="undefined")return Le;let t=(c=e==null?void 0:e.cookieName)!=null?c:xe,d=((l=e==null?void 0:e.cookieTTLDays)!=null?l:365)*24*60*60,s=(h=(u=(m=(p=_e(t))!=null?p:Ae(O))!=null?m:Ne(O))!=null?u:e==null?void 0:e.ssrSessionId)!=null?h:Te();ke(t,s,d);let a=De(O,s),o=Me(t),i=a?!1:Oe(O,s),r=!a&&!o&&!i;return{getSessionId:()=>s,isEphemeral:()=>r,destroy:()=>{s=null,Pe(t),Ue(O),Re(O)}}}var Ge={push:()=>{},flush:()=>{},destroy:()=>{}};function $e(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let d=JSON.parse(n);return Array.isArray(d)?(localStorage.removeItem(t),d.slice(-e)):[]}catch(n){return[]}}function J(e,t,n){try{let s=[...(()=>{try{let a=localStorage.getItem(n);if(!a)return[];let o=JSON.parse(a);return Array.isArray(o)?o:[]}catch(a){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(s))}catch(d){}}function se(e){var v,x,C;if(typeof window=="undefined")return Ge;let t=(v=e.flushIntervalMs)!=null?v:5e3,n=(x=e.maxBatchSize)!=null?x:20,d=(C=e.maxRetrySize)!=null?C:100,s=e.ingestUrl,a=e.apiKey,o=`_snt_retry_${a.slice(0,12)}`,i=[],r=new Set,c=[],l=g=>{for(let S of g)p.delete(S),!r.has(S)&&(r.add(S),c.push(S));for(;c.length>500;){let S=c.shift();S&&r.delete(S)}},p=new Set,m=g=>{r.has(g.id)||p.has(g.id)||(p.add(g.id),i.push(g))},u=$e(d,o);for(let g of u)m(g);let h=0,w=0,k=g=>{if(g.length===0)return;let S=JSON.stringify(g),E=g.map(I=>I.id),b;try{b=fetch(s,{method:"POST",keepalive:!0,body:S,headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`}})}catch(I){J(g,d,o);for(let z of E)p.delete(z);w++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(w,6));return}let D=I=>{if(I.ok||I.status>=400&&I.status<500&&I.status!==429){l(E),w=0,h=0;return}J(g,d,o);for(let z of E)p.delete(z);w++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(w,6))};b instanceof Promise?b.then(D).catch(()=>{J(g,d,o);for(let I of E)p.delete(I);w++,h=Date.now()+Math.min(6e4,1e3*2**Math.min(w,6))}):D(b)},A=typeof TextEncoder!="undefined"?new TextEncoder:null,$=g=>A?A.encode(g).length:g.length,K=g=>{let S=[],E=2;for(let b of g){let D=$(JSON.stringify(b))+1;if(S.length>0&&E+D>57344||S.length>=n)break;S.push(b),E+=D}return S},T=()=>{try{if(Date.now()<h)return;for(;i.length>0;){let g=i.filter(E=>!r.has(E.id));if(i.length=0,g.length===0)break;let S=K(g);if(S.length===0)break;S.length<g.length&&i.push(...g.slice(S.length)),k(S)}}catch(g){}},L=!0,N=null;N=setInterval(()=>{L&&T()},t);let f=()=>{document.visibilityState==="hidden"&&T()},y=()=>{T()};return document.addEventListener("visibilitychange",f),window.addEventListener("beforeunload",y),{push(g){m(g),i.length>=n&&T()},flush:T,destroy(){L=!1,N!==null&&(clearInterval(N),N=null),document.removeEventListener("visibilitychange",f),window.removeEventListener("beforeunload",y),T()}}}var H="_snt_asgn_";function F(e,t){return`${e}:${t}`}function Ke(e,t){return`${H}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function ie(e){let t=e.slice(H.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(d){return null}}function Q(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(H)&&e.push(n)}return e}catch(e){return[]}}function ae(e=18e5){let t=new Map,n=s=>s.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let s of Q())try{let a=localStorage.getItem(s);if(!a)continue;let o=JSON.parse(a);if(n(o)){localStorage.removeItem(s);continue}let i=ie(s);if(!i)continue;t.set(F(i.componentId,i.segment),o)}catch(a){}})(),{get(s,a){let o=t.get(F(s,a));return o?n(o)?(t.delete(F(s,a)),null):o:null},set(s,a,o){let i=F(s,a);t.set(i,o);try{localStorage.setItem(Ke(s,a),JSON.stringify(o))}catch(r){}},invalidate(s){let a=`${s}:`;for(let o of[...t.keys()])o.startsWith(a)&&t.delete(o);for(let o of Q()){let i=ie(o);if((i==null?void 0:i.componentId)===s)try{localStorage.removeItem(o)}catch(r){}}},clear(){t.clear();for(let s of Q())try{localStorage.removeItem(s)}catch(a){}}}}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 j(e){return de(e)!==null}function de(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=ce.find(d=>t.includes(d.toLowerCase())))!=null?n:null}function R(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 M(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(s){}let d=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(d)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(d)?"social":"referral"}catch(n){return"direct"}}function U(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function P(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function q(e){let t=Be("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Be(e,t){var a,o,i,r,c,l,p;let n=(o=(a=t==null?void 0:t.userAgent)==null?void 0:a.trim())!=null?o:"",d=(r=(i=t==null?void 0:t.referer)==null?void 0:i.trim())!=null?r:"",s=(c=t==null?void 0:t.now)!=null?c:new Date;return{sessionId:e,ephemeral:!1,utmParams:(l=t==null?void 0:t.utmParams)!=null?l:{},deviceClass:n?R(n):"desktop",trafficSource:d?M(d,t==null?void 0:t.appOrigin):"direct",referrerDomain:U(d),timeOfDay:P(s),dayOfWeek:(p=["sun","mon","tue","wed","thu","fri","sat"][s.getDay()])!=null?p:"sun",automation:(t==null?void 0:t.webdriver)===!0||j(n)}}var ue="https://api.sentient-ui.com/v1/events",V=new Map,We=null;function Y(){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 G={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Fe(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,d]of t)n.startsWith("utm_")&&(e[n]=d);return e}catch(e){return{}}}function le(e){return e.replace(/\/events\/?$/,"")}function je(){return[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function ze(e){var o;let t=le((o=e.ingestUrl)!=null?o:ue),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(i,r,c){try{let l=new URLSearchParams({componentId:i});for(let u of r!=null?r:[])l.append("variantIds[]",u);let p=await fetch(`${t}/winner?${l.toString()}`,{headers:n});return p.ok?{variantId:(await p.json()).variantId,assignmentTtlMs:0}:r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}catch(l){return r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}},getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}},s={track:i=>d.track(i),goal:(i,r,c,l)=>d.goal(i,r,c,l),componentGoal:(i,r,c)=>d.componentGoal(i,r,c),identify:i=>d.identify(i),getAssignment:(i,r)=>d.getAssignment(i,r),assign:(i,r,c,l)=>d.assign(i,r,c,l),fetchWeights:()=>d.fetchWeights(),getGraph:()=>d.getGraph(),destroy:()=>d.destroy()};function a(i){d=i}return{proxy:s,setInner:a}}function ge(e){var A,$,K,T,L,N;if(typeof window=="undefined")return G;We=e.apiKey;let t=e.respectDoNotTrack!==!1&&je();if(e.consent===!1||t){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."),G;let{proxy:f,setInner:y}=ze(e);return V.set(e.apiKey,{config:e,upgrade:t?null:y}),f}return V.set(e.apiKey,{config:e,upgrade:null}),G}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."),G;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),G;let n=(A=e.ingestUrl)!=null?A:ue,d=Date.now(),s=re({ssrSessionId:e.ssrSessionId}),a=ae(),o=se({ingestUrl:n,apiKey:e.apiKey}),i=le(n),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},c=R(($=navigator.userAgent)!=null?$:""),l=typeof window!="undefined"?window.location.origin:void 0,p=M((K=document.referrer)!=null?K:"",l),m=(T=e.sessionSegment)!=null?T:`${c}:${p}`,u=new Map;if(e.initialAssignments)for(let[f,y]of Object.entries(e.initialAssignments))a.set(f,m,{variantId:y,assignedAt:Date.now(),segment:m,confidence:1});let h=Promise.resolve(),w=s.getSessionId();if(w){let f=U((L=document.referrer)!=null?L:""),y=_(_({sessionId:w,deviceClass:c,trafficSource:p,referrerDomain:f,utmParams:Fe(),timeOfDay:P(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:s.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||j((N=navigator.userAgent)!=null?N:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{h=fetch(`${i}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(y),headers:r}).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:o});let k={goal(f,y={},v=1,x=0){let C=s.getSessionId();if(!C)return;let g=Y();h.then(()=>{fetch(`${i}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:C,name:f,metadata:y,weight:v,stepIndex:x,goalId:g}),headers:r}).catch(()=>{})})},componentGoal(f,y,v){var S,E;let x=s.getSessionId();if(!x)return;let C=a.get(f,m);if(!C){e.debug&&console.warn(`[sentient] componentGoal("${f}"): no assignment yet \u2014 render its <Adaptive> or call assign() before recording a goal.`);return}let g={id:Y(),sessionId:x,projectId:e.apiKey,componentId:f,variantId:C.variantId,eventType:"goal_achieved",goalType:y,payload:_({reward:(S=v==null?void 0:v.reward)!=null?S:1},(E=v==null?void 0:v.metadata)!=null?E:{}),timestamp:Date.now(),timeInSession:Date.now()-d};e.debug&&console.log("[sentient] componentGoal",g),h.then(()=>o.push(g))},identify(f){let y=s.getSessionId();y&&h.then(()=>{fetch(`${i}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:y,userId:f,ephemeral:s.isEphemeral()}),headers:r}).catch(()=>{})})},track(f){let y=s.getSessionId();if(!y)return;let v=W(_({},f),{id:Y(),sessionId:y,timestamp:Date.now(),timeInSession:Date.now()-d});e.debug&&console.log("[sentient] track",v),h.then(()=>o.push(v))},getAssignment(f,y){return a.get(f,y)},async assign(f,y,v,x){let C=s.getSessionId();if(!C)return null;let g=a.get(f,m);if(g&&(y!=null&&y.length||g.content!==void 0))return{variantId:g.variantId,assignmentTtlMs:0,content:g.content};let S=u.get(f);if(S)return S;let E=(async()=>{await h;try{let b={sessionId:C,componentId:f,variantIds:y};x!==void 0?b.agentDataByVariant=x:v!==void 0&&(b.agentData=v);let D=await fetch(`${i}/assign`,{method:"POST",body:JSON.stringify(b),headers:r});if(!D.ok)return null;let I=await D.json();return a.set(f,m,{variantId:I.variantId,assignedAt:Date.now(),segment:m,confidence:1,content:I.content}),I}catch(b){return null}finally{u.delete(f)}})();return u.set(f,E),E},async fetchWeights(){var f;try{let y=await fetch(`${i}/weights`,{headers:r});return y.ok?(f=(await y.json()).components)!=null?f:[]:[]}catch(y){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){o.destroy(),s.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(V.set(e.apiKey,{config:e,upgrade:null}),e.debug){let f=window;f.__sentient&&(f.__sentient.client=k)}return k}var Je=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Qe="h1, h2, h3",He={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function X(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function qe(e){var t,n,d;try{let s=e;for(let a of Object.keys(s)){if(!a.startsWith("__reactFiber")&&!a.startsWith("__reactInternalInstance"))continue;let o=s[a],i=(d=(t=o==null?void 0:o.type)==null?void 0:t.displayName)!=null?d:(n=o==null?void 0:o.type)==null?void 0:n.name;if(i&&i.length>1)return i}}catch(s){}}function Ve(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function Ye(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function Xe(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function Ze(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function Z(e,t){var d,s,a;let n=e.querySelector(Qe);return{componentId:Xe(e),semanticType:Ye(e),ariaLabel:(d=e.getAttribute("aria-label"))!=null?d:void 0,headingText:(a=(s=n==null?void 0:n.textContent)==null?void 0:s.trim())!=null?a:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Ze(e),reactComponentName:qe(e),dataAttributes:Ve(e)}}function pe(e){var a;let t=[],n=new Set,d="__root__",s=new Map;for(let[o,i]of e){let r=o.parentElement,c=d;for(;r;){if(e.has(r)){c=e.get(r);let p=e.get(o),m=`${c}->${p}`;!n.has(m)&&c!==p&&(n.add(m),t.push({fromComponentId:c,toComponentId:p,weight:.6}));break}r=r.parentElement}let l=(a=s.get(c))!=null?a:[];l.push(o),s.set(c,l)}for(let o of s.values())if(!(o.length<2))for(let i=0;i<o.length;i++)for(let r=i+1;r<o.length;r++){let c=e.get(o[i]),l=e.get(o[r]);if(c===l)continue;let p=`${c}->${l}::sib`,m=`${l}->${c}::sib`;n.has(p)||(n.add(p),t.push({fromComponentId:c,toComponentId:l,weight:.3})),n.has(m)||(n.add(m),t.push({fromComponentId:l,toComponentId:c,weight:.3}))}return t}function et(e){let t=[],n=new Set,d=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(o=>{if(o instanceof Element&&!n.has(o)){n.add(o);let i=Z(o,e);t.push(i),d.set(o,i.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(o=>{if(!(o instanceof Element)||n.has(o))return;let i=o.hasAttribute("aria-label"),r=o.hasAttribute("data-sentient-id");if(!i&&!r)return;n.add(o);let c=Z(o,e);t.push(c),d.set(o,c.componentId)}),{nodes:t,edges:pe(d)}}function fe(){if(typeof window=="undefined")return He;let e=null,t=0,n=null,d=i=>{try{let r=window.getComputedStyle(i),c=parseFloat(r.fontSize)||12,l=parseFloat(r.zIndex)||0,p=i.getBoundingClientRect(),m=Math.max(p.top,0),u=window.innerHeight||1,h=1/(m/u+1),w=X(c,12,48)*.4+X(h,0,1)*.4+X(l,0,100)*.2;return Math.max(0,Math.min(1,w))}catch(r){return .5}};return{scan:()=>new Promise(i=>{let r=()=>{let{nodes:c,edges:l}=et(d);i({nodes:c,edges:l,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(r,{timeout:100}):r()}catch(c){r()}}),observe:i=>{n=i;try{e=new MutationObserver(r=>{let c=[],l=new Map;for(let p of r)p.type==="childList"&&p.addedNodes.forEach(m=>{if(!(m instanceof Element)||!Je.has(m.tagName))return;let u=m.hasAttribute("data-sentient-id"),h=m.hasAttribute("aria-label");if(!u&&!h)return;let w=Z(m,d);c.push(w),l.set(m,w.componentId)});c.length>0&&n&&n({nodes:c,edges:pe(l),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(r){}},getProminenceScore:d,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(i){}t=0,n=null}}}var ee="_snt_graph_nodes",me="_snt_graph_edges",tt={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function nt(e){var t;return(t=tt[e])!=null?t:[]}function ot(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function rt(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var st=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function it(e){return st.has(e)?e:"generic"}function at(e,t,n){let d=`${e}:${t}:${n.join(",")}`,s=5381;for(let a=0;a<d.length;a++)s=(s<<5)+s+d.charCodeAt(a)&4294967295;return(s>>>0).toString(16).padStart(8,"0")}function he(e){let t=new Map,n=new Map,d=()=>{typeof window!="undefined"&&rt(ee,[...t.values()])},s=a=>{var o;try{let i=JSON.parse(a);t.clear();for(let r of(o=i.pageNodes)!=null?o:[])t.set(r.componentId,r)}catch(i){}};if(typeof window!="undefined"){let a=ot(ee,[]);for(let o of a)t.set(o.componentId,o);try{localStorage.removeItem(me)}catch(o){}}return{addPageNode(a){t.set(a.componentId,a),d()},addStructuralEdge(a){let o=`${a.fromComponentId}->${a.toComponentId}`;n.set(o,a)},syncOnce(){var o,i;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let a=[...t.values()];if(a.length!==0)try{let r=new Map;for(let u of a){let h=(o=r.get(u.semanticType))!=null?o:[];h.push(u),r.set(u.semanticType,h)}let c=[],l=new Set;for(let u of a)for(let h of nt(u.semanticType)){let w=(i=r.get(h))!=null?i:[];for(let k of w){if(k.componentId===u.componentId)continue;let A=`semantic:${u.componentId}->${k.componentId}`;l.has(A)||(l.add(A),c.push({fromComponentId:u.componentId,toComponentId:k.componentId,type:"semantic",weight:.4,confidence:.9}))}}let p=new Set(a.map(u=>u.componentId));for(let u of n.values()){if(!p.has(u.fromComponentId)||!p.has(u.toComponentId))continue;let h=`structural:${u.fromComponentId}->${u.toComponentId}`;l.has(h)||(l.add(h),c.push({fromComponentId:u.fromComponentId,toComponentId:u.toComponentId,type:"structural",weight:u.weight,confidence:1}))}let m={pageUrl:window.location.href,nodes:a.map(u=>{let h=it(u.semanticType);return{componentId:u.componentId,semanticType:h,answers:u.answers,contentHash:at(u.componentId,h,u.answers),prominenceScore:u.prominenceScore,depthInPage:u.depth}}),edges:c};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:_({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(m)}).catch(()=>{})}catch(r){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:s,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(ee),localStorage.removeItem(me)}catch(a){}}}}var ct="https://api.sentient-ui.com/v1/events";function dt(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function ut(e){var i;let t=ge(e);if(!e.graph||typeof window=="undefined")return t;let n=fe(),d=(i=e.ingestUrl)!=null?i:ct,s=he({syncUrl:d.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:dt()});try{let r=localStorage.getItem("_snt_graph_nodes");r&&s.restore(JSON.stringify({pageNodes:JSON.parse(r)}))}catch(r){}n.scan().then(r=>{for(let c of r.nodes)s.addPageNode({id:c.componentId,componentId:c.componentId,semanticType:c.semanticType,answers:c.headingText?[c.headingText]:[],prominenceScore:c.prominenceScore,depth:c.depth});for(let c of r.edges)s.addStructuralEdge(c);s.syncOnce()});let a=null,o=()=>{a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,s.syncOnce()},500)};return n.observe(r=>{for(let c of r.nodes)s.addPageNode({id:c.componentId,componentId:c.componentId,semanticType:c.semanticType,answers:c.headingText?[c.headingText]:[],prominenceScore:c.prominenceScore,depth:c.depth});for(let c of r.edges)s.addStructuralEdge(c);o()}),W(_({},t),{getGraph:()=>s.snapshot(),destroy:()=>{a!==null&&clearTimeout(a),n.destroy(),s.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer});
|
|
1
|
+
"use strict";var Qe=Object.create;var Z=Object.defineProperty,Ve=Object.defineProperties,Ye=Object.getOwnPropertyDescriptor,qe=Object.getOwnPropertyDescriptors,Xe=Object.getOwnPropertyNames,Re=Object.getOwnPropertySymbols,Ze=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var Oe=(e,t,n)=>t in e?Z(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,b=(e,t)=>{for(var n in t||(t={}))De.call(t,n)&&Oe(e,n,t[n]);if(Re)for(var n of Re(t))et.call(t,n)&&Oe(e,n,t[n]);return e},$=(e,t)=>Ve(e,qe(t));var tt=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},ke=(e,t,n,d)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of Xe(t))!De.call(e,c)&&c!==n&&Z(e,c,{get:()=>t[c],enumerable:!(d=Ye(t,c))||d.enumerable});return e};var nt=(e,t,n)=>(n=e!=null?Qe(Ze(e)):{},ke(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e)),ot=e=>ke(Z({},"__esModule",{value:!0}),e);var zt={};tt(zt,{deriveSessionSegment:()=>he,detectDeviceClass:()=>B,detectTimeOfDay:()=>F,detectTrafficSource:()=>j,init:()=>Jt,referrerDomainFromReferer:()=>W});module.exports=ot(zt);var rt="_snt_uid";var K="_snt_uid";function st(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function it(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function at(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(d){}}function ct(e){try{return localStorage.getItem(e)}catch(t){return null}}function dt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function lt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function ut(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function gt(e){try{sessionStorage.removeItem(e)}catch(t){}}function pt(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function ft(e){try{localStorage.removeItem(e)}catch(t){}}function mt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var ht={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function oe(e){var r,u,f,m,p,S;if(typeof window=="undefined")return ht;let t=(r=e==null?void 0:e.cookieName)!=null?r:rt,d=((u=e==null?void 0:e.cookieTTLDays)!=null?u:365)*24*60*60,c=(S=(p=(m=(f=it(t))!=null?f:ct(K))!=null?m:lt(K))!=null?p:e==null?void 0:e.ssrSessionId)!=null?S:st();at(t,c,d);let o=dt(K,c),i=pt(t),a=o?!1:ut(K,c),s=!o&&!i&&!a;return{getSessionId:()=>c,isEphemeral:()=>s,destroy:()=>{c=null,mt(t),ft(K),gt(K)}}}var yt={push:()=>{},flush:()=>{},destroy:()=>{}};function St(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let d=JSON.parse(n);return Array.isArray(d)?(localStorage.removeItem(t),d.slice(-e)):[]}catch(n){return[]}}function pe(e,t,n){try{let c=[...(()=>{try{let o=localStorage.getItem(n);if(!o)return[];let i=JSON.parse(o);return Array.isArray(i)?i:[]}catch(o){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(c))}catch(d){}}function Ne(e){var V,Y,q;if(typeof window=="undefined")return yt;let t=(V=e.flushIntervalMs)!=null?V:5e3,n=(Y=e.maxBatchSize)!=null?Y:20,d=(q=e.maxRetrySize)!=null?q:100,c=e.ingestUrl,o=e.apiKey,i=`_snt_retry_${o.slice(0,12)}`,a=[],s=new Set,r=[],u=h=>{for(let w of h)f.delete(w),!s.has(w)&&(s.add(w),r.push(w));for(;r.length>500;){let w=r.shift();w&&s.delete(w)}},f=new Set,m=h=>{s.has(h.id)||f.has(h.id)||(f.add(h.id),a.push(h))},p=St(d,i);for(let h of p)m(h);let S=0,v=0,E=h=>{if(h.length===0)return;let w=JSON.stringify(h),x=h.map(g=>g.id),_;try{_=fetch(c,{method:"POST",keepalive:!0,body:w,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}})}catch(g){pe(h,d,i);for(let y of x)f.delete(y);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6));return}let l=g=>{if(g.ok||g.status>=400&&g.status<500&&g.status!==429){u(x),v=0,S=0;return}pe(h,d,i);for(let y of x)f.delete(y);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))};_ instanceof Promise?_.then(l).catch(()=>{pe(h,d,i);for(let g of x)f.delete(g);v++,S=Date.now()+Math.min(6e4,1e3*2**Math.min(v,6))}):l(_)},k=typeof TextEncoder!="undefined"?new TextEncoder:null,L=h=>k?k.encode(h).length:h.length,ne=h=>{let w=[],x=2;for(let _ of h){let l=L(JSON.stringify(_))+1;if(w.length>0&&x+l>57344||w.length>=n)break;w.push(_),x+=l}return w},I=()=>{try{if(Date.now()<S)return;for(;a.length>0;){let h=a.filter(x=>!s.has(x.id));if(a.length=0,h.length===0)break;let w=ne(h);if(w.length===0)break;w.length<h.length&&a.push(...h.slice(w.length)),E(w)}}catch(h){}},z=!0,M=null;M=setInterval(()=>{z&&I()},t);let H=()=>{document.visibilityState==="hidden"&&I()},Q=()=>{I()};return document.addEventListener("visibilitychange",H),window.addEventListener("beforeunload",Q),{push(h){m(h),a.length>=n&&I()},flush:I,destroy(){z=!1,M!==null&&(clearInterval(M),M=null),document.removeEventListener("visibilitychange",H),window.removeEventListener("beforeunload",Q),I()}}}var me="_snt_asgn_";function re(e,t){return`${e}:${t}`}function vt(e,t){return`${me}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Pe(e){let t=e.slice(me.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(d){return null}}function fe(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(me)&&e.push(n)}return e}catch(e){return[]}}function Le(e=18e5){let t=new Map,n=c=>c.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let c of fe())try{let o=localStorage.getItem(c);if(!o)continue;let i=JSON.parse(o);if(n(i)){localStorage.removeItem(c);continue}let a=Pe(c);if(!a)continue;t.set(re(a.componentId,a.segment),i)}catch(o){}})(),{get(c,o){let i=t.get(re(c,o));return i?n(i)?(t.delete(re(c,o)),null):i:null},set(c,o,i){let a=re(c,o);t.set(a,i);try{localStorage.setItem(vt(c,o),JSON.stringify(i))}catch(s){}},invalidate(c){let o=`${c}:`;for(let i of[...t.keys()])i.startsWith(o)&&t.delete(i);for(let i of fe()){let a=Pe(i);if((a==null?void 0:a.componentId)===c)try{localStorage.removeItem(i)}catch(s){}}},clear(){t.clear();for(let c of fe())try{localStorage.removeItem(c)}catch(o){}}}}var Me=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function se(e){return Ue(e)!==null}function Ue(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Me.find(d=>t.includes(d.toLowerCase())))!=null?n:null}function B(e){let t=e.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(t)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(t)?"mobile":"desktop"}function j(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(c){}let d=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(d)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(d)?"social":"referral"}catch(n){return"direct"}}function W(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function F(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function he(e){let t=wt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function wt(e,t){var o,i,a,s,r,u,f;let n=(i=(o=t==null?void 0:t.userAgent)==null?void 0:o.trim())!=null?i:"",d=(s=(a=t==null?void 0:t.referer)==null?void 0:a.trim())!=null?s:"",c=(r=t==null?void 0:t.now)!=null?r:new Date;return{sessionId:e,ephemeral:!1,utmParams:(u=t==null?void 0:t.utmParams)!=null?u:{},deviceClass:n?B(n):"desktop",trafficSource:d?j(d,t==null?void 0:t.appOrigin):"direct",referrerDomain:W(d),timeOfDay:F(c),dayOfWeek:(f=["sun","mon","tue","wed","thu","fri","sat"][c.getDay()])!=null?f:"sun",automation:(t==null?void 0:t.webdriver)===!0||se(n)}}var J=require("@sentientui/policy");function ie(e){return b(b(b({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function ae(e){let t=ie(e);return(0,J.slotResultFor)(t,(0,J.slotBaselineArm)(t))}function ye(e){return typeof e=="string"?e:(0,J.canonicalArm)(e)}var Se="_snt_snap:",Et=["low","medium","high"];function ve(e){try{let t=localStorage.getItem(Se+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!Et.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"?null:n}catch(t){return null}}function ee(e,t){try{localStorage.setItem(Se+e,JSON.stringify(t))}catch(n){}}var be=require("@sentientui/policy");var de=require("@sentientui/policy");var we="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",$e="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",Ge=!1,ce=!1;function bt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Ke(e){var a;let t=oe({ssrSessionId:e.ssrSessionId}),n=(a=t.getSessionId())!=null?a:"local",d=bt(),c=import("@sentientui/core/local").then(s=>{let r=s;return r.LOCAL_ENGINE_AVAILABLE?(Ge||(Ge=!0,console.info($e)),r):(ce||(ce=!0,console.error(we)),null)}).catch(()=>(ce||(ce=!0,console.error(we)),null)),o=null;function i(s){let r=document.documentElement;r.dataset.sentientPersona===void 0&&(r.dataset.sentientPersona=s.persona,r.dataset.sentientConfidence=(0,de.confidenceBand)(s.confidence))}return{isLocal:!0,async decide(s){var f,m,p;let r=await c;if(!r)return null;let u=r.createLocalEngine({sessionId:n,forcedPersona:d}).decide(s);return o=$(b({},u),{layoutOrder:(m=(f=u.layoutOrder)!=null?f:o==null?void 0:o.layoutOrder)!=null?m:null,slots:b(b({},(p=o==null?void 0:o.slots)!=null?p:{}),u.slots)}),ee(e.apiKey||"local",{v:1,persona:o.persona,band:(0,de.confidenceBand)(o.confidence),slots:o.slots,layoutOrder:o.layoutOrder,savedAt:Date.now()}),i(u),u},getSlotResult(s){var r,u,f;return(f=(u=o==null?void 0:o.slots[s])!=null?u:(r=e.initialSlots)==null?void 0:r[s])!=null?f:null},getPersona(){return o?{persona:o.persona,confidence:o.confidence,band:(0,de.confidenceBand)(o.confidence)}:null},async assign(s,r){var m;let u=await c;return!u||!r||r.length===0?r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null:{variantId:(m=u.createLocalEngine({sessionId:n,forcedPersona:d}).decide({components:[{id:s,variantIds:r}]}).assignments[s])!=null?m:r[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>t.destroy()}}var Be="https://api.sentient-ui.com/v1/events",le=new Map,It=null;function Ee(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var te={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}};function Ct(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,d]of t)n.startsWith("utm_")&&(e[n]=d);return e}catch(e){return{}}}function je(e){return e.replace(/\/events\/?$/,"")}function xt(){return[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function At(e){var i;let t=je((i=e.ingestUrl)!=null?i:Be),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(a,s,r){try{let u=new URLSearchParams({componentId:a});for(let p of s!=null?s:[])u.append("variantIds[]",p);let f=await fetch(`${t}/winner?${u.toString()}`,{headers:n});return f.ok?{variantId:(await f.json()).variantId,assignmentTtlMs:0}:s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}catch(u){return s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),destroy:()=>{}},c={track:a=>d.track(a),goal:(a,s,r,u)=>d.goal(a,s,r,u),componentGoal:(a,s,r)=>d.componentGoal(a,s,r),identify:a=>d.identify(a),getAssignment:(a,s)=>d.getAssignment(a,s),assign:(a,s,r,u)=>d.assign(a,s,r,u),decide:a=>d.decide(a),getSlotResult:a=>d.getSlotResult(a),getPersona:()=>d.getPersona(),fetchWeights:()=>d.fetchWeights(),getGraph:()=>d.getGraph(),destroy:()=>d.destroy()};function o(a){d=a}return{proxy:c,setInner:o}}function We(e){var H,Q,V,Y,q,h,w,x,_;if(typeof window=="undefined")return te;It=e.apiKey;let t=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!t&&e.localMode!==!1)return le.set(e.apiKey||"local",{config:e,upgrade:null}),Ke(e);let n=e.respectDoNotTrack!==!1&&xt();if(e.consent===!1||n){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),te;let{proxy:l,setInner:g}=At(e);return le.set(e.apiKey,{config:e,upgrade:n?null:g}),l}return le.set(e.apiKey,{config:e,upgrade:null}),te}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),te;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),te;let d=(H=e.ingestUrl)!=null?H:Be,c=Date.now(),o=oe({ssrSessionId:e.ssrSessionId}),i=Le(),a=Ne({ingestUrl:d,apiKey:e.apiKey}),s=je(d),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u=B((Q=navigator.userAgent)!=null?Q:""),f=typeof window!="undefined"?window.location.origin:void 0,m=j((V=document.referrer)!=null?V:"",f),p=(Y=e.sessionSegment)!=null?Y:`${u}:${m}`,S=new Map,v=new Map,E=null,k=l=>{for(let g of l)v.has(g.id)||v.set(g.id,ae(g))};if(e.initialSlots)for(let[l,g]of Object.entries(e.initialSlots))v.set(l,g);let L=ve(e.apiKey);if(L)for(let[l,g]of Object.entries(L.slots))v.has(l)||v.set(l,g);let ne={low:.15,medium:.5,high:.85};if(e.initialPersona)E=b({},e.initialPersona);else{let l=document.documentElement.dataset;l.sentientPersona?E={persona:l.sentientPersona,confidence:(h=ne[(q=l.sentientConfidence)!=null?q:"low"])!=null?h:.15}:L&&(E={persona:L.persona,confidence:(w=ne[L.band])!=null?w:.15})}if(e.initialAssignments)for(let[l,g]of Object.entries(e.initialAssignments))i.set(l,p,{variantId:g,assignedAt:Date.now(),segment:p,confidence:1});let I=Promise.resolve(),z=o.getSessionId();if(z){let l=W((x=document.referrer)!=null?x:""),g=b(b({sessionId:z,deviceClass:u,trafficSource:m,referrerDomain:l,utmParams:Ct(),timeOfDay:F(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||se((_=navigator.userAgent)!=null?_:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{I=fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(g),headers:r}).then(y=>{y.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(y){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:a});let M={goal(l,g={},y=1,T=0){let C=o.getSessionId();if(!C)return;let A=Ee();I.then(()=>{fetch(`${s}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:C,name:l,metadata:g,weight:y,stepIndex:T,goalId:A}),headers:r}).catch(()=>{})})},componentGoal(l,g,y){var R,P,O;let T=o.getSessionId();if(!T)return;let C=i.get(l,p),A=C?null:(R=v.get(l))!=null?R:null;if(!C&&A===null){e.debug&&console.warn(`[sentient] componentGoal("${l}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let U=C?C.variantId:ye(A),N={id:Ee(),sessionId:T,projectId:e.apiKey,componentId:l,variantId:U,eventType:"goal_achieved",goalType:g,payload:b({reward:(P=y==null?void 0:y.reward)!=null?P:1},(O=y==null?void 0:y.metadata)!=null?O:{}),timestamp:Date.now(),timeInSession:Date.now()-c};e.debug&&console.log("[sentient] componentGoal",N),I.then(()=>a.push(N))},identify(l){let g=o.getSessionId();g&&I.then(()=>{fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:g,userId:l,ephemeral:o.isEphemeral()}),headers:r}).catch(()=>{})})},track(l){let g=o.getSessionId();if(!g)return;let y=$(b({},l),{id:Ee(),sessionId:g,timestamp:Date.now(),timeInSession:Date.now()-c});e.debug&&console.log("[sentient] track",y),I.then(()=>a.push(y))},getAssignment(l,g){return i.get(l,g)},async assign(l,g,y,T){let C=o.getSessionId();if(!C)return null;let A=i.get(l,p);if(A&&(g!=null&&g.length||A.content!==void 0))return{variantId:A.variantId,assignmentTtlMs:0,content:A.content};let U=S.get(l);if(U)return U;let N=(async()=>{await I;try{let R={sessionId:C,componentId:l,variantIds:g};T!==void 0?R.agentDataByVariant=T:y!==void 0&&(R.agentData=y);let P=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify(R),headers:r});if(!P.ok)return null;let O=await P.json();return i.set(l,p,{variantId:O.variantId,assignedAt:Date.now(),segment:p,confidence:1,content:O.content}),O}catch(R){return null}finally{S.delete(l)}})();return S.set(l,N),N},async decide(l){var T,C,A,U,N,R,P,O,Ae,_e;let g=o.getSessionId();if(!g)return null;let y=(T=l.slots)!=null?T:[];await I;try{let X={sessionId:g};l.sections&&l.sections.length>0&&(X.sections=l.sections.map(D=>({id:D}))),X.components=(C=l.components)!=null?C:[],y.length>0&&(X.slots=y.map(ie));let Te=await fetch(`${s}/decide`,{method:"POST",body:JSON.stringify(X),headers:r});if(!Te.ok)return k(y),null;let G=await Te.json(),ue={};for(let D of y)ue[D.id]=(U=(A=G.slots)==null?void 0:A[D.id])!=null?U:ae(D);for(let[D,ge]of Object.entries(ue))v.set(D,ge);E={persona:(N=G.persona)!=null?N:"unknown",confidence:(R=G.confidence)!=null?R:0};for(let[D,ge]of Object.entries((P=G.assignments)!=null?P:{}))i.set(D,p,{variantId:ge,assignedAt:Date.now(),segment:p,confidence:1});return ee(e.apiKey,{v:1,persona:E.persona,band:(0,be.confidenceBand)(E.confidence),slots:Object.fromEntries(v),layoutOrder:(O=G.layoutOrder)!=null?O:null,savedAt:Date.now()}),{layoutOrder:(Ae=G.layoutOrder)!=null?Ae:null,assignments:(_e=G.assignments)!=null?_e:{},slots:ue,persona:E.persona,confidence:E.confidence}}catch(X){return k(y),null}},getSlotResult(l){var g;return(g=v.get(l))!=null?g:null},getPersona(){return E?{persona:E.persona,confidence:E.confidence,band:(0,be.confidenceBand)(E.confidence)}:null},async fetchWeights(){var l;try{let g=await fetch(`${s}/weights`,{headers:r});return g.ok?(l=(await g.json()).components)!=null?l:[]:[]}catch(g){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},destroy(){a.destroy(),o.destroy(),e.debug&&console.log("[sentient] destroyed")}};if(le.set(e.apiKey,{config:e,upgrade:null}),e.debug){let l=window;l.__sentient&&(l.__sentient.client=M)}return M}var _t=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Tt="h1, h2, h3",Rt={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function Ie(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Ot(e){var t,n,d;try{let c=e;for(let o of Object.keys(c)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let i=c[o],a=(d=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?d:(n=i==null?void 0:i.type)==null?void 0:n.name;if(a&&a.length>1)return a}}catch(c){}}function Dt(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function kt(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function Nt(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function Pt(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function Ce(e,t){var d,c,o;let n=e.querySelector(Tt);return{componentId:Nt(e),semanticType:kt(e),ariaLabel:(d=e.getAttribute("aria-label"))!=null?d:void 0,headingText:(o=(c=n==null?void 0:n.textContent)==null?void 0:c.trim())!=null?o:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Pt(e),reactComponentName:Ot(e),dataAttributes:Dt(e)}}function Fe(e){var o;let t=[],n=new Set,d="__root__",c=new Map;for(let[i,a]of e){let s=i.parentElement,r=d;for(;s;){if(e.has(s)){r=e.get(s);let f=e.get(i),m=`${r}->${f}`;!n.has(m)&&r!==f&&(n.add(m),t.push({fromComponentId:r,toComponentId:f,weight:.6}));break}s=s.parentElement}let u=(o=c.get(r))!=null?o:[];u.push(i),c.set(r,u)}for(let i of c.values())if(!(i.length<2))for(let a=0;a<i.length;a++)for(let s=a+1;s<i.length;s++){let r=e.get(i[a]),u=e.get(i[s]);if(r===u)continue;let f=`${r}->${u}::sib`,m=`${u}->${r}::sib`;n.has(f)||(n.add(f),t.push({fromComponentId:r,toComponentId:u,weight:.3})),n.has(m)||(n.add(m),t.push({fromComponentId:u,toComponentId:r,weight:.3}))}return t}function Lt(e){let t=[],n=new Set,d=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(i=>{if(i instanceof Element&&!n.has(i)){n.add(i);let a=Ce(i,e);t.push(a),d.set(i,a.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(i=>{if(!(i instanceof Element)||n.has(i))return;let a=i.hasAttribute("aria-label"),s=i.hasAttribute("data-sentient-id");if(!a&&!s)return;n.add(i);let r=Ce(i,e);t.push(r),d.set(i,r.componentId)}),{nodes:t,edges:Fe(d)}}function Je(){if(typeof window=="undefined")return Rt;let e=null,t=0,n=null,d=a=>{try{let s=window.getComputedStyle(a),r=parseFloat(s.fontSize)||12,u=parseFloat(s.zIndex)||0,f=a.getBoundingClientRect(),m=Math.max(f.top,0),p=window.innerHeight||1,S=1/(m/p+1),v=Ie(r,12,48)*.4+Ie(S,0,1)*.4+Ie(u,0,100)*.2;return Math.max(0,Math.min(1,v))}catch(s){return .5}};return{scan:()=>new Promise(a=>{let s=()=>{let{nodes:r,edges:u}=Lt(d);a({nodes:r,edges:u,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(s,{timeout:100}):s()}catch(r){s()}}),observe:a=>{n=a;try{e=new MutationObserver(s=>{let r=[],u=new Map;for(let f of s)f.type==="childList"&&f.addedNodes.forEach(m=>{if(!(m instanceof Element)||!_t.has(m.tagName))return;let p=m.hasAttribute("data-sentient-id"),S=m.hasAttribute("aria-label");if(!p&&!S)return;let v=Ce(m,d);r.push(v),u.set(m,v.componentId)});r.length>0&&n&&n({nodes:r,edges:Fe(u),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(s){}},getProminenceScore:d,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(a){}t=0,n=null}}}var xe="_snt_graph_nodes",ze="_snt_graph_edges",Mt={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function Ut(e){var t;return(t=Mt[e])!=null?t:[]}function Gt(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function $t(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var Kt=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function Bt(e){return Kt.has(e)?e:"generic"}function jt(e,t,n){let d=`${e}:${t}:${n.join(",")}`,c=5381;for(let o=0;o<d.length;o++)c=(c<<5)+c+d.charCodeAt(o)&4294967295;return(c>>>0).toString(16).padStart(8,"0")}function He(e){let t=new Map,n=new Map,d=()=>{typeof window!="undefined"&&$t(xe,[...t.values()])},c=o=>{var i;try{let a=JSON.parse(o);t.clear();for(let s of(i=a.pageNodes)!=null?i:[])t.set(s.componentId,s)}catch(a){}};if(typeof window!="undefined"){let o=Gt(xe,[]);for(let i of o)t.set(i.componentId,i);try{localStorage.removeItem(ze)}catch(i){}}return{addPageNode(o){t.set(o.componentId,o),d()},addStructuralEdge(o){let i=`${o.fromComponentId}->${o.toComponentId}`;n.set(i,o)},syncOnce(){var i,a;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let s=new Map;for(let p of o){let S=(i=s.get(p.semanticType))!=null?i:[];S.push(p),s.set(p.semanticType,S)}let r=[],u=new Set;for(let p of o)for(let S of Ut(p.semanticType)){let v=(a=s.get(S))!=null?a:[];for(let E of v){if(E.componentId===p.componentId)continue;let k=`semantic:${p.componentId}->${E.componentId}`;u.has(k)||(u.add(k),r.push({fromComponentId:p.componentId,toComponentId:E.componentId,type:"semantic",weight:.4,confidence:.9}))}}let f=new Set(o.map(p=>p.componentId));for(let p of n.values()){if(!f.has(p.fromComponentId)||!f.has(p.toComponentId))continue;let S=`structural:${p.fromComponentId}->${p.toComponentId}`;u.has(S)||(u.add(S),r.push({fromComponentId:p.fromComponentId,toComponentId:p.toComponentId,type:"structural",weight:p.weight,confidence:1}))}let m={pageUrl:window.location.href,nodes:o.map(p=>{let S=Bt(p.semanticType);return{componentId:p.componentId,semanticType:S,answers:p.answers,contentHash:jt(p.componentId,S,p.answers),prominenceScore:p.prominenceScore,depthInPage:p.depth}}),edges:r};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:b({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(m)}).catch(()=>{})}catch(s){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:c,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(xe),localStorage.removeItem(ze)}catch(o){}}}}var Wt="https://api.sentient-ui.com/v1/events";function Ft(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function Jt(e){var a;let t=We(e);if(!e.graph||typeof window=="undefined")return t;let n=Je(),d=(a=e.ingestUrl)!=null?a:Wt,c=He({syncUrl:d.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Ft()});try{let s=localStorage.getItem("_snt_graph_nodes");s&&c.restore(JSON.stringify({pageNodes:JSON.parse(s)}))}catch(s){}n.scan().then(s=>{for(let r of s.nodes)c.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});for(let r of s.edges)c.addStructuralEdge(r);c.syncOnce()});let o=null,i=()=>{o!==null&&clearTimeout(o),o=setTimeout(()=>{o=null,c.syncOnce()},500)};return n.observe(s=>{for(let r of s.nodes)c.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});for(let r of s.edges)c.addStructuralEdge(r);i()}),$(b({},t),{getGraph:()=>c.snapshot(),destroy:()=>{o!==null&&clearTimeout(o),n.destroy(),c.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer});
|
package/dist/index-graph.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{j as v}from"./chunk-X2URHWFL.mjs";import{d as x,e as _,f as O,g as R,h as M}from"./chunk-SVYHTU5Z.mjs";import{a as h,b}from"./chunk-HGGX55FR.mjs";var P=new Set(["SECTION","ARTICLE","MAIN","DIV"]),D="h1, h2, h3",G={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function S(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function k(e){var t,n,p;try{let d=e;for(let s of Object.keys(d)){if(!s.startsWith("__reactFiber")&&!s.startsWith("__reactInternalInstance"))continue;let r=d[s],i=(p=(t=r==null?void 0:r.type)==null?void 0:t.displayName)!=null?p:(n=r==null?void 0:r.type)==null?void 0:n.name;if(i&&i.length>1)return i}}catch(d){}}function $(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}function L(e){let t=e.getAttribute("data-sentient-type");if(t)return t;let n=e.getAttribute("role");return n||"generic"}function U(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function j(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function I(e,t){var p,d,s;let n=e.querySelector(D);return{componentId:U(e),semanticType:L(e),ariaLabel:(p=e.getAttribute("aria-label"))!=null?p:void 0,headingText:(s=(d=n==null?void 0:n.textContent)==null?void 0:d.trim())!=null?s:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:j(e),reactComponentName:k(e),dataAttributes:$(e)}}function w(e){var s;let t=[],n=new Set,p="__root__",d=new Map;for(let[r,i]of e){let a=r.parentElement,o=p;for(;a;){if(e.has(a)){o=e.get(a);let m=e.get(r),g=`${o}->${m}`;!n.has(g)&&o!==m&&(n.add(g),t.push({fromComponentId:o,toComponentId:m,weight:.6}));break}a=a.parentElement}let u=(s=d.get(o))!=null?s:[];u.push(r),d.set(o,u)}for(let r of d.values())if(!(r.length<2))for(let i=0;i<r.length;i++)for(let a=i+1;a<r.length;a++){let o=e.get(r[i]),u=e.get(r[a]);if(o===u)continue;let m=`${o}->${u}::sib`,g=`${u}->${o}::sib`;n.has(m)||(n.add(m),t.push({fromComponentId:o,toComponentId:u,weight:.3})),n.has(g)||(n.add(g),t.push({fromComponentId:u,toComponentId:o,weight:.3}))}return t}function F(e){let t=[],n=new Set,p=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(r=>{if(r instanceof Element&&!n.has(r)){n.add(r);let i=I(r,e);t.push(i),p.set(r,i.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(r=>{if(!(r instanceof Element)||n.has(r))return;let i=r.hasAttribute("aria-label"),a=r.hasAttribute("data-sentient-id");if(!i&&!a)return;n.add(r);let o=I(r,e);t.push(o),p.set(r,o.componentId)}),{nodes:t,edges:w(p)}}function N(){if(typeof window=="undefined")return G;let e=null,t=0,n=null,p=i=>{try{let a=window.getComputedStyle(i),o=parseFloat(a.fontSize)||12,u=parseFloat(a.zIndex)||0,m=i.getBoundingClientRect(),g=Math.max(m.top,0),c=window.innerHeight||1,l=1/(g/c+1),f=S(o,12,48)*.4+S(l,0,1)*.4+S(u,0,100)*.2;return Math.max(0,Math.min(1,f))}catch(a){return .5}};return{scan:()=>new Promise(i=>{let a=()=>{let{nodes:o,edges:u}=F(p);i({nodes:o,edges:u,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(a,{timeout:100}):a()}catch(o){a()}}),observe:i=>{n=i;try{e=new MutationObserver(a=>{let o=[],u=new Map;for(let m of a)m.type==="childList"&&m.addedNodes.forEach(g=>{if(!(g instanceof Element)||!P.has(g.tagName))return;let c=g.hasAttribute("data-sentient-id"),l=g.hasAttribute("aria-label");if(!c&&!l)return;let f=I(g,p);o.push(f),u.set(g,f.componentId)});o.length>0&&n&&n({nodes:o,edges:w(u),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(a){}},getProminenceScore:p,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(i){}t=0,n=null}}}var C="_snt_graph_nodes",A="_snt_graph_edges",K={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function q(e){var t;return(t=K[e])!=null?t:[]}function z(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function H(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var J=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function B(e){return J.has(e)?e:"generic"}function V(e,t,n){let p=`${e}:${t}:${n.join(",")}`,d=5381;for(let s=0;s<p.length;s++)d=(d<<5)+d+p.charCodeAt(s)&4294967295;return(d>>>0).toString(16).padStart(8,"0")}function T(e){let t=new Map,n=new Map,p=()=>{typeof window!="undefined"&&H(C,[...t.values()])},d=s=>{var r;try{let i=JSON.parse(s);t.clear();for(let a of(r=i.pageNodes)!=null?r:[])t.set(a.componentId,a)}catch(i){}};if(typeof window!="undefined"){let s=z(C,[]);for(let r of s)t.set(r.componentId,r);try{localStorage.removeItem(A)}catch(r){}}return{addPageNode(s){t.set(s.componentId,s),p()},addStructuralEdge(s){let r=`${s.fromComponentId}->${s.toComponentId}`;n.set(r,s)},syncOnce(){var r,i;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let s=[...t.values()];if(s.length!==0)try{let a=new Map;for(let c of s){let l=(r=a.get(c.semanticType))!=null?r:[];l.push(c),a.set(c.semanticType,l)}let o=[],u=new Set;for(let c of s)for(let l of q(c.semanticType)){let f=(i=a.get(l))!=null?i:[];for(let y of f){if(y.componentId===c.componentId)continue;let E=`semantic:${c.componentId}->${y.componentId}`;u.has(E)||(u.add(E),o.push({fromComponentId:c.componentId,toComponentId:y.componentId,type:"semantic",weight:.4,confidence:.9}))}}let m=new Set(s.map(c=>c.componentId));for(let c of n.values()){if(!m.has(c.fromComponentId)||!m.has(c.toComponentId))continue;let l=`structural:${c.fromComponentId}->${c.toComponentId}`;u.has(l)||(u.add(l),o.push({fromComponentId:c.fromComponentId,toComponentId:c.toComponentId,type:"structural",weight:c.weight,confidence:1}))}let g={pageUrl:window.location.href,nodes:s.map(c=>{let l=B(c.semanticType);return{componentId:c.componentId,semanticType:l,answers:c.answers,contentHash:V(c.componentId,l,c.answers),prominenceScore:c.prominenceScore,depthInPage:c.depth}}),edges:o};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:h({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(g)}).catch(()=>{})}catch(a){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:d,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(C),localStorage.removeItem(A)}catch(s){}}}}var W="https://api.sentient-ui.com/v1/events";function Y(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function oe(e){var i;let t=v(e);if(!e.graph||typeof window=="undefined")return t;let n=N(),p=(i=e.ingestUrl)!=null?i:W,d=T({syncUrl:p.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Y()});try{let a=localStorage.getItem("_snt_graph_nodes");a&&d.restore(JSON.stringify({pageNodes:JSON.parse(a)}))}catch(a){}n.scan().then(a=>{for(let o of a.nodes)d.addPageNode({id:o.componentId,componentId:o.componentId,semanticType:o.semanticType,answers:o.headingText?[o.headingText]:[],prominenceScore:o.prominenceScore,depth:o.depth});for(let o of a.edges)d.addStructuralEdge(o);d.syncOnce()});let s=null,r=()=>{s!==null&&clearTimeout(s),s=setTimeout(()=>{s=null,d.syncOnce()},500)};return n.observe(a=>{for(let o of a.nodes)d.addPageNode({id:o.componentId,componentId:o.componentId,semanticType:o.semanticType,answers:o.headingText?[o.headingText]:[],prominenceScore:o.prominenceScore,depth:o.depth});for(let o of a.edges)d.addStructuralEdge(o);r()}),b(h({},t),{getGraph:()=>d.snapshot(),destroy:()=>{s!==null&&clearTimeout(s),n.destroy(),d.destroy(),t.destroy()}})}export{M as deriveSessionSegment,x as detectDeviceClass,R as detectTimeOfDay,_ as detectTrafficSource,oe as init,O as referrerDomainFromReferer};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Production stub for `@sentientui/core/local`. The package.json "./local"
|
|
3
|
+
* exports map resolves here under the `production` condition — and as the
|
|
4
|
+
* fallback for resolvers that set neither condition — so production bundles
|
|
5
|
+
* physically contain no local-engine code.
|
|
6
|
+
*/
|
|
7
|
+
declare const LOCAL_ENGINE_AVAILABLE = false;
|
|
8
|
+
declare function createLocalEngine(_opts: {
|
|
9
|
+
sessionId: string;
|
|
10
|
+
forcedPersona?: string;
|
|
11
|
+
}): never;
|
|
12
|
+
|
|
13
|
+
export { LOCAL_ENGINE_AVAILABLE, createLocalEngine };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Production stub for `@sentientui/core/local`. The package.json "./local"
|
|
3
|
+
* exports map resolves here under the `production` condition — and as the
|
|
4
|
+
* fallback for resolvers that set neither condition — so production bundles
|
|
5
|
+
* physically contain no local-engine code.
|
|
6
|
+
*/
|
|
7
|
+
declare const LOCAL_ENGINE_AVAILABLE = false;
|
|
8
|
+
declare function createLocalEngine(_opts: {
|
|
9
|
+
sessionId: string;
|
|
10
|
+
forcedPersona?: string;
|
|
11
|
+
}): never;
|
|
12
|
+
|
|
13
|
+
export { LOCAL_ENGINE_AVAILABLE, createLocalEngine };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var i=Object.defineProperty;var s=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var l=(n,e)=>{for(var t in e)i(n,t,{get:e[t],enumerable:!0})},d=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of a(e))!c.call(n,o)&&o!==t&&i(n,o,{get:()=>e[o],enumerable:!(r=s(e,o))||r.enumerable});return n};var p=n=>d(i({},"__esModule",{value:!0}),n);var g={};l(g,{LOCAL_ENGINE_AVAILABLE:()=>E,createLocalEngine:()=>L});module.exports=p(g);var E=!1;function L(n){throw new Error("[sentient] createLocalEngine is not available in production builds. The local engine only exists under the `development` export condition.")}0&&(module.exports={LOCAL_ENGINE_AVAILABLE,createLocalEngine});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./chunk-HGGX55FR.mjs";var n=!1;function o(e){throw new Error("[sentient] createLocalEngine is not available in production builds. The local engine only exists under the `development` export condition.")}export{n as LOCAL_ENGINE_AVAILABLE,o as createLocalEngine};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { DecideOutcome } from './index.cjs';
|
|
2
|
+
import { a as SlotDeclInput } from './session-meta-DU_3mY7U.cjs';
|
|
3
|
+
import '@sentientui/policy';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Sentinel embedded so build-level tests can assert the production bundle
|
|
7
|
+
* physically excludes the local engine (scripts/verify-local-exclusion.ts).
|
|
8
|
+
* Do not rename without updating that script.
|
|
9
|
+
*/
|
|
10
|
+
declare const LOCAL_ENGINE_SENTINEL = "SENTIENT_LOCAL_ENGINE";
|
|
11
|
+
/** True on the real engine module, false on the production stub. */
|
|
12
|
+
declare const LOCAL_ENGINE_AVAILABLE = true;
|
|
13
|
+
/** Simulated decisions carry a fixed mid confidence (band 'medium'). */
|
|
14
|
+
declare const LOCAL_CONFIDENCE = 0.5;
|
|
15
|
+
declare function inferSectionTypes(sections: string[]): Map<string, string>;
|
|
16
|
+
declare function createLocalEngine(opts: {
|
|
17
|
+
sessionId: string;
|
|
18
|
+
forcedPersona?: string;
|
|
19
|
+
}): {
|
|
20
|
+
decide(input: {
|
|
21
|
+
sections?: string[];
|
|
22
|
+
components?: Array<{
|
|
23
|
+
id: string;
|
|
24
|
+
variantIds?: string[];
|
|
25
|
+
}>;
|
|
26
|
+
slots?: SlotDeclInput[];
|
|
27
|
+
}): DecideOutcome;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export { LOCAL_CONFIDENCE, LOCAL_ENGINE_AVAILABLE, LOCAL_ENGINE_SENTINEL, createLocalEngine, inferSectionTypes };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { DecideOutcome } from './index.js';
|
|
2
|
+
import { a as SlotDeclInput } from './session-meta-DU_3mY7U.js';
|
|
3
|
+
import '@sentientui/policy';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Sentinel embedded so build-level tests can assert the production bundle
|
|
7
|
+
* physically excludes the local engine (scripts/verify-local-exclusion.ts).
|
|
8
|
+
* Do not rename without updating that script.
|
|
9
|
+
*/
|
|
10
|
+
declare const LOCAL_ENGINE_SENTINEL = "SENTIENT_LOCAL_ENGINE";
|
|
11
|
+
/** True on the real engine module, false on the production stub. */
|
|
12
|
+
declare const LOCAL_ENGINE_AVAILABLE = true;
|
|
13
|
+
/** Simulated decisions carry a fixed mid confidence (band 'medium'). */
|
|
14
|
+
declare const LOCAL_CONFIDENCE = 0.5;
|
|
15
|
+
declare function inferSectionTypes(sections: string[]): Map<string, string>;
|
|
16
|
+
declare function createLocalEngine(opts: {
|
|
17
|
+
sessionId: string;
|
|
18
|
+
forcedPersona?: string;
|
|
19
|
+
}): {
|
|
20
|
+
decide(input: {
|
|
21
|
+
sections?: string[];
|
|
22
|
+
components?: Array<{
|
|
23
|
+
id: string;
|
|
24
|
+
variantIds?: string[];
|
|
25
|
+
}>;
|
|
26
|
+
slots?: SlotDeclInput[];
|
|
27
|
+
}): DecideOutcome;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export { LOCAL_CONFIDENCE, LOCAL_ENGINE_AVAILABLE, LOCAL_ENGINE_SENTINEL, createLocalEngine, inferSectionTypes };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var l=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var I=(t,n)=>{for(var s in n)l(t,s,{get:n[s],enumerable:!0})},N=(t,n,s,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of m(n))!E.call(t,r)&&r!==s&&l(t,r,{get:()=>n[r],enumerable:!(i=p(n,r))||i.enumerable});return t};var S=t=>N(l({},"__esModule",{value:!0}),t);var C={};I(C,{LOCAL_CONFIDENCE:()=>g,LOCAL_ENGINE_AVAILABLE:()=>L,LOCAL_ENGINE_SENTINEL:()=>y,createLocalEngine:()=>v,inferSectionTypes:()=>f});module.exports=S(C);var e=require("@sentientui/policy"),y="SENTIENT_LOCAL_ENGINE",L=!0,g=.5,O=[["pricing","pricing"],["hero","hero"],["faq","faq"],["cta","cta"],["trust","trust"],["social","social_proof"],["testimonial","social_proof"],["feature","features"],["comparison","comparison"],["compare","comparison"],["nav","navigation"]];function f(t){let n=new Map;for(let s of t){let i=s.toLowerCase(),r=O.find(([c])=>i.includes(c));n.set(s,r?r[1]:"generic")}return n}function A(t,n){if(n){if(e.PERSONAS.includes(n))return n;if(n===e.UNKNOWN_PERSONA)return e.UNKNOWN_PERSONA}return e.PERSONAS[(0,e.fnv1a)(t)%e.PERSONAS.length]}function _(t,n,s){let i=`${t}:${n}`;if(s.arms&&s.arms.length>=2)return(0,e.pickDeterministicArm)(i,s.id,s.arms);if(s.dims){let r={};for(let[c,a]of Object.entries(s.dims)){if(!a||a.length<2)return null;r[c]=(0,e.pickDeterministicArm)(i,`${s.id}.${c}`,[...a])}return r}return null}function v(t){let n=A(t.sessionId,t.forcedPersona);return{decide(s){var a,u;let i=s.sections&&s.sections.length>0?(0,e.applyClusterHeuristic)(s.sections,f(s.sections),n):null,r={};for(let o of(a=s.components)!=null?a:[])o.variantIds&&o.variantIds.length>0&&(r[o.id]=(0,e.pickDeterministicArm)(t.sessionId,o.id,o.variantIds));let c={};for(let o of(u=s.slots)!=null?u:[]){let d=_(t.sessionId,n,o);d!==null&&(c[o.id]=d)}return{layoutOrder:i,assignments:r,slots:c,persona:n,confidence:g}}}}0&&(module.exports={LOCAL_CONFIDENCE,LOCAL_ENGINE_AVAILABLE,LOCAL_ENGINE_SENTINEL,createLocalEngine,inferSectionTypes});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./chunk-HGGX55FR.mjs";import{PERSONAS as a,UNKNOWN_PERSONA as g,applyClusterHeuristic as f,fnv1a as p,pickDeterministicArm as l}from"@sentientui/policy";var L="SENTIENT_LOCAL_ENGINE",O=!0,m=.5,E=[["pricing","pricing"],["hero","hero"],["faq","faq"],["cta","cta"],["trust","trust"],["social","social_proof"],["testimonial","social_proof"],["feature","features"],["comparison","comparison"],["compare","comparison"],["nav","navigation"]];function I(t){let s=new Map;for(let n of t){let o=n.toLowerCase(),e=E.find(([i])=>o.includes(i));s.set(n,e?e[1]:"generic")}return s}function N(t,s){if(s){if(a.includes(s))return s;if(s===g)return g}return a[p(t)%a.length]}function S(t,s,n){let o=`${t}:${s}`;if(n.arms&&n.arms.length>=2)return l(o,n.id,n.arms);if(n.dims){let e={};for(let[i,c]of Object.entries(n.dims)){if(!c||c.length<2)return null;e[i]=l(o,`${n.id}.${i}`,[...c])}return e}return null}function A(t){let s=N(t.sessionId,t.forcedPersona);return{decide(n){var c,u;let o=n.sections&&n.sections.length>0?f(n.sections,I(n.sections),s):null,e={};for(let r of(c=n.components)!=null?c:[])r.variantIds&&r.variantIds.length>0&&(e[r.id]=l(t.sessionId,r.id,r.variantIds));let i={};for(let r of(u=n.slots)!=null?u:[]){let d=S(t.sessionId,s,r);d!==null&&(i[r.id]=d)}return{layoutOrder:o,assignments:e,slots:i,persona:s,confidence:m}}}}export{m as LOCAL_CONFIDENCE,O as LOCAL_ENGINE_AVAILABLE,L as LOCAL_ENGINE_SENTINEL,A as createLocalEngine,I as inferSectionTypes};
|
package/dist/index-server.d.cts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
import { a as SlotDeclInput } from './session-meta-DU_3mY7U.cjs';
|
|
2
|
+
export { S as SessionUpsertPayload, f as buildSessionUpsertPayload, g as deriveSessionSegment, h as detectDeviceClass, i as detectTimeOfDay, j as detectTrafficSource, r as referrerDomainFromReferer } from './session-meta-DU_3mY7U.cjs';
|
|
3
|
+
import { SlotResult } from '@sentientui/policy';
|
|
4
|
+
export { SlotResult } from '@sentientui/policy';
|
|
2
5
|
|
|
3
6
|
type ServerAssignConfig = {
|
|
4
7
|
/** Public API key (pk_...). */
|
|
@@ -66,20 +69,25 @@ declare function readSessionCookie(cookies: {
|
|
|
66
69
|
type DecideResult = {
|
|
67
70
|
layoutOrder: string[];
|
|
68
71
|
assignments: Record<string, string>;
|
|
72
|
+
/** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */
|
|
73
|
+
slots: Record<string, SlotResult>;
|
|
69
74
|
persona: string;
|
|
70
75
|
confidence: number;
|
|
71
76
|
};
|
|
72
77
|
/**
|
|
73
|
-
* Single-roundtrip SSR call returning layout order
|
|
74
|
-
* Falls back to default section order + empty
|
|
75
|
-
*
|
|
78
|
+
* Single-roundtrip SSR call returning layout order, component assignments,
|
|
79
|
+
* and adaptive-slot results. Falls back to default section order + empty
|
|
80
|
+
* assignments + baseline slots if the API is unavailable. A response without
|
|
81
|
+
* a `slots` field means the server predates slots — every declared slot
|
|
82
|
+
* resolves to its baseline (no retry).
|
|
76
83
|
*/
|
|
77
84
|
declare function preloadDecisions(params: {
|
|
78
|
-
sections
|
|
85
|
+
sections?: string[];
|
|
79
86
|
components: Array<{
|
|
80
87
|
id: string;
|
|
81
88
|
variantIds?: string[];
|
|
82
89
|
}>;
|
|
90
|
+
slots?: SlotDeclInput[];
|
|
83
91
|
}, sessionId: string, config: ServerAssignConfig): Promise<DecideResult>;
|
|
84
92
|
|
|
85
|
-
export { type DecideResult, type ServerAssignConfig, type ServerAssignments, preloadAssignments, preloadDecisions, readSessionCookie };
|
|
93
|
+
export { type DecideResult, type ServerAssignConfig, type ServerAssignments, SlotDeclInput, preloadAssignments, preloadDecisions, readSessionCookie };
|
package/dist/index-server.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
import { a as SlotDeclInput } from './session-meta-DU_3mY7U.js';
|
|
2
|
+
export { S as SessionUpsertPayload, f as buildSessionUpsertPayload, g as deriveSessionSegment, h as detectDeviceClass, i as detectTimeOfDay, j as detectTrafficSource, r as referrerDomainFromReferer } from './session-meta-DU_3mY7U.js';
|
|
3
|
+
import { SlotResult } from '@sentientui/policy';
|
|
4
|
+
export { SlotResult } from '@sentientui/policy';
|
|
2
5
|
|
|
3
6
|
type ServerAssignConfig = {
|
|
4
7
|
/** Public API key (pk_...). */
|
|
@@ -66,20 +69,25 @@ declare function readSessionCookie(cookies: {
|
|
|
66
69
|
type DecideResult = {
|
|
67
70
|
layoutOrder: string[];
|
|
68
71
|
assignments: Record<string, string>;
|
|
72
|
+
/** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */
|
|
73
|
+
slots: Record<string, SlotResult>;
|
|
69
74
|
persona: string;
|
|
70
75
|
confidence: number;
|
|
71
76
|
};
|
|
72
77
|
/**
|
|
73
|
-
* Single-roundtrip SSR call returning layout order
|
|
74
|
-
* Falls back to default section order + empty
|
|
75
|
-
*
|
|
78
|
+
* Single-roundtrip SSR call returning layout order, component assignments,
|
|
79
|
+
* and adaptive-slot results. Falls back to default section order + empty
|
|
80
|
+
* assignments + baseline slots if the API is unavailable. A response without
|
|
81
|
+
* a `slots` field means the server predates slots — every declared slot
|
|
82
|
+
* resolves to its baseline (no retry).
|
|
76
83
|
*/
|
|
77
84
|
declare function preloadDecisions(params: {
|
|
78
|
-
sections
|
|
85
|
+
sections?: string[];
|
|
79
86
|
components: Array<{
|
|
80
87
|
id: string;
|
|
81
88
|
variantIds?: string[];
|
|
82
89
|
}>;
|
|
90
|
+
slots?: SlotDeclInput[];
|
|
83
91
|
}, sessionId: string, config: ServerAssignConfig): Promise<DecideResult>;
|
|
84
92
|
|
|
85
|
-
export { type DecideResult, type ServerAssignConfig, type ServerAssignments, preloadAssignments, preloadDecisions, readSessionCookie };
|
|
93
|
+
export { type DecideResult, type ServerAssignConfig, type ServerAssignments, SlotDeclInput, preloadAssignments, preloadDecisions, readSessionCookie };
|
package/dist/index-server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var R=Object.defineProperty,z=Object.defineProperties,G=Object.getOwnPropertyDescriptor,K=Object.getOwnPropertyDescriptors,q=Object.getOwnPropertyNames,$=Object.getOwnPropertySymbols;var M=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable;var B=(t,e,r)=>e in t?R(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,p=(t,e)=>{for(var r in e||(e={}))M.call(e,r)&&B(t,r,e[r]);if($)for(var r of $(e))H.call(e,r)&&B(t,r,e[r]);return t},L=(t,e)=>z(t,K(e));var Q=(t,e)=>{for(var r in e)R(t,r,{get:e[r],enumerable:!0})},V=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of q(e))!M.call(t,i)&&i!==r&&R(t,i,{get:()=>e[i],enumerable:!(s=G(e,i))||s.enumerable});return t};var X=t=>V(R({},"__esModule",{value:!0}),t);var te={};Q(te,{buildSessionUpsertPayload:()=>y,deriveSessionSegment:()=>_,detectDeviceClass:()=>A,detectTimeOfDay:()=>v,detectTrafficSource:()=>w,preloadAssignments:()=>W,preloadDecisions:()=>N,readSessionCookie:()=>J,referrerDomainFromReferer:()=>x});module.exports=X(te);var Y=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function Z(t){return ee(t)!==null}function ee(t){var r;if(!t)return null;let e=t.toLowerCase();return(r=Y.find(s=>e.includes(s.toLowerCase())))!=null?r:null}function A(t){let e=t.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(e)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(e)?"mobile":"desktop"}function w(t,e){if(!t)return"direct";try{let r=new URL(t);if(e)try{if(new URL(e).host===r.host)return"direct"}catch(i){}let s=r.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(s)?"search":/(^|\.)(twitter|x\.com|facebook|linkedin|reddit|t\.co)/.test(s)?"social":"referral"}catch(r){return"direct"}}function x(t){if(!t)return null;try{return new URL(t).hostname}catch(e){return null}}function v(t){let e=t.getHours();return e<6?"night":e<12?"morning":e<18?"afternoon":"evening"}function _(t){let e=y("__segment__",t);return`${e.deviceClass}:${e.trafficSource}`}function y(t,e){var d,c,g,u,n,l,a;let r=(c=(d=e==null?void 0:e.userAgent)==null?void 0:d.trim())!=null?c:"",s=(u=(g=e==null?void 0:e.referer)==null?void 0:g.trim())!=null?u:"",i=(n=e==null?void 0:e.now)!=null?n:new Date;return{sessionId:t,ephemeral:!1,utmParams:(l=e==null?void 0:e.utmParams)!=null?l:{},deviceClass:r?A(r):"desktop",trafficSource:s?w(s,e==null?void 0:e.appOrigin):"direct",referrerDomain:x(s),timeOfDay:v(i),dayOfWeek:(a=["sun","mon","tue","wed","thu","fri","sat"][i.getDay()])!=null?a:"sun",automation:(e==null?void 0:e.webdriver)===!0||Z(r)}}var S=require("@sentientui/policy");function O(t){return p(p(p({id:t.id},t.arms?{arms:[...t.arms]}:{}),t.dims?{dims:Object.fromEntries(Object.entries(t.dims).map(([e,r])=>[e,[...r]]))}:{}),t.baseline!==void 0?{baseline:t.baseline}:{})}function U(t){let e=O(t);return(0,S.slotResultFor)(e,(0,S.slotBaselineArm)(e))}function E(t){let e={};for(let r of t)e[r.id]=U(r);return e}var F=1e3;function D(t,e,r){let s=new AbortController,i=setTimeout(()=>s.abort(),r);return fetch(t,L(p({},e),{signal:s.signal})).finally(()=>clearTimeout(i))}async function W(t,e,r){var u;let s=(u=r.timeoutMs)!=null?u:F,i={"Content-Type":"application/json",Authorization:`Bearer ${r.apiKey}`};r.origin&&(i.Origin=r.origin);let d=y(e,{userAgent:r.userAgent,referer:r.referer,utmParams:r.utmParams,appOrigin:r.origin});try{let n=await D(`${r.baseUrl}/sessions`,{method:"POST",headers:i,body:JSON.stringify(d)},s);if(n.status===402)console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing");else if(!n.ok){let l=await n.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${n.status})`,l)}}catch(n){console.error("[SentientUI] preloadAssignments: session upsert threw",n)}let c=await Promise.allSettled(t.map(async({id:n,variantIds:l})=>{let a=await D(`${r.baseUrl}/assign`,{method:"POST",headers:i,body:JSON.stringify({sessionId:e,componentId:n,variantIds:l})},s);if(!a.ok){let h=await a.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${n}" (${a.status})`,h),null}let b=await a.json();return{id:n,variantId:b.variantId}})),g={};for(let n of c)n.status==="fulfilled"&&n.value&&(g[n.value.id]=n.value.variantId);return g}function J(t){var e,r;return(r=(e=t.get("_snt_uid"))==null?void 0:e.value)!=null?r:null}async function N(t,e,r){var u,n,l,a,b,h,P,I,C,k,T;let s=(u=r.timeoutMs)!=null?u:F,i=(n=t.slots)!=null?n:[],d={layoutOrder:(l=t.sections)!=null?l:[],assignments:{},slots:E(i),persona:"unknown",confidence:0},c={"Content-Type":"application/json",Authorization:`Bearer ${r.apiKey}`};r.origin&&(c.Origin=r.origin);let g=y(e,{userAgent:r.userAgent,referer:r.referer,utmParams:r.utmParams,appOrigin:r.origin});try{let o=await D(`${r.baseUrl}/sessions`,{method:"POST",headers:c,body:JSON.stringify(g)},s);if(!o.ok){let m=await o.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${o.status})`,m)}}catch(o){console.error("[SentientUI] preloadDecisions: session upsert threw",o)}try{let o=await D(`${r.baseUrl}/decide`,{method:"POST",headers:c,body:JSON.stringify(p({sessionId:e,sections:((a=t.sections)!=null?a:[]).map(f=>({id:f})),components:t.components},i.length>0?{slots:i.map(O)}:{}))},s);if(!o.ok){let f=await o.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${o.status})`,f),d}let m=await o.json(),j={};for(let f of i)j[f.id]=(h=(b=m.slots)==null?void 0:b[f.id])!=null?h:U(f);return{layoutOrder:(I=(P=m.layoutOrder)!=null?P:t.sections)!=null?I:[],assignments:(C=m.assignments)!=null?C:{},slots:j,persona:(k=m.persona)!=null?k:"unknown",confidence:(T=m.confidence)!=null?T:0}}catch(o){return console.error("[SentientUI] preloadDecisions: decide threw",o),d}}0&&(module.exports={buildSessionUpsertPayload,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,preloadAssignments,preloadDecisions,readSessionCookie,referrerDomainFromReferer});
|
package/dist/index-server.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{d as j,e as $,f as C,g as k,h as M,i as f,j as D,k as P,l as T}from"./chunk-SVYHTU5Z.mjs";import{a as A,b as U}from"./chunk-HGGX55FR.mjs";var x=1e3;function b(r,n,e){let i=new AbortController,o=setTimeout(()=>i.abort(),e);return fetch(r,U(A({},n),{signal:i.signal})).finally(()=>clearTimeout(o))}async function B(r,n,e){var g;let i=(g=e.timeoutMs)!=null?g:x,o={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};e.origin&&(o.Origin=e.origin);let p=f(n,{userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,appOrigin:e.origin});try{let s=await b(`${e.baseUrl}/sessions`,{method:"POST",headers:o,body:JSON.stringify(p)},i);if(s.status===402)console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing");else if(!s.ok){let d=await s.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${s.status})`,d)}}catch(s){console.error("[SentientUI] preloadAssignments: session upsert threw",s)}let u=await Promise.allSettled(r.map(async({id:s,variantIds:d})=>{let a=await b(`${e.baseUrl}/assign`,{method:"POST",headers:o,body:JSON.stringify({sessionId:n,componentId:s,variantIds:d})},i);if(!a.ok){let y=await a.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${s}" (${a.status})`,y),null}let S=await a.json();return{id:s,variantId:S.variantId}})),m={};for(let s of u)s.status==="fulfilled"&&s.value&&(m[s.value.id]=s.value.variantId);return m}function J(r){var n,e;return(e=(n=r.get("_snt_uid"))==null?void 0:n.value)!=null?e:null}async function N(r,n,e){var g,s,d,a,S,y,R,h,v,w,I;let i=(g=e.timeoutMs)!=null?g:x,o=(s=r.slots)!=null?s:[],p={layoutOrder:(d=r.sections)!=null?d:[],assignments:{},slots:T(o),persona:"unknown",confidence:0},u={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};e.origin&&(u.Origin=e.origin);let m=f(n,{userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,appOrigin:e.origin});try{let t=await b(`${e.baseUrl}/sessions`,{method:"POST",headers:u,body:JSON.stringify(m)},i);if(!t.ok){let l=await t.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${t.status})`,l)}}catch(t){console.error("[SentientUI] preloadDecisions: session upsert threw",t)}try{let t=await b(`${e.baseUrl}/decide`,{method:"POST",headers:u,body:JSON.stringify(A({sessionId:n,sections:((a=r.sections)!=null?a:[]).map(c=>({id:c})),components:r.components},o.length>0?{slots:o.map(D)}:{}))},i);if(!t.ok){let c=await t.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${t.status})`,c),p}let l=await t.json(),O={};for(let c of o)O[c.id]=(y=(S=l.slots)==null?void 0:S[c.id])!=null?y:P(c);return{layoutOrder:(h=(R=l.layoutOrder)!=null?R:r.sections)!=null?h:[],assignments:(v=l.assignments)!=null?v:{},slots:O,persona:(w=l.persona)!=null?w:"unknown",confidence:(I=l.confidence)!=null?I:0}}catch(t){return console.error("[SentientUI] preloadDecisions: decide threw",t),p}}export{f as buildSessionUpsertPayload,M as deriveSessionSegment,j as detectDeviceClass,k as detectTimeOfDay,$ as detectTrafficSource,B as preloadAssignments,N as preloadDecisions,J as readSessionCookie,C as referrerDomainFromReferer};
|