@sentientui/core 0.21.2 → 0.22.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nexport type { SlotDeclInput, SlotResult };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n): string | null {\n return cookies.get('_snt_uid')?.value ?? null;\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"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","names":["DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","_b","preloadDecisions","params","_c","_d","_e","_f","_g","_h","_i","_j","_k","declaredSlots","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor"]}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["/**\n * Server-side helpers for SSR variant pre-loading.\n * Pure fetch — no DOM APIs. Safe in Node.js, Edge, and Deno runtimes.\n */\nimport { buildSessionUpsertPayload } from './session-meta.js';\nimport { LEGACY_SESSION_COOKIE_NAME, sessionCookieName } from './storage-key.js';\nimport {\n toWireSlot,\n baselineResultFor,\n baselineSlots,\n type SlotDeclInput,\n type SlotResult,\n} from './slots.js';\n\nexport type { SlotDeclInput, SlotResult };\n\nexport type ServerAssignConfig = {\n /** Public API key (pk_...). */\n apiKey: string;\n /**\n * Base URL of the Sentient API without trailing slash.\n * e.g. 'https://api.yourapp.com/v1'\n */\n baseUrl: string;\n /**\n * Browser origin of your app (e.g. `http://localhost:3001`). Required for `pk_`\n * keys — server-side fetch must send the same `Origin` the API allows.\n */\n origin?: string;\n /** From `User-Agent` request header (Next.js `headers()`). */\n userAgent?: string;\n /** From `Referer` request header. */\n referer?: string;\n utmParams?: Record<string, string>;\n /**\n * Set true when the request carries a tracking opt-out — `DNT: 1` or\n * `Sec-GPC: 1`. When set, the SSR helpers skip the session upsert and the\n * assign/decide call entirely: the page renders defaults/baseline and no\n * session row is minted for the visitor (audit P4). The client SDK already\n * no-ops for these visitors; this keeps the server from minting a session +\n * assignment on every page view before the client can.\n */\n doNotTrack?: boolean;\n /**\n * Declared persona — the role your app already knows for this visitor\n * (e.g. from your auth context during SSR). Same contract as the client\n * option: must be a vocabulary key; unrecognized values are ignored\n * server-side. Never a user id or email.\n */\n persona?: string;\n /**\n * Milliseconds to wait for the API before returning default variants.\n * Prevents slow/cold API from blocking SSR. Defaults to 1000 — the hot path\n * is served from in-process caches and typically returns in well under\n * 150 ms. The full 1 s budget is only reached on a cold start or an API\n * geographically distant from your SSR host, after which defaults render\n * with no layout shift. Lower it if your API is co-located and warm.\n */\n timeoutMs?: number;\n};\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number };\n\nconst DEFAULT_TIMEOUT_MS = 1000;\n\nfunction fetchWithTimeout(\n url: string,\n init: RequestInit,\n timeoutMs: number,\n): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n return fetch(url, { ...init, signal: controller.signal }).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Fetches variant assignments server-side for all listed components.\n * Returns a map suitable for passing as `initialAssignments` to `<AdaptiveProvider>`.\n *\n * Call from Next.js layout, Server Component, or getServerSideProps.\n *\n * @example\n * ```tsx\n * const assignments = await preloadAssignments(\n * [\n * { id: 'hero', variantIds: ['hero-a', 'hero-b'] },\n * { id: 'cta', variantIds: ['cta-short', 'cta-long'] },\n * ],\n * sessionId, // read from cookies() or req.cookies\n * { apiKey: process.env.NEXT_PUBLIC_SENTIENT_API_KEY!, baseUrl: 'https://api.sentient-ui.com/v1' },\n * );\n * return <AdaptiveProvider ... initialAssignments={assignments}>{children}</AdaptiveProvider>;\n * ```\n */\nexport async function preloadAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<ServerAssignments> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return {};\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) {\n headers.Origin = config.origin;\n }\n\n // Session metadata must match the browser SDK so assign seeds variant_weights\n // under the same segment (not `unknown:unknown`).\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (res.status === 402) {\n console.warn(\n '[SentientUI] Session limit exceeded for this project. The bandit will stop learning until the limit resets. Upgrade at sentient-ui.com/pricing',\n );\n } else if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: session upsert failed (${res.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadAssignments: session upsert threw', err);\n }\n\n const results = await Promise.allSettled(\n components.map(async ({ id, variantIds }) => {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/assign`,\n { method: 'POST', headers, body: JSON.stringify({ sessionId, componentId: id, variantIds }) },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadAssignments: assign failed for \"${id}\" (${res.status})`, body);\n return null;\n }\n const body = (await res.json()) as AssignResult;\n return { id, variantId: body.variantId };\n }),\n );\n\n const assignments: ServerAssignments = {};\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n assignments[result.value.id] = result.value.variantId;\n }\n }\n return assignments;\n}\n\n/**\n * Reads the Sentient session cookie from a Next.js `ReadonlyRequestCookies` object\n * (the return value of `cookies()` from `next/headers`), or any object with a\n * `get(name: string)` method. Returns null if the cookie is absent.\n *\n * Pass the project's `apiKey`: the client writes the per-project SUFFIXED name\n * (`sessionCookieName` — see storage-key.ts), so reading only the bare\n * `_snt_uid` missed the cookie on every SSR request for a returning visitor and\n * minted a fresh orphan session each page view (quota inflation, broken sticky\n * assignments and persona continuity). The bare name is still read as a\n * fallback for identities minted before namespacing.\n */\nexport function readSessionCookie(\n cookies: { get(name: string): { value: string } | undefined },\n apiKey?: string,\n): string | null {\n return (\n (apiKey ? cookies.get(sessionCookieName(apiKey))?.value : undefined) ??\n cookies.get(LEGACY_SESSION_COOKIE_NAME)?.value ??\n null\n );\n}\n\nexport type DecideResult = {\n layoutOrder: string[];\n assignments: Record<string, string>;\n /** Slot results keyed by slot id. Baseline-resolved when the API omits/fails them. */\n slots: Record<string, SlotResult>;\n persona: string;\n confidence: number;\n};\n\n/**\n * Single-roundtrip SSR call returning layout order, component assignments,\n * and adaptive-slot results. Falls back to default section order + empty\n * assignments + baseline slots if the API is unavailable. A response without\n * a `slots` field means the server predates slots — every declared slot\n * resolves to its baseline (no retry).\n */\nexport async function preloadDecisions(\n params: {\n sections?: string[];\n components: Array<{ id: string; variantIds?: string[] }>;\n slots?: SlotDeclInput[];\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n const fallback: DecideResult = {\n layoutOrder: params.sections ?? [],\n assignments: {},\n slots: baselineSlots(declaredSlots),\n persona: 'unknown',\n confidence: 0,\n };\n\n // Opted-out visitor (DNT/GPC): baseline layout/slots, mint no session (audit P4).\n if (config.doNotTrack) return fallback;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n };\n if (config.origin) headers.Origin = config.origin;\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n appOrigin: config.origin,\n }),\n ...(config.persona ? { persona: config.persona } : {}),\n };\n\n try {\n const sessionRes = await fetchWithTimeout(\n `${config.baseUrl}/sessions`,\n { method: 'POST', headers, body: JSON.stringify(sessionBody) },\n timeoutMs,\n );\n if (!sessionRes.ok) {\n const body = await sessionRes.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: session upsert failed (${sessionRes.status})`, body);\n }\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: session upsert threw', err);\n }\n\n try {\n const res = await fetchWithTimeout(\n `${config.baseUrl}/decide`,\n {\n method: 'POST',\n headers,\n body: JSON.stringify({\n sessionId,\n sections: (params.sections ?? []).map((id) => ({ id })),\n components: params.components,\n ...(declaredSlots.length > 0 ? { slots: declaredSlots.map(toWireSlot) } : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n }),\n },\n timeoutMs,\n );\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n console.error(`[SentientUI] preloadDecisions: decide failed (${res.status})`, body);\n return fallback;\n }\n const data = (await res.json()) as {\n layoutOrder?: string[];\n assignments?: Record<string, string>;\n slots?: Record<string, SlotResult>;\n persona?: string;\n confidence?: number;\n };\n\n const slots: Record<string, SlotResult> = {};\n for (const d of declaredSlots) {\n // `data.slots === undefined` ⇒ server predates slots: baseline, no retry.\n slots[d.id] = data.slots?.[d.id] ?? baselineResultFor(d);\n }\n\n return {\n layoutOrder: data.layoutOrder ?? params.sections ?? [],\n assignments: data.assignments ?? {},\n slots,\n persona: data.persona ?? 'unknown',\n confidence: data.confidence ?? 0,\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n"],"mappings":"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","names":["DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","config","_a","headers","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","declaredSlots","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor"]}
package/dist/index.d.cts CHANGED
@@ -1,3 +1,3 @@
1
- export { A as AssignResult, a as Assignment, B as BLOCK_ALIGNS, c as BLOCK_EMPHASES, d as BLOCK_FITS, e as BLOCK_GAPS, f as BLOCK_GRID_COLUMNS, g as BLOCK_HEADING_LEVELS, h as BLOCK_JUSTIFIES, i as BLOCK_RATIOS, j as BLOCK_SIZES, k as BLOCK_TEXT_ALIGNS, l as BLOCK_TONES, m as BLOCK_WEIGHTS, n as BadgeBlock, o as BlockAlign, p as BlockEmphasis, q as BlockFit, r as BlockGap, s as BlockJustify, t as BlockNode, u as BlockRatio, v as BlockSize, w as BlockTextAlign, x as BlockTone, y as BlockWeight, z as ButtonBlock, C as ComponentGoalOptions, D as ComponentWeightEntry, E as CompoundLocator, F as DecideInput, G as DecideOutcome, H as DecisionSnapshot, J as EventType, K as GoalDefinition, L as GoalOptions, N as GraphConfig, O as GraphSnapshot, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LOCAL_MODE_BANNER, T as LinkBlock, U as MAX_BLOCK_ARMS, V as MAX_BLOCK_CHILDREN, W as MAX_BLOCK_DEPTH, X as MAX_BLOCK_NODES, Y as MAX_BLOCK_TEXT_LEN, Z as MicroSignalEmitter, _ as MicroSignalType, $ as PROD_KEYLESS_ERROR, a1 as QueueConfig, a2 as SNAPSHOT_STORAGE_KEY_PREFIX, a3 as SectionMapEntry, a4 as SentientClient, a5 as SentientConfig, a6 as SentientEvent, a7 as SessionConfig, a8 as SessionManager, a9 as SitePalette, aa as SlotConfigEntry, ab as SlotOps, ac as SpacerBlock, ad as StackBlock, ae as TextBlock, af as WeightEntry, ag as attachMicroSignalDetectors, ah as grantConsent, ai as init, aj as isDoNotTrackEnabled, ak as readSnapshot, al as renderPrePaintScript, an as writeSnapshot } from './index-BheP9F8h.cjs';
1
+ export { A as AssignResult, a as Assignment, B as BLOCK_ALIGNS, c as BLOCK_EMPHASES, d as BLOCK_FITS, e as BLOCK_GAPS, f as BLOCK_GRID_COLUMNS, g as BLOCK_HEADING_LEVELS, h as BLOCK_JUSTIFIES, i as BLOCK_RATIOS, j as BLOCK_SIZES, k as BLOCK_TEXT_ALIGNS, l as BLOCK_TONES, m as BLOCK_WEIGHTS, n as BadgeBlock, o as BlockAlign, p as BlockEmphasis, q as BlockFit, r as BlockGap, s as BlockJustify, t as BlockNode, u as BlockRatio, v as BlockSize, w as BlockTextAlign, x as BlockTone, y as BlockWeight, z as ButtonBlock, C as ComponentGoalOptions, D as ComponentWeightEntry, E as CompoundLocator, F as DecideInput, G as DecideOutcome, H as DecisionSnapshot, J as EventType, K as GoalDefinition, L as GoalOptions, N as GraphConfig, O as GraphSnapshot, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LEGACY_SESSION_COOKIE_NAME, T as LOCAL_MODE_BANNER, U as LinkBlock, V as MAX_BLOCK_ARMS, W as MAX_BLOCK_CHILDREN, X as MAX_BLOCK_DEPTH, Y as MAX_BLOCK_NODES, Z as MAX_BLOCK_TEXT_LEN, _ as MicroSignalEmitter, $ as MicroSignalType, a0 as PROD_KEYLESS_ERROR, a2 as QueueConfig, a3 as SNAPSHOT_STORAGE_KEY_PREFIX, a4 as SectionMapEntry, a5 as SentientClient, a6 as SentientConfig, a7 as SentientEvent, a8 as SessionConfig, a9 as SessionManager, aa as SitePalette, ab as SlotConfigEntry, ac as SlotOps, ad as SpacerBlock, ae as StackBlock, af as TextBlock, ag as WeightEntry, ah as _registerConsentUpgradeInit, ai as attachMicroSignalDetectors, aj as grantConsent, ak as init, al as isDoNotTrackEnabled, am as readSnapshot, an as renderPrePaintScript, ap as sessionCookieName, aq as writeSnapshot } from './index-CXxvWxCB.cjs';
2
2
  export { A as AGENT_INTENTS, a as AgentIntent, b as SlotDeclInput, c as agentIntent, d as agentUaList, e as armOfResult, f as baselineResultFor, g as baselineSlots, i as classifiedAgents, j as deriveSessionSegment, k as detectDeviceClass, l as detectTimeOfDay, m as detectTrafficSource, n as matchedAgentToken, r as referrerDomainFromReferer, t as toWireSlot, u as uaTokenMatch } from './session-meta-BVvq5RBB.cjs';
3
3
  export { SlotResult } from '@sentientui/policy';
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { A as AssignResult, a as Assignment, B as BLOCK_ALIGNS, c as BLOCK_EMPHASES, d as BLOCK_FITS, e as BLOCK_GAPS, f as BLOCK_GRID_COLUMNS, g as BLOCK_HEADING_LEVELS, h as BLOCK_JUSTIFIES, i as BLOCK_RATIOS, j as BLOCK_SIZES, k as BLOCK_TEXT_ALIGNS, l as BLOCK_TONES, m as BLOCK_WEIGHTS, n as BadgeBlock, o as BlockAlign, p as BlockEmphasis, q as BlockFit, r as BlockGap, s as BlockJustify, t as BlockNode, u as BlockRatio, v as BlockSize, w as BlockTextAlign, x as BlockTone, y as BlockWeight, z as ButtonBlock, C as ComponentGoalOptions, D as ComponentWeightEntry, E as CompoundLocator, F as DecideInput, G as DecideOutcome, H as DecisionSnapshot, J as EventType, K as GoalDefinition, L as GoalOptions, N as GraphConfig, O as GraphSnapshot, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LOCAL_MODE_BANNER, T as LinkBlock, U as MAX_BLOCK_ARMS, V as MAX_BLOCK_CHILDREN, W as MAX_BLOCK_DEPTH, X as MAX_BLOCK_NODES, Y as MAX_BLOCK_TEXT_LEN, Z as MicroSignalEmitter, _ as MicroSignalType, $ as PROD_KEYLESS_ERROR, a1 as QueueConfig, a2 as SNAPSHOT_STORAGE_KEY_PREFIX, a3 as SectionMapEntry, a4 as SentientClient, a5 as SentientConfig, a6 as SentientEvent, a7 as SessionConfig, a8 as SessionManager, a9 as SitePalette, aa as SlotConfigEntry, ab as SlotOps, ac as SpacerBlock, ad as StackBlock, ae as TextBlock, af as WeightEntry, ag as attachMicroSignalDetectors, ah as grantConsent, ai as init, aj as isDoNotTrackEnabled, ak as readSnapshot, al as renderPrePaintScript, an as writeSnapshot } from './index-BvHshOSe.js';
1
+ export { A as AssignResult, a as Assignment, B as BLOCK_ALIGNS, c as BLOCK_EMPHASES, d as BLOCK_FITS, e as BLOCK_GAPS, f as BLOCK_GRID_COLUMNS, g as BLOCK_HEADING_LEVELS, h as BLOCK_JUSTIFIES, i as BLOCK_RATIOS, j as BLOCK_SIZES, k as BLOCK_TEXT_ALIGNS, l as BLOCK_TONES, m as BLOCK_WEIGHTS, n as BadgeBlock, o as BlockAlign, p as BlockEmphasis, q as BlockFit, r as BlockGap, s as BlockJustify, t as BlockNode, u as BlockRatio, v as BlockSize, w as BlockTextAlign, x as BlockTone, y as BlockWeight, z as ButtonBlock, C as ComponentGoalOptions, D as ComponentWeightEntry, E as CompoundLocator, F as DecideInput, G as DecideOutcome, H as DecisionSnapshot, J as EventType, K as GoalDefinition, L as GoalOptions, N as GraphConfig, O as GraphSnapshot, P as GridBlock, Q as HeadingBlock, R as ImageBlock, S as LEGACY_SESSION_COOKIE_NAME, T as LOCAL_MODE_BANNER, U as LinkBlock, V as MAX_BLOCK_ARMS, W as MAX_BLOCK_CHILDREN, X as MAX_BLOCK_DEPTH, Y as MAX_BLOCK_NODES, Z as MAX_BLOCK_TEXT_LEN, _ as MicroSignalEmitter, $ as MicroSignalType, a0 as PROD_KEYLESS_ERROR, a2 as QueueConfig, a3 as SNAPSHOT_STORAGE_KEY_PREFIX, a4 as SectionMapEntry, a5 as SentientClient, a6 as SentientConfig, a7 as SentientEvent, a8 as SessionConfig, a9 as SessionManager, aa as SitePalette, ab as SlotConfigEntry, ac as SlotOps, ad as SpacerBlock, ae as StackBlock, af as TextBlock, ag as WeightEntry, ah as _registerConsentUpgradeInit, ai as attachMicroSignalDetectors, aj as grantConsent, ak as init, al as isDoNotTrackEnabled, am as readSnapshot, an as renderPrePaintScript, ap as sessionCookieName, aq as writeSnapshot } from './index-BbrtAtrY.js';
2
2
  export { A as AGENT_INTENTS, a as AgentIntent, b as SlotDeclInput, c as agentIntent, d as agentUaList, e as armOfResult, f as baselineResultFor, g as baselineSlots, i as classifiedAgents, j as deriveSessionSegment, k as detectDeviceClass, l as detectTimeOfDay, m as detectTrafficSource, n as matchedAgentToken, r as referrerDomainFromReferer, t as toWireSlot, u as uaTokenMatch } from './session-meta-BVvq5RBB.js';
3
3
  export { SlotResult } from '@sentientui/policy';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var ct=Object.create;var pe=Object.defineProperty,dt=Object.defineProperties,ut=Object.getOwnPropertyDescriptor,pt=Object.getOwnPropertyDescriptors,gt=Object.getOwnPropertyNames,Fe=Object.getOwnPropertySymbols,ft=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty,mt=Object.prototype.propertyIsEnumerable;var We=(e,t,n)=>t in e?pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,b=(e,t)=>{for(var n in t||(t={}))je.call(t,n)&&We(e,n,t[n]);if(Fe)for(var n of Fe(t))mt.call(t,n)&&We(e,n,t[n]);return e},oe=(e,t)=>dt(e,pt(t));var yt=(e,t)=>{for(var n in t)pe(e,n,{get:t[n],enumerable:!0})},He=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of gt(t))!je.call(e,u)&&u!==n&&pe(e,u,{get:()=>t[u],enumerable:!(c=ut(t,u))||c.enumerable});return e};var ht=(e,t,n)=>(n=e!=null?ct(ft(e)):{},He(t||!e||!e.__esModule?pe(n,"default",{value:e,enumerable:!0}):n,e)),St=e=>He(pe({},"__esModule",{value:!0}),e);var fn={};yt(fn,{AGENT_INTENTS:()=>_e,BLOCK_ALIGNS:()=>jt,BLOCK_EMPHASES:()=>Vt,BLOCK_FITS:()=>qt,BLOCK_GAPS:()=>Wt,BLOCK_GRID_COLUMNS:()=>Zt,BLOCK_HEADING_LEVELS:()=>en,BLOCK_JUSTIFIES:()=>Ht,BLOCK_RATIOS:()=>Yt,BLOCK_SIZES:()=>zt,BLOCK_TEXT_ALIGNS:()=>Xt,BLOCK_TONES:()=>Jt,BLOCK_WEIGHTS:()=>Qt,LOCAL_MODE_BANNER:()=>Ke,MAX_BLOCK_ARMS:()=>rn,MAX_BLOCK_CHILDREN:()=>on,MAX_BLOCK_DEPTH:()=>nn,MAX_BLOCK_NODES:()=>tn,MAX_BLOCK_TEXT_LEN:()=>sn,PROD_KEYLESS_ERROR:()=>Be,SNAPSHOT_STORAGE_KEY_PREFIX:()=>te,agentIntent:()=>Ve,agentUaList:()=>ge,armOfResult:()=>Ae,attachMicroSignalDetectors:()=>nt,baselineResultFor:()=>ie,baselineSlots:()=>qe,classifiedAgents:()=>Xe,deriveSessionSegment:()=>Ye,detectDeviceClass:()=>me,detectTimeOfDay:()=>Se,detectTrafficSource:()=>ye,grantConsent:()=>pn,init:()=>at,isDoNotTrackEnabled:()=>Ue,matchedAgentToken:()=>Me,readSnapshot:()=>Te,referrerDomainFromReferer:()=>he,renderPrePaintScript:()=>Ze,toWireSlot:()=>ve,uaTokenMatch:()=>fe,writeSnapshot:()=>ae});module.exports=St(fn);function we(){try{if(typeof crypto!="undefined"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch(e){}try{if(typeof crypto!="undefined"&&typeof crypto.getRandomValues=="function"){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t="";for(let n=0;n<16;n++)t+=e[n].toString(16).padStart(2,"0"),(n===3||n===5||n===7||n===9)&&(t+="-");return t}}catch(e){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function be(e){return e?`_${e.slice(0,12)}`:""}var vt="_snt_uid",xt=365,wt="_snt_uid";function bt(){return we()}function kt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Et(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(c){}}function It(e){try{return localStorage.getItem(e)}catch(t){return null}}function Ct(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function _t(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function At(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Tt(e){try{sessionStorage.removeItem(e)}catch(t){}}function Ot(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 Rt(e){try{localStorage.removeItem(e)}catch(t){}}function Bt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Dt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function ke(e){var y,x,B,C,_,A;if(typeof window=="undefined")return Dt;let t=be(e==null?void 0:e.apiKey),n=(y=e==null?void 0:e.cookieName)!=null?y:`${vt}${t}`,c=`${wt}${t}`,s=((x=e==null?void 0:e.cookieTTLDays)!=null?x:xt)*24*60*60,p=L=>L&&L.length>0?L:null,d=(A=(_=(C=(B=p(kt(n)))!=null?B:p(It(c)))!=null?C:p(_t(c)))!=null?_:p(e==null?void 0:e.ssrSessionId))!=null?A:bt();Et(n,d,s);let r=Ct(c,d),o=Ot(n),i=r?!1:At(c,d),a=!r&&!o&&!i;return{getSessionId:()=>d,isEphemeral:()=>a,destroy:()=>{d=null,Bt(n),Rt(c),Tt(c)}}}function q(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function re(e){if(e.ok===!0)return"delivered";let{status:t}=e;return typeof t!="number"?"retry":t>=200&&t<300?"delivered":t>=400&&t<500&&t!==429?"dropped":"retry"}function Ee(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let c=JSON.parse(n);return Array.isArray(c)?(localStorage.removeItem(e),c.slice(-t)):[]}catch(n){return[]}}function Z(e,t,n){try{let c=(()=>{try{let s=localStorage.getItem(n);if(!s)return[];let p=JSON.parse(s);return Array.isArray(p)?p:[]}catch(s){return[]}})(),u=new Map;for(let s of c)u.set(s.id,s);for(let s of e)u.set(s.id,s);localStorage.setItem(n,JSON.stringify([...u.values()].slice(-t)))}catch(c){}}function Ie(e,t){try{let n=localStorage.getItem(t);if(!n)return;let c=JSON.parse(n);if(!Array.isArray(c))return;let u=new Set(e),s=c.filter(p=>!u.has(p.id));if(s.length===c.length)return;s.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(s))}catch(n){}}var Lt=500,Pt=56*1024;function Le(e){return`_snt_retry_${e.slice(0,12)}`}var Mt={push:()=>{},flush:()=>{},destroy:()=>{}};function ze(e){var U,P,z;if(typeof window=="undefined")return Mt;let t=(U=e.flushIntervalMs)!=null?U:5e3,n=(P=e.maxBatchSize)!=null?P:20,c=(z=e.maxRetrySize)!=null?z:100,u=e.ingestUrl,s=e.apiKey,p=Le(s),d=[],r=new Set,o=[],i=f=>{for(let S of f)a.delete(S),!r.has(S)&&(r.add(S),o.push(S));for(;o.length>Lt;){let S=o.shift();S&&r.delete(S)}Ie(f,p)},a=new Set,y=f=>{r.has(f.id)||a.has(f.id)||(a.add(f.id),d.push(f))},x=f=>{for(let S of f)r.has(S.id)||(a.add(S.id),d.push(S))},B=Ee(p,c);for(let f of B)y(f);let C=0,_=0,A=(f,S=!0)=>{if(f.length===0)return;let Q=JSON.stringify(f),ee=f.map(V=>V.id),W;try{W=fetch(u,{method:"POST",keepalive:!0,body:Q,headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})}catch(V){Z(f,c,p),x(f),_++,C=Date.now()+q(_);return}let le=V=>{if(re(V)!=="retry"){if(!V.ok&&S){let ne=f.filter(X=>X.eventType!=="pageview");if(ne.length>0&&ne.length<f.length){i(f.filter(X=>X.eventType==="pageview").map(X=>X.id)),A(ne,!1);return}}i(ee),_=0,C=0;return}Z(f,c,p),x(f),_++,C=Date.now()+q(_)};W instanceof Promise?W.then(le).catch(()=>{Z(f,c,p),x(f),_++,C=Date.now()+q(_)}):le(W)},L=typeof TextEncoder!="undefined"?new TextEncoder:null,D=f=>L?L.encode(f).length:f.length,E=f=>{let S=[],Q=2;for(let ee of f){let W=D(JSON.stringify(ee))+1;if(S.length>0&&Q+W>Pt||S.length>=n)break;S.push(ee),Q+=W}return S},K=()=>{try{if(Date.now()<C)return;for(;d.length>0&&!(Date.now()<C);){let f=d.filter(Q=>!r.has(Q.id));if(d.length=0,f.length===0)break;let S=E(f);if(S.length===0)break;S.length<f.length&&d.push(...f.slice(S.length)),A(S)}}catch(f){}},G=!0,m=null;m=setInterval(()=>{G&&K()},t);let k=()=>{document.visibilityState==="hidden"&&K()},J=()=>{K()};return document.addEventListener("visibilitychange",k),window.addEventListener("pagehide",J),{push(f){y(f),d.length>=n&&K()},flush:K,destroy(){G=!1,m!==null&&(clearInterval(m),m=null),document.removeEventListener("visibilitychange",k),window.removeEventListener("pagehide",J),K()}}}var Kt=200;function Pe(e){return`_snt_goal_retry_${e.slice(0,12)}`}var Nt={send:()=>{},flush:()=>{},destroy:()=>{}};function Qe(e){var E,K,G;if(typeof window=="undefined")return Nt;let t=(E=e.flushIntervalMs)!=null?E:5e3,n=(K=e.maxRetrySize)!=null?K:100,c=(G=e.maxPerFlush)!=null?G:5,u=Pe(e.apiKey),s=[],p=new Set,d=new Set,r=[],o=0,i=0,a=!1,y=m=>{for(p.delete(m.id),d.has(m.id)||(d.add(m.id),r.push(m.id));r.length>Kt;){let k=r.shift();k&&d.delete(k)}Ie([m.id],u)},x=m=>{Z([m],n,u),!d.has(m.id)&&!p.has(m.id)&&(p.add(m.id),s.push(m)),Date.now()>=o&&(i++,o=Date.now()+q(i))},B=m=>{let k;try{k=fetch(e.url,{method:"POST",keepalive:!0,body:m.body,headers:e.headers})}catch(U){x(m);return}let J=U=>{var z;let P=re(U);if(P==="retry"){x(m);return}P==="dropped"&&((z=e.onDrop)==null||z.call(e,m,U.status)),y(m),i=0,o=0};k instanceof Promise?k.then(J).catch(()=>x(m)):J(k)},C=()=>{try{if(a||Date.now()<o)return;let m=0;for(;s.length>0&&m<c&&!(Date.now()<o);){let k=s.shift();p.delete(k.id),!d.has(k.id)&&(m++,B(k))}}catch(m){}},_=Ee(u,n);for(let m of _)p.has(m.id)||(p.add(m.id),s.push(m));_.length>0&&Z(_,n,u);let A=setInterval(C,t),L=()=>{document.visibilityState==="hidden"&&C()},D=()=>C();return document.addEventListener("visibilitychange",L),window.addEventListener("pagehide",D),{send(m){if(!a&&!(d.has(m.id)||p.has(m.id))){if(Date.now()<o){Z([m],n,u),p.add(m.id),s.push(m);return}B(m)}},flush:C,destroy(){clearInterval(A),document.removeEventListener("visibilitychange",L),window.removeEventListener("pagehide",D),C(),a=!0}}}var Gt=1800*1e3;function Ce(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Je(e=Gt,t){let n=new Map,c=`_snt_asgn${be(t)}_`,u=(o,i)=>`${c}${encodeURIComponent(o)}:${encodeURIComponent(i)}`,s=o=>{let i=o.slice(c.length),a=i.indexOf(":");if(a<0)return null;try{return{componentId:decodeURIComponent(i.slice(0,a)),segment:decodeURIComponent(i.slice(a+1))}}catch(y){return null}},p=()=>{try{let o=[];for(let i=0;i<localStorage.length;i++){let a=localStorage.key(i);a!=null&&a.startsWith(c)&&o.push(a)}return o}catch(o){return[]}},d=o=>o.assignedAt+(o.ttlMs&&o.ttlMs>0?o.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let o of p())try{let i=localStorage.getItem(o);if(!i)continue;let a=JSON.parse(i);if(d(a)){localStorage.removeItem(o);continue}let y=s(o);if(!y)continue;n.set(Ce(y.componentId,y.segment),a)}catch(i){}})(),{get(o,i){let a=n.get(Ce(o,i));return a?d(a)?(n.delete(Ce(o,i)),null):a:null},set(o,i,a){let y=Ce(o,i);n.set(y,a);try{localStorage.setItem(u(o,i),JSON.stringify(a))}catch(x){}},invalidate(o){let i=`${encodeURIComponent(o)}:`;for(let a of[...n.keys()])a.startsWith(i)&&n.delete(a);for(let a of p()){let y=s(a);if((y==null?void 0:y.componentId)===o)try{localStorage.removeItem(a)}catch(x){}}},clear(){n.clear();for(let o of p())try{localStorage.removeItem(o)}catch(i){}}}}var ge=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function fe(e){return Me(e)!==null}function Me(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=ge.find(c=>t.includes(c.toLowerCase())))!=null?n:null}var _e={GPTBot:"training","ChatGPT-User":"user","OAI-SearchBot":"search",ClaudeBot:"training","Claude-User":"user","Claude-SearchBot":"search",PerplexityBot:"search","Perplexity-User":"user","Google-Extended":"training","Applebot-Extended":"training","Meta-ExternalAgent":"training",Bytespider:"training",CCBot:"training",Amazonbot:"other","cohere-ai":"training",Diffbot:"other"};function Ve(e){if(!e)return"other";let t=ge.find(n=>n.toLowerCase()===e.toLowerCase());return t&&_e[t]||"other"}function Xe(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of ge)e[(t=_e[n])!=null?t:"other"].push(n);return e}function me(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 ye(e,t){if(!e)return"direct";try{let n=new URL(e);if(t)try{if(new URL(t).host===n.host)return"direct"}catch(u){}let c=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(c)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(c)?"social":"referral"}catch(n){return"direct"}}function he(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function Se(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Ye(e){let t=Ut("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function Ut(e,t){var s,p,d,r,o,i,a;let n=(p=(s=t==null?void 0:t.userAgent)==null?void 0:s.trim())!=null?p:"",c=(r=(d=t==null?void 0:t.referer)==null?void 0:d.trim())!=null?r:"",u=(o=t==null?void 0:t.now)!=null?o:new Date;return{sessionId:e,ephemeral:!1,utmParams:(i=t==null?void 0:t.utmParams)!=null?i:{},deviceClass:n?me(n):"desktop",trafficSource:c?ye(c,t==null?void 0:t.appOrigin):"direct",referrerDomain:he(c),timeOfDay:Se(u),dayOfWeek:(a=["sun","mon","tue","wed","thu","fri","sat"][u.getDay()])!=null?a:"sun",automation:(t==null?void 0:t.webdriver)===!0||fe(n)}}var se=require("@sentientui/policy");function ve(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 ie(e){let t=ve(e);return(0,se.slotResultFor)(t,(0,se.slotBaselineArm)(t))}function qe(e){let t={};for(let n of e)t[n.id]=ie(n);return t}function Ae(e){return typeof e=="string"?e:(0,se.canonicalArm)(e)}var te="_snt_snap:",$t=["low","medium","high"];function Te(e){try{let t=localStorage.getItem(te+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"||!$t.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 ae(e,t){try{localStorage.setItem(te+e,JSON.stringify(t))}catch(n){}}function Ze(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(te+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 Ge=require("@sentientui/policy");var Re=require("@sentientui/policy");var Be="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Ke="[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.",et=!1,Oe=!1;function Ft(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function tt(e){var d;let t=ke({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(d=t.getSessionId())!=null?d:"local",c=Ft(),u=import("@sentientui/core/local").then(r=>{let o=r;return o.LOCAL_ENGINE_AVAILABLE?(et||(et=!0,console.info(Ke)),o):(Oe||(Oe=!0,console.error(Be)),null)}).catch(()=>(Oe||(Oe=!0,console.error(Be)),null)),s=null;function p(r){let o=document.documentElement;o.dataset.sentientPersona===void 0&&(o.dataset.sentientPersona=r.persona,o.dataset.sentientConfidence=(0,Re.confidenceBand)(r.confidence))}return{isLocal:!0,async decide(r){var a,y,x;let o=await u;if(!o)return null;let i=o.createLocalEngine({sessionId:n,forcedPersona:c}).decide(r);return s=oe(b({},i),{layoutOrder:(y=(a=i.layoutOrder)!=null?a:s==null?void 0:s.layoutOrder)!=null?y:null,slots:b(b({},(x=s==null?void 0:s.slots)!=null?x:{}),i.slots)}),ae(e.apiKey||"local",{v:1,persona:s.persona,band:(0,Re.confidenceBand)(s.confidence),slots:s.slots,layoutOrder:s.layoutOrder,savedAt:Date.now()}),p(i),i},getSlotResult(r){var o,i,a;return(a=(i=s==null?void 0:s.slots[r])!=null?i:(o=e.initialSlots)==null?void 0:o[r])!=null?a:null},getPersona(){return s?{persona:s.persona,confidence:s.confidence,band:(0,Re.confidenceBand)(s.confidence)}:null},async assign(r,o){var y;let i=await u;return!i||!o||o.length===0?o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null:{variantId:(y=i.createLocalEngine({sessionId:n,forcedPersona:c}).decide({components:[{id:r,variantIds:o}]}).assignments[r])!=null?y:o[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var Wt=["none","sm","md","lg"],jt=["start","center","end","stretch"],Ht=["start","center","end","between"],zt=["sm","md","lg"],Qt=["normal","medium","bold"],Jt=["default","muted","accent"],Vt=["primary","secondary","ghost"],Xt=["left","center","right"],Yt=["auto","square","landscape","wide"],qt=["cover","contain"],Zt=[2,3,4],en=[2,3,4],tn=64,nn=5,on=12,rn=4,sn=500;function nt(e,t,n,c){let u=[];{let d=!1,r=[],o=()=>{if(d)return;let i=Date.now();for(r.push(i);r.length>0&&i-r[0]>500;)r.shift();r.length>=3&&(d=!0,e("rage_click"))};t.addEventListener("click",o),u.push(()=>t.removeEventListener("click",o))}{let s=!1,p=d=>{if(s||!(d.target instanceof Node)||!t.contains(d.target)&&t!==d.target)return;s=!0;let r=typeof window!="undefined"?window.getSelection():null,o=r?r.toString().length:0;e("text_copy",{selectionLength:o})};document.addEventListener("copy",p),u.push(()=>document.removeEventListener("copy",p))}{let s=!1,p=!1,d=null,r=()=>{d!==null&&(clearTimeout(d),d=null)},o=()=>{s||!p||(r(),d=setTimeout(()=>{!s&&p&&(s=!0,e("scroll_hesitation"))},3e3))},i=()=>{r(),o()},a=x=>{for(let B of x)p=B.intersectionRatio>.3,p?o():r()},y=new IntersectionObserver(a,{threshold:[.3]});y.observe(t),window.addEventListener("scroll",i,{passive:!0}),u.push(()=>{y.disconnect(),window.removeEventListener("scroll",i),r()})}if((c==null?void 0:c.tabLoss)!==!1){let s=!1,p=n!=null?n:Date.now(),d=()=>{if(s||document.visibilityState!=="hidden")return;let r=Date.now()-p;r<15e3&&(s=!0,e("tab_loss",{timeOnPage:r}))};document.addEventListener("visibilitychange",d),u.push(()=>document.removeEventListener("visibilitychange",d))}return()=>{for(let s of u)s()}}var ot="https://api.sentient-ui.com/v1/events",M=new Map,rt=null;function an(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var ln=3;function Ne(){return we()}function De(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function cn(e){if(typeof MessageChannel=="function"){let t=new MessageChannel;t.port1.onmessage=()=>{e.clear(),t.port1.close(),t.port2.close()},t.port2.postMessage(0)}else setTimeout(()=>e.clear(),0)}var st=new Set;function dn(e,t,n){let c=typeof window=="undefined"?null:window.history;if(!c)return()=>{};let u=!1,s,p=()=>{if(u)return;let o=De();!o||o===s||(s=o,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${o}`))},d=[];for(let o of["pushState","replaceState"]){let i=c[o],a=function(...y){let x=i.apply(this,y);return p(),x};c[o]=a,d.push([o,i,a])}window.addEventListener("popstate",p);let r=De();return r&&st.has(`${t}:${r}`)?s=r:p(),()=>{if(!u){u=!0,window.removeEventListener("popstate",p);for(let[o,i,a]of d)c[o]===a&&(c[o]=i)}}}var xe={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 un(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,c]of t)n.startsWith("utm_")&&(e[n]=c);return e}catch(e){return{}}}function it(e){return e.replace(/\/events\/?$/,"")}function Ue(){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 pn(e){var d;if(typeof window=="undefined")return;let t=e!=null?e:rt;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=M.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:c,upgrade:u}=n;if(!u||c.respectDoNotTrack!==!1&&Ue())return;let s=at(oe(b({},c),{consent:!0}));u(s);let p=(d=M.get(t))==null?void 0:d.dispose;M.set(t,{config:oe(b({},c),{consent:!0}),upgrade:null,dispose:p})}function gn(e){var d;let t=e.preConsentBehavior==="statistical_winner",n=it((d=e.ingestUrl)!=null?d:ot),c={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),async assign(r,o,i){if(!t)return null;try{let a=new URLSearchParams({componentId:r});for(let B of o!=null?o:[])a.append("variantIds[]",B);let y=await fetch(`${n}/winner?${a.toString()}`,{headers:c});return y.ok?{variantId:(await y.json()).variantId,assignmentTtlMs:0}:o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}catch(a){return o!=null&&o[0]?{variantId:o[0],assignmentTtlMs:0}:null}},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},s={track:r=>u.track(r),goal:((r,o,i,a)=>u.goal(r,o,i,a)),componentGoal:(r,o,i)=>u.componentGoal(r,o,i),identify:r=>u.identify(r),getAssignment:(r,o)=>u.getAssignment(r,o),assign:(r,o,i,a)=>u.assign(r,o,i,a),decide:r=>u.decide(r),getSlotResult:r=>u.getSlotResult(r),getPersona:()=>u.getPersona(),fetchWeights:()=>u.fetchWeights(),getGraph:()=>u.getGraph(),dispose:()=>u.dispose(),destroy:()=>u.destroy()};function p(r){u=r}return{proxy:s,setInner:p}}function at(e){var S,Q,ee,W,le,V,ne,X,$e;if(typeof window=="undefined")return xe;rt=e.apiKey;let t=M.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(l){}let n=e.respectDoNotTrack!==!1&&Ue(),c=e.consent===!1||n,u=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!u&&e.localMode!==!1)return c?(M.set(e.apiKey||"local",{config:e,upgrade:null}),xe):(M.set(e.apiKey||"local",{config:e,upgrade:null}),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."),M.set(e.apiKey,{config:e,upgrade:null}),xe;let{proxy:l,setInner:g}=gn(e);return M.set(e.apiKey,{config:e,upgrade:n?null:g}),l}if(!e.apiKey||!e.apiKey.startsWith("pk_"))return console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),xe;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),xe;let s=(S=e.ingestUrl)!=null?S:ot,p=Date.now(),d=ke({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),r=Je(void 0,e.apiKey),o=ze({ingestUrl:s,apiKey:e.apiKey}),i=it(s),a={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},y=new Set,x=Qe({url:`${i}/goals`,apiKey:e.apiKey,headers:a,onDrop:(l,g)=>{if(!e.debug){if(y.has(g))return;y.add(g)}console.warn(`[sentient] goal dropped (HTTP ${g}) \u2014 this will not be retried. `+(g===400?"The session was not found: call init() and let the session upsert complete before firing goals.":g===401||g===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),l)}}),B=me((Q=navigator.userAgent)!=null?Q:""),C=typeof window!="undefined"?window.location.origin:void 0,_=ye((ee=document.referrer)!=null?ee:"",C),A=(W=e.sessionSegment)!=null?W:`${B}:${_}`,L=new Map,D=new Map,E=null,K=l=>{for(let g of l)D.has(g.id)||D.set(g.id,ie(g))};if(e.initialSlots)for(let[l,g]of Object.entries(e.initialSlots))D.set(l,g);let G=Te(e.apiKey);if(G)for(let[l,g]of Object.entries(G.slots))D.has(l)||D.set(l,g);let m={low:.15,medium:.5,high:.85};if(e.initialPersona)E=b({},e.initialPersona);else{let l=document.documentElement.dataset;l.sentientPersona?E={persona:l.sentientPersona,confidence:(V=m[(le=l.sentientConfidence)!=null?le:"low"])!=null?V:.15}:G&&(E={persona:G.persona,confidence:(ne=m[G.band])!=null?ne:.15})}if(e.initialAssignments)for(let[l,g]of Object.entries(e.initialAssignments))r.set(l,A,{variantId:g,assignedAt:Date.now(),segment:A,confidence:1});let k=Promise.resolve(),J=d.getSessionId();if(J){let l=he((X=document.referrer)!=null?X:""),g=b(b(b({sessionId:J,deviceClass:B,trafficSource:_,referrerDomain:l,utmParams:un(),timeOfDay:Se(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:d.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||fe(($e=navigator.userAgent)!=null?$e:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{}),h=async()=>{for(let T=0;;T++){try{let I=await fetch(`${i}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(g),headers:a});if(I.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(I.ok||re(I)==="dropped")return}catch(I){}if(T>=ln){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(I=>setTimeout(I,q(T+1)))}};try{k=h()}catch(T){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:o});let U=new Set,P=null,z=!1,f={goal(l,g={},h=1,T=0){var R,ce,F,de,v,Y;let I=d.getSessionId();if(!I)return;let w=an(g)?g:{metadata:g},j=`${l}\0${(R=w.externalId)!=null?R:""}\0${(ce=w.stepIndex)!=null?ce:T}\0${(F=w.weight)!=null?F:h}`;if(U.has(j)){e.debug&&console.log(`[sentient] goal("${l}") already recorded for this action \u2014 not sent twice`);return}U.add(j),U.size===1&&cn(U);let $=Ne(),O={sessionId:I,name:l,metadata:(de=w.metadata)!=null?de:{},weight:(v=w.weight)!=null?v:h,stepIndex:(Y=w.stepIndex)!=null?Y:T,goalId:$,value:w.value,currency:w.currency,externalId:w.externalId};e.debug&&console.log("[sentient] goal",O);let H={id:$,body:JSON.stringify(O)};k.then(()=>x.send(H))},componentGoal(l,g,h){var O,H,R;let T=d.getSessionId();if(!T)return;let I=r.get(l,A),w=I?null:(O=D.get(l))!=null?O:null;if(!I&&w===null){e.debug&&console.warn(`[sentient] componentGoal("${l}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let j=I?I.variantId:Ae(w),$={id:Ne(),sessionId:T,projectId:e.apiKey,componentId:l,variantId:j,eventType:"goal_achieved",goalType:g,payload:b({reward:(H=h==null?void 0:h.reward)!=null?H:1,goalValue:h==null?void 0:h.value,currency:h==null?void 0:h.currency},(R=h==null?void 0:h.metadata)!=null?R:{}),timestamp:Date.now(),timeInSession:Date.now()-p,path:De()};e.debug&&console.log("[sentient] componentGoal",$),k.then(()=>o.push($))},identify(l){let g=d.getSessionId();g&&k.then(()=>{fetch(`${i}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:g,userId:l,ephemeral:d.isEphemeral()}),headers:a}).catch(()=>{})})},track(l){let g=d.getSessionId();if(!g)return;let h=oe(b({path:De()},l),{id:Ne(),sessionId:g,timestamp:Date.now(),timeInSession:Date.now()-p});e.debug&&console.log("[sentient] track",h),k.then(()=>o.push(h))},getAssignment(l,g){return r.get(l,g)},async assign(l,g,h,T){let I=d.getSessionId();if(!I)return null;let w=r.get(l,A);if(w&&(g!=null&&g.length||w.content!==void 0)){let O=w.ttlMs&&w.ttlMs>0?Math.max(0,w.assignedAt+w.ttlMs-Date.now()):0;return{variantId:w.variantId,assignmentTtlMs:O,content:w.content}}let j=L.get(l);if(j)return j;let $=(async()=>{await k;try{let O={sessionId:I,componentId:l,variantIds:g};T!==void 0?O.agentDataByVariant=T:h!==void 0&&(O.agentData=h);let H=await fetch(`${i}/assign`,{method:"POST",body:JSON.stringify(O),headers:a});if(!H.ok)return null;let R=await H.json();return r.set(l,A,b({variantId:R.variantId,assignedAt:Date.now(),segment:A,confidence:1,content:R.content},R.assignmentTtlMs&&R.assignmentTtlMs>0?{ttlMs:R.assignmentTtlMs}:{})),R}catch(O){return null}finally{L.delete(l)}})();return L.set(l,$),$},async decide(l){var T,I,w,j,$,O,H,R,ce;let g=d.getSessionId();if(!g)return null;let h=(T=l.slots)!=null?T:[];await k;try{let F={sessionId:g};l.sections&&l.sections.length>0&&(F.sections=l.sections.map(N=>({id:N}))),F.components=(I=l.components)!=null?I:[],h.length>0&&(F.slots=h.map(ve)),l.slotsFrom==="registry"&&(F.slotsFrom="registry"),l.v&&(F.v=l.v),e.persona&&(F.persona=e.persona);let de=await fetch(`${i}/decide`,{method:"POST",body:JSON.stringify(F),headers:a});if(!de.ok)return K(h),null;let v=await de.json(),Y={};for(let N of h)Y[N.id]=(j=(w=v.slots)==null?void 0:w[N.id])!=null?j:ie(N);if(v.slots)for(let[N,ue]of Object.entries(v.slots))N in Y||(Y[N]=ue);for(let[N,ue]of Object.entries(Y))D.set(N,ue);let lt=E!=null&&E.persona!=="unknown";v.persona&&!(v.persona==="unknown"&&lt)?E={persona:v.persona,confidence:($=v.confidence)!=null?$:0}:E||(E={persona:"unknown",confidence:0});for(let[N,ue]of Object.entries((O=v.assignments)!=null?O:{}))r.set(N,A,{variantId:ue,assignedAt:Date.now(),segment:A,confidence:1});return ae(e.apiKey,b(b({v:1,persona:E.persona,band:(0,Ge.confidenceBand)(E.confidence),slots:Object.fromEntries(D),layoutOrder:(H=v.layoutOrder)!=null?H:null,savedAt:Date.now()},v.slotConfig?{slotConfig:v.slotConfig}:{}),v.palette?{palette:v.palette}:{})),b(b(b(b({layoutOrder:(R=v.layoutOrder)!=null?R:null,assignments:(ce=v.assignments)!=null?ce:{},slots:Y,persona:E.persona,confidence:E.confidence},v.slotConfig?{slotConfig:v.slotConfig}:{}),v.goals?{goals:v.goals}:{}),v.sectionMap?{sectionMap:v.sectionMap}:{}),v.palette?{palette:v.palette}:{})}catch(F){return K(h),null}},getSlotResult(l){var g;return(g=D.get(l))!=null?g:null},getPersona(){return E?{persona:E.persona,confidence:E.confidence,band:(0,Ge.confidenceBand)(E.confidence)}:null},async fetchWeights(){var l;try{let g=await fetch(`${i}/weights`,{headers:a});return g.ok?(l=(await g.json()).components)!=null?l:[]:[]}catch(g){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var l;P==null||P(),z=!0,o.destroy(),x.destroy(),((l=M.get(e.apiKey))==null?void 0:l.dispose)===f.dispose&&M.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var l;P==null||P(),z=!0,o.destroy(),x.destroy(),d.destroy(),((l=M.get(e.apiKey))==null?void 0:l.dispose)===f.dispose&&M.delete(e.apiKey);try{localStorage.removeItem(te+e.apiKey),localStorage.removeItem(Le(e.apiKey)),localStorage.removeItem(Pe(e.apiKey))}catch(g){}e.debug&&console.log("[sentient] destroyed")}};if(M.set(e.apiKey,{config:e,upgrade:null,dispose:f.dispose}),P=dn(f,e.apiKey,l=>{k.then(()=>{z||st.add(l)})}),e.debug){let l=window;l.__sentient&&(l.__sentient.client=f)}return f}0&&(module.exports={AGENT_INTENTS,BLOCK_ALIGNS,BLOCK_EMPHASES,BLOCK_FITS,BLOCK_GAPS,BLOCK_GRID_COLUMNS,BLOCK_HEADING_LEVELS,BLOCK_JUSTIFIES,BLOCK_RATIOS,BLOCK_SIZES,BLOCK_TEXT_ALIGNS,BLOCK_TONES,BLOCK_WEIGHTS,LOCAL_MODE_BANNER,MAX_BLOCK_ARMS,MAX_BLOCK_CHILDREN,MAX_BLOCK_DEPTH,MAX_BLOCK_NODES,MAX_BLOCK_TEXT_LEN,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,agentIntent,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,toWireSlot,uaTokenMatch,writeSnapshot});
1
+ "use strict";var wt=Object.create;var fe=Object.defineProperty,xt=Object.defineProperties,bt=Object.getOwnPropertyDescriptor,kt=Object.getOwnPropertyDescriptors,Et=Object.getOwnPropertyNames,Ye=Object.getOwnPropertySymbols,Ct=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty,It=Object.prototype.propertyIsEnumerable;var qe=(e,t,n)=>t in e?fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,k=(e,t)=>{for(var n in t||(t={}))Ze.call(t,n)&&qe(e,n,t[n]);if(Ye)for(var n of Ye(t))It.call(t,n)&&qe(e,n,t[n]);return e},se=(e,t)=>xt(e,kt(t));var _t=(e,t)=>{for(var n in t)fe(e,n,{get:t[n],enumerable:!0})},et=(e,t,n,l)=>{if(t&&typeof t=="object"||typeof t=="function")for(let p of Et(t))!Ze.call(e,p)&&p!==n&&fe(e,p,{get:()=>t[p],enumerable:!(l=bt(t,p))||l.enumerable});return e};var At=(e,t,n)=>(n=e!=null?wt(Ct(e)):{},et(t||!e||!e.__esModule?fe(n,"default",{value:e,enumerable:!0}):n,e)),Ot=e=>et(fe({},"__esModule",{value:!0}),e);var xn={};_t(xn,{AGENT_INTENTS:()=>Be,BLOCK_ALIGNS:()=>Xt,BLOCK_EMPHASES:()=>tn,BLOCK_FITS:()=>rn,BLOCK_GAPS:()=>Vt,BLOCK_GRID_COLUMNS:()=>sn,BLOCK_HEADING_LEVELS:()=>an,BLOCK_JUSTIFIES:()=>Yt,BLOCK_RATIOS:()=>on,BLOCK_SIZES:()=>qt,BLOCK_TEXT_ALIGNS:()=>nn,BLOCK_TONES:()=>en,BLOCK_WEIGHTS:()=>Zt,LEGACY_SESSION_COOKIE_NAME:()=>Ke,LOCAL_MODE_BANNER:()=>We,MAX_BLOCK_ARMS:()=>un,MAX_BLOCK_CHILDREN:()=>dn,MAX_BLOCK_DEPTH:()=>cn,MAX_BLOCK_NODES:()=>ln,MAX_BLOCK_TEXT_LEN:()=>pn,PROD_KEYLESS_ERROR:()=>Me,SNAPSHOT_STORAGE_KEY_PREFIX:()=>te,_registerConsentUpgradeInit:()=>gn,agentIntent:()=>at,agentUaList:()=>ye,armOfResult:()=>De,attachMicroSignalDetectors:()=>ft,baselineResultFor:()=>le,baselineSlots:()=>dt,classifiedAgents:()=>lt,deriveSessionSegment:()=>ct,detectDeviceClass:()=>Se,detectTimeOfDay:()=>xe,detectTrafficSource:()=>ve,grantConsent:()=>vn,init:()=>vt,isDoNotTrackEnabled:()=>Qe,matchedAgentToken:()=>Fe,readSnapshot:()=>ce,referrerDomainFromReferer:()=>we,renderPrePaintScript:()=>ut,sessionCookieName:()=>Ie,toWireSlot:()=>be,uaTokenMatch:()=>he,writeSnapshot:()=>de});module.exports=Ot(xn);function Ce(){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 me(e){return e?`_${e.slice(0,12)}`:""}var Ke="_snt_uid";function Ie(e){return`${Ke}${me(e)}`}var Rt="_snt_uid",Tt=365,_e="_snt_uid";function Bt(){return Ce()}function tt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function Dt(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=strict; path=/`}catch(l){}}function Ge(e){try{return localStorage.getItem(e)}catch(t){return null}}function nt(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function ot(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function Lt(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function Pt(e){try{sessionStorage.removeItem(e)}catch(t){}}function Mt(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 Nt(e){try{localStorage.removeItem(e)}catch(t){}}function Kt(e){try{document.cookie=`${e}=; max-age=0; SameSite=strict; path=/`}catch(t){}}var Gt={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function Ae(e){var E,R,T,C,G,$,_;if(typeof window=="undefined")return Gt;let t=me(e==null?void 0:e.apiKey),n=(E=e==null?void 0:e.cookieName)!=null?E:Ie(e==null?void 0:e.apiKey),l=`${_e}${t}`,p=`${_e}_tomb${t}`,c=((R=e==null?void 0:e.cookieTTLDays)!=null?R:Tt)*24*60*60,i=v=>v&&v.length>0?v:null,u=()=>{var v,D;return t&&!(e!=null&&e.cookieName)&&Ge(p)===null?(D=(v=i(tt(Rt)))!=null?v:i(Ge(_e)))!=null?D:i(ot(_e)):null},s=(_=($=(G=(C=(T=i(tt(n)))!=null?T:i(Ge(l)))!=null?C:i(ot(l)))!=null?G:u())!=null?$:i(e==null?void 0:e.ssrSessionId))!=null?_:Bt();Dt(n,s,c);let o=nt(l,s),r=Mt(n),y=o?!1:Lt(l,s),h=!o&&!r&&!y;return{getSessionId:()=>s,isEphemeral:()=>h,destroy:()=>{s=null,Kt(n),Nt(l),Pt(l),t&&!(e!=null&&e.cookieName)&&nt(p,"1")}}}function X(e){return Math.min(6e4,1e3*2**Math.min(e,6))}function ie(e){if(e.ok===!0)return"delivered";let{status:t}=e;return typeof t!="number"?"retry":t>=200&&t<300?"delivered":t>=400&&t<500&&t!==429?"dropped":"retry"}function Oe(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let l=JSON.parse(n);return Array.isArray(l)?(localStorage.removeItem(e),l.slice(-t)):[]}catch(n){return[]}}function Y(e,t,n){try{let l=(()=>{try{let a=localStorage.getItem(n);if(!a)return[];let c=JSON.parse(a);return Array.isArray(c)?c:[]}catch(a){return[]}})(),p=new Map;for(let a of l)p.set(a.id,a);for(let a of e)p.set(a.id,a);localStorage.setItem(n,JSON.stringify([...p.values()].slice(-t)))}catch(l){}}function Re(e,t){try{let n=localStorage.getItem(t);if(!n)return;let l=JSON.parse(n);if(!Array.isArray(l))return;let p=new Set(e),a=l.filter(c=>!p.has(c.id));if(a.length===l.length)return;a.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(a))}catch(n){}}var Ut=500,$t=56*1024;function Ue(e){return`_snt_retry_${e.slice(0,12)}`}var Ft={push:()=>{},flush:()=>{},destroy:()=>{}};function rt(e){var q,M,ne;if(typeof window=="undefined")return Ft;let t=(q=e.flushIntervalMs)!=null?q:5e3,n=(M=e.maxBatchSize)!=null?M:20,l=(ne=e.maxRetrySize)!=null?ne:100,p=e.ingestUrl,a=e.apiKey,c=Ue(a),i=[],u=new Set,s=[],o=f=>{for(let x of f)r.delete(x),!u.has(x)&&(u.add(x),s.push(x));for(;s.length>Ut;){let x=s.shift();x&&u.delete(x)}Re(f,c)},r=new Set,y=()=>{for(;i.length>l;){let f=i.shift();f&&r.delete(f.id)}},h=f=>{u.has(f.id)||r.has(f.id)||(r.add(f.id),i.push(f),y())},E=f=>{for(let x of f)u.has(x.id)||(r.add(x.id),i.push(x));y()},R=Oe(c,l);for(let f of R)h(f);let T=0,C=0,G=(f,x=!0)=>{if(f.length===0)return;let j=JSON.stringify(f),Z=f.map(z=>z.id),F;try{F=fetch(p,{method:"POST",keepalive:!0,body:j,headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`}})}catch(z){Y(f,l,c),E(f),C++,T=Date.now()+X(C);return}let ue=z=>{if(ie(z)!=="retry"){if(!z.ok&&x){let oe=f.filter(Q=>Q.eventType!=="pageview");if(oe.length>0&&oe.length<f.length){o(f.filter(Q=>Q.eventType==="pageview").map(Q=>Q.id)),G(oe,!1);return}}o(Z),C=0,T=0;return}Y(f,l,c),E(f),C++,T=Date.now()+X(C)};F instanceof Promise?F.then(ue).catch(()=>{Y(f,l,c),E(f),C++,T=Date.now()+X(C)}):ue(F)},$=typeof TextEncoder!="undefined"?new TextEncoder:null,_=f=>$?$.encode(f).length:f.length,v=f=>{let x=[],j=2;for(let Z of f){let F=_(JSON.stringify(Z))+1;if(x.length>0&&j+F>$t||x.length>=n)break;x.push(Z),j+=F}return x},D=()=>{try{if(Date.now()<T)return;for(;i.length>0&&!(Date.now()<T);){let f=i.filter(j=>!u.has(j.id));if(i.length=0,f.length===0)break;let x=v(f);if(x.length===0)break;x.length<f.length&&i.push(...f.slice(x.length)),G(x)}}catch(f){}},m=!0,O=null;O=setInterval(()=>{m&&D()},t);let P=()=>{document.visibilityState==="hidden"&&D()},W=()=>{D()};return document.addEventListener("visibilitychange",P),window.addEventListener("pagehide",W),{push(f){h(f),i.length>=n&&D()},flush:D,destroy(){m=!1,O!==null&&(clearInterval(O),O=null),document.removeEventListener("visibilitychange",P),window.removeEventListener("pagehide",W),D()}}}var Wt=200;function $e(e){return`_snt_goal_retry_${e.slice(0,12)}`}var jt={send:()=>{},flush:()=>{},destroy:()=>{}};function st(e){var _,v,D;if(typeof window=="undefined")return jt;let t=(_=e.flushIntervalMs)!=null?_:5e3,n=(v=e.maxRetrySize)!=null?v:100,l=(D=e.maxPerFlush)!=null?D:5,p=$e(e.apiKey),a=[],c=new Set,i=new Set,u=[],s=0,o=0,r=!1,y=m=>{for(c.delete(m.id),i.has(m.id)||(i.add(m.id),u.push(m.id));u.length>Wt;){let O=u.shift();O&&i.delete(O)}Re([m.id],p)},h=m=>{Y([m],n,p),!i.has(m.id)&&!c.has(m.id)&&(c.add(m.id),a.push(m)),Date.now()>=s&&(o++,s=Date.now()+X(o))},E=m=>{let O;try{O=fetch(e.url,{method:"POST",keepalive:!0,body:m.body,headers:e.headers})}catch(W){h(m);return}let P=W=>{var M;let q=ie(W);if(q==="retry"){h(m);return}q==="dropped"&&((M=e.onDrop)==null||M.call(e,m,W.status)),y(m),o=0,s=0};O instanceof Promise?O.then(P).catch(()=>h(m)):P(O)},R=()=>{try{if(r||Date.now()<s)return;let m=0;for(;a.length>0&&m<l&&!(Date.now()<s);){let O=a.shift();c.delete(O.id),!i.has(O.id)&&(m++,E(O))}}catch(m){}},T=Oe(p,n);for(let m of T)c.has(m.id)||(c.add(m.id),a.push(m));T.length>0&&Y(T,n,p);let C=setInterval(R,t),G=()=>{document.visibilityState==="hidden"&&R()},$=()=>R();return document.addEventListener("visibilitychange",G),window.addEventListener("pagehide",$),{send(m){if(!r&&!(i.has(m.id)||c.has(m.id))){if(Date.now()<s){Y([m],n,p),c.add(m.id),a.push(m);return}E(m)}},flush:R,destroy(){clearInterval(C),document.removeEventListener("visibilitychange",G),window.removeEventListener("pagehide",$),R(),r=!0}}}var Ht=1800*1e3;function Te(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function it(e=Ht,t){let n=new Map,l=`_snt_asgn${me(t)}_`,p=(s,o)=>`${l}${encodeURIComponent(s)}:${encodeURIComponent(o)}`,a=s=>{let o=s.slice(l.length),r=o.indexOf(":");if(r<0)return null;try{return{componentId:decodeURIComponent(o.slice(0,r)),segment:decodeURIComponent(o.slice(r+1))}}catch(y){return null}},c=()=>{try{let s=[];for(let o=0;o<localStorage.length;o++){let r=localStorage.key(o);r!=null&&r.startsWith(l)&&s.push(r)}return s}catch(s){return[]}},i=s=>s.assignedAt+(s.ttlMs&&s.ttlMs>0?s.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let s of c())try{let o=localStorage.getItem(s);if(!o)continue;let r=JSON.parse(o);if(i(r)){localStorage.removeItem(s);continue}let y=a(s);if(!y)continue;n.set(Te(y.componentId,y.segment),r)}catch(o){}})(),{get(s,o){let r=n.get(Te(s,o));return r?i(r)?(n.delete(Te(s,o)),null):r:null},set(s,o,r){let y=Te(s,o);n.set(y,r);try{localStorage.setItem(p(s,o),JSON.stringify(r))}catch(h){}},clear(){n.clear();for(let s of c())try{localStorage.removeItem(s)}catch(o){}}}}var ye=["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 he(e){return Fe(e)!==null}function Fe(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=ye.find(l=>t.includes(l.toLowerCase())))!=null?n:null}var Be={GPTBot:"training","ChatGPT-User":"user","OAI-SearchBot":"search",ClaudeBot:"training","Claude-User":"user","Claude-SearchBot":"search",PerplexityBot:"search","Perplexity-User":"user","Google-Extended":"training","Applebot-Extended":"training","Meta-ExternalAgent":"training",Bytespider:"training",CCBot:"training",Amazonbot:"other","cohere-ai":"training",Diffbot:"other"};function at(e){if(!e)return"other";let t=ye.find(n=>n.toLowerCase()===e.toLowerCase());return t&&Be[t]||"other"}function lt(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of ye)e[(t=Be[n])!=null?t:"other"].push(n);return e}function Se(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 ve(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(p){}let l=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(l)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(l)?"social":"referral"}catch(n){return"direct"}}function we(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}function xe(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function ct(e){let t=zt("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function zt(e,t){var a,c,i,u,s,o,r;let n=(c=(a=t==null?void 0:t.userAgent)==null?void 0:a.trim())!=null?c:"",l=(u=(i=t==null?void 0:t.referer)==null?void 0:i.trim())!=null?u:"",p=(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:{},deviceClass:n?Se(n):"desktop",trafficSource:l?ve(l,t==null?void 0:t.appOrigin):"direct",referrerDomain:we(l),timeOfDay:xe(p),dayOfWeek:(r=["sun","mon","tue","wed","thu","fri","sat"][p.getDay()])!=null?r:"sun",automation:(t==null?void 0:t.webdriver)===!0||he(n)}}var ae=require("@sentientui/policy");function be(e){return k(k(k({id:e.id},e.arms?{arms:[...e.arms]}:{}),e.dims?{dims:Object.fromEntries(Object.entries(e.dims).map(([t,n])=>[t,[...n]]))}:{}),e.baseline!==void 0?{baseline:e.baseline}:{})}function le(e){let t=be(e);return(0,ae.slotResultFor)(t,(0,ae.slotBaselineArm)(t))}function dt(e){let t={};for(let n of e)t[n.id]=le(n);return t}function De(e){return typeof e=="string"?e:(0,ae.canonicalArm)(e)}var te="_snt_snap:",Qt=["low","medium","high"];function ce(e){try{let t=localStorage.getItem(te+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"||!Qt.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 de(e,t){try{localStorage.setItem(te+e,JSON.stringify(t))}catch(n){}}function ut(e){return"(function(){try{var r=localStorage.getItem("+JSON.stringify(te+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 Pe=require("@sentientui/policy");var Me="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",We="[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.",pt=!1,Le=!1;function Jt(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function gt(e){var s;let t=Ae({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(s=t.getSessionId())!=null?s:"local",l=Jt(),p=import("@sentientui/core/local").then(o=>{let r=o;return r.LOCAL_ENGINE_AVAILABLE?(pt||(pt=!0,console.info(We)),r):(Le||(Le=!0,console.error(Me)),null)}).catch(()=>(Le||(Le=!0,console.error(Me)),null)),a=null,c={low:.15,medium:.5,high:.85},i=(()=>{var r;if(e.initialPersona)return k({},e.initialPersona);let o=ce(e.apiKey||"local");return o?{persona:o.persona,confidence:(r=c[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,Pe.confidenceBand)(o.confidence))}return{isLocal:!0,async decide(o){var h,E,R;let r=await p;if(!r)return null;let y=r.createLocalEngine({sessionId:n,forcedPersona:l}).decide(o);return a=se(k({},y),{layoutOrder:(E=(h=y.layoutOrder)!=null?h:a==null?void 0:a.layoutOrder)!=null?E:null,slots:k(k({},(R=a==null?void 0:a.slots)!=null?R:{}),y.slots)}),de(e.apiKey||"local",{v:1,persona:a.persona,band:(0,Pe.confidenceBand)(a.confidence),slots:a.slots,layoutOrder:a.layoutOrder,savedAt:Date.now()}),u(y),y},getSlotResult(o){var r,y,h;return(h=(y=a==null?void 0:a.slots[o])!=null?y:(r=e.initialSlots)==null?void 0:r[o])!=null?h:null},getPersona(){let o=a!=null?a:i;return o?{persona:o.persona,confidence:o.confidence,band:(0,Pe.confidenceBand)(o.confidence)}:null},async assign(o,r){var E;let y=await p;return!y||!r||r.length===0?r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null:{variantId:(E=y.createLocalEngine({sessionId:n,forcedPersona:l}).decide({components:[{id:o,variantIds:r}]}).assignments[o])!=null?E:r[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>t.destroy()}}var Vt=["none","sm","md","lg"],Xt=["start","center","end","stretch"],Yt=["start","center","end","between"],qt=["sm","md","lg"],Zt=["normal","medium","bold"],en=["default","muted","accent"],tn=["primary","secondary","ghost"],nn=["left","center","right"],on=["auto","square","landscape","wide"],rn=["cover","contain"],sn=[2,3,4],an=[2,3,4],ln=64,cn=5,dn=12,un=4,pn=500;function ft(e,t,n,l){let p=[];{let i=!1,u=[],s=()=>{if(i)return;let o=Date.now();for(u.push(o);u.length>0&&o-u[0]>500;)u.shift();u.length>=3&&(i=!0,e("rage_click"))};t.addEventListener("click",s),p.push(()=>t.removeEventListener("click",s))}{let a=!1,c=i=>{if(a||!(i.target instanceof Node)||!t.contains(i.target)&&t!==i.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",c),p.push(()=>document.removeEventListener("copy",c))}{let a=!1,c=!1,i=null,u=()=>{i!==null&&(clearTimeout(i),i=null)},s=()=>{a||!c||(u(),i=setTimeout(()=>{!a&&c&&(a=!0,e("scroll_hesitation"))},3e3))},o=()=>{u(),s()},r=h=>{for(let E of h)c=E.intersectionRatio>.3,c?s():u()},y=new IntersectionObserver(r,{threshold:[.3]});y.observe(t),window.addEventListener("scroll",o,{passive:!0}),p.push(()=>{y.disconnect(),window.removeEventListener("scroll",o),u()})}if((l==null?void 0:l.tabLoss)!==!1){let a=!1,c=n!=null?n:Date.now(),i=()=>{if(a||document.visibilityState!=="hidden")return;let u=Date.now()-c;u<15e3&&(a=!0,e("tab_loss",{timeOnPage:u}))};document.addEventListener("visibilitychange",i),p.push(()=>document.removeEventListener("visibilitychange",i))}return()=>{for(let a of p)a()}}var mt="https://api.sentient-ui.com/v1/events",K=new Map,yt=null;function gn(e,t){let n=K.get(e);n&&n.upgrade&&(n.reinit=t)}function fn(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var mn=3;function je(){return Ce()}function Ne(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function yn(){let e=new WeakMap,t=new Map,n=!1,l=(i,u,s)=>{let o=i.get(u);return s===null?o?!0:(i.set(u,new Set),!1):o?o.has(s)?!0:(o.add(s),!1):(i.set(u,new Set([s])),!1)},p=typeof window!="undefined"&&"event"in window,a=()=>{if(!p)return;let i=window.event;return typeof Event=="function"&&i instanceof Event?i:void 0},c=()=>{if(p){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 s=new MessageChannel;s.port1.onmessage=()=>{s.port1.close(),s.port2.close(),u()},s.port2.postMessage(0)}};return{firedBefore(i,u){let s=a();if(s){let r=e.get(s);return r||(r=new Map,e.set(s,r)),l(r,i,u)}let o=l(t,i,u);return!o&&!n&&(n=!0,c()),o}}}var ht=new Set;function hn(e,t,n){let l=typeof window=="undefined"?null:window.history;if(!l)return()=>{};let p=!1,a,c=()=>{if(p)return;let s=Ne();!s||s===a||(a=s,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${s}`))},i=[];for(let s of["pushState","replaceState"]){let o=l[s],r=function(...y){let h=o.apply(this,y);return c(),h};l[s]=r,i.push([s,o,r])}window.addEventListener("popstate",c);let u=Ne();return u&&ht.has(`${t}:${u}`)?a=u:c(),()=>{if(!p){p=!0,window.removeEventListener("popstate",c);for(let[s,o,r]of i)l[s]===r&&(l[s]=o)}}}var ke={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 Sn(){try{let e={},t=new URLSearchParams(window.location.search);for(let[n,l]of t)n.startsWith("utm_")&&(e[n]=l);return e}catch(e){return{}}}function St(e){return e.replace(/\/events\/?$/,"")}function Qe(){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 vn(e){var u;if(typeof window=="undefined")return;let t=e!=null?e:yt;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=K.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:l,upgrade:p,reinit:a}=n;if(!p){n.upgradeBlockedReason&&console.warn(n.upgradeBlockedReason);return}if(l.respectDoNotTrack!==!1&&Qe())return;let c=(a!=null?a:vt)(se(k({},l),{consent:!0}));p(c);let i=(u=K.get(t))==null?void 0:u.dispose;K.set(t,{config:se(k({},l),{consent:!0}),upgrade:null,dispose:i})}function wn(e){var s;let t=e.preConsentBehavior==="statistical_winner",n=St((s=e.ingestUrl)!=null?s:mt),l={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},p=new Map,a=new Map,c={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(o,r,y){if(!t)return Promise.resolve(null);let h=p.get(o);return h?Promise.resolve(h):ze(a,o,async()=>{try{let E=new URLSearchParams({componentId:o});for(let G of r!=null?r:[])E.append("variantIds[]",G);let R=await fetch(`${n}/winner?${E.toString()}`,{headers:l});if(!R.ok)return r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null;let C={variantId:(await R.json()).variantId,assignmentTtlMs:0};return p.set(o,C),C}catch(E){return r!=null&&r[0]?{variantId:r[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),dispose:()=>{},destroy:()=>{}},i={track:o=>c.track(o),goal:((o,r,y,h)=>c.goal(o,r,y,h)),componentGoal:(o,r,y)=>c.componentGoal(o,r,y),identify:o=>c.identify(o),getAssignment:(o,r)=>c.getAssignment(o,r),assign:(o,r,y,h)=>c.assign(o,r,y,h),decide:o=>c.decide(o),getSlotResult:o=>c.getSlotResult(o),getPersona:()=>c.getPersona(),fetchWeights:()=>c.fetchWeights(),getGraph:()=>c.getGraph(),dispose:()=>c.dispose(),destroy:()=>c.destroy()};function u(o){c=o}return{proxy:i,setInner:u}}function ze(e,t,n){let l=e.get(t);if(l)return l;let p=(async()=>{try{return await n()}finally{e.delete(t)}})();return e.set(t,p),p}function vt(e){var x,j,Z,F,ue,z,oe,Q,Je;if(typeof window=="undefined")return ke;yt=e.apiKey||"local";let t=K.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(d){}let n=e.respectDoNotTrack!==!1&&Qe(),l=e.consent===!1||n,p=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!p&&e.localMode!==!1)return K.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."}),l?ke:gt(e);if(l){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."),K.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."}),ke;let{proxy:d,setInner:g}=wn(e);return K.set(e.apiKey,{config:e,upgrade:n?null:g}),d}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."),ke;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),ke;let a=(x=e.ingestUrl)!=null?x:mt,c=Date.now(),i=Ae({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),u=it(void 0,e.apiKey),s=rt({ingestUrl:a,apiKey:e.apiKey}),o=St(a),r={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},y=new Set,h=st({url:`${o}/goals`,apiKey:e.apiKey,headers:r,onDrop:(d,g)=>{if(!e.debug){if(y.has(g))return;y.add(g)}console.warn(`[sentient] goal dropped (HTTP ${g}) \u2014 this will not be retried. `+(g===400?"The session was not found: call init() and let the session upsert complete before firing goals.":g===401||g===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),d)}}),E=Se((j=navigator.userAgent)!=null?j:""),R=window.location.origin,T=ve((Z=document.referrer)!=null?Z:"",R),C=(F=e.sessionSegment)!=null?F:`${E}:${T}`,G=new Map,$=new Map,_=new Map,v=null,D=d=>{for(let g of d)_.has(g.id)||_.set(g.id,le(g))};if(e.initialSlots)for(let[d,g]of Object.entries(e.initialSlots))_.set(d,g);let m=ce(e.apiKey);if(m)for(let[d,g]of Object.entries(m.slots))_.has(d)||_.set(d,g);let O={low:.15,medium:.5,high:.85};if(e.initialPersona)v=k({},e.initialPersona);else{let d=document.documentElement.dataset;d.sentientPersona?v={persona:d.sentientPersona,confidence:(z=O[(ue=d.sentientConfidence)!=null?ue:"low"])!=null?z:.15}:m&&(v={persona:m.persona,confidence:(oe=O[m.band])!=null?oe:.15})}if(e.initialAssignments)for(let[d,g]of Object.entries(e.initialAssignments))u.set(d,C,{variantId:g,assignedAt:Date.now(),segment:C,confidence:1});let P=Promise.resolve(),W=i.getSessionId();if(W){let d=we((Q=document.referrer)!=null?Q:""),g=k(k(k({sessionId:W,deviceClass:E,trafficSource:T,referrerDomain:d,utmParams:Sn(),timeOfDay:xe(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:i.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||he((Je=navigator.userAgent)!=null?Je:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{}),S=async()=>{for(let I=0;;I++){try{let A=await fetch(`${o}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(g),headers:r});if(A.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(A.ok||ie(A)==="dropped")return}catch(A){}if(I>=mn){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(A=>setTimeout(A,X(I+1)))}};try{P=S()}catch(I){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:s});let q=yn(),M=null,ne=!1,f={goal(d,g={},S=1,I=0){var pe,ge,re,b,H,Ee,B;let A=i.getSessionId();if(!A)return;let w=fn(g)?g:{metadata:g},N=[d,(pe=w.externalId)!=null?pe:"",(ge=w.stepIndex)!=null?ge:I,(re=w.weight)!=null?re:S].join("\0"),U=w.value!==void 0?`${w.value}\0${(b=w.currency)!=null?b:""}`:null;if(q.firedBefore(N,U)){e.debug&&console.log(`[sentient] goal("${d}") already recorded for this action \u2014 not sent twice`);return}let L=je(),J={sessionId:A,name:d,metadata:(H=w.metadata)!=null?H:{},weight:(Ee=w.weight)!=null?Ee:S,stepIndex:(B=w.stepIndex)!=null?B:I,goalId:L,value:w.value,currency:w.currency,externalId:w.externalId};e.debug&&console.log("[sentient] goal",J);let ee={id:L,body:JSON.stringify(J)};P.then(()=>h.send(ee))},componentGoal(d,g,S){var L,J,ee;let I=i.getSessionId();if(!I)return;let A=u.get(d,C),w=A?null:(L=_.get(d))!=null?L:null;if(!A&&w===null){e.debug&&console.warn(`[sentient] componentGoal("${d}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}let N=A?A.variantId:De(w),U={id:je(),sessionId:I,projectId:e.apiKey,componentId:d,variantId:N,eventType:"goal_achieved",goalType:g,payload:k({reward:(J=S==null?void 0:S.reward)!=null?J:1,goalValue:S==null?void 0:S.value,currency:S==null?void 0:S.currency},(ee=S==null?void 0:S.metadata)!=null?ee:{}),timestamp:Date.now(),timeInSession:Date.now()-c,path:Ne()};e.debug&&console.log("[sentient] componentGoal",U),P.then(()=>s.push(U))},identify(d){let g=i.getSessionId();g&&P.then(()=>{fetch(`${o}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:g,userId:d,ephemeral:i.isEphemeral()}),headers:r}).catch(()=>{})})},track(d){let g=i.getSessionId();if(!g)return;let S=se(k({path:Ne()},d),{id:je(),sessionId:g,timestamp:Date.now(),timeInSession:Date.now()-c});e.debug&&console.log("[sentient] track",S),P.then(()=>s.push(S))},getAssignment(d,g){return u.get(d,g)},async assign(d,g,S,I){let A=i.getSessionId();if(!A)return null;let w=u.get(d,C);if(w&&(g!=null&&g.length||w.content!==void 0)){let N=w.ttlMs&&w.ttlMs>0?Math.max(0,w.assignedAt+w.ttlMs-Date.now()):0;return{variantId:w.variantId,assignmentTtlMs:N,content:w.content}}return ze(G,d,async()=>{await P;try{let N={sessionId:A,componentId:d,variantIds:g};I!==void 0?N.agentDataByVariant=I:S!==void 0&&(N.agentData=S);let U=await fetch(`${o}/assign`,{method:"POST",body:JSON.stringify(N),headers:r});if(!U.ok)return null;let L=await U.json();return u.set(d,C,k({variantId:L.variantId,assignedAt:Date.now(),segment:C,confidence:1,content:L.content},L.assignmentTtlMs&&L.assignmentTtlMs>0?{ttlMs:L.assignmentTtlMs}:{})),L}catch(N){return null}})},async decide(d){var w,N;let g=i.getSessionId();if(!g)return null;let S=(w=d.slots)!=null?w:[],I={sessionId:g};d.sections&&d.sections.length>0&&(I.sections=d.sections.map(U=>({id:U}))),I.components=(N=d.components)!=null?N:[],S.length>0&&(I.slots=S.map(be)),d.slotsFrom==="registry"&&(I.slotsFrom="registry"),d.v&&(I.v=d.v),e.persona&&(I.persona=e.persona);let A=JSON.stringify(I);return ze($,A,async()=>{var U,L,J,ee,pe,ge;await P;try{let re=await fetch(`${o}/decide`,{method:"POST",body:A,headers:r});if(!re.ok)return D(S),null;let b=await re.json(),H={};for(let B of S){let V=(U=b.slots)==null?void 0:U[B.id];if(V!==void 0){H[B.id]=V,_.set(B.id,V);continue}let Ve=_.get(B.id);if(Ve!==void 0)H[B.id]=Ve;else{let Xe=le(B);H[B.id]=Xe,_.set(B.id,Xe)}}if(b.slots)for(let[B,V]of Object.entries(b.slots))B in H||(H[B]=V,_.set(B,V));let Ee=v!=null&&v.persona!=="unknown";b.persona&&!(b.persona==="unknown"&&Ee)?v={persona:b.persona,confidence:(L=b.confidence)!=null?L:0}:v||(v={persona:"unknown",confidence:0});for(let[B,V]of Object.entries((J=b.assignments)!=null?J:{}))u.set(B,C,{variantId:V,assignedAt:Date.now(),segment:C,confidence:1});return de(e.apiKey,k(k({v:1,persona:v.persona,band:(0,He.confidenceBand)(v.confidence),slots:Object.fromEntries(_),layoutOrder:(ee=b.layoutOrder)!=null?ee:null,savedAt:Date.now()},b.slotConfig?{slotConfig:b.slotConfig}:{}),b.palette?{palette:b.palette}:{})),k(k(k(k({layoutOrder:(pe=b.layoutOrder)!=null?pe:null,assignments:(ge=b.assignments)!=null?ge:{},slots:H,persona:v.persona,confidence:v.confidence},b.slotConfig?{slotConfig:b.slotConfig}:{}),b.goals?{goals:b.goals}:{}),b.sectionMap?{sectionMap:b.sectionMap}:{}),b.palette?{palette:b.palette}:{})}catch(re){return D(S),null}})},getSlotResult(d){var g;return(g=_.get(d))!=null?g:null},getPersona(){return v?{persona:v.persona,confidence:v.confidence,band:(0,He.confidenceBand)(v.confidence)}:null},async fetchWeights(){var d;try{let g=await fetch(`${o}/weights`,{headers:r});return g.ok?(d=(await g.json()).components)!=null?d:[]:[]}catch(g){return[]}},getGraph(){return{pageNodes:[],capturedAt:0}},dispose(){var d;M==null||M(),ne=!0,s.destroy(),h.destroy(),((d=K.get(e.apiKey))==null?void 0:d.dispose)===f.dispose&&K.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var d;M==null||M(),ne=!0,s.destroy(),h.destroy(),i.destroy(),u.clear(),((d=K.get(e.apiKey))==null?void 0:d.dispose)===f.dispose&&K.delete(e.apiKey);try{localStorage.removeItem(te+e.apiKey),localStorage.removeItem(Ue(e.apiKey)),localStorage.removeItem($e(e.apiKey))}catch(g){}e.debug&&console.log("[sentient] destroyed")}};if(K.set(e.apiKey,{config:e,upgrade:null,dispose:f.dispose}),M=hn(f,e.apiKey,d=>{P.then(()=>{ne||ht.add(d)})}),e.debug){let d=window;d.__sentient&&(d.__sentient.client=f)}return f}0&&(module.exports={AGENT_INTENTS,BLOCK_ALIGNS,BLOCK_EMPHASES,BLOCK_FITS,BLOCK_GAPS,BLOCK_GRID_COLUMNS,BLOCK_HEADING_LEVELS,BLOCK_JUSTIFIES,BLOCK_RATIOS,BLOCK_SIZES,BLOCK_TEXT_ALIGNS,BLOCK_TONES,BLOCK_WEIGHTS,LEGACY_SESSION_COOKIE_NAME,LOCAL_MODE_BANNER,MAX_BLOCK_ARMS,MAX_BLOCK_CHILDREN,MAX_BLOCK_DEPTH,MAX_BLOCK_NODES,MAX_BLOCK_TEXT_LEN,PROD_KEYLESS_ERROR,SNAPSHOT_STORAGE_KEY_PREFIX,_registerConsentUpgradeInit,agentIntent,agentUaList,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,sessionCookieName,toWireSlot,uaTokenMatch,writeSnapshot});
2
2
  //# sourceMappingURL=index.js.map