@sentientui/core 0.34.3 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +51 -12
  2. package/dist/chunk-735EJYJX.mjs +2 -0
  3. package/dist/chunk-735EJYJX.mjs.map +1 -0
  4. package/dist/chunk-DU3AXQHR.mjs +2 -0
  5. package/dist/chunk-DU3AXQHR.mjs.map +1 -0
  6. package/dist/chunk-GVKKOUWE.mjs +2 -0
  7. package/dist/chunk-GVKKOUWE.mjs.map +1 -0
  8. package/dist/chunk-J5EL7HKC.mjs +2 -0
  9. package/dist/chunk-J5EL7HKC.mjs.map +1 -0
  10. package/dist/{index-Dyc-wA0o.d.cts → index-BYOMZ3t-.d.cts} +38 -2
  11. package/dist/{index-JgzRgOO4.d.ts → index-DEwRTvxc.d.ts} +38 -2
  12. package/dist/index-consent.d.cts +124 -0
  13. package/dist/index-consent.d.ts +124 -0
  14. package/dist/index-consent.js +2 -0
  15. package/dist/index-consent.js.map +1 -0
  16. package/dist/index-consent.mjs +2 -0
  17. package/dist/index-consent.mjs.map +1 -0
  18. package/dist/index-engagement.js +1 -1
  19. package/dist/index-engagement.js.map +1 -1
  20. package/dist/index-engagement.mjs +1 -1
  21. package/dist/index-engagement.mjs.map +1 -1
  22. package/dist/index-graph.d.cts +3 -2
  23. package/dist/index-graph.d.ts +3 -2
  24. package/dist/index-graph.js +1 -1
  25. package/dist/index-graph.js.map +1 -1
  26. package/dist/index-graph.mjs +1 -1
  27. package/dist/index-graph.mjs.map +1 -1
  28. package/dist/index-local.d.cts +2 -1
  29. package/dist/index-local.d.ts +2 -1
  30. package/dist/index-server.d.cts +10 -0
  31. package/dist/index-server.d.ts +10 -0
  32. package/dist/index-server.js +1 -1
  33. package/dist/index-server.js.map +1 -1
  34. package/dist/index-server.mjs +1 -1
  35. package/dist/index-server.mjs.map +1 -1
  36. package/dist/index-style-sample.js +1 -1
  37. package/dist/index-style-sample.js.map +1 -1
  38. package/dist/index-style-sample.mjs +1 -1
  39. package/dist/index-style-sample.mjs.map +1 -1
  40. package/dist/index.d.cts +2 -1
  41. package/dist/index.d.ts +2 -1
  42. package/dist/index.js +1 -1
  43. package/dist/index.js.map +1 -1
  44. package/dist/index.mjs +1 -1
  45. package/llms.txt +2 -2
  46. package/package.json +11 -2
  47. package/dist/chunk-2NVSFI4V.mjs +0 -2
  48. package/dist/chunk-2NVSFI4V.mjs.map +0 -1
  49. package/dist/chunk-DGRAS5VP.mjs +0 -2
  50. package/dist/chunk-DGRAS5VP.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{A as T,B as U,C as V,D as W,E as X,F as Y,G as Z,H as ba,I as ca,J as da,K as ea,L as fa,M as ga,N as ha,O as ia,a as t,b as u,c as v,d as w,e as x,f as y,g as z,h as A,i as B,j as C,k as D,l as E,m as F,n as G,o as H,p as I,q as J,r as K,s as L,t as M,u as N,v as O,w as P,x as Q,y as R,z as S}from"./chunk-DGRAS5VP.mjs";import{a as _,b as $,c as aa}from"./chunk-NCLBL5V3.mjs";import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,r as p,s as q,t as r,u as s}from"./chunk-2NVSFI4V.mjs";import"./chunk-TMCGHANO.mjs";export{f as AGENT_INTENTS,C as BLOCK_ALIGNS,H as BLOCK_EMPHASES,K as BLOCK_FITS,B as BLOCK_GAPS,L as BLOCK_GRID_COLUMNS,M as BLOCK_HEADING_LEVELS,D as BLOCK_JUSTIFIES,P as BLOCK_MAX_WIDTHS,O as BLOCK_PADS,J as BLOCK_RATIOS,E as BLOCK_SIZES,N as BLOCK_SURFACES,I as BLOCK_TEXT_ALIGNS,G as BLOCK_TONES,F as BLOCK_WEIGHTS,l as CLICK_ID_KEYS,Q as FORM_FIELD_KINDS,R as FORM_INPUT_TYPES,a as LEGACY_SESSION_COOKIE_NAME,y as LOCAL_MODE_BANNER,X as MAX_BLOCK_ARMS,W as MAX_BLOCK_CHILDREN,V as MAX_BLOCK_DEPTH,U as MAX_BLOCK_NODES,Y as MAX_BLOCK_TEXT_LEN,S as MAX_FORM_FIELDS,T as MAX_FORM_SELECT_OPTIONS,$ as MAX_SKELETON_LEAVES,_ as MAX_SKELETON_NODES,aa as MAX_SKELETON_TEXT,z as PAGE_SCOPE_RE,x as PROD_KEYLESS_ERROR,ba as REVEAL_MS,t as SNAPSHOT_STORAGE_KEY_PREFIX,fa as _registerConsentUpgradeInit,g as agentIntent,c as agentUaList,s as armOfResult,ea as attachMicroSignalDetectors,q as baselineResultFor,r as baselineSlots,h as classifiedAgents,Z as containsFormBlock,o as deriveSessionSegment,i as detectDeviceClass,n as detectTimeOfDay,j as detectTrafficSource,m as extractTrackedParams,ha as grantConsent,ia as init,ga as isDoNotTrackEnabled,e as matchedAgentToken,A as pageScopeMatches,u as readSnapshot,k as referrerDomainFromReferer,w as renderPrePaintScript,ca as resetRevealStyles,da as reveal,b as sessionCookieName,p as toWireSlot,d as uaTokenMatch,v as writeSnapshot};
1
+ import{A as Z,B as _,C as $,D as aa,E as ba,F as ca,G as ga,H as ha,I as ia,J as ja,K as ka,L as la,M as ma,N as na,O as oa,a as i,b as j,c as k,d as C,e as D,f as E,g as F,h as G,i as H,j as I,k as J,l as K,m as L,n as M,o as N,p as O,q as P,r as Q,s as R,t as S,u as T,v as U,w as V,x as W,y as X,z as Y}from"./chunk-GVKKOUWE.mjs";import{a as d,b as e,c as f,d as g,m as h}from"./chunk-DU3AXQHR.mjs";import{a as da,b as ea,c as fa}from"./chunk-NCLBL5V3.mjs";import{a as l,b as m,c as n,d as o,e as p,f as q,g as r,h as s,i as t,j as u,k as v,l as w,m as x,o as y,p as z,q as A,r as B}from"./chunk-735EJYJX.mjs";import{b as a,c as b,e as c}from"./chunk-J5EL7HKC.mjs";import"./chunk-TMCGHANO.mjs";export{o as AGENT_INTENTS,H as BLOCK_ALIGNS,M as BLOCK_EMPHASES,P as BLOCK_FITS,G as BLOCK_GAPS,Q as BLOCK_GRID_COLUMNS,R as BLOCK_HEADING_LEVELS,I as BLOCK_JUSTIFIES,U as BLOCK_MAX_WIDTHS,T as BLOCK_PADS,O as BLOCK_RATIOS,J as BLOCK_SIZES,S as BLOCK_SURFACES,N as BLOCK_TEXT_ALIGNS,L as BLOCK_TONES,K as BLOCK_WEIGHTS,u as CLICK_ID_KEYS,V as FORM_FIELD_KINDS,W as FORM_INPUT_TYPES,a as LEGACY_SESSION_COOKIE_NAME,D as LOCAL_MODE_BANNER,aa as MAX_BLOCK_ARMS,$ as MAX_BLOCK_CHILDREN,_ as MAX_BLOCK_DEPTH,Z as MAX_BLOCK_NODES,ba as MAX_BLOCK_TEXT_LEN,X as MAX_FORM_FIELDS,Y as MAX_FORM_SELECT_OPTIONS,ea as MAX_SKELETON_LEAVES,da as MAX_SKELETON_NODES,fa as MAX_SKELETON_TEXT,E as PAGE_SCOPE_RE,C as PROD_KEYLESS_ERROR,ga as REVEAL_MS,d as SNAPSHOT_STORAGE_KEY_PREFIX,ka as _registerConsentUpgradeInit,p as agentIntent,l as agentUaList,k as applyNonce,B as armOfResult,ja as attachMicroSignalDetectors,z as baselineResultFor,A as baselineSlots,q as classifiedAgents,ca as containsFormBlock,j as cspNonce,x as deriveSessionSegment,r as detectDeviceClass,w as detectTimeOfDay,s as detectTrafficSource,v as extractTrackedParams,c as forgetGeneration,h as forgetVisitor,ma as grantConsent,oa as init,la as isDoNotTrackEnabled,n as matchedAgentToken,F as pageScopeMatches,e as readSnapshot,t as referrerDomainFromReferer,g as renderPrePaintScript,ha as resetRevealStyles,ia as reveal,na as routeKey,b as sessionCookieName,i as setCspNonce,y as toWireSlot,m as uaTokenMatch,f as writeSnapshot};
2
2
  //# sourceMappingURL=index.mjs.map
package/llms.txt CHANGED
@@ -3,8 +3,8 @@
3
3
  > SentientUI makes websites adapt to each visitor. The SDK observes behaviour, classifies
4
4
  > visitors into the personas your app declares (e.g. admin, evaluator) or discovery proposes
5
5
  > (`unknown` until then), and a server-side persona-keyed optimizer picks, per visitor type,
6
- > which styling, content, and section order to show, learning from real conversions. Decisions are locked per session: Visit 1 learns,
7
- > Visit 2 converts. React SDK, vanilla JS SDK, and a script-tag snippet are open source; the
6
+ > which styling, content, and section order to show, learning from real conversions. It measures the lift against a held-out control
7
+ > group. Decisions are locked per session: a first visit sees the original, the return visit adapts. React SDK, vanilla JS SDK, and a script-tag snippet are open source; the
8
8
  > learning API is hosted (api.sentient-ui.com).
9
9
 
10
10
  ## Install (agent quickstart)
package/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "@sentientui/core",
3
- "version": "0.34.3",
3
+ "version": "0.36.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
+ "engines": {
7
+ "node": ">=18.18"
8
+ },
6
9
  "sideEffects": false,
7
10
  "description": "SentientUI core SDK — the framework-agnostic client that powers adaptive UI personalization: session tracking, bandit variant assignment, adaptive slots, and persona decisions. SSR-safe.",
8
11
  "homepage": "https://sentient-ui.com",
@@ -42,6 +45,11 @@
42
45
  "import": "./dist/index-style-sample.mjs",
43
46
  "require": "./dist/index-style-sample.js"
44
47
  },
48
+ "./consent": {
49
+ "types": "./dist/index-consent.d.ts",
50
+ "import": "./dist/index-consent.mjs",
51
+ "require": "./dist/index-consent.js"
52
+ },
45
53
  "./region": {
46
54
  "types": "./dist/index-region.d.ts",
47
55
  "import": "./dist/index-region.mjs",
@@ -81,9 +89,10 @@
81
89
  "llms.txt"
82
90
  ],
83
91
  "dependencies": {
84
- "@sentientui/policy": "0.12.0"
92
+ "@sentientui/policy": "0.12.1"
85
93
  },
86
94
  "devDependencies": {
95
+ "@iabtechlabtcf/core": "1.5.22",
87
96
  "@types/node": "^22.10.2",
88
97
  "esbuild": "^0.24.0",
89
98
  "jsdom": "^25.0.1",
@@ -1,2 +0,0 @@
1
- import{a}from"./chunk-TMCGHANO.mjs";function x(t){return t?`_${t.slice(0,12)}`:""}var S="_snt_uid";function _(t){return`${S}${x(t)}`}var c=["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 y(t){return b(t)!==null}function b(t){var r;if(!t)return null;let e=t.toLowerCase();return(r=c.find(i=>e.includes(i.toLowerCase())))!=null?r:null}var h={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 L(t){if(!t)return"other";let e=c.find(r=>r.toLowerCase()===t.toLowerCase());return e&&h[e]||"other"}function E(){var e;let t={user:[],search:[],training:[],other:[]};for(let r of c)t[(e=h[r])!=null?e:"other"].push(r);return t}function p(t){let e=t.toLowerCase();return/ipad|tablet|playbook|kindle|silk/.test(e)?"tablet":/mobi|iphone|ipod|android.*mobile|phone/.test(e)?"mobile":"desktop"}function R(t,e){if(!t)return"direct";try{let r=new URL(t);if(e)try{if(new URL(e).host===r.host)return"direct"}catch(n){}let i=r.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(i)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(i)?"social":"referral"}catch(r){return"direct"}}function C(t){if(!t)return null;try{return new URL(t).hostname}catch(e){return null}}var A=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function T(t){let e={},r={};try{let i=typeof t=="string"||t instanceof URLSearchParams?new URLSearchParams(t):Object.entries(t).flatMap(([n,o])=>{let s=Array.isArray(o)?o[0]:o;return s===void 0?[]:[[n,s]]});for(let[n,o]of i)n.startsWith("utm_")?n in e||(e[n]=o):A.includes(n)&&(n in r||(r[n]=o))}catch(i){}return{utmParams:e,clickIds:r}}function I(t){let e=t.getHours();return e<6?"night":e<12?"morning":e<18?"afternoon":"evening"}function G(t){let e=k("__segment__",t);return`${e.deviceClass}:${e.trafficSource}`}function k(t,e){var o,s,l,u,g,d,f,m;let r=(s=(o=e==null?void 0:e.userAgent)==null?void 0:o.trim())!=null?s:"",i=(u=(l=e==null?void 0:e.referer)==null?void 0:l.trim())!=null?u:"",n=(g=e==null?void 0:e.now)!=null?g:new Date;return{sessionId:t,ephemeral:!1,utmParams:(d=e==null?void 0:e.utmParams)!=null?d:{},clickIds:(f=e==null?void 0:e.clickIds)!=null?f:{},deviceClass:r?p(r):"desktop",trafficSource:i?R(i,e==null?void 0:e.appOrigin):"direct",referrerDomain:C(i),timeOfDay:I(n),dayOfWeek:(m=["sun","mon","tue","wed","thu","fri","sat"][n.getDay()])!=null?m:"sun",automation:(e==null?void 0:e.webdriver)===!0||y(r)}}import{canonicalArm as P,slotBaselineArm as w,slotResultFor as D}from"@sentientui/policy";function U(t){return a(a(a({id:t.id},t.arms?{arms:[...t.arms]}:{}),t.dims?{dims:Object.fromEntries(Object.entries(t.dims).map(([e,r])=>[e,[...r]]))}:{}),t.baseline!==void 0?{baseline:t.baseline}:{})}function O(t){let e=U(t);return D(e,w(e))}function M(t){let e={};for(let r of t)e[r.id]=O(r);return e}function N(t){return typeof t=="string"?t:P(t)}export{x as a,S as b,_ as c,c as d,y as e,b as f,h as g,L as h,E as i,p as j,R as k,C as l,A as m,T as n,I as o,G as p,k as q,U as r,O as s,M as t,N as u};
2
- //# sourceMappingURL=chunk-2NVSFI4V.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/storage-key.ts","../src/session-meta.ts","../src/slots.ts"],"sourcesContent":["/**\n * Per-project browser-storage namespace suffix, derived from the public apiKey.\n *\n * Multiple SentientUI projects (different `pk_` keys) can run on the same exact\n * origin. Storage keyed only by name (`_snt_uid`, `_snt_asgn_*`,\n * `_snt_graph_nodes`) would then collide across projects — the visitor id in\n * particular, whose session row is keyed globally server-side, would let one\n * project's traffic land on another's session. Suffixing every browser key with\n * the apiKey prefix isolates projects, matching the queue's existing\n * `_snt_retry_${apiKey.slice(0,12)}` convention.\n *\n * Returns `''` when no apiKey is available (local mode) so keys stay stable\n * there.\n */\nexport function storageSuffix(apiKey?: string): string {\n return apiKey ? `_${apiKey.slice(0, 12)}` : '';\n}\n\n/**\n * The bare, pre-namespacing session cookie name. Still read as a FALLBACK\n * everywhere the suffixed name is read, so visitors who got their identity\n * before per-project namespacing keep it instead of being minted a fresh one.\n */\nexport const LEGACY_SESSION_COOKIE_NAME = '_snt_uid';\n\n/**\n * The one place the session cookie's name is decided. The writer (session.ts)\n * and every reader (core/server.ts SSR helper, graph sync, react devtools) must\n * call THIS — when namespacing landed, the writer moved to the suffixed name\n * while three readers kept the bare `_snt_uid`, so every SSR request for a\n * returning visitor missed the cookie and minted a fresh orphan session (quota\n * inflation, broken sticky assignments and persona continuity), and graph sync\n * sent `sessionId: undefined`. Deriving both sides from one function makes that\n * drift impossible, and index.test.ts pins the reader against the writer.\n */\nexport function sessionCookieName(apiKey?: string): string {\n return `${LEGACY_SESSION_COOKIE_NAME}${storageSuffix(apiKey)}`;\n}\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\n/**\n * Ad-platform click-ID query params worth keeping. An ALLOWLIST, unlike the\n * `utm_` prefix match: unknown query keys here are unbounded-cardinality junk\n * (session tokens, cache busters) that would bloat the sessions table, so only\n * the IDs the major ad platforms actually append survive.\n *\n * gclid / gbraid / wbraid — Google Ads auto-tagging (search, YouTube, Display;\n * gbraid/wbraid are the iOS-14 privacy variants)\n * fbclid — Meta (Facebook + Instagram). Appended to EVERY outbound Meta\n * click, paid and organic alike — it identifies the platform, never spend.\n * ttclid — TikTok Ads\n * msclkid — Microsoft Ads (Bing)\n * twclid — X/Twitter Ads\n * li_fat_id — LinkedIn Ads\n */\nexport const CLICK_ID_KEYS: readonly string[] = [\n 'gclid',\n 'gbraid',\n 'wbraid',\n 'fbclid',\n 'ttclid',\n 'msclkid',\n 'twclid',\n 'li_fat_id',\n];\n\n/**\n * Splits a URL query into the attribution params the session upsert carries:\n * every `utm_`-prefixed key, plus allowlisted ad click IDs (CLICK_ID_KEYS).\n * Accepts a raw search string (\"?a=b\" or \"a=b\"), a URLSearchParams, or a\n * Next.js `searchParams` object (whose values may be string arrays — the\n * first occurrence wins, matching URLSearchParams iteration order).\n * Node-safe: no DOM APIs.\n */\nexport function extractTrackedParams(\n search: string | URLSearchParams | Record<string, string | string[] | undefined>,\n): { utmParams: Record<string, string>; clickIds: Record<string, string> } {\n const utmParams: Record<string, string> = {};\n const clickIds: Record<string, string> = {};\n try {\n const entries: Iterable<[string, string]> =\n typeof search === 'string' || search instanceof URLSearchParams\n ? new URLSearchParams(search)\n : Object.entries(search).flatMap(([k, v]): Array<[string, string]> => {\n const first = Array.isArray(v) ? v[0] : v;\n return first === undefined ? [] : [[k, first]];\n });\n for (const [k, v] of entries) {\n // First occurrence wins for duplicates — a repeated gclid in a mangled\n // URL must not let the later value silently replace the real one.\n if (k.startsWith('utm_')) {\n if (!(k in utmParams)) utmParams[k] = v;\n } else if (CLICK_ID_KEYS.includes(k)) {\n if (!(k in clickIds)) clickIds[k] = v;\n }\n }\n } catch {\n /* malformed input → empty attribution, never a throw at init() */\n }\n return { utmParams, clickIds };\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 /** Allowlisted ad-platform click IDs from the landing URL (CLICK_ID_KEYS). */\n clickIds: 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 clickIds?: 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 clickIds: opts?.clickIds ?? {},\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"],"mappings":"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","names":["storageSuffix","apiKey","LEGACY_SESSION_COOKIE_NAME","sessionCookieName","agentUaList","uaTokenMatch","userAgent","matchedAgentToken","_a","s","token","AGENT_INTENTS","agentIntent","botName","hit","t","classifiedAgents","out","detectDeviceClass","detectTrafficSource","referrer","appOrigin","refUrl","e","host","referrerDomainFromReferer","CLICK_ID_KEYS","extractTrackedParams","search","utmParams","clickIds","entries","k","v","first","detectTimeOfDay","d","h","deriveSessionSegment","opts","body","buildSessionUpsertPayload","sessionId","_b","_c","_d","_e","_f","_g","_h","ua","referer","now","canonicalArm","slotBaselineArm","slotResultFor","toWireSlot","d","__spreadValues","dim","values","baselineResultFor","decl","slotResultFor","slotBaselineArm","baselineSlots","decls","out","armOfResult","result","canonicalArm"]}
@@ -1,2 +0,0 @@
1
- import{a as xe,c as Ke,e as Ge,j as Fe,k as $e,l as Ue,n as je,o as We,r as Ve,s as Ee,u as ze}from"./chunk-2NVSFI4V.mjs";import{a as T,b as pe}from"./chunk-TMCGHANO.mjs";function Ie(){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 o=0;o<16;o++)t+=e[o].toString(16).padStart(2,"0"),(o===3||o===5||o===7||o===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)})}var Nt="_snt_uid",Kt=365,_e="_snt_uid";function Gt(){return Ie()}function vt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Ft(e,t,o){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${o}; SameSite=strict; path=/`}catch(p){}}function He(e){try{return localStorage.getItem(e)}catch(t){return null}}function kt(e,t){try{return localStorage.setItem(e,t),!0}catch(o){return!1}}function bt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function $t(e,t){try{return sessionStorage.setItem(e,t),!0}catch(o){return!1}}function Ut(e){try{sessionStorage.removeItem(e)}catch(t){}}function jt(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 Wt(e){try{localStorage.removeItem(e)}catch(t){}}function Vt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var zt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Ce(e){var c,f,w,v,D,V,P;if(typeof window=="undefined")return zt;let t=xe(e==null?void 0:e.apiKey),o=(c=e==null?void 0:e.cookieName)!=null?c:Ke(e==null?void 0:e.apiKey),p=`${_e}${t}`,h=`${_e}_tomb${t}`,r=((f=e==null?void 0:e.cookieTTLDays)!=null?f:Kt)*24*60*60,d=K=>K&&K.length>0?K:null,g=()=>{var K,M;return t&&!(e!=null&&e.cookieName)&&He(h)===null?(M=(K=d(vt(Nt)))!=null?K:d(He(_e)))!=null?M:d(bt(_e)):null},i=(P=(V=(D=(v=(w=d(vt(o)))!=null?w:d(He(p)))!=null?v:d(bt(p)))!=null?D:g())!=null?V:d(e==null?void 0:e.ssrSessionId))!=null?P:Gt();Ft(o,i,r);let s=kt(p,i),l=jt(o),I=s?!1:$t(p,i),R=!s&&!l&&!I;return{getSessionId:()=>i,isEphemeral:()=>R,destroy:()=>{i=null,Vt(o),Wt(p),Ut(p),t&&!(e!=null&&e.cookieName)&&kt(h,"1")}}}function re(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function fe(e){if(e.ok===!0)return"delivered";let{status:t}=e;return typeof t!="number"?"retry":t>=200&&t<300?"delivered":t>=400&&t<500&&t!==429?"dropped":"retry"}function Re(e,t){try{let o=localStorage.getItem(e);if(!o)return[];let p=JSON.parse(o);return Array.isArray(p)?(localStorage.removeItem(e),p.slice(-t)):[]}catch(o){return[]}}function ce(e,t,o){try{let p=(()=>{try{let u=localStorage.getItem(o);if(!u)return[];let r=JSON.parse(u);return Array.isArray(r)?r:[]}catch(u){return[]}})(),h=new Map;for(let u of p)h.set(u.id,u);for(let u of e)h.set(u.id,u);localStorage.setItem(o,JSON.stringify([...h.values()].slice(-t)))}catch(p){}}function Oe(e,t){try{let o=localStorage.getItem(t);if(!o)return;let p=JSON.parse(o);if(!Array.isArray(p))return;let h=new Set(e),u=p.filter(r=>!h.has(r.id));if(u.length===p.length)return;u.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(u))}catch(o){}}var Ht=500,Jt=56*1024;function Je(e){return`_snt_retry_${e.slice(0,12)}`}var Qt={push:()=>{},flush:()=>{},destroy:()=>{}};function wt(e){var Y,oe,ge;if(typeof window=="undefined")return Qt;let t=(Y=e.flushIntervalMs)!=null?Y:5e3,o=(oe=e.maxBatchSize)!=null?oe:20,p=(ge=e.maxRetrySize)!=null?ge:100,h=e.ingestUrl,u=e.apiKey,r=Je(u),d=[],g=new Set,i=[],s=b=>{for(let A of b)l.delete(A),!g.has(A)&&(g.add(A),i.push(A));for(;i.length>Ht;){let A=i.shift();A&&g.delete(A)}Oe(b,r)},l=new Set,I=()=>{for(;d.length>p;){let b=d.shift();b&&l.delete(b.id)}},R=b=>{g.has(b.id)||l.has(b.id)||(l.add(b.id),d.push(b),I())},c=b=>{for(let A of b)g.has(A.id)||(l.add(A.id),d.push(A));I()},f=Re(r,p);for(let b of f)R(b);let w=0,v=0,D=(b,A=!0)=>{if(b.length===0)return;let se=JSON.stringify(b),ie=b.map(Z=>Z.id),Q;try{Q=fetch(h,{method:"POST",keepalive:!0,body:se,headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`}})}catch(Z){ce(b,p,r),c(b),v++,w=Date.now()+re(v);return}let Se=Z=>{if(fe(Z)!=="retry"){if(!Z.ok&&A){let ae=b.filter(X=>X.eventType!=="pageview");if(ae.length>0&&ae.length<b.length){s(b.filter(X=>X.eventType==="pageview").map(X=>X.id)),D(ae,!1);return}}s(ie),v=0,w=0;return}ce(b,p,r),c(b),v++,w=Date.now()+re(v)};Q instanceof Promise?Q.then(Se).catch(()=>{ce(b,p,r),c(b),v++,w=Date.now()+re(v)}):Se(Q)},V=typeof TextEncoder!="undefined"?new TextEncoder:null,P=b=>V?V.encode(b).length:b.length,K=b=>{let A=[],se=2;for(let ie of b){let Q=P(JSON.stringify(ie))+1;if(A.length>0&&se+Q>Jt||A.length>=o)break;A.push(ie),se+=Q}return A},M=()=>{try{if(Date.now()<w)return;for(;d.length>0&&!(Date.now()<w);){let b=d.filter(se=>!g.has(se.id));if(d.length=0,b.length===0)break;let A=K(b);if(A.length===0)break;A.length<b.length&&d.push(...b.slice(A.length)),D(A)}}catch(b){}},k=!0,L=null;L=setInterval(()=>{k&&M()},t);let G=()=>{document.visibilityState==="hidden"&&M()},ne=()=>{M()};return document.addEventListener("visibilitychange",G),window.addEventListener("pagehide",ne),{push(b){R(b),d.length>=o&&M()},flush:M,destroy(){k=!1,L!==null&&(clearInterval(L),L=null),document.removeEventListener("visibilitychange",G),window.removeEventListener("pagehide",ne),M()}}}var qt=200;function Qe(e){return`_snt_goal_retry_${e.slice(0,12)}`}var Xt={send:()=>{},flush:()=>{},destroy:()=>{}};function xt(e){var P,K,M;if(typeof window=="undefined")return Xt;let t=(P=e.flushIntervalMs)!=null?P:5e3,o=(K=e.maxRetrySize)!=null?K:100,p=(M=e.maxPerFlush)!=null?M:5,h=Qe(e.apiKey),u=[],r=new Set,d=new Set,g=[],i=0,s=0,l=!1,I=k=>{for(r.delete(k.id),d.has(k.id)||(d.add(k.id),g.push(k.id));g.length>qt;){let L=g.shift();L&&d.delete(L)}Oe([k.id],h)},R=k=>{ce([k],o,h),!d.has(k.id)&&!r.has(k.id)&&(r.add(k.id),u.push(k)),Date.now()>=i&&(s++,i=Date.now()+re(s))},c=k=>{let L;try{L=fetch(e.url,{method:"POST",keepalive:!0,body:k.body,headers:e.headers})}catch(ne){R(k);return}let G=ne=>{var oe;let Y=fe(ne);if(Y==="retry"){R(k);return}Y==="dropped"&&((oe=e.onDrop)==null||oe.call(e,k,ne.status)),I(k),s=0,i=0};L instanceof Promise?L.then(G).catch(()=>R(k)):G(L)},f=()=>{try{if(l||Date.now()<i)return;let k=0;for(;u.length>0&&k<p&&!(Date.now()<i);){let L=u.shift();r.delete(L.id),!d.has(L.id)&&(k++,c(L))}}catch(k){}},w=Re(h,o);for(let k of w)r.has(k.id)||(r.add(k.id),u.push(k));w.length>0&&ce(w,o,h);let v=setInterval(f,t),D=()=>{document.visibilityState==="hidden"&&f()},V=()=>f();return document.addEventListener("visibilitychange",D),window.addEventListener("pagehide",V),{send(k){if(!l&&!(d.has(k.id)||r.has(k.id))){if(Date.now()<i){ce([k],o,h),r.add(k.id),u.push(k);return}c(k)}},flush:f,destroy(){clearInterval(v),document.removeEventListener("visibilitychange",D),window.removeEventListener("pagehide",V),f(),l=!0}}}var Yt=1800*1e3;function Ae(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Et(e=Yt,t){let o=new Map,p=`_snt_asgn${xe(t)}_`,h=(i,s)=>`${p}${encodeURIComponent(i)}:${encodeURIComponent(s)}`,u=i=>{let s=i.slice(p.length),l=s.indexOf(":");if(l<0)return null;try{return{componentId:decodeURIComponent(s.slice(0,l)),segment:decodeURIComponent(s.slice(l+1))}}catch(I){return null}},r=()=>{try{let i=[];for(let s=0;s<localStorage.length;s++){let l=localStorage.key(s);l!=null&&l.startsWith(p)&&i.push(l)}return i}catch(i){return[]}},d=i=>i.assignedAt+(i.ttlMs&&i.ttlMs>0?i.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let i of r())try{let s=localStorage.getItem(i);if(!s)continue;let l=JSON.parse(s);if(d(l)){localStorage.removeItem(i);continue}let I=u(i);if(!I)continue;o.set(Ae(I.componentId,I.segment),l)}catch(s){}})(),{get(i,s){let l=o.get(Ae(i,s));return l?d(l)?(o.delete(Ae(i,s)),null):l:null},set(i,s,l){let I=Ae(i,s);o.set(I,l);try{localStorage.setItem(h(i,s),JSON.stringify(l))}catch(R){}},clear(){o.clear();for(let i of r())try{localStorage.removeItem(i)}catch(s){}}}}var ye="_snt_snap:",Zt=["low","medium","high"];function ve(e){try{let t=localStorage.getItem(ye+e);if(!t)return null;let o=JSON.parse(t);if(!o||typeof o!="object"||o.v!==1||typeof o.persona!="string"||typeof o.band!="string"||!Zt.includes(o.band)||typeof o.slots!="object"||o.slots===null||Array.isArray(o.slots)||!(o.layoutOrder===null||Array.isArray(o.layoutOrder))||typeof o.savedAt!="number"||!(o.slotConfig===void 0||typeof o.slotConfig=="object"&&o.slotConfig!==null&&!Array.isArray(o.slotConfig)))return null;let p=o.vocabulary;return p!==void 0&&(typeof p!="object"||p===null||!Array.isArray(p.entries)||!Array.isArray(p.images))&&delete o.vocabulary,o}catch(t){return null}}function ke(e,t){try{localStorage.setItem(ye+e,JSON.stringify(t))}catch(o){}}function en(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(ye+e).replace(/</g,"\\u003c")+');if(!r)return;var s=JSON.parse(r);if(!s||s.v!==1||typeof s.persona!=="string"||typeof s.band!=="string")return;var d=document.documentElement;if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}import{confidenceBand as Ot}from"@sentientui/policy";import{confidenceBand as qe}from"@sentientui/policy";var Xe="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",_t="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",It=!1,Te=!1;function tn(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Ct(e){var i;let t=Ce({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),o=(i=t.getSessionId())!=null?i:"local",p=tn(),h=import("@sentientui/core/local").then(s=>{let l=s;return l.LOCAL_ENGINE_AVAILABLE?(It||(It=!0,console.info(_t)),l):(Te||(Te=!0,console.error(Xe)),null)}).catch(()=>(Te||(Te=!0,console.error(Xe)),null)),u=null,r={low:.15,medium:.5,high:.85},d=(()=>{var l;if(e.initialPersona)return T({},e.initialPersona);let s=ve(e.apiKey||"local");return s?{persona:s.persona,confidence:(l=r[s.band])!=null?l:.15}:null})();function g(s){let l=document.documentElement;l.dataset.sentientPersona===void 0&&(l.dataset.sentientPersona=s.persona,l.dataset.sentientConfidence=qe(s.confidence))}return{isLocal:!0,async decide(s){var R,c,f;let l=await h;if(!l)return null;let I=l.createLocalEngine({sessionId:o,forcedPersona:p}).decide(s);return u=pe(T({},I),{layoutOrder:(c=(R=I.layoutOrder)!=null?R:u==null?void 0:u.layoutOrder)!=null?c:null,slots:T(T({},(f=u==null?void 0:u.slots)!=null?f:{}),I.slots)}),ke(e.apiKey||"local",{v:1,persona:u.persona,band:qe(u.confidence),slots:u.slots,layoutOrder:u.layoutOrder,savedAt:Date.now()}),g(I),I},getSlotResult(s){var l,I,R;return(R=(I=u==null?void 0:u.slots[s])!=null?I:(l=e.initialSlots)==null?void 0:l[s])!=null?R:null},getSlotConfig(s){var l,I;return(I=(l=e.initialSlotConfig)==null?void 0:l[s])!=null?I:null},getSitePalette(){var s;return(s=e.initialPalette)!=null?s:null},reportSlots(){},getPersona(){let s=u!=null?u:d;return s?{persona:s.persona,confidence:s.confidence,band:qe(s.confidence)}:null},async assign(s,l){var c;let I=await h;return!I||!l||l.length===0?l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null:{variantId:(c=I.createLocalEngine({sessionId:o,forcedPersona:p}).decide({components:[{id:s,variantIds:l}]}).assignments[s])!=null?c:l[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>t.destroy()}}var Rt=/^(\*|\/[^\s?#*]*(\/\*)?)$/;function Ye(e){let t=e.split(/[?#]/)[0]||"/";return t.length>1?t.replace(/\/+$/,"")||"/":t}function nn(e,t){if(e===void 0||!Rt.test(e))return!1;if(e==="*")return!0;let o=Ye(t);if(e.endsWith("/*")){let p=Ye(e.slice(0,-2));return o.startsWith(p==="/"?"/":`${p}/`)&&o!==p}return o===Ye(e)}var Mn=["none","sm","md","lg"],Nn=["start","center","end","stretch"],Kn=["start","center","end","between"],Gn=["sm","md","lg"],Fn=["normal","medium","bold"],$n=["default","muted","accent"],Un=["primary","secondary","ghost"],jn=["left","center","right"],Wn=["auto","square","landscape","wide"],Vn=["cover","contain"],zn=[2,3,4],Hn=[1,2,3,4],Jn=["default","raised"],Qn=["none","sm","md","lg"],qn=["measure"],Xn=["input","textarea","select"],Yn=["text","email","number","tel"],Zn=5,eo=8,to=64,no=5,oo=12,so=4,ro=500;function on(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.type==="form"?!0:Array.isArray(t.children)?t.children.some(on):!1}var Ze="sentient-reveal",me="sentient-revealed",sn=240,Pe=!1;function rn(){var e;Pe=!1,typeof document!="undefined"&&((e=document.getElementById(Ze))==null||e.remove())}function an(e){if(Pe||e.getElementById(Ze)){Pe=!0;return}let t=e.createElement("style");t.id=Ze,t.textContent=`@media (prefers-reduced-motion: no-preference){@keyframes ${me}{from{opacity:.55;transform:translateY(2px)}to{opacity:1;transform:none}}.${me}{animation:${me} 240ms cubic-bezier(.2,.6,.2,1) both}}`,e.head.appendChild(t),Pe=!0}function ln(e,t={}){var h;let o=(h=t.doc)!=null?h:typeof document!="undefined"?document:void 0;if(!o||!(e instanceof Element)||(t.arm!==void 0&&e.setAttribute("data-sentient-arm",t.arm),t.persona!==void 0&&e.setAttribute("data-sentient-persona",t.persona),t.previous!==void 0&&t.previous===e.textContent))return!1;an(o),e.classList.remove(me),e.offsetWidth,e.classList.add(me);let p=()=>{e.classList.remove(me),e.removeEventListener("animationend",p)};return e.addEventListener("animationend",p),!0}function dn(e,t,o,p){let h=[];{let d=!1,g=[],i=()=>{if(d)return;let s=Date.now();for(g.push(s);g.length>0&&s-g[0]>500;)g.shift();g.length>=3&&(d=!0,e("rage_click"))};t.addEventListener("click",i),h.push(()=>t.removeEventListener("click",i))}{let u=!1,r=d=>{if(u||!(d.target instanceof Node)||!t.contains(d.target)&&t!==d.target)return;u=!0;let g=typeof window!="undefined"?window.getSelection():null,i=g?g.toString().length:0;e("text_copy",{selectionLength:i})};document.addEventListener("copy",r),h.push(()=>document.removeEventListener("copy",r))}{let u=!1,r=!1,d=null,g=()=>{d!==null&&(clearTimeout(d),d=null)},i=()=>{u||!r||(g(),d=setTimeout(()=>{!u&&r&&(u=!0,e("scroll_hesitation"))},3e3))},s=()=>{g(),i()},l=R=>{for(let c of R)r=c.intersectionRatio>.3,r?i():g()},I=new IntersectionObserver(l,{threshold:[.3]});I.observe(t),window.addEventListener("scroll",s,{passive:!0}),h.push(()=>{I.disconnect(),window.removeEventListener("scroll",s),g()})}if((p==null?void 0:p.tabLoss)!==!1){let u=!1,r=o!=null?o:Date.now(),d=()=>{if(u||document.visibilityState!=="hidden")return;let g=Date.now()-r;g<15e3&&(u=!0,e("tab_loss",{timeOnPage:g}))};document.addEventListener("visibilitychange",d),h.push(()=>document.removeEventListener("visibilitychange",d))}return()=>{for(let u of h)u()}}function cn(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var At="https://api.sentient-ui.com/v1/events",J=new Map,Tt=null;function Ao(e,t){let o=J.get(e);o&&o.upgrade&&(o.reinit=t)}function un(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var pn=3;function et(){return Ie()}function Be(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function gn(){let e=new WeakMap,t=new Map,o=!1,p=(d,g,i)=>{let s=d.get(g);return i===null?s?!0:(d.set(g,new Set),!1):s?s.has(i)?!0:(s.add(i),!1):(d.set(g,new Set([i])),!1)},h=typeof window!="undefined"&&"event"in window,u=()=>{if(!h)return;let d=window.event;return typeof Event=="function"&&d instanceof Event?d:void 0},r=()=>{if(h){Promise.resolve().then(()=>{o=!1,t.clear()});return}let d=!1,g=()=>{d||(d=!0,o=!1,t.clear())};if(setTimeout(g,0),typeof MessageChannel=="function"){let i=new MessageChannel;i.port1.onmessage=()=>{i.port1.close(),i.port2.close(),g()},i.port2.postMessage(0)}};return{firedBefore(d,g){let i=u();if(i){let l=e.get(i);return l||(l=new Map,e.set(i,l)),p(l,d,g)}let s=p(t,d,g);return!s&&!o&&(o=!0,r()),s}}}var Pt=new Set;function fn(e,t,o){let p=typeof window=="undefined"?null:window.history;if(!p)return()=>{};let h=!1,u,r=()=>{if(h)return;let i=Be();!i||i===u||(u=i,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),o(`${t}:${i}`))},d=[];for(let i of["pushState","replaceState"]){let s=p[i],l=function(...I){let R=s.apply(this,I);return r(),R};p[i]=l,d.push([i,s,l])}window.addEventListener("popstate",r);let g=Be();return g&&Pt.has(`${t}:${g}`)?u=g:r(),()=>{if(!h){h=!0,window.removeEventListener("popstate",r);for(let[i,s,l]of d)p[i]===l&&(p[i]=s)}}}var be={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}};function yn(){try{return je(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function Bt(e){return e.replace(/\/events\/?$/,"")}function Dt(){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 To(e){var g;if(typeof window=="undefined")return;let t=e!=null?e:Tt;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let o=J.get(t);if(!o){console.warn("[sentient] grantConsent() called before init()");return}let{config:p,upgrade:h,reinit:u}=o;if(!h){o.upgradeBlockedReason&&console.warn(o.upgradeBlockedReason);return}if(p.respectDoNotTrack!==!1&&Dt())return;let r=(u!=null?u:Sn)(pe(T({},p),{consent:!0}));h(r);let d=(g=J.get(t))==null?void 0:g.dispose;J.set(t,{config:pe(T({},p),{consent:!0}),upgrade:null,dispose:d})}function mn(e){var R;let t=e.preConsentBehavior==="statistical_winner",o=Bt((R=e.ingestUrl)!=null?R:At),p={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},h=new Map,u=new Map,r={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(c,f,w){if(!t)return Promise.resolve(null);let v=h.get(c);return v?Promise.resolve(v):tt(u,c,async()=>{try{let D=new URLSearchParams({componentId:c});for(let M of f!=null?f:[])D.append("variantIds[]",M);let V=await fetch(`${o}/winner?${D.toString()}`,{headers:p});if(!V.ok)return f!=null&&f[0]?{variantId:f[0],assignmentTtlMs:0}:null;let K={variantId:(await V.json()).variantId,assignmentTtlMs:0};return h.set(c,K),K}catch(D){return f!=null&&f[0]?{variantId:f[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}},d=!1,g=new Set,i=[],s=[],l={track:c=>r.track(c),goal:((c,f,w,v)=>r.goal(c,f,w,v)),componentGoal:(c,f,w)=>r.componentGoal(c,f,w),identify:c=>r.identify(c),getAssignment:(c,f)=>r.getAssignment(c,f),assign:(c,f,w,v)=>r.assign(c,f,w,v),decide:c=>r.decide(c),getSlotResult:c=>r.getSlotResult(c),isSlotDecided:c=>{var f,w;return(w=(f=r.isSlotDecided)==null?void 0:f.call(r,c))!=null?w:!0},getSlotConfig:c=>r.getSlotConfig(c),getSitePalette:()=>r.getSitePalette(),getStyleVocabulary:()=>{var c,f;return(f=(c=r.getStyleVocabulary)==null?void 0:c.call(r))!=null?f:null},reportSlots:(c,f,w,v)=>r.reportSlots(c,f,w,v),reportSkeleton:(c,f)=>{var w;return(w=r.reportSkeleton)==null?void 0:w.call(r,c,f)},reportDrift:(c,f,w,v)=>{var D;return(D=r.reportDrift)==null?void 0:D.call(r,c,f,w,v)},requestSlots:(c,f,w)=>{var v;return d?(v=r.requestSlots)==null?void 0:v.call(r,c,f,w):i.push([c,f,w])},decideSlots:c=>{var f;return d?(f=r.decideSlots)==null?void 0:f.call(r,c):s.push(...c)},cancelSlots:c=>{var w;if(d)return(w=r.cancelSlots)==null?void 0:w.call(r,c);let f=new Set(c);for(let v of i)v[0]=v[0].filter(D=>!f.has(D));s=s.filter(v=>!f.has(v.id))},onSlotsChanged:c=>(g.add(c),()=>{g.delete(c)}),getPersona:()=>r.getPersona(),fetchWeights:()=>r.fetchWeights(),getGraph:()=>r.getGraph(),flush:()=>r.flush(),dispose:()=>r.dispose(),destroy:()=>r.destroy()};function I(c){var f,w,v;r=c,d=!0,(f=c.onSlotsChanged)==null||f.call(c,()=>g.forEach(D=>D()));for(let[D,V,P]of i.splice(0))D.length>0&&((w=c.requestSlots)==null||w.call(c,D,V,P));s.length>0&&((v=c.decideSlots)==null||v.call(c,s.splice(0)))}return{proxy:l,setInner:I}}function tt(e,t,o){let p=e.get(t);if(p)return p;let h=(async()=>{try{return await o()}finally{e.delete(t)}})();return e.set(t,h),h}function Sn(e){var at,lt,dt,ct,ut,pt,gt,ft,yt,mt;if(typeof window=="undefined")return be;Tt=e.apiKey||"local";let t=J.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(n){}let o=e.respectDoNotTrack!==!1&&Dt(),p=e.consent===!1||o,h=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!h&&e.localMode!==!1)return J.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): this client is keyless/local \u2014 there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking."}),p?be:Ct(e);if(p){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return e.preConsentBehavior==="statistical_winner"&&console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),J.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) \u2014 consent cannot enable tracking."}),be;let{proxy:n,setInner:a}=mn(e);return J.set(e.apiKey,{config:e,upgrade:o?null:a}),n}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."),be;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),be;let u=(at=e.ingestUrl)!=null?at:At,r=Date.now(),d=Ce({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),g=Et(void 0,e.apiKey),i=wt({ingestUrl:u,apiKey:e.apiKey}),s=Bt(u),l={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},I=new Set,R=xt({url:`${s}/goals`,apiKey:e.apiKey,headers:l,onDrop:(n,a)=>{if(!e.debug){if(I.has(a))return;I.add(a)}console.warn(`[sentient] goal dropped (HTTP ${a}) \u2014 this will not be retried. `+(a===400?"The session was not found: call init() and let the session upsert complete before firing goals.":a===401||a===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),n)}}),c=Fe((lt=navigator.userAgent)!=null?lt:""),f=window.location.origin,w=$e((dt=document.referrer)!=null?dt:"",f),v=(ct=e.sessionSegment)!=null?ct:`${c}:${w}`,D=new Map,V=new Map,P=new Map,K=new Set,M=new Map,k=null,L=null,G=null,ne=new Set,Y=new Set,oe=new Map,ge=new Map,b=new Set,A=new Set,se=new Set,ie=null,Q=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,Se=new Set,Z=new Set,ae=new Set,X=new Map,De=null,we=new Set,he=new Map,Le=null,Lt=2,nt=new Map,Me=!1,ot=(n,a,S)=>{var y;let E=new Set,_=1;for(let m of n){a.delete(m);let C=((y=nt.get(m))!=null?y:0)+1;nt.set(m,C),C<=Lt&&(E.add(m),C>_&&(_=C))}E.size>0&&setTimeout(()=>{Me||S(E)},re(_))},st=n=>{for(let a of n)P.has(a.id)||P.set(a.id,Ee(a))};if(e.initialSlots)for(let[n,a]of Object.entries(e.initialSlots))P.set(n,a),K.add(n);if(e.initialSlotConfig)for(let[n,a]of Object.entries(e.initialSlotConfig))M.set(n,a);e.initialPalette&&(k=e.initialPalette),e.initialVocabulary&&(L=e.initialVocabulary);let ee=ve(e.apiKey);if(ee){for(let[n,a]of Object.entries(ee.slots))P.has(n)||P.set(n,a);for(let[n,a]of Object.entries((ut=ee.slotConfig)!=null?ut:{}))M.has(n)||M.set(n,a);!k&&ee.palette&&(k=ee.palette),!L&&ee.vocabulary&&(L=ee.vocabulary)}let rt={low:.15,medium:.5,high:.85};if(e.initialPersona)G=T({},e.initialPersona);else{let n=document.documentElement.dataset;n.sentientPersona?G={persona:n.sentientPersona,confidence:(gt=rt[(pt=n.sentientConfidence)!=null?pt:"low"])!=null?gt:.15}:ee&&(G={persona:ee.persona,confidence:(ft=rt[ee.band])!=null?ft:.15})}if(e.initialAssignments)for(let[n,a]of Object.entries(e.initialAssignments))g.set(n,v,{variantId:a,assignedAt:Date.now(),segment:v,confidence:1});let le=Promise.resolve(),it=d.getSessionId();if(it){let n=Ue((yt=document.referrer)!=null?yt:""),{utmParams:a,clickIds:S}=yn(),E=T(T(T(T({sessionId:it,deviceClass:c,trafficSource:w,referrerDomain:n,utmParams:a,clickIds:S,timeOfDay:We(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:d.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Ge((mt=navigator.userAgent)!=null?mt:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{}),e.sdk?{sdk:e.sdk.name,sdkVersion:e.sdk.version}:{}),_=async()=>{for(let y=0;;y++){try{let m=await fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(E),headers:l});if(m.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");return}if(m.ok||fe(m)==="dropped")return}catch(m){}if(y>=pn){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(m=>setTimeout(m,re(y+1)))}};try{le=_()}catch(y){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:i});let Mt=gn(),ue=null,Ne=!1,F={goal(n,a={},S=1,E=0){var j,$,H,q,z,x,W;let _=d.getSessionId();if(!_)return;let y=un(a)?a:{metadata:a},m=[n,(j=y.externalId)!=null?j:"",($=y.stepIndex)!=null?$:E,(H=y.weight)!=null?H:S].join("\0"),C=y.value!==void 0?`${y.value}\0${(q=y.currency)!=null?q:""}`:null;if(Mt.firedBefore(m,C)){e.debug&&console.log(`[sentient] goal("${n}") already recorded for this action \u2014 not sent twice`);return}let O=et(),B={sessionId:_,name:n,metadata:(z=y.metadata)!=null?z:{},weight:(x=y.weight)!=null?x:S,stepIndex:(W=y.stepIndex)!=null?W:E,goalId:O,value:y.value,currency:y.currency,externalId:y.externalId};e.debug&&console.log("[sentient] goal",B);let U={id:O,body:JSON.stringify(B)};le.then(()=>R.send(U))},componentGoal(n,a,S){var O,B,U;let E=d.getSessionId();if(!E)return;let _=g.get(n,v),y=_?null:(O=P.get(n))!=null?O:null;if(!_&&y===null){e.debug&&console.warn(`[sentient] componentGoal("${n}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}if(!_&&!K.has(n)){e.debug&&console.warn(`[sentient] componentGoal("${n}"): slot not decided this session \u2014 not attributed`);return}let m=_?_.variantId:ze(y),C={id:et(),sessionId:E,projectId:e.apiKey,componentId:n,variantId:m,eventType:"goal_achieved",goalType:a,payload:T({reward:(B=S==null?void 0:S.reward)!=null?B:1,goalValue:S==null?void 0:S.value,currency:S==null?void 0:S.currency},(U=S==null?void 0:S.metadata)!=null?U:{}),timestamp:Date.now(),timeInSession:Date.now()-r,path:Be()};e.debug&&console.log("[sentient] componentGoal",C),le.then(()=>i.push(C))},identify(n){let a=d.getSessionId();a&&le.then(()=>{fetch(`${s}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:a,userId:n,ephemeral:d.isEphemeral()}),headers:l}).catch(()=>{})})},track(n){let a=d.getSessionId();if(!a||n.eventType==="variant_assigned"&&P.get(n.componentId)!==void 0&&!K.has(n.componentId)&&!g.get(n.componentId,v))return;let S=pe(T({path:Be()},n),{id:et(),sessionId:a,timestamp:Date.now(),timeInSession:Date.now()-r});e.debug&&console.log("[sentient] track",S),le.then(()=>i.push(S))},getAssignment(n,a){return g.get(n,a)},async assign(n,a,S,E){let _=d.getSessionId();if(!_)return null;let y=g.get(n,v);if(y&&(a!=null&&a.length||y.content!==void 0)){let m=y.ttlMs&&y.ttlMs>0?Math.max(0,y.assignedAt+y.ttlMs-Date.now()):0;return{variantId:y.variantId,assignmentTtlMs:m,content:y.content}}return tt(D,n,async()=>{await le;try{let m={sessionId:_,componentId:n,variantIds:a};E!==void 0?m.agentDataByVariant=E:S!==void 0&&(m.agentData=S);let C=await fetch(`${s}/assign`,{method:"POST",body:JSON.stringify(m),headers:l});if(!C.ok)return null;let O=await C.json();return g.set(n,v,T({variantId:O.variantId,assignedAt:Date.now(),segment:v,confidence:1,content:O.content},O.assignmentTtlMs&&O.assignmentTtlMs>0?{ttlMs:O.assignmentTtlMs}:{})),O}catch(m){return null}})},async decide(n){var y,m;let a=d.getSessionId();if(!a)return null;let S=(y=n.slots)!=null?y:[],E={sessionId:a};n.sections&&n.sections.length>0&&(E.sections=n.sections.map(C=>({id:C}))),E.components=(m=n.components)!=null?m:[],S.length>0&&(E.slots=S.map(Ve)),n.slotsFrom==="registry"&&(E.slotsFrom="registry",n.registrySlotIds&&(E.registrySlotIds=n.registrySlotIds),n.bootstrap===!1&&(E.bootstrap=!1),n.render&&Object.keys(n.render).length>0&&(E.render=n.render)),n.v&&(E.v=n.v),typeof n.pp=="number"&&(E.pp=n.pp),e.persona&&(E.persona=e.persona);let _=JSON.stringify(E);return tt(V,_,async()=>{var C,O,B,U,j,$,H,q;await le;try{let z=await fetch(`${s}/decide`,{method:"POST",body:_,headers:l});if(!z.ok)return st(S),null;let x=await z.json(),W={};for(let N of S){let te=(C=x.slots)==null?void 0:C[N.id];if(te!==void 0){W[N.id]=te,P.set(N.id,te),K.add(N.id);continue}let St=P.get(N.id);if(St!==void 0)W[N.id]=St;else{let ht=Ee(N);W[N.id]=ht,P.set(N.id,ht)}}if(x.slots)for(let[N,te]of Object.entries(x.slots))N in W||(W[N]=te,P.set(N,te),K.add(N));let de=G!=null&&G.persona!=="unknown";x.persona&&!(x.persona==="unknown"&&de)?G={persona:x.persona,confidence:(O=x.confidence)!=null?O:0}:G||(G={persona:"unknown",confidence:0});for(let[N,te]of Object.entries((B=x.assignments)!=null?B:{}))g.set(N,v,{variantId:te,assignedAt:Date.now(),segment:v,confidence:1});if(x.slotConfig)for(let[N,te]of Object.entries(x.slotConfig))M.set(N,te);x.palette&&(k=x.palette),x.vocabulary&&(L=x.vocabulary);for(let N of(U=n.registrySlotIds)!=null?U:[])(j=x.slotConfig)!=null&&j[N]||(M.delete(N),P.delete(N),K.delete(N));return ke(e.apiKey,T(T(T({v:1,persona:G.persona,band:Ot(G.confidence),slots:Object.fromEntries(P),layoutOrder:($=x.layoutOrder)!=null?$:null,savedAt:Date.now()},M.size>0?{slotConfig:Object.fromEntries(M)}:{}),k?{palette:k}:{}),L?{vocabulary:L}:{})),T(T(T(T(T({layoutOrder:(H=x.layoutOrder)!=null?H:null,assignments:(q=x.assignments)!=null?q:{},slots:W,persona:G.persona,confidence:G.confidence},x.slotConfig?{slotConfig:x.slotConfig}:{}),x.goals?{goals:x.goals}:{}),x.sectionMap?{sectionMap:x.sectionMap}:{}),x.palette?{palette:x.palette}:{}),x.vocabulary?{vocabulary:x.vocabulary}:{})}catch(z){return st(S),null}})},getSlotResult(n){var a;return(a=P.get(n))!=null?a:null},isSlotDecided(n){return K.has(n)},getSlotConfig(n){var a;return(a=M.get(n))!=null?a:null},reportSlots(n,a,S,E){var y;let _={};for(let[m,C]of Object.entries(E!=null?E:{}))for(let O of C){let B=`${m}|${O.key}`;!Q.test(m)||se.has(B)||(se.add(B),((y=_[m])!=null?y:_[m]=[]).push(O))}Object.keys(_).length>0&&fetch(`${s}/slots/observed`,{method:"POST",headers:l,body:JSON.stringify({slotIds:Object.keys(_),authoredArms:_})}).catch(()=>{});for(let m of n)if(!(typeof m!="string"||m.length===0)){if(!Q.test(m)){cn()&&!Se.has(m)&&(Se.add(m),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(m)} will not register \u2014 ids must start with a letter or digit and contain only letters, digits, '_' or '-' (max 128 chars): /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.`));continue}if(!ne.has(m)){ne.add(m),Y.add(m);let C=a==null?void 0:a[m];if(typeof C=="string"){let B=C.replace(/\s+/g," ").trim().slice(0,400);B!==""&&oe.set(m,B)}let O=S==null?void 0:S[m];O!==void 0&&ge.set(m,O)}}Y.size===0||ie!=null||(ie=setTimeout(()=>{ie=null;let m=[...Y];Y.clear();for(let C=0;C<m.length;C+=20){let O=m.slice(C,C+20),B={},U={};for(let j of O){let $=oe.get(j);$!==void 0&&(B[j]=$,oe.delete(j));let H=ge.get(j);H!==void 0&&(U[j]=H,ge.delete(j))}fetch(`${s}/slots/observed`,{method:"POST",headers:l,body:JSON.stringify(pe(T(T({slotIds:O},Object.keys(B).length>0?{baselineTexts:B}:{}),Object.keys(U).length>0?{baselineSkeletons:U}:{}),{pagePaths:Object.fromEntries(O.map(j=>[j,location.pathname]))}))}).catch(()=>{})}},1e3))},reportSkeleton(n,a){!Q.test(n)||b.has(n)||(b.add(n),fetch(`${s}/slots/observed`,{method:"POST",headers:l,body:JSON.stringify({slotIds:[n],baselineSkeletons:{[n]:a}})}).catch(()=>{}))},reportDrift(n,a,S,E){let _=`${n}|${a}`,y=d.getSessionId();!y||A.has(_)||(A.add(_),fetch(`${s}/slots/drift`,{method:"POST",headers:l,body:JSON.stringify({sessionId:y,reports:[{slotId:n,expectedFp:a,observedFp:S,reason:E}]})}).catch(()=>{}))},requestSlots(n,a,S){var E,_;for(let y of n)ae.has(y)||(ae.add(y),Q.test(y)?X.set(y,{text:a==null?void 0:a[y],render:(E=S==null?void 0:S.render)==null?void 0:E[y],skeleton:(_=S==null?void 0:S.skeletons)==null?void 0:_[y]}):F.reportSlots([y]));X.size===0||De!=null||(De=setTimeout(()=>{De=null;let y=[...X];X.clear();for(let m=0;m<y.length;m+=50){let C=y.slice(m,m+50),O={};for(let[B,U]of C)U.render&&(O[B]=U.render);F.decide({slotsFrom:"registry",registrySlotIds:C.map(([B])=>B),bootstrap:!1,render:O}).then(B=>{var U,j;if(B){let $={},H={},q=[];for(let[z,x]of C){let W=(U=B.slotConfig)==null?void 0:U[z];if(W){W.needsSkeleton&&x.skeleton&&((j=F.reportSkeleton)==null||j.call(F,z,x.skeleton));continue}q.push(z),x.text&&($[z]=x.text),x.skeleton&&(H[z]=x.skeleton)}q.length>0&&F.reportSlots(q,$,H)}else ot(C.map(([$])=>$),ae,$=>{var x;let H={},q={},z={};for(let[W,de]of C)$.has(W)&&(de.text&&(H[W]=de.text),de.render&&(q[W]=de.render),de.skeleton&&(z[W]=de.skeleton));(x=F.requestSlots)==null||x.call(F,[...$],H,{render:q,skeletons:z})});Z.forEach($=>$())})}},0))},decideSlots(n){for(let a of n)we.has(a.id)||(we.add(a.id),he.set(a.id,a));he.size===0||Le!=null||(Le=setTimeout(()=>{Le=null;let a=[...he.values()];he.clear();for(let S=0;S<a.length;S+=30){let E=a.slice(S,S+30);F.decide({slots:E}).then(_=>{_||ot(E.map(y=>y.id),we,y=>{var m;return(m=F.decideSlots)==null?void 0:m.call(F,E.filter(C=>y.has(C.id)))}),Z.forEach(y=>y())})}},0))},cancelSlots(n){for(let a of n)X.delete(a)&&ae.delete(a),he.delete(a)&&we.delete(a)},onSlotsChanged(n){return Z.add(n),()=>{Z.delete(n)}},getStyleVocabulary(){return L},getSitePalette(){return k},getPersona(){return G?{persona:G.persona,confidence:G.confidence,band:Ot(G.confidence)}:null},async fetchWeights(){var n;try{let a=await fetch(`${s}/weights`,{headers:l});return a.ok?(n=(await a.json()).components)!=null?n:[]:[]}catch(a){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},flush(){i.flush(),R.flush()},dispose(){var n;ue==null||ue(),Ne=!0,Me=!0,i.destroy(),R.destroy(),((n=J.get(e.apiKey))==null?void 0:n.dispose)===F.dispose&&J.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var n;ue==null||ue(),Ne=!0,Me=!0,i.destroy(),R.destroy(),d.destroy(),g.clear(),((n=J.get(e.apiKey))==null?void 0:n.dispose)===F.dispose&&J.delete(e.apiKey);try{localStorage.removeItem(ye+e.apiKey),localStorage.removeItem(Je(e.apiKey)),localStorage.removeItem(Qe(e.apiKey))}catch(a){}e.debug&&console.log("[sentient] destroyed")}};if(J.set(e.apiKey,{config:e,upgrade:null,dispose:F.dispose}),ue=fn(F,e.apiKey,n=>{le.then(()=>{Ne||Pt.add(n)})}),e.debug){let n=window;n.__sentient&&(n.__sentient.client=F)}return F}export{ye as a,ve as b,ke as c,en as d,Xe as e,_t as f,Rt as g,nn as h,Mn as i,Nn as j,Kn as k,Gn as l,Fn as m,$n as n,Un as o,jn as p,Wn as q,Vn as r,zn as s,Hn as t,Jn as u,Qn as v,qn as w,Xn as x,Yn as y,Zn as z,eo as A,to as B,no as C,oo as D,so as E,ro as F,on as G,sn as H,rn as I,ln as J,dn as K,Ao as L,Dt as M,To as N,Sn as O};
2
- //# sourceMappingURL=chunk-DGRAS5VP.mjs.map