@sentientui/core 0.29.1 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -5
- package/dist/chunk-SFNOFZUH.mjs +2 -0
- package/dist/chunk-SFNOFZUH.mjs.map +1 -0
- package/dist/{index-B0PkJoeB.d.cts → index-DErBinAw.d.cts} +68 -3
- package/dist/{index-BIdUwF-v.d.ts → index-DxWcBI5U.d.ts} +68 -3
- package/dist/index-engagement.d.cts +8 -2
- package/dist/index-engagement.d.ts +8 -2
- package/dist/index-engagement.js +1 -1
- package/dist/index-engagement.js.map +1 -1
- package/dist/index-engagement.mjs +1 -1
- package/dist/index-engagement.mjs.map +1 -1
- package/dist/index-graph.d.cts +21 -5
- package/dist/index-graph.d.ts +21 -5
- 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-graph.mjs.map +1 -1
- package/dist/index-local.d.cts +2 -2
- package/dist/index-local.d.ts +2 -2
- package/dist/index-local.js +1 -1
- package/dist/index-local.js.map +1 -1
- package/dist/index-local.mjs +1 -1
- package/dist/index-local.mjs.map +1 -1
- package/dist/index-server.d.cts +14 -3
- package/dist/index-server.d.ts +14 -3
- 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 +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{session-meta-CY_Luh5i.d.ts → session-meta-DydKfQiR.d.cts} +2 -0
- package/dist/{session-meta-CY_Luh5i.d.cts → session-meta-DydKfQiR.d.ts} +2 -0
- package/llms.txt +4 -4
- package/package.json +2 -2
- package/dist/chunk-HY23LTUY.mjs +0 -2
- package/dist/chunk-HY23LTUY.mjs.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as U}from"./chunk-WKXD7KI3.mjs";import{a as S,d as J,e as b,f as E,g as X}from"./chunk-Z6ILOYBD.mjs";import{K as Y,M as q}from"./chunk-SFNOFZUH.mjs";import"./chunk-2NVSFI4V.mjs";import{a as f,b as H}from"./chunk-TMCGHANO.mjs";import{fnv1a as Z}from"@sentientui/policy";var ee="section, header, footer, nav, main > div, [data-sentient-section]",te=2e4;function ne(d){let o=Array.from(d.querySelectorAll(ee)),i=o.filter(a=>o.filter(c=>c!==a&&a.contains(c)).length<2);return i.filter(a=>!i.some(c=>c!==a&&c.contains(a)))}function oe(d,o,i,a){try{fetch(`${o}/v1/section-map`,{method:"POST",keepalive:!0,headers:{"content-type":"application/json",authorization:`Bearer ${d}`},body:JSON.stringify({pageUrl:i,sections:a})}).catch(()=>{})}catch(c){}}var h=()=>{};function re(d,o){var k,x,R,L,N,D,_,F,P,M,$,K,B,j,V;let i=(k=o.doc)!=null?k:typeof document!="undefined"?document:void 0;if(!i||typeof IntersectionObserver=="undefined"||q()||!o.apiKey||!o.apiKey.startsWith("pk_"))return h;let a=((x=o.apiBase)!=null?x:"https://api.sentient-ui.com").replace(/\/+$/,"").replace(/\/v1$/,""),c=ne(i);if(c.length===0)return h;let g=new Map,A=[];for(let e of c){let t=(N=[(L=o.sectionTypes)==null?void 0:L[(R=e.getAttribute("data-sentient-id"))!=null?R:""],e.getAttribute("data-sentient-type")].find(p=>S.includes(p)))!=null?N:null,n=E(e),r=(_=t!=null?t:(D=o.typeOf)==null?void 0:D.call(o,e))!=null?_:b(n).type,l=U(e,i),T=l?`nc-${r}-${Z(JSON.stringify({id:(F=l.id)!=null?F:null,dataAttr:(P=l.dataAttr)!=null?P:null,selector:(M=l.selector)!=null?M:null})).toString(36)}`:`nc-${r}`;g.set(e,T);let z=J.filter(([,p])=>p.test(n.bodyText)).map(([p])=>p);A.push(H(f({componentId:T,semanticType:r,source:t?"markup":"auto"},l?{locator:l}:{}),{observation:f(f({tag:n.tag,idClass:n.idClass.slice(0,200),headingText:n.headingText,textLength:n.textLength,actionCount:n.actionCount},n.ariaRole?{ariaRole:n.ariaRole}:{}),z.length>0?{patternFlags:z}:{})}))}let W=(j=(B=(K=($=i.defaultView)!=null?$:typeof window!="undefined"?window:void 0)==null?void 0:K.location)==null?void 0:B.pathname)!=null?j:"/";oe(o.apiKey,a,W,A);let u=new Map,G=e=>{let t=u.get(e);return t||(t={ms:0,scroll:0,enterAt:null,intersecting:!1},u.set(e,t)),t},v=new IntersectionObserver(e=>{for(let t of e){let n=g.get(t.target);if(!n)continue;let r=G(n);t.isIntersecting?(r.intersecting=!0,r.enterAt=Date.now(),t.intersectionRatio>r.scroll&&(r.scroll=t.intersectionRatio)):(r.intersecting=!1,r.enterAt!=null&&(r.ms+=Date.now()-r.enterAt,r.enterAt=null))}},{threshold:[0,.25,.5,.75,1]});for(let e of g.keys())v.observe(e);let m=()=>{let e=Date.now();for(let[t,n]of u)if(n.enterAt!=null&&(n.ms+=e-n.enterAt,n.enterAt=null),!(n.ms<=0)){try{d.track({projectId:o.apiKey,componentId:t,eventType:"dwell",payload:{dwell_time:Math.round(n.ms),scroll_depth:Number(n.scroll.toFixed(2))}})}catch(r){}n.ms=0}},w=()=>{if(i.hidden)m();else{let e=Date.now();for(let t of u.values())t.intersecting&&(t.enterAt=e)}},y=!1,C=e=>{if(m(),e!=null&&e.persisted){y=!0;return}try{v.disconnect()}catch(t){}},O=e=>{if(!(e!=null&&e.persisted)||!y)return;y=!1;let t=Date.now();for(let n of u.values())n.enterAt=n.intersecting&&!i.hidden?t:null};i.addEventListener("visibilitychange",w);let s=(V=i.defaultView)!=null?V:typeof window!="undefined"?window:void 0;s==null||s.addEventListener("pagehide",C),s==null||s.addEventListener("pageshow",O);let Q=setInterval(()=>{if(i.hidden||y)return;m();let e=Date.now();for(let t of u.values())t.intersecting&&(t.enterAt=e)},te),I=[];return o.microSignals&&[...g.entries()].forEach(([e,t],n)=>{I.push(Y((r,l={})=>{try{d.track({projectId:o.apiKey,componentId:t,eventType:"micro_signal",payload:f({signalType:r},l)})}catch(T){}},e,void 0,{tabLoss:n===0}))}),()=>{m(),clearInterval(Q),i.removeEventListener("visibilitychange",w),s==null||s.removeEventListener("pagehide",C),s==null||s.removeEventListener("pageshow",O);for(let e of I)e();try{v.disconnect()}catch(e){}}}export{S as SEMANTIC_TYPES,b as classifyFeatures,X as classifySection,E as featuresFromElement,re as startEngagementCapture};
|
|
2
2
|
//# sourceMappingURL=index-engagement.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/engagement/capture.ts"],"sourcesContent":["import {\n classifyFeatures,\n featuresFromElement,\n CONTENT_PATTERNS,\n SEMANTIC_TYPES,\n type SemanticType,\n} from './classify';\nimport { fnv1a } from '@sentientui/policy';\nimport { isDoNotTrackEnabled } from '../index.js';\nimport { attachMicroSignalDetectors } from '../micro-signals.js';\nimport { locatorFromElement } from '../locator-from-dom.js';\n\n// Shared engagement capture (spec 2026-07-22-persona-signal-capture). Detects\n// semantic sections, registers them via /v1/section-map, and records per-section\n// dwell/scroll via IntersectionObserver — emitting the same 'dwell' events the\n// persona pipeline consumes. Used by the React provider (default on) and the\n// no-code snippet. Defense-in-depth: checks DNT internally even though callers\n// gate on consent/DNT too; a missing IntersectionObserver → no-op.\n\ntype CaptureClient = {\n track(event: { projectId: string; componentId: string; eventType: string; payload: Record<string, unknown> }): void;\n};\n\nexport type EngagementCaptureOptions = {\n apiKey: string;\n /** API base, no trailing slash. Defaults to the hosted API. */\n apiBase?: string;\n doc?: Document;\n /**\n * Also attach per-section micro-signal detectors (rage click, text copy,\n * scroll hesitation, tab loss), attributed to the section's per-element `nc-*`\n * component. For the no-code snippet, whose pages have no `<Adaptive>`\n * components carrying their own detectors. Default false — the React SDK\n * keeps its per-component detectors and must not double-attach.\n */\n microSignals?: boolean;\n /**\n * Server-served section-map lookup (persona-coverage auto-classification):\n * consulted after explicit `data-sentient-type` markup, before the local\n * heuristic. Return null when the element has no served label.\n */\n typeOf?: (el: Element) => SemanticType | null;\n};\n\nconst SECTION_SELECTOR = 'section, header, footer, nav, main > div, [data-sentient-section]';\n\n/** Bank cadence for visible dwell. Dwell used to leave the page only on\n * visibilitychange/pagehide, and in production that path delivered for ~5-8%\n * of sessions (Bodyshop audit 2026-08-30): a visitor who reads and closes the\n * tab races the unload pipeline, and mobile browsers can kill a page with no\n * lifecycle event at all. The heartbeat caps the loss at one interval. */\nconst HEARTBEAT_MS = 20_000;\n\n/**\n * Pick the elements to observe. Two rules, in order:\n * 1. A candidate that CONTAINS two or more other candidates is a layout\n * wrapper, not a section — drop it. Pages built from bare divs match\n * `main > div` with their page-wide content wrapper; keeping that outer\n * match swallowed every real <section> inside it, collapsing the whole page\n * into one nc-generic component whose intersectionRatio could never exceed\n * viewport-height / page-height (a constant ~0.05 scroll_depth on the\n * audited site). A candidate with exactly one nested candidate (header >\n * nav) is NOT a wrapper — rule 2 keeps the outer one, as before.\n * 2. Of what remains, skip a section nested inside another kept section\n * (avoid double count).\n */\nfunction selectSections(doc: Document): Element[] {\n const candidates = Array.from(doc.querySelectorAll(SECTION_SELECTOR));\n const kept = candidates.filter(\n (el) => candidates.filter((c) => c !== el && el.contains(c)).length < 2,\n );\n return kept.filter((el) => !kept.some((k) => k !== el && k.contains(el)));\n}\n\n/** Client-sensor observation riding each section-map entry (spec 2026-09-04\n * §2): structure, headings, and which CONTENT_PATTERNS matched — never body\n * text, so nothing beyond headings leaves the page. Lets the server's richer\n * topic classifier label pages the crawler cannot fetch (CSR, auth-walled). */\ntype SectionObservation = {\n tag: string;\n idClass: string;\n headingText: string;\n textLength: number;\n actionCount: number;\n ariaRole?: string;\n patternFlags?: SemanticType[];\n};\n\nfunction registerSections(\n apiKey: string,\n apiBase: string,\n pageUrl: string,\n sections: Array<{\n componentId: string;\n semanticType: SemanticType;\n source: 'markup' | 'auto';\n locator?: unknown;\n observation?: SectionObservation;\n }>,\n): void {\n try {\n void fetch(`${apiBase}/v1/section-map`, {\n method: 'POST',\n keepalive: true,\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify({ pageUrl, sections }),\n }).catch(() => undefined);\n } catch {\n /* fail-safe */\n }\n}\n\nconst NOOP = (): void => undefined;\n\nexport function startEngagementCapture(\n client: CaptureClient,\n opts: EngagementCaptureOptions,\n): () => void {\n const doc = opts.doc ?? (typeof document !== 'undefined' ? document : undefined);\n if (!doc || typeof IntersectionObserver === 'undefined') return NOOP;\n if (isDoNotTrackEnabled()) return NOOP;\n // Keyless zero-network contract: capture exists to feed the hosted persona\n // pipeline — with no api key there is nothing to feed, and the section-map\n // registration fetch must never fire. Same validity rule as init() and the\n // graph entry: this used to check truthiness only, so an invalid non-`pk_`\n // (typo'd) key still fired /v1/section-map registration and dwell events\n // into a client that discards everything.\n if (!opts.apiKey || !opts.apiKey.startsWith('pk_')) return NOOP;\n // Normalize so both a ROOT base (`https://api.sentient-ui.com`) and a\n // `/v1`-suffixed base resolve to exactly one `/v1/section-map` — some callers\n // pass the versioned base, which would otherwise produce `/v1/v1/section-map`\n // (a silent 404). Strip trailing slashes, then a single trailing `/v1`.\n const apiBase = (opts.apiBase ?? 'https://api.sentient-ui.com')\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '');\n\n const els = selectSections(doc);\n if (els.length === 0) return NOOP;\n\n // One component per ELEMENT (nc-* retirement, 2026-09-05): the id carries a\n // short locator hash — `nc-<type>-<hash>` — so two same-typed bands no longer\n // collapse into one row with summed dwell, which is what made \"which features\n // band holds attention?\" unanswerable. The hash is over the locator's\n // identity fields (the same subset section_key hashes server-side), so the id\n // is stable across visits. An element with no resolvable locator falls back\n // to the collapsed `nc-<type>` — no identity means no better name exists.\n // The type-level matrix is unaffected (it aggregates via graph_nodes\n // semantic_type); pre-change dwell history stays keyed to collapsed ids and\n // ages out of the reporting windows.\n // Per-element precedence: explicit data-sentient-type markup → served\n // section map (opts.typeOf) → local heuristic.\n const componentOf = new Map<Element, string>();\n const entries: Array<{\n componentId: string;\n semanticType: SemanticType;\n source: 'markup' | 'auto';\n locator?: unknown;\n observation?: SectionObservation;\n }> = [];\n for (const el of els) {\n const explicit = el.getAttribute('data-sentient-type');\n const markup = explicit && (SEMANTIC_TYPES as readonly string[]).includes(explicit)\n ? (explicit as SemanticType)\n : null;\n const f = featuresFromElement(el);\n const type = markup ?? opts.typeOf?.(el) ?? classifyFeatures(f).type;\n const locator = locatorFromElement(el, doc) as\n | { id?: string; dataAttr?: unknown; selector?: string }\n | null;\n const componentId = locator\n ? `nc-${type}-${fnv1a(\n JSON.stringify({ id: locator.id ?? null, dataAttr: locator.dataAttr ?? null, selector: locator.selector ?? null }),\n ).toString(36)}`\n : `nc-${type}`;\n componentOf.set(el, componentId);\n // Client-sensor observation: which shipped CONTENT_PATTERNS matched the\n // body text (booleans — the text itself never leaves the page), plus the\n // structural features the server classifier keys on.\n const patternFlags = CONTENT_PATTERNS.filter(([, re]) => re.test(f.bodyText)).map(([t]) => t);\n entries.push({\n componentId,\n semanticType: type,\n // `source` is per ELEMENT: with one row per section the server records\n // each section's real provenance, not the most-confident of its siblings'.\n source: markup ? 'markup' : 'auto',\n ...(locator ? { locator } : {}),\n observation: {\n tag: f.tag,\n idClass: f.idClass.slice(0, 200),\n headingText: f.headingText,\n textLength: f.textLength,\n actionCount: f.actionCount,\n ...(f.ariaRole ? { ariaRole: f.ariaRole } : {}),\n ...(patternFlags.length > 0 ? { patternFlags } : {}),\n },\n });\n }\n\n const pageUrl = (doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined))?.location?.pathname ?? '/';\n registerSections(opts.apiKey, apiBase, pageUrl, entries);\n\n // Accumulate visible dwell (ms) + max scroll ratio per component. `intersecting`\n // tracks in-viewport state independently of `enterAt` (the running clock) so a\n // tab-hide can pause the clock and a tab-show can resume it for still-visible\n // sections — IntersectionObserver does not re-fire on visibilitychange.\n const state = new Map<string, { ms: number; scroll: number; enterAt: number | null; intersecting: boolean }>();\n const get = (id: string) => {\n let s = state.get(id);\n if (!s) { s = { ms: 0, scroll: 0, enterAt: null, intersecting: false }; state.set(id, s); }\n return s;\n };\n\n const observer = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n const id = componentOf.get(entry.target);\n if (!id) continue;\n const s = get(id);\n if (entry.isIntersecting) {\n s.intersecting = true;\n s.enterAt = Date.now();\n if (entry.intersectionRatio > s.scroll) s.scroll = entry.intersectionRatio;\n } else {\n s.intersecting = false;\n if (s.enterAt != null) { s.ms += Date.now() - s.enterAt; s.enterAt = null; }\n }\n }\n }, { threshold: [0, 0.25, 0.5, 0.75, 1] });\n for (const el of componentOf.keys()) observer.observe(el);\n\n // Bank accumulated dwell and RESET the accumulators (so a later emit can't\n // double-count) WITHOUT disconnecting — a visitor who hides/re-shows the tab\n // or tab-switches keeps being measured. Pauses the running clock; the tab-show\n // handler restarts it for still-visible sections so hidden time isn't counted.\n const emit = (): void => {\n const now = Date.now();\n for (const [id, s] of state) {\n if (s.enterAt != null) { s.ms += now - s.enterAt; s.enterAt = null; }\n if (s.ms <= 0) continue;\n try {\n client.track({\n projectId: opts.apiKey, // SDK convention: server derives the real project from the key\n componentId: id,\n eventType: 'dwell',\n payload: { dwell_time: Math.round(s.ms), scroll_depth: Number(s.scroll.toFixed(2)) },\n });\n } catch {\n /* fail-safe */\n }\n s.ms = 0;\n }\n };\n\n const onVisibility = (): void => {\n if (doc.hidden) {\n emit(); // bank + pause\n } else {\n const now = Date.now(); // resume the clock for sections still on screen\n for (const s of state.values()) if (s.intersecting) s.enterAt = now;\n }\n };\n // A page can be FROZEN into the bfcache rather than torn down. Timers keep\n // firing on restore, and `intersecting` still holds whatever it held at\n // pagehide — so without this the heartbeat kept banking dwell for sections the\n // visitor had scrolled far past, forever, while the observer that could have\n // corrected them had been disconnected. Freeze the clocks instead, and only\n // tear down for real when the page is genuinely going away.\n let frozen = false;\n const onPageHide = (event?: { persisted?: boolean }): void => {\n emit(); // bank whatever is measured either way\n if (event?.persisted) {\n frozen = true; // bfcache: keep the observer, stop counting\n return;\n }\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n const onPageShow = (event?: { persisted?: boolean }): void => {\n if (!event?.persisted || !frozen) return;\n frozen = false;\n // The observer stayed connected, so it will correct `intersecting` for\n // anything that moved. Restart clocks only for what is on screen NOW.\n const now = Date.now();\n for (const s of state.values()) s.enterAt = s.intersecting && !doc.hidden ? now : null;\n };\n doc.addEventListener('visibilitychange', onVisibility);\n const win = doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined);\n win?.addEventListener('pagehide', onPageHide);\n win?.addEventListener('pageshow', onPageShow);\n\n // See HEARTBEAT_MS: bank visible dwell periodically so a hard close (or a\n // mobile page kill) loses at most one interval instead of the whole visit.\n // Hidden tabs skip the emit — their clock is already paused, and an empty\n // state map makes emit a no-op anyway.\n const heartbeat = setInterval(() => {\n if (doc.hidden || frozen) return;\n emit();\n // emit() pauses every running clock and only the tab-show handler restarts\n // them — here the page never went hidden, so restart the clock ourselves\n // or accumulation silently stops after the first heartbeat.\n const now = Date.now();\n for (const s of state.values()) if (s.intersecting) s.enterAt = now;\n }, HEARTBEAT_MS);\n\n // Per-section micro-signal detectors (opt-in; see EngagementCaptureOptions).\n // Attributed to the section's per-element nc-* id with no variant — they feed the\n // persona attention fallback and auto-discovery, never rewards.\n const detectorCleanups: Array<() => void> = [];\n if (opts.microSignals) {\n // tab_loss is a single document-level `visibilitychange` signal, so enabling\n // it on every section detector would emit one tab_loss per section\n // on a single tab-hide — attributing one page-level exit to every section\n // (audit M5). Enable it on only the first section so the exit is recorded\n // once, mirroring the per-option path in slot-signals.ts ({ tabLoss: index === 0 }).\n [...componentOf.entries()].forEach(([el, componentId], i) => {\n detectorCleanups.push(\n attachMicroSignalDetectors((signalType, extra = {}) => {\n try {\n client.track({\n projectId: opts.apiKey,\n componentId,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n } catch {\n /* fail-safe */\n }\n }, el, undefined, { tabLoss: i === 0 }),\n );\n });\n }\n\n // Cleanup: bank any remaining dwell, then detach everything (provider unmount\n // / consent re-init must not leak observers or listeners).\n return () => {\n emit();\n clearInterval(heartbeat);\n doc.removeEventListener('visibilitychange', onVisibility);\n win?.removeEventListener('pagehide', onPageHide);\n win?.removeEventListener('pageshow', onPageShow);\n for (const c of detectorCleanups) c();\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n}\n"],"mappings":"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","names":["fnv1a","SECTION_SELECTOR","HEARTBEAT_MS","selectSections","doc","candidates","kept","el","k","registerSections","apiKey","apiBase","pageUrl","sections","e","NOOP","startEngagementCapture","client","opts","_a","_b","_c","_d","_e","_f","_g","_h","_i","_j","_k","_l","isDoNotTrackEnabled","els","componentOf","entries","explicit","markup","SEMANTIC_TYPES","f","featuresFromElement","type","classifyFeatures","locator","locatorFromElement","componentId","fnv1a","patternFlags","CONTENT_PATTERNS","re","t","__spreadProps","__spreadValues","state","get","id","s","observer","entry","emit","now","onVisibility","frozen","onPageHide","event","onPageShow","win","heartbeat","detectorCleanups","i","attachMicroSignalDetectors","signalType","extra","c"]}
|
|
1
|
+
{"version":3,"sources":["../src/engagement/capture.ts"],"sourcesContent":["import {\n classifyFeatures,\n featuresFromElement,\n CONTENT_PATTERNS,\n SEMANTIC_TYPES,\n type SemanticType,\n} from './classify';\nimport { fnv1a } from '@sentientui/policy';\nimport { isDoNotTrackEnabled } from '../index.js';\nimport { attachMicroSignalDetectors } from '../micro-signals.js';\nimport { locatorFromElement } from '../locator-from-dom.js';\n\n// Shared engagement capture (spec 2026-07-22-persona-signal-capture). Detects\n// semantic sections, registers them via /v1/section-map, and records per-section\n// dwell/scroll via IntersectionObserver — emitting the same 'dwell' events the\n// persona pipeline consumes. Used by the React provider (default on) and the\n// no-code snippet. Defense-in-depth: checks DNT internally even though callers\n// gate on consent/DNT too; a missing IntersectionObserver → no-op.\n\ntype CaptureClient = {\n track(event: { projectId: string; componentId: string; eventType: string; payload: Record<string, unknown> }): void;\n};\n\nexport type EngagementCaptureOptions = {\n apiKey: string;\n /** API base, no trailing slash. Defaults to the hosted API. */\n apiBase?: string;\n doc?: Document;\n /**\n * Also attach per-section micro-signal detectors (rage click, text copy,\n * scroll hesitation, tab loss), attributed to the section's per-element `nc-*`\n * component. For the no-code snippet, whose pages have no `<Adaptive>`\n * components carrying their own detectors. Default false — the React SDK\n * keeps its per-component detectors and must not double-attach.\n */\n microSignals?: boolean;\n /**\n * Section types declared in code, keyed by `data-sentient-id`. The highest\n * precedence — the same map the graph scanner receives, so capture and the\n * graph never disagree on what a declared section is.\n */\n sectionTypes?: Readonly<Partial<Record<string, string>>>;\n /**\n * Server-served section-map lookup (persona-coverage auto-classification):\n * consulted after declared types and legacy `data-sentient-type` markup,\n * before the local heuristic. Return null when the element has no served label.\n */\n typeOf?: (el: Element) => SemanticType | null;\n};\n\nconst SECTION_SELECTOR = 'section, header, footer, nav, main > div, [data-sentient-section]';\n\n/** Bank cadence for visible dwell. Dwell used to leave the page only on\n * visibilitychange/pagehide, and in production that path delivered for ~5-8%\n * of sessions (Bodyshop audit 2026-08-30): a visitor who reads and closes the\n * tab races the unload pipeline, and mobile browsers can kill a page with no\n * lifecycle event at all. The heartbeat caps the loss at one interval. */\nconst HEARTBEAT_MS = 20_000;\n\n/**\n * Pick the elements to observe. Two rules, in order:\n * 1. A candidate that CONTAINS two or more other candidates is a layout\n * wrapper, not a section — drop it. Pages built from bare divs match\n * `main > div` with their page-wide content wrapper; keeping that outer\n * match swallowed every real <section> inside it, collapsing the whole page\n * into one nc-generic component whose intersectionRatio could never exceed\n * viewport-height / page-height (a constant ~0.05 scroll_depth on the\n * audited site). A candidate with exactly one nested candidate (header >\n * nav) is NOT a wrapper — rule 2 keeps the outer one, as before.\n * 2. Of what remains, skip a section nested inside another kept section\n * (avoid double count).\n */\nfunction selectSections(doc: Document): Element[] {\n const candidates = Array.from(doc.querySelectorAll(SECTION_SELECTOR));\n const kept = candidates.filter(\n (el) => candidates.filter((c) => c !== el && el.contains(c)).length < 2,\n );\n return kept.filter((el) => !kept.some((k) => k !== el && k.contains(el)));\n}\n\n/** Client-sensor observation riding each section-map entry (spec 2026-09-04\n * §2): structure, headings, and which CONTENT_PATTERNS matched — never body\n * text, so nothing beyond headings leaves the page. Lets the server's richer\n * topic classifier label pages the crawler cannot fetch (CSR, auth-walled). */\ntype SectionObservation = {\n tag: string;\n idClass: string;\n headingText: string;\n textLength: number;\n actionCount: number;\n ariaRole?: string;\n patternFlags?: SemanticType[];\n};\n\nfunction registerSections(\n apiKey: string,\n apiBase: string,\n pageUrl: string,\n sections: Array<{\n componentId: string;\n semanticType: SemanticType;\n source: 'markup' | 'auto';\n locator?: unknown;\n observation?: SectionObservation;\n }>,\n): void {\n try {\n void fetch(`${apiBase}/v1/section-map`, {\n method: 'POST',\n keepalive: true,\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify({ pageUrl, sections }),\n }).catch(() => undefined);\n } catch {\n /* fail-safe */\n }\n}\n\nconst NOOP = (): void => undefined;\n\nexport function startEngagementCapture(\n client: CaptureClient,\n opts: EngagementCaptureOptions,\n): () => void {\n const doc = opts.doc ?? (typeof document !== 'undefined' ? document : undefined);\n if (!doc || typeof IntersectionObserver === 'undefined') return NOOP;\n if (isDoNotTrackEnabled()) return NOOP;\n // Keyless zero-network contract: capture exists to feed the hosted persona\n // pipeline — with no api key there is nothing to feed, and the section-map\n // registration fetch must never fire. Same validity rule as init() and the\n // graph entry: this used to check truthiness only, so an invalid non-`pk_`\n // (typo'd) key still fired /v1/section-map registration and dwell events\n // into a client that discards everything.\n if (!opts.apiKey || !opts.apiKey.startsWith('pk_')) return NOOP;\n // Normalize so both a ROOT base (`https://api.sentient-ui.com`) and a\n // `/v1`-suffixed base resolve to exactly one `/v1/section-map` — some callers\n // pass the versioned base, which would otherwise produce `/v1/v1/section-map`\n // (a silent 404). Strip trailing slashes, then a single trailing `/v1`.\n const apiBase = (opts.apiBase ?? 'https://api.sentient-ui.com')\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '');\n\n const els = selectSections(doc);\n if (els.length === 0) return NOOP;\n\n // One component per ELEMENT (nc-* retirement, 2026-09-05): the id carries a\n // short locator hash — `nc-<type>-<hash>` — so two same-typed bands no longer\n // collapse into one row with summed dwell, which is what made \"which features\n // band holds attention?\" unanswerable. The hash is over the locator's\n // identity fields (the same subset section_key hashes server-side), so the id\n // is stable across visits. An element with no resolvable locator falls back\n // to the collapsed `nc-<type>` — no identity means no better name exists.\n // The type-level matrix is unaffected (it aggregates via graph_nodes\n // semantic_type); pre-change dwell history stays keyed to collapsed ids and\n // ages out of the reporting windows.\n // Per-element precedence: declared sectionTypes (by data-sentient-id) →\n // legacy data-sentient-type markup → served section map (opts.typeOf) →\n // local heuristic. Declared and markup types both report source 'markup':\n // they are author-asserted, not inferred.\n const componentOf = new Map<Element, string>();\n const entries: Array<{\n componentId: string;\n semanticType: SemanticType;\n source: 'markup' | 'auto';\n locator?: unknown;\n observation?: SectionObservation;\n }> = [];\n for (const el of els) {\n const markup = [\n opts.sectionTypes?.[el.getAttribute('data-sentient-id') ?? ''],\n el.getAttribute('data-sentient-type'),\n ].find((t): t is SemanticType => (SEMANTIC_TYPES as readonly unknown[]).includes(t)) ?? null;\n const f = featuresFromElement(el);\n const type = markup ?? opts.typeOf?.(el) ?? classifyFeatures(f).type;\n const locator = locatorFromElement(el, doc) as\n | { id?: string; dataAttr?: unknown; selector?: string }\n | null;\n const componentId = locator\n ? `nc-${type}-${fnv1a(\n JSON.stringify({ id: locator.id ?? null, dataAttr: locator.dataAttr ?? null, selector: locator.selector ?? null }),\n ).toString(36)}`\n : `nc-${type}`;\n componentOf.set(el, componentId);\n // Client-sensor observation: which shipped CONTENT_PATTERNS matched the\n // body text (booleans — the text itself never leaves the page), plus the\n // structural features the server classifier keys on.\n const patternFlags = CONTENT_PATTERNS.filter(([, re]) => re.test(f.bodyText)).map(([t]) => t);\n entries.push({\n componentId,\n semanticType: type,\n // `source` is per ELEMENT: with one row per section the server records\n // each section's real provenance, not the most-confident of its siblings'.\n source: markup ? 'markup' : 'auto',\n ...(locator ? { locator } : {}),\n observation: {\n tag: f.tag,\n idClass: f.idClass.slice(0, 200),\n headingText: f.headingText,\n textLength: f.textLength,\n actionCount: f.actionCount,\n ...(f.ariaRole ? { ariaRole: f.ariaRole } : {}),\n ...(patternFlags.length > 0 ? { patternFlags } : {}),\n },\n });\n }\n\n const pageUrl = (doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined))?.location?.pathname ?? '/';\n registerSections(opts.apiKey, apiBase, pageUrl, entries);\n\n // Accumulate visible dwell (ms) + max scroll ratio per component. `intersecting`\n // tracks in-viewport state independently of `enterAt` (the running clock) so a\n // tab-hide can pause the clock and a tab-show can resume it for still-visible\n // sections — IntersectionObserver does not re-fire on visibilitychange.\n const state = new Map<string, { ms: number; scroll: number; enterAt: number | null; intersecting: boolean }>();\n const get = (id: string) => {\n let s = state.get(id);\n if (!s) { s = { ms: 0, scroll: 0, enterAt: null, intersecting: false }; state.set(id, s); }\n return s;\n };\n\n const observer = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n const id = componentOf.get(entry.target);\n if (!id) continue;\n const s = get(id);\n if (entry.isIntersecting) {\n s.intersecting = true;\n s.enterAt = Date.now();\n if (entry.intersectionRatio > s.scroll) s.scroll = entry.intersectionRatio;\n } else {\n s.intersecting = false;\n if (s.enterAt != null) { s.ms += Date.now() - s.enterAt; s.enterAt = null; }\n }\n }\n }, { threshold: [0, 0.25, 0.5, 0.75, 1] });\n for (const el of componentOf.keys()) observer.observe(el);\n\n // Bank accumulated dwell and RESET the accumulators (so a later emit can't\n // double-count) WITHOUT disconnecting — a visitor who hides/re-shows the tab\n // or tab-switches keeps being measured. Pauses the running clock; the tab-show\n // handler restarts it for still-visible sections so hidden time isn't counted.\n const emit = (): void => {\n const now = Date.now();\n for (const [id, s] of state) {\n if (s.enterAt != null) { s.ms += now - s.enterAt; s.enterAt = null; }\n if (s.ms <= 0) continue;\n try {\n client.track({\n projectId: opts.apiKey, // SDK convention: server derives the real project from the key\n componentId: id,\n eventType: 'dwell',\n payload: { dwell_time: Math.round(s.ms), scroll_depth: Number(s.scroll.toFixed(2)) },\n });\n } catch {\n /* fail-safe */\n }\n s.ms = 0;\n }\n };\n\n const onVisibility = (): void => {\n if (doc.hidden) {\n emit(); // bank + pause\n } else {\n const now = Date.now(); // resume the clock for sections still on screen\n for (const s of state.values()) if (s.intersecting) s.enterAt = now;\n }\n };\n // A page can be FROZEN into the bfcache rather than torn down. Timers keep\n // firing on restore, and `intersecting` still holds whatever it held at\n // pagehide — so without this the heartbeat kept banking dwell for sections the\n // visitor had scrolled far past, forever, while the observer that could have\n // corrected them had been disconnected. Freeze the clocks instead, and only\n // tear down for real when the page is genuinely going away.\n let frozen = false;\n const onPageHide = (event?: { persisted?: boolean }): void => {\n emit(); // bank whatever is measured either way\n if (event?.persisted) {\n frozen = true; // bfcache: keep the observer, stop counting\n return;\n }\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n const onPageShow = (event?: { persisted?: boolean }): void => {\n if (!event?.persisted || !frozen) return;\n frozen = false;\n // The observer stayed connected, so it will correct `intersecting` for\n // anything that moved. Restart clocks only for what is on screen NOW.\n const now = Date.now();\n for (const s of state.values()) s.enterAt = s.intersecting && !doc.hidden ? now : null;\n };\n doc.addEventListener('visibilitychange', onVisibility);\n const win = doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined);\n win?.addEventListener('pagehide', onPageHide);\n win?.addEventListener('pageshow', onPageShow);\n\n // See HEARTBEAT_MS: bank visible dwell periodically so a hard close (or a\n // mobile page kill) loses at most one interval instead of the whole visit.\n // Hidden tabs skip the emit — their clock is already paused, and an empty\n // state map makes emit a no-op anyway.\n const heartbeat = setInterval(() => {\n if (doc.hidden || frozen) return;\n emit();\n // emit() pauses every running clock and only the tab-show handler restarts\n // them — here the page never went hidden, so restart the clock ourselves\n // or accumulation silently stops after the first heartbeat.\n const now = Date.now();\n for (const s of state.values()) if (s.intersecting) s.enterAt = now;\n }, HEARTBEAT_MS);\n\n // Per-section micro-signal detectors (opt-in; see EngagementCaptureOptions).\n // Attributed to the section's per-element nc-* id with no variant — they feed the\n // persona attention fallback and auto-discovery, never rewards.\n const detectorCleanups: Array<() => void> = [];\n if (opts.microSignals) {\n // tab_loss is a single document-level `visibilitychange` signal, so enabling\n // it on every section detector would emit one tab_loss per section\n // on a single tab-hide — attributing one page-level exit to every section\n // (audit M5). Enable it on only the first section so the exit is recorded\n // once, mirroring the per-option path in slot-signals.ts ({ tabLoss: index === 0 }).\n [...componentOf.entries()].forEach(([el, componentId], i) => {\n detectorCleanups.push(\n attachMicroSignalDetectors((signalType, extra = {}) => {\n try {\n client.track({\n projectId: opts.apiKey,\n componentId,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n } catch {\n /* fail-safe */\n }\n }, el, undefined, { tabLoss: i === 0 }),\n );\n });\n }\n\n // Cleanup: bank any remaining dwell, then detach everything (provider unmount\n // / consent re-init must not leak observers or listeners).\n return () => {\n emit();\n clearInterval(heartbeat);\n doc.removeEventListener('visibilitychange', onVisibility);\n win?.removeEventListener('pagehide', onPageHide);\n win?.removeEventListener('pageshow', onPageShow);\n for (const c of detectorCleanups) c();\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n}\n"],"mappings":"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","names":["fnv1a","SECTION_SELECTOR","HEARTBEAT_MS","selectSections","doc","candidates","kept","el","k","registerSections","apiKey","apiBase","pageUrl","sections","e","NOOP","startEngagementCapture","client","opts","_a","_b","_c","_d","_e","_f","_g","_h","_i","_j","_k","_l","_m","_n","_o","isDoNotTrackEnabled","els","componentOf","entries","markup","t","SEMANTIC_TYPES","f","featuresFromElement","type","classifyFeatures","locator","locatorFromElement","componentId","fnv1a","patternFlags","CONTENT_PATTERNS","re","__spreadProps","__spreadValues","state","get","id","s","observer","entry","emit","now","onVisibility","frozen","onPageHide","event","onPageShow","win","heartbeat","detectorCleanups","i","attachMicroSignalDetectors","signalType","extra","c"]}
|
package/dist/index-graph.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { A as AssignResult, a as Assignment, b as AssignmentCache, E as EventQueue, e as EventType, g as GraphClient, h as GraphConfig, i as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, M as MicroSignalEmitter, k as MicroSignalType,
|
|
3
|
-
import { I as CompoundLocator } from './session-meta-
|
|
4
|
-
export { B as BLOCK_ALIGNS, b as BLOCK_EMPHASES, c as BLOCK_FITS, d as BLOCK_GAPS, e as BLOCK_GRID_COLUMNS, f as BLOCK_HEADING_LEVELS, g as BLOCK_JUSTIFIES, h as BLOCK_MAX_WIDTHS, i as BLOCK_PADS, j as BLOCK_RATIOS, k as BLOCK_SIZES, l as BLOCK_SURFACES, m as BLOCK_TEXT_ALIGNS, n as BLOCK_TONES, o as BLOCK_WEIGHTS, p as BadgeBlock, q as BlockAlign, r as BlockEmphasis, s as BlockFit, t as BlockGap, u as BlockJustify, v as BlockMaxWidth, w as BlockNode, x as BlockPad, y as BlockRatio, z as BlockSize, C as BlockSurface, D as BlockTextAlign, E as BlockTone, F as BlockWeight, G as ButtonBlock, J as DecisionSnapshot, K as DividerBlock, L as FORM_FIELD_KINDS, M as FORM_INPUT_TYPES, N as FormBlock, O as FormField, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LinkBlock, T as MAX_BLOCK_ARMS, U as MAX_BLOCK_CHILDREN, V as MAX_BLOCK_DEPTH, W as MAX_BLOCK_NODES, X as MAX_BLOCK_TEXT_LEN, Y as MAX_FORM_FIELDS, Z as MAX_FORM_SELECT_OPTIONS, _ as SNAPSHOT_STORAGE_KEY_PREFIX, a0 as SitePalette, a1 as SlotConfigEntry, a2 as SlotDeclInput, a3 as SlotOps, a4 as SpacerBlock, a5 as StackBlock, a6 as TextBlock, a9 as armOfResult, aa as baselineResultFor, ab as baselineSlots, ae as containsFormBlock, af as deriveSessionSegment, ag as detectDeviceClass, ah as detectTimeOfDay, ai as detectTrafficSource, al as readSnapshot, am as referrerDomainFromReferer, an as renderPrePaintScript, ao as toWireSlot, aq as writeSnapshot } from './session-meta-
|
|
1
|
+
import { p as SentientConfig, o as SentientClient } from './index-DErBinAw.cjs';
|
|
2
|
+
export { A as AssignResult, a as Assignment, b as AssignmentCache, E as EventQueue, e as EventType, g as GraphClient, h as GraphConfig, i as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, M as MicroSignalEmitter, k as MicroSignalType, m as PageNode, Q as QueueConfig, q as SentientEvent, r as SessionConfig, s as SessionManager, t as attachMicroSignalDetectors, u as grantConsent, w as isDoNotTrackEnabled, B as sanitizePageUrl, F as sessionCookieName } from './index-DErBinAw.cjs';
|
|
3
|
+
import { I as CompoundLocator } from './session-meta-DydKfQiR.cjs';
|
|
4
|
+
export { B as BLOCK_ALIGNS, b as BLOCK_EMPHASES, c as BLOCK_FITS, d as BLOCK_GAPS, e as BLOCK_GRID_COLUMNS, f as BLOCK_HEADING_LEVELS, g as BLOCK_JUSTIFIES, h as BLOCK_MAX_WIDTHS, i as BLOCK_PADS, j as BLOCK_RATIOS, k as BLOCK_SIZES, l as BLOCK_SURFACES, m as BLOCK_TEXT_ALIGNS, n as BLOCK_TONES, o as BLOCK_WEIGHTS, p as BadgeBlock, q as BlockAlign, r as BlockEmphasis, s as BlockFit, t as BlockGap, u as BlockJustify, v as BlockMaxWidth, w as BlockNode, x as BlockPad, y as BlockRatio, z as BlockSize, C as BlockSurface, D as BlockTextAlign, E as BlockTone, F as BlockWeight, G as ButtonBlock, J as DecisionSnapshot, K as DividerBlock, L as FORM_FIELD_KINDS, M as FORM_INPUT_TYPES, N as FormBlock, O as FormField, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LinkBlock, T as MAX_BLOCK_ARMS, U as MAX_BLOCK_CHILDREN, V as MAX_BLOCK_DEPTH, W as MAX_BLOCK_NODES, X as MAX_BLOCK_TEXT_LEN, Y as MAX_FORM_FIELDS, Z as MAX_FORM_SELECT_OPTIONS, _ as SNAPSHOT_STORAGE_KEY_PREFIX, a0 as SitePalette, a1 as SlotConfigEntry, a2 as SlotDeclInput, a3 as SlotOps, a4 as SpacerBlock, a5 as StackBlock, a6 as TextBlock, a9 as armOfResult, aa as baselineResultFor, ab as baselineSlots, ae as containsFormBlock, af as deriveSessionSegment, ag as detectDeviceClass, ah as detectTimeOfDay, ai as detectTrafficSource, al as readSnapshot, am as referrerDomainFromReferer, an as renderPrePaintScript, ao as toWireSlot, aq as writeSnapshot } from './session-meta-DydKfQiR.cjs';
|
|
5
5
|
export { SlotResult } from '@sentientui/policy';
|
|
6
6
|
|
|
7
7
|
/** Reads the rendered DOM to build the page-side context graph. */
|
|
@@ -44,6 +44,16 @@ type DOMScanner = {
|
|
|
44
44
|
getProminenceScore(element: Element): number;
|
|
45
45
|
destroy(): void;
|
|
46
46
|
};
|
|
47
|
+
type DOMScannerOptions = {
|
|
48
|
+
/**
|
|
49
|
+
* Section types declared in code, keyed by `data-sentient-id`. Replaces the
|
|
50
|
+
* per-element `data-sentient-type` attribute so a section needs one attribute
|
|
51
|
+
* of markup. The content classifier misses sections whose copy carries no
|
|
52
|
+
* strong signal (an "About us" band reads `generic`, not `trust`), and a
|
|
53
|
+
* wrong type here reorders that section for the wrong personas.
|
|
54
|
+
*/
|
|
55
|
+
sectionTypes?: Readonly<Partial<Record<string, string>>>;
|
|
56
|
+
};
|
|
47
57
|
|
|
48
58
|
/** Build a compound locator for a live DOM element. Returns null when nothing
|
|
49
59
|
* resolves uniquely — the runtime never guesses an identity. */
|
|
@@ -71,7 +81,13 @@ type GraphSentientConfig = SentientConfig & {
|
|
|
71
81
|
* (component ids, semantic types, prominence) still syncs when `graph: true`.
|
|
72
82
|
*/
|
|
73
83
|
captureDomText?: boolean;
|
|
84
|
+
/**
|
|
85
|
+
* Section types declared in code, keyed by `data-sentient-id`
|
|
86
|
+
* (e.g. `{ about: 'trust' }`). Wins over the content classifier and over
|
|
87
|
+
* legacy `data-sentient-type` markup. See `DOMScannerOptions.sectionTypes`.
|
|
88
|
+
*/
|
|
89
|
+
sectionTypes?: Readonly<Partial<Record<string, string>>>;
|
|
74
90
|
};
|
|
75
91
|
declare function init(config: GraphSentientConfig): SentientClient;
|
|
76
92
|
|
|
77
|
-
export { CompoundLocator, type ContentAddedEvent, type DOMScanner, type GraphSentientConfig, type ScanResult, type ScannedNode, SentientClient, SentientConfig, init, locatorFromElement };
|
|
93
|
+
export { CompoundLocator, type ContentAddedEvent, type DOMScanner, type DOMScannerOptions, type GraphSentientConfig, type ScanResult, type ScannedNode, SentientClient, SentientConfig, init, locatorFromElement };
|
package/dist/index-graph.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { A as AssignResult, a as Assignment, b as AssignmentCache, E as EventQueue, e as EventType, g as GraphClient, h as GraphConfig, i as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, M as MicroSignalEmitter, k as MicroSignalType,
|
|
3
|
-
import { I as CompoundLocator } from './session-meta-
|
|
4
|
-
export { B as BLOCK_ALIGNS, b as BLOCK_EMPHASES, c as BLOCK_FITS, d as BLOCK_GAPS, e as BLOCK_GRID_COLUMNS, f as BLOCK_HEADING_LEVELS, g as BLOCK_JUSTIFIES, h as BLOCK_MAX_WIDTHS, i as BLOCK_PADS, j as BLOCK_RATIOS, k as BLOCK_SIZES, l as BLOCK_SURFACES, m as BLOCK_TEXT_ALIGNS, n as BLOCK_TONES, o as BLOCK_WEIGHTS, p as BadgeBlock, q as BlockAlign, r as BlockEmphasis, s as BlockFit, t as BlockGap, u as BlockJustify, v as BlockMaxWidth, w as BlockNode, x as BlockPad, y as BlockRatio, z as BlockSize, C as BlockSurface, D as BlockTextAlign, E as BlockTone, F as BlockWeight, G as ButtonBlock, J as DecisionSnapshot, K as DividerBlock, L as FORM_FIELD_KINDS, M as FORM_INPUT_TYPES, N as FormBlock, O as FormField, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LinkBlock, T as MAX_BLOCK_ARMS, U as MAX_BLOCK_CHILDREN, V as MAX_BLOCK_DEPTH, W as MAX_BLOCK_NODES, X as MAX_BLOCK_TEXT_LEN, Y as MAX_FORM_FIELDS, Z as MAX_FORM_SELECT_OPTIONS, _ as SNAPSHOT_STORAGE_KEY_PREFIX, a0 as SitePalette, a1 as SlotConfigEntry, a2 as SlotDeclInput, a3 as SlotOps, a4 as SpacerBlock, a5 as StackBlock, a6 as TextBlock, a9 as armOfResult, aa as baselineResultFor, ab as baselineSlots, ae as containsFormBlock, af as deriveSessionSegment, ag as detectDeviceClass, ah as detectTimeOfDay, ai as detectTrafficSource, al as readSnapshot, am as referrerDomainFromReferer, an as renderPrePaintScript, ao as toWireSlot, aq as writeSnapshot } from './session-meta-
|
|
1
|
+
import { p as SentientConfig, o as SentientClient } from './index-DxWcBI5U.js';
|
|
2
|
+
export { A as AssignResult, a as Assignment, b as AssignmentCache, E as EventQueue, e as EventType, g as GraphClient, h as GraphConfig, i as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, M as MicroSignalEmitter, k as MicroSignalType, m as PageNode, Q as QueueConfig, q as SentientEvent, r as SessionConfig, s as SessionManager, t as attachMicroSignalDetectors, u as grantConsent, w as isDoNotTrackEnabled, B as sanitizePageUrl, F as sessionCookieName } from './index-DxWcBI5U.js';
|
|
3
|
+
import { I as CompoundLocator } from './session-meta-DydKfQiR.js';
|
|
4
|
+
export { B as BLOCK_ALIGNS, b as BLOCK_EMPHASES, c as BLOCK_FITS, d as BLOCK_GAPS, e as BLOCK_GRID_COLUMNS, f as BLOCK_HEADING_LEVELS, g as BLOCK_JUSTIFIES, h as BLOCK_MAX_WIDTHS, i as BLOCK_PADS, j as BLOCK_RATIOS, k as BLOCK_SIZES, l as BLOCK_SURFACES, m as BLOCK_TEXT_ALIGNS, n as BLOCK_TONES, o as BLOCK_WEIGHTS, p as BadgeBlock, q as BlockAlign, r as BlockEmphasis, s as BlockFit, t as BlockGap, u as BlockJustify, v as BlockMaxWidth, w as BlockNode, x as BlockPad, y as BlockRatio, z as BlockSize, C as BlockSurface, D as BlockTextAlign, E as BlockTone, F as BlockWeight, G as ButtonBlock, J as DecisionSnapshot, K as DividerBlock, L as FORM_FIELD_KINDS, M as FORM_INPUT_TYPES, N as FormBlock, O as FormField, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LinkBlock, T as MAX_BLOCK_ARMS, U as MAX_BLOCK_CHILDREN, V as MAX_BLOCK_DEPTH, W as MAX_BLOCK_NODES, X as MAX_BLOCK_TEXT_LEN, Y as MAX_FORM_FIELDS, Z as MAX_FORM_SELECT_OPTIONS, _ as SNAPSHOT_STORAGE_KEY_PREFIX, a0 as SitePalette, a1 as SlotConfigEntry, a2 as SlotDeclInput, a3 as SlotOps, a4 as SpacerBlock, a5 as StackBlock, a6 as TextBlock, a9 as armOfResult, aa as baselineResultFor, ab as baselineSlots, ae as containsFormBlock, af as deriveSessionSegment, ag as detectDeviceClass, ah as detectTimeOfDay, ai as detectTrafficSource, al as readSnapshot, am as referrerDomainFromReferer, an as renderPrePaintScript, ao as toWireSlot, aq as writeSnapshot } from './session-meta-DydKfQiR.js';
|
|
5
5
|
export { SlotResult } from '@sentientui/policy';
|
|
6
6
|
|
|
7
7
|
/** Reads the rendered DOM to build the page-side context graph. */
|
|
@@ -44,6 +44,16 @@ type DOMScanner = {
|
|
|
44
44
|
getProminenceScore(element: Element): number;
|
|
45
45
|
destroy(): void;
|
|
46
46
|
};
|
|
47
|
+
type DOMScannerOptions = {
|
|
48
|
+
/**
|
|
49
|
+
* Section types declared in code, keyed by `data-sentient-id`. Replaces the
|
|
50
|
+
* per-element `data-sentient-type` attribute so a section needs one attribute
|
|
51
|
+
* of markup. The content classifier misses sections whose copy carries no
|
|
52
|
+
* strong signal (an "About us" band reads `generic`, not `trust`), and a
|
|
53
|
+
* wrong type here reorders that section for the wrong personas.
|
|
54
|
+
*/
|
|
55
|
+
sectionTypes?: Readonly<Partial<Record<string, string>>>;
|
|
56
|
+
};
|
|
47
57
|
|
|
48
58
|
/** Build a compound locator for a live DOM element. Returns null when nothing
|
|
49
59
|
* resolves uniquely — the runtime never guesses an identity. */
|
|
@@ -71,7 +81,13 @@ type GraphSentientConfig = SentientConfig & {
|
|
|
71
81
|
* (component ids, semantic types, prominence) still syncs when `graph: true`.
|
|
72
82
|
*/
|
|
73
83
|
captureDomText?: boolean;
|
|
84
|
+
/**
|
|
85
|
+
* Section types declared in code, keyed by `data-sentient-id`
|
|
86
|
+
* (e.g. `{ about: 'trust' }`). Wins over the content classifier and over
|
|
87
|
+
* legacy `data-sentient-type` markup. See `DOMScannerOptions.sectionTypes`.
|
|
88
|
+
*/
|
|
89
|
+
sectionTypes?: Readonly<Partial<Record<string, string>>>;
|
|
74
90
|
};
|
|
75
91
|
declare function init(config: GraphSentientConfig): SentientClient;
|
|
76
92
|
|
|
77
|
-
export { CompoundLocator, type ContentAddedEvent, type DOMScanner, type GraphSentientConfig, type ScanResult, type ScannedNode, SentientClient, SentientConfig, init, locatorFromElement };
|
|
93
|
+
export { CompoundLocator, type ContentAddedEvent, type DOMScanner, type DOMScannerOptions, type GraphSentientConfig, type ScanResult, type ScannedNode, SentientClient, SentientConfig, init, locatorFromElement };
|
package/dist/index-graph.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Jt=Object.create;var be=Object.defineProperty,Qt=Object.defineProperties,Vt=Object.getOwnPropertyDescriptor,Yt=Object.getOwnPropertyDescriptors,Zt=Object.getOwnPropertyNames,dt=Object.getOwnPropertySymbols,en=Object.getPrototypeOf,pt=Object.prototype.hasOwnProperty,tn=Object.prototype.propertyIsEnumerable;var ut=(e,t,n)=>t in e?be(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,x=(e,t)=>{for(var n in t||(t={}))pt.call(t,n)&&ut(e,n,t[n]);if(dt)for(var n of dt(t))tn.call(t,n)&&ut(e,n,t[n]);return e},q=(e,t)=>Qt(e,Yt(t));var nn=(e,t)=>{for(var n in t)be(e,n,{get:t[n],enumerable:!0})},gt=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of Zt(t))!pt.call(e,d)&&d!==n&&be(e,d,{get:()=>t[d],enumerable:!(c=Vt(t,d))||c.enumerable});return e};var on=(e,t,n)=>(n=e!=null?Jt(en(e)):{},gt(t||!e||!e.__esModule?be(n,"default",{value:e,enumerable:!0}):n,e)),rn=e=>gt(be({},"__esModule",{value:!0}),e);var Bo={};nn(Bo,{BLOCK_ALIGNS:()=>Tn,BLOCK_EMPHASES:()=>Pn,BLOCK_FITS:()=>Dn,BLOCK_GAPS:()=>kn,BLOCK_GRID_COLUMNS:()=>Bn,BLOCK_HEADING_LEVELS:()=>Mn,BLOCK_JUSTIFIES:()=>_n,BLOCK_MAX_WIDTHS:()=>$n,BLOCK_PADS:()=>Gn,BLOCK_RATIOS:()=>Nn,BLOCK_SIZES:()=>An,BLOCK_SURFACES:()=>Kn,BLOCK_TEXT_ALIGNS:()=>Ln,BLOCK_TONES:()=>On,BLOCK_WEIGHTS:()=>Rn,FORM_FIELD_KINDS:()=>Un,FORM_INPUT_TYPES:()=>Fn,LEGACY_SESSION_COOKIE_NAME:()=>ve,MAX_BLOCK_ARMS:()=>Xn,MAX_BLOCK_CHILDREN:()=>qn,MAX_BLOCK_DEPTH:()=>Hn,MAX_BLOCK_NODES:()=>zn,MAX_BLOCK_TEXT_LEN:()=>Jn,MAX_FORM_FIELDS:()=>jn,MAX_FORM_SELECT_OPTIONS:()=>Wn,SNAPSHOT_STORAGE_KEY_PREFIX:()=>re,armOfResult:()=>Ne,attachMicroSignalDetectors:()=>At,baselineResultFor:()=>ge,baselineSlots:()=>Et,containsFormBlock:()=>_t,deriveSessionSegment:()=>We,detectDeviceClass:()=>ce,detectTimeOfDay:()=>ue,detectTrafficSource:()=>le,grantConsent:()=>Dt,init:()=>Xt,isDoNotTrackEnabled:()=>Ee,locatorFromElement:()=>Ke,readSnapshot:()=>fe,referrerDomainFromReferer:()=>de,renderPrePaintScript:()=>Ct,sanitizePageUrl:()=>Je,sessionCookieName:()=>ie,toWireSlot:()=>we,writeSnapshot:()=>me});module.exports=rn(Bo);function Te(){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 oe(e){return e?`_${e.slice(0,12)}`:""}var ve="_snt_uid";function ie(e){return`${ve}${oe(e)}`}var sn="_snt_uid",an=365,_e="_snt_uid";function cn(){return Te()}function ft(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function ln(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(c){}}function $e(e){try{return localStorage.getItem(e)}catch(t){return null}}function mt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function yt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function dn(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function un(e){try{sessionStorage.removeItem(e)}catch(t){}}function pn(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 gn(e){try{localStorage.removeItem(e)}catch(t){}}function fn(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var mn={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Ae(e){var y,S,I,C,$,F,R;if(typeof window=="undefined")return mn;let t=oe(e==null?void 0:e.apiKey),n=(y=e==null?void 0:e.cookieName)!=null?y:ie(e==null?void 0:e.apiKey),c=`${_e}${t}`,d=`${_e}_tomb${t}`,i=((S=e==null?void 0:e.cookieTTLDays)!=null?S:an)*24*60*60,l=P=>P&&P.length>0?P:null,u=()=>{var P,O;return t&&!(e!=null&&e.cookieName)&&$e(d)===null?(O=(P=l(ft(sn)))!=null?P:l($e(_e)))!=null?O:l(yt(_e)):null},s=(R=(F=($=(C=(I=l(ft(n)))!=null?I:l($e(c)))!=null?C:l(yt(c)))!=null?$:u())!=null?F:l(e==null?void 0:e.ssrSessionId))!=null?R:cn();ln(n,s,i);let o=mt(c,s),r=pn(n),f=o?!1:dn(c,s),p=!o&&!r&&!f;return{getSessionId:()=>s,isEphemeral:()=>p,destroy:()=>{s=null,fn(n),gn(c),un(c),t&&!(e!=null&&e.cookieName)&&mt(d,"1")}}}function Y(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function ae(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 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 Z(e,t,n){try{let c=(()=>{try{let a=localStorage.getItem(n);if(!a)return[];let i=JSON.parse(a);return Array.isArray(i)?i:[]}catch(a){return[]}})(),d=new Map;for(let a of c)d.set(a.id,a);for(let a of e)d.set(a.id,a);localStorage.setItem(n,JSON.stringify([...d.values()].slice(-t)))}catch(c){}}function Oe(e,t){try{let n=localStorage.getItem(t);if(!n)return;let c=JSON.parse(n);if(!Array.isArray(c))return;let d=new Set(e),a=c.filter(i=>!d.has(i.id));if(a.length===c.length)return;a.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(a))}catch(n){}}var yn=500,hn=56*1024;function Ue(e){return`_snt_retry_${e.slice(0,12)}`}var Sn={push:()=>{},flush:()=>{},destroy:()=>{}};function ht(e){var X,ee,ye;if(typeof window=="undefined")return Sn;let t=(X=e.flushIntervalMs)!=null?X:5e3,n=(ee=e.maxBatchSize)!=null?ee:20,c=(ye=e.maxRetrySize)!=null?ye:100,d=e.ingestUrl,a=e.apiKey,i=Ue(a),l=[],u=new Set,s=[],o=v=>{for(let E of v)r.delete(E),!u.has(E)&&(u.add(E),s.push(E));for(;s.length>yn;){let E=s.shift();E&&u.delete(E)}Oe(v,i)},r=new Set,f=()=>{for(;l.length>c;){let v=l.shift();v&&r.delete(v.id)}},p=v=>{u.has(v.id)||r.has(v.id)||(r.add(v.id),l.push(v),f())},y=v=>{for(let E of v)u.has(E.id)||(r.add(E.id),l.push(E));f()},S=Re(i,c);for(let v of S)p(v);let I=0,C=0,$=(v,E=!0)=>{if(v.length===0)return;let J=JSON.stringify(v),M=v.map(K=>K.id),z;try{z=fetch(d,{method:"POST",keepalive:!0,body:J,headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`}})}catch(K){Z(v,c,i),y(v),C++,I=Date.now()+Y(C);return}let Ie=K=>{if(ae(K)!=="retry"){if(!K.ok&&E){let te=v.filter(U=>U.eventType!=="pageview");if(te.length>0&&te.length<v.length){o(v.filter(U=>U.eventType==="pageview").map(U=>U.id)),$(te,!1);return}}o(M),C=0,I=0;return}Z(v,c,i),y(v),C++,I=Date.now()+Y(C)};z instanceof Promise?z.then(Ie).catch(()=>{Z(v,c,i),y(v),C++,I=Date.now()+Y(C)}):Ie(z)},F=typeof TextEncoder!="undefined"?new TextEncoder:null,R=v=>F?F.encode(v).length:v.length,P=v=>{let E=[],J=2;for(let M of v){let z=R(JSON.stringify(M))+1;if(E.length>0&&J+z>hn||E.length>=n)break;E.push(M),J+=z}return E},O=()=>{try{if(Date.now()<I)return;for(;l.length>0&&!(Date.now()<I);){let v=l.filter(J=>!u.has(J.id));if(l.length=0,v.length===0)break;let E=P(v);if(E.length===0)break;E.length<v.length&&l.push(...v.slice(E.length)),$(E)}}catch(v){}},h=!0,L=null;L=setInterval(()=>{h&&O()},t);let j=()=>{document.visibilityState==="hidden"&&O()},W=()=>{O()};return document.addEventListener("visibilitychange",j),window.addEventListener("pagehide",W),{push(v){p(v),l.length>=n&&O()},flush:O,destroy(){h=!1,L!==null&&(clearInterval(L),L=null),document.removeEventListener("visibilitychange",j),window.removeEventListener("pagehide",W),O()}}}var bn=200;function Fe(e){return`_snt_goal_retry_${e.slice(0,12)}`}var vn={send:()=>{},flush:()=>{},destroy:()=>{}};function St(e){var R,P,O;if(typeof window=="undefined")return vn;let t=(R=e.flushIntervalMs)!=null?R:5e3,n=(P=e.maxRetrySize)!=null?P:100,c=(O=e.maxPerFlush)!=null?O:5,d=Fe(e.apiKey),a=[],i=new Set,l=new Set,u=[],s=0,o=0,r=!1,f=h=>{for(i.delete(h.id),l.has(h.id)||(l.add(h.id),u.push(h.id));u.length>bn;){let L=u.shift();L&&l.delete(L)}Oe([h.id],d)},p=h=>{Z([h],n,d),!l.has(h.id)&&!i.has(h.id)&&(i.add(h.id),a.push(h)),Date.now()>=s&&(o++,s=Date.now()+Y(o))},y=h=>{let L;try{L=fetch(e.url,{method:"POST",keepalive:!0,body:h.body,headers:e.headers})}catch(W){p(h);return}let j=W=>{var ee;let X=ae(W);if(X==="retry"){p(h);return}X==="dropped"&&((ee=e.onDrop)==null||ee.call(e,h,W.status)),f(h),o=0,s=0};L instanceof Promise?L.then(j).catch(()=>p(h)):j(L)},S=()=>{try{if(r||Date.now()<s)return;let h=0;for(;a.length>0&&h<c&&!(Date.now()<s);){let L=a.shift();i.delete(L.id),!l.has(L.id)&&(h++,y(L))}}catch(h){}},I=Re(d,n);for(let h of I)i.has(h.id)||(i.add(h.id),a.push(h));I.length>0&&Z(I,n,d);let C=setInterval(S,t),$=()=>{document.visibilityState==="hidden"&&S()},F=()=>S();return document.addEventListener("visibilitychange",$),window.addEventListener("pagehide",F),{send(h){if(!r&&!(l.has(h.id)||i.has(h.id))){if(Date.now()<s){Z([h],n,d),i.add(h.id),a.push(h);return}y(h)}},flush:S,destroy(){clearInterval(C),document.removeEventListener("visibilitychange",$),window.removeEventListener("pagehide",F),S(),r=!0}}}var wn=1800*1e3;function Pe(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function bt(e=wn,t){let n=new Map,c=`_snt_asgn${oe(t)}_`,d=(s,o)=>`${c}${encodeURIComponent(s)}:${encodeURIComponent(o)}`,a=s=>{let o=s.slice(c.length),r=o.indexOf(":");if(r<0)return null;try{return{componentId:decodeURIComponent(o.slice(0,r)),segment:decodeURIComponent(o.slice(r+1))}}catch(f){return null}},i=()=>{try{let s=[];for(let o=0;o<localStorage.length;o++){let r=localStorage.key(o);r!=null&&r.startsWith(c)&&s.push(r)}return s}catch(s){return[]}},l=s=>s.assignedAt+(s.ttlMs&&s.ttlMs>0?s.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let s of i())try{let o=localStorage.getItem(s);if(!o)continue;let r=JSON.parse(o);if(l(r)){localStorage.removeItem(s);continue}let f=a(s);if(!f)continue;n.set(Pe(f.componentId,f.segment),r)}catch(o){}})(),{get(s,o){let r=n.get(Pe(s,o));return r?l(r)?(n.delete(Pe(s,o)),null):r:null},set(s,o,r){let f=Pe(s,o);n.set(f,r);try{localStorage.setItem(d(s,o),JSON.stringify(r))}catch(p){}},clear(){n.clear();for(let s of i())try{localStorage.removeItem(s)}catch(o){}}}}var vt=["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 Le(e){return wt(e)!==null}function wt(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=vt.find(c=>t.includes(c.toLowerCase())))!=null?n:null}function ce(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 le(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(d){}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 de(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var xt=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function je(e){let t={},n={};try{let c=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([d,a])=>{let i=Array.isArray(a)?a[0]:a;return i===void 0?[]:[[d,i]]});for(let[d,a]of c)d.startsWith("utm_")?d in t||(t[d]=a):xt.includes(d)&&(d in n||(n[d]=a))}catch(c){}return{utmParams:t,clickIds:n}}function ue(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function We(e){let t=xn("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function xn(e,t){var a,i,l,u,s,o,r,f;let n=(i=(a=t==null?void 0:t.userAgent)==null?void 0:a.trim())!=null?i:"",c=(u=(l=t==null?void 0:t.referer)==null?void 0:l.trim())!=null?u:"",d=(s=t==null?void 0:t.now)!=null?s:new Date;return{sessionId:e,ephemeral:!1,utmParams:(o=t==null?void 0:t.utmParams)!=null?o:{},clickIds:(r=t==null?void 0:t.clickIds)!=null?r:{},deviceClass:n?ce(n):"desktop",trafficSource:c?le(c,t==null?void 0:t.appOrigin):"direct",referrerDomain:de(c),timeOfDay:ue(d),dayOfWeek:(f=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?f:"sun",automation:(t==null?void 0:t.webdriver)===!0||Le(n)}}var pe=require("@sentientui/policy");function we(e){return x(x(x({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 ge(e){let t=we(e);return(0,pe.slotResultFor)(t,(0,pe.slotBaselineArm)(t))}function Et(e){let t={};for(let n of e)t[n.id]=ge(n);return t}function Ne(e){return typeof e=="string"?e:(0,pe.canonicalArm)(e)}var re="_snt_snap:",En=["low","medium","high"];function fe(e){try{let t=localStorage.getItem(re+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"||!En.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 me(e,t){try{localStorage.setItem(re+e,JSON.stringify(t))}catch(n){}}function Ct(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(re+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 He=require("@sentientui/policy");var Be=require("@sentientui/policy");var It="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Cn="[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.",kt=!1,De=!1;function In(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Tt(e){var s;let t=Ae({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(s=t.getSessionId())!=null?s:"local",c=In(),d=import("@sentientui/core/local").then(o=>{let r=o;return r.LOCAL_ENGINE_AVAILABLE?(kt||(kt=!0,console.info(Cn)),r):(De||(De=!0,console.error(It)),null)}).catch(()=>(De||(De=!0,console.error(It)),null)),a=null,i={low:.15,medium:.5,high:.85},l=(()=>{var r;if(e.initialPersona)return x({},e.initialPersona);let o=fe(e.apiKey||"local");return o?{persona:o.persona,confidence:(r=i[o.band])!=null?r:.15}:null})();function u(o){let r=document.documentElement;r.dataset.sentientPersona===void 0&&(r.dataset.sentientPersona=o.persona,r.dataset.sentientConfidence=(0,Be.confidenceBand)(o.confidence))}return{isLocal:!0,async decide(o){var p,y,S;let r=await d;if(!r)return null;let f=r.createLocalEngine({sessionId:n,forcedPersona:c}).decide(o);return a=q(x({},f),{layoutOrder:(y=(p=f.layoutOrder)!=null?p:a==null?void 0:a.layoutOrder)!=null?y:null,slots:x(x({},(S=a==null?void 0:a.slots)!=null?S:{}),f.slots)}),me(e.apiKey||"local",{v:1,persona:a.persona,band:(0,Be.confidenceBand)(a.confidence),slots:a.slots,layoutOrder:a.layoutOrder,savedAt:Date.now()}),u(f),f},getSlotResult(o){var r,f,p;return(p=(f=a==null?void 0:a.slots[o])!=null?f:(r=e.initialSlots)==null?void 0:r[o])!=null?p:null},getSlotConfig(o){var r,f;return(f=(r=e.initialSlotConfig)==null?void 0:r[o])!=null?f:null},getSitePalette(){var o;return(o=e.initialPalette)!=null?o:null},reportSlots(){},getPersona(){let o=a!=null?a:l;return o?{persona:o.persona,confidence:o.confidence,band:(0,Be.confidenceBand)(o.confidence)}:null},async assign(o,r){var y;let f=await d;return!f||!r||r.length===0?r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null:{variantId:(y=f.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()}}var kn=["none","sm","md","lg"],Tn=["start","center","end","stretch"],_n=["start","center","end","between"],An=["sm","md","lg"],Rn=["normal","medium","bold"],On=["default","muted","accent"],Pn=["primary","secondary","ghost"],Ln=["left","center","right"],Nn=["auto","square","landscape","wide"],Dn=["cover","contain"],Bn=[2,3,4],Mn=[2,3,4],Kn=["default","raised"],Gn=["none","sm","md","lg"],$n=["measure"],Un=["input","textarea","select"],Fn=["text","email","number","tel"],jn=5,Wn=8,zn=64,Hn=5,qn=12,Xn=4,Jn=500;function _t(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(_t):!1}function At(e,t,n,c){let d=[];{let l=!1,u=[],s=()=>{if(l)return;let o=Date.now();for(u.push(o);u.length>0&&o-u[0]>500;)u.shift();u.length>=3&&(l=!0,e("rage_click"))};t.addEventListener("click",s),d.push(()=>t.removeEventListener("click",s))}{let a=!1,i=l=>{if(a||!(l.target instanceof Node)||!t.contains(l.target)&&t!==l.target)return;a=!0;let u=typeof window!="undefined"?window.getSelection():null,s=u?u.toString().length:0;e("text_copy",{selectionLength:s})};document.addEventListener("copy",i),d.push(()=>document.removeEventListener("copy",i))}{let a=!1,i=!1,l=null,u=()=>{l!==null&&(clearTimeout(l),l=null)},s=()=>{a||!i||(u(),l=setTimeout(()=>{!a&&i&&(a=!0,e("scroll_hesitation"))},3e3))},o=()=>{u(),s()},r=p=>{for(let y of p)i=y.intersectionRatio>.3,i?s():u()},f=new IntersectionObserver(r,{threshold:[.3]});f.observe(t),window.addEventListener("scroll",o,{passive:!0}),d.push(()=>{f.disconnect(),window.removeEventListener("scroll",o),u()})}if((c==null?void 0:c.tabLoss)!==!1){let a=!1,i=n!=null?n:Date.now(),l=()=>{if(a||document.visibilityState!=="hidden")return;let u=Date.now()-i;u<15e3&&(a=!0,e("tab_loss",{timeOnPage:u}))};document.addEventListener("visibilitychange",l),d.push(()=>document.removeEventListener("visibilitychange",l))}return()=>{for(let a of d)a()}}function Qn(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Rt="https://api.sentient-ui.com/v1/events",G=new Map,Ot=null;function Pt(e,t){let n=G.get(e);n&&n.upgrade&&(n.reinit=t)}function Vn(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var Yn=3;function ze(){return Te()}function Me(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function Zn(){let e=new WeakMap,t=new Map,n=!1,c=(l,u,s)=>{let o=l.get(u);return s===null?o?!0:(l.set(u,new Set),!1):o?o.has(s)?!0:(o.add(s),!1):(l.set(u,new Set([s])),!1)},d=typeof window!="undefined"&&"event"in window,a=()=>{if(!d)return;let l=window.event;return typeof Event=="function"&&l instanceof Event?l:void 0},i=()=>{if(d){Promise.resolve().then(()=>{n=!1,t.clear()});return}let l=!1,u=()=>{l||(l=!0,n=!1,t.clear())};if(setTimeout(u,0),typeof MessageChannel=="function"){let s=new MessageChannel;s.port1.onmessage=()=>{s.port1.close(),s.port2.close(),u()},s.port2.postMessage(0)}};return{firedBefore(l,u){let s=a();if(s){let r=e.get(s);return r||(r=new Map,e.set(s,r)),c(r,l,u)}let o=c(t,l,u);return!o&&!n&&(n=!0,i()),o}}}var Lt=new Set;function eo(e,t,n){let c=typeof window=="undefined"?null:window.history;if(!c)return()=>{};let d=!1,a,i=()=>{if(d)return;let s=Me();!s||s===a||(a=s,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${s}`))},l=[];for(let s of["pushState","replaceState"]){let o=c[s],r=function(...f){let p=o.apply(this,f);return i(),p};c[s]=r,l.push([s,o,r])}window.addEventListener("popstate",i);let u=Me();return u&&Lt.has(`${t}:${u}`)?a=u:i(),()=>{if(!d){d=!0,window.removeEventListener("popstate",i);for(let[s,o,r]of l)c[s]===r&&(c[s]=o)}}}var xe={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}),dispose:()=>{},destroy:()=>{}};function to(){try{return je(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function Nt(e){return e.replace(/\/events\/?$/,"")}function Ee(){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 Dt(e){var u;if(typeof window=="undefined")return;let t=e!=null?e:Ot;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=G.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:c,upgrade:d,reinit:a}=n;if(!d){n.upgradeBlockedReason&&console.warn(n.upgradeBlockedReason);return}if(c.respectDoNotTrack!==!1&&Ee())return;let i=(a!=null?a:Xe)(q(x({},c),{consent:!0}));d(i);let l=(u=G.get(t))==null?void 0:u.dispose;G.set(t,{config:q(x({},c),{consent:!0}),upgrade:null,dispose:l})}function no(e){var s;let t=e.preConsentBehavior==="statistical_winner",n=Nt((s=e.ingestUrl)!=null?s:Rt),c={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d=new Map,a=new Map,i={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(o,r,f){if(!t)return Promise.resolve(null);let p=d.get(o);return p?Promise.resolve(p):qe(a,o,async()=>{try{let y=new URLSearchParams({componentId:o});for(let $ of r!=null?r:[])y.append("variantIds[]",$);let S=await fetch(`${n}/winner?${y.toString()}`,{headers:c});if(!S.ok)return r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null;let C={variantId:(await S.json()).variantId,assignmentTtlMs:0};return d.set(o,C),C}catch(y){return r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},l={track:o=>i.track(o),goal:((o,r,f,p)=>i.goal(o,r,f,p)),componentGoal:(o,r,f)=>i.componentGoal(o,r,f),identify:o=>i.identify(o),getAssignment:(o,r)=>i.getAssignment(o,r),assign:(o,r,f,p)=>i.assign(o,r,f,p),decide:o=>i.decide(o),getSlotResult:o=>i.getSlotResult(o),getSlotConfig:o=>i.getSlotConfig(o),getSitePalette:()=>i.getSitePalette(),reportSlots:(o,r)=>i.reportSlots(o,r),getPersona:()=>i.getPersona(),fetchWeights:()=>i.fetchWeights(),getGraph:()=>i.getGraph(),dispose:()=>i.dispose(),destroy:()=>i.destroy()};function u(o){i=o}return{proxy:l,setInner:u}}function qe(e,t,n){let c=e.get(t);if(c)return c;let d=(async()=>{try{return await n()}finally{e.delete(t)}})();return e.set(t,d),d}function Xe(e){var Ye,Ze,et,tt,nt,ot,rt,st,it,at;if(typeof window=="undefined")return xe;Ot=e.apiKey||"local";let t=G.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(g){}let n=e.respectDoNotTrack!==!1&&Ee(),c=e.consent===!1||n,d=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!d&&e.localMode!==!1)return G.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."}),c?xe:Tt(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."),G.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."}),xe;let{proxy:g,setInner:m}=no(e);return G.set(e.apiKey,{config:e,upgrade:n?null:m}),g}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),xe;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),xe;let a=(Ye=e.ingestUrl)!=null?Ye:Rt,i=Date.now(),l=Ae({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),u=bt(void 0,e.apiKey),s=ht({ingestUrl:a,apiKey:e.apiKey}),o=Nt(a),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},f=new Set,p=St({url:`${o}/goals`,apiKey:e.apiKey,headers:r,onDrop:(g,m)=>{if(!e.debug){if(f.has(m))return;f.add(m)}console.warn(`[sentient] goal dropped (HTTP ${m}) \u2014 this will not be retried. `+(m===400?"The session was not found: call init() and let the session upsert complete before firing goals.":m===401||m===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),g)}}),y=ce((Ze=navigator.userAgent)!=null?Ze:""),S=window.location.origin,I=le((et=document.referrer)!=null?et:"",S),C=(tt=e.sessionSegment)!=null?tt:`${y}:${I}`,$=new Map,F=new Map,R=new Map,P=new Map,O=null,h=null,L=new Set,j=new Set,W=new Map,X=null,ee=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,ye=new Set,v=g=>{for(let m of g)R.has(m.id)||R.set(m.id,ge(m))};if(e.initialSlots)for(let[g,m]of Object.entries(e.initialSlots))R.set(g,m);if(e.initialSlotConfig)for(let[g,m]of Object.entries(e.initialSlotConfig))P.set(g,m);e.initialPalette&&(O=e.initialPalette);let E=fe(e.apiKey);if(E){for(let[g,m]of Object.entries(E.slots))R.has(g)||R.set(g,m);for(let[g,m]of Object.entries((nt=E.slotConfig)!=null?nt:{}))P.has(g)||P.set(g,m);!O&&E.palette&&(O=E.palette)}let J={low:.15,medium:.5,high:.85};if(e.initialPersona)h=x({},e.initialPersona);else{let g=document.documentElement.dataset;g.sentientPersona?h={persona:g.sentientPersona,confidence:(rt=J[(ot=g.sentientConfidence)!=null?ot:"low"])!=null?rt:.15}:E&&(h={persona:E.persona,confidence:(st=J[E.band])!=null?st:.15})}if(e.initialAssignments)for(let[g,m]of Object.entries(e.initialAssignments))u.set(g,C,{variantId:m,assignedAt:Date.now(),segment:C,confidence:1});let M=Promise.resolve(),z=l.getSessionId();if(z){let g=de((it=document.referrer)!=null?it:""),{utmParams:m,clickIds:b}=to(),k=x(x(x(x({sessionId:z,deviceClass:y,trafficSource:I,referrerDomain:g,utmParams:m,clickIds:b,timeOfDay:ue(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:l.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Le((at=navigator.userAgent)!=null?at:"")},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}:{}),A=async()=>{for(let w=0;;w++){try{let _=await fetch(`${o}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(k),headers:r});if(_.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(_.ok||ae(_)==="dropped")return}catch(_){}if(w>=Yn){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(_=>setTimeout(_,Y(w+1)))}};try{M=A()}catch(w){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:s});let Ie=Zn(),K=null,te=!1,U={goal(g,m={},b=1,k=0){var he,Se,se,T,Q,ke,N;let A=l.getSessionId();if(!A)return;let w=Vn(m)?m:{metadata:m},_=[g,(he=w.externalId)!=null?he:"",(Se=w.stepIndex)!=null?Se:k,(se=w.weight)!=null?se:b].join("\0"),D=w.value!==void 0?`${w.value}\0${(T=w.currency)!=null?T:""}`:null;if(Ie.firedBefore(_,D)){e.debug&&console.log(`[sentient] goal("${g}") already recorded for this action \u2014 not sent twice`);return}let B=ze(),V={sessionId:A,name:g,metadata:(Q=w.metadata)!=null?Q:{},weight:(ke=w.weight)!=null?ke:b,stepIndex:(N=w.stepIndex)!=null?N:k,goalId:B,value:w.value,currency:w.currency,externalId:w.externalId};e.debug&&console.log("[sentient] goal",V);let ne={id:B,body:JSON.stringify(V)};M.then(()=>p.send(ne))},componentGoal(g,m,b){var B,V,ne;let k=l.getSessionId();if(!k)return;let A=u.get(g,C),w=A?null:(B=R.get(g))!=null?B:null;if(!A&&w===null){e.debug&&console.warn(`[sentient] componentGoal("${g}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let _=A?A.variantId:Ne(w),D={id:ze(),sessionId:k,projectId:e.apiKey,componentId:g,variantId:_,eventType:"goal_achieved",goalType:m,payload:x({reward:(V=b==null?void 0:b.reward)!=null?V:1,goalValue:b==null?void 0:b.value,currency:b==null?void 0:b.currency},(ne=b==null?void 0:b.metadata)!=null?ne:{}),timestamp:Date.now(),timeInSession:Date.now()-i,path:Me()};e.debug&&console.log("[sentient] componentGoal",D),M.then(()=>s.push(D))},identify(g){let m=l.getSessionId();m&&M.then(()=>{fetch(`${o}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:m,userId:g,ephemeral:l.isEphemeral()}),headers:r}).catch(()=>{})})},track(g){let m=l.getSessionId();if(!m)return;let b=q(x({path:Me()},g),{id:ze(),sessionId:m,timestamp:Date.now(),timeInSession:Date.now()-i});e.debug&&console.log("[sentient] track",b),M.then(()=>s.push(b))},getAssignment(g,m){return u.get(g,m)},async assign(g,m,b,k){let A=l.getSessionId();if(!A)return null;let w=u.get(g,C);if(w&&(m!=null&&m.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}}return qe($,g,async()=>{await M;try{let _={sessionId:A,componentId:g,variantIds:m};k!==void 0?_.agentDataByVariant=k:b!==void 0&&(_.agentData=b);let D=await fetch(`${o}/assign`,{method:"POST",body:JSON.stringify(_),headers:r});if(!D.ok)return null;let B=await D.json();return u.set(g,C,x({variantId:B.variantId,assignedAt:Date.now(),segment:C,confidence:1,content:B.content},B.assignmentTtlMs&&B.assignmentTtlMs>0?{ttlMs:B.assignmentTtlMs}:{})),B}catch(_){return null}})},async decide(g){var w,_;let m=l.getSessionId();if(!m)return null;let b=(w=g.slots)!=null?w:[],k={sessionId:m};g.sections&&g.sections.length>0&&(k.sections=g.sections.map(D=>({id:D}))),k.components=(_=g.components)!=null?_:[],b.length>0&&(k.slots=b.map(we)),g.slotsFrom==="registry"&&(k.slotsFrom="registry"),g.v&&(k.v=g.v),typeof g.pp=="number"&&(k.pp=g.pp),e.persona&&(k.persona=e.persona);let A=JSON.stringify(k);return qe(F,A,async()=>{var D,B,V,ne,he,Se;await M;try{let se=await fetch(`${o}/decide`,{method:"POST",body:A,headers:r});if(!se.ok)return v(b),null;let T=await se.json(),Q={};for(let N of b){let H=(D=T.slots)==null?void 0:D[N.id];if(H!==void 0){Q[N.id]=H,R.set(N.id,H);continue}let ct=R.get(N.id);if(ct!==void 0)Q[N.id]=ct;else{let lt=ge(N);Q[N.id]=lt,R.set(N.id,lt)}}if(T.slots)for(let[N,H]of Object.entries(T.slots))N in Q||(Q[N]=H,R.set(N,H));let ke=h!=null&&h.persona!=="unknown";T.persona&&!(T.persona==="unknown"&&ke)?h={persona:T.persona,confidence:(B=T.confidence)!=null?B:0}:h||(h={persona:"unknown",confidence:0});for(let[N,H]of Object.entries((V=T.assignments)!=null?V:{}))u.set(N,C,{variantId:H,assignedAt:Date.now(),segment:C,confidence:1});if(T.slotConfig)for(let[N,H]of Object.entries(T.slotConfig))P.set(N,H);return T.palette&&(O=T.palette),me(e.apiKey,x(x({v:1,persona:h.persona,band:(0,He.confidenceBand)(h.confidence),slots:Object.fromEntries(R),layoutOrder:(ne=T.layoutOrder)!=null?ne:null,savedAt:Date.now()},P.size>0?{slotConfig:Object.fromEntries(P)}:{}),O?{palette:O}:{})),x(x(x(x({layoutOrder:(he=T.layoutOrder)!=null?he:null,assignments:(Se=T.assignments)!=null?Se:{},slots:Q,persona:h.persona,confidence:h.confidence},T.slotConfig?{slotConfig:T.slotConfig}:{}),T.goals?{goals:T.goals}:{}),T.sectionMap?{sectionMap:T.sectionMap}:{}),T.palette?{palette:T.palette}:{})}catch(se){return v(b),null}})},getSlotResult(g){var m;return(m=R.get(g))!=null?m:null},getSlotConfig(g){var m;return(m=P.get(g))!=null?m:null},reportSlots(g,m){for(let b of g)if(!(typeof b!="string"||b.length===0)){if(!ee.test(b)){Qn()&&!ye.has(b)&&(ye.add(b),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(b)} 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(!L.has(b)){L.add(b),j.add(b);let k=m==null?void 0:m[b];if(typeof k=="string"){let A=k.replace(/\s+/g," ").trim().slice(0,400);A!==""&&W.set(b,A)}}}j.size===0||X!=null||(X=setTimeout(()=>{X=null;let b=[...j];j.clear();for(let k=0;k<b.length;k+=20){let A=b.slice(k,k+20),w={};for(let _ of A){let D=W.get(_);D!==void 0&&(w[_]=D,W.delete(_))}fetch(`${o}/slots/observed`,{method:"POST",headers:r,body:JSON.stringify(x({slotIds:A},Object.keys(w).length>0?{baselineTexts:w}:{}))}).catch(()=>{})}},1e3))},getSitePalette(){return O},getPersona(){return h?{persona:h.persona,confidence:h.confidence,band:(0,He.confidenceBand)(h.confidence)}:null},async fetchWeights(){var g;try{let m=await fetch(`${o}/weights`,{headers:r});return m.ok?(g=(await m.json()).components)!=null?g:[]:[]}catch(m){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var g;K==null||K(),te=!0,s.destroy(),p.destroy(),((g=G.get(e.apiKey))==null?void 0:g.dispose)===U.dispose&&G.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var g;K==null||K(),te=!0,s.destroy(),p.destroy(),l.destroy(),u.clear(),((g=G.get(e.apiKey))==null?void 0:g.dispose)===U.dispose&&G.delete(e.apiKey);try{localStorage.removeItem(re+e.apiKey),localStorage.removeItem(Ue(e.apiKey)),localStorage.removeItem(Fe(e.apiKey))}catch(m){}e.debug&&console.log("[sentient] destroyed")}};if(G.set(e.apiKey,{config:e,upgrade:null,dispose:U.dispose}),K=eo(U,e.apiKey,g=>{M.then(()=>{te||Lt.add(g)})}),e.debug){let g=window;g.__sentient&&(g.__sentient.client=U)}return U}var Bt="_snt_graph_edges",oo={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function ro(e){var t;return(t=oo[e])!=null?t:[]}function so(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function io(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var ao=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function co(e){return ao.has(e)?e:"generic"}function Je(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function lo(e,t,n){let c=`${e}:${t}:${n.join(",")}`,d=5381;for(let a=0;a<c.length;a++)d=(d<<5)+d+c.charCodeAt(a)&4294967295;return(d>>>0).toString(16).padStart(8,"0")}function Mt(e){let t=new Map,n=new Map,c=`_snt_graph_nodes${oe(e==null?void 0:e.apiKey)}`,d=()=>{typeof window!="undefined"&&io(c,[...t.values()])};if(typeof window!="undefined"){let a=so(c,[]);for(let i of a)t.set(i.componentId,i);try{localStorage.removeItem(Bt)}catch(i){}}return{addPageNode(a){t.set(a.componentId,a),d()},addStructuralEdge(a){let i=`${a.fromComponentId}->${a.toComponentId}`;n.set(i,a)},syncOnce(){var i,l;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let a=[...t.values()];if(a.length!==0)try{let u=new Map;for(let p of a){let y=(i=u.get(p.semanticType))!=null?i:[];y.push(p),u.set(p.semanticType,y)}let s=[],o=new Set;for(let p of a)for(let y of ro(p.semanticType)){let S=(l=u.get(y))!=null?l:[];for(let I of S){if(I.componentId===p.componentId)continue;let C=`semantic:${p.componentId}->${I.componentId}`;o.has(C)||(o.add(C),s.push({fromComponentId:p.componentId,toComponentId:I.componentId,type:"semantic",weight:.4,confidence:.9}))}}let r=new Set(a.map(p=>p.componentId));for(let p of n.values()){if(!r.has(p.fromComponentId)||!r.has(p.toComponentId))continue;let y=`structural:${p.fromComponentId}->${p.toComponentId}`;o.has(y)||(o.add(y),s.push({fromComponentId:p.fromComponentId,toComponentId:p.toComponentId,type:"structural",weight:p.weight,confidence:1}))}let f=q(x(x({pageUrl:Je(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:a.map(p=>{let y=co(p.semanticType);return{componentId:p.componentId,semanticType:y,answers:p.answers,contentHash:lo(p.componentId,y,p.answers),prominenceScore:p.prominenceScore,depthInPage:p.depth}}),edges:s});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:x({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(f)}).catch(()=>{})}catch(u){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(c),localStorage.removeItem(Bt)}catch(a){}}}}var uo=["data-sentient-id","data-testid","data-test","data-id","data-name","data-cy"];function Qe(e){var t;return((t=e.textContent)!=null?t:"").replace(/\s+/g," ").trim()}function po(e){return{tag:e.tagName.toLowerCase(),text:Qe(e).slice(0,40)}}function Kt(e){return e.replace(/["\\\]]/g,"\\$&")}function Ce(e,t){try{return e.querySelectorAll(t).length===1}catch(n){return!1}}function Gt(e,t){var i;let n=e.tagName.toLowerCase();if(!n)return null;let c=((i=e.getAttribute("class"))!=null?i:"").split(/\s+/).filter(l=>/^[a-zA-Z][\w-]*$/.test(l)),d=[n,...c.map(l=>`${n}.${l}`)];for(let l of d)if(Ce(t,l))return l;let a=e.parentElement;if(a&&a!==t){let l=Gt(a,t);if(l){for(let r of d){let f=`${l} > ${r}`;if(Ce(t,f))return f}let u=Array.from(a.children).filter(r=>r.tagName.toLowerCase()===n),s=u.indexOf(e),o=u.some(r=>r!==e&&Qe(r)!==Qe(e));if(s>=0&&o){let r=`${l} > ${n}:nth-of-type(${s+1})`;if(Ce(t,r))return r}}}return null}function Ke(e,t){let n=po(e),c=e.getAttribute("id");if(c&&Ce(t,`#${Kt(c)}`))return{v:1,id:c,fingerprint:n};for(let a of uo){let i=e.getAttribute(a);if(i&&Ce(t,`[${a}="${Kt(i)}"]`))return{v:1,dataAttr:{name:a,value:i},fingerprint:n}}let d=Gt(e,t);return d?{v:1,selector:d,fingerprint:n}:null}var Ut=["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"],go={banner:"hero",navigation:"navigation",contentinfo:"footer"};function fo(e){let t=e.ariaRole?go[e.ariaRole.toLowerCase()]:void 0;if(t)return t;if(e.tag==="nav")return"navigation";if(e.tag==="footer")return"footer";if(e.tag==="header")return e.actionCount>=5?"navigation":"hero";let n=`${e.idClass} ${e.headingText}`.toLowerCase();return/\b(navbar|nav-bar|navigation|site-nav|main-nav|topbar|footer)\b/.test(n)?/footer/.test(n)?"footer":"navigation":/\b(hero|masthead|jumbotron)\b/i.test(e.idClass)?"hero":null}function mo(e){return e.actionCount>=1&&e.textLength>0&&e.textLength<200?"cta":"generic"}var yo=[["pricing",/\b(pricing|price list|per month|\/mo|subscriptions?)\b|\bplans?\b(?=[^.]{0,40}(from|start|month|year|[$€£]))/i],["faq",/\bfaq\b|frequently asked|common questions?/i],["comparison",/\b(compare|comparison|versus)\b|\bvs\./i],["social_proof",/\b(reviews?|ratings?|testimonial|brands?|galler(y|ies)|logos)\b|trusted by|loved by|case stud|what our customers say/i],["trust",/\b(insurance|warrant(y|ies)|guarantees?|certifi|accredit|security|privacy|compliance|gdpr|encrypt)\b|why choose|about us|our team/i],["cta",/\b(book|booking|reserve|appointments?|newsletter|subscribe)\b|contact us|get in touch|opening hours/i],["features",/\b(features?|benefits?|capabilit|services?|repairs?|menus?|products?)\b|how it works|our process|what we (do|offer)|what you get/i]],ho=[["pricing",/(?:[$€£]\s?\d[\d,.]*\s*(?:\/|per\s)\s*(?:mo|month|yr|year|seat|user))|(?:\b(?:starter|basic|pro|growth|premium|enterprise)\b[^.]{0,60}[$€£]\s?\d)/i],["social_proof",/(?:★{2,})|(?:\b\d(?:\.\d)?\s*(?:out of|\/)\s*5\b)|(?:\brated\b)|(?:["“][^"”]{20,160}["”]\s*[—–-]\s*[A-Z][a-z]+)/],["trust",/\b(?:money[- ]back guarantee|free returns?|returns? within|refund(?:s)? within|encrypted|soc ?2|iso ?27001|gdpr[- ]compliant|cancel anytime)\b/i],["comparison",/\b(?:vs|versus)\b\.?[^.!?]{0,80}\b(?:compare|comparison|plans?|features?|alternative)\b|\bhow (?:we|it) compares?\b/i]],$t={navigation:"navigation",footer:"navigation",hero:"hero",cta:"cta",generic:"generic"};function So(e){var n;let t=e.querySelector("h1, h2, h3");return((n=t==null?void 0:t.textContent)!=null?n:"").slice(0,160)}function bo(e){var d,a;let t=fo(e);if(t)return{type:(d=$t[t])!=null?d:"generic",strength:"strong"};let n=`${e.idClass} ${e.headingText}`.toLowerCase();for(let[i,l]of yo)if(l.test(n))return{type:i,strength:"strong"};for(let[i,l]of ho)if(l.test(e.bodyText))return{type:i,strength:"strong"};let c=mo(e);return{type:(a=$t[c])!=null?a:"generic",strength:"weak"}}function vo(e){var c,d;let t=((c=e.textContent)!=null?c:"").replace(/\s+/g," ").trim(),n=e.getAttribute("role");return x({tag:e.tagName.toLowerCase(),idClass:`${e.id} ${String((d=e.className)!=null?d:"")}`,headingText:So(e),bodyText:t.slice(0,2e3),actionCount:e.querySelectorAll('a, button, [role="button"]').length,textLength:t.length},n?{ariaRole:n}:{})}function Ft(e){return bo(vo(e)).type}var wo=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),xo="h1, h2, h3",Eo="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",jt=30,Co=1500,Io={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function Wt(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function ko(e){var t,n,c;try{let d=e;for(let a of Object.keys(d)){if(!a.startsWith("__reactFiber")&&!a.startsWith("__reactInternalInstance"))continue;let i=d[a],l=(c=(t=i==null?void 0:i.type)==null?void 0:t.displayName)!=null?c:(n=i==null?void 0:i.type)==null?void 0:n.name;if(l&&l.length>1)return l}}catch(d){}}function To(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var zt=new Set(Ut);function _o(e){let t=e.getAttribute("data-sentient-type");if(t&&zt.has(t))return t;let n=e.getAttribute("role");return n&&zt.has(n)?n:Ft(e)}function Ao(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 Ro(e){let t=[],n=e;for(;n;){let c=n.parentElement;if(!c){t.push(n.tagName.toLowerCase());break}let d=Array.prototype.indexOf.call(c.children,n);t.push(`${n.tagName.toLowerCase()}[${d}]`),n=c}return t.reverse().join("/")}function Oo(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${Ao(Ro(e))}`}function Po(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function Ve(e,t){var c,d,a,i;let n=e.querySelector(xo);return{componentId:Oo(e),semanticType:_o(e),ariaLabel:(c=e.getAttribute("aria-label"))!=null?c:void 0,headingText:(a=(d=n==null?void 0:n.textContent)==null?void 0:d.trim())!=null?a:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Po(e),reactComponentName:ko(e),dataAttributes:To(e),locator:(i=Ke(e,e.ownerDocument))!=null?i:void 0}}function Ht(e){var a;let t=[],n=new Set,c="__root__",d=new Map;for(let[i,l]of e){let u=i.parentElement,s=c;for(;u;){if(e.has(u)){s=e.get(u);let r=e.get(i),f=`${s}->${r}`;!n.has(f)&&s!==r&&(n.add(f),t.push({fromComponentId:s,toComponentId:r,weight:.6}));break}u=u.parentElement}let o=(a=d.get(s))!=null?a:[];o.push(i),d.set(s,o)}for(let i of d.values()){if(i.length<2)continue;let l=i.length>jt?i.slice(0,jt):i;for(let u=0;u<l.length;u++)for(let s=u+1;s<l.length;s++){if(t.length>=Co)return t;let o=e.get(l[u]),r=e.get(l[s]);if(o===r)continue;let f=`${o}->${r}::sib`,p=`${r}->${o}::sib`;n.has(f)||(n.add(f),t.push({fromComponentId:o,toComponentId:r,weight:.3})),n.has(p)||(n.add(p),t.push({fromComponentId:r,toComponentId:o,weight:.3}))}}return t}function Lo(e){let t=[],n=new Set,c=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(i=>{if(i instanceof Element&&!n.has(i)){n.add(i);let l=Ve(i,e);t.push(l),c.set(i,l.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(i=>{if(!(i instanceof Element)||n.has(i))return;let l=i.hasAttribute("aria-label"),u=i.hasAttribute("data-sentient-id");if(!l&&!u)return;n.add(i);let s=Ve(i,e);t.push(s),c.set(i,s.componentId)}),{nodes:t,edges:Ht(c),elementToId:c}}function qt(){if(typeof window=="undefined")return Io;let e=null,t=0,n=null,c=new Map,d=u=>{try{let s=window.getComputedStyle(u),o=parseFloat(s.fontSize)||12,r=parseFloat(s.zIndex)||0,f=u.getBoundingClientRect(),p=Math.max(f.top,0),y=window.innerHeight||1,S=1/(p/y+1),I=Wt(o,12,48)*.4+S*.4+Wt(r,0,100)*.2;return Math.max(0,Math.min(1,I))}catch(s){return .5}};return{scan:()=>new Promise(u=>{let s=()=>{let{nodes:o,edges:r,elementToId:f}=Lo(d);c.clear();for(let[p,y]of f)c.set(p,y);u({nodes:o,edges:r,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(s,{timeout:100}):s()}catch(o){s()}}),observe:u=>{n=u;try{e=new MutationObserver(s=>{let o=[],r=new Set;for(let p of s)p.type==="childList"&&p.addedNodes.forEach(y=>{if(!(y instanceof Element))return;let S=[];wo.has(y.tagName)&&(y.hasAttribute("data-sentient-id")||y.hasAttribute("aria-label"))&&S.push(y);try{y.querySelectorAll(Eo).forEach(I=>S.push(I))}catch(I){}for(let I of S){if(c.has(I))continue;let C=Ve(I,d);o.push(C),r.add(C.componentId),c.set(I,C.componentId)}});if(o.length===0||!n)return;for(let p of[...c.keys()])p.isConnected||c.delete(p);let f=Ht(c).filter(p=>r.has(p.fromComponentId)||r.has(p.toComponentId));n({nodes:o,edges:f,addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(s){}},getProminenceScore:d,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(u){}t=0,n=null,c.clear()}}}var No="https://api.sentient-ui.com/v1/events";function Do(e){var n;let t=c=>{try{let d=document.cookie.match(new RegExp(`(?:^|; )${c}=([^;]*)`));return d?decodeURIComponent(d[1]):void 0}catch(d){return}};return(n=e?t(ie(e)):void 0)!=null?n:t(ve)}var Ge=new Map;function Xt(e){var p;let t=Xe(e),n=e.respectDoNotTrack!==!1&&Ee(),c=e.consent===!1||n,d=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),a=e.localMode===!0||!d;if(!e.graph||a||typeof window=="undefined")return t;if(c)return n||Pt(e.apiKey,y=>Xt(y)),t;let i=Ge.get(e.apiKey);if(i)try{i()}catch(y){}let l=qt(),u=(p=e.ingestUrl)!=null?p:No,s=Mt({syncUrl:u.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Do(e.apiKey)});l.scan().then(y=>{for(let S of y.nodes)s.addPageNode({id:S.componentId,componentId:S.componentId,semanticType:S.semanticType,answers:e.captureDomText&&S.headingText?[S.headingText]:[],prominenceScore:S.prominenceScore,depth:S.depth});for(let S of y.edges)s.addStructuralEdge(S);s.syncOnce()});let o=null,r=()=>{o!==null&&clearTimeout(o),o=setTimeout(()=>{o=null,s.syncOnce()},500)};l.observe(y=>{for(let S of y.nodes)s.addPageNode({id:S.componentId,componentId:S.componentId,semanticType:S.semanticType,answers:e.captureDomText&&S.headingText?[S.headingText]:[],prominenceScore:S.prominenceScore,depth:S.depth});for(let S of y.edges)s.addStructuralEdge(S);r()});let f=()=>{o!==null&&(clearTimeout(o),o=null),l.destroy(),s.destroy(),Ge.get(e.apiKey)===f&&Ge.delete(e.apiKey)};return Ge.set(e.apiKey,f),q(x({},t),{getGraph:()=>s.snapshot(),dispose:()=>{f(),t.dispose()},destroy:()=>{f(),t.destroy()}})}0&&(module.exports={BLOCK_ALIGNS,BLOCK_EMPHASES,BLOCK_FITS,BLOCK_GAPS,BLOCK_GRID_COLUMNS,BLOCK_HEADING_LEVELS,BLOCK_JUSTIFIES,BLOCK_MAX_WIDTHS,BLOCK_PADS,BLOCK_RATIOS,BLOCK_SIZES,BLOCK_SURFACES,BLOCK_TEXT_ALIGNS,BLOCK_TONES,BLOCK_WEIGHTS,FORM_FIELD_KINDS,FORM_INPUT_TYPES,LEGACY_SESSION_COOKIE_NAME,MAX_BLOCK_ARMS,MAX_BLOCK_CHILDREN,MAX_BLOCK_DEPTH,MAX_BLOCK_NODES,MAX_BLOCK_TEXT_LEN,MAX_FORM_FIELDS,MAX_FORM_SELECT_OPTIONS,SNAPSHOT_STORAGE_KEY_PREFIX,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,containsFormBlock,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,locatorFromElement,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,sanitizePageUrl,sessionCookieName,toWireSlot,writeSnapshot});
|
|
1
|
+
"use strict";var dn=Object.create;var ke=Object.defineProperty,un=Object.defineProperties,pn=Object.getOwnPropertyDescriptor,gn=Object.getOwnPropertyDescriptors,fn=Object.getOwnPropertyNames,xt=Object.getOwnPropertySymbols,mn=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty,yn=Object.prototype.propertyIsEnumerable;var It=(e,t,n)=>t in e?ke(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,k=(e,t)=>{for(var n in t||(t={}))Ct.call(t,n)&&It(e,n,t[n]);if(xt)for(var n of xt(t))yn.call(t,n)&&It(e,n,t[n]);return e},J=(e,t)=>un(e,gn(t));var Sn=(e,t)=>{for(var n in t)ke(e,n,{get:t[n],enumerable:!0})},kt=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of fn(t))!Ct.call(e,d)&&d!==n&&ke(e,d,{get:()=>t[d],enumerable:!(a=pn(t,d))||a.enumerable});return e};var hn=(e,t,n)=>(n=e!=null?dn(mn(e)):{},kt(t||!e||!e.__esModule?ke(n,"default",{value:e,enumerable:!0}):n,e)),bn=e=>kt(ke({},"__esModule",{value:!0}),e);var Qo={};Sn(Qo,{BLOCK_ALIGNS:()=>Un,BLOCK_EMPHASES:()=>qn,BLOCK_FITS:()=>Jn,BLOCK_GAPS:()=>$n,BLOCK_GRID_COLUMNS:()=>Qn,BLOCK_HEADING_LEVELS:()=>Vn,BLOCK_JUSTIFIES:()=>Fn,BLOCK_MAX_WIDTHS:()=>eo,BLOCK_PADS:()=>Zn,BLOCK_RATIOS:()=>Xn,BLOCK_SIZES:()=>jn,BLOCK_SURFACES:()=>Yn,BLOCK_TEXT_ALIGNS:()=>Hn,BLOCK_TONES:()=>zn,BLOCK_WEIGHTS:()=>Wn,FORM_FIELD_KINDS:()=>to,FORM_INPUT_TYPES:()=>no,LEGACY_SESSION_COOKIE_NAME:()=>Te,MAX_BLOCK_ARMS:()=>co,MAX_BLOCK_CHILDREN:()=>ao,MAX_BLOCK_DEPTH:()=>io,MAX_BLOCK_NODES:()=>so,MAX_BLOCK_TEXT_LEN:()=>lo,MAX_FORM_FIELDS:()=>oo,MAX_FORM_SELECT_OPTIONS:()=>ro,SNAPSHOT_STORAGE_KEY_PREFIX:()=>de,armOfResult:()=>Ge,attachMicroSignalDetectors:()=>Ft,baselineResultFor:()=>be,baselineSlots:()=>Bt,containsFormBlock:()=>Ut,deriveSessionSegment:()=>Ve,detectDeviceClass:()=>fe,detectTimeOfDay:()=>Se,detectTrafficSource:()=>me,grantConsent:()=>Xt,init:()=>an,isDoNotTrackEnabled:()=>Re,locatorFromElement:()=>je,readSnapshot:()=>ve,referrerDomainFromReferer:()=>ye,renderPrePaintScript:()=>Mt,sanitizePageUrl:()=>nt,sessionCookieName:()=>pe,toWireSlot:()=>_e,writeSnapshot:()=>we});module.exports=bn(Qo);function Pe(){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 le(e){return e?`_${e.slice(0,12)}`:""}var Te="_snt_uid";function pe(e){return`${Te}${le(e)}`}var vn="_snt_uid",wn=365,De="_snt_uid";function En(){return Pe()}function Tt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function xn(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(a){}}function He(e){try{return localStorage.getItem(e)}catch(t){return null}}function _t(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function At(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function In(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Cn(e){try{sessionStorage.removeItem(e)}catch(t){}}function kn(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 Tn(e){try{localStorage.removeItem(e)}catch(t){}}function _n(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var An={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Le(e){var p,f,b,w,R,K,D;if(typeof window=="undefined")return An;let t=le(e==null?void 0:e.apiKey),n=(p=e==null?void 0:e.cookieName)!=null?p:pe(e==null?void 0:e.apiKey),a=`${De}${t}`,d=`${De}_tomb${t}`,r=((f=e==null?void 0:e.cookieTTLDays)!=null?f:wn)*24*60*60,s=B=>B&&B.length>0?B:null,g=()=>{var B,L;return t&&!(e!=null&&e.cookieName)&&He(d)===null?(L=(B=s(Tt(vn)))!=null?B:s(He(De)))!=null?L:s(At(De)):null},c=(D=(K=(R=(w=(b=s(Tt(n)))!=null?b:s(He(a)))!=null?w:s(At(a)))!=null?R:g())!=null?K:s(e==null?void 0:e.ssrSessionId))!=null?D:En();xn(n,c,r);let i=_t(a,c),l=kn(n),S=i?!1:In(a,c),y=!i&&!l&&!S;return{getSessionId:()=>c,isEphemeral:()=>y,destroy:()=>{c=null,_n(n),Tn(a),Cn(a),t&&!(e!=null&&e.cookieName)&&_t(d,"1")}}}function Z(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function ge(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 Ne(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let a=JSON.parse(n);return Array.isArray(a)?(localStorage.removeItem(e),a.slice(-t)):[]}catch(n){return[]}}function re(e,t,n){try{let a=(()=>{try{let o=localStorage.getItem(n);if(!o)return[];let r=JSON.parse(o);return Array.isArray(r)?r:[]}catch(o){return[]}})(),d=new Map;for(let o of a)d.set(o.id,o);for(let o of e)d.set(o.id,o);localStorage.setItem(n,JSON.stringify([...d.values()].slice(-t)))}catch(a){}}function Be(e,t){try{let n=localStorage.getItem(t);if(!n)return;let a=JSON.parse(n);if(!Array.isArray(a))return;let d=new Set(e),o=a.filter(r=>!d.has(r.id));if(o.length===a.length)return;o.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(o))}catch(n){}}var Rn=500,On=56*1024;function Xe(e){return`_snt_retry_${e.slice(0,12)}`}var Pn={push:()=>{},flush:()=>{},destroy:()=>{}};function Rt(e){var Q,V,Ee;if(typeof window=="undefined")return Pn;let t=(Q=e.flushIntervalMs)!=null?Q:5e3,n=(V=e.maxBatchSize)!=null?V:20,a=(Ee=e.maxRetrySize)!=null?Ee:100,d=e.ingestUrl,o=e.apiKey,r=Xe(o),s=[],g=new Set,c=[],i=x=>{for(let O of x)l.delete(O),!g.has(O)&&(g.add(O),c.push(O));for(;c.length>Rn;){let O=c.shift();O&&g.delete(O)}Be(x,r)},l=new Set,S=()=>{for(;s.length>a;){let x=s.shift();x&&l.delete(x.id)}},y=x=>{g.has(x.id)||l.has(x.id)||(l.add(x.id),s.push(x),S())},p=x=>{for(let O of x)g.has(O.id)||(l.add(O.id),s.push(O));S()},f=Ne(r,a);for(let x of f)y(x);let b=0,w=0,R=(x,O=!0)=>{if(x.length===0)return;let W=JSON.stringify(x),H=x.map(q=>q.id),z;try{z=fetch(d,{method:"POST",keepalive:!0,body:W,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}})}catch(q){re(x,a,r),p(x),w++,b=Date.now()+Z(w);return}let se=q=>{if(ge(q)!=="retry"){if(!q.ok&&O){let ie=x.filter(ae=>ae.eventType!=="pageview");if(ie.length>0&&ie.length<x.length){i(x.filter(ae=>ae.eventType==="pageview").map(ae=>ae.id)),R(ie,!1);return}}i(H),w=0,b=0;return}re(x,a,r),p(x),w++,b=Date.now()+Z(w)};z instanceof Promise?z.then(se).catch(()=>{re(x,a,r),p(x),w++,b=Date.now()+Z(w)}):se(z)},K=typeof TextEncoder!="undefined"?new TextEncoder:null,D=x=>K?K.encode(x).length:x.length,B=x=>{let O=[],W=2;for(let H of x){let z=D(JSON.stringify(H))+1;if(O.length>0&&W+z>On||O.length>=n)break;O.push(H),W+=z}return O},L=()=>{try{if(Date.now()<b)return;for(;s.length>0&&!(Date.now()<b);){let x=s.filter(W=>!g.has(W.id));if(s.length=0,x.length===0)break;let O=B(x);if(O.length===0)break;O.length<x.length&&s.push(...x.slice(O.length)),R(O)}}catch(x){}},E=!0,T=null;T=setInterval(()=>{E&&L()},t);let ee=()=>{document.visibilityState==="hidden"&&L()},j=()=>{L()};return document.addEventListener("visibilitychange",ee),window.addEventListener("pagehide",j),{push(x){y(x),s.length>=n&&L()},flush:L,destroy(){E=!1,T!==null&&(clearInterval(T),T=null),document.removeEventListener("visibilitychange",ee),window.removeEventListener("pagehide",j),L()}}}var Dn=200;function Je(e){return`_snt_goal_retry_${e.slice(0,12)}`}var Ln={send:()=>{},flush:()=>{},destroy:()=>{}};function Ot(e){var D,B,L;if(typeof window=="undefined")return Ln;let t=(D=e.flushIntervalMs)!=null?D:5e3,n=(B=e.maxRetrySize)!=null?B:100,a=(L=e.maxPerFlush)!=null?L:5,d=Je(e.apiKey),o=[],r=new Set,s=new Set,g=[],c=0,i=0,l=!1,S=E=>{for(r.delete(E.id),s.has(E.id)||(s.add(E.id),g.push(E.id));g.length>Dn;){let T=g.shift();T&&s.delete(T)}Be([E.id],d)},y=E=>{re([E],n,d),!s.has(E.id)&&!r.has(E.id)&&(r.add(E.id),o.push(E)),Date.now()>=c&&(i++,c=Date.now()+Z(i))},p=E=>{let T;try{T=fetch(e.url,{method:"POST",keepalive:!0,body:E.body,headers:e.headers})}catch(j){y(E);return}let ee=j=>{var V;let Q=ge(j);if(Q==="retry"){y(E);return}Q==="dropped"&&((V=e.onDrop)==null||V.call(e,E,j.status)),S(E),i=0,c=0};T instanceof Promise?T.then(ee).catch(()=>y(E)):ee(T)},f=()=>{try{if(l||Date.now()<c)return;let E=0;for(;o.length>0&&E<a&&!(Date.now()<c);){let T=o.shift();r.delete(T.id),!s.has(T.id)&&(E++,p(T))}}catch(E){}},b=Ne(d,n);for(let E of b)r.has(E.id)||(r.add(E.id),o.push(E));b.length>0&&re(b,n,d);let w=setInterval(f,t),R=()=>{document.visibilityState==="hidden"&&f()},K=()=>f();return document.addEventListener("visibilitychange",R),window.addEventListener("pagehide",K),{send(E){if(!l&&!(s.has(E.id)||r.has(E.id))){if(Date.now()<c){re([E],n,d),r.add(E.id),o.push(E);return}p(E)}},flush:f,destroy(){clearInterval(w),document.removeEventListener("visibilitychange",R),window.removeEventListener("pagehide",K),f(),l=!0}}}var Nn=1800*1e3;function Me(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Pt(e=Nn,t){let n=new Map,a=`_snt_asgn${le(t)}_`,d=(c,i)=>`${a}${encodeURIComponent(c)}:${encodeURIComponent(i)}`,o=c=>{let i=c.slice(a.length),l=i.indexOf(":");if(l<0)return null;try{return{componentId:decodeURIComponent(i.slice(0,l)),segment:decodeURIComponent(i.slice(l+1))}}catch(S){return null}},r=()=>{try{let c=[];for(let i=0;i<localStorage.length;i++){let l=localStorage.key(i);l!=null&&l.startsWith(a)&&c.push(l)}return c}catch(c){return[]}},s=c=>c.assignedAt+(c.ttlMs&&c.ttlMs>0?c.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let c of r())try{let i=localStorage.getItem(c);if(!i)continue;let l=JSON.parse(i);if(s(l)){localStorage.removeItem(c);continue}let S=o(c);if(!S)continue;n.set(Me(S.componentId,S.segment),l)}catch(i){}})(),{get(c,i){let l=n.get(Me(c,i));return l?s(l)?(n.delete(Me(c,i)),null):l:null},set(c,i,l){let S=Me(c,i);n.set(S,l);try{localStorage.setItem(d(c,i),JSON.stringify(l))}catch(y){}},clear(){n.clear();for(let c of r())try{localStorage.removeItem(c)}catch(i){}}}}var Dt=["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 Ke(e){return Lt(e)!==null}function Lt(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Dt.find(a=>t.includes(a.toLowerCase())))!=null?n:null}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(d){}let a=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(a)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(a)?"social":"referral"}catch(n){return"direct"}}function ye(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var Nt=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function Qe(e){let t={},n={};try{let a=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([d,o])=>{let r=Array.isArray(o)?o[0]:o;return r===void 0?[]:[[d,r]]});for(let[d,o]of a)d.startsWith("utm_")?d in t||(t[d]=o):Nt.includes(d)&&(d in n||(n[d]=o))}catch(a){}return{utmParams:t,clickIds:n}}function Se(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ve(e){let t=Bn("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Bn(e,t){var o,r,s,g,c,i,l,S;let n=(r=(o=t==null?void 0:t.userAgent)==null?void 0:o.trim())!=null?r:"",a=(g=(s=t==null?void 0:t.referer)==null?void 0:s.trim())!=null?g:"",d=(c=t==null?void 0:t.now)!=null?c:new Date;return{sessionId:e,ephemeral:!1,utmParams:(i=t==null?void 0:t.utmParams)!=null?i:{},clickIds:(l=t==null?void 0:t.clickIds)!=null?l:{},deviceClass:n?fe(n):"desktop",trafficSource:a?me(a,t==null?void 0:t.appOrigin):"direct",referrerDomain:ye(a),timeOfDay:Se(d),dayOfWeek:(S=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?S:"sun",automation:(t==null?void 0:t.webdriver)===!0||Ke(n)}}var he=require("@sentientui/policy");function _e(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 be(e){let t=_e(e);return(0,he.slotResultFor)(t,(0,he.slotBaselineArm)(t))}function Bt(e){let t={};for(let n of e)t[n.id]=be(n);return t}function Ge(e){return typeof e=="string"?e:(0,he.canonicalArm)(e)}var de="_snt_snap:",Mn=["low","medium","high"];function ve(e){try{let t=localStorage.getItem(de+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"||!Mn.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 we(e,t){try{localStorage.setItem(de+e,JSON.stringify(t))}catch(n){}}function Mt(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(de+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 Ze=require("@sentientui/policy");var Ue=require("@sentientui/policy");var Kt="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Kn="[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.",Gt=!1,$e=!1;function Gn(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function $t(e){var c;let t=Le({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(c=t.getSessionId())!=null?c:"local",a=Gn(),d=import("@sentientui/core/local").then(i=>{let l=i;return l.LOCAL_ENGINE_AVAILABLE?(Gt||(Gt=!0,console.info(Kn)),l):($e||($e=!0,console.error(Kt)),null)}).catch(()=>($e||($e=!0,console.error(Kt)),null)),o=null,r={low:.15,medium:.5,high:.85},s=(()=>{var l;if(e.initialPersona)return k({},e.initialPersona);let i=ve(e.apiKey||"local");return i?{persona:i.persona,confidence:(l=r[i.band])!=null?l:.15}:null})();function g(i){let l=document.documentElement;l.dataset.sentientPersona===void 0&&(l.dataset.sentientPersona=i.persona,l.dataset.sentientConfidence=(0,Ue.confidenceBand)(i.confidence))}return{isLocal:!0,async decide(i){var y,p,f;let l=await d;if(!l)return null;let S=l.createLocalEngine({sessionId:n,forcedPersona:a}).decide(i);return o=J(k({},S),{layoutOrder:(p=(y=S.layoutOrder)!=null?y:o==null?void 0:o.layoutOrder)!=null?p:null,slots:k(k({},(f=o==null?void 0:o.slots)!=null?f:{}),S.slots)}),we(e.apiKey||"local",{v:1,persona:o.persona,band:(0,Ue.confidenceBand)(o.confidence),slots:o.slots,layoutOrder:o.layoutOrder,savedAt:Date.now()}),g(S),S},getSlotResult(i){var l,S,y;return(y=(S=o==null?void 0:o.slots[i])!=null?S:(l=e.initialSlots)==null?void 0:l[i])!=null?y:null},getSlotConfig(i){var l,S;return(S=(l=e.initialSlotConfig)==null?void 0:l[i])!=null?S:null},getSitePalette(){var i;return(i=e.initialPalette)!=null?i:null},reportSlots(){},getPersona(){let i=o!=null?o:s;return i?{persona:i.persona,confidence:i.confidence,band:(0,Ue.confidenceBand)(i.confidence)}:null},async assign(i,l){var p;let S=await d;return!S||!l||l.length===0?l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null:{variantId:(p=S.createLocalEngine({sessionId:n,forcedPersona:a}).decide({components:[{id:i,variantIds:l}]}).assignments[i])!=null?p:l[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var $n=["none","sm","md","lg"],Un=["start","center","end","stretch"],Fn=["start","center","end","between"],jn=["sm","md","lg"],Wn=["normal","medium","bold"],zn=["default","muted","accent"],qn=["primary","secondary","ghost"],Hn=["left","center","right"],Xn=["auto","square","landscape","wide"],Jn=["cover","contain"],Qn=[2,3,4],Vn=[2,3,4],Yn=["default","raised"],Zn=["none","sm","md","lg"],eo=["measure"],to=["input","textarea","select"],no=["text","email","number","tel"],oo=5,ro=8,so=64,io=5,ao=12,co=4,lo=500;function Ut(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(Ut):!1}function Ft(e,t,n,a){let d=[];{let s=!1,g=[],c=()=>{if(s)return;let i=Date.now();for(g.push(i);g.length>0&&i-g[0]>500;)g.shift();g.length>=3&&(s=!0,e("rage_click"))};t.addEventListener("click",c),d.push(()=>t.removeEventListener("click",c))}{let o=!1,r=s=>{if(o||!(s.target instanceof Node)||!t.contains(s.target)&&t!==s.target)return;o=!0;let g=typeof window!="undefined"?window.getSelection():null,c=g?g.toString().length:0;e("text_copy",{selectionLength:c})};document.addEventListener("copy",r),d.push(()=>document.removeEventListener("copy",r))}{let o=!1,r=!1,s=null,g=()=>{s!==null&&(clearTimeout(s),s=null)},c=()=>{o||!r||(g(),s=setTimeout(()=>{!o&&r&&(o=!0,e("scroll_hesitation"))},3e3))},i=()=>{g(),c()},l=y=>{for(let p of y)r=p.intersectionRatio>.3,r?c():g()},S=new IntersectionObserver(l,{threshold:[.3]});S.observe(t),window.addEventListener("scroll",i,{passive:!0}),d.push(()=>{S.disconnect(),window.removeEventListener("scroll",i),g()})}if((a==null?void 0:a.tabLoss)!==!1){let o=!1,r=n!=null?n:Date.now(),s=()=>{if(o||document.visibilityState!=="hidden")return;let g=Date.now()-r;g<15e3&&(o=!0,e("tab_loss",{timeOnPage:g}))};document.addEventListener("visibilitychange",s),d.push(()=>document.removeEventListener("visibilitychange",s))}return()=>{for(let o of d)o()}}function uo(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var jt="https://api.sentient-ui.com/v1/events",F=new Map,Wt=null;function zt(e,t){let n=F.get(e);n&&n.upgrade&&(n.reinit=t)}function po(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var go=3;function Ye(){return Pe()}function Fe(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function fo(){let e=new WeakMap,t=new Map,n=!1,a=(s,g,c)=>{let i=s.get(g);return c===null?i?!0:(s.set(g,new Set),!1):i?i.has(c)?!0:(i.add(c),!1):(s.set(g,new Set([c])),!1)},d=typeof window!="undefined"&&"event"in window,o=()=>{if(!d)return;let s=window.event;return typeof Event=="function"&&s instanceof Event?s:void 0},r=()=>{if(d){Promise.resolve().then(()=>{n=!1,t.clear()});return}let s=!1,g=()=>{s||(s=!0,n=!1,t.clear())};if(setTimeout(g,0),typeof MessageChannel=="function"){let c=new MessageChannel;c.port1.onmessage=()=>{c.port1.close(),c.port2.close(),g()},c.port2.postMessage(0)}};return{firedBefore(s,g){let c=o();if(c){let l=e.get(c);return l||(l=new Map,e.set(c,l)),a(l,s,g)}let i=a(t,s,g);return!i&&!n&&(n=!0,r()),i}}}var qt=new Set;function mo(e,t,n){let a=typeof window=="undefined"?null:window.history;if(!a)return()=>{};let d=!1,o,r=()=>{if(d)return;let c=Fe();!c||c===o||(o=c,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${c}`))},s=[];for(let c of["pushState","replaceState"]){let i=a[c],l=function(...S){let y=i.apply(this,S);return r(),y};a[c]=l,s.push([c,i,l])}window.addEventListener("popstate",r);let g=Fe();return g&&qt.has(`${t}:${g}`)?o=g:r(),()=>{if(!d){d=!0,window.removeEventListener("popstate",r);for(let[c,i,l]of s)a[c]===l&&(a[c]=i)}}}var Ae={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}),dispose:()=>{},destroy:()=>{}};function yo(){try{return Qe(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function Ht(e){return e.replace(/\/events\/?$/,"")}function Re(){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 Xt(e){var g;if(typeof window=="undefined")return;let t=e!=null?e:Wt;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=F.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:a,upgrade:d,reinit:o}=n;if(!d){n.upgradeBlockedReason&&console.warn(n.upgradeBlockedReason);return}if(a.respectDoNotTrack!==!1&&Re())return;let r=(o!=null?o:tt)(J(k({},a),{consent:!0}));d(r);let s=(g=F.get(t))==null?void 0:g.dispose;F.set(t,{config:J(k({},a),{consent:!0}),upgrade:null,dispose:s})}function So(e){var y;let t=e.preConsentBehavior==="statistical_winner",n=Ht((y=e.ingestUrl)!=null?y:jt),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d=new Map,o=new Map,r={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(p,f,b){if(!t)return Promise.resolve(null);let w=d.get(p);return w?Promise.resolve(w):et(o,p,async()=>{try{let R=new URLSearchParams({componentId:p});for(let L of f!=null?f:[])R.append("variantIds[]",L);let K=await fetch(`${n}/winner?${R.toString()}`,{headers:a});if(!K.ok)return f!=null&&f[0]?{variantId:f[0],assignmentTtlMs:0}:null;let B={variantId:(await K.json()).variantId,assignmentTtlMs:0};return d.set(p,B),B}catch(R){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}),dispose:()=>{},destroy:()=>{}},s=!1,g=new Set,c=[],i=[],l={track:p=>r.track(p),goal:((p,f,b,w)=>r.goal(p,f,b,w)),componentGoal:(p,f,b)=>r.componentGoal(p,f,b),identify:p=>r.identify(p),getAssignment:(p,f)=>r.getAssignment(p,f),assign:(p,f,b,w)=>r.assign(p,f,b,w),decide:p=>r.decide(p),getSlotResult:p=>r.getSlotResult(p),isSlotDecided:p=>{var f,b;return(b=(f=r.isSlotDecided)==null?void 0:f.call(r,p))!=null?b:!0},getSlotConfig:p=>r.getSlotConfig(p),getSitePalette:()=>r.getSitePalette(),reportSlots:(p,f)=>r.reportSlots(p,f),requestSlots:(p,f)=>{var b;return s?(b=r.requestSlots)==null?void 0:b.call(r,p,f):c.push([p,f])},decideSlots:p=>{var f;return s?(f=r.decideSlots)==null?void 0:f.call(r,p):i.push(...p)},cancelSlots:p=>{var b;if(s)return(b=r.cancelSlots)==null?void 0:b.call(r,p);let f=new Set(p);for(let w of c)w[0]=w[0].filter(R=>!f.has(R));i=i.filter(w=>!f.has(w.id))},onSlotsChanged:p=>(g.add(p),()=>{g.delete(p)}),getPersona:()=>r.getPersona(),fetchWeights:()=>r.fetchWeights(),getGraph:()=>r.getGraph(),dispose:()=>r.dispose(),destroy:()=>r.destroy()};function S(p){var f,b,w;r=p,s=!0,(f=p.onSlotsChanged)==null||f.call(p,()=>g.forEach(R=>R()));for(let[R,K]of c.splice(0))R.length>0&&((b=p.requestSlots)==null||b.call(p,R,K));i.length>0&&((w=p.decideSlots)==null||w.call(p,i.splice(0)))}return{proxy:l,setInner:S}}function et(e,t,n){let a=e.get(t);if(a)return a;let d=(async()=>{try{return await n()}finally{e.delete(t)}})();return e.set(t,d),d}function tt(e){var ut,pt,gt,ft,mt,yt,St,ht,bt,vt;if(typeof window=="undefined")return Ae;Wt=e.apiKey||"local";let t=F.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(u){}let n=e.respectDoNotTrack!==!1&&Re(),a=e.consent===!1||n,d=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!d&&e.localMode!==!1)return F.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."}),a?Ae:$t(e);if(a){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."),F.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."}),Ae;let{proxy:u,setInner:m}=So(e);return F.set(e.apiKey,{config:e,upgrade:n?null:m}),u}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."),Ae;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),Ae;let o=(ut=e.ingestUrl)!=null?ut:jt,r=Date.now(),s=Le({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),g=Pt(void 0,e.apiKey),c=Rt({ingestUrl:o,apiKey:e.apiKey}),i=Ht(o),l={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},S=new Set,y=Ot({url:`${i}/goals`,apiKey:e.apiKey,headers:l,onDrop:(u,m)=>{if(!e.debug){if(S.has(m))return;S.add(m)}console.warn(`[sentient] goal dropped (HTTP ${m}) \u2014 this will not be retried. `+(m===400?"The session was not found: call init() and let the session upsert complete before firing goals.":m===401||m===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),u)}}),p=fe((pt=navigator.userAgent)!=null?pt:""),f=window.location.origin,b=me((gt=document.referrer)!=null?gt:"",f),w=(ft=e.sessionSegment)!=null?ft:`${p}:${b}`,R=new Map,K=new Map,D=new Map,B=new Set,L=new Map,E=null,T=null,ee=new Set,j=new Set,Q=new Map,V=null,Ee=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,x=new Set,O=new Set,W=new Set,H=new Map,z=null,se=new Set,q=new Map,ie=null,ae=2,it=new Map,ze=!1,at=(u,m,h)=>{var v;let I=new Set,_=1;for(let C of u){m.delete(C);let A=((v=it.get(C))!=null?v:0)+1;it.set(C,A),A<=ae&&(I.add(C),A>_&&(_=A))}I.size>0&&setTimeout(()=>{ze||h(I)},Z(_))},ct=u=>{for(let m of u)D.has(m.id)||D.set(m.id,be(m))};if(e.initialSlots)for(let[u,m]of Object.entries(e.initialSlots))D.set(u,m),B.add(u);if(e.initialSlotConfig)for(let[u,m]of Object.entries(e.initialSlotConfig))L.set(u,m);e.initialPalette&&(E=e.initialPalette);let te=ve(e.apiKey);if(te){for(let[u,m]of Object.entries(te.slots))D.has(u)||D.set(u,m);for(let[u,m]of Object.entries((mt=te.slotConfig)!=null?mt:{}))L.has(u)||L.set(u,m);!E&&te.palette&&(E=te.palette)}let lt={low:.15,medium:.5,high:.85};if(e.initialPersona)T=k({},e.initialPersona);else{let u=document.documentElement.dataset;u.sentientPersona?T={persona:u.sentientPersona,confidence:(St=lt[(yt=u.sentientConfidence)!=null?yt:"low"])!=null?St:.15}:te&&(T={persona:te.persona,confidence:(ht=lt[te.band])!=null?ht:.15})}if(e.initialAssignments)for(let[u,m]of Object.entries(e.initialAssignments))g.set(u,w,{variantId:m,assignedAt:Date.now(),segment:w,confidence:1});let ne=Promise.resolve(),dt=s.getSessionId();if(dt){let u=ye((bt=document.referrer)!=null?bt:""),{utmParams:m,clickIds:h}=yo(),I=k(k(k(k({sessionId:dt,deviceClass:p,trafficSource:b,referrerDomain:u,utmParams:m,clickIds:h,timeOfDay:Se(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:s.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Ke((vt=navigator.userAgent)!=null?vt:"")},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 v=0;;v++){try{let C=await fetch(`${i}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(I),headers:l});if(C.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(C.ok||ge(C)==="dropped")return}catch(C){}if(v>=go){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(C=>setTimeout(C,Z(v+1)))}};try{ne=_()}catch(v){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:c});let cn=fo(),ce=null,qe=!1,G={goal(u,m={},h=1,I=0){var oe,xe,Ie,Ce,ue,P,Y;let _=s.getSessionId();if(!_)return;let v=po(m)?m:{metadata:m},C=[u,(oe=v.externalId)!=null?oe:"",(xe=v.stepIndex)!=null?xe:I,(Ie=v.weight)!=null?Ie:h].join("\0"),A=v.value!==void 0?`${v.value}\0${(Ce=v.currency)!=null?Ce:""}`:null;if(cn.firedBefore(C,A)){e.debug&&console.log(`[sentient] goal("${u}") already recorded for this action \u2014 not sent twice`);return}let M=Ye(),$={sessionId:_,name:u,metadata:(ue=v.metadata)!=null?ue:{},weight:(P=v.weight)!=null?P:h,stepIndex:(Y=v.stepIndex)!=null?Y:I,goalId:M,value:v.value,currency:v.currency,externalId:v.externalId};e.debug&&console.log("[sentient] goal",$);let U={id:M,body:JSON.stringify($)};ne.then(()=>y.send(U))},componentGoal(u,m,h){var M,$,U;let I=s.getSessionId();if(!I)return;let _=g.get(u,w),v=_?null:(M=D.get(u))!=null?M:null;if(!_&&v===null){e.debug&&console.warn(`[sentient] componentGoal("${u}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}if(!_&&!B.has(u)){e.debug&&console.warn(`[sentient] componentGoal("${u}"): slot not decided this session \u2014 not attributed`);return}let C=_?_.variantId:Ge(v),A={id:Ye(),sessionId:I,projectId:e.apiKey,componentId:u,variantId:C,eventType:"goal_achieved",goalType:m,payload:k({reward:($=h==null?void 0:h.reward)!=null?$:1,goalValue:h==null?void 0:h.value,currency:h==null?void 0:h.currency},(U=h==null?void 0:h.metadata)!=null?U:{}),timestamp:Date.now(),timeInSession:Date.now()-r,path:Fe()};e.debug&&console.log("[sentient] componentGoal",A),ne.then(()=>c.push(A))},identify(u){let m=s.getSessionId();m&&ne.then(()=>{fetch(`${i}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:m,userId:u,ephemeral:s.isEphemeral()}),headers:l}).catch(()=>{})})},track(u){let m=s.getSessionId();if(!m||u.eventType==="variant_assigned"&&D.get(u.componentId)!==void 0&&!B.has(u.componentId)&&!g.get(u.componentId,w))return;let h=J(k({path:Fe()},u),{id:Ye(),sessionId:m,timestamp:Date.now(),timeInSession:Date.now()-r});e.debug&&console.log("[sentient] track",h),ne.then(()=>c.push(h))},getAssignment(u,m){return g.get(u,m)},async assign(u,m,h,I){let _=s.getSessionId();if(!_)return null;let v=g.get(u,w);if(v&&(m!=null&&m.length||v.content!==void 0)){let C=v.ttlMs&&v.ttlMs>0?Math.max(0,v.assignedAt+v.ttlMs-Date.now()):0;return{variantId:v.variantId,assignmentTtlMs:C,content:v.content}}return et(R,u,async()=>{await ne;try{let C={sessionId:_,componentId:u,variantIds:m};I!==void 0?C.agentDataByVariant=I:h!==void 0&&(C.agentData=h);let A=await fetch(`${i}/assign`,{method:"POST",body:JSON.stringify(C),headers:l});if(!A.ok)return null;let M=await A.json();return g.set(u,w,k({variantId:M.variantId,assignedAt:Date.now(),segment:w,confidence:1,content:M.content},M.assignmentTtlMs&&M.assignmentTtlMs>0?{ttlMs:M.assignmentTtlMs}:{})),M}catch(C){return null}})},async decide(u){var v,C;let m=s.getSessionId();if(!m)return null;let h=(v=u.slots)!=null?v:[],I={sessionId:m};u.sections&&u.sections.length>0&&(I.sections=u.sections.map(A=>({id:A}))),I.components=(C=u.components)!=null?C:[],h.length>0&&(I.slots=h.map(_e)),u.slotsFrom==="registry"&&(I.slotsFrom="registry",u.registrySlotIds&&(I.registrySlotIds=u.registrySlotIds),u.bootstrap===!1&&(I.bootstrap=!1)),u.v&&(I.v=u.v),typeof u.pp=="number"&&(I.pp=u.pp),e.persona&&(I.persona=e.persona);let _=JSON.stringify(I);return et(K,_,async()=>{var A,M,$,U,oe,xe,Ie,Ce;await ne;try{let ue=await fetch(`${i}/decide`,{method:"POST",body:_,headers:l});if(!ue.ok)return ct(h),null;let P=await ue.json(),Y={};for(let N of h){let X=(A=P.slots)==null?void 0:A[N.id];if(X!==void 0){Y[N.id]=X,D.set(N.id,X),B.add(N.id);continue}let wt=D.get(N.id);if(wt!==void 0)Y[N.id]=wt;else{let Et=be(N);Y[N.id]=Et,D.set(N.id,Et)}}if(P.slots)for(let[N,X]of Object.entries(P.slots))N in Y||(Y[N]=X,D.set(N,X),B.add(N));let ln=T!=null&&T.persona!=="unknown";P.persona&&!(P.persona==="unknown"&&ln)?T={persona:P.persona,confidence:(M=P.confidence)!=null?M:0}:T||(T={persona:"unknown",confidence:0});for(let[N,X]of Object.entries(($=P.assignments)!=null?$:{}))g.set(N,w,{variantId:X,assignedAt:Date.now(),segment:w,confidence:1});if(P.slotConfig)for(let[N,X]of Object.entries(P.slotConfig))L.set(N,X);P.palette&&(E=P.palette);for(let N of(U=u.registrySlotIds)!=null?U:[])(oe=P.slotConfig)!=null&&oe[N]||(L.delete(N),D.delete(N),B.delete(N));return we(e.apiKey,k(k({v:1,persona:T.persona,band:(0,Ze.confidenceBand)(T.confidence),slots:Object.fromEntries(D),layoutOrder:(xe=P.layoutOrder)!=null?xe:null,savedAt:Date.now()},L.size>0?{slotConfig:Object.fromEntries(L)}:{}),E?{palette:E}:{})),k(k(k(k({layoutOrder:(Ie=P.layoutOrder)!=null?Ie:null,assignments:(Ce=P.assignments)!=null?Ce:{},slots:Y,persona:T.persona,confidence:T.confidence},P.slotConfig?{slotConfig:P.slotConfig}:{}),P.goals?{goals:P.goals}:{}),P.sectionMap?{sectionMap:P.sectionMap}:{}),P.palette?{palette:P.palette}:{})}catch(ue){return ct(h),null}})},getSlotResult(u){var m;return(m=D.get(u))!=null?m:null},isSlotDecided(u){return B.has(u)},getSlotConfig(u){var m;return(m=L.get(u))!=null?m:null},reportSlots(u,m){for(let h of u)if(!(typeof h!="string"||h.length===0)){if(!Ee.test(h)){uo()&&!x.has(h)&&(x.add(h),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(h)} 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(!ee.has(h)){ee.add(h),j.add(h);let I=m==null?void 0:m[h];if(typeof I=="string"){let _=I.replace(/\s+/g," ").trim().slice(0,400);_!==""&&Q.set(h,_)}}}j.size===0||V!=null||(V=setTimeout(()=>{V=null;let h=[...j];j.clear();for(let I=0;I<h.length;I+=20){let _=h.slice(I,I+20),v={};for(let C of _){let A=Q.get(C);A!==void 0&&(v[C]=A,Q.delete(C))}fetch(`${i}/slots/observed`,{method:"POST",headers:l,body:JSON.stringify(k({slotIds:_},Object.keys(v).length>0?{baselineTexts:v}:{}))}).catch(()=>{})}},1e3))},requestSlots(u,m){for(let h of u)W.has(h)||(W.add(h),Ee.test(h)?H.set(h,m==null?void 0:m[h]):G.reportSlots([h]));H.size===0||z!=null||(z=setTimeout(()=>{z=null;let h=[...H];H.clear();for(let I=0;I<h.length;I+=50){let _=h.slice(I,I+50);G.decide({slotsFrom:"registry",registrySlotIds:_.map(([v])=>v),bootstrap:!1}).then(v=>{var C;if(v){let A={},M=[];for(let[$,U]of _)(C=v.slotConfig)!=null&&C[$]||(M.push($),U&&(A[$]=U));M.length>0&&G.reportSlots(M,A)}else at(_.map(([A])=>A),W,A=>{var $;let M={};for(let[U,oe]of _)A.has(U)&&oe&&(M[U]=oe);($=G.requestSlots)==null||$.call(G,[...A],M)});O.forEach(A=>A())})}},0))},decideSlots(u){for(let m of u)se.has(m.id)||(se.add(m.id),q.set(m.id,m));q.size===0||ie!=null||(ie=setTimeout(()=>{ie=null;let m=[...q.values()];q.clear();for(let h=0;h<m.length;h+=30){let I=m.slice(h,h+30);G.decide({slots:I}).then(_=>{_||at(I.map(v=>v.id),se,v=>{var C;return(C=G.decideSlots)==null?void 0:C.call(G,I.filter(A=>v.has(A.id)))}),O.forEach(v=>v())})}},0))},cancelSlots(u){for(let m of u)H.delete(m)&&W.delete(m),q.delete(m)&&se.delete(m)},onSlotsChanged(u){return O.add(u),()=>{O.delete(u)}},getSitePalette(){return E},getPersona(){return T?{persona:T.persona,confidence:T.confidence,band:(0,Ze.confidenceBand)(T.confidence)}:null},async fetchWeights(){var u;try{let m=await fetch(`${i}/weights`,{headers:l});return m.ok?(u=(await m.json()).components)!=null?u:[]:[]}catch(m){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var u;ce==null||ce(),qe=!0,ze=!0,c.destroy(),y.destroy(),((u=F.get(e.apiKey))==null?void 0:u.dispose)===G.dispose&&F.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var u;ce==null||ce(),qe=!0,ze=!0,c.destroy(),y.destroy(),s.destroy(),g.clear(),((u=F.get(e.apiKey))==null?void 0:u.dispose)===G.dispose&&F.delete(e.apiKey);try{localStorage.removeItem(de+e.apiKey),localStorage.removeItem(Xe(e.apiKey)),localStorage.removeItem(Je(e.apiKey))}catch(m){}e.debug&&console.log("[sentient] destroyed")}};if(F.set(e.apiKey,{config:e,upgrade:null,dispose:G.dispose}),ce=mo(G,e.apiKey,u=>{ne.then(()=>{qe||qt.add(u)})}),e.debug){let u=window;u.__sentient&&(u.__sentient.client=G)}return G}var Jt="_snt_graph_edges",ho={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function bo(e){var t;return(t=ho[e])!=null?t:[]}function vo(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function wo(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var Eo=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function xo(e){return Eo.has(e)?e:"generic"}function nt(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function Io(e,t,n){let a=`${e}:${t}:${n.join(",")}`,d=5381;for(let o=0;o<a.length;o++)d=(d<<5)+d+a.charCodeAt(o)&4294967295;return(d>>>0).toString(16).padStart(8,"0")}function Qt(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${le(e==null?void 0:e.apiKey)}`,d=()=>{typeof window!="undefined"&&wo(a,[...t.values()])};if(typeof window!="undefined"){let o=vo(a,[]);for(let r of o)t.set(r.componentId,r);try{localStorage.removeItem(Jt)}catch(r){}}return{addPageNode(o){t.set(o.componentId,o),d()},addStructuralEdge(o){let r=`${o.fromComponentId}->${o.toComponentId}`;n.set(r,o)},syncOnce(){var r,s;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let g=new Map;for(let y of o){let p=(r=g.get(y.semanticType))!=null?r:[];p.push(y),g.set(y.semanticType,p)}let c=[],i=new Set;for(let y of o)for(let p of bo(y.semanticType)){let f=(s=g.get(p))!=null?s:[];for(let b of f){if(b.componentId===y.componentId)continue;let w=`semantic:${y.componentId}->${b.componentId}`;i.has(w)||(i.add(w),c.push({fromComponentId:y.componentId,toComponentId:b.componentId,type:"semantic",weight:.4,confidence:.9}))}}let l=new Set(o.map(y=>y.componentId));for(let y of n.values()){if(!l.has(y.fromComponentId)||!l.has(y.toComponentId))continue;let p=`structural:${y.fromComponentId}->${y.toComponentId}`;i.has(p)||(i.add(p),c.push({fromComponentId:y.fromComponentId,toComponentId:y.toComponentId,type:"structural",weight:y.weight,confidence:1}))}let S=J(k(k({pageUrl:nt(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:o.map(y=>{let p=xo(y.semanticType);return{componentId:y.componentId,semanticType:p,answers:y.answers,contentHash:Io(y.componentId,p,y.answers),prominenceScore:y.prominenceScore,depthInPage:y.depth}}),edges:c});fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:k({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(S)}).catch(()=>{})}catch(g){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},destroy(){if(typeof window!="undefined")try{localStorage.removeItem(a),localStorage.removeItem(Jt)}catch(o){}}}}var Co=["data-sentient-id","data-testid","data-test","data-id","data-name","data-cy"];function ot(e){var t;return((t=e.textContent)!=null?t:"").replace(/\s+/g," ").trim()}function ko(e){return{tag:e.tagName.toLowerCase(),text:ot(e).slice(0,40)}}function Vt(e){return e.replace(/["\\\]]/g,"\\$&")}function Oe(e,t){try{return e.querySelectorAll(t).length===1}catch(n){return!1}}function Yt(e,t){var r;let n=e.tagName.toLowerCase();if(!n)return null;let a=((r=e.getAttribute("class"))!=null?r:"").split(/\s+/).filter(s=>/^[a-zA-Z][\w-]*$/.test(s)),d=[n,...a.map(s=>`${n}.${s}`)];for(let s of d)if(Oe(t,s))return s;let o=e.parentElement;if(o&&o!==t){let s=Yt(o,t);if(s){for(let l of d){let S=`${s} > ${l}`;if(Oe(t,S))return S}let g=Array.from(o.children).filter(l=>l.tagName.toLowerCase()===n),c=g.indexOf(e),i=g.some(l=>l!==e&&ot(l)!==ot(e));if(c>=0&&i){let l=`${s} > ${n}:nth-of-type(${c+1})`;if(Oe(t,l))return l}}}return null}function je(e,t){let n=ko(e),a=e.getAttribute("id");if(a&&Oe(t,`#${Vt(a)}`))return{v:1,id:a,fingerprint:n};for(let o of Co){let r=e.getAttribute(o);if(r&&Oe(t,`[${o}="${Vt(r)}"]`))return{v:1,dataAttr:{name:o,value:r},fingerprint:n}}let d=Yt(e,t);return d?{v:1,selector:d,fingerprint:n}:null}var en=["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"],To={banner:"hero",navigation:"navigation",contentinfo:"footer"};function _o(e){let t=e.ariaRole?To[e.ariaRole.toLowerCase()]:void 0;if(t)return t;if(e.tag==="nav")return"navigation";if(e.tag==="footer")return"footer";if(e.tag==="header")return e.actionCount>=5?"navigation":"hero";let n=`${e.idClass} ${e.headingText}`.toLowerCase();return/\b(navbar|nav-bar|navigation|site-nav|main-nav|topbar|footer)\b/.test(n)?/footer/.test(n)?"footer":"navigation":/\b(hero|masthead|jumbotron)\b/i.test(e.idClass)?"hero":null}function Ao(e){return e.actionCount>=1&&e.textLength>0&&e.textLength<200?"cta":"generic"}var Ro=[["pricing",/\b(pricing|price list|per month|\/mo|subscriptions?)\b|\bplans?\b(?=[^.]{0,40}(from|start|month|year|[$€£]))/i],["faq",/\bfaq\b|frequently asked|common questions?/i],["comparison",/\b(compare|comparison|versus)\b|\bvs\./i],["social_proof",/\b(reviews?|ratings?|testimonial|brands?|galler(y|ies)|logos)\b|trusted by|loved by|case stud|what our customers say/i],["trust",/\b(insurance|warrant(y|ies)|guarantees?|certifi|accredit|security|privacy|compliance|gdpr|encrypt)\b|why choose|about us|our team/i],["cta",/\b(book|booking|reserve|appointments?|newsletter|subscribe)\b|contact us|get in touch|opening hours/i],["features",/\b(features?|benefits?|capabilit|services?|repairs?|menus?|products?)\b|how it works|our process|what we (do|offer)|what you get/i]],Oo=[["pricing",/(?:[$€£]\s?\d[\d,.]*\s*(?:\/|per\s)\s*(?:mo|month|yr|year|seat|user))|(?:\b(?:starter|basic|pro|growth|premium|enterprise)\b[^.]{0,60}[$€£]\s?\d)/i],["social_proof",/(?:★{2,})|(?:\b\d(?:\.\d)?\s*(?:out of|\/)\s*5\b)|(?:\brated\b)|(?:["“][^"”]{20,160}["”]\s*[—–-]\s*[A-Z][a-z]+)/],["trust",/\b(?:money[- ]back guarantee|free returns?|returns? within|refund(?:s)? within|encrypted|soc ?2|iso ?27001|gdpr[- ]compliant|cancel anytime)\b/i],["comparison",/\b(?:vs|versus)\b\.?[^.!?]{0,80}\b(?:compare|comparison|plans?|features?|alternative)\b|\bhow (?:we|it) compares?\b/i]],Zt={navigation:"navigation",footer:"navigation",hero:"hero",cta:"cta",generic:"generic"};function Po(e){var n;let t=e.querySelector("h1, h2, h3");return((n=t==null?void 0:t.textContent)!=null?n:"").slice(0,160)}function Do(e){var d,o;let t=_o(e);if(t)return{type:(d=Zt[t])!=null?d:"generic",strength:"strong"};let n=`${e.idClass} ${e.headingText}`.toLowerCase();for(let[r,s]of Ro)if(s.test(n))return{type:r,strength:"strong"};for(let[r,s]of Oo)if(s.test(e.bodyText))return{type:r,strength:"strong"};let a=Ao(e);return{type:(o=Zt[a])!=null?o:"generic",strength:"weak"}}function Lo(e){var a,d;let t=((a=e.textContent)!=null?a:"").replace(/\s+/g," ").trim(),n=e.getAttribute("role");return k({tag:e.tagName.toLowerCase(),idClass:`${e.id} ${String((d=e.className)!=null?d:"")}`,headingText:Po(e),bodyText:t.slice(0,2e3),actionCount:e.querySelectorAll('a, button, [role="button"]').length,textLength:t.length},n?{ariaRole:n}:{})}function tn(e){return Do(Lo(e)).type}var No=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),Bo="h1, h2, h3",Mo="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",nn=30,Ko=1500,Go={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function on(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function $o(e){var t,n,a;try{let d=e;for(let o of Object.keys(d)){if(!o.startsWith("__reactFiber")&&!o.startsWith("__reactInternalInstance"))continue;let r=d[o],s=(a=(t=r==null?void 0:r.type)==null?void 0:t.displayName)!=null?a:(n=r==null?void 0:r.type)==null?void 0:n.name;if(s&&s.length>1)return s}}catch(d){}}function Uo(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var rt=new Set(en);function Fo(e,t){let n=e.getAttribute("data-sentient-id"),a=n?t==null?void 0:t[n]:void 0;if(a&&rt.has(a))return a;let d=e.getAttribute("data-sentient-type");if(d&&rt.has(d))return d;let o=e.getAttribute("role");return o&&rt.has(o)?o:tn(e)}function jo(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 Wo(e){let t=[],n=e;for(;n;){let a=n.parentElement;if(!a){t.push(n.tagName.toLowerCase());break}let d=Array.prototype.indexOf.call(a.children,n);t.push(`${n.tagName.toLowerCase()}[${d}]`),n=a}return t.reverse().join("/")}function zo(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${jo(Wo(e))}`}function qo(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function st(e,t,n){var d,o,r,s;let a=e.querySelector(Bo);return{componentId:zo(e),semanticType:Fo(e,n),ariaLabel:(d=e.getAttribute("aria-label"))!=null?d:void 0,headingText:(r=(o=a==null?void 0:a.textContent)==null?void 0:o.trim())!=null?r:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:qo(e),reactComponentName:$o(e),dataAttributes:Uo(e),locator:(s=je(e,e.ownerDocument))!=null?s:void 0}}function rn(e){var o;let t=[],n=new Set,a="__root__",d=new Map;for(let[r,s]of e){let g=r.parentElement,c=a;for(;g;){if(e.has(g)){c=e.get(g);let l=e.get(r),S=`${c}->${l}`;!n.has(S)&&c!==l&&(n.add(S),t.push({fromComponentId:c,toComponentId:l,weight:.6}));break}g=g.parentElement}let i=(o=d.get(c))!=null?o:[];i.push(r),d.set(c,i)}for(let r of d.values()){if(r.length<2)continue;let s=r.length>nn?r.slice(0,nn):r;for(let g=0;g<s.length;g++)for(let c=g+1;c<s.length;c++){if(t.length>=Ko)return t;let i=e.get(s[g]),l=e.get(s[c]);if(i===l)continue;let S=`${i}->${l}::sib`,y=`${l}->${i}::sib`;n.has(S)||(n.add(S),t.push({fromComponentId:i,toComponentId:l,weight:.3})),n.has(y)||(n.add(y),t.push({fromComponentId:l,toComponentId:i,weight:.3}))}}return t}function Ho(e,t){let n=[],a=new Set,d=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(s=>{if(s instanceof Element&&!a.has(s)){a.add(s);let g=st(s,e,t);n.push(g),d.set(s,g.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(s=>{if(!(s instanceof Element)||a.has(s))return;let g=s.hasAttribute("aria-label"),c=s.hasAttribute("data-sentient-id");if(!g&&!c)return;a.add(s);let i=st(s,e,t);n.push(i),d.set(s,i.componentId)}),{nodes:n,edges:rn(d),elementToId:d}}function sn(e={}){let{sectionTypes:t}=e;if(typeof window=="undefined")return Go;let n=null,a=0,d=null,o=new Map,r=i=>{try{let l=window.getComputedStyle(i),S=parseFloat(l.fontSize)||12,y=parseFloat(l.zIndex)||0,p=i.getBoundingClientRect(),f=Math.max(p.top,0),b=window.innerHeight||1,w=1/(f/b+1),R=on(S,12,48)*.4+w*.4+on(y,0,100)*.2;return Math.max(0,Math.min(1,R))}catch(l){return .5}};return{scan:()=>new Promise(i=>{let l=()=>{let{nodes:S,edges:y,elementToId:p}=Ho(r,t);o.clear();for(let[f,b]of p)o.set(f,b);i({nodes:S,edges:y,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?a=requestIdleCallback(l,{timeout:100}):l()}catch(S){l()}}),observe:i=>{d=i;try{n=new MutationObserver(l=>{let S=[],y=new Set;for(let f of l)f.type==="childList"&&f.addedNodes.forEach(b=>{if(!(b instanceof Element))return;let w=[];No.has(b.tagName)&&(b.hasAttribute("data-sentient-id")||b.hasAttribute("aria-label"))&&w.push(b);try{b.querySelectorAll(Mo).forEach(R=>w.push(R))}catch(R){}for(let R of w){if(o.has(R))continue;let K=st(R,r,t);S.push(K),y.add(K.componentId),o.set(R,K.componentId)}});if(S.length===0||!d)return;for(let f of[...o.keys()])f.isConnected||o.delete(f);let p=rn(o).filter(f=>y.has(f.fromComponentId)||y.has(f.toComponentId));d({nodes:S,edges:p,addedAt:Date.now()})}),n.observe(document.body,{childList:!0,subtree:!0})}catch(l){}},getProminenceScore:r,destroy:()=>{if(n&&(n.disconnect(),n=null),a&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(a)}catch(i){}a=0,d=null,o.clear()}}}var Xo="https://api.sentient-ui.com/v1/events";function Jo(e){var n;let t=a=>{try{let d=document.cookie.match(new RegExp(`(?:^|; )${a}=([^;]*)`));return d?decodeURIComponent(d[1]):void 0}catch(d){return}};return(n=e?t(pe(e)):void 0)!=null?n:t(Te)}var We=new Map;function an(e){var y;let t=tt(e),n=e.respectDoNotTrack!==!1&&Re(),a=e.consent===!1||n,d=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_"),o=e.localMode===!0||!d;if(!e.graph||o||typeof window=="undefined")return t;if(a)return n||zt(e.apiKey,p=>an(p)),t;let r=We.get(e.apiKey);if(r)try{r()}catch(p){}let s=sn({sectionTypes:e.sectionTypes}),g=(y=e.ingestUrl)!=null?y:Xo,c=Qt({syncUrl:g.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Jo(e.apiKey)});s.scan().then(p=>{for(let f of p.nodes)c.addPageNode({id:f.componentId,componentId:f.componentId,semanticType:f.semanticType,answers:e.captureDomText&&f.headingText?[f.headingText]:[],prominenceScore:f.prominenceScore,depth:f.depth});for(let f of p.edges)c.addStructuralEdge(f);c.syncOnce()});let i=null,l=()=>{i!==null&&clearTimeout(i),i=setTimeout(()=>{i=null,c.syncOnce()},500)};s.observe(p=>{for(let f of p.nodes)c.addPageNode({id:f.componentId,componentId:f.componentId,semanticType:f.semanticType,answers:e.captureDomText&&f.headingText?[f.headingText]:[],prominenceScore:f.prominenceScore,depth:f.depth});for(let f of p.edges)c.addStructuralEdge(f);l()});let S=()=>{i!==null&&(clearTimeout(i),i=null),s.destroy(),c.destroy(),We.get(e.apiKey)===S&&We.delete(e.apiKey)};return We.set(e.apiKey,S),J(k({},t),{getGraph:()=>c.snapshot(),dispose:()=>{S(),t.dispose()},destroy:()=>{S(),t.destroy()}})}0&&(module.exports={BLOCK_ALIGNS,BLOCK_EMPHASES,BLOCK_FITS,BLOCK_GAPS,BLOCK_GRID_COLUMNS,BLOCK_HEADING_LEVELS,BLOCK_JUSTIFIES,BLOCK_MAX_WIDTHS,BLOCK_PADS,BLOCK_RATIOS,BLOCK_SIZES,BLOCK_SURFACES,BLOCK_TEXT_ALIGNS,BLOCK_TONES,BLOCK_WEIGHTS,FORM_FIELD_KINDS,FORM_INPUT_TYPES,LEGACY_SESSION_COOKIE_NAME,MAX_BLOCK_ARMS,MAX_BLOCK_CHILDREN,MAX_BLOCK_DEPTH,MAX_BLOCK_NODES,MAX_BLOCK_TEXT_LEN,MAX_FORM_FIELDS,MAX_FORM_SELECT_OPTIONS,SNAPSHOT_STORAGE_KEY_PREFIX,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,containsFormBlock,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,locatorFromElement,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,sanitizePageUrl,sessionCookieName,toWireSlot,writeSnapshot});
|
|
2
2
|
//# sourceMappingURL=index-graph.js.map
|