@sentientui/core 0.29.1 → 0.30.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/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 +17 -1
- package/dist/index-graph.d.ts +17 -1
- 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/package.json +1 -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{I as Y,K as q}from"./chunk-HY23LTUY.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":"2OAOA,OAAS,SAAAA,MAAa,qBAqCtB,IAAMC,EAAmB,oEAOnBC,EAAe,IAerB,SAASC,GAAeC,EAA0B,CAChD,IAAMC,EAAa,MAAM,KAAKD,EAAI,iBAAiBH,CAAgB,CAAC,EAC9DK,EAAOD,EAAW,OACrBE,GAAOF,EAAW,OAAQ,GAAM,IAAME,GAAMA,EAAG,SAAS,CAAC,CAAC,EAAE,OAAS,CACxE,EACA,OAAOD,EAAK,OAAQC,GAAO,CAACD,EAAK,KAAME,GAAMA,IAAMD,GAAMC,EAAE,SAASD,CAAE,CAAC,CAAC,CAC1E,CAgBA,SAASE,GACPC,EACAC,EACAC,EACAC,EAOM,CACN,GAAI,CACG,MAAM,GAAGF,CAAO,kBAAmB,CACtC,OAAQ,OACR,UAAW,GACX,QAAS,CAAE,eAAgB,mBAAoB,cAAe,U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AAI,CAAEhB,EAAS,WAAW,CAAG,OAAQ,GAAe,CACtD,CACF","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":"2OAOA,OAAS,SAAAA,MAAa,qBA2CtB,IAAMC,GAAmB,oEAOnBC,GAAe,IAerB,SAASC,GAAeC,EAA0B,CAChD,IAAMC,EAAa,MAAM,KAAKD,EAAI,iBAAiBH,EAAgB,CAAC,EAC9DK,EAAOD,EAAW,OACrBE,GAAOF,EAAW,OAAQ,GAAM,IAAME,GAAMA,EAAG,SAAS,CAAC,CAAC,EAAE,OAAS,CACxE,EACA,OAAOD,EAAK,OAAQC,GAAO,CAACD,EAAK,KAAME,GAAMA,IAAMD,GAAMC,EAAE,SAASD,CAAE,CAAC,CAAC,CAC1E,CAgBA,SAASE,GACPC,EACAC,EACAC,EACAC,EAOM,CACN,GAAI,CACG,MAAM,GAAGF,CAAO,kBAAmB,CACtC,OAAQ,OACR,UAAW,GACX,QAAS,CAAE,eAAgB,mBAAoB,cAAe,UAAUD,CAAM,EAAG,EACjF,KAAM,KAAK,UAAU,CAAE,QAAAE,EAAS,SAAAC,CAAS,CAAC,CAC5C,CAAC,EAAE,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AoB,WAAYD,GACrC,QAAWQ,KAAKL,EAAkBK,EAAE,EACpC,GAAI,CAAEhB,EAAS,WAAW,CAAG,OAAQ,GAAe,CACtD,CACF","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
|
@@ -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
|
@@ -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 Jt=Object.create;var be=Object.defineProperty,Qt=Object.defineProperties,Vt=Object.getOwnPropertyDescriptor,Yt=Object.getOwnPropertyDescriptors,Zt=Object.getOwnPropertyNames,ut=Object.getOwnPropertySymbols,en=Object.getPrototypeOf,gt=Object.prototype.hasOwnProperty,tn=Object.prototype.propertyIsEnumerable;var pt=(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={}))gt.call(t,n)&&pt(e,n,t[n]);if(ut)for(var n of ut(t))tn.call(t,n)&&pt(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})},ft=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of Zt(t))!gt.call(e,d)&&d!==n&&be(e,d,{get:()=>t[d],enumerable:!(a=Vt(t,d))||a.enumerable});return e};var rn=(e,t,n)=>(n=e!=null?Jt(en(e)):{},ft(t||!e||!e.__esModule?be(n,"default",{value:e,enumerable:!0}):n,e)),on=e=>ft(be({},"__esModule",{value:!0}),e);var Nr={};nn(Nr,{BLOCK_ALIGNS:()=>Tn,BLOCK_EMPHASES:()=>Pn,BLOCK_FITS:()=>Nn,BLOCK_GAPS:()=>kn,BLOCK_GRID_COLUMNS:()=>Bn,BLOCK_HEADING_LEVELS:()=>Mn,BLOCK_JUSTIFIES:()=>_n,BLOCK_MAX_WIDTHS:()=>$n,BLOCK_PADS:()=>Gn,BLOCK_RATIOS:()=>Ln,BLOCK_SIZES:()=>An,BLOCK_SURFACES:()=>Kn,BLOCK_TEXT_ALIGNS:()=>Dn,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:()=>oe,armOfResult:()=>Le,attachMicroSignalDetectors:()=>Rt,baselineResultFor:()=>ge,baselineSlots:()=>Ct,containsFormBlock:()=>At,deriveSessionSegment:()=>We,detectDeviceClass:()=>ce,detectTimeOfDay:()=>ue,detectTrafficSource:()=>le,grantConsent:()=>Bt,init:()=>Xt,isDoNotTrackEnabled:()=>Ee,locatorFromElement:()=>Ke,readSnapshot:()=>fe,referrerDomainFromReferer:()=>de,renderPrePaintScript:()=>It,sanitizePageUrl:()=>Je,sessionCookieName:()=>ie,toWireSlot:()=>we,writeSnapshot:()=>me});module.exports=on(Nr);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 re(e){return e?`_${e.slice(0,12)}`:""}var ve="_snt_uid";function ie(e){return`${ve}${re(e)}`}var sn="_snt_uid",an=365,_e="_snt_uid";function cn(){return Te()}function mt(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(a){}}function $e(e){try{return localStorage.getItem(e)}catch(t){return null}}function yt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function ht(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 S,y,C,E,A,K,O;if(typeof window=="undefined")return mn;let t=re(e==null?void 0:e.apiKey),n=(S=e==null?void 0:e.cookieName)!=null?S:ie(e==null?void 0:e.apiKey),a=`${_e}${t}`,d=`${_e}_tomb${t}`,c=((y=e==null?void 0:e.cookieTTLDays)!=null?y:an)*24*60*60,i=D=>D&&D.length>0?D:null,u=()=>{var D,P;return t&&!(e!=null&&e.cookieName)&&$e(d)===null?(P=(D=i(mt(sn)))!=null?D:i($e(_e)))!=null?P:i(ht(_e)):null},l=(O=(K=(A=(E=(C=i(mt(n)))!=null?C:i($e(a)))!=null?E:i(ht(a)))!=null?A:u())!=null?K:i(e==null?void 0:e.ssrSessionId))!=null?O:cn();ln(n,l,c);let r=yt(a,l),s=pn(n),f=r?!1:dn(a,l),g=!r&&!s&&!f;return{getSessionId:()=>l,isEphemeral:()=>g,destroy:()=>{l=null,fn(n),gn(a),un(a),t&&!(e!=null&&e.cookieName)&&yt(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 a=JSON.parse(n);return Array.isArray(a)?(localStorage.removeItem(e),a.slice(-t)):[]}catch(n){return[]}}function Z(e,t,n){try{let a=(()=>{try{let o=localStorage.getItem(n);if(!o)return[];let c=JSON.parse(o);return Array.isArray(c)?c:[]}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 Oe(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(c=>!d.has(c.id));if(o.length===a.length)return;o.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(o))}catch(n){}}var yn=500,hn=56*1024;function Ue(e){return`_snt_retry_${e.slice(0,12)}`}var Sn={push:()=>{},flush:()=>{},destroy:()=>{}};function St(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,a=(ye=e.maxRetrySize)!=null?ye:100,d=e.ingestUrl,o=e.apiKey,c=Ue(o),i=[],u=new Set,l=[],r=v=>{for(let I of v)s.delete(I),!u.has(I)&&(u.add(I),l.push(I));for(;l.length>yn;){let I=l.shift();I&&u.delete(I)}Oe(v,c)},s=new Set,f=()=>{for(;i.length>a;){let v=i.shift();v&&s.delete(v.id)}},g=v=>{u.has(v.id)||s.has(v.id)||(s.add(v.id),i.push(v),f())},S=v=>{for(let I of v)u.has(I.id)||(s.add(I.id),i.push(I));f()},y=Re(c,a);for(let v of y)g(v);let C=0,E=0,A=(v,I=!0)=>{if(v.length===0)return;let J=JSON.stringify(v),G=v.map($=>$.id),z;try{z=fetch(d,{method:"POST",keepalive:!0,body:J,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`}})}catch($){Z(v,a,c),S(v),E++,C=Date.now()+Y(E);return}let Ie=$=>{if(ae($)!=="retry"){if(!$.ok&&I){let te=v.filter(F=>F.eventType!=="pageview");if(te.length>0&&te.length<v.length){r(v.filter(F=>F.eventType==="pageview").map(F=>F.id)),A(te,!1);return}}r(G),E=0,C=0;return}Z(v,a,c),S(v),E++,C=Date.now()+Y(E)};z instanceof Promise?z.then(Ie).catch(()=>{Z(v,a,c),S(v),E++,C=Date.now()+Y(E)}):Ie(z)},K=typeof TextEncoder!="undefined"?new TextEncoder:null,O=v=>K?K.encode(v).length:v.length,D=v=>{let I=[],J=2;for(let G of v){let z=O(JSON.stringify(G))+1;if(I.length>0&&J+z>hn||I.length>=n)break;I.push(G),J+=z}return I},P=()=>{try{if(Date.now()<C)return;for(;i.length>0&&!(Date.now()<C);){let v=i.filter(J=>!u.has(J.id));if(i.length=0,v.length===0)break;let I=D(v);if(I.length===0)break;I.length<v.length&&i.push(...v.slice(I.length)),A(I)}}catch(v){}},h=!0,L=null;L=setInterval(()=>{h&&P()},t);let j=()=>{document.visibilityState==="hidden"&&P()},W=()=>{P()};return document.addEventListener("visibilitychange",j),window.addEventListener("pagehide",W),{push(v){g(v),i.length>=n&&P()},flush:P,destroy(){h=!1,L!==null&&(clearInterval(L),L=null),document.removeEventListener("visibilitychange",j),window.removeEventListener("pagehide",W),P()}}}var bn=200;function Fe(e){return`_snt_goal_retry_${e.slice(0,12)}`}var vn={send:()=>{},flush:()=>{},destroy:()=>{}};function bt(e){var O,D,P;if(typeof window=="undefined")return vn;let t=(O=e.flushIntervalMs)!=null?O:5e3,n=(D=e.maxRetrySize)!=null?D:100,a=(P=e.maxPerFlush)!=null?P:5,d=Fe(e.apiKey),o=[],c=new Set,i=new Set,u=[],l=0,r=0,s=!1,f=h=>{for(c.delete(h.id),i.has(h.id)||(i.add(h.id),u.push(h.id));u.length>bn;){let L=u.shift();L&&i.delete(L)}Oe([h.id],d)},g=h=>{Z([h],n,d),!i.has(h.id)&&!c.has(h.id)&&(c.add(h.id),o.push(h)),Date.now()>=l&&(r++,l=Date.now()+Y(r))},S=h=>{let L;try{L=fetch(e.url,{method:"POST",keepalive:!0,body:h.body,headers:e.headers})}catch(W){g(h);return}let j=W=>{var ee;let X=ae(W);if(X==="retry"){g(h);return}X==="dropped"&&((ee=e.onDrop)==null||ee.call(e,h,W.status)),f(h),r=0,l=0};L instanceof Promise?L.then(j).catch(()=>g(h)):j(L)},y=()=>{try{if(s||Date.now()<l)return;let h=0;for(;o.length>0&&h<a&&!(Date.now()<l);){let L=o.shift();c.delete(L.id),!i.has(L.id)&&(h++,S(L))}}catch(h){}},C=Re(d,n);for(let h of C)c.has(h.id)||(c.add(h.id),o.push(h));C.length>0&&Z(C,n,d);let E=setInterval(y,t),A=()=>{document.visibilityState==="hidden"&&y()},K=()=>y();return document.addEventListener("visibilitychange",A),window.addEventListener("pagehide",K),{send(h){if(!s&&!(i.has(h.id)||c.has(h.id))){if(Date.now()<l){Z([h],n,d),c.add(h.id),o.push(h);return}S(h)}},flush:y,destroy(){clearInterval(E),document.removeEventListener("visibilitychange",A),window.removeEventListener("pagehide",K),y(),s=!0}}}var wn=1800*1e3;function Pe(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function vt(e=wn,t){let n=new Map,a=`_snt_asgn${re(t)}_`,d=(l,r)=>`${a}${encodeURIComponent(l)}:${encodeURIComponent(r)}`,o=l=>{let r=l.slice(a.length),s=r.indexOf(":");if(s<0)return null;try{return{componentId:decodeURIComponent(r.slice(0,s)),segment:decodeURIComponent(r.slice(s+1))}}catch(f){return null}},c=()=>{try{let l=[];for(let r=0;r<localStorage.length;r++){let s=localStorage.key(r);s!=null&&s.startsWith(a)&&l.push(s)}return l}catch(l){return[]}},i=l=>l.assignedAt+(l.ttlMs&&l.ttlMs>0?l.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let l of c())try{let r=localStorage.getItem(l);if(!r)continue;let s=JSON.parse(r);if(i(s)){localStorage.removeItem(l);continue}let f=o(l);if(!f)continue;n.set(Pe(f.componentId,f.segment),s)}catch(r){}})(),{get(l,r){let s=n.get(Pe(l,r));return s?i(s)?(n.delete(Pe(l,r)),null):s:null},set(l,r,s){let f=Pe(l,r);n.set(f,s);try{localStorage.setItem(d(l,r),JSON.stringify(s))}catch(g){}},clear(){n.clear();for(let l of c())try{localStorage.removeItem(l)}catch(r){}}}}var wt=["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 De(e){return xt(e)!==null}function xt(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=wt.find(a=>t.includes(a.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 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 de(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var Et=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function je(e){let t={},n={};try{let a=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([d,o])=>{let c=Array.isArray(o)?o[0]:o;return c===void 0?[]:[[d,c]]});for(let[d,o]of a)d.startsWith("utm_")?d in t||(t[d]=o):Et.includes(d)&&(d in n||(n[d]=o))}catch(a){}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 o,c,i,u,l,r,s,f;let n=(c=(o=t==null?void 0:t.userAgent)==null?void 0:o.trim())!=null?c:"",a=(u=(i=t==null?void 0:t.referer)==null?void 0:i.trim())!=null?u:"",d=(l=t==null?void 0:t.now)!=null?l:new Date;return{sessionId:e,ephemeral:!1,utmParams:(r=t==null?void 0:t.utmParams)!=null?r:{},clickIds:(s=t==null?void 0:t.clickIds)!=null?s:{},deviceClass:n?ce(n):"desktop",trafficSource:a?le(a,t==null?void 0:t.appOrigin):"direct",referrerDomain:de(a),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||De(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 Ct(e){let t={};for(let n of e)t[n.id]=ge(n);return t}function Le(e){return typeof e=="string"?e:(0,pe.canonicalArm)(e)}var oe="_snt_snap:",En=["low","medium","high"];function fe(e){try{let t=localStorage.getItem(oe+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!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(oe+e,JSON.stringify(t))}catch(n){}}function It(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(oe+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 kt="[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.",Tt=!1,Ne=!1;function In(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function _t(e){var l;let t=Ae({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(l=t.getSessionId())!=null?l:"local",a=In(),d=import("@sentientui/core/local").then(r=>{let s=r;return s.LOCAL_ENGINE_AVAILABLE?(Tt||(Tt=!0,console.info(Cn)),s):(Ne||(Ne=!0,console.error(kt)),null)}).catch(()=>(Ne||(Ne=!0,console.error(kt)),null)),o=null,c={low:.15,medium:.5,high:.85},i=(()=>{var s;if(e.initialPersona)return x({},e.initialPersona);let r=fe(e.apiKey||"local");return r?{persona:r.persona,confidence:(s=c[r.band])!=null?s:.15}:null})();function u(r){let s=document.documentElement;s.dataset.sentientPersona===void 0&&(s.dataset.sentientPersona=r.persona,s.dataset.sentientConfidence=(0,Be.confidenceBand)(r.confidence))}return{isLocal:!0,async decide(r){var g,S,y;let s=await d;if(!s)return null;let f=s.createLocalEngine({sessionId:n,forcedPersona:a}).decide(r);return o=q(x({},f),{layoutOrder:(S=(g=f.layoutOrder)!=null?g:o==null?void 0:o.layoutOrder)!=null?S:null,slots:x(x({},(y=o==null?void 0:o.slots)!=null?y:{}),f.slots)}),me(e.apiKey||"local",{v:1,persona:o.persona,band:(0,Be.confidenceBand)(o.confidence),slots:o.slots,layoutOrder:o.layoutOrder,savedAt:Date.now()}),u(f),f},getSlotResult(r){var s,f,g;return(g=(f=o==null?void 0:o.slots[r])!=null?f:(s=e.initialSlots)==null?void 0:s[r])!=null?g:null},getSlotConfig(r){var s,f;return(f=(s=e.initialSlotConfig)==null?void 0:s[r])!=null?f:null},getSitePalette(){var r;return(r=e.initialPalette)!=null?r:null},reportSlots(){},getPersona(){let r=o!=null?o:i;return r?{persona:r.persona,confidence:r.confidence,band:(0,Be.confidenceBand)(r.confidence)}:null},async assign(r,s){var S;let f=await d;return!f||!s||s.length===0?s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null:{variantId:(S=f.createLocalEngine({sessionId:n,forcedPersona:a}).decide({components:[{id:r,variantIds:s}]}).assignments[r])!=null?S:s[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"],Dn=["left","center","right"],Ln=["auto","square","landscape","wide"],Nn=["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 At(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(At):!1}function Rt(e,t,n,a){let d=[];{let i=!1,u=[],l=()=>{if(i)return;let r=Date.now();for(u.push(r);u.length>0&&r-u[0]>500;)u.shift();u.length>=3&&(i=!0,e("rage_click"))};t.addEventListener("click",l),d.push(()=>t.removeEventListener("click",l))}{let o=!1,c=i=>{if(o||!(i.target instanceof Node)||!t.contains(i.target)&&t!==i.target)return;o=!0;let u=typeof window!="undefined"?window.getSelection():null,l=u?u.toString().length:0;e("text_copy",{selectionLength:l})};document.addEventListener("copy",c),d.push(()=>document.removeEventListener("copy",c))}{let o=!1,c=!1,i=null,u=()=>{i!==null&&(clearTimeout(i),i=null)},l=()=>{o||!c||(u(),i=setTimeout(()=>{!o&&c&&(o=!0,e("scroll_hesitation"))},3e3))},r=()=>{u(),l()},s=g=>{for(let S of g)c=S.intersectionRatio>.3,c?l():u()},f=new IntersectionObserver(s,{threshold:[.3]});f.observe(t),window.addEventListener("scroll",r,{passive:!0}),d.push(()=>{f.disconnect(),window.removeEventListener("scroll",r),u()})}if((a==null?void 0:a.tabLoss)!==!1){let o=!1,c=n!=null?n:Date.now(),i=()=>{if(o||document.visibilityState!=="hidden")return;let u=Date.now()-c;u<15e3&&(o=!0,e("tab_loss",{timeOnPage:u}))};document.addEventListener("visibilitychange",i),d.push(()=>document.removeEventListener("visibilitychange",i))}return()=>{for(let o of d)o()}}function Qn(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var Ot="https://api.sentient-ui.com/v1/events",U=new Map,Pt=null;function Dt(e,t){let n=U.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,a=(i,u,l)=>{let r=i.get(u);return l===null?r?!0:(i.set(u,new Set),!1):r?r.has(l)?!0:(r.add(l),!1):(i.set(u,new Set([l])),!1)},d=typeof window!="undefined"&&"event"in window,o=()=>{if(!d)return;let i=window.event;return typeof Event=="function"&&i instanceof Event?i:void 0},c=()=>{if(d){Promise.resolve().then(()=>{n=!1,t.clear()});return}let i=!1,u=()=>{i||(i=!0,n=!1,t.clear())};if(setTimeout(u,0),typeof MessageChannel=="function"){let l=new MessageChannel;l.port1.onmessage=()=>{l.port1.close(),l.port2.close(),u()},l.port2.postMessage(0)}};return{firedBefore(i,u){let l=o();if(l){let s=e.get(l);return s||(s=new Map,e.set(l,s)),a(s,i,u)}let r=a(t,i,u);return!r&&!n&&(n=!0,c()),r}}}var Lt=new Set;function er(e,t,n){let a=typeof window=="undefined"?null:window.history;if(!a)return()=>{};let d=!1,o,c=()=>{if(d)return;let l=Me();!l||l===o||(o=l,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${l}`))},i=[];for(let l of["pushState","replaceState"]){let r=a[l],s=function(...f){let g=r.apply(this,f);return c(),g};a[l]=s,i.push([l,r,s])}window.addEventListener("popstate",c);let u=Me();return u&&Lt.has(`${t}:${u}`)?o=u:c(),()=>{if(!d){d=!0,window.removeEventListener("popstate",c);for(let[l,r,s]of i)a[l]===s&&(a[l]=r)}}}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 tr(){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 Bt(e){var u;if(typeof window=="undefined")return;let t=e!=null?e:Pt;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=U.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&&Ee())return;let c=(o!=null?o:Xe)(q(x({},a),{consent:!0}));d(c);let i=(u=U.get(t))==null?void 0:u.dispose;U.set(t,{config:q(x({},a),{consent:!0}),upgrade:null,dispose:i})}function nr(e){var l;let t=e.preConsentBehavior==="statistical_winner",n=Nt((l=e.ingestUrl)!=null?l:Ot),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d=new Map,o=new Map,c={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(r,s,f){if(!t)return Promise.resolve(null);let g=d.get(r);return g?Promise.resolve(g):qe(o,r,async()=>{try{let S=new URLSearchParams({componentId:r});for(let A of s!=null?s:[])S.append("variantIds[]",A);let y=await fetch(`${n}/winner?${S.toString()}`,{headers:a});if(!y.ok)return s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null;let E={variantId:(await y.json()).variantId,assignmentTtlMs:0};return d.set(r,E),E}catch(S){return s!=null&&s[0]?{variantId:s[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},i={track:r=>c.track(r),goal:((r,s,f,g)=>c.goal(r,s,f,g)),componentGoal:(r,s,f)=>c.componentGoal(r,s,f),identify:r=>c.identify(r),getAssignment:(r,s)=>c.getAssignment(r,s),assign:(r,s,f,g)=>c.assign(r,s,f,g),decide:r=>c.decide(r),getSlotResult:r=>c.getSlotResult(r),getSlotConfig:r=>c.getSlotConfig(r),getSitePalette:()=>c.getSitePalette(),reportSlots:(r,s)=>c.reportSlots(r,s),getPersona:()=>c.getPersona(),fetchWeights:()=>c.fetchWeights(),getGraph:()=>c.getGraph(),dispose:()=>c.dispose(),destroy:()=>c.destroy()};function u(r){c=r}return{proxy:i,setInner:u}}function qe(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 Xe(e){var Ze,et,tt,nt,rt,ot,st,it,at,ct;if(typeof window=="undefined")return xe;Pt=e.apiKey||"local";let t=U.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(p){}let n=e.respectDoNotTrack!==!1&&Ee(),a=e.consent===!1||n,d=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!d&&e.localMode!==!1)return U.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?xe:_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."),U.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:p,setInner:m}=nr(e);return U.set(e.apiKey,{config:e,upgrade:n?null:m}),p}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 o=(Ze=e.ingestUrl)!=null?Ze:Ot,c=Date.now(),i=Ae({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),u=vt(void 0,e.apiKey),l=St({ingestUrl:o,apiKey:e.apiKey}),r=Nt(o),s={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},f=new Set,g=bt({url:`${r}/goals`,apiKey:e.apiKey,headers:s,onDrop:(p,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."),p)}}),S=ce((et=navigator.userAgent)!=null?et:""),y=window.location.origin,C=le((tt=document.referrer)!=null?tt:"",y),E=(nt=e.sessionSegment)!=null?nt:`${S}:${C}`,A=new Map,K=new Map,O=new Map,D=new Map,P=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=p=>{for(let m of p)O.has(m.id)||O.set(m.id,ge(m))};if(e.initialSlots)for(let[p,m]of Object.entries(e.initialSlots))O.set(p,m);if(e.initialSlotConfig)for(let[p,m]of Object.entries(e.initialSlotConfig))D.set(p,m);e.initialPalette&&(P=e.initialPalette);let I=fe(e.apiKey);if(I){for(let[p,m]of Object.entries(I.slots))O.has(p)||O.set(p,m);for(let[p,m]of Object.entries((rt=I.slotConfig)!=null?rt:{}))D.has(p)||D.set(p,m);!P&&I.palette&&(P=I.palette)}let J={low:.15,medium:.5,high:.85};if(e.initialPersona)h=x({},e.initialPersona);else{let p=document.documentElement.dataset;p.sentientPersona?h={persona:p.sentientPersona,confidence:(st=J[(ot=p.sentientConfidence)!=null?ot:"low"])!=null?st:.15}:I&&(h={persona:I.persona,confidence:(it=J[I.band])!=null?it:.15})}if(e.initialAssignments)for(let[p,m]of Object.entries(e.initialAssignments))u.set(p,E,{variantId:m,assignedAt:Date.now(),segment:E,confidence:1});let G=Promise.resolve(),z=i.getSessionId();if(z){let p=de((at=document.referrer)!=null?at:""),{utmParams:m,clickIds:b}=tr(),k=x(x(x(x({sessionId:z,deviceClass:S,trafficSource:C,referrerDomain:p,utmParams:m,clickIds:b,timeOfDay:ue(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:i.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||De((ct=navigator.userAgent)!=null?ct:"")},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}:{}),R=async()=>{for(let w=0;;w++){try{let _=await fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(k),headers:s});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{G=R()}catch(w){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:l});let Ie=Zn(),$=null,te=!1,F={goal(p,m={},b=1,k=0){var he,Se,se,T,Q,ke,N;let R=i.getSessionId();if(!R)return;let w=Vn(m)?m:{metadata:m},_=[p,(he=w.externalId)!=null?he:"",(Se=w.stepIndex)!=null?Se:k,(se=w.weight)!=null?se:b].join("\0"),B=w.value!==void 0?`${w.value}\0${(T=w.currency)!=null?T:""}`:null;if(Ie.firedBefore(_,B)){e.debug&&console.log(`[sentient] goal("${p}") already recorded for this action \u2014 not sent twice`);return}let M=ze(),V={sessionId:R,name:p,metadata:(Q=w.metadata)!=null?Q:{},weight:(ke=w.weight)!=null?ke:b,stepIndex:(N=w.stepIndex)!=null?N:k,goalId:M,value:w.value,currency:w.currency,externalId:w.externalId};e.debug&&console.log("[sentient] goal",V);let ne={id:M,body:JSON.stringify(V)};G.then(()=>g.send(ne))},componentGoal(p,m,b){var M,V,ne;let k=i.getSessionId();if(!k)return;let R=u.get(p,E),w=R?null:(M=O.get(p))!=null?M:null;if(!R&&w===null){e.debug&&console.warn(`[sentient] componentGoal("${p}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let _=R?R.variantId:Le(w),B={id:ze(),sessionId:k,projectId:e.apiKey,componentId:p,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()-c,path:Me()};e.debug&&console.log("[sentient] componentGoal",B),G.then(()=>l.push(B))},identify(p){let m=i.getSessionId();m&&G.then(()=>{fetch(`${r}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:m,userId:p,ephemeral:i.isEphemeral()}),headers:s}).catch(()=>{})})},track(p){let m=i.getSessionId();if(!m)return;let b=q(x({path:Me()},p),{id:ze(),sessionId:m,timestamp:Date.now(),timeInSession:Date.now()-c});e.debug&&console.log("[sentient] track",b),G.then(()=>l.push(b))},getAssignment(p,m){return u.get(p,m)},async assign(p,m,b,k){let R=i.getSessionId();if(!R)return null;let w=u.get(p,E);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(A,p,async()=>{await G;try{let _={sessionId:R,componentId:p,variantIds:m};k!==void 0?_.agentDataByVariant=k:b!==void 0&&(_.agentData=b);let B=await fetch(`${r}/assign`,{method:"POST",body:JSON.stringify(_),headers:s});if(!B.ok)return null;let M=await B.json();return u.set(p,E,x({variantId:M.variantId,assignedAt:Date.now(),segment:E,confidence:1,content:M.content},M.assignmentTtlMs&&M.assignmentTtlMs>0?{ttlMs:M.assignmentTtlMs}:{})),M}catch(_){return null}})},async decide(p){var w,_;let m=i.getSessionId();if(!m)return null;let b=(w=p.slots)!=null?w:[],k={sessionId:m};p.sections&&p.sections.length>0&&(k.sections=p.sections.map(B=>({id:B}))),k.components=(_=p.components)!=null?_:[],b.length>0&&(k.slots=b.map(we)),p.slotsFrom==="registry"&&(k.slotsFrom="registry"),p.v&&(k.v=p.v),typeof p.pp=="number"&&(k.pp=p.pp),e.persona&&(k.persona=e.persona);let R=JSON.stringify(k);return qe(K,R,async()=>{var B,M,V,ne,he,Se;await G;try{let se=await fetch(`${r}/decide`,{method:"POST",body:R,headers:s});if(!se.ok)return v(b),null;let T=await se.json(),Q={};for(let N of b){let H=(B=T.slots)==null?void 0:B[N.id];if(H!==void 0){Q[N.id]=H,O.set(N.id,H);continue}let lt=O.get(N.id);if(lt!==void 0)Q[N.id]=lt;else{let dt=ge(N);Q[N.id]=dt,O.set(N.id,dt)}}if(T.slots)for(let[N,H]of Object.entries(T.slots))N in Q||(Q[N]=H,O.set(N,H));let ke=h!=null&&h.persona!=="unknown";T.persona&&!(T.persona==="unknown"&&ke)?h={persona:T.persona,confidence:(M=T.confidence)!=null?M:0}:h||(h={persona:"unknown",confidence:0});for(let[N,H]of Object.entries((V=T.assignments)!=null?V:{}))u.set(N,E,{variantId:H,assignedAt:Date.now(),segment:E,confidence:1});if(T.slotConfig)for(let[N,H]of Object.entries(T.slotConfig))D.set(N,H);return T.palette&&(P=T.palette),me(e.apiKey,x(x({v:1,persona:h.persona,band:(0,He.confidenceBand)(h.confidence),slots:Object.fromEntries(O),layoutOrder:(ne=T.layoutOrder)!=null?ne:null,savedAt:Date.now()},D.size>0?{slotConfig:Object.fromEntries(D)}:{}),P?{palette:P}:{})),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(p){var m;return(m=O.get(p))!=null?m:null},getSlotConfig(p){var m;return(m=D.get(p))!=null?m:null},reportSlots(p,m){for(let b of p)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 R=k.replace(/\s+/g," ").trim().slice(0,400);R!==""&&W.set(b,R)}}}j.size===0||X!=null||(X=setTimeout(()=>{X=null;let b=[...j];j.clear();for(let k=0;k<b.length;k+=20){let R=b.slice(k,k+20),w={};for(let _ of R){let B=W.get(_);B!==void 0&&(w[_]=B,W.delete(_))}fetch(`${r}/slots/observed`,{method:"POST",headers:s,body:JSON.stringify(x({slotIds:R},Object.keys(w).length>0?{baselineTexts:w}:{}))}).catch(()=>{})}},1e3))},getSitePalette(){return P},getPersona(){return h?{persona:h.persona,confidence:h.confidence,band:(0,He.confidenceBand)(h.confidence)}:null},async fetchWeights(){var p;try{let m=await fetch(`${r}/weights`,{headers:s});return m.ok?(p=(await m.json()).components)!=null?p:[]:[]}catch(m){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var p;$==null||$(),te=!0,l.destroy(),g.destroy(),((p=U.get(e.apiKey))==null?void 0:p.dispose)===F.dispose&&U.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var p;$==null||$(),te=!0,l.destroy(),g.destroy(),i.destroy(),u.clear(),((p=U.get(e.apiKey))==null?void 0:p.dispose)===F.dispose&&U.delete(e.apiKey);try{localStorage.removeItem(oe+e.apiKey),localStorage.removeItem(Ue(e.apiKey)),localStorage.removeItem(Fe(e.apiKey))}catch(m){}e.debug&&console.log("[sentient] destroyed")}};if(U.set(e.apiKey,{config:e,upgrade:null,dispose:F.dispose}),$=er(F,e.apiKey,p=>{G.then(()=>{te||Lt.add(p)})}),e.debug){let p=window;p.__sentient&&(p.__sentient.client=F)}return F}var Mt="_snt_graph_edges",rr={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function or(e){var t;return(t=rr[e])!=null?t:[]}function sr(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function ir(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var ar=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function cr(e){return ar.has(e)?e:"generic"}function Je(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch(t){return"/"}}function lr(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 Kt(e){let t=new Map,n=new Map,a=`_snt_graph_nodes${re(e==null?void 0:e.apiKey)}`,d=()=>{typeof window!="undefined"&&ir(a,[...t.values()])};if(typeof window!="undefined"){let o=sr(a,[]);for(let c of o)t.set(c.componentId,c);try{localStorage.removeItem(Mt)}catch(c){}}return{addPageNode(o){t.set(o.componentId,o),d()},addStructuralEdge(o){let c=`${o.fromComponentId}->${o.toComponentId}`;n.set(c,o)},syncOnce(){var c,i;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let o=[...t.values()];if(o.length!==0)try{let u=new Map;for(let g of o){let S=(c=u.get(g.semanticType))!=null?c:[];S.push(g),u.set(g.semanticType,S)}let l=[],r=new Set;for(let g of o)for(let S of or(g.semanticType)){let y=(i=u.get(S))!=null?i:[];for(let C of y){if(C.componentId===g.componentId)continue;let E=`semantic:${g.componentId}->${C.componentId}`;r.has(E)||(r.add(E),l.push({fromComponentId:g.componentId,toComponentId:C.componentId,type:"semantic",weight:.4,confidence:.9}))}}let s=new Set(o.map(g=>g.componentId));for(let g of n.values()){if(!s.has(g.fromComponentId)||!s.has(g.toComponentId))continue;let S=`structural:${g.fromComponentId}->${g.toComponentId}`;r.has(S)||(r.add(S),l.push({fromComponentId:g.fromComponentId,toComponentId:g.toComponentId,type:"structural",weight:g.weight,confidence:1}))}let f=q(x(x({pageUrl:Je(window.location.href)},e.sessionId?{sessionId:e.sessionId}:{}),e.projectId?{projectId:e.projectId}:{}),{nodes:o.map(g=>{let S=cr(g.semanticType);return{componentId:g.componentId,semanticType:S,answers:g.answers,contentHash:lr(g.componentId,S,g.answers),prominenceScore:g.prominenceScore,depthInPage:g.depth}}),edges:l});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(a),localStorage.removeItem(Mt)}catch(o){}}}}var dr=["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 ur(e){return{tag:e.tagName.toLowerCase(),text:Qe(e).slice(0,40)}}function Gt(e){return e.replace(/["\\\]]/g,"\\$&")}function Ce(e,t){try{return e.querySelectorAll(t).length===1}catch(n){return!1}}function $t(e,t){var c;let n=e.tagName.toLowerCase();if(!n)return null;let a=((c=e.getAttribute("class"))!=null?c:"").split(/\s+/).filter(i=>/^[a-zA-Z][\w-]*$/.test(i)),d=[n,...a.map(i=>`${n}.${i}`)];for(let i of d)if(Ce(t,i))return i;let o=e.parentElement;if(o&&o!==t){let i=$t(o,t);if(i){for(let s of d){let f=`${i} > ${s}`;if(Ce(t,f))return f}let u=Array.from(o.children).filter(s=>s.tagName.toLowerCase()===n),l=u.indexOf(e),r=u.some(s=>s!==e&&Qe(s)!==Qe(e));if(l>=0&&r){let s=`${i} > ${n}:nth-of-type(${l+1})`;if(Ce(t,s))return s}}}return null}function Ke(e,t){let n=ur(e),a=e.getAttribute("id");if(a&&Ce(t,`#${Gt(a)}`))return{v:1,id:a,fingerprint:n};for(let o of dr){let c=e.getAttribute(o);if(c&&Ce(t,`[${o}="${Gt(c)}"]`))return{v:1,dataAttr:{name:o,value:c},fingerprint:n}}let d=$t(e,t);return d?{v:1,selector:d,fingerprint:n}:null}var Ft=["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"],pr={banner:"hero",navigation:"navigation",contentinfo:"footer"};function gr(e){let t=e.ariaRole?pr[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 fr(e){return e.actionCount>=1&&e.textLength>0&&e.textLength<200?"cta":"generic"}var mr=[["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]],yr=[["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]],Ut={navigation:"navigation",footer:"navigation",hero:"hero",cta:"cta",generic:"generic"};function hr(e){var n;let t=e.querySelector("h1, h2, h3");return((n=t==null?void 0:t.textContent)!=null?n:"").slice(0,160)}function Sr(e){var d,o;let t=gr(e);if(t)return{type:(d=Ut[t])!=null?d:"generic",strength:"strong"};let n=`${e.idClass} ${e.headingText}`.toLowerCase();for(let[c,i]of mr)if(i.test(n))return{type:c,strength:"strong"};for(let[c,i]of yr)if(i.test(e.bodyText))return{type:c,strength:"strong"};let a=fr(e);return{type:(o=Ut[a])!=null?o:"generic",strength:"weak"}}function br(e){var a,d;let t=((a=e.textContent)!=null?a:"").replace(/\s+/g," ").trim(),n=e.getAttribute("role");return x({tag:e.tagName.toLowerCase(),idClass:`${e.id} ${String((d=e.className)!=null?d:"")}`,headingText:hr(e),bodyText:t.slice(0,2e3),actionCount:e.querySelectorAll('a, button, [role="button"]').length,textLength:t.length},n?{ariaRole:n}:{})}function jt(e){return Sr(br(e)).type}var vr=new Set(["SECTION","ARTICLE","MAIN","DIV","ASIDE"]),wr="h1, h2, h3",xr="[data-sentient-id], section[aria-label], article[aria-label], main[aria-label], aside[aria-label]",Wt=30,Er=1500,Cr={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function zt(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function Ir(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 c=d[o],i=(a=(t=c==null?void 0:c.type)==null?void 0:t.displayName)!=null?a:(n=c==null?void 0:c.type)==null?void 0:n.name;if(i&&i.length>1)return i}}catch(d){}}function kr(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var Ve=new Set(Ft);function Tr(e,t){let n=e.getAttribute("data-sentient-id"),a=n?t==null?void 0:t[n]:void 0;if(a&&Ve.has(a))return a;let d=e.getAttribute("data-sentient-type");if(d&&Ve.has(d))return d;let o=e.getAttribute("role");return o&&Ve.has(o)?o:jt(e)}function _r(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 Ar(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 Rr(e){var n;let t=(n=e.getAttribute("data-sentient-id"))!=null?n:e.getAttribute("id");return t||`${e.tagName.toLowerCase()}-${_r(Ar(e))}`}function Or(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function Ye(e,t,n){var d,o,c,i;let a=e.querySelector(wr);return{componentId:Rr(e),semanticType:Tr(e,n),ariaLabel:(d=e.getAttribute("aria-label"))!=null?d:void 0,headingText:(c=(o=a==null?void 0:a.textContent)==null?void 0:o.trim())!=null?c:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Or(e),reactComponentName:Ir(e),dataAttributes:kr(e),locator:(i=Ke(e,e.ownerDocument))!=null?i:void 0}}function Ht(e){var o;let t=[],n=new Set,a="__root__",d=new Map;for(let[c,i]of e){let u=c.parentElement,l=a;for(;u;){if(e.has(u)){l=e.get(u);let s=e.get(c),f=`${l}->${s}`;!n.has(f)&&l!==s&&(n.add(f),t.push({fromComponentId:l,toComponentId:s,weight:.6}));break}u=u.parentElement}let r=(o=d.get(l))!=null?o:[];r.push(c),d.set(l,r)}for(let c of d.values()){if(c.length<2)continue;let i=c.length>Wt?c.slice(0,Wt):c;for(let u=0;u<i.length;u++)for(let l=u+1;l<i.length;l++){if(t.length>=Er)return t;let r=e.get(i[u]),s=e.get(i[l]);if(r===s)continue;let f=`${r}->${s}::sib`,g=`${s}->${r}::sib`;n.has(f)||(n.add(f),t.push({fromComponentId:r,toComponentId:s,weight:.3})),n.has(g)||(n.add(g),t.push({fromComponentId:s,toComponentId:r,weight:.3}))}}return t}function Pr(e,t){let n=[],a=new Set,d=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(i=>{if(i instanceof Element&&!a.has(i)){a.add(i);let u=Ye(i,e,t);n.push(u),d.set(i,u.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(i=>{if(!(i instanceof Element)||a.has(i))return;let u=i.hasAttribute("aria-label"),l=i.hasAttribute("data-sentient-id");if(!u&&!l)return;a.add(i);let r=Ye(i,e,t);n.push(r),d.set(i,r.componentId)}),{nodes:n,edges:Ht(d),elementToId:d}}function qt(e={}){let{sectionTypes:t}=e;if(typeof window=="undefined")return Cr;let n=null,a=0,d=null,o=new Map,c=r=>{try{let s=window.getComputedStyle(r),f=parseFloat(s.fontSize)||12,g=parseFloat(s.zIndex)||0,S=r.getBoundingClientRect(),y=Math.max(S.top,0),C=window.innerHeight||1,E=1/(y/C+1),A=zt(f,12,48)*.4+E*.4+zt(g,0,100)*.2;return Math.max(0,Math.min(1,A))}catch(s){return .5}};return{scan:()=>new Promise(r=>{let s=()=>{let{nodes:f,edges:g,elementToId:S}=Pr(c,t);o.clear();for(let[y,C]of S)o.set(y,C);r({nodes:f,edges:g,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?a=requestIdleCallback(s,{timeout:100}):s()}catch(f){s()}}),observe:r=>{d=r;try{n=new MutationObserver(s=>{let f=[],g=new Set;for(let y of s)y.type==="childList"&&y.addedNodes.forEach(C=>{if(!(C instanceof Element))return;let E=[];vr.has(C.tagName)&&(C.hasAttribute("data-sentient-id")||C.hasAttribute("aria-label"))&&E.push(C);try{C.querySelectorAll(xr).forEach(A=>E.push(A))}catch(A){}for(let A of E){if(o.has(A))continue;let K=Ye(A,c,t);f.push(K),g.add(K.componentId),o.set(A,K.componentId)}});if(f.length===0||!d)return;for(let y of[...o.keys()])y.isConnected||o.delete(y);let S=Ht(o).filter(y=>g.has(y.fromComponentId)||g.has(y.toComponentId));d({nodes:f,edges:S,addedAt:Date.now()})}),n.observe(document.body,{childList:!0,subtree:!0})}catch(s){}},getProminenceScore:c,destroy:()=>{if(n&&(n.disconnect(),n=null),a&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(a)}catch(r){}a=0,d=null,o.clear()}}}var Dr="https://api.sentient-ui.com/v1/events";function Lr(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(ie(e)):void 0)!=null?n:t(ve)}var Ge=new Map;function Xt(e){var g;let t=Xe(e),n=e.respectDoNotTrack!==!1&&Ee(),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||Dt(e.apiKey,S=>Xt(S)),t;let c=Ge.get(e.apiKey);if(c)try{c()}catch(S){}let i=qt({sectionTypes:e.sectionTypes}),u=(g=e.ingestUrl)!=null?g:Dr,l=Kt({syncUrl:u.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:Lr(e.apiKey)});i.scan().then(S=>{for(let y of S.nodes)l.addPageNode({id:y.componentId,componentId:y.componentId,semanticType:y.semanticType,answers:e.captureDomText&&y.headingText?[y.headingText]:[],prominenceScore:y.prominenceScore,depth:y.depth});for(let y of S.edges)l.addStructuralEdge(y);l.syncOnce()});let r=null,s=()=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{r=null,l.syncOnce()},500)};i.observe(S=>{for(let y of S.nodes)l.addPageNode({id:y.componentId,componentId:y.componentId,semanticType:y.semanticType,answers:e.captureDomText&&y.headingText?[y.headingText]:[],prominenceScore:y.prominenceScore,depth:y.depth});for(let y of S.edges)l.addStructuralEdge(y);s()});let f=()=>{r!==null&&(clearTimeout(r),r=null),i.destroy(),l.destroy(),Ge.get(e.apiKey)===f&&Ge.delete(e.apiKey)};return Ge.set(e.apiKey,f),q(x({},t),{getGraph:()=>l.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});
|
|
2
2
|
//# sourceMappingURL=index-graph.js.map
|