@sentientui/core 0.16.1 → 0.16.3
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/LICENSE +21 -0
- package/dist/{chunk-KZHVBFG7.mjs → chunk-CD2A55US.mjs} +1 -0
- package/dist/chunk-CD2A55US.mjs.map +1 -0
- package/dist/{chunk-P5ZTJLZE.mjs → chunk-L5TA3FAB.mjs} +2 -1
- package/dist/chunk-L5TA3FAB.mjs.map +1 -0
- package/dist/chunk-SHGSYP75.mjs +2 -0
- package/dist/chunk-SHGSYP75.mjs.map +1 -0
- package/dist/{chunk-HGGX55FR.mjs → chunk-TMCGHANO.mjs} +1 -0
- package/dist/chunk-TMCGHANO.mjs.map +1 -0
- package/dist/index-CTs3AM9E.d.ts +396 -0
- package/dist/index-DqbtJfra.d.cts +396 -0
- package/dist/index-engagement.js +2 -1
- package/dist/index-engagement.js.map +1 -0
- package/dist/index-engagement.mjs +2 -1
- package/dist/index-engagement.mjs.map +1 -0
- package/dist/index-graph.d.cts +38 -3
- package/dist/index-graph.d.ts +38 -3
- package/dist/index-graph.js +2 -1
- package/dist/index-graph.js.map +1 -0
- package/dist/index-graph.mjs +2 -1
- package/dist/index-graph.mjs.map +1 -0
- package/dist/index-local-stub.js +1 -0
- package/dist/index-local-stub.js.map +1 -0
- package/dist/index-local-stub.mjs +2 -1
- package/dist/index-local-stub.mjs.map +1 -0
- package/dist/index-local.d.cts +1 -1
- package/dist/index-local.d.ts +1 -1
- package/dist/index-local.js +1 -0
- package/dist/index-local.js.map +1 -0
- package/dist/index-local.mjs +2 -1
- package/dist/index-local.mjs.map +1 -0
- package/dist/index-server.js +1 -0
- package/dist/index-server.js.map +1 -0
- package/dist/index-server.mjs +2 -1
- package/dist/index-server.mjs.map +1 -0
- package/dist/index.d.cts +2 -430
- package/dist/index.d.ts +2 -430
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -0
- package/package.json +21 -2
- package/dist/chunk-CWUFS37B.mjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/engagement/capture.ts"],"sourcesContent":["import { classifySection, SEMANTIC_TYPES, type SemanticType } from './classify';\nimport { isDoNotTrackEnabled } from '../index.js';\nimport { attachMicroSignalDetectors } from '../micro-signals.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 `nc-<type>`\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/** Skip a section nested inside another candidate section (avoid double count). */\nfunction isNested(el: Element): boolean {\n return el.parentElement?.closest(SECTION_SELECTOR) != null;\n}\n\nfunction registerSections(\n apiKey: string,\n apiBase: string,\n pageUrl: string,\n sections: Array<{ componentId: string; semanticType: SemanticType; source: 'markup' | 'auto' }>,\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.\n if (!opts.apiKey) return NOOP;\n const apiBase = opts.apiBase ?? 'https://api.sentient-ui.com';\n\n const els = Array.from(doc.querySelectorAll(SECTION_SELECTOR)).filter((el) => !isNested(el));\n if (els.length === 0) return NOOP;\n\n // Collapse to one component per semantic type per page (the matrix aggregates\n // by semantic type anyway). Per-element precedence: explicit data-sentient-type\n // markup → served section map (opts.typeOf) → local heuristic.\n const componentOf = new Map<Element, string>();\n const types = new Map<string, SemanticType>();\n const sources = new Map<string, 'markup' | 'auto'>();\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 type = markup ?? opts.typeOf?.(el) ?? classifySection(el);\n const componentId = `nc-${type}`;\n componentOf.set(el, componentId);\n types.set(componentId, type);\n // Markup wins if the same collapsed component gets both provenances.\n if (markup) sources.set(componentId, 'markup');\n else if (!sources.has(componentId)) sources.set(componentId, 'auto');\n }\n\n const pageUrl = (doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined))?.location?.pathname ?? '/';\n registerSections(opts.apiKey, apiBase, pageUrl, [...types.entries()].map(([componentId, semanticType]) => ({\n componentId, semanticType, source: sources.get(componentId) ?? 'auto',\n })));\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 const onPageHide = (): void => {\n emit();\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n doc.addEventListener('visibilitychange', onVisibility);\n const win = doc.defaultView ?? (typeof window !== 'undefined' ? window : undefined);\n win?.addEventListener('pagehide', onPageHide);\n\n // Per-section micro-signal detectors (opt-in; see EngagementCaptureOptions).\n // Attributed to the section's nc-<type> 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 for (const [el, componentId] of componentOf) {\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),\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 doc.removeEventListener('visibilitychange', onVisibility);\n win?.removeEventListener('pagehide', onPageHide);\n for (const c of detectorCleanups) c();\n try { observer.disconnect(); } catch { /* ignore */ }\n };\n}\n"],"mappings":"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","names":["SECTION_SELECTOR","isNested","el","_a","registerSections","apiKey","apiBase","pageUrl","sections","e","NOOP","startEngagementCapture","client","opts","_b","_c","_d","_e","_f","_g","_h","_i","doc","isDoNotTrackEnabled","els","componentOf","types","sources","explicit","markup","SEMANTIC_TYPES","type","classifySection","componentId","semanticType","state","get","id","s","observer","entries","entry","emit","now","onVisibility","onPageHide","win","detectorCleanups","attachMicroSignalDetectors","signalType","extra","__spreadValues","c"]}
|
package/dist/index-graph.d.cts
CHANGED
|
@@ -1,8 +1,43 @@
|
|
|
1
|
-
import { SentientConfig, SentientClient } from './index.cjs';
|
|
2
|
-
export { AssignResult, Assignment, AssignmentCache,
|
|
1
|
+
import { n as SentientConfig, m as SentientClient } from './index-DqbtJfra.cjs';
|
|
2
|
+
export { A as AssignResult, a as Assignment, b as AssignmentCache, E as EventQueue, g as EventType, h as GraphClient, i as GraphConfig, j as GraphSnapshot, l as PageNode, Q as QueueConfig, o as SentientEvent, p as SessionConfig, q as SessionManager } from './index-DqbtJfra.cjs';
|
|
3
3
|
export { g as deriveSessionSegment, h as detectDeviceClass, i as detectTimeOfDay, j as detectTrafficSource, r as referrerDomainFromReferer } from './session-meta-DU_3mY7U.cjs';
|
|
4
4
|
import '@sentientui/policy';
|
|
5
5
|
|
|
6
|
+
/** Reads the rendered DOM to build the page-side context graph. */
|
|
7
|
+
type ScannedNode = {
|
|
8
|
+
componentId: string;
|
|
9
|
+
semanticType: string;
|
|
10
|
+
ariaLabel?: string;
|
|
11
|
+
headingText?: string;
|
|
12
|
+
isAboveFold: boolean;
|
|
13
|
+
prominenceScore: number;
|
|
14
|
+
depth: number;
|
|
15
|
+
reactComponentName?: string;
|
|
16
|
+
dataAttributes: Record<string, string>;
|
|
17
|
+
};
|
|
18
|
+
type StructuralEdge = {
|
|
19
|
+
fromComponentId: string;
|
|
20
|
+
toComponentId: string;
|
|
21
|
+
/** 0.6 for direct parent → child, 0.3 for sibling (both directions emitted). */
|
|
22
|
+
weight: number;
|
|
23
|
+
};
|
|
24
|
+
type ScanResult = {
|
|
25
|
+
nodes: ScannedNode[];
|
|
26
|
+
edges: StructuralEdge[];
|
|
27
|
+
scannedAt: number;
|
|
28
|
+
};
|
|
29
|
+
type ContentAddedEvent = {
|
|
30
|
+
nodes: ScannedNode[];
|
|
31
|
+
edges: StructuralEdge[];
|
|
32
|
+
addedAt: number;
|
|
33
|
+
};
|
|
34
|
+
type DOMScanner = {
|
|
35
|
+
scan(): Promise<ScanResult>;
|
|
36
|
+
observe(onContentAdded: (event: ContentAddedEvent) => void): void;
|
|
37
|
+
getProminenceScore(element: Element): number;
|
|
38
|
+
destroy(): void;
|
|
39
|
+
};
|
|
40
|
+
|
|
6
41
|
/**
|
|
7
42
|
* Graph-capable entry point for @sentientui/core.
|
|
8
43
|
*
|
|
@@ -30,4 +65,4 @@ type GraphSentientConfig = SentientConfig & {
|
|
|
30
65
|
*/
|
|
31
66
|
declare function init(config: GraphSentientConfig): SentientClient;
|
|
32
67
|
|
|
33
|
-
export { type GraphSentientConfig, SentientClient, SentientConfig, init };
|
|
68
|
+
export { type ContentAddedEvent, type DOMScanner, type GraphSentientConfig, type ScanResult, type ScannedNode, SentientClient, SentientConfig, init };
|
package/dist/index-graph.d.ts
CHANGED
|
@@ -1,8 +1,43 @@
|
|
|
1
|
-
import { SentientConfig, SentientClient } from './index.js';
|
|
2
|
-
export { AssignResult, Assignment, AssignmentCache,
|
|
1
|
+
import { n as SentientConfig, m as SentientClient } from './index-CTs3AM9E.js';
|
|
2
|
+
export { A as AssignResult, a as Assignment, b as AssignmentCache, E as EventQueue, g as EventType, h as GraphClient, i as GraphConfig, j as GraphSnapshot, l as PageNode, Q as QueueConfig, o as SentientEvent, p as SessionConfig, q as SessionManager } from './index-CTs3AM9E.js';
|
|
3
3
|
export { g as deriveSessionSegment, h as detectDeviceClass, i as detectTimeOfDay, j as detectTrafficSource, r as referrerDomainFromReferer } from './session-meta-DU_3mY7U.js';
|
|
4
4
|
import '@sentientui/policy';
|
|
5
5
|
|
|
6
|
+
/** Reads the rendered DOM to build the page-side context graph. */
|
|
7
|
+
type ScannedNode = {
|
|
8
|
+
componentId: string;
|
|
9
|
+
semanticType: string;
|
|
10
|
+
ariaLabel?: string;
|
|
11
|
+
headingText?: string;
|
|
12
|
+
isAboveFold: boolean;
|
|
13
|
+
prominenceScore: number;
|
|
14
|
+
depth: number;
|
|
15
|
+
reactComponentName?: string;
|
|
16
|
+
dataAttributes: Record<string, string>;
|
|
17
|
+
};
|
|
18
|
+
type StructuralEdge = {
|
|
19
|
+
fromComponentId: string;
|
|
20
|
+
toComponentId: string;
|
|
21
|
+
/** 0.6 for direct parent → child, 0.3 for sibling (both directions emitted). */
|
|
22
|
+
weight: number;
|
|
23
|
+
};
|
|
24
|
+
type ScanResult = {
|
|
25
|
+
nodes: ScannedNode[];
|
|
26
|
+
edges: StructuralEdge[];
|
|
27
|
+
scannedAt: number;
|
|
28
|
+
};
|
|
29
|
+
type ContentAddedEvent = {
|
|
30
|
+
nodes: ScannedNode[];
|
|
31
|
+
edges: StructuralEdge[];
|
|
32
|
+
addedAt: number;
|
|
33
|
+
};
|
|
34
|
+
type DOMScanner = {
|
|
35
|
+
scan(): Promise<ScanResult>;
|
|
36
|
+
observe(onContentAdded: (event: ContentAddedEvent) => void): void;
|
|
37
|
+
getProminenceScore(element: Element): number;
|
|
38
|
+
destroy(): void;
|
|
39
|
+
};
|
|
40
|
+
|
|
6
41
|
/**
|
|
7
42
|
* Graph-capable entry point for @sentientui/core.
|
|
8
43
|
*
|
|
@@ -30,4 +65,4 @@ type GraphSentientConfig = SentientConfig & {
|
|
|
30
65
|
*/
|
|
31
66
|
declare function init(config: GraphSentientConfig): SentientClient;
|
|
32
67
|
|
|
33
|
-
export { type GraphSentientConfig, SentientClient, SentientConfig, init };
|
|
68
|
+
export { type ContentAddedEvent, type DOMScanner, type GraphSentientConfig, type ScanResult, type ScannedNode, SentientClient, SentientConfig, init };
|
package/dist/index-graph.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
"use strict";var et=Object.create;var oe=Object.defineProperty,tt=Object.defineProperties,nt=Object.getOwnPropertyDescriptor,ot=Object.getOwnPropertyDescriptors,rt=Object.getOwnPropertyNames,De=Object.getOwnPropertySymbols,st=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty,it=Object.prototype.propertyIsEnumerable;var Ne=(e,t,n)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,b=(e,t)=>{for(var n in t||(t={}))Pe.call(t,n)&&Ne(e,n,t[n]);if(De)for(var n of De(t))it.call(t,n)&&Ne(e,n,t[n]);return e},F=(e,t)=>tt(e,ot(t));var at=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},Le=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of rt(t))!Pe.call(e,d)&&d!==n&&oe(e,d,{get:()=>t[d],enumerable:!(a=nt(t,d))||a.enumerable});return e};var ct=(e,t,n)=>(n=e!=null?et(st(e)):{},Le(t||!e||!e.__esModule?oe(n,"default",{value:e,enumerable:!0}):n,e)),dt=e=>Le(oe({},"__esModule",{value:!0}),e);var nn={};at(nn,{deriveSessionSegment:()=>ve,detectDeviceClass:()=>W,detectTimeOfDay:()=>z,detectTrafficSource:()=>q,init:()=>tn,referrerDomainFromReferer:()=>J});module.exports=dt(nn);var lt="_snt_uid";var j="_snt_uid";function ut(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function gt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function pt(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(a){}}function ft(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 ht(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function St(e){try{sessionStorage.removeItem(e)}catch(t){}}function vt(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function bt(e){try{localStorage.removeItem(e)}catch(t){}}function Et(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var wt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ce(e){var c,l,g,y,f,m;if(typeof window=="undefined")return wt;let t=(c=e==null?void 0:e.cookieName)!=null?c:lt,a=((l=e==null?void 0:e.cookieTTLDays)!=null?l:365)*24*60*60,d=(m=(f=(y=(g=gt(t))!=null?g:ft(j))!=null?y:yt(j))!=null?f:e==null?void 0:e.ssrSessionId)!=null?m:ut();pt(t,d,a);let s=mt(j,d),o=vt(t),r=s?!1:ht(j,d),i=!s&&!o&&!r;return{getSessionId:()=>d,isEphemeral:()=>i,destroy:()=>{d=null,Et(t),bt(j),St(j)}}}function ye(e){return`_snt_retry_${e.slice(0,12)}`}var It={push:()=>{},flush:()=>{},destroy:()=>{}};function Ct(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let a=JSON.parse(n);return Array.isArray(a)?(localStorage.removeItem(t),a.slice(-e)):[]}catch(n){return[]}}function me(e,t,n){try{let d=[...(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let o=JSON.parse(s);return Array.isArray(o)?o:[]}catch(s){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(d))}catch(a){}}function Me(e){var X,Z,ee;if(typeof window=="undefined")return It;let t=(X=e.flushIntervalMs)!=null?X:5e3,n=(Z=e.maxBatchSize)!=null?Z:20,a=(ee=e.maxRetrySize)!=null?ee:100,d=e.ingestUrl,s=e.apiKey,o=ye(s),r=[],i=new Set,c=[],l=h=>{for(let v of h)g.delete(v),!i.has(v)&&(i.add(v),c.push(v));for(;c.length>500;){let v=c.shift();v&&i.delete(v)}},g=new Set,y=h=>{i.has(h.id)||g.has(h.id)||(g.add(h.id),r.push(h))},f=Ct(a,o);for(let h of f)y(h);let m=0,E=0,I=h=>{if(h.length===0)return;let v=JSON.stringify(h),A=h.map(u=>u.id),k;try{k=fetch(d,{method:"POST",keepalive:!0,body:v,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(u){me(h,a,o);for(let p of A)g.delete(p);E++,m=Date.now()+Math.min(6e4,1e3*2**Math.min(E,6));return}let L=u=>{if(u.ok||u.status>=400&&u.status<500&&u.status!==429){l(A),E=0,m=0;return}me(h,a,o);for(let p of A)g.delete(p);E++,m=Date.now()+Math.min(6e4,1e3*2**Math.min(E,6))};k instanceof Promise?k.then(L).catch(()=>{me(h,a,o);for(let u of A)g.delete(u);E++,m=Date.now()+Math.min(6e4,1e3*2**Math.min(E,6))}):L(k)},w=typeof TextEncoder!="undefined"?new TextEncoder:null,ae=h=>w?w.encode(h).length:h.length,G=h=>{let v=[],A=2;for(let k of h){let L=ae(JSON.stringify(k))+1;if(v.length>0&&A+L>57344||v.length>=n)break;v.push(k),A+=L}return v},N=()=>{try{if(Date.now()<m)return;for(;r.length>0;){let h=r.filter(A=>!i.has(A.id));if(r.length=0,h.length===0)break;let v=G(h);if(v.length===0)break;v.length<h.length&&r.push(...h.slice(v.length)),I(v)}}catch(h){}},R=!0,K=null;K=setInterval(()=>{R&&N()},t);let Q=()=>{document.visibilityState==="hidden"&&N()},V=()=>{N()};return document.addEventListener("visibilitychange",Q),window.addEventListener("beforeunload",V),{push(h){y(h),r.length>=n&&N()},flush:N,destroy(){R=!1,K!==null&&(clearInterval(K),K=null),document.removeEventListener("visibilitychange",Q),window.removeEventListener("beforeunload",V),N()}}}var Se="_snt_asgn_";function de(e,t){return`${e}:${t}`}function xt(e,t){return`${Se}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Ue(e){let t=e.slice(Se.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(a){return null}}function he(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(Se)&&e.push(n)}return e}catch(e){return[]}}function Ge(e=18e5){let t=new Map,n=d=>d.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let d of he())try{let s=localStorage.getItem(d);if(!s)continue;let o=JSON.parse(s);if(n(o)){localStorage.removeItem(d);continue}let r=Ue(d);if(!r)continue;t.set(de(r.componentId,r.segment),o)}catch(s){}})(),{get(d,s){let o=t.get(de(d,s));return o?n(o)?(t.delete(de(d,s)),null):o:null},set(d,s,o){let r=de(d,s);t.set(r,o);try{localStorage.setItem(xt(d,s),JSON.stringify(o))}catch(i){}},invalidate(d){let s=`${d}:`;for(let o of[...t.keys()])o.startsWith(s)&&t.delete(o);for(let o of he()){let r=Ue(o);if((r==null?void 0:r.componentId)===d)try{localStorage.removeItem(o)}catch(i){}}},clear(){t.clear();for(let d of he())try{localStorage.removeItem(d)}catch(s){}}}}var Ke=["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 $e(e)!==null}function $e(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ke.find(a=>t.includes(a.toLowerCase())))!=null?n:null}function W(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 q(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 J(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function z(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function ve(e){let t=At("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function At(e,t){var s,o,r,i,c,l,g;let n=(o=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?o:"",a=(i=(r=t==null?void 0:t.referer)==null?void 0:r.trim())!=null?i:"",d=(c=t==null?void 0:t.now)!=null?c:new Date;return{sessionId:e,ephemeral:!1,utmParams:(l=t==null?void 0:t.utmParams)!=null?l:{},deviceClass:n?W(n):"desktop",trafficSource:a?q(a,t==null?void 0:t.appOrigin):"direct",referrerDomain:J(a),timeOfDay:z(d),dayOfWeek:(g=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?g:"sun",automation:(t==null?void 0:t.webdriver)===!0||le(n)}}var Y=require("@sentientui/policy");function ue(e){return b(b(b({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function ge(e){let t=ue(e);return(0,Y.slotResultFor)(t,(0,Y.slotBaselineArm)(t))}function be(e){return typeof e=="string"?e:(0,Y.canonicalArm)(e)}var re="_snt_snap:",Tt=["low","medium","high"];function Ee(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"||!Tt.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 se(e,t){try{localStorage.setItem(re+e,JSON.stringify(t))}catch(n){}}var Ce=require("@sentientui/policy");var fe=require("@sentientui/policy");var we="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Fe="[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.",Be=!1,pe=!1;function _t(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function je(e){var r;let t=ce({ssrSessionId:e.ssrSessionId}),n=(r=t.getSessionId())!=null?r:"local",a=_t(),d=import("@sentientui/core/local").then(i=>{let c=i;return c.LOCAL_ENGINE_AVAILABLE?(Be||(Be=!0,console.info(Fe)),c):(pe||(pe=!0,console.error(we)),null)}).catch(()=>(pe||(pe=!0,console.error(we)),null)),s=null;function o(i){let c=document.documentElement;c.dataset.sentientPersona===void 0&&(c.dataset.sentientPersona=i.persona,c.dataset.sentientConfidence=(0,fe.confidenceBand)(i.confidence))}return{isLocal:!0,async decide(i){var g,y,f;let c=await d;if(!c)return null;let l=c.createLocalEngine({sessionId:n,forcedPersona:a}).decide(i);return s=F(b({},l),{layoutOrder:(y=(g=l.layoutOrder)!=null?g:s==null?void 0:s.layoutOrder)!=null?y:null,slots:b(b({},(f=s==null?void 0:s.slots)!=null?f:{}),l.slots)}),se(e.apiKey||"local",{v:1,persona:s.persona,band:(0,fe.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),o(l),l},getSlotResult(i){var c,l,g;return(g=(l=s==null?void 0:s.slots[i])!=null?l:(c=e.initialSlots)==null?void 0:c[i])!=null?g:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,fe.confidenceBand)(s.confidence)}:null},async assign(i,c){var y;let l=await d;return!l||!c||c.length===0?c!=null&&c[0]?{variantId:c[0],assignmentTtlMs:0}:null:{variantId:(y=l.createLocalEngine({sessionId:n,forcedPersona:a}).decide({components:[{id:i,variantIds:c}]}).assignments[i])!=null?y:c[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var We="https://api.sentient-ui.com/v1/events",ie=new Map,Rt=null;function Ie(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var H={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function kt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,a]of t)n.startsWith("utm_")&&(e[n]=a);return e}catch(e){return{}}}function qe(e){return e.replace(/\/events\/?$/,"")}function xe(){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 Ot(e){var o;let t=qe((o=e.ingestUrl)!=null?o:We),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},a={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(r,i,c){try{let l=new URLSearchParams({componentId:r});for(let f of i!=null?i:[])l.append("variantIds[]",f);let g=await fetch(`${t}/winner?${l.toString()}`,{headers:n});return g.ok?{variantId:(await g.json()).variantId,assignmentTtlMs:0}:i!=null&&i[0]?{variantId:i[0],assignmentTtlMs:0}:null}catch(l){return i!=null&&i[0]?{variantId:i[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},d={track:r=>a.track(r),goal:(r,i,c,l)=>a.goal(r,i,c,l),componentGoal:(r,i,c)=>a.componentGoal(r,i,c),identify:r=>a.identify(r),getAssignment:(r,i)=>a.getAssignment(r,i),assign:(r,i,c,l)=>a.assign(r,i,c,l),decide:r=>a.decide(r),getSlotResult:r=>a.getSlotResult(r),getPersona:()=>a.getPersona(),fetchWeights:()=>a.fetchWeights(),getGraph:()=>a.getGraph(),dispose:()=>a.dispose(),destroy:()=>a.destroy()};function s(r){a=r}return{proxy:d,setInner:s}}function Je(e){var V,X,Z,ee,h,v,A,k,L;if(typeof window=="undefined")return H;Rt=e.apiKey;let t=e.respectDoNotTrack!==!1&&xe(),n=e.consent===!1||t,a=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!a&&e.localMode!==!1)return n?(ie.set(e.apiKey||"local",{config:e,upgrade:null}),H):(ie.set(e.apiKey||"local",{config:e,upgrade:null}),je(e));if(n){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),H;let{proxy:u,setInner:p}=Ot(e);return ie.set(e.apiKey,{config:e,upgrade:t?null:p}),u}return ie.set(e.apiKey,{config:e,upgrade:null}),H}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),H;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),H;let d=(V=e.ingestUrl)!=null?V:We,s=Date.now(),o=ce({ssrSessionId:e.ssrSessionId}),r=Ge(),i=Me({ingestUrl:d,apiKey:e.apiKey}),c=qe(d),l={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=W((X=navigator.userAgent)!=null?X:""),y=typeof window!="undefined"?window.location.origin:void 0,f=q((Z=document.referrer)!=null?Z:"",y),m=(ee=e.sessionSegment)!=null?ee:`${g}:${f}`,E=new Map,I=new Map,w=null,ae=u=>{for(let p of u)I.has(p.id)||I.set(p.id,ge(p))};if(e.initialSlots)for(let[u,p]of Object.entries(e.initialSlots))I.set(u,p);let G=Ee(e.apiKey);if(G)for(let[u,p]of Object.entries(G.slots))I.has(u)||I.set(u,p);let N={low:.15,medium:.5,high:.85};if(e.initialPersona)w=b({},e.initialPersona);else{let u=document.documentElement.dataset;u.sentientPersona?w={persona:u.sentientPersona,confidence:(v=N[(h=u.sentientConfidence)!=null?h:"low"])!=null?v:.15}:G&&(w={persona:G.persona,confidence:(A=N[G.band])!=null?A:.15})}if(e.initialAssignments)for(let[u,p]of Object.entries(e.initialAssignments))r.set(u,m,{variantId:p,assignedAt:Date.now(),segment:m,confidence:1});let R=Promise.resolve(),K=o.getSessionId();if(K){let u=J((k=document.referrer)!=null?k:""),p=b(b({sessionId:K,deviceClass:g,trafficSource:f,referrerDomain:u,utmParams:kt(),timeOfDay:z(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||le((L=navigator.userAgent)!=null?L:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{R=fetch(`${c}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(p),headers:l}).then(S=>{S.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(S){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:i});let Q={goal(u,p={},S=1,O=0){let x=o.getSessionId();if(!x)return;let T=Ie();R.then(()=>{fetch(`${c}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:x,name:u,metadata:p,weight:S,stepIndex:O,goalId:T}),headers:l}).catch(()=>{})})},componentGoal(u,p,S){var D,U,P;let O=o.getSessionId();if(!O)return;let x=r.get(u,m),T=x?null:(D=I.get(u))!=null?D:null;if(!x&&T===null){e.debug&&console.warn(`[sentient] componentGoal("${u}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let $=x?x.variantId:be(T),M={id:Ie(),sessionId:O,projectId:e.apiKey,componentId:u,variantId:$,eventType:"goal_achieved",goalType:p,payload:b({reward:(U=S==null?void 0:S.reward)!=null?U:1},(P=S==null?void 0:S.metadata)!=null?P:{}),timestamp:Date.now(),timeInSession:Date.now()-s};e.debug&&console.log("[sentient] componentGoal",M),R.then(()=>i.push(M))},identify(u){let p=o.getSessionId();p&&R.then(()=>{fetch(`${c}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:p,userId:u,ephemeral:o.isEphemeral()}),headers:l}).catch(()=>{})})},track(u){let p=o.getSessionId();if(!p)return;let S=F(b({},u),{id:Ie(),sessionId:p,timestamp:Date.now(),timeInSession:Date.now()-s});e.debug&&console.log("[sentient] track",S),R.then(()=>i.push(S))},getAssignment(u,p){return r.get(u,p)},async assign(u,p,S,O){let x=o.getSessionId();if(!x)return null;let T=r.get(u,m);if(T&&(p!=null&&p.length||T.content!==void 0))return{variantId:T.variantId,assignmentTtlMs:0,content:T.content};let $=E.get(u);if($)return $;let M=(async()=>{await R;try{let D={sessionId:x,componentId:u,variantIds:p};O!==void 0?D.agentDataByVariant=O:S!==void 0&&(D.agentData=S);let U=await fetch(`${c}/assign`,{method:"POST",body:JSON.stringify(D),headers:l});if(!U.ok)return null;let P=await U.json();return r.set(u,m,{variantId:P.variantId,assignedAt:Date.now(),segment:m,confidence:1,content:P.content}),P}catch(D){return null}finally{E.delete(u)}})();return E.set(u,M),M},async decide(u){var O,x,T,$,M,D,U,P,Re,ke;let p=o.getSessionId();if(!p)return null;let S=(O=u.slots)!=null?O:[];await R;try{let B={sessionId:p};u.sections&&u.sections.length>0&&(B.sections=u.sections.map(_=>({id:_}))),B.components=(x=u.components)!=null?x:[],S.length>0&&(B.slots=S.map(ue)),u.slotsFrom==="registry"&&(B.slotsFrom="registry"),u.v&&(B.v=u.v);let Oe=await fetch(`${c}/decide`,{method:"POST",body:JSON.stringify(B),headers:l});if(!Oe.ok)return ae(S),null;let C=await Oe.json(),te={};for(let _ of S)te[_.id]=($=(T=C.slots)==null?void 0:T[_.id])!=null?$:ge(_);if(C.slots)for(let[_,ne]of Object.entries(C.slots))_ in te||(te[_]=ne);for(let[_,ne]of Object.entries(te))I.set(_,ne);w={persona:(M=C.persona)!=null?M:"unknown",confidence:(D=C.confidence)!=null?D:0};for(let[_,ne]of Object.entries((U=C.assignments)!=null?U:{}))r.set(_,m,{variantId:ne,assignedAt:Date.now(),segment:m,confidence:1});return se(e.apiKey,b({v:1,persona:w.persona,band:(0,Ce.confidenceBand)(w.confidence),slots:Object.fromEntries(I),layoutOrder:(P=C.layoutOrder)!=null?P:null,savedAt:Date.now()},C.slotConfig?{slotConfig:C.slotConfig}:{})),b(b({layoutOrder:(Re=C.layoutOrder)!=null?Re:null,assignments:(ke=C.assignments)!=null?ke:{},slots:te,persona:w.persona,confidence:w.confidence},C.slotConfig?{slotConfig:C.slotConfig}:{}),C.goals?{goals:C.goals}:{})}catch(B){return ae(S),null}},getSlotResult(u){var p;return(p=I.get(u))!=null?p:null},getPersona(){return w?{persona:w.persona,confidence:w.confidence,band:(0,Ce.confidenceBand)(w.confidence)}:null},async fetchWeights(){var u;try{let p=await fetch(`${c}/weights`,{headers:l});return p.ok?(u=(await p.json()).components)!=null?u:[]:[]}catch(p){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){i.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){i.destroy(),o.destroy();try{localStorage.removeItem(re+e.apiKey),localStorage.removeItem(ye(e.apiKey))}catch(u){}e.debug&&console.log("[sentient] destroyed")}};if(ie.set(e.apiKey,{config:e,upgrade:null}),e.debug){let u=window;u.__sentient&&(u.__sentient.client=Q)}return Q}var ze=["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"],Dt=[["pricing",/\b(pricing|price|plans?|subscriptions?|per month|\/mo|tier)\b/i],["faq",/\b(faq|frequently asked|common questions?)\b/i],["comparison",/\b(compare|comparison|versus|vs\.)\b/i],["social_proof",/\b(testimonial|reviews?|trusted by|loved by|customers?|logos|rated|case stud)\b/i],["trust",/\b(security|guarantee|privacy|compliance|secure|gdpr|soc ?2|encrypt)\b/i],["features",/\b(features?|how it works|benefits?|capabilit|what you get)\b/i]],Nt=[["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|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]];function Pt(e){var n;let t=e.querySelector("h1, h2, h3");return((n=t==null?void 0:t.textContent)!=null?n:"").slice(0,160)}function Lt(e){if(e.tag==="nav"||e.tag==="footer")return{type:"navigation",strength:"weak"};let t=`${e.idClass} ${e.headingText}`.toLowerCase();for(let[n,a]of Dt)if(a.test(t))return{type:n,strength:"strong"};for(let[n,a]of Nt)if(a.test(e.bodyText))return{type:n,strength:"strong"};return e.actionCount>=1&&e.textLength>0&&e.textLength<200?{type:"cta",strength:"weak"}:e.tag==="header"?{type:"hero",strength:"weak"}:/\b(hero|headline|banner)\b/i.test(t)?{type:"hero",strength:"weak"}:{type:"generic",strength:"weak"}}function Mt(e){var n,a;let t=((n=e.textContent)!=null?n:"").replace(/\s+/g," ").trim();return{tag:e.tagName.toLowerCase(),idClass:`${e.id} ${String((a=e.className)!=null?a:"")}`,headingText:Pt(e),bodyText:t.slice(0,2e3),actionCount:e.querySelectorAll('a, button, [role="button"]').length,textLength:t.length}}function Ye(e){return Lt(Mt(e)).type}var Ut=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Gt="h1, h2, h3",Kt={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function Ae(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function $t(e){var t,n,a;try{let d=e;for(let s of Object.keys(d)){if(!s.startsWith("__reactFiber")&&!s.startsWith("__reactInternalInstance"))continue;let o=d[s],r=(a=(t=o==null?void 0:o.type)==null?void 0:t.displayName)!=null?a:(n=o==null?void 0:o.type)==null?void 0:n.name;if(r&&r.length>1)return r}}catch(d){}}function Bt(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var He=new Set(ze);function Ft(e){let t=e.getAttribute("data-sentient-type");if(t&&He.has(t))return t;let n=e.getAttribute("role");return n&&He.has(n)?n:Ye(e)}function jt(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function Wt(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function Te(e,t){var a,d,s;let n=e.querySelector(Gt);return{componentId:jt(e),semanticType:Ft(e),ariaLabel:(a=e.getAttribute("aria-label"))!=null?a:void 0,headingText:(s=(d=n==null?void 0:n.textContent)==null?void 0:d.trim())!=null?s:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Wt(e),reactComponentName:$t(e),dataAttributes:Bt(e)}}function Qe(e){var s;let t=[],n=new Set,a="__root__",d=new Map;for(let[o,r]of e){let i=o.parentElement,c=a;for(;i;){if(e.has(i)){c=e.get(i);let g=e.get(o),y=`${c}->${g}`;!n.has(y)&&c!==g&&(n.add(y),t.push({fromComponentId:c,toComponentId:g,weight:.6}));break}i=i.parentElement}let l=(s=d.get(c))!=null?s:[];l.push(o),d.set(c,l)}for(let o of d.values())if(!(o.length<2))for(let r=0;r<o.length;r++)for(let i=r+1;i<o.length;i++){let c=e.get(o[r]),l=e.get(o[i]);if(c===l)continue;let g=`${c}->${l}::sib`,y=`${l}->${c}::sib`;n.has(g)||(n.add(g),t.push({fromComponentId:c,toComponentId:l,weight:.3})),n.has(y)||(n.add(y),t.push({fromComponentId:l,toComponentId:c,weight:.3}))}return t}function qt(e){let t=[],n=new Set,a=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(o=>{if(o instanceof Element&&!n.has(o)){n.add(o);let r=Te(o,e);t.push(r),a.set(o,r.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(o=>{if(!(o instanceof Element)||n.has(o))return;let r=o.hasAttribute("aria-label"),i=o.hasAttribute("data-sentient-id");if(!r&&!i)return;n.add(o);let c=Te(o,e);t.push(c),a.set(o,c.componentId)}),{nodes:t,edges:Qe(a)}}function Ve(){if(typeof window=="undefined")return Kt;let e=null,t=0,n=null,a=r=>{try{let i=window.getComputedStyle(r),c=parseFloat(i.fontSize)||12,l=parseFloat(i.zIndex)||0,g=r.getBoundingClientRect(),y=Math.max(g.top,0),f=window.innerHeight||1,m=1/(y/f+1),E=Ae(c,12,48)*.4+Ae(m,0,1)*.4+Ae(l,0,100)*.2;return Math.max(0,Math.min(1,E))}catch(i){return .5}};return{scan:()=>new Promise(r=>{let i=()=>{let{nodes:c,edges:l}=qt(a);r({nodes:c,edges:l,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(i,{timeout:100}):i()}catch(c){i()}}),observe:r=>{n=r;try{e=new MutationObserver(i=>{let c=[],l=new Map;for(let g of i)g.type==="childList"&&g.addedNodes.forEach(y=>{if(!(y instanceof Element)||!Ut.has(y.tagName))return;let f=y.hasAttribute("data-sentient-id"),m=y.hasAttribute("aria-label");if(!f&&!m)return;let E=Te(y,a);c.push(E),l.set(y,E.componentId)});c.length>0&&n&&n({nodes:c,edges:Qe(l),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(i){}},getProminenceScore:a,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(r){}t=0,n=null}}}var _e="_snt_graph_nodes",Xe="_snt_graph_edges",Jt={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function zt(e){var t;return(t=Jt[e])!=null?t:[]}function Yt(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function Ht(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var Qt=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function Vt(e){return Qt.has(e)?e:"generic"}function Xt(e,t,n){let a=`${e}:${t}:${n.join(",")}`,d=5381;for(let s=0;s<a.length;s++)d=(d<<5)+d+a.charCodeAt(s)&4294967295;return(d>>>0).toString(16).padStart(8,"0")}function Ze(e){let t=new Map,n=new Map,a=()=>{typeof window!="undefined"&&Ht(_e,[...t.values()])},d=s=>{var o;try{let r=JSON.parse(s);t.clear();for(let i of(o=r.pageNodes)!=null?o:[])t.set(i.componentId,i)}catch(r){}};if(typeof window!="undefined"){let s=Yt(_e,[]);for(let o of s)t.set(o.componentId,o);try{localStorage.removeItem(Xe)}catch(o){}}return{addPageNode(s){t.set(s.componentId,s),a()},addStructuralEdge(s){let o=`${s.fromComponentId}->${s.toComponentId}`;n.set(o,s)},syncOnce(){var o,r;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let s=[...t.values()];if(s.length!==0)try{let i=new Map;for(let f of s){let m=(o=i.get(f.semanticType))!=null?o:[];m.push(f),i.set(f.semanticType,m)}let c=[],l=new Set;for(let f of s)for(let m of zt(f.semanticType)){let E=(r=i.get(m))!=null?r:[];for(let I of E){if(I.componentId===f.componentId)continue;let w=`semantic:${f.componentId}->${I.componentId}`;l.has(w)||(l.add(w),c.push({fromComponentId:f.componentId,toComponentId:I.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(s.map(f=>f.componentId));for(let f of n.values()){if(!g.has(f.fromComponentId)||!g.has(f.toComponentId))continue;let m=`structural:${f.fromComponentId}->${f.toComponentId}`;l.has(m)||(l.add(m),c.push({fromComponentId:f.fromComponentId,toComponentId:f.toComponentId,type:"structural",weight:f.weight,confidence:1}))}let y={pageUrl:window.location.href,nodes:s.map(f=>{let m=Vt(f.semanticType);return{componentId:f.componentId,semanticType:m,answers:f.answers,contentHash:Xt(f.componentId,m,f.answers),prominenceScore:f.prominenceScore,depthInPage:f.depth}}),edges:c};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:b({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(y)}).catch(()=>{})}catch(i){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:d,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(_e),localStorage.removeItem(Xe)}catch(s){}}}}var Zt="https://api.sentient-ui.com/v1/events";function en(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function tn(e){var c;let t=Je(e),n=e.respectDoNotTrack!==!1&&xe(),a=e.consent===!1||n;if(!e.graph||!e.apiKey||a||typeof window=="undefined")return t;let d=Ve(),s=(c=e.ingestUrl)!=null?c:Zt,o=Ze({syncUrl:s.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:en()});try{let l=localStorage.getItem("_snt_graph_nodes");l&&o.restore(JSON.stringify({pageNodes:JSON.parse(l)}))}catch(l){}d.scan().then(l=>{for(let g of l.nodes)o.addPageNode({id:g.componentId,componentId:g.componentId,semanticType:g.semanticType,answers:g.headingText?[g.headingText]:[],prominenceScore:g.prominenceScore,depth:g.depth});for(let g of l.edges)o.addStructuralEdge(g);o.syncOnce()});let r=null,i=()=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{r=null,o.syncOnce()},500)};return d.observe(l=>{for(let g of l.nodes)o.addPageNode({id:g.componentId,componentId:g.componentId,semanticType:g.semanticType,answers:g.headingText?[g.headingText]:[],prominenceScore:g.prominenceScore,depth:g.depth});for(let g of l.edges)o.addStructuralEdge(g);i()}),F(b({},t),{getGraph:()=>o.snapshot(),dispose:()=>{r!==null&&clearTimeout(r),d.destroy(),o.destroy(),t.dispose()},destroy:()=>{r!==null&&clearTimeout(r),d.destroy(),o.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer});
|
|
1
|
+
"use strict";var Ze=Object.create;var oe=Object.defineProperty,et=Object.defineProperties,tt=Object.getOwnPropertyDescriptor,nt=Object.getOwnPropertyDescriptors,ot=Object.getOwnPropertyNames,Re=Object.getOwnPropertySymbols,rt=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty,st=Object.prototype.propertyIsEnumerable;var ke=(e,t,n)=>t in e?oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v=(e,t)=>{for(var n in t||(t={}))Oe.call(t,n)&&ke(e,n,t[n]);if(Re)for(var n of Re(t))st.call(t,n)&&ke(e,n,t[n]);return e},F=(e,t)=>et(e,nt(t));var it=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:!0})},De=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of ot(t))!Oe.call(e,d)&&d!==n&&oe(e,d,{get:()=>t[d],enumerable:!(a=tt(t,d))||a.enumerable});return e};var at=(e,t,n)=>(n=e!=null?Ze(rt(e)):{},De(t||!e||!e.__esModule?oe(n,"default",{value:e,enumerable:!0}):n,e)),ct=e=>De(oe({},"__esModule",{value:!0}),e);var nn={};it(nn,{deriveSessionSegment:()=>he,detectDeviceClass:()=>W,detectTimeOfDay:()=>z,detectTrafficSource:()=>q,init:()=>tn,referrerDomainFromReferer:()=>J});module.exports=ct(nn);var dt="_snt_uid";var j="_snt_uid";function lt(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(t){}let e=()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0");return`${e()}-${e()}-${e()}-${e()}`}function ut(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function gt(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(a){}}function pt(e){try{return localStorage.getItem(e)}catch(t){return null}}function ft(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function mt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function yt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function ht(e){try{sessionStorage.removeItem(e)}catch(t){}}function St(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=strict; path=/`,/(?:^|; )_snt_uid_probe=1/.test(document.cookie)||document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function bt(e){try{localStorage.removeItem(e)}catch(t){}}function vt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Et={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ie(e){var c,l,g,y,f,m;if(typeof window=="undefined")return Et;let t=(c=e==null?void 0:e.cookieName)!=null?c:dt,a=((l=e==null?void 0:e.cookieTTLDays)!=null?l:365)*24*60*60,d=(m=(f=(y=(g=ut(t))!=null?g:pt(j))!=null?y:mt(j))!=null?f:e==null?void 0:e.ssrSessionId)!=null?m:lt();gt(t,d,a);let s=ft(j,d),o=St(t),r=s?!1:yt(j,d),i=!s&&!o&&!r;return{getSessionId:()=>d,isEphemeral:()=>i,destroy:()=>{d=null,vt(t),bt(j),ht(j)}}}function fe(e){return`_snt_retry_${e.slice(0,12)}`}var wt={push:()=>{},flush:()=>{},destroy:()=>{}};function It(e,t){try{let n=localStorage.getItem(t);if(!n)return[];let a=JSON.parse(n);return Array.isArray(a)?(localStorage.removeItem(t),a.slice(-e)):[]}catch(n){return[]}}function pe(e,t,n){try{let d=[...(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let o=JSON.parse(s);return Array.isArray(o)?o:[]}catch(s){return[]}})(),...e].slice(-t);localStorage.setItem(n,JSON.stringify(d))}catch(a){}}function Ne(e){var X,Z,ee;if(typeof window=="undefined")return wt;let t=(X=e.flushIntervalMs)!=null?X:5e3,n=(Z=e.maxBatchSize)!=null?Z:20,a=(ee=e.maxRetrySize)!=null?ee:100,d=e.ingestUrl,s=e.apiKey,o=fe(s),r=[],i=new Set,c=[],l=h=>{for(let b of h)g.delete(b),!i.has(b)&&(i.add(b),c.push(b));for(;c.length>500;){let b=c.shift();b&&i.delete(b)}},g=new Set,y=h=>{i.has(h.id)||g.has(h.id)||(g.add(h.id),r.push(h))},f=It(a,o);for(let h of f)y(h);let m=0,E=0,I=h=>{if(h.length===0)return;let b=JSON.stringify(h),A=h.map(u=>u.id),k;try{k=fetch(d,{method:"POST",keepalive:!0,body:b,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(u){pe(h,a,o);for(let p of A)g.delete(p);E++,m=Date.now()+Math.min(6e4,1e3*2**Math.min(E,6));return}let L=u=>{if(u.ok||u.status>=400&&u.status<500&&u.status!==429){l(A),E=0,m=0;return}pe(h,a,o);for(let p of A)g.delete(p);E++,m=Date.now()+Math.min(6e4,1e3*2**Math.min(E,6))};k instanceof Promise?k.then(L).catch(()=>{pe(h,a,o);for(let u of A)g.delete(u);E++,m=Date.now()+Math.min(6e4,1e3*2**Math.min(E,6))}):L(k)},w=typeof TextEncoder!="undefined"?new TextEncoder:null,se=h=>w?w.encode(h).length:h.length,G=h=>{let b=[],A=2;for(let k of h){let L=se(JSON.stringify(k))+1;if(b.length>0&&A+L>57344||b.length>=n)break;b.push(k),A+=L}return b},N=()=>{try{if(Date.now()<m)return;for(;r.length>0;){let h=r.filter(A=>!i.has(A.id));if(r.length=0,h.length===0)break;let b=G(h);if(b.length===0)break;b.length<h.length&&r.push(...h.slice(b.length)),I(b)}}catch(h){}},R=!0,K=null;K=setInterval(()=>{R&&N()},t);let H=()=>{document.visibilityState==="hidden"&&N()},V=()=>{N()};return document.addEventListener("visibilitychange",H),window.addEventListener("pagehide",V),{push(h){y(h),r.length>=n&&N()},flush:N,destroy(){R=!1,K!==null&&(clearInterval(K),K=null),document.removeEventListener("visibilitychange",H),window.removeEventListener("pagehide",V),N()}}}var ye="_snt_asgn_";function ae(e,t){return`${e}:${t}`}function Ct(e,t){return`${ye}${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Pe(e){let t=e.slice(ye.length),n=t.indexOf(":");if(n<0)return null;try{return{componentId:decodeURIComponent(t.slice(0,n)),segment:decodeURIComponent(t.slice(n+1))}}catch(a){return null}}function me(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n!=null&&n.startsWith(ye)&&e.push(n)}return e}catch(e){return[]}}function Le(e=18e5){let t=new Map,n=d=>d.assignedAt+e<Date.now();return typeof window!="undefined"&&(()=>{for(let d of me())try{let s=localStorage.getItem(d);if(!s)continue;let o=JSON.parse(s);if(n(o)){localStorage.removeItem(d);continue}let r=Pe(d);if(!r)continue;t.set(ae(r.componentId,r.segment),o)}catch(s){}})(),{get(d,s){let o=t.get(ae(d,s));return o?n(o)?(t.delete(ae(d,s)),null):o:null},set(d,s,o){let r=ae(d,s);t.set(r,o);try{localStorage.setItem(Ct(d,s),JSON.stringify(o))}catch(i){}},invalidate(d){let s=`${d}:`;for(let o of[...t.keys()])o.startsWith(s)&&t.delete(o);for(let o of me()){let r=Pe(o);if((r==null?void 0:r.componentId)===d)try{localStorage.removeItem(o)}catch(i){}}},clear(){t.clear();for(let d of me())try{localStorage.removeItem(d)}catch(s){}}}}var Me=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function ce(e){return Ue(e)!==null}function Ue(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Me.find(a=>t.includes(a.toLowerCase())))!=null?n:null}function W(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 q(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 J(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function z(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function he(e){let t=xt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function xt(e,t){var s,o,r,i,c,l,g;let n=(o=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?o:"",a=(i=(r=t==null?void 0:t.referer)==null?void 0:r.trim())!=null?i:"",d=(c=t==null?void 0:t.now)!=null?c:new Date;return{sessionId:e,ephemeral:!1,utmParams:(l=t==null?void 0:t.utmParams)!=null?l:{},deviceClass:n?W(n):"desktop",trafficSource:a?q(a,t==null?void 0:t.appOrigin):"direct",referrerDomain:J(a),timeOfDay:z(d),dayOfWeek:(g=["sun","mon","tue","wed","thu","fri","sat"][d.getDay()])!=null?g:"sun",automation:(t==null?void 0:t.webdriver)===!0||ce(n)}}var Y=require("@sentientui/policy");function Se(e){return v(v(v({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function be(e){let t=Se(e);return(0,Y.slotResultFor)(t,(0,Y.slotBaselineArm)(t))}function Ge(e){return typeof e=="string"?e:(0,Y.canonicalArm)(e)}var de="_snt_snap:",At=["low","medium","high"];function Ke(e){try{let t=localStorage.getItem(de+e);if(!t)return null;let n=JSON.parse(t);return!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!At.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 le(e,t){try{localStorage.setItem(de+e,JSON.stringify(t))}catch(n){}}var Ee=require("@sentientui/policy");var ge=require("@sentientui/policy");var $e="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Tt="[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.",Be=!1,ue=!1;function _t(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function Fe(e){var r;let t=ie({ssrSessionId:e.ssrSessionId}),n=(r=t.getSessionId())!=null?r:"local",a=_t(),d=import("@sentientui/core/local").then(i=>{let c=i;return c.LOCAL_ENGINE_AVAILABLE?(Be||(Be=!0,console.info(Tt)),c):(ue||(ue=!0,console.error($e)),null)}).catch(()=>(ue||(ue=!0,console.error($e)),null)),s=null;function o(i){let c=document.documentElement;c.dataset.sentientPersona===void 0&&(c.dataset.sentientPersona=i.persona,c.dataset.sentientConfidence=(0,ge.confidenceBand)(i.confidence))}return{isLocal:!0,async decide(i){var g,y,f;let c=await d;if(!c)return null;let l=c.createLocalEngine({sessionId:n,forcedPersona:a}).decide(i);return s=F(v({},l),{layoutOrder:(y=(g=l.layoutOrder)!=null?g:s==null?void 0:s.layoutOrder)!=null?y:null,slots:v(v({},(f=s==null?void 0:s.slots)!=null?f:{}),l.slots)}),le(e.apiKey||"local",{v:1,persona:s.persona,band:(0,ge.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),o(l),l},getSlotResult(i){var c,l,g;return(g=(l=s==null?void 0:s.slots[i])!=null?l:(c=e.initialSlots)==null?void 0:c[i])!=null?g:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,ge.confidenceBand)(s.confidence)}:null},async assign(i,c){var y;let l=await d;return!l||!c||c.length===0?c!=null&&c[0]?{variantId:c[0],assignmentTtlMs:0}:null:{variantId:(y=l.createLocalEngine({sessionId:n,forcedPersona:a}).decide({components:[{id:i,variantIds:c}]}).assignments[i])!=null?y:c[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var je="https://api.sentient-ui.com/v1/events",re=new Map,Rt=null;function ve(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var Q={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}};function kt(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,a]of t)n.startsWith("utm_")&&(e[n]=a);return e}catch(e){return{}}}function We(e){return e.replace(/\/events\/?$/,"")}function we(){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 Ot(e){var o;let t=We((o=e.ingestUrl)!=null?o:je),n={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},a={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(r,i,c){try{let l=new URLSearchParams({componentId:r});for(let f of i!=null?i:[])l.append("variantIds[]",f);let g=await fetch(`${t}/winner?${l.toString()}`,{headers:n});return g.ok?{variantId:(await g.json()).variantId,assignmentTtlMs:0}:i!=null&&i[0]?{variantId:i[0],assignmentTtlMs:0}:null}catch(l){return i!=null&&i[0]?{variantId:i[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},d={track:r=>a.track(r),goal:(r,i,c,l)=>a.goal(r,i,c,l),componentGoal:(r,i,c)=>a.componentGoal(r,i,c),identify:r=>a.identify(r),getAssignment:(r,i)=>a.getAssignment(r,i),assign:(r,i,c,l)=>a.assign(r,i,c,l),decide:r=>a.decide(r),getSlotResult:r=>a.getSlotResult(r),getPersona:()=>a.getPersona(),fetchWeights:()=>a.fetchWeights(),getGraph:()=>a.getGraph(),dispose:()=>a.dispose(),destroy:()=>a.destroy()};function s(r){a=r}return{proxy:d,setInner:s}}function qe(e){var V,X,Z,ee,h,b,A,k,L;if(typeof window=="undefined")return Q;Rt=e.apiKey;let t=e.respectDoNotTrack!==!1&&we(),n=e.consent===!1||t,a=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!a&&e.localMode!==!1)return n?(re.set(e.apiKey||"local",{config:e,upgrade:null}),Q):(re.set(e.apiKey||"local",{config:e,upgrade:null}),Fe(e));if(n){if(e.preConsentBehavior==="statistical_winner"){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),Q;let{proxy:u,setInner:p}=Ot(e);return re.set(e.apiKey,{config:e,upgrade:t?null:p}),u}return re.set(e.apiKey,{config:e,upgrade:null}),Q}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."),Q;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),Q;let d=(V=e.ingestUrl)!=null?V:je,s=Date.now(),o=ie({ssrSessionId:e.ssrSessionId}),r=Le(),i=Ne({ingestUrl:d,apiKey:e.apiKey}),c=We(d),l={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},g=W((X=navigator.userAgent)!=null?X:""),y=typeof window!="undefined"?window.location.origin:void 0,f=q((Z=document.referrer)!=null?Z:"",y),m=(ee=e.sessionSegment)!=null?ee:`${g}:${f}`,E=new Map,I=new Map,w=null,se=u=>{for(let p of u)I.has(p.id)||I.set(p.id,be(p))};if(e.initialSlots)for(let[u,p]of Object.entries(e.initialSlots))I.set(u,p);let G=Ke(e.apiKey);if(G)for(let[u,p]of Object.entries(G.slots))I.has(u)||I.set(u,p);let N={low:.15,medium:.5,high:.85};if(e.initialPersona)w=v({},e.initialPersona);else{let u=document.documentElement.dataset;u.sentientPersona?w={persona:u.sentientPersona,confidence:(b=N[(h=u.sentientConfidence)!=null?h:"low"])!=null?b:.15}:G&&(w={persona:G.persona,confidence:(A=N[G.band])!=null?A:.15})}if(e.initialAssignments)for(let[u,p]of Object.entries(e.initialAssignments))r.set(u,m,{variantId:p,assignedAt:Date.now(),segment:m,confidence:1});let R=Promise.resolve(),K=o.getSessionId();if(K){let u=J((k=document.referrer)!=null?k:""),p=v(v({sessionId:K,deviceClass:g,trafficSource:f,referrerDomain:u,utmParams:kt(),timeOfDay:z(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||ce((L=navigator.userAgent)!=null?L:"")},e.userId?{userId:e.userId}:{}),e.country?{country:e.country}:{});try{R=fetch(`${c}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(p),headers:l}).then(S=>{S.status===402&&console.warn("[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing")}).catch(()=>{})}catch(S){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:i});let H={goal(u,p={},S=1,O=0){let x=o.getSessionId();if(!x)return;let T=ve();R.then(()=>{fetch(`${c}/goals`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:x,name:u,metadata:p,weight:S,stepIndex:O,goalId:T}),headers:l}).catch(()=>{})})},componentGoal(u,p,S){var D,U,P;let O=o.getSessionId();if(!O)return;let x=r.get(u,m),T=x?null:(D=I.get(u))!=null?D:null;if(!x&&T===null){e.debug&&console.warn(`[sentient] componentGoal("${u}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let $=x?x.variantId:Ge(T),M={id:ve(),sessionId:O,projectId:e.apiKey,componentId:u,variantId:$,eventType:"goal_achieved",goalType:p,payload:v({reward:(U=S==null?void 0:S.reward)!=null?U:1},(P=S==null?void 0:S.metadata)!=null?P:{}),timestamp:Date.now(),timeInSession:Date.now()-s};e.debug&&console.log("[sentient] componentGoal",M),R.then(()=>i.push(M))},identify(u){let p=o.getSessionId();p&&R.then(()=>{fetch(`${c}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:p,userId:u,ephemeral:o.isEphemeral()}),headers:l}).catch(()=>{})})},track(u){let p=o.getSessionId();if(!p)return;let S=F(v({},u),{id:ve(),sessionId:p,timestamp:Date.now(),timeInSession:Date.now()-s});e.debug&&console.log("[sentient] track",S),R.then(()=>i.push(S))},getAssignment(u,p){return r.get(u,p)},async assign(u,p,S,O){let x=o.getSessionId();if(!x)return null;let T=r.get(u,m);if(T&&(p!=null&&p.length||T.content!==void 0))return{variantId:T.variantId,assignmentTtlMs:0,content:T.content};let $=E.get(u);if($)return $;let M=(async()=>{await R;try{let D={sessionId:x,componentId:u,variantIds:p};O!==void 0?D.agentDataByVariant=O:S!==void 0&&(D.agentData=S);let U=await fetch(`${c}/assign`,{method:"POST",body:JSON.stringify(D),headers:l});if(!U.ok)return null;let P=await U.json();return r.set(u,m,{variantId:P.variantId,assignedAt:Date.now(),segment:m,confidence:1,content:P.content}),P}catch(D){return null}finally{E.delete(u)}})();return E.set(u,M),M},async decide(u){var O,x,T,$,M,D,U,P,Ae,Te;let p=o.getSessionId();if(!p)return null;let S=(O=u.slots)!=null?O:[];await R;try{let B={sessionId:p};u.sections&&u.sections.length>0&&(B.sections=u.sections.map(_=>({id:_}))),B.components=(x=u.components)!=null?x:[],S.length>0&&(B.slots=S.map(Se)),u.slotsFrom==="registry"&&(B.slotsFrom="registry"),u.v&&(B.v=u.v);let _e=await fetch(`${c}/decide`,{method:"POST",body:JSON.stringify(B),headers:l});if(!_e.ok)return se(S),null;let C=await _e.json(),te={};for(let _ of S)te[_.id]=($=(T=C.slots)==null?void 0:T[_.id])!=null?$:be(_);if(C.slots)for(let[_,ne]of Object.entries(C.slots))_ in te||(te[_]=ne);for(let[_,ne]of Object.entries(te))I.set(_,ne);w={persona:(M=C.persona)!=null?M:"unknown",confidence:(D=C.confidence)!=null?D:0};for(let[_,ne]of Object.entries((U=C.assignments)!=null?U:{}))r.set(_,m,{variantId:ne,assignedAt:Date.now(),segment:m,confidence:1});return le(e.apiKey,v({v:1,persona:w.persona,band:(0,Ee.confidenceBand)(w.confidence),slots:Object.fromEntries(I),layoutOrder:(P=C.layoutOrder)!=null?P:null,savedAt:Date.now()},C.slotConfig?{slotConfig:C.slotConfig}:{})),v(v({layoutOrder:(Ae=C.layoutOrder)!=null?Ae:null,assignments:(Te=C.assignments)!=null?Te:{},slots:te,persona:w.persona,confidence:w.confidence},C.slotConfig?{slotConfig:C.slotConfig}:{}),C.goals?{goals:C.goals}:{})}catch(B){return se(S),null}},getSlotResult(u){var p;return(p=I.get(u))!=null?p:null},getPersona(){return w?{persona:w.persona,confidence:w.confidence,band:(0,Ee.confidenceBand)(w.confidence)}:null},async fetchWeights(){var u;try{let p=await fetch(`${c}/weights`,{headers:l});return p.ok?(u=(await p.json()).components)!=null?u:[]:[]}catch(p){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){i.destroy(),e.debug&&console.log("[sentient] disposed")},destroy(){i.destroy(),o.destroy();try{localStorage.removeItem(de+e.apiKey),localStorage.removeItem(fe(e.apiKey))}catch(u){}e.debug&&console.log("[sentient] destroyed")}};if(re.set(e.apiKey,{config:e,upgrade:null}),e.debug){let u=window;u.__sentient&&(u.__sentient.client=H)}return H}var Je=["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"],Dt=[["pricing",/\b(pricing|price|plans?|subscriptions?|per month|\/mo|tier)\b/i],["faq",/\b(faq|frequently asked|common questions?)\b/i],["comparison",/\b(compare|comparison|versus|vs\.)\b/i],["social_proof",/\b(testimonial|reviews?|trusted by|loved by|customers?|logos|rated|case stud)\b/i],["trust",/\b(security|guarantee|privacy|compliance|secure|gdpr|soc ?2|encrypt)\b/i],["features",/\b(features?|how it works|benefits?|capabilit|what you get)\b/i]],Nt=[["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|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]];function Pt(e){var n;let t=e.querySelector("h1, h2, h3");return((n=t==null?void 0:t.textContent)!=null?n:"").slice(0,160)}function Lt(e){if(e.tag==="nav"||e.tag==="footer")return{type:"navigation",strength:"weak"};let t=`${e.idClass} ${e.headingText}`.toLowerCase();for(let[n,a]of Dt)if(a.test(t))return{type:n,strength:"strong"};for(let[n,a]of Nt)if(a.test(e.bodyText))return{type:n,strength:"strong"};return e.actionCount>=1&&e.textLength>0&&e.textLength<200?{type:"cta",strength:"weak"}:e.tag==="header"?{type:"hero",strength:"weak"}:/\b(hero|headline|banner)\b/i.test(t)?{type:"hero",strength:"weak"}:{type:"generic",strength:"weak"}}function Mt(e){var n,a;let t=((n=e.textContent)!=null?n:"").replace(/\s+/g," ").trim();return{tag:e.tagName.toLowerCase(),idClass:`${e.id} ${String((a=e.className)!=null?a:"")}`,headingText:Pt(e),bodyText:t.slice(0,2e3),actionCount:e.querySelectorAll('a, button, [role="button"]').length,textLength:t.length}}function ze(e){return Lt(Mt(e)).type}var Ut=new Set(["SECTION","ARTICLE","MAIN","DIV"]),Gt="h1, h2, h3",Kt={scan:async()=>({nodes:[],edges:[],scannedAt:0}),observe:()=>{},getProminenceScore:()=>0,destroy:()=>{}};function Ie(e,t,n){return n<=t?0:Math.max(0,Math.min(1,(e-t)/(n-t)))}function $t(e){var t,n,a;try{let d=e;for(let s of Object.keys(d)){if(!s.startsWith("__reactFiber")&&!s.startsWith("__reactInternalInstance"))continue;let o=d[s],r=(a=(t=o==null?void 0:o.type)==null?void 0:t.displayName)!=null?a:(n=o==null?void 0:o.type)==null?void 0:n.name;if(r&&r.length>1)return r}}catch(d){}}function Bt(e){let t={};for(let n of Array.from(e.attributes))n.name.startsWith("data-")&&(t[n.name]=n.value);return t}var Ye=new Set(Je);function Ft(e){let t=e.getAttribute("data-sentient-type");if(t&&Ye.has(t))return t;let n=e.getAttribute("role");return n&&Ye.has(n)?n:ze(e)}function jt(e){var t,n;return(n=(t=e.getAttribute("data-sentient-id"))!=null?t:e.getAttribute("id"))!=null?n:e.tagName.toLowerCase()}function Wt(e){let t=0,n=e.parentElement;for(;n;)t++,n=n.parentElement;return t}function Ce(e,t){var a,d,s;let n=e.querySelector(Gt);return{componentId:jt(e),semanticType:Ft(e),ariaLabel:(a=e.getAttribute("aria-label"))!=null?a:void 0,headingText:(s=(d=n==null?void 0:n.textContent)==null?void 0:d.trim())!=null?s:void 0,isAboveFold:e.getBoundingClientRect().top<window.innerHeight,prominenceScore:t(e),depth:Wt(e),reactComponentName:$t(e),dataAttributes:Bt(e)}}function Qe(e){var s;let t=[],n=new Set,a="__root__",d=new Map;for(let[o,r]of e){let i=o.parentElement,c=a;for(;i;){if(e.has(i)){c=e.get(i);let g=e.get(o),y=`${c}->${g}`;!n.has(y)&&c!==g&&(n.add(y),t.push({fromComponentId:c,toComponentId:g,weight:.6}));break}i=i.parentElement}let l=(s=d.get(c))!=null?s:[];l.push(o),d.set(c,l)}for(let o of d.values())if(!(o.length<2))for(let r=0;r<o.length;r++)for(let i=r+1;i<o.length;i++){let c=e.get(o[r]),l=e.get(o[i]);if(c===l)continue;let g=`${c}->${l}::sib`,y=`${l}->${c}::sib`;n.has(g)||(n.add(g),t.push({fromComponentId:c,toComponentId:l,weight:.3})),n.has(y)||(n.add(y),t.push({fromComponentId:l,toComponentId:c,weight:.3}))}return t}function qt(e){let t=[],n=new Set,a=new Map;return document.querySelectorAll("[data-sentient-id]").forEach(o=>{if(o instanceof Element&&!n.has(o)){n.add(o);let r=Ce(o,e);t.push(r),a.set(o,r.componentId)}}),document.querySelectorAll("section, article, main, aside").forEach(o=>{if(!(o instanceof Element)||n.has(o))return;let r=o.hasAttribute("aria-label"),i=o.hasAttribute("data-sentient-id");if(!r&&!i)return;n.add(o);let c=Ce(o,e);t.push(c),a.set(o,c.componentId)}),{nodes:t,edges:Qe(a)}}function He(){if(typeof window=="undefined")return Kt;let e=null,t=0,n=null,a=r=>{try{let i=window.getComputedStyle(r),c=parseFloat(i.fontSize)||12,l=parseFloat(i.zIndex)||0,g=r.getBoundingClientRect(),y=Math.max(g.top,0),f=window.innerHeight||1,m=1/(y/f+1),E=Ie(c,12,48)*.4+Ie(m,0,1)*.4+Ie(l,0,100)*.2;return Math.max(0,Math.min(1,E))}catch(i){return .5}};return{scan:()=>new Promise(r=>{let i=()=>{let{nodes:c,edges:l}=qt(a);r({nodes:c,edges:l,scannedAt:Date.now()})};try{typeof requestIdleCallback=="function"?t=requestIdleCallback(i,{timeout:100}):i()}catch(c){i()}}),observe:r=>{n=r;try{e=new MutationObserver(i=>{let c=[],l=new Map;for(let g of i)g.type==="childList"&&g.addedNodes.forEach(y=>{if(!(y instanceof Element)||!Ut.has(y.tagName))return;let f=y.hasAttribute("data-sentient-id"),m=y.hasAttribute("aria-label");if(!f&&!m)return;let E=Ce(y,a);c.push(E),l.set(y,E.componentId)});c.length>0&&n&&n({nodes:c,edges:Qe(l),addedAt:Date.now()})}),e.observe(document.body,{childList:!0,subtree:!0})}catch(i){}},getProminenceScore:a,destroy:()=>{if(e&&(e.disconnect(),e=null),t&&typeof cancelIdleCallback=="function")try{cancelIdleCallback(t)}catch(r){}t=0,n=null}}}var xe="_snt_graph_nodes",Ve="_snt_graph_edges",Jt={pricing:["features","faq"],features:["pricing"],faq:["pricing"],social_proof:["cta"],cta:["social_proof","hero","trust"],hero:["cta"],comparison:["pricing"],trust:["cta"]};function zt(e){var t;return(t=Jt[e])!=null?t:[]}function Yt(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch(n){return t}}function Qt(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(n){}}var Ht=new Set(["pricing","hero","social_proof","cta","features","faq","comparison","trust","navigation","generic"]);function Vt(e){return Ht.has(e)?e:"generic"}function Xt(e,t,n){let a=`${e}:${t}:${n.join(",")}`,d=5381;for(let s=0;s<a.length;s++)d=(d<<5)+d+a.charCodeAt(s)&4294967295;return(d>>>0).toString(16).padStart(8,"0")}function Xe(e){let t=new Map,n=new Map,a=()=>{typeof window!="undefined"&&Qt(xe,[...t.values()])},d=s=>{var o;try{let r=JSON.parse(s);t.clear();for(let i of(o=r.pageNodes)!=null?o:[])t.set(i.componentId,i)}catch(r){}};if(typeof window!="undefined"){let s=Yt(xe,[]);for(let o of s)t.set(o.componentId,o);try{localStorage.removeItem(Ve)}catch(o){}}return{addPageNode(s){t.set(s.componentId,s),a()},addStructuralEdge(s){let o=`${s.fromComponentId}->${s.toComponentId}`;n.set(o,s)},syncOnce(){var o,r;if(!(e!=null&&e.syncUrl)||typeof window=="undefined")return;let s=[...t.values()];if(s.length!==0)try{let i=new Map;for(let f of s){let m=(o=i.get(f.semanticType))!=null?o:[];m.push(f),i.set(f.semanticType,m)}let c=[],l=new Set;for(let f of s)for(let m of zt(f.semanticType)){let E=(r=i.get(m))!=null?r:[];for(let I of E){if(I.componentId===f.componentId)continue;let w=`semantic:${f.componentId}->${I.componentId}`;l.has(w)||(l.add(w),c.push({fromComponentId:f.componentId,toComponentId:I.componentId,type:"semantic",weight:.4,confidence:.9}))}}let g=new Set(s.map(f=>f.componentId));for(let f of n.values()){if(!g.has(f.fromComponentId)||!g.has(f.toComponentId))continue;let m=`structural:${f.fromComponentId}->${f.toComponentId}`;l.has(m)||(l.add(m),c.push({fromComponentId:f.fromComponentId,toComponentId:f.toComponentId,type:"structural",weight:f.weight,confidence:1}))}let y={pageUrl:window.location.href,nodes:s.map(f=>{let m=Vt(f.semanticType);return{componentId:f.componentId,semanticType:m,answers:f.answers,contentHash:Xt(f.componentId,m,f.answers),prominenceScore:f.prominenceScore,depthInPage:f.depth}}),edges:c};fetch(e.syncUrl,{method:"POST",keepalive:!0,headers:v({"Content-Type":"application/json"},e.apiKey?{Authorization:`Bearer ${e.apiKey}`}:{}),body:JSON.stringify(y)}).catch(()=>{})}catch(i){}},snapshot(){return{pageNodes:[...t.values()],capturedAt:Date.now()}},serialize(){return JSON.stringify({pageNodes:[...t.values()]})},restore:d,destroy(){if(typeof window!="undefined")try{localStorage.removeItem(xe),localStorage.removeItem(Ve)}catch(s){}}}}var Zt="https://api.sentient-ui.com/v1/events";function en(){try{let e=document.cookie.match(/(?:^|; )_snt_uid=([^;]*)/);return e?decodeURIComponent(e[1]):void 0}catch(e){return}}function tn(e){var c;let t=qe(e),n=e.respectDoNotTrack!==!1&&we(),a=e.consent===!1||n;if(!e.graph||!e.apiKey||a||typeof window=="undefined")return t;let d=He(),s=(c=e.ingestUrl)!=null?c:Zt,o=Xe({syncUrl:s.replace(/\/events\/?$/,"/graph/sync"),apiKey:e.apiKey,projectId:e.apiKey,sessionId:en()});try{let l=localStorage.getItem("_snt_graph_nodes");l&&o.restore(JSON.stringify({pageNodes:JSON.parse(l)}))}catch(l){}d.scan().then(l=>{for(let g of l.nodes)o.addPageNode({id:g.componentId,componentId:g.componentId,semanticType:g.semanticType,answers:g.headingText?[g.headingText]:[],prominenceScore:g.prominenceScore,depth:g.depth});for(let g of l.edges)o.addStructuralEdge(g);o.syncOnce()});let r=null,i=()=>{r!==null&&clearTimeout(r),r=setTimeout(()=>{r=null,o.syncOnce()},500)};return d.observe(l=>{for(let g of l.nodes)o.addPageNode({id:g.componentId,componentId:g.componentId,semanticType:g.semanticType,answers:g.headingText?[g.headingText]:[],prominenceScore:g.prominenceScore,depth:g.depth});for(let g of l.edges)o.addStructuralEdge(g);i()}),F(v({},t),{getGraph:()=>o.snapshot(),dispose:()=>{r!==null&&clearTimeout(r),d.destroy(),o.destroy(),t.dispose()},destroy:()=>{r!==null&&clearTimeout(r),d.destroy(),o.destroy(),t.destroy()}})}0&&(module.exports={deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,init,referrerDomainFromReferer});
|
|
2
|
+
//# sourceMappingURL=index-graph.js.map
|