@sentientui/core 0.19.1 → 0.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/{chunk-FJOZXSCS.mjs → chunk-WKU4J5I2.mjs} +2 -2
- package/dist/chunk-WKU4J5I2.mjs.map +1 -0
- package/dist/{index-DeTm1xvY.d.cts → index-DqALhS-k.d.cts} +9 -0
- package/dist/index-engagement.js.map +1 -1
- package/dist/index-engagement.mjs +1 -1
- package/dist/index-graph.d.cts +2 -2
- package/dist/index-graph.d.ts +2 -2
- package/dist/index-graph.js +1 -1
- package/dist/index-graph.js.map +1 -1
- package/dist/index-graph.mjs +1 -1
- package/dist/index-local.d.cts +1 -1
- package/dist/index-local.d.ts +1 -1
- package/dist/{index-C-VCLqSk.d.ts → index-og9t6fz3.d.ts} +9 -0
- package/dist/index-server.d.cts +7 -0
- package/dist/index-server.d.ts +7 -0
- package/dist/index-server.js +1 -1
- package/dist/index-server.js.map +1 -1
- package/dist/index-server.mjs +1 -1
- package/dist/index-server.mjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-FJOZXSCS.mjs.map +0 -1
package/dist/index-graph.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as b,d as v}from"./chunk-CD2A55US.mjs";import{a as T,i as N,k as A}from"./chunk-
|
|
1
|
+
import{a as b,d as v}from"./chunk-CD2A55US.mjs";import{a as T,i as N,k as A}from"./chunk-WKU4J5I2.mjs";import{g as $,h as k,i as U,j as L,k as j}from"./chunk-MYT7OJBV.mjs";import{a as y,b as I}from"./chunk-TMCGHANO.mjs";var x="_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 z(e){var t;return(t=K[e])!=null?t:[]}function F(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function q(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var B=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function H(e){return B.has(e)?e:"generic"}function _(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function J(e,t,n){let d=`${e}:${t}:${n.join(",")}`,p=5381;for(let m=0;m<d.length;m++)p=(p<<5)+p+d.charCodeAt(m)&4294967295;return(p>>>0).toString(16).padStart(8,"0")}function M(e){let t=new Map,n=new Map,d=`_snt_graph_nodes${T(e==null?void 0:e.apiKey)}`,p=()=>{typeof window!="undefined"&&q(d,[...t.values()])},m=o=>{var a;try{let i=JSON.parse(o);t.clear();for(let c of(a=i.pageNodes)!=null?a:[])t.set(c.componentId,c)}catch(i){}};if(typeof window!="undefined"){let o=F(d,[]);for(let a of o)t.set(a.componentId,a);try{localStorage.removeItem(x)}catch(a){}}return{addPageNode(o){t.set(o.componentId,o),p()},addStructuralEdge(o){let a=`${o.fromComponentId}->${o.toComponentId}`;n.set(a,o)},syncOnce(){var a,i;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let c=new Map;for(let s of o){let f=(a=c.get(s.semanticType))!=null?a:[];f.push(s),c.set(s.semanticType,f)}let u=[],l=new Set;for(let s of o)for(let f of z(s.semanticType)){let S=(i=c.get(f))!=null?i:[];for(let h of S){if(h.componentId===s.componentId)continue;let w=`semantic:${s.componentId}->${h.componentId}`;l.has(w)||(l.add(w),u.push({fromComponentId:s.componentId,toComponentId:h.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(o.map(s=>s.componentId));for(let s of n.values()){if(!g.has(s.fromComponentId)||!g.has(s.toComponentId))continue;let f=`structural:${s.fromComponentId}->${s.toComponentId}`;l.has(f)||(l.add(f),u.push({fromComponentId:s.fromComponentId,toComponentId:s.toComponentId,type:"structural",weight:s.weight,confidence:1}))}let r=I(y(y({pageUrl:_(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:o.map(s=>{let f=H(s.semanticType);return{componentId:s.componentId,semanticType:f,answers:s.answers,contentHash:J(s.componentId,f,s.answers),prominenceScore:s.prominenceScore,depthInPage:s.depth}}),edges:u});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:y({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(r)}).catch(()=>{})}catch(c){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:m,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(d),localStorage.removeItem(x)}catch(o){}}}}var V=new Set(["SECTION","ARTICLE","MAIN","DIV"]),W="h1, h2, h3",O=30,Y=1500,Q={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function R(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function X(e){var t,n,d;try{let p=e;for(let m of Object.keys(p)){if(!m.startsWith("__reactFiber")&&!m.startsWith("__reactInternalInstance"))continue;let o=p[m],a=(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(a&&a.length>1)return a}}catch(p){}}function Z(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var P=new Set(b);function ee(e){let t=e.getAttribute("data-sentient-type");if(t&&P.has(t))return t;let n=e.getAttribute("role");return n&&P.has(n)?n:v(e)}function te(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)&4294967295;return(t>>>0).toString(16).padStart(8,"0")}function ne(e){let t=[],n=e;for(;n;){let d=n.parentElement;if(!d){t.push(n.tagName.toLowerCase());break}let p=Array.prototype.indexOf.call(d.children,n);t.push(`${n.tagName.toLowerCase()}[${p}]`),n=d}return t.reverse().join("/")}function oe(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${te(ne(e))}`}function re(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function C(e,t){var d,p,m;let n=e.querySelector(W);return{componentId:oe(e),semanticType:ee(e),ariaLabel:(d=e.getAttribute("aria-label"))!=null?d:void 0,headingText:(m=(p=n==null?void 0:n.textContent)==null?void 0:p.trim())!=null?m:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:re(e),reactComponentName:X(e),dataAttributes:Z(e)}}function D(e){var m;let t=[],n=new Set,d="__root__",p=new Map;for(let[o,a]of e){let i=o.parentElement,c=d;for(;i;){if(e.has(i)){c=e.get(i);let l=e.get(o),g=`${c}->${l}`;!n.has(g)&&c!==l&&(n.add(g),t.push({fromComponentId:c,toComponentId:l,weight:.6}));break}i=i.parentElement}let u=(m=p.get(c))!=null?m:[];u.push(o),p.set(c,u)}for(let o of p.values()){if(o.length<2)continue;let a=o.length>O?o.slice(0,O):o;for(let i=0;i<a.length;i++)for(let c=i+1;c<a.length;c++){if(t.length>=Y)return t;let u=e.get(a[i]),l=e.get(a[c]);if(u===l)continue;let g=`${u}->${l}::sib`,r=`${l}->${u}::sib`;n.has(g)||(n.add(g),t.push({fromComponentId:u,toComponentId:l,weight:.3})),n.has(r)||(n.add(r),t.push({fromComponentId:l,toComponentId:u,weight:.3}))}}return t}function se(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 a=C(o,e);t.push(a),d.set(o,a.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(o=>{if(!(o instanceof Element)||n.has(o))return;let a=o.hasAttribute("aria-label"),i=o.hasAttribute("data-sentient-id");if(!a&&!i)return;n.add(o);let c=C(o,e);t.push(c),d.set(o,c.componentId)}),{nodes:t,edges:D(d),elementToId:d}}function G(){if(typeof window=="undefined")return Q;let e=null,t=0,n=null,d=new Map,p=i=>{try{let c=window.getComputedStyle(i),u=parseFloat(c.fontSize)||12,l=parseFloat(c.zIndex)||0,g=i.getBoundingClientRect(),r=Math.max(g.top,0),s=window.innerHeight||1,f=1/(r/s+1),S=R(u,12,48)*.4+f*.4+R(l,0,100)*.2;return Math.max(0,Math.min(1,S))}catch(c){return .5}};return{scan:()=>new Promise(i=>{let c=()=>{let{nodes:u,edges:l,elementToId:g}=se(p);d.clear();for(let[r,s]of g)d.set(r,s);i({nodes:u,edges:l,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(c,{timeout:100}):c()}catch(u){c()}}),observe:i=>{n=i;try{e=new MutationObserver(c=>{let u=[],l=new Set;for(let r of c)r.type==="childList"&&r.addedNodes.forEach(s=>{if(!(s instanceof Element)||!V.has(s.tagName))return;let f=s.hasAttribute("data-sentient-id"),S=s.hasAttribute("aria-label");if(!f&&!S)return;let h=C(s,p);u.push(h),l.add(h.componentId),d.set(s,h.componentId)});if(u.length===0||!n)return;for(let r of[...d.keys()])r.isConnected||d.delete(r);let g=D(d).filter(r=>l.has(r.fromComponentId)||l.has(r.toComponentId));n({nodes:u,edges:g,addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(c){}},getProminenceScore:p,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(i){}t=0,n=null,d.clear()}}}var ae="https://api.sentient-ui.com/v1/events";function ie(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}var E=new Map;function he(e){var l;let t=A(e),n=e.respectDoNotTrack!==!1&&N(),d=e.consent===!1||n;if(!e.graph||!e.apiKey||d||typeof window=="undefined")return t;let p=E.get(e.apiKey);if(p)try{p()}catch(g){}let m=G(),o=(l=e.ingestUrl)!=null?l:ae,a=M({syncUrl:o.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:ie()});m.scan().then(g=>{for(let r of g.nodes)a.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:e.captureDomText&&r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});for(let r of g.edges)a.addStructuralEdge(r);a.syncOnce()});let i=null,c=()=>{i!==null&&clearTimeout(i),i=setTimeout(()=>{i=null,a.syncOnce()},500)};m.observe(g=>{for(let r of g.nodes)a.addPageNode({id:r.componentId,componentId:r.componentId,semanticType:r.semanticType,answers:e.captureDomText&&r.headingText?[r.headingText]:[],prominenceScore:r.prominenceScore,depth:r.depth});for(let r of g.edges)a.addStructuralEdge(r);c()});let u=()=>{i!==null&&(clearTimeout(i),i=null),m.destroy(),a.destroy(),E.get(e.apiKey)===u&&E.delete(e.apiKey)};return E.set(e.apiKey,u),I(y({},t),{getGraph:()=>a.snapshot(),dispose:()=>{u(),t.dispose()},destroy:()=>{u(),t.destroy()}})}export{j as deriveSessionSegment,$ as detectDeviceClass,L as detectTimeOfDay,k as detectTrafficSource,he as init,U as referrerDomainFromReferer,_ as sanitizePageUrl};
|
|
2
2
|
//# sourceMappingURL=index-graph.mjs.map
|
package/dist/index-local.d.cts
CHANGED
package/dist/index-local.d.ts
CHANGED
|
@@ -254,6 +254,15 @@ type SentientConfig = {
|
|
|
254
254
|
*/
|
|
255
255
|
respectDoNotTrack?: boolean;
|
|
256
256
|
userId?: string;
|
|
257
|
+
/**
|
|
258
|
+
* Declared persona — the role your app already knows for this visitor
|
|
259
|
+
* (e.g. 'admin', 'evaluator'). Must be a key in the project's persona
|
|
260
|
+
* vocabulary (dashboard → Settings → Personas); unrecognized values are
|
|
261
|
+
* ignored server-side and surfaced in the dashboard so you can add them.
|
|
262
|
+
* Declared personas are served at full confidence, overriding the inferred
|
|
263
|
+
* one. Keep it a low-cardinality role label — never a user id or email.
|
|
264
|
+
*/
|
|
265
|
+
persona?: string;
|
|
257
266
|
/**
|
|
258
267
|
* Session ID generated server-side (from `loadAdaptiveAssignments` / `loadAdaptiveDecision`).
|
|
259
268
|
* When provided, the client adopts this ID on first visit instead of generating a new one,
|
package/dist/index-server.d.cts
CHANGED
|
@@ -30,6 +30,13 @@ type ServerAssignConfig = {
|
|
|
30
30
|
* assignment on every page view before the client can.
|
|
31
31
|
*/
|
|
32
32
|
doNotTrack?: boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Declared persona — the role your app already knows for this visitor
|
|
35
|
+
* (e.g. from your auth context during SSR). Same contract as the client
|
|
36
|
+
* option: must be a vocabulary key; unrecognized values are ignored
|
|
37
|
+
* server-side. Never a user id or email.
|
|
38
|
+
*/
|
|
39
|
+
persona?: string;
|
|
33
40
|
/**
|
|
34
41
|
* Milliseconds to wait for the API before returning default variants.
|
|
35
42
|
* Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path
|
package/dist/index-server.d.ts
CHANGED
|
@@ -30,6 +30,13 @@ type ServerAssignConfig = {
|
|
|
30
30
|
* assignment on every page view before the client can.
|
|
31
31
|
*/
|
|
32
32
|
doNotTrack?: boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Declared persona — the role your app already knows for this visitor
|
|
35
|
+
* (e.g. from your auth context during SSR). Same contract as the client
|
|
36
|
+
* option: must be a vocabulary key; unrecognized values are ignored
|
|
37
|
+
* server-side. Never a user id or email.
|
|
38
|
+
*/
|
|
39
|
+
persona?: string;
|
|
33
40
|
/**
|
|
34
41
|
* Milliseconds to wait for the API before returning default variants.
|
|
35
42
|
* Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path
|
package/dist/index-server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var R=Object.defineProperty,z=Object.defineProperties,J=Object.getOwnPropertyDescriptor,K=Object.getOwnPropertyDescriptors,q=Object.getOwnPropertyNames,$=Object.getOwnPropertySymbols;var E=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable;var j=(
|
|
1
|
+
"use strict";var R=Object.defineProperty,z=Object.defineProperties,J=Object.getOwnPropertyDescriptor,K=Object.getOwnPropertyDescriptors,q=Object.getOwnPropertyNames,$=Object.getOwnPropertySymbols;var E=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable;var j=(r,e,t)=>e in r?R(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,a=(r,e)=>{for(var t in e||(e={}))E.call(e,t)&&j(r,t,e[t]);if($)for(var t of $(e))H.call(e,t)&&j(r,t,e[t]);return r},L=(r,e)=>z(r,K(e));var Q=(r,e)=>{for(var t in e)R(r,t,{get:e[t],enumerable:!0})},V=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of q(e))!E.call(r,o)&&o!==t&&R(r,o,{get:()=>e[o],enumerable:!(s=J(e,o))||s.enumerable});return r};var X=r=>V(R({},"__esModule",{value:!0}),r);var te={};Q(te,{buildSessionUpsertPayload:()=>y,deriveSessionSegment:()=>M,detectDeviceClass:()=>x,detectTimeOfDay:()=>I,detectTrafficSource:()=>D,preloadAssignments:()=>G,preloadDecisions:()=>W,readSessionCookie:()=>F,referrerDomainFromReferer:()=>w});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(r){return ee(r)!==null}function ee(r){var t;if(!r)return null;let e=r.toLowerCase();return(t=Y.find(s=>e.includes(s.toLowerCase())))!=null?t:null}function x(r){let e=r.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(e)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(e)?"mobile":"desktop"}function D(r,e){if(!r)return"direct";try{let t=new URL(r);if(e)try{if(new URL(e).host===t.host)return"direct"}catch(o){}let s=t.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(s)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(s)?"social":"referral"}catch(t){return"direct"}}function w(r){if(!r)return null;try{return new URL(r).hostname}catch(e){return null}}function I(r){let e=r.getHours();return e<6?"night":e<12?"morning":e<18?"afternoon":"evening"}function M(r){let e=y("__segment__",r);return`${e.deviceClass}:${e.trafficSource}`}function y(r,e){var u,d,m,g,n,c,l;let t=(d=(u=e==null?void 0:e.userAgent)==null?void 0:u.trim())!=null?d:"",s=(g=(m=e==null?void 0:e.referer)==null?void 0:m.trim())!=null?g:"",o=(n=e==null?void 0:e.now)!=null?n:new Date;return{sessionId:r,ephemeral:!1,utmParams:(c=e==null?void 0:e.utmParams)!=null?c:{},deviceClass:t?x(t):"desktop",trafficSource:s?D(s,e==null?void 0:e.appOrigin):"direct",referrerDomain:w(s),timeOfDay:I(o),dayOfWeek:(l=["sun","mon","tue","wed","thu","fri","sat"][o.getDay()])!=null?l:"sun",automation:(e==null?void 0:e.webdriver)===!0||Z(t)}}var S=require("@sentientui/policy");function U(r){return a(a(a({id:r.id},r.arms?{arms:[...r.arms]}:{}),r.dims?{dims:Object.fromEntries(Object.entries(r.dims).map(([e,t])=>[e,[...t]]))}:{}),r.baseline!==void 0?{baseline:r.baseline}:{})}function C(r){let e=U(r);return(0,S.slotResultFor)(e,(0,S.slotBaselineArm)(e))}function N(r){let e={};for(let t of r)e[t.id]=C(t);return e}var _=1e3;function A(r,e,t){let s=new AbortController,o=setTimeout(()=>s.abort(),t);return fetch(r,L(a({},e),{signal:s.signal})).finally(()=>clearTimeout(o))}async function G(r,e,t){var g;if(t.doNotTrack)return{};let s=(g=t.timeoutMs)!=null?g:_,o={"Content-Type":"application/json",Authorization:`Bearer ${t.apiKey}`};t.origin&&(o.Origin=t.origin);let u=a(a({},y(e,{userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,appOrigin:t.origin})),t.persona?{persona:t.persona}:{});try{let n=await A(`${t.baseUrl}/sessions`,{method:"POST",headers:o,body:JSON.stringify(u)},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 c=await n.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${n.status})`,c)}}catch(n){console.error("[SentientUI] preloadAssignments: session upsert threw",n)}let d=await Promise.allSettled(r.map(async({id:n,variantIds:c})=>{let l=await A(`${t.baseUrl}/assign`,{method:"POST",headers:o,body:JSON.stringify({sessionId:e,componentId:n,variantIds:c})},s);if(!l.ok){let b=await l.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${n}" (${l.status})`,b),null}let h=await l.json();return{id:n,variantId:h.variantId}})),m={};for(let n of d)n.status==="fulfilled"&&n.value&&(m[n.value.id]=n.value.variantId);return m}function F(r){var e,t;return(t=(e=r.get("_snt_uid"))==null?void 0:e.value)!=null?t:null}async function W(r,e,t){var g,n,c,l,h,b,O,P,v,T,k;let s=(g=t.timeoutMs)!=null?g:_,o=(n=r.slots)!=null?n:[],u={layoutOrder:(c=r.sections)!=null?c:[],assignments:{},slots:N(o),persona:"unknown",confidence:0};if(t.doNotTrack)return u;let d={"Content-Type":"application/json",Authorization:`Bearer ${t.apiKey}`};t.origin&&(d.Origin=t.origin);let m=a(a({},y(e,{userAgent:t.userAgent,referer:t.referer,utmParams:t.utmParams,appOrigin:t.origin})),t.persona?{persona:t.persona}:{});try{let i=await A(`${t.baseUrl}/sessions`,{method:"POST",headers:d,body:JSON.stringify(m)},s);if(!i.ok){let p=await i.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${i.status})`,p)}}catch(i){console.error("[SentientUI] preloadDecisions: session upsert threw",i)}try{let i=await A(`${t.baseUrl}/decide`,{method:"POST",headers:d,body:JSON.stringify(a(a({sessionId:e,sections:((l=r.sections)!=null?l:[]).map(f=>({id:f})),components:r.components},o.length>0?{slots:o.map(U)}:{}),t.persona?{persona:t.persona}:{}))},s);if(!i.ok){let f=await i.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${i.status})`,f),u}let p=await i.json(),B={};for(let f of o)B[f.id]=(b=(h=p.slots)==null?void 0:h[f.id])!=null?b:C(f);return{layoutOrder:(P=(O=p.layoutOrder)!=null?O:r.sections)!=null?P:[],assignments:(v=p.assignments)!=null?v:{},slots:B,persona:(T=p.persona)!=null?T:"unknown",confidence:(k=p.confidence)!=null?k:0}}catch(i){return console.error("[SentientUI] preloadDecisions: decide threw",i),u}}0&&(module.exports={buildSessionUpsertPayload,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,preloadAssignments,preloadDecisions,readSessionCookie,referrerDomainFromReferer});
|
|
2
2
|
//# sourceMappingURL=index-server.js.map
|
package/dist/index-server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index-server.ts","../src/session-meta.ts","../src/slots.ts","../src/server.ts"],"sourcesContent":["/**\n * Server-only entry (`@sentientui/core/server`). SSR preload helpers that are\n * never needed in the browser — kept out of the lean client bundle.\n */\n\nexport { preloadAssignments, readSessionCookie, preloadDecisions } from './server.js';\nexport type { ServerAssignConfig, ServerAssignments, DecideResult, SlotDeclInput, SlotResult } from './server.js';\n\nexport {\n deriveSessionSegment,\n buildSessionUpsertPayload,\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n referrerDomainFromReferer,\n} from './session-meta.js';\nexport type { SessionUpsertPayload } from './session-meta.js';\n","/** Session metadata helpers (browser + Node). No DOM APIs. */\n\n/**\n * Known AI-agent / crawler user-agent tokens. Matched case-insensitively as\n * substrings. This is maintained data — bot lists move monthly. Used both to\n * flag automation on sessions (agentic browsers that leak a token) and by the\n * server middleware / agent-feed route to identify crawler HTTP reads.\n */\nexport const agentUaList: readonly string[] = [\n 'GPTBot',\n 'ChatGPT-User',\n 'OAI-SearchBot',\n 'ClaudeBot',\n 'Claude-User',\n 'Claude-SearchBot',\n 'PerplexityBot',\n 'Perplexity-User',\n 'Google-Extended',\n 'Applebot-Extended',\n 'Meta-ExternalAgent',\n 'Bytespider',\n 'CCBot',\n 'Amazonbot',\n 'cohere-ai',\n 'Diffbot',\n];\n\n/** True when the user-agent contains a known AI-agent / crawler token. */\nexport function uaTokenMatch(userAgent: string): boolean {\n return matchedAgentToken(userAgent) !== null;\n}\n\n/** The first known agent token found in the user-agent, or null. */\nexport function matchedAgentToken(userAgent: string): string | null {\n if (!userAgent) return null;\n const s = userAgent.toLowerCase();\n return agentUaList.find((token) => s.includes(token.toLowerCase())) ?? null;\n}\n\n/**\n * Purpose category for an agent fetch, inferred from its published user-agent:\n * - `user` — a person asked an assistant to read the page, live (…-User UAs)\n * - `search` — indexing for an AI answer engine (…-SearchBot / SearchBot)\n * - `training` — model-training crawl (GPTBot, ClaudeBot, CCBot, …)\n * - `other` — not clearly AI, or an unknown/new token\n */\nexport type AgentIntent = 'user' | 'search' | 'training' | 'other';\n\n/** Intent per agent token. Maintained beside `agentUaList` — when you add or\n * rename a token above, set its intent here (a unit test enforces coverage). */\nexport const AGENT_INTENTS: Record<string, AgentIntent> = {\n 'GPTBot': 'training',\n 'ChatGPT-User': 'user',\n 'OAI-SearchBot': 'search',\n 'ClaudeBot': 'training',\n 'Claude-User': 'user',\n 'Claude-SearchBot': 'search',\n 'PerplexityBot': 'search',\n 'Perplexity-User': 'user',\n 'Google-Extended': 'training',\n 'Applebot-Extended': 'training',\n 'Meta-ExternalAgent': 'training',\n 'Bytespider': 'training',\n 'CCBot': 'training',\n 'Amazonbot': 'other',\n 'cohere-ai': 'training',\n 'Diffbot': 'other',\n};\n\n/** Intent for a matched bot token (case-insensitive); `other` for null/unknown. */\nexport function agentIntent(botName: string | null): AgentIntent {\n if (!botName) return 'other';\n const hit = agentUaList.find((t) => t.toLowerCase() === botName.toLowerCase());\n return (hit && AGENT_INTENTS[hit]) || 'other';\n}\n\n/** `agentUaList` grouped by intent — the \"which crawlers do you classify?\" reference. */\nexport function classifiedAgents(): Record<AgentIntent, string[]> {\n const out: Record<AgentIntent, string[]> = { user: [], search: [], training: [], other: [] };\n for (const t of agentUaList) out[AGENT_INTENTS[t] ?? 'other'].push(t);\n return out;\n}\n\nexport function detectDeviceClass(userAgent: string): string {\n const s = userAgent.toLowerCase();\n if (/ipad|tablet|playbook|kindle|silk/.test(s)) return 'tablet';\n if (/mobi|iphone|ipod|android.*mobile|phone/.test(s)) return 'mobile';\n return 'desktop';\n}\n\nexport function detectTrafficSource(referrer: string, appOrigin?: string): string {\n if (!referrer) return 'direct';\n try {\n const refUrl = new URL(referrer);\n if (appOrigin) {\n try {\n if (new URL(appOrigin).host === refUrl.host) return 'direct';\n } catch {\n /* ignore invalid appOrigin */\n }\n }\n const host = refUrl.hostname.toLowerCase();\n if (/(^|\\.)(google|bing|duckduckgo|yahoo)\\./.test(host)) return 'search';\n // Anchor to the registrable domain (exact host or a subdomain of it) so\n // hosts like `x.company.com`, `t.company.io` or `linkedinsights.com` are not\n // misclassified as social by an unbounded substring match.\n if (/(^|\\.)(twitter\\.com|x\\.com|facebook\\.com|linkedin\\.com|reddit\\.com|t\\.co)$/.test(host)) return 'social';\n return 'referral';\n } catch {\n return 'direct';\n }\n}\n\nexport function referrerDomainFromReferer(referrer: string): string | null {\n if (!referrer) return null;\n try {\n return new URL(referrer).hostname;\n } catch {\n return null;\n }\n}\n\nexport function detectTimeOfDay(d: Date): string {\n const h = d.getHours();\n if (h < 6) return 'night';\n if (h < 12) return 'morning';\n if (h < 18) return 'afternoon';\n return 'evening';\n}\n\nexport type SessionUpsertPayload = {\n sessionId: string;\n ephemeral: boolean;\n utmParams: Record<string, string>;\n deviceClass: string;\n trafficSource: string;\n referrerDomain: string | null;\n timeOfDay: string;\n dayOfWeek: string;\n /**\n * True when this session is likely driven by automation — either\n * `navigator.webdriver` was set, or the user-agent carried a known agent\n * token. Probabilistic: a flag for metrics + bandit exclusion, never a gate.\n */\n automation: boolean;\n};\n\n/** Bandit segment key: `<device_class>:<traffic_source>`. */\nexport function deriveSessionSegment(opts?: {\n userAgent?: string;\n referer?: string;\n appOrigin?: string;\n}): string {\n const body = buildSessionUpsertPayload('__segment__', opts);\n return `${body.deviceClass}:${body.trafficSource}`;\n}\n\n/**\n * Builds a session upsert body aligned with the browser SDK so SSR assign uses\n * the same segment key (`device:source`) as the client after hydration.\n */\nexport function buildSessionUpsertPayload(\n sessionId: string,\n opts?: {\n userAgent?: string;\n referer?: string;\n appOrigin?: string;\n utmParams?: Record<string, string>;\n now?: Date;\n /** `navigator.webdriver` value from the browser, when available. */\n webdriver?: boolean;\n },\n): SessionUpsertPayload {\n const ua = opts?.userAgent?.trim() ?? '';\n const referer = opts?.referer?.trim() ?? '';\n const now = opts?.now ?? new Date();\n return {\n sessionId,\n ephemeral: false,\n utmParams: opts?.utmParams ?? {},\n deviceClass: ua ? detectDeviceClass(ua) : 'desktop',\n trafficSource: referer\n ? detectTrafficSource(referer, opts?.appOrigin)\n : 'direct',\n referrerDomain: referrerDomainFromReferer(referer),\n timeOfDay: detectTimeOfDay(now),\n dayOfWeek: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][now.getDay()] ?? 'sun',\n automation: opts?.webdriver === true || uaTokenMatch(ua),\n };\n}\n","/**\n * Slot declaration helpers shared by the browser client (decide) and the\n * server preload path. Pure wrappers over @sentientui/policy.\n */\nimport {\n canonicalArm,\n slotBaselineArm,\n slotResultFor,\n type SlotDecl,\n type SlotResult,\n} from '@sentientui/policy';\n\n/** SDK-facing slot declaration. `dims` accepts readonly arrays (`as const`). */\nexport type SlotDeclInput = {\n id: string;\n arms?: string[];\n dims?: Record<string, readonly string[]>;\n baseline?: string | Record<string, string>;\n};\n\nexport type { SlotResult };\n\n/**\n * Whitelists the wire fields of a slot declaration. Anything an SDK layer\n * attached (goal configs, refs, …) is stripped so it never reaches the zod\n * schema on the API. Also normalizes readonly arrays to mutable ones.\n */\nexport function toWireSlot(d: SlotDeclInput): SlotDecl {\n return {\n id: d.id,\n ...(d.arms ? { arms: [...d.arms] } : {}),\n ...(d.dims\n ? {\n dims: Object.fromEntries(\n Object.entries(d.dims).map(([dim, values]) => [dim, [...values]]),\n ),\n }\n : {}),\n ...(d.baseline !== undefined ? { baseline: d.baseline } : {}),\n };\n}\n\n/** The declared (or default first-declared) baseline result for a slot. */\nexport function baselineResultFor(d: SlotDeclInput): SlotResult {\n const decl = toWireSlot(d);\n return slotResultFor(decl, slotBaselineArm(decl));\n}\n\n/** Baseline results for a whole declaration list, keyed by slot id. */\nexport function baselineSlots(decls: SlotDeclInput[]): Record<string, SlotResult> {\n const out: Record<string, SlotResult> = {};\n for (const d of decls) out[d.id] = baselineResultFor(d);\n return out;\n}\n\n/**\n * Canonical arm string of a slot result: dims results encode as sorted\n * `dim=value` pairs joined with '|'; arms results are the arm id verbatim.\n */\nexport function armOfResult(result: SlotResult): string {\n return typeof result === 'string' ? result : canonicalArm(result);\n}\n","/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nexport type { SlotDeclInput, SlotResult };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\n });\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n): string | null {\n return cookies.get('_snt_uid')?.value ?? null;\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n\n const sessionBody = buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\n });\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"owBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,+BAAAE,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,uBAAAC,EAAA,qBAAAC,EAAA,sBAAAC,EAAA,8BAAAC,IAAA,eAAAC,EAAAX,ICQO,IAAMY,EAAiC,CAC5C,SACA,eACA,gBACA,YACA,cACA,mBACA,gBACA,kBACA,kBACA,oBACA,qBACA,aACA,QACA,YACA,YACA,SACF,EAGO,SAASC,EAAaC,EAA4B,CACvD,OAAOC,GAAkBD,CAAS,IAAM,IAC1C,CAGO,SAASC,GAAkBD,EAAkC,CAjCpE,IAAAE,EAkCE,GAAI,CAACF,EAAW,OAAO,KACvB,IAAMG,EAAIH,EAAU,YAAY,EAChC,OAAOE,EAAAJ,EAAY,KAAMM,GAAUD,EAAE,SAASC,EAAM,YAAY,CAAC,CAAC,IAA3D,KAAAF,EAAgE,IACzE,CA8CO,SAASG,EAAkBC,EAA2B,CAC3D,IAAMC,EAA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AAAS,EACA,SAASR,EAAAO,EAAK,UAAL,KAAAP,EAAgB,UACzB,YAAYC,EAAAM,EAAK,aAAL,KAAAN,EAAmB,CACjC,CACF,OAASnB,EAAK,CACZ,eAAQ,MAAM,8CAA+CA,CAAG,EACzDqB,CACT,CACF","names":["index_server_exports","__export","buildSessionUpsertPayload","deriveSessionSegment","detectDeviceClass","detectTimeOfDay","detectTrafficSource","preloadAssignments","preloadDecisions","readSessionCookie","referrerDomainFromReferer","__toCommonJS","agentUaList","uaTokenMatch","userAgent","matchedAgentToken","_a","s","token","detectDeviceClass","userAgent","s","detectTrafficSource","referrer","appOrigin","refUrl","e","host","referrerDomainFromReferer","detectTimeOfDay","d","h","deriveSessionSegment","opts","body","buildSessionUpsertPayload","sessionId","_a","_b","_c","_d","_e","_f","_g","ua","referer","now","uaTokenMatch","import_policy","toWireSlot","d","__spreadValues","dim","values","baselineResultFor","decl","baselineSlots","decls","out","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","_b","preloadDecisions","params","_c","_d","_e","_f","_g","_h","_i","_j","_k","declaredSlots","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor"]}
|
|
1
|
+
{"version":3,"sources":["../src/index-server.ts","../src/session-meta.ts","../src/slots.ts","../src/server.ts"],"sourcesContent":["/**\n * Server-only entry (`@sentientui/core/server`). SSR preload helpers that are\n * never needed in the browser — kept out of the lean client bundle.\n */\n\nexport { preloadAssignments, readSessionCookie, preloadDecisions } from './server.js';\nexport type { ServerAssignConfig, ServerAssignments, DecideResult, SlotDeclInput, SlotResult } from './server.js';\n\nexport {\n deriveSessionSegment,\n buildSessionUpsertPayload,\n detectDeviceClass,\n detectTrafficSource,\n detectTimeOfDay,\n referrerDomainFromReferer,\n} from './session-meta.js';\nexport type { SessionUpsertPayload } from './session-meta.js';\n","/** Session metadata helpers (browser + Node). No DOM APIs. */\n\n/**\n * Known AI-agent / crawler user-agent tokens. Matched case-insensitively as\n * substrings. This is maintained data — bot lists move monthly. Used both to\n * flag automation on sessions (agentic browsers that leak a token) and by the\n * server middleware / agent-feed route to identify crawler HTTP reads.\n */\nexport const agentUaList: readonly string[] = [\n 'GPTBot',\n 'ChatGPT-User',\n 'OAI-SearchBot',\n 'ClaudeBot',\n 'Claude-User',\n 'Claude-SearchBot',\n 'PerplexityBot',\n 'Perplexity-User',\n 'Google-Extended',\n 'Applebot-Extended',\n 'Meta-ExternalAgent',\n 'Bytespider',\n 'CCBot',\n 'Amazonbot',\n 'cohere-ai',\n 'Diffbot',\n];\n\n/** True when the user-agent contains a known AI-agent / crawler token. */\nexport function uaTokenMatch(userAgent: string): boolean {\n return matchedAgentToken(userAgent) !== null;\n}\n\n/** The first known agent token found in the user-agent, or null. */\nexport function matchedAgentToken(userAgent: string): string | null {\n if (!userAgent) return null;\n const s = userAgent.toLowerCase();\n return agentUaList.find((token) => s.includes(token.toLowerCase())) ?? null;\n}\n\n/**\n * Purpose category for an agent fetch, inferred from its published user-agent:\n * - `user` — a person asked an assistant to read the page, live (…-User UAs)\n * - `search` — indexing for an AI answer engine (…-SearchBot / SearchBot)\n * - `training` — model-training crawl (GPTBot, ClaudeBot, CCBot, …)\n * - `other` — not clearly AI, or an unknown/new token\n */\nexport type AgentIntent = 'user' | 'search' | 'training' | 'other';\n\n/** Intent per agent token. Maintained beside `agentUaList` — when you add or\n * rename a token above, set its intent here (a unit test enforces coverage). */\nexport const AGENT_INTENTS: Record<string, AgentIntent> = {\n 'GPTBot': 'training',\n 'ChatGPT-User': 'user',\n 'OAI-SearchBot': 'search',\n 'ClaudeBot': 'training',\n 'Claude-User': 'user',\n 'Claude-SearchBot': 'search',\n 'PerplexityBot': 'search',\n 'Perplexity-User': 'user',\n 'Google-Extended': 'training',\n 'Applebot-Extended': 'training',\n 'Meta-ExternalAgent': 'training',\n 'Bytespider': 'training',\n 'CCBot': 'training',\n 'Amazonbot': 'other',\n 'cohere-ai': 'training',\n 'Diffbot': 'other',\n};\n\n/** Intent for a matched bot token (case-insensitive); `other` for null/unknown. */\nexport function agentIntent(botName: string | null): AgentIntent {\n if (!botName) return 'other';\n const hit = agentUaList.find((t) => t.toLowerCase() === botName.toLowerCase());\n return (hit && AGENT_INTENTS[hit]) || 'other';\n}\n\n/** `agentUaList` grouped by intent — the \"which crawlers do you classify?\" reference. */\nexport function classifiedAgents(): Record<AgentIntent, string[]> {\n const out: Record<AgentIntent, string[]> = { user: [], search: [], training: [], other: [] };\n for (const t of agentUaList) out[AGENT_INTENTS[t] ?? 'other'].push(t);\n return out;\n}\n\nexport function detectDeviceClass(userAgent: string): string {\n const s = userAgent.toLowerCase();\n if (/ipad|tablet|playbook|kindle|silk/.test(s)) return 'tablet';\n if (/mobi|iphone|ipod|android.*mobile|phone/.test(s)) return 'mobile';\n return 'desktop';\n}\n\nexport function detectTrafficSource(referrer: string, appOrigin?: string): string {\n if (!referrer) return 'direct';\n try {\n const refUrl = new URL(referrer);\n if (appOrigin) {\n try {\n if (new URL(appOrigin).host === refUrl.host) return 'direct';\n } catch {\n /* ignore invalid appOrigin */\n }\n }\n const host = refUrl.hostname.toLowerCase();\n if (/(^|\\.)(google|bing|duckduckgo|yahoo)\\./.test(host)) return 'search';\n // Anchor to the registrable domain (exact host or a subdomain of it) so\n // hosts like `x.company.com`, `t.company.io` or `linkedinsights.com` are not\n // misclassified as social by an unbounded substring match.\n if (/(^|\\.)(twitter\\.com|x\\.com|facebook\\.com|linkedin\\.com|reddit\\.com|t\\.co)$/.test(host)) return 'social';\n return 'referral';\n } catch {\n return 'direct';\n }\n}\n\nexport function referrerDomainFromReferer(referrer: string): string | null {\n if (!referrer) return null;\n try {\n return new URL(referrer).hostname;\n } catch {\n return null;\n }\n}\n\nexport function detectTimeOfDay(d: Date): string {\n const h = d.getHours();\n if (h < 6) return 'night';\n if (h < 12) return 'morning';\n if (h < 18) return 'afternoon';\n return 'evening';\n}\n\nexport type SessionUpsertPayload = {\n sessionId: string;\n ephemeral: boolean;\n utmParams: Record<string, string>;\n deviceClass: string;\n trafficSource: string;\n referrerDomain: string | null;\n timeOfDay: string;\n dayOfWeek: string;\n /**\n * True when this session is likely driven by automation — either\n * `navigator.webdriver` was set, or the user-agent carried a known agent\n * token. Probabilistic: a flag for metrics + bandit exclusion, never a gate.\n */\n automation: boolean;\n};\n\n/** Bandit segment key: `<device_class>:<traffic_source>`. */\nexport function deriveSessionSegment(opts?: {\n userAgent?: string;\n referer?: string;\n appOrigin?: string;\n}): string {\n const body = buildSessionUpsertPayload('__segment__', opts);\n return `${body.deviceClass}:${body.trafficSource}`;\n}\n\n/**\n * Builds a session upsert body aligned with the browser SDK so SSR assign uses\n * the same segment key (`device:source`) as the client after hydration.\n */\nexport function buildSessionUpsertPayload(\n sessionId: string,\n opts?: {\n userAgent?: string;\n referer?: string;\n appOrigin?: string;\n utmParams?: Record<string, string>;\n now?: Date;\n /** `navigator.webdriver` value from the browser, when available. */\n webdriver?: boolean;\n },\n): SessionUpsertPayload {\n const ua = opts?.userAgent?.trim() ?? '';\n const referer = opts?.referer?.trim() ?? '';\n const now = opts?.now ?? new Date();\n return {\n sessionId,\n ephemeral: false,\n utmParams: opts?.utmParams ?? {},\n deviceClass: ua ? detectDeviceClass(ua) : 'desktop',\n trafficSource: referer\n ? detectTrafficSource(referer, opts?.appOrigin)\n : 'direct',\n referrerDomain: referrerDomainFromReferer(referer),\n timeOfDay: detectTimeOfDay(now),\n dayOfWeek: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][now.getDay()] ?? 'sun',\n automation: opts?.webdriver === true || uaTokenMatch(ua),\n };\n}\n","/**\n * Slot declaration helpers shared by the browser client (decide) and the\n * server preload path. Pure wrappers over @sentientui/policy.\n */\nimport {\n canonicalArm,\n slotBaselineArm,\n slotResultFor,\n type SlotDecl,\n type SlotResult,\n} from '@sentientui/policy';\n\n/** SDK-facing slot declaration. `dims` accepts readonly arrays (`as const`). */\nexport type SlotDeclInput = {\n id: string;\n arms?: string[];\n dims?: Record<string, readonly string[]>;\n baseline?: string | Record<string, string>;\n};\n\nexport type { SlotResult };\n\n/**\n * Whitelists the wire fields of a slot declaration. Anything an SDK layer\n * attached (goal configs, refs, …) is stripped so it never reaches the zod\n * schema on the API. Also normalizes readonly arrays to mutable ones.\n */\nexport function toWireSlot(d: SlotDeclInput): SlotDecl {\n return {\n id: d.id,\n ...(d.arms ? { arms: [...d.arms] } : {}),\n ...(d.dims\n ? {\n dims: Object.fromEntries(\n Object.entries(d.dims).map(([dim, values]) => [dim, [...values]]),\n ),\n }\n : {}),\n ...(d.baseline !== undefined ? { baseline: d.baseline } : {}),\n };\n}\n\n/** The declared (or default first-declared) baseline result for a slot. */\nexport function baselineResultFor(d: SlotDeclInput): SlotResult {\n const decl = toWireSlot(d);\n return slotResultFor(decl, slotBaselineArm(decl));\n}\n\n/** Baseline results for a whole declaration list, keyed by slot id. */\nexport function baselineSlots(decls: SlotDeclInput[]): Record<string, SlotResult> {\n const out: Record<string, SlotResult> = {};\n for (const d of decls) out[d.id] = baselineResultFor(d);\n return out;\n}\n\n/**\n * Canonical arm string of a slot result: dims results encode as sorted\n * `dim=value` pairs joined with '|'; arms results are the arm id verbatim.\n */\nexport function armOfResult(result: SlotResult): string {\n return typeof result === 'string' ? result : canonicalArm(result);\n}\n","/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nexport type { SlotDeclInput, SlotResult };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n): string | null {\n return cookies.get('_snt_uid')?.value ?? null;\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"owBAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,+BAAAE,EAAA,yBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,uBAAAC,EAAA,qBAAAC,EAAA,sBAAAC,EAAA,8BAAAC,IAAA,eAAAC,EAAAX,IC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AAII,CAAU,CAAE,EAAI,CAAC,GACvE/B,EAAO,QAAU,CAAE,QAASA,EAAO,OAAQ,EAAI,CAAC,EACrD,CACH,EACAR,CACF,EACA,GAAI,CAACa,EAAI,GAAI,CACX,IAAMC,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,eAAQ,MAAM,iDAAiDA,EAAI,MAAM,IAAKC,CAAI,EAC3EsB,CACT,CACA,IAAMI,EAAQ,MAAM3B,EAAI,KAAK,EAQvB4B,EAAoC,CAAC,EAC3C,QAAWC,KAAKP,EAEdM,EAAMC,EAAE,EAAE,GAAIb,GAAAD,EAAAY,EAAK,QAAL,YAAAZ,EAAac,EAAE,MAAf,KAAAb,EAAsBc,EAAkBD,CAAC,EAGzD,MAAO,CACL,aAAaX,GAAAD,EAAAU,EAAK,cAAL,KAAAV,EAAoBL,EAAO,WAA3B,KAAAM,EAAuC,CAAC,EACrD,aAAaC,EAAAQ,EAAK,cAAL,KAAAR,EAAoB,CAAC,EAClC,MAAAS,EACA,SAASR,EAAAO,EAAK,UAAL,KAAAP,EAAgB,UACzB,YAAYC,EAAAM,EAAK,aAAL,KAAAN,EAAmB,CACjC,CACF,OAASnB,EAAK,CACZ,eAAQ,MAAM,8CAA+CA,CAAG,EACzDqB,CACT,CACF","names":["index_server_exports","__export","buildSessionUpsertPayload","deriveSessionSegment","detectDeviceClass","detectTimeOfDay","detectTrafficSource","preloadAssignments","preloadDecisions","readSessionCookie","referrerDomainFromReferer","__toCommonJS","agentUaList","uaTokenMatch","userAgent","matchedAgentToken","_a","s","token","detectDeviceClass","userAgent","s","detectTrafficSource","referrer","appOrigin","refUrl","e","host","referrerDomainFromReferer","detectTimeOfDay","d","h","deriveSessionSegment","opts","body","buildSessionUpsertPayload","sessionId","_a","_b","_c","_d","_e","_f","_g","ua","referer","now","uaTokenMatch","import_policy","toWireSlot","d","__spreadValues","dim","values","baselineResultFor","decl","baselineSlots","decls","out","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","_b","preloadDecisions","params","_c","_d","_e","_f","_g","_h","_i","_j","_k","declaredSlots","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor"]}
|
package/dist/index-server.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{g as x,h as j,i as $,j as C,k as M,l as
|
|
1
|
+
import{g as x,h as j,i as $,j as C,k as M,l as b,m as U,n as D,o as P}from"./chunk-MYT7OJBV.mjs";import{a,b as T}from"./chunk-TMCGHANO.mjs";var k=1e3;function A(r,n,e){let i=new AbortController,o=setTimeout(()=>i.abort(),e);return fetch(r,T(a({},n),{signal:i.signal})).finally(()=>clearTimeout(o))}async function N(r,n,e){var m;if(e.doNotTrack)return{};let i=(m=e.timeoutMs)!=null?m:k,o={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};e.origin&&(o.Origin=e.origin);let p=a(a({},b(n,{userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,appOrigin:e.origin})),e.persona?{persona:e.persona}:{});try{let s=await A(`${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 u=await s.json().catch(()=>({}));console.error(`[SentientUI] preloadAssignments: session upsert failed (${s.status})`,u)}}catch(s){console.error("[SentientUI] preloadAssignments: session upsert threw",s)}let g=await Promise.allSettled(r.map(async({id:s,variantIds:u})=>{let l=await A(`${e.baseUrl}/assign`,{method:"POST",headers:o,body:JSON.stringify({sessionId:n,componentId:s,variantIds:u})},i);if(!l.ok){let f=await l.json().catch(()=>({}));return console.error(`[SentientUI] preloadAssignments: assign failed for "${s}" (${l.status})`,f),null}let y=await l.json();return{id:s,variantId:y.variantId}})),S={};for(let s of g)s.status==="fulfilled"&&s.value&&(S[s.value.id]=s.value.variantId);return S}function B(r){var n,e;return(e=(n=r.get("_snt_uid"))==null?void 0:n.value)!=null?e:null}async function J(r,n,e){var m,s,u,l,y,f,R,h,v,w,I;let i=(m=e.timeoutMs)!=null?m:k,o=(s=r.slots)!=null?s:[],p={layoutOrder:(u=r.sections)!=null?u:[],assignments:{},slots:P(o),persona:"unknown",confidence:0};if(e.doNotTrack)return p;let g={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`};e.origin&&(g.Origin=e.origin);let S=a(a({},b(n,{userAgent:e.userAgent,referer:e.referer,utmParams:e.utmParams,appOrigin:e.origin})),e.persona?{persona:e.persona}:{});try{let t=await A(`${e.baseUrl}/sessions`,{method:"POST",headers:g,body:JSON.stringify(S)},i);if(!t.ok){let d=await t.json().catch(()=>({}));console.error(`[SentientUI] preloadDecisions: session upsert failed (${t.status})`,d)}}catch(t){console.error("[SentientUI] preloadDecisions: session upsert threw",t)}try{let t=await A(`${e.baseUrl}/decide`,{method:"POST",headers:g,body:JSON.stringify(a(a({sessionId:n,sections:((l=r.sections)!=null?l:[]).map(c=>({id:c})),components:r.components},o.length>0?{slots:o.map(U)}:{}),e.persona?{persona:e.persona}:{}))},i);if(!t.ok){let c=await t.json().catch(()=>({}));return console.error(`[SentientUI] preloadDecisions: decide failed (${t.status})`,c),p}let d=await t.json(),O={};for(let c of o)O[c.id]=(f=(y=d.slots)==null?void 0:y[c.id])!=null?f:D(c);return{layoutOrder:(h=(R=d.layoutOrder)!=null?R:r.sections)!=null?h:[],assignments:(v=d.assignments)!=null?v:{},slots:O,persona:(w=d.persona)!=null?w:"unknown",confidence:(I=d.confidence)!=null?I:0}}catch(t){return console.error("[SentientUI] preloadDecisions: decide threw",t),p}}export{b as buildSessionUpsertPayload,M as deriveSessionSegment,x as detectDeviceClass,C as detectTimeOfDay,j as detectTrafficSource,N as preloadAssignments,J as preloadDecisions,B as readSessionCookie,$ as referrerDomainFromReferer};
|
|
2
2
|
//# sourceMappingURL=index-server.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nexport type { SlotDeclInput, SlotResult };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\n });\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n): string | null {\n return cookies.get('_snt_uid')?.value ?? null;\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n\n const sessionBody = buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\n });\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n };\n } catch (err) {\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sBc,EAAkBD,CAAC,EAGzD,MAAO,CACL,aAAaX,GAAAD,EAAAU,EAAK,cAAL,KAAAV,EAAoBL,EAAO,WAA3B,KAAAM,EAAuC,CAAC,EACrD,aAAaC,EAAAQ,EAAK,cAAL,KAAAR,EAAoB,CAAC,EAClC,MAAAS,EACA,SAASR,EAAAO,EAAK,UAAL,KAAAP,EAAgB,UACzB,YAAYC,EAAAM,EAAK,aAAL,KAAAN,EAAmB,CACjC,CACF,OAASnB,EAAK,CACZ,eAAQ,MAAM,8CAA+CA,CAAG,EACzDqB,CACT,CACF","names":["DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","_b","preloadDecisions","params","_c","_d","_e","_f","_g","_h","_i","_j","_k","declaredSlots","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nexport type { SlotDeclInput, SlotResult };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n): string | null {\n return cookies.get('_snt_uid')?.value ?? null;\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"4IAiEA,IAAMA,EAAqB,IAE3B,SAASC,EACPC,EACAC,EACAC,EACmB,CACnB,IAAMC,EAAa,IAAI,gBACjBC,EAAQ,WAAW,IAAMD,EAAW,MAAM,EAAGD,CAAS,EAC5D,OAAO,MAAMF,EAAKK,EAAAC,EAAA,GAAKL,GAAL,CAAW,OAAQE,EAAW,MAAO,EAAC,EAAE,QAAQ,IAChE,aAAaC,CAAK,CACpB,CACF,CAqBA,eAAsBG,EACpBC,EACAC,EACAC,EAC4B,CAtG9B,IAAAC,EAwGE,GAAID,EAAO,WAAY,MAAO,CAAC,EAE/B,IAAMR,GAAYS,EAAAD,EAAO,YAAP,KA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AAN,EAAmB,CACjC,CACF,OAASnB,EAAK,CACZ,eAAQ,MAAM,8CAA+CA,CAAG,EACzDqB,CACT,CACF","names":["DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","_b","preloadDecisions","params","_c","_d","_e","_f","_g","_h","_i","_j","_k","declaredSlots","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, d as CompoundLocator, D as DecideInput, e as DecideOutcome, f as DecisionSnapshot, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LOCAL_MODE_BANNER, M as MicroSignalEmitter, l as MicroSignalType, P as PROD_KEYLESS_ERROR, Q as QueueConfig, S as SNAPSHOT_STORAGE_KEY_PREFIX, n as SectionMapEntry, o as SentientClient, p as SentientConfig, q as SentientEvent, r as SessionConfig, s as SessionManager, t as SlotConfigEntry, u as SlotOps, W as WeightEntry, v as attachMicroSignalDetectors, w as grantConsent, x as init, y as isDoNotTrackEnabled, z as readSnapshot, B as renderPrePaintScript, H as writeSnapshot } from './index-
|
|
1
|
+
export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, d as CompoundLocator, D as DecideInput, e as DecideOutcome, f as DecisionSnapshot, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LOCAL_MODE_BANNER, M as MicroSignalEmitter, l as MicroSignalType, P as PROD_KEYLESS_ERROR, Q as QueueConfig, S as SNAPSHOT_STORAGE_KEY_PREFIX, n as SectionMapEntry, o as SentientClient, p as SentientConfig, q as SentientEvent, r as SessionConfig, s as SessionManager, t as SlotConfigEntry, u as SlotOps, W as WeightEntry, v as attachMicroSignalDetectors, w as grantConsent, x as init, y as isDoNotTrackEnabled, z as readSnapshot, B as renderPrePaintScript, H as writeSnapshot } from './index-DqALhS-k.cjs';
|
|
2
2
|
export { A as AGENT_INTENTS, a as AgentIntent, b as SlotDeclInput, c as agentIntent, d as agentUaList, e as armOfResult, f as baselineResultFor, g as baselineSlots, i as classifiedAgents, j as deriveSessionSegment, k as detectDeviceClass, l as detectTimeOfDay, m as detectTrafficSource, n as matchedAgentToken, r as referrerDomainFromReferer, t as toWireSlot, u as uaTokenMatch } from './session-meta-BVvq5RBB.cjs';
|
|
3
3
|
export { SlotResult } from '@sentientui/policy';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, d as CompoundLocator, D as DecideInput, e as DecideOutcome, f as DecisionSnapshot, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LOCAL_MODE_BANNER, M as MicroSignalEmitter, l as MicroSignalType, P as PROD_KEYLESS_ERROR, Q as QueueConfig, S as SNAPSHOT_STORAGE_KEY_PREFIX, n as SectionMapEntry, o as SentientClient, p as SentientConfig, q as SentientEvent, r as SessionConfig, s as SessionManager, t as SlotConfigEntry, u as SlotOps, W as WeightEntry, v as attachMicroSignalDetectors, w as grantConsent, x as init, y as isDoNotTrackEnabled, z as readSnapshot, B as renderPrePaintScript, H as writeSnapshot } from './index-
|
|
1
|
+
export { A as AssignResult, a as Assignment, C as ComponentGoalOptions, c as ComponentWeightEntry, d as CompoundLocator, D as DecideInput, e as DecideOutcome, f as DecisionSnapshot, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LOCAL_MODE_BANNER, M as MicroSignalEmitter, l as MicroSignalType, P as PROD_KEYLESS_ERROR, Q as QueueConfig, S as SNAPSHOT_STORAGE_KEY_PREFIX, n as SectionMapEntry, o as SentientClient, p as SentientConfig, q as SentientEvent, r as SessionConfig, s as SessionManager, t as SlotConfigEntry, u as SlotOps, W as WeightEntry, v as attachMicroSignalDetectors, w as grantConsent, x as init, y as isDoNotTrackEnabled, z as readSnapshot, B as renderPrePaintScript, H as writeSnapshot } from './index-og9t6fz3.js';
|
|
2
2
|
export { A as AGENT_INTENTS, a as AgentIntent, b as SlotDeclInput, c as agentIntent, d as agentUaList, e as armOfResult, f as baselineResultFor, g as baselineSlots, i as classifiedAgents, j as deriveSessionSegment, k as detectDeviceClass, l as detectTimeOfDay, m as detectTrafficSource, n as matchedAgentToken, r as referrerDomainFromReferer, t as toWireSlot, u as uaTokenMatch } from './session-meta-BVvq5RBB.js';
|
|
3
3
|
export { SlotResult } from '@sentientui/policy';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var lt=Object.create;var ue=Object.defineProperty,ct=Object.defineProperties,dt=Object.getOwnPropertyDescriptor,ut=Object.getOwnPropertyDescriptors,gt=Object.getOwnPropertyNames,$e=Object.getOwnPropertySymbols,pt=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty,ft=Object.prototype.propertyIsEnumerable;var Fe=(e,t,n)=>t in e?ue(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,k=(e,t)=>{for(var n in t||(t={}))We.call(t,n)&&Fe(e,n,t[n]);if($e)for(var n of $e(t))ft.call(t,n)&&Fe(e,n,t[n]);return e},te=(e,t)=>ct(e,ut(t));var mt=(e,t)=>{for(var n in t)ue(e,n,{get:t[n],enumerable:!0})},je=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of gt(t))!We.call(e,u)&&u!==n&&ue(e,u,{get:()=>t[u],enumerable:!(c=dt(t,u))||c.enumerable});return e};var yt=(e,t,n)=>(n=e!=null?lt(pt(e)):{},je(t||!e||!e.__esModule?ue(n,"default",{value:e,enumerable:!0}):n,e)),ht=e=>je(ue({},"__esModule",{value:!0}),e);var zt={};mt(zt,{AGENT_INTENTS:()=>Re,LOCAL_MODE_BANNER:()=>Ge,PROD_KEYLESS_ERROR:()=>Oe,SNAPSHOT_STORAGE_KEY_PREFIX:()=>Z,agentIntent:()=>ze,agentUaList:()=>ge,armOfResult:()=>Ae,attachMicroSignalDetectors:()=>tt,baselineResultFor:()=>se,baselineSlots:()=>Xe,classifiedAgents:()=>Ve,deriveSessionSegment:()=>Ye,detectDeviceClass:()=>fe,detectTimeOfDay:()=>he,detectTrafficSource:()=>me,grantConsent:()=>Ht,init:()=>it,isDoNotTrackEnabled:()=>Be,matchedAgentToken:()=>Ne,readSnapshot:()=>_e,referrerDomainFromReferer:()=>ye,renderPrePaintScript:()=>qe,toWireSlot:()=>Se,uaTokenMatch:()=>pe,writeSnapshot:()=>ie});module.exports=ht(zt);function we(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(t+="-");return t}}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function be(e){return e?`_${e.slice(0,12)}`:""}var St="_snt_uid",vt=365,wt="_snt_uid";function bt(){return we()}function xt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function It(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(c){}}function Et(e){try{return localStorage.getItem(e)}catch(t){return null}}function kt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function Ct(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function Rt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function At(e){try{sessionStorage.removeItem(e)}catch(t){}}function _t(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function Tt(e){try{localStorage.removeItem(e)}catch(t){}}function Dt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Ot={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function xe(e){var y,b,D,R,I,M;if(typeof window=="undefined")return Ot;let t=be(e==null?void 0:e.apiKey),n=(y=e==null?void 0:e.cookieName)!=null?y:`${St}${t}`,c=`${wt}${t}`,s=((b=e==null?void 0:e.cookieTTLDays)!=null?b:vt)*24*60*60,g=C=>C&&C.length>0?C:null,d=(M=(I=(R=(D=g(xt(n)))!=null?D:g(Et(c)))!=null?R:g(Ct(c)))!=null?I:g(e==null?void 0:e.ssrSessionId))!=null?M:bt();It(n,d,s);let o=kt(c,d),r=_t(n),i=o?!1:Rt(c,d),a=!o&&!r&&!i;return{getSessionId:()=>d,isEphemeral:()=>a,destroy:()=>{d=null,Dt(n),Tt(c),At(c)}}}function ne(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function Ie(e){if(e.ok===!0)return"delivered";let{status:t}=e;return typeof t!="number"?"retry":t>=200&&t<300?"delivered":t>=400&&t<500&&t!==429?"dropped":"retry"}function Ee(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let c=JSON.parse(n);return Array.isArray(c)?(localStorage.removeItem(e),c.slice(-t)):[]}catch(n){return[]}}function re(e,t,n){try{let c=(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let g=JSON.parse(s);return Array.isArray(g)?g:[]}catch(s){return[]}})(),u=new Map;for(let s of c)u.set(s.id,s);for(let s of e)u.set(s.id,s);localStorage.setItem(n,JSON.stringify([...u.values()].slice(-t)))}catch(c){}}function ke(e,t){try{let n=localStorage.getItem(t);if(!n)return;let c=JSON.parse(n);if(!Array.isArray(c))return;let u=new Set(e),s=c.filter(g=>!u.has(g.id));if(s.length===c.length)return;s.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(s))}catch(n){}}var Pt=500,Lt=56*1024;function Le(e){return`_snt_retry_${e.slice(0,12)}`}var Mt={push:()=>{},flush:()=>{},destroy:()=>{}};function Qe(e){var O,j,Q;if(typeof window=="undefined")return Mt;let t=(O=e.flushIntervalMs)!=null?O:5e3,n=(j=e.maxBatchSize)!=null?j:20,c=(Q=e.maxRetrySize)!=null?Q:100,u=e.ingestUrl,s=e.apiKey,g=Le(s),d=[],o=new Set,r=[],i=f=>{for(let S of f)a.delete(S),!o.has(S)&&(o.add(S),r.push(S));for(;r.length>Pt;){let S=r.shift();S&&o.delete(S)}ke(f,g)},a=new Set,y=f=>{o.has(f.id)||a.has(f.id)||(a.add(f.id),d.push(f))},b=f=>{for(let S of f)o.has(S.id)||(a.add(S.id),d.push(S))},D=Ee(g,c);for(let f of D)y(f);let R=0,I=0,M=(f,S=!0)=>{if(f.length===0)return;let H=JSON.stringify(f),q=f.map(z=>z.id),B;try{B=fetch(u,{method:"POST",keepalive:!0,body:H,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(z){re(f,c,g),b(f),I++,R=Date.now()+ne(I);return}let ae=z=>{if(Ie(z)!=="retry"){if(!z.ok&&S){let ee=f.filter(V=>V.eventType!=="pageview");if(ee.length>0&&ee.length<f.length){i(f.filter(V=>V.eventType==="pageview").map(V=>V.id)),M(ee,!1);return}}i(q),I=0,R=0;return}re(f,c,g),b(f),I++,R=Date.now()+ne(I)};B instanceof Promise?B.then(ae).catch(()=>{re(f,c,g),b(f),I++,R=Date.now()+ne(I)}):ae(B)},C=typeof TextEncoder!="undefined"?new TextEncoder:null,E=f=>C?C.encode(f).length:f.length,X=f=>{let S=[],H=2;for(let q of f){let B=E(JSON.stringify(q))+1;if(S.length>0&&H+B>Lt||S.length>=n)break;S.push(q),H+=B}return S},A=()=>{try{if(Date.now()<R)return;for(;d.length>0&&!(Date.now()<R);){let f=d.filter(H=>!o.has(H.id));if(d.length=0,f.length===0)break;let S=X(f);if(S.length===0)break;S.length<f.length&&d.push(...f.slice(S.length)),M(S)}}catch(f){}},m=!0,v=null;v=setInterval(()=>{m&&A()},t);let J=()=>{document.visibilityState==="hidden"&&A()},G=()=>{A()};return document.addEventListener("visibilitychange",J),window.addEventListener("pagehide",G),{push(f){y(f),d.length>=n&&A()},flush:A,destroy(){m=!1,v!==null&&(clearInterval(v),v=null),document.removeEventListener("visibilitychange",J),window.removeEventListener("pagehide",G),A()}}}var Nt=200;function Me(e){return`_snt_goal_retry_${e.slice(0,12)}`}var Gt={send:()=>{},flush:()=>{},destroy:()=>{}};function He(e){var E,X,A;if(typeof window=="undefined")return Gt;let t=(E=e.flushIntervalMs)!=null?E:5e3,n=(X=e.maxRetrySize)!=null?X:100,c=(A=e.maxPerFlush)!=null?A:5,u=Me(e.apiKey),s=[],g=new Set,d=new Set,o=[],r=0,i=0,a=!1,y=m=>{for(g.delete(m.id),d.has(m.id)||(d.add(m.id),o.push(m.id));o.length>Nt;){let v=o.shift();v&&d.delete(v)}ke([m.id],u)},b=m=>{re([m],n,u),!d.has(m.id)&&!g.has(m.id)&&(g.add(m.id),s.push(m)),i++,r=Date.now()+ne(i)},D=m=>{let v;try{v=fetch(e.url,{method:"POST",keepalive:!0,body:m.body,headers:e.headers})}catch(G){b(m);return}let J=G=>{var j;let O=Ie(G);if(O==="retry"){b(m);return}O==="dropped"&&((j=e.onDrop)==null||j.call(e,m,G.status)),y(m),i=0,r=0};v instanceof Promise?v.then(J).catch(()=>b(m)):J(v)},R=()=>{try{if(a||Date.now()<r)return;let m=0;for(;s.length>0&&m<c&&!(Date.now()<r);){let v=s.shift();g.delete(v.id),!d.has(v.id)&&(m++,D(v))}}catch(m){}};for(let m of Ee(u,n))g.has(m.id)||(g.add(m.id),s.push(m));let I=setInterval(R,t),M=()=>{document.visibilityState==="hidden"&&R()},C=()=>R();return document.addEventListener("visibilitychange",M),window.addEventListener("pagehide",C),{send(m){if(!a&&!(d.has(m.id)||g.has(m.id))){if(Date.now()<r){g.add(m.id),s.push(m);return}D(m)}},flush:R,destroy(){clearInterval(I),document.removeEventListener("visibilitychange",M),window.removeEventListener("pagehide",C),R(),a=!0}}}var Kt=1800*1e3;function Ce(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Je(e=Kt,t){let n=new Map,c=`_snt_asgn${be(t)}_`,u=(r,i)=>`${c}${encodeURIComponent(r)}:${encodeURIComponent(i)}`,s=r=>{let i=r.slice(c.length),a=i.indexOf(":");if(a<0)return null;try{return{componentId:decodeURIComponent(i.slice(0,a)),segment:decodeURIComponent(i.slice(a+1))}}catch(y){return null}},g=()=>{try{let r=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a!=null&&a.startsWith(c)&&r.push(a)}return r}catch(r){return[]}},d=r=>r.assignedAt+(r.ttlMs&&r.ttlMs>0?r.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let r of g())try{let i=localStorage.getItem(r);if(!i)continue;let a=JSON.parse(i);if(d(a)){localStorage.removeItem(r);continue}let y=s(r);if(!y)continue;n.set(Ce(y.componentId,y.segment),a)}catch(i){}})(),{get(r,i){let a=n.get(Ce(r,i));return a?d(a)?(n.delete(Ce(r,i)),null):a:null},set(r,i,a){let y=Ce(r,i);n.set(y,a);try{localStorage.setItem(u(r,i),JSON.stringify(a))}catch(b){}},invalidate(r){let i=`${encodeURIComponent(r)}:`;for(let a of[...n.keys()])a.startsWith(i)&&n.delete(a);for(let a of g()){let y=s(a);if((y==null?void 0:y.componentId)===r)try{localStorage.removeItem(a)}catch(b){}}},clear(){n.clear();for(let r of g())try{localStorage.removeItem(r)}catch(i){}}}}var ge=["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 pe(e){return Ne(e)!==null}function Ne(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=ge.find(c=>t.includes(c.toLowerCase())))!=null?n:null}var Re={GPTBot:"training","ChatGPT-User":"user","OAI-SearchBot":"search",ClaudeBot:"training","Claude-User":"user","Claude-SearchBot":"search",PerplexityBot:"search","Perplexity-User":"user","Google-Extended":"training","Applebot-Extended":"training","Meta-ExternalAgent":"training",Bytespider:"training",CCBot:"training",Amazonbot:"other","cohere-ai":"training",Diffbot:"other"};function ze(e){if(!e)return"other";let t=ge.find(n=>n.toLowerCase()===e.toLowerCase());return t&&Re[t]||"other"}function Ve(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of ge)e[(t=Re[n])!=null?t:"other"].push(n);return e}function fe(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 me(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(u){}let c=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(c)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(c)?"social":"referral"}catch(n){return"direct"}}function ye(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function he(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ye(e){let t=Ut("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Ut(e,t){var s,g,d,o,r,i,a;let n=(g=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?g:"",c=(o=(d=t==null?void 0:t.referer)==null?void 0:d.trim())!=null?o:"",u=(r=t==null?void 0:t.now)!=null?r:new Date;return{sessionId:e,ephemeral:!1,utmParams:(i=t==null?void 0:t.utmParams)!=null?i:{},deviceClass:n?fe(n):"desktop",trafficSource:c?me(c,t==null?void 0:t.appOrigin):"direct",referrerDomain:ye(c),timeOfDay:he(u),dayOfWeek:(a=["sun","mon","tue","wed","thu","fri","sat"][u.getDay()])!=null?a:"sun",automation:(t==null?void 0:t.webdriver)===!0||pe(n)}}var oe=require("@sentientui/policy");function Se(e){return k(k(k({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 se(e){let t=Se(e);return(0,oe.slotResultFor)(t,(0,oe.slotBaselineArm)(t))}function Xe(e){let t={};for(let n of e)t[n.id]=se(n);return t}function Ae(e){return typeof e=="string"?e:(0,oe.canonicalArm)(e)}var Z="_snt_snap:",Bt=["low","medium","high"];function _e(e){try{let t=localStorage.getItem(Z+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!Bt.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function ie(e,t){try{localStorage.setItem(Z+e,JSON.stringify(t))}catch(n){}}function qe(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(Z+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}var Ue=require("@sentientui/policy");var De=require("@sentientui/policy");var Oe="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ge="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",Ze=!1,Te=!1;function $t(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function et(e){var d;let t=xe({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(d=t.getSessionId())!=null?d:"local",c=$t(),u=import("@sentientui/core/local").then(o=>{let r=o;return r.LOCAL_ENGINE_AVAILABLE?(Ze||(Ze=!0,console.info(Ge)),r):(Te||(Te=!0,console.error(Oe)),null)}).catch(()=>(Te||(Te=!0,console.error(Oe)),null)),s=null;function g(o){let r=document.documentElement;r.dataset.sentientPersona===void 0&&(r.dataset.sentientPersona=o.persona,r.dataset.sentientConfidence=(0,De.confidenceBand)(o.confidence))}return{isLocal:!0,async decide(o){var a,y,b;let r=await u;if(!r)return null;let i=r.createLocalEngine({sessionId:n,forcedPersona:c}).decide(o);return s=te(k({},i),{layoutOrder:(y=(a=i.layoutOrder)!=null?a:s==null?void 0:s.layoutOrder)!=null?y:null,slots:k(k({},(b=s==null?void 0:s.slots)!=null?b:{}),i.slots)}),ie(e.apiKey||"local",{v:1,persona:s.persona,band:(0,De.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),g(i),i},getSlotResult(o){var r,i,a;return(a=(i=s==null?void 0:s.slots[o])!=null?i:(r=e.initialSlots)==null?void 0:r[o])!=null?a:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,De.confidenceBand)(s.confidence)}:null},async assign(o,r){var y;let i=await u;return!i||!r||r.length===0?r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null:{variantId:(y=i.createLocalEngine({sessionId:n,forcedPersona:c}).decide({components:[{id:o,variantIds:r}]}).assignments[o])!=null?y:r[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function tt(e,t,n,c){let u=[];{let d=!1,o=[],r=()=>{if(d)return;let i=Date.now();for(o.push(i);o.length>0&&i-o[0]>500;)o.shift();o.length>=3&&(d=!0,e("rage_click"))};t.addEventListener("click",r),u.push(()=>t.removeEventListener("click",r))}{let s=!1,g=d=>{if(s||!(d.target instanceof Node)||!t.contains(d.target)&&t!==d.target)return;s=!0;let o=typeof window!="undefined"?window.getSelection():null,r=o?o.toString().length:0;e("text_copy",{selectionLength:r})};document.addEventListener("copy",g),u.push(()=>document.removeEventListener("copy",g))}{let s=!1,g=!1,d=null,o=()=>{d!==null&&(clearTimeout(d),d=null)},r=()=>{s||!g||(o(),d=setTimeout(()=>{!s&&g&&(s=!0,e("scroll_hesitation"))},3e3))},i=()=>{o(),r()},a=b=>{for(let D of b)g=D.intersectionRatio>.3,g?r():o()},y=new IntersectionObserver(a,{threshold:[.3]});y.observe(t),window.addEventListener("scroll",i,{passive:!0}),u.push(()=>{y.disconnect(),window.removeEventListener("scroll",i),o()})}if((c==null?void 0:c.tabLoss)!==!1){let s=!1,g=n!=null?n:Date.now(),d=()=>{if(s||document.visibilityState!=="hidden")return;let o=Date.now()-g;o<15e3&&(s=!0,e("tab_loss",{timeOnPage:o}))};document.addEventListener("visibilitychange",d),u.push(()=>document.removeEventListener("visibilitychange",d))}return()=>{for(let s of u)s()}}var nt="https://api.sentient-ui.com/v1/events",L=new Map,rt=null;function Ft(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}function Ke(){return we()}function Pe(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function Wt(e){if(typeof MessageChannel=="function"){let t=new MessageChannel;t.port1.onmessage=()=>{e.clear(),t.port1.close(),t.port2.close()},t.port2.postMessage(0)}else setTimeout(()=>e.clear(),0)}var ot=new Set;function jt(e,t,n){let c=typeof window=="undefined"?null:window.history;if(!c)return()=>{};let u=!1,s,g=()=>{if(u)return;let r=Pe();!r||r===s||(s=r,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${r}`))},d=[];for(let r of["pushState","replaceState"]){let i=c[r],a=function(...y){let b=i.apply(this,y);return g(),b};c[r]=a,d.push([r,i,a])}window.addEventListener("popstate",g);let o=Pe();return o&&ot.has(`${t}:${o}`)?s=o:g(),()=>{if(!u){u=!0,window.removeEventListener("popstate",g);for(let[r,i,a]of d)c[r]===a&&(c[r]=i)}}}var ve={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function Qt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,c]of t)n.startsWith("utm_")&&(e[n]=c);return e}catch(e){return{}}}function st(e){return e.replace(/\/events\/?$/,"")}function Be(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function Ht(e){var d;if(typeof window=="undefined")return;let t=e!=null?e:rt;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=L.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:c,upgrade:u}=n;if(!u||c.respectDoNotTrack!==!1&&Be())return;let s=it(te(k({},c),{consent:!0}));u(s);let g=(d=L.get(t))==null?void 0:d.dispose;L.set(t,{config:te(k({},c),{consent:!0}),upgrade:null,dispose:g})}function Jt(e){var d;let t=e.preConsentBehavior==="statistical_winner",n=st((d=e.ingestUrl)!=null?d:nt),c={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(o,r,i){if(!t)return null;try{let a=new URLSearchParams({componentId:o});for(let D of r!=null?r:[])a.append("variantIds[]",D);let y=await fetch(`${n}/winner?${a.toString()}`,{headers:c});return y.ok?{variantId:(await y.json()).variantId,assignmentTtlMs:0}:r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}catch(a){return r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},s={track:o=>u.track(o),goal:((o,r,i,a)=>u.goal(o,r,i,a)),componentGoal:(o,r,i)=>u.componentGoal(o,r,i),identify:o=>u.identify(o),getAssignment:(o,r)=>u.getAssignment(o,r),assign:(o,r,i,a)=>u.assign(o,r,i,a),decide:o=>u.decide(o),getSlotResult:o=>u.getSlotResult(o),getPersona:()=>u.getPersona(),fetchWeights:()=>u.fetchWeights(),getGraph:()=>u.getGraph(),dispose:()=>u.dispose(),destroy:()=>u.destroy()};function g(o){u=o}return{proxy:s,setInner:g}}function it(e){var f,S,H,q,B,ae,z,ee,V;if(typeof window=="undefined")return ve;rt=e.apiKey;let t=L.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(l){}let n=e.respectDoNotTrack!==!1&&Be(),c=e.consent===!1||n,u=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!u&&e.localMode!==!1)return c?(L.set(e.apiKey||"local",{config:e,upgrade:null}),ve):(L.set(e.apiKey||"local",{config:e,upgrade:null}),et(e));if(c){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return e.preConsentBehavior==="statistical_winner"&&console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),L.set(e.apiKey,{config:e,upgrade:null}),ve;let{proxy:l,setInner:p}=Jt(e);return L.set(e.apiKey,{config:e,upgrade:n?null:p}),l}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."),ve;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),ve;let s=(f=e.ingestUrl)!=null?f:nt,g=Date.now(),d=xe({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),o=Je(void 0,e.apiKey),r=Qe({ingestUrl:s,apiKey:e.apiKey}),i=st(s),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},y=He({url:`${i}/goals`,apiKey:e.apiKey,headers:a,onDrop:(l,p)=>{e.debug&&console.warn(`[sentient] goal dropped (HTTP ${p}) \u2014 this will not be retried. `+(p===400?"The session was not found: call init() and let the session upsert complete before firing goals.":p===401||p===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),l)}}),b=fe((S=navigator.userAgent)!=null?S:""),D=typeof window!="undefined"?window.location.origin:void 0,R=me((H=document.referrer)!=null?H:"",D),I=(q=e.sessionSegment)!=null?q:`${b}:${R}`,M=new Map,C=new Map,E=null,X=l=>{for(let p of l)C.has(p.id)||C.set(p.id,se(p))};if(e.initialSlots)for(let[l,p]of Object.entries(e.initialSlots))C.set(l,p);let A=_e(e.apiKey);if(A)for(let[l,p]of Object.entries(A.slots))C.has(l)||C.set(l,p);let m={low:.15,medium:.5,high:.85};if(e.initialPersona)E=k({},e.initialPersona);else{let l=document.documentElement.dataset;l.sentientPersona?E={persona:l.sentientPersona,confidence:(ae=m[(B=l.sentientConfidence)!=null?B:"low"])!=null?ae:.15}:A&&(E={persona:A.persona,confidence:(z=m[A.band])!=null?z:.15})}if(e.initialAssignments)for(let[l,p]of Object.entries(e.initialAssignments))o.set(l,I,{variantId:p,assignedAt:Date.now(),segment:I,confidence:1});let v=Promise.resolve(),J=d.getSessionId();if(J){let l=ye((ee=document.referrer)!=null?ee:""),p=k(k({sessionId:J,deviceClass:b,trafficSource:R,referrerDomain:l,utmParams:Qt(),timeOfDay:he(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:d.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||pe((V=navigator.userAgent)!=null?V:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{v=fetch(`${i}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(p),headers:a}).then(h=>{h.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(h){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:r});let G=new Set,O=null,j=!1,Q={goal(l,p={},h=1,K=0){var T,le,W,ce,x,Y;let P=d.getSessionId();if(!P)return;let w=Ft(p)?p:{metadata:p},$=`${l}\0${(T=w.externalId)!=null?T:""}\0${(le=w.stepIndex)!=null?le:K}\0${(W=w.weight)!=null?W:h}`;if(G.has($)){e.debug&&console.log(`[sentient] goal("${l}") already recorded for this action \u2014 not sent twice`);return}G.add($),G.size===1&&Wt(G);let U=Ke(),_={sessionId:P,name:l,metadata:(ce=w.metadata)!=null?ce:{},weight:(x=w.weight)!=null?x:h,stepIndex:(Y=w.stepIndex)!=null?Y:K,goalId:U,value:w.value,currency:w.currency,externalId:w.externalId};e.debug&&console.log("[sentient] goal",_);let F={id:U,body:JSON.stringify(_)};v.then(()=>y.send(F))},componentGoal(l,p,h){var _,F,T;let K=d.getSessionId();if(!K)return;let P=o.get(l,I),w=P?null:(_=C.get(l))!=null?_:null;if(!P&&w===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 $=P?P.variantId:Ae(w),U={id:Ke(),sessionId:K,projectId:e.apiKey,componentId:l,variantId:$,eventType:"goal_achieved",goalType:p,payload:k({reward:(F=h==null?void 0:h.reward)!=null?F:1,goalValue:h==null?void 0:h.value,currency:h==null?void 0:h.currency},(T=h==null?void 0:h.metadata)!=null?T:{}),timestamp:Date.now(),timeInSession:Date.now()-g,path:Pe()};e.debug&&console.log("[sentient] componentGoal",U),v.then(()=>r.push(U))},identify(l){let p=d.getSessionId();p&&v.then(()=>{fetch(`${i}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:p,userId:l,ephemeral:d.isEphemeral()}),headers:a}).catch(()=>{})})},track(l){let p=d.getSessionId();if(!p)return;let h=te(k({path:Pe()},l),{id:Ke(),sessionId:p,timestamp:Date.now(),timeInSession:Date.now()-g});e.debug&&console.log("[sentient] track",h),v.then(()=>r.push(h))},getAssignment(l,p){return o.get(l,p)},async assign(l,p,h,K){let P=d.getSessionId();if(!P)return null;let w=o.get(l,I);if(w&&(p!=null&&p.length||w.content!==void 0)){let _=w.ttlMs&&w.ttlMs>0?Math.max(0,w.assignedAt+w.ttlMs-Date.now()):0;return{variantId:w.variantId,assignmentTtlMs:_,content:w.content}}let $=M.get(l);if($)return $;let U=(async()=>{await v;try{let _={sessionId:P,componentId:l,variantIds:p};K!==void 0?_.agentDataByVariant=K:h!==void 0&&(_.agentData=h);let F=await fetch(`${i}/assign`,{method:"POST",body:JSON.stringify(_),headers:a});if(!F.ok)return null;let T=await F.json();return o.set(l,I,k({variantId:T.variantId,assignedAt:Date.now(),segment:I,confidence:1,content:T.content},T.assignmentTtlMs&&T.assignmentTtlMs>0?{ttlMs:T.assignmentTtlMs}:{})),T}catch(_){return null}finally{M.delete(l)}})();return M.set(l,U),U},async decide(l){var K,P,w,$,U,_,F,T,le;let p=d.getSessionId();if(!p)return null;let h=(K=l.slots)!=null?K:[];await v;try{let W={sessionId:p};l.sections&&l.sections.length>0&&(W.sections=l.sections.map(N=>({id:N}))),W.components=(P=l.components)!=null?P:[],h.length>0&&(W.slots=h.map(Se)),l.slotsFrom==="registry"&&(W.slotsFrom="registry"),l.v&&(W.v=l.v);let ce=await fetch(`${i}/decide`,{method:"POST",body:JSON.stringify(W),headers:a});if(!ce.ok)return X(h),null;let x=await ce.json(),Y={};for(let N of h)Y[N.id]=($=(w=x.slots)==null?void 0:w[N.id])!=null?$:se(N);if(x.slots)for(let[N,de]of Object.entries(x.slots))N in Y||(Y[N]=de);for(let[N,de]of Object.entries(Y))C.set(N,de);let at=E!=null&&E.persona!=="unknown";x.persona&&!(x.persona==="unknown"&&at)?E={persona:x.persona,confidence:(U=x.confidence)!=null?U:0}:E||(E={persona:"unknown",confidence:0});for(let[N,de]of Object.entries((_=x.assignments)!=null?_:{}))o.set(N,I,{variantId:de,assignedAt:Date.now(),segment:I,confidence:1});return ie(e.apiKey,k({v:1,persona:E.persona,band:(0,Ue.confidenceBand)(E.confidence),slots:Object.fromEntries(C),layoutOrder:(F=x.layoutOrder)!=null?F:null,savedAt:Date.now()},x.slotConfig?{slotConfig:x.slotConfig}:{})),k(k(k({layoutOrder:(T=x.layoutOrder)!=null?T:null,assignments:(le=x.assignments)!=null?le:{},slots:Y,persona:E.persona,confidence:E.confidence},x.slotConfig?{slotConfig:x.slotConfig}:{}),x.goals?{goals:x.goals}:{}),x.sectionMap?{sectionMap:x.sectionMap}:{})}catch(W){return X(h),null}},getSlotResult(l){var p;return(p=C.get(l))!=null?p:null},getPersona(){return E?{persona:E.persona,confidence:E.confidence,band:(0,Ue.confidenceBand)(E.confidence)}:null},async fetchWeights(){var l;try{let p=await fetch(`${i}/weights`,{headers:a});return p.ok?(l=(await p.json()).components)!=null?l:[]:[]}catch(p){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var l;O==null||O(),j=!0,r.destroy(),y.destroy(),((l=L.get(e.apiKey))==null?void 0:l.dispose)===Q.dispose&&L.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var l;O==null||O(),j=!0,r.destroy(),y.destroy(),d.destroy(),((l=L.get(e.apiKey))==null?void 0:l.dispose)===Q.dispose&&L.delete(e.apiKey);try{localStorage.removeItem(Z+e.apiKey),localStorage.removeItem(Le(e.apiKey)),localStorage.removeItem(Me(e.apiKey))}catch(p){}e.debug&&console.log("[sentient] destroyed")}};if(L.set(e.apiKey,{config:e,upgrade:null,dispose:Q.dispose}),O=jt(Q,e.apiKey,l=>{v.then(()=>{j||ot.add(l)})}),e.debug){let l=window;l.__sentient&&(l.__sentient.client=Q)}return Q}0&&(module.exports={AGENT_INTENTS,LOCAL_MODE_BANNER,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,agentIntent,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,toWireSlot,uaTokenMatch,writeSnapshot});
|
|
1
|
+
"use strict";var lt=Object.create;var ue=Object.defineProperty,ct=Object.defineProperties,dt=Object.getOwnPropertyDescriptor,ut=Object.getOwnPropertyDescriptors,gt=Object.getOwnPropertyNames,$e=Object.getOwnPropertySymbols,pt=Object.getPrototypeOf,We=Object.prototype.hasOwnProperty,ft=Object.prototype.propertyIsEnumerable;var Fe=(e,t,n)=>t in e?ue(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,I=(e,t)=>{for(var n in t||(t={}))We.call(t,n)&&Fe(e,n,t[n]);if($e)for(var n of $e(t))ft.call(t,n)&&Fe(e,n,t[n]);return e},te=(e,t)=>ct(e,ut(t));var mt=(e,t)=>{for(var n in t)ue(e,n,{get:t[n],enumerable:!0})},je=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of gt(t))!We.call(e,u)&&u!==n&&ue(e,u,{get:()=>t[u],enumerable:!(c=dt(t,u))||c.enumerable});return e};var yt=(e,t,n)=>(n=e!=null?lt(pt(e)):{},je(t||!e||!e.__esModule?ue(n,"default",{value:e,enumerable:!0}):n,e)),ht=e=>je(ue({},"__esModule",{value:!0}),e);var zt={};mt(zt,{AGENT_INTENTS:()=>Re,LOCAL_MODE_BANNER:()=>Ge,PROD_KEYLESS_ERROR:()=>Oe,SNAPSHOT_STORAGE_KEY_PREFIX:()=>Z,agentIntent:()=>ze,agentUaList:()=>ge,armOfResult:()=>Ae,attachMicroSignalDetectors:()=>tt,baselineResultFor:()=>se,baselineSlots:()=>Xe,classifiedAgents:()=>Ve,deriveSessionSegment:()=>Ye,detectDeviceClass:()=>fe,detectTimeOfDay:()=>he,detectTrafficSource:()=>me,grantConsent:()=>Ht,init:()=>it,isDoNotTrackEnabled:()=>Be,matchedAgentToken:()=>Ne,readSnapshot:()=>_e,referrerDomainFromReferer:()=>ye,renderPrePaintScript:()=>qe,toWireSlot:()=>Se,uaTokenMatch:()=>pe,writeSnapshot:()=>ie});module.exports=ht(zt);function we(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(t+="-");return t}}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function be(e){return e?`_${e.slice(0,12)}`:""}var St="_snt_uid",vt=365,wt="_snt_uid";function bt(){return we()}function xt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function It(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(c){}}function Et(e){try{return localStorage.getItem(e)}catch(t){return null}}function kt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function Ct(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function Rt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function At(e){try{sessionStorage.removeItem(e)}catch(t){}}function _t(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function Tt(e){try{localStorage.removeItem(e)}catch(t){}}function Dt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Ot={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function xe(e){var y,b,D,R,E,M;if(typeof window=="undefined")return Ot;let t=be(e==null?void 0:e.apiKey),n=(y=e==null?void 0:e.cookieName)!=null?y:`${St}${t}`,c=`${wt}${t}`,s=((b=e==null?void 0:e.cookieTTLDays)!=null?b:vt)*24*60*60,g=C=>C&&C.length>0?C:null,d=(M=(E=(R=(D=g(xt(n)))!=null?D:g(Et(c)))!=null?R:g(Ct(c)))!=null?E:g(e==null?void 0:e.ssrSessionId))!=null?M:bt();It(n,d,s);let o=kt(c,d),r=_t(n),i=o?!1:Rt(c,d),a=!o&&!r&&!i;return{getSessionId:()=>d,isEphemeral:()=>a,destroy:()=>{d=null,Dt(n),Tt(c),At(c)}}}function ne(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function Ie(e){if(e.ok===!0)return"delivered";let{status:t}=e;return typeof t!="number"?"retry":t>=200&&t<300?"delivered":t>=400&&t<500&&t!==429?"dropped":"retry"}function Ee(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let c=JSON.parse(n);return Array.isArray(c)?(localStorage.removeItem(e),c.slice(-t)):[]}catch(n){return[]}}function re(e,t,n){try{let c=(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let g=JSON.parse(s);return Array.isArray(g)?g:[]}catch(s){return[]}})(),u=new Map;for(let s of c)u.set(s.id,s);for(let s of e)u.set(s.id,s);localStorage.setItem(n,JSON.stringify([...u.values()].slice(-t)))}catch(c){}}function ke(e,t){try{let n=localStorage.getItem(t);if(!n)return;let c=JSON.parse(n);if(!Array.isArray(c))return;let u=new Set(e),s=c.filter(g=>!u.has(g.id));if(s.length===c.length)return;s.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(s))}catch(n){}}var Pt=500,Lt=56*1024;function Le(e){return`_snt_retry_${e.slice(0,12)}`}var Mt={push:()=>{},flush:()=>{},destroy:()=>{}};function Qe(e){var O,j,Q;if(typeof window=="undefined")return Mt;let t=(O=e.flushIntervalMs)!=null?O:5e3,n=(j=e.maxBatchSize)!=null?j:20,c=(Q=e.maxRetrySize)!=null?Q:100,u=e.ingestUrl,s=e.apiKey,g=Le(s),d=[],o=new Set,r=[],i=f=>{for(let S of f)a.delete(S),!o.has(S)&&(o.add(S),r.push(S));for(;r.length>Pt;){let S=r.shift();S&&o.delete(S)}ke(f,g)},a=new Set,y=f=>{o.has(f.id)||a.has(f.id)||(a.add(f.id),d.push(f))},b=f=>{for(let S of f)o.has(S.id)||(a.add(S.id),d.push(S))},D=Ee(g,c);for(let f of D)y(f);let R=0,E=0,M=(f,S=!0)=>{if(f.length===0)return;let H=JSON.stringify(f),q=f.map(z=>z.id),$;try{$=fetch(u,{method:"POST",keepalive:!0,body:H,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(z){re(f,c,g),b(f),E++,R=Date.now()+ne(E);return}let ae=z=>{if(Ie(z)!=="retry"){if(!z.ok&&S){let ee=f.filter(V=>V.eventType!=="pageview");if(ee.length>0&&ee.length<f.length){i(f.filter(V=>V.eventType==="pageview").map(V=>V.id)),M(ee,!1);return}}i(q),E=0,R=0;return}re(f,c,g),b(f),E++,R=Date.now()+ne(E)};$ instanceof Promise?$.then(ae).catch(()=>{re(f,c,g),b(f),E++,R=Date.now()+ne(E)}):ae($)},C=typeof TextEncoder!="undefined"?new TextEncoder:null,k=f=>C?C.encode(f).length:f.length,X=f=>{let S=[],H=2;for(let q of f){let $=k(JSON.stringify(q))+1;if(S.length>0&&H+$>Lt||S.length>=n)break;S.push(q),H+=$}return S},A=()=>{try{if(Date.now()<R)return;for(;d.length>0&&!(Date.now()<R);){let f=d.filter(H=>!o.has(H.id));if(d.length=0,f.length===0)break;let S=X(f);if(S.length===0)break;S.length<f.length&&d.push(...f.slice(S.length)),M(S)}}catch(f){}},m=!0,v=null;v=setInterval(()=>{m&&A()},t);let J=()=>{document.visibilityState==="hidden"&&A()},G=()=>{A()};return document.addEventListener("visibilitychange",J),window.addEventListener("pagehide",G),{push(f){y(f),d.length>=n&&A()},flush:A,destroy(){m=!1,v!==null&&(clearInterval(v),v=null),document.removeEventListener("visibilitychange",J),window.removeEventListener("pagehide",G),A()}}}var Nt=200;function Me(e){return`_snt_goal_retry_${e.slice(0,12)}`}var Gt={send:()=>{},flush:()=>{},destroy:()=>{}};function He(e){var k,X,A;if(typeof window=="undefined")return Gt;let t=(k=e.flushIntervalMs)!=null?k:5e3,n=(X=e.maxRetrySize)!=null?X:100,c=(A=e.maxPerFlush)!=null?A:5,u=Me(e.apiKey),s=[],g=new Set,d=new Set,o=[],r=0,i=0,a=!1,y=m=>{for(g.delete(m.id),d.has(m.id)||(d.add(m.id),o.push(m.id));o.length>Nt;){let v=o.shift();v&&d.delete(v)}ke([m.id],u)},b=m=>{re([m],n,u),!d.has(m.id)&&!g.has(m.id)&&(g.add(m.id),s.push(m)),i++,r=Date.now()+ne(i)},D=m=>{let v;try{v=fetch(e.url,{method:"POST",keepalive:!0,body:m.body,headers:e.headers})}catch(G){b(m);return}let J=G=>{var j;let O=Ie(G);if(O==="retry"){b(m);return}O==="dropped"&&((j=e.onDrop)==null||j.call(e,m,G.status)),y(m),i=0,r=0};v instanceof Promise?v.then(J).catch(()=>b(m)):J(v)},R=()=>{try{if(a||Date.now()<r)return;let m=0;for(;s.length>0&&m<c&&!(Date.now()<r);){let v=s.shift();g.delete(v.id),!d.has(v.id)&&(m++,D(v))}}catch(m){}};for(let m of Ee(u,n))g.has(m.id)||(g.add(m.id),s.push(m));let E=setInterval(R,t),M=()=>{document.visibilityState==="hidden"&&R()},C=()=>R();return document.addEventListener("visibilitychange",M),window.addEventListener("pagehide",C),{send(m){if(!a&&!(d.has(m.id)||g.has(m.id))){if(Date.now()<r){g.add(m.id),s.push(m);return}D(m)}},flush:R,destroy(){clearInterval(E),document.removeEventListener("visibilitychange",M),window.removeEventListener("pagehide",C),R(),a=!0}}}var Kt=1800*1e3;function Ce(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Je(e=Kt,t){let n=new Map,c=`_snt_asgn${be(t)}_`,u=(r,i)=>`${c}${encodeURIComponent(r)}:${encodeURIComponent(i)}`,s=r=>{let i=r.slice(c.length),a=i.indexOf(":");if(a<0)return null;try{return{componentId:decodeURIComponent(i.slice(0,a)),segment:decodeURIComponent(i.slice(a+1))}}catch(y){return null}},g=()=>{try{let r=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a!=null&&a.startsWith(c)&&r.push(a)}return r}catch(r){return[]}},d=r=>r.assignedAt+(r.ttlMs&&r.ttlMs>0?r.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let r of g())try{let i=localStorage.getItem(r);if(!i)continue;let a=JSON.parse(i);if(d(a)){localStorage.removeItem(r);continue}let y=s(r);if(!y)continue;n.set(Ce(y.componentId,y.segment),a)}catch(i){}})(),{get(r,i){let a=n.get(Ce(r,i));return a?d(a)?(n.delete(Ce(r,i)),null):a:null},set(r,i,a){let y=Ce(r,i);n.set(y,a);try{localStorage.setItem(u(r,i),JSON.stringify(a))}catch(b){}},invalidate(r){let i=`${encodeURIComponent(r)}:`;for(let a of[...n.keys()])a.startsWith(i)&&n.delete(a);for(let a of g()){let y=s(a);if((y==null?void 0:y.componentId)===r)try{localStorage.removeItem(a)}catch(b){}}},clear(){n.clear();for(let r of g())try{localStorage.removeItem(r)}catch(i){}}}}var ge=["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 pe(e){return Ne(e)!==null}function Ne(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=ge.find(c=>t.includes(c.toLowerCase())))!=null?n:null}var Re={GPTBot:"training","ChatGPT-User":"user","OAI-SearchBot":"search",ClaudeBot:"training","Claude-User":"user","Claude-SearchBot":"search",PerplexityBot:"search","Perplexity-User":"user","Google-Extended":"training","Applebot-Extended":"training","Meta-ExternalAgent":"training",Bytespider:"training",CCBot:"training",Amazonbot:"other","cohere-ai":"training",Diffbot:"other"};function ze(e){if(!e)return"other";let t=ge.find(n=>n.toLowerCase()===e.toLowerCase());return t&&Re[t]||"other"}function Ve(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of ge)e[(t=Re[n])!=null?t:"other"].push(n);return e}function fe(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 me(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(u){}let c=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(c)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(c)?"social":"referral"}catch(n){return"direct"}}function ye(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function he(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ye(e){let t=Ut("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Ut(e,t){var s,g,d,o,r,i,a;let n=(g=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?g:"",c=(o=(d=t==null?void 0:t.referer)==null?void 0:d.trim())!=null?o:"",u=(r=t==null?void 0:t.now)!=null?r:new Date;return{sessionId:e,ephemeral:!1,utmParams:(i=t==null?void 0:t.utmParams)!=null?i:{},deviceClass:n?fe(n):"desktop",trafficSource:c?me(c,t==null?void 0:t.appOrigin):"direct",referrerDomain:ye(c),timeOfDay:he(u),dayOfWeek:(a=["sun","mon","tue","wed","thu","fri","sat"][u.getDay()])!=null?a:"sun",automation:(t==null?void 0:t.webdriver)===!0||pe(n)}}var oe=require("@sentientui/policy");function Se(e){return I(I(I({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 se(e){let t=Se(e);return(0,oe.slotResultFor)(t,(0,oe.slotBaselineArm)(t))}function Xe(e){let t={};for(let n of e)t[n.id]=se(n);return t}function Ae(e){return typeof e=="string"?e:(0,oe.canonicalArm)(e)}var Z="_snt_snap:",Bt=["low","medium","high"];function _e(e){try{let t=localStorage.getItem(Z+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!Bt.includes(n.band)||typeof n.slots!="object"||n.slots===null||Array.isArray(n.slots)||!(n.layoutOrder===null||Array.isArray(n.layoutOrder))||typeof n.savedAt!="number"||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig))?null:n}catch(t){return null}}function ie(e,t){try{localStorage.setItem(Z+e,JSON.stringify(t))}catch(n){}}function qe(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(Z+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}var Ue=require("@sentientui/policy");var De=require("@sentientui/policy");var Oe="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ge="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",Ze=!1,Te=!1;function $t(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function et(e){var d;let t=xe({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(d=t.getSessionId())!=null?d:"local",c=$t(),u=import("@sentientui/core/local").then(o=>{let r=o;return r.LOCAL_ENGINE_AVAILABLE?(Ze||(Ze=!0,console.info(Ge)),r):(Te||(Te=!0,console.error(Oe)),null)}).catch(()=>(Te||(Te=!0,console.error(Oe)),null)),s=null;function g(o){let r=document.documentElement;r.dataset.sentientPersona===void 0&&(r.dataset.sentientPersona=o.persona,r.dataset.sentientConfidence=(0,De.confidenceBand)(o.confidence))}return{isLocal:!0,async decide(o){var a,y,b;let r=await u;if(!r)return null;let i=r.createLocalEngine({sessionId:n,forcedPersona:c}).decide(o);return s=te(I({},i),{layoutOrder:(y=(a=i.layoutOrder)!=null?a:s==null?void 0:s.layoutOrder)!=null?y:null,slots:I(I({},(b=s==null?void 0:s.slots)!=null?b:{}),i.slots)}),ie(e.apiKey||"local",{v:1,persona:s.persona,band:(0,De.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),g(i),i},getSlotResult(o){var r,i,a;return(a=(i=s==null?void 0:s.slots[o])!=null?i:(r=e.initialSlots)==null?void 0:r[o])!=null?a:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,De.confidenceBand)(s.confidence)}:null},async assign(o,r){var y;let i=await u;return!i||!r||r.length===0?r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null:{variantId:(y=i.createLocalEngine({sessionId:n,forcedPersona:c}).decide({components:[{id:o,variantIds:r}]}).assignments[o])!=null?y:r[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}function tt(e,t,n,c){let u=[];{let d=!1,o=[],r=()=>{if(d)return;let i=Date.now();for(o.push(i);o.length>0&&i-o[0]>500;)o.shift();o.length>=3&&(d=!0,e("rage_click"))};t.addEventListener("click",r),u.push(()=>t.removeEventListener("click",r))}{let s=!1,g=d=>{if(s||!(d.target instanceof Node)||!t.contains(d.target)&&t!==d.target)return;s=!0;let o=typeof window!="undefined"?window.getSelection():null,r=o?o.toString().length:0;e("text_copy",{selectionLength:r})};document.addEventListener("copy",g),u.push(()=>document.removeEventListener("copy",g))}{let s=!1,g=!1,d=null,o=()=>{d!==null&&(clearTimeout(d),d=null)},r=()=>{s||!g||(o(),d=setTimeout(()=>{!s&&g&&(s=!0,e("scroll_hesitation"))},3e3))},i=()=>{o(),r()},a=b=>{for(let D of b)g=D.intersectionRatio>.3,g?r():o()},y=new IntersectionObserver(a,{threshold:[.3]});y.observe(t),window.addEventListener("scroll",i,{passive:!0}),u.push(()=>{y.disconnect(),window.removeEventListener("scroll",i),o()})}if((c==null?void 0:c.tabLoss)!==!1){let s=!1,g=n!=null?n:Date.now(),d=()=>{if(s||document.visibilityState!=="hidden")return;let o=Date.now()-g;o<15e3&&(s=!0,e("tab_loss",{timeOnPage:o}))};document.addEventListener("visibilitychange",d),u.push(()=>document.removeEventListener("visibilitychange",d))}return()=>{for(let s of u)s()}}var nt="https://api.sentient-ui.com/v1/events",L=new Map,rt=null;function Ft(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}function Ke(){return we()}function Pe(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function Wt(e){if(typeof MessageChannel=="function"){let t=new MessageChannel;t.port1.onmessage=()=>{e.clear(),t.port1.close(),t.port2.close()},t.port2.postMessage(0)}else setTimeout(()=>e.clear(),0)}var ot=new Set;function jt(e,t,n){let c=typeof window=="undefined"?null:window.history;if(!c)return()=>{};let u=!1,s,g=()=>{if(u)return;let r=Pe();!r||r===s||(s=r,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${r}`))},d=[];for(let r of["pushState","replaceState"]){let i=c[r],a=function(...y){let b=i.apply(this,y);return g(),b};c[r]=a,d.push([r,i,a])}window.addEventListener("popstate",g);let o=Pe();return o&&ot.has(`${t}:${o}`)?s=o:g(),()=>{if(!u){u=!0,window.removeEventListener("popstate",g);for(let[r,i,a]of d)c[r]===a&&(c[r]=i)}}}var ve={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function Qt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,c]of t)n.startsWith("utm_")&&(e[n]=c);return e}catch(e){return{}}}function st(e){return e.replace(/\/events\/?$/,"")}function Be(){return typeof navigator!="undefined"&&navigator.globalPrivacyControl===!0?!0:[typeof navigator!="undefined"?navigator.doNotTrack:void 0,typeof window!="undefined"?window.doNotTrack:void 0,typeof navigator!="undefined"?navigator.msDoNotTrack:void 0].some(t=>t==="1"||t==="yes")}function Ht(e){var d;if(typeof window=="undefined")return;let t=e!=null?e:rt;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=L.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:c,upgrade:u}=n;if(!u||c.respectDoNotTrack!==!1&&Be())return;let s=it(te(I({},c),{consent:!0}));u(s);let g=(d=L.get(t))==null?void 0:d.dispose;L.set(t,{config:te(I({},c),{consent:!0}),upgrade:null,dispose:g})}function Jt(e){var d;let t=e.preConsentBehavior==="statistical_winner",n=st((d=e.ingestUrl)!=null?d:nt),c={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(o,r,i){if(!t)return null;try{let a=new URLSearchParams({componentId:o});for(let D of r!=null?r:[])a.append("variantIds[]",D);let y=await fetch(`${n}/winner?${a.toString()}`,{headers:c});return y.ok?{variantId:(await y.json()).variantId,assignmentTtlMs:0}:r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}catch(a){return r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},s={track:o=>u.track(o),goal:((o,r,i,a)=>u.goal(o,r,i,a)),componentGoal:(o,r,i)=>u.componentGoal(o,r,i),identify:o=>u.identify(o),getAssignment:(o,r)=>u.getAssignment(o,r),assign:(o,r,i,a)=>u.assign(o,r,i,a),decide:o=>u.decide(o),getSlotResult:o=>u.getSlotResult(o),getPersona:()=>u.getPersona(),fetchWeights:()=>u.fetchWeights(),getGraph:()=>u.getGraph(),dispose:()=>u.dispose(),destroy:()=>u.destroy()};function g(o){u=o}return{proxy:s,setInner:g}}function it(e){var f,S,H,q,$,ae,z,ee,V;if(typeof window=="undefined")return ve;rt=e.apiKey;let t=L.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(l){}let n=e.respectDoNotTrack!==!1&&Be(),c=e.consent===!1||n,u=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!u&&e.localMode!==!1)return c?(L.set(e.apiKey||"local",{config:e,upgrade:null}),ve):(L.set(e.apiKey||"local",{config:e,upgrade:null}),et(e));if(c){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return e.preConsentBehavior==="statistical_winner"&&console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),L.set(e.apiKey,{config:e,upgrade:null}),ve;let{proxy:l,setInner:p}=Jt(e);return L.set(e.apiKey,{config:e,upgrade:n?null:p}),l}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."),ve;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),ve;let s=(f=e.ingestUrl)!=null?f:nt,g=Date.now(),d=xe({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),o=Je(void 0,e.apiKey),r=Qe({ingestUrl:s,apiKey:e.apiKey}),i=st(s),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},y=He({url:`${i}/goals`,apiKey:e.apiKey,headers:a,onDrop:(l,p)=>{e.debug&&console.warn(`[sentient] goal dropped (HTTP ${p}) \u2014 this will not be retried. `+(p===400?"The session was not found: call init() and let the session upsert complete before firing goals.":p===401||p===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),l)}}),b=fe((S=navigator.userAgent)!=null?S:""),D=typeof window!="undefined"?window.location.origin:void 0,R=me((H=document.referrer)!=null?H:"",D),E=(q=e.sessionSegment)!=null?q:`${b}:${R}`,M=new Map,C=new Map,k=null,X=l=>{for(let p of l)C.has(p.id)||C.set(p.id,se(p))};if(e.initialSlots)for(let[l,p]of Object.entries(e.initialSlots))C.set(l,p);let A=_e(e.apiKey);if(A)for(let[l,p]of Object.entries(A.slots))C.has(l)||C.set(l,p);let m={low:.15,medium:.5,high:.85};if(e.initialPersona)k=I({},e.initialPersona);else{let l=document.documentElement.dataset;l.sentientPersona?k={persona:l.sentientPersona,confidence:(ae=m[($=l.sentientConfidence)!=null?$:"low"])!=null?ae:.15}:A&&(k={persona:A.persona,confidence:(z=m[A.band])!=null?z:.15})}if(e.initialAssignments)for(let[l,p]of Object.entries(e.initialAssignments))o.set(l,E,{variantId:p,assignedAt:Date.now(),segment:E,confidence:1});let v=Promise.resolve(),J=d.getSessionId();if(J){let l=ye((ee=document.referrer)!=null?ee:""),p=I(I(I({sessionId:J,deviceClass:b,trafficSource:R,referrerDomain:l,utmParams:Qt(),timeOfDay:he(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:d.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||pe((V=navigator.userAgent)!=null?V:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{});try{v=fetch(`${i}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(p),headers:a}).then(h=>{h.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(h){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:r});let G=new Set,O=null,j=!1,Q={goal(l,p={},h=1,K=0){var T,le,B,ce,x,Y;let P=d.getSessionId();if(!P)return;let w=Ft(p)?p:{metadata:p},F=`${l}\0${(T=w.externalId)!=null?T:""}\0${(le=w.stepIndex)!=null?le:K}\0${(B=w.weight)!=null?B:h}`;if(G.has(F)){e.debug&&console.log(`[sentient] goal("${l}") already recorded for this action \u2014 not sent twice`);return}G.add(F),G.size===1&&Wt(G);let U=Ke(),_={sessionId:P,name:l,metadata:(ce=w.metadata)!=null?ce:{},weight:(x=w.weight)!=null?x:h,stepIndex:(Y=w.stepIndex)!=null?Y:K,goalId:U,value:w.value,currency:w.currency,externalId:w.externalId};e.debug&&console.log("[sentient] goal",_);let W={id:U,body:JSON.stringify(_)};v.then(()=>y.send(W))},componentGoal(l,p,h){var _,W,T;let K=d.getSessionId();if(!K)return;let P=o.get(l,E),w=P?null:(_=C.get(l))!=null?_:null;if(!P&&w===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 F=P?P.variantId:Ae(w),U={id:Ke(),sessionId:K,projectId:e.apiKey,componentId:l,variantId:F,eventType:"goal_achieved",goalType:p,payload:I({reward:(W=h==null?void 0:h.reward)!=null?W:1,goalValue:h==null?void 0:h.value,currency:h==null?void 0:h.currency},(T=h==null?void 0:h.metadata)!=null?T:{}),timestamp:Date.now(),timeInSession:Date.now()-g,path:Pe()};e.debug&&console.log("[sentient] componentGoal",U),v.then(()=>r.push(U))},identify(l){let p=d.getSessionId();p&&v.then(()=>{fetch(`${i}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:p,userId:l,ephemeral:d.isEphemeral()}),headers:a}).catch(()=>{})})},track(l){let p=d.getSessionId();if(!p)return;let h=te(I({path:Pe()},l),{id:Ke(),sessionId:p,timestamp:Date.now(),timeInSession:Date.now()-g});e.debug&&console.log("[sentient] track",h),v.then(()=>r.push(h))},getAssignment(l,p){return o.get(l,p)},async assign(l,p,h,K){let P=d.getSessionId();if(!P)return null;let w=o.get(l,E);if(w&&(p!=null&&p.length||w.content!==void 0)){let _=w.ttlMs&&w.ttlMs>0?Math.max(0,w.assignedAt+w.ttlMs-Date.now()):0;return{variantId:w.variantId,assignmentTtlMs:_,content:w.content}}let F=M.get(l);if(F)return F;let U=(async()=>{await v;try{let _={sessionId:P,componentId:l,variantIds:p};K!==void 0?_.agentDataByVariant=K:h!==void 0&&(_.agentData=h);let W=await fetch(`${i}/assign`,{method:"POST",body:JSON.stringify(_),headers:a});if(!W.ok)return null;let T=await W.json();return o.set(l,E,I({variantId:T.variantId,assignedAt:Date.now(),segment:E,confidence:1,content:T.content},T.assignmentTtlMs&&T.assignmentTtlMs>0?{ttlMs:T.assignmentTtlMs}:{})),T}catch(_){return null}finally{M.delete(l)}})();return M.set(l,U),U},async decide(l){var K,P,w,F,U,_,W,T,le;let p=d.getSessionId();if(!p)return null;let h=(K=l.slots)!=null?K:[];await v;try{let B={sessionId:p};l.sections&&l.sections.length>0&&(B.sections=l.sections.map(N=>({id:N}))),B.components=(P=l.components)!=null?P:[],h.length>0&&(B.slots=h.map(Se)),l.slotsFrom==="registry"&&(B.slotsFrom="registry"),l.v&&(B.v=l.v),e.persona&&(B.persona=e.persona);let ce=await fetch(`${i}/decide`,{method:"POST",body:JSON.stringify(B),headers:a});if(!ce.ok)return X(h),null;let x=await ce.json(),Y={};for(let N of h)Y[N.id]=(F=(w=x.slots)==null?void 0:w[N.id])!=null?F:se(N);if(x.slots)for(let[N,de]of Object.entries(x.slots))N in Y||(Y[N]=de);for(let[N,de]of Object.entries(Y))C.set(N,de);let at=k!=null&&k.persona!=="unknown";x.persona&&!(x.persona==="unknown"&&at)?k={persona:x.persona,confidence:(U=x.confidence)!=null?U:0}:k||(k={persona:"unknown",confidence:0});for(let[N,de]of Object.entries((_=x.assignments)!=null?_:{}))o.set(N,E,{variantId:de,assignedAt:Date.now(),segment:E,confidence:1});return ie(e.apiKey,I({v:1,persona:k.persona,band:(0,Ue.confidenceBand)(k.confidence),slots:Object.fromEntries(C),layoutOrder:(W=x.layoutOrder)!=null?W:null,savedAt:Date.now()},x.slotConfig?{slotConfig:x.slotConfig}:{})),I(I(I({layoutOrder:(T=x.layoutOrder)!=null?T:null,assignments:(le=x.assignments)!=null?le:{},slots:Y,persona:k.persona,confidence:k.confidence},x.slotConfig?{slotConfig:x.slotConfig}:{}),x.goals?{goals:x.goals}:{}),x.sectionMap?{sectionMap:x.sectionMap}:{})}catch(B){return X(h),null}},getSlotResult(l){var p;return(p=C.get(l))!=null?p:null},getPersona(){return k?{persona:k.persona,confidence:k.confidence,band:(0,Ue.confidenceBand)(k.confidence)}:null},async fetchWeights(){var l;try{let p=await fetch(`${i}/weights`,{headers:a});return p.ok?(l=(await p.json()).components)!=null?l:[]:[]}catch(p){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var l;O==null||O(),j=!0,r.destroy(),y.destroy(),((l=L.get(e.apiKey))==null?void 0:l.dispose)===Q.dispose&&L.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var l;O==null||O(),j=!0,r.destroy(),y.destroy(),d.destroy(),((l=L.get(e.apiKey))==null?void 0:l.dispose)===Q.dispose&&L.delete(e.apiKey);try{localStorage.removeItem(Z+e.apiKey),localStorage.removeItem(Le(e.apiKey)),localStorage.removeItem(Me(e.apiKey))}catch(p){}e.debug&&console.log("[sentient] destroyed")}};if(L.set(e.apiKey,{config:e,upgrade:null,dispose:Q.dispose}),O=jt(Q,e.apiKey,l=>{v.then(()=>{j||ot.add(l)})}),e.debug){let l=window;l.__sentient&&(l.__sentient.client=Q)}return Q}0&&(module.exports={AGENT_INTENTS,LOCAL_MODE_BANNER,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,agentIntent,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,toWireSlot,uaTokenMatch,writeSnapshot});
|
|
2
2
|
//# sourceMappingURL=index.js.map
|