@sentientui/core 0.37.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +43 -1
  2. package/dist/{chunk-NCLBL5V3.mjs → chunk-EVF5PQ4U.mjs} +1 -1
  3. package/dist/{chunk-NCLBL5V3.mjs.map → chunk-EVF5PQ4U.mjs.map} +1 -1
  4. package/dist/chunk-VE2K45X4.mjs +2 -0
  5. package/dist/chunk-VE2K45X4.mjs.map +1 -0
  6. package/dist/chunk-XZRKD2GS.mjs +2 -0
  7. package/dist/chunk-XZRKD2GS.mjs.map +1 -0
  8. package/dist/{index-C-meVCmm.d.cts → index-BAfi7_FG.d.cts} +90 -5
  9. package/dist/{index-DbpGK3Dj.d.ts → index-DyKtujwf.d.ts} +90 -5
  10. package/dist/index-consent.js.map +1 -1
  11. package/dist/index-consent.mjs +1 -1
  12. package/dist/index-engagement.js +1 -1
  13. package/dist/index-engagement.js.map +1 -1
  14. package/dist/index-engagement.mjs +1 -1
  15. package/dist/index-graph.d.cts +5 -5
  16. package/dist/index-graph.d.ts +5 -5
  17. package/dist/index-graph.js +1 -1
  18. package/dist/index-graph.js.map +1 -1
  19. package/dist/index-graph.mjs +1 -1
  20. package/dist/index-graph.mjs.map +1 -1
  21. package/dist/index-local.d.cts +3 -3
  22. package/dist/index-local.d.ts +3 -3
  23. package/dist/index-region.d.cts +1 -1
  24. package/dist/index-region.d.ts +1 -1
  25. package/dist/index-region.mjs +1 -1
  26. package/dist/index-server.d.cts +78 -5
  27. package/dist/index-server.d.ts +78 -5
  28. package/dist/index-server.js +1 -1
  29. package/dist/index-server.js.map +1 -1
  30. package/dist/index-server.mjs +1 -1
  31. package/dist/index-server.mjs.map +1 -1
  32. package/dist/index.d.cts +3 -3
  33. package/dist/index.d.ts +3 -3
  34. package/dist/index.js +1 -1
  35. package/dist/index.js.map +1 -1
  36. package/dist/index.mjs +1 -1
  37. package/dist/{region-skeleton-D2ahkcbe.d.cts → region-skeleton-BRIVB-qf.d.cts} +1 -0
  38. package/dist/{region-skeleton-D2ahkcbe.d.ts → region-skeleton-BRIVB-qf.d.ts} +1 -0
  39. package/dist/{session-meta-DlCp0tyi.d.ts → session-meta-BtRtwsHI.d.ts} +7 -2
  40. package/dist/{session-meta-CJ-QAskZ.d.cts → session-meta-qx4kIL5y.d.cts} +7 -2
  41. package/package.json +1 -1
  42. package/dist/chunk-5CCBWT6H.mjs +0 -2
  43. package/dist/chunk-5CCBWT6H.mjs.map +0 -1
  44. package/dist/chunk-DU3AXQHR.mjs +0 -2
  45. package/dist/chunk-DU3AXQHR.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts","../src/agent-capture.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\nimport type { SlotConfigEntry } from './snapshot.js';\nimport type { RenderCaps } from './region-skeleton.js';\nimport type { SitePalette } from './blocks.js';\n\nexport type { SlotDeclInput, SlotResult, SlotConfigEntry, SitePalette };\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 /**\n * Optional: this project's SECRET key (sk_...), read from a server-only env\n * var. When set, SSR calls also send it as `X-Sentient-Server-Key`, which\n * proves they come from your server: the API then holds them to your plan's\n * per-key limit instead of the 100 requests/min per-IP cap meant for\n * browsers — without it, all SSR traffic from one server address shares that\n * one cap. Never set this in code that ships to the browser; it is ignored\n * (and not sent) when `window` exists.\n */\n serverKey?: 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 * Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.\n * Derive both this and `utmParams` with `extractTrackedParams(searchParams)`\n * — the Referer header never carries the landing page's own query string, so\n * without these two fields SSR-minted sessions have no campaign attribution\n * until the client SDK hydrates.\n */\n clickIds?: Record<string, string>;\n /**\n * The landing page's path (no query string). With it the server can tell a\n * paid click to a product page, or a Shopify `/discount/CODE` link, from any\n * other arrival on the FIRST decision of the visit.\n */\n landingPath?: 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/** Header carrying `serverKey` (apps/api lib/rate-limit.ts SERVER_KEY_HEADER). */\nexport const SERVER_KEY_HEADER = 'X-Sentient-Server-Key';\n\n/** Auth headers for an SSR call: the pk_, its Origin, and the optional server proof. */\nfunction ssrHeaders(config: ServerAssignConfig): Record<string, string> {\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 // A secret key must never leave a browser: if this module was bundled\n // client-side by mistake, drop it rather than send it.\n if (config.serverKey && typeof window === 'undefined') headers[SERVER_KEY_HEADER] = config.serverKey;\n return headers;\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 = ssrHeaders(config);\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 clickIds: config.clickIds,\n appOrigin: config.origin,\n landingPath: config.landingPath,\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 /** Registry mode only: content/ops/blocks for server-defined slots. */\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Registry mode only: site palette for block rendering. */\n palette?: SitePalette;\n /** Registry mode only: site styles the served Redesign arms borrow. */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\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 /** 'registry' serves the project's published slot_definitions as if declared\n * (and is the only way slotConfig/palette come back). Default 'request'.\n * Requires `registrySlotIds`: the `<Adaptive id>`s THIS page renders. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: decide only these published slot ids. Close-out turns\n * every slot decision into a trial without checking an exposure, so an\n * unscoped registry decide accrues trials — and session-level credit — for\n * every published slot on every page, including ones this page never\n * renders (CONTRACTS §2). Omitting it in registry mode is refused: the\n * call downgrades to request mode with one console.error, rather than\n * silently minting those trials.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render (CONTRACTS §2).\n * The server has no DOM here, so no fingerprint is sent and a Rewrite arm\n * is assumed to match; a real mismatch is reported from the browser as\n * drift. Declare `forms: false` for slots without an `onFormSubmit`, or a\n * form arm can be drawn that this page will refuse. Default per slot:\n * `{ forms: true, compose: true }`.\n */\n renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n let registryIds: string[] | null = null;\n if (params.slotsFrom === 'registry') {\n if (Array.isArray(params.registrySlotIds)) {\n registryIds = params.registrySlotIds;\n } else {\n console.error(\n \"[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). \" +\n 'An unscoped registry decide records a trial for every published slot on every page; falling back to request mode.',\n );\n }\n }\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 = ssrHeaders(config);\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n landingPath: config.landingPath,\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 // bootstrap:false — editor goals and the section map are snippet\n // data the React SDK never reads. An EMPTY id list is meaningful\n // (\"nothing published is on this page\"): zero trials, still a decide.\n ...(registryIds !== null\n ? {\n slotsFrom: 'registry',\n registrySlotIds: registryIds,\n bootstrap: false,\n // Always sent, so the server knows this is an SDK that can\n // render Rewrite arms — no `render` field means legacy.\n render: Object.fromEntries(\n // compose: true — the React SDK (the SSR consumer) renders\n // Redesign trees since native generation phase 2.\n registryIds.map((id) => [id, params.renderCaps?.[id] ?? { forms: true, compose: true }]),\n ),\n }\n : {}),\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 slotConfig?: Record<string, SlotConfigEntry>;\n palette?: SitePalette;\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\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 // Registry mode returns slots the request never declared — union them in\n // (same rule as the browser client), or an SSR page gets results for none\n // of its registry slots.\n for (const [slotId, result] of Object.entries(data.slots ?? {})) {\n if (!(slotId in slots)) slots[slotId] = result;\n }\n\n // Plain-object guard only (readSnapshot's rule): the server total-validated\n // the config at publish; a deep re-validation here would just drift.\n const slotConfigOk =\n data.slotConfig !== undefined && typeof data.slotConfig === 'object' && data.slotConfig !== null && !Array.isArray(data.slotConfig);\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 ...(slotConfigOk ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n ...(data.vocabulary ? { vocabulary: data.vocabulary } : {}),\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n","// Server-side capture of AI-assistant fetches, for any framework.\n// Spec: docs/superpowers/specs/2026-09-23-server-side-agent-capture-design.md §4.1\n//\n// Assistants that fetch a page without running JavaScript (ChatGPT-User,\n// Claude-User, Perplexity-User, GPTBot, …) never execute the snippet or the\n// React SDK, so only the server that answered can see them. Until this, only\n// Next.js AdaptiveRoot logged them; every other site read \"no AI traffic\",\n// which is wrong rather than empty.\n//\n// OBSERVATION ONLY. Nothing here may change a response based on the user\n// agent: that is cloaking, and SentientUI never claims to adapt serving to\n// agents. These functions return nothing a caller could branch on except\n// \"did this look like an agent\", and log to crawler_requests — never to\n// sessions, never to training, never to billing.\n\nimport { matchedAgentToken } from './session-meta.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type AgentCaptureOptions = {\n /** Your public `pk_` key — the same one the snippet uses. */\n apiKey: string;\n /** API base ending in `/v1`. Defaults to the hosted API. */\n baseUrl?: string;\n /** Which capture path saw the fetch. Shown per row on the dashboard. */\n source?: 'middleware' | 'edge' | 'ssr';\n /**\n * REQUIRED on edge runtimes (Vercel Routing Middleware, Cloudflare Workers,\n * Netlify Edge): they cancel outstanding work once the response is\n * returned, so a fire-and-forget request without it is silently dropped.\n * Pass the platform's `waitUntil` (`ctx.waitUntil.bind(ctx)` on Workers,\n * `waitUntil` from `@vercel/functions`). Node servers do not need it.\n */\n waitUntil?: (p: Promise<unknown>) => void;\n /** Injectable for tests. */\n fetchImpl?: typeof fetch;\n};\n\n/** The minimum of a request both the Fetch API `Request` and hand-rolled\n * objects satisfy. */\nexport type CapturableRequest = {\n url: string;\n headers: { get(name: string): string | null };\n};\n\n/** Pathname only: a query string can carry tokens, emails or campaign ids. */\nfunction pathOf(url: string): string {\n try {\n return new URL(url, 'http://localhost').pathname || '/';\n } catch {\n return url.split(/[?#]/, 1)[0] || '/';\n }\n}\n\n/**\n * Low-level sender: posts one agent fetch to `/v1/crawler-events`. Never\n * throws, never blocks. The API re-derives the agent from `userAgent`\n * itself, so `botName` is advisory.\n */\nexport function postAgentFetch(\n entry: { path: string; userAgent: string; botName: string },\n opts: AgentCaptureOptions,\n): void {\n const doFetch = opts.fetchImpl ?? (typeof fetch === 'function' ? fetch : undefined);\n if (!doFetch || !opts.apiKey) return;\n try {\n const p = doFetch(`${opts.baseUrl ?? DEFAULT_API_BASE_URL}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent,\n source: opts.source ?? 'middleware',\n }),\n }).catch(() => undefined);\n opts.waitUntil?.(p);\n } catch {\n /* capture must never break the page it is observing */\n }\n}\n\n/**\n * Log this request if its user agent is a known AI assistant or crawler.\n * Works with a Fetch API `Request` (edge runtimes, Hono, Remix / React\n * Router, Astro, SvelteKit) or anything with `url` + `headers.get`.\n *\n * Returns whether the request matched, so a caller can skip its own work;\n * it must NOT be used to serve anything different. Non-matching requests —\n * nearly all of them — make no network call.\n */\nexport function captureAgentRequest(req: CapturableRequest, opts: AgentCaptureOptions): boolean {\n let userAgent = '';\n try {\n userAgent = req.headers.get('user-agent') ?? '';\n } catch {\n return false;\n }\n const botName = matchedAgentToken(userAgent);\n if (!botName) return false;\n postAgentFetch({ path: pathOf(req.url), userAgent, botName }, opts);\n return true;\n}\n\ntype ConnectRequest = {\n url?: string;\n originalUrl?: string;\n headers: Record<string, string | string[] | undefined>;\n};\n\n/**\n * Connect-style middleware (Express, Nitro / Nuxt on Node, Fastify via\n * middie, any `(req, res, next)` stack). Calls `next()` synchronously and\n * logs in the background; it never touches the response.\n */\nexport function sentientAgentMiddleware(\n opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>,\n): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void {\n return (req, _res, next) => {\n try {\n const raw = req.headers['user-agent'];\n const ua = Array.isArray(raw) ? raw[0] ?? '' : raw ?? '';\n captureAgentRequest(\n { url: req.originalUrl ?? req.url ?? '/', headers: { get: (n) => (n.toLowerCase() === 'user-agent' ? ua : null) } },\n { ...opts, source: 'middleware' },\n );\n } catch {\n /* never block the request */\n }\n next();\n };\n}\n"],"mappings":"iNA0FO,IAAMA,EAAoB,wBAGjC,SAASC,EAAWC,EAAoD,CACtE,IAAMC,EAAkC,CACtC,eAAgB,mBAChB,cAAe,UAAUD,EAAO,MAAM,EACxC,EACA,OAAIA,EAAO,SAAQC,EAAQ,OAASD,EAAO,QAGvCA,EAAO,WAAa,OAAO,QAAW,cAAaC,EAAQH,CAAiB,EAAIE,EAAO,WACpFC,CACT,CAOA,IAAMC,EAAqB,IAE3B,SAASC,EACPC,EACAC,EACAC,EACmB,CACnB,IAAMC,EAAa,IAAI,gBACjBC,EAAQ,WAAW,IAAMD,EAAW,MAAM,EAAGD,CAAS,EAC5D,OAAO,MAAMF,EAAKK,EAAAC,EAAA,GAAKL,GAAL,CAAW,OAAQE,EAAW,MAAO,EAAC,EAAE,QAAQ,IAChE,aAAaC,CAAK,CACpB,CACF,CAqBA,eAAsBG,EACpBC,EACAC,EACAb,EAC4B,CAnJ9B,IAAAc,EAqJE,GAAId,EAAO,WAAY,MAAO,CAAC,EAE/B,IAAMM,GAAYQ,EAAAd,EAAO,YAAP,KAAAc,EAAoBZ,EAChCD,EAAUF,EAAWC,CAAM,EAI3Be,EAAcL,IAAA,GACfM,EAA0BH,EAAW,CACtC,UAAWb,EAAO,UAClB,QAASA,EAAO,QAChB,UAAWA,EAAO,UAClB,SAAUA,EAAO,SACjB,UAAWA,EAAO,OAClB,YAAaA,EAAO,WACtB,CAAC,GACGA,EAAO,QAAU,CAAE,QAASA,EAAO,OAAQ,EAAI,CAAC,GAGtD,GAAI,CACF,IAAMiB,EAAM,MAAMd,EAChB,GAAGH,EAAO,OAAO,YACjB,CAAE,OAAQ,OAAQ,QAAAC,EAAS,KAAM,KAAK,UAAUc,CAAW,CAAE,EAC7DT,CACF,EACA,GAAIW,EAAI,SAAW,IACjB,QAAQ,KACN,gJACF,UACS,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xBC,EAAAJ,EAAK,YAAL,MAAAI,EAAA,KAAAJ,EAAiBM,EACnB,OAAQT,EAAA,CAER,CACF,CAWO,SAASU,EAAoBC,EAAwBR,EAAoC,CA3FhG,IAAAC,EA4FE,IAAIQ,EAAY,GAChB,GAAI,CACFA,GAAYR,EAAAO,EAAI,QAAQ,IAAI,YAAY,IAA5B,KAAAP,EAAiC,EAC/C,OAAQJ,EAAA,CACN,MAAO,EACT,CACA,IAAMa,EAAUC,EAAkBF,CAAS,EAC3C,OAAKC,GACLZ,EAAe,CAAE,KAAMH,GAAOa,EAAI,GAAG,EAAG,UAAAC,EAAW,QAAAC,CAAQ,EAAGV,CAAI,EAC3D,IAFc,EAGvB,CAaO,SAASY,GACdZ,EAC4E,CAC5E,MAAO,CAACQ,EAAKK,EAAMC,IAAS,CAtH9B,IAAAb,EAAAC,EAAAC,EAuHI,GAAI,CACF,IAAMY,EAAMP,EAAI,QAAQ,YAAY,EAC9BQ,EAAK,MAAM,QAAQD,CAAG,GAAId,EAAAc,EAAI,CAAC,IAAL,KAAAd,EAAU,GAAKc,GAAA,KAAAA,EAAO,GACtDR,EACE,CAAE,KAAKJ,GAAAD,EAAAM,EAAI,cAAJ,KAAAN,EAAmBM,EAAI,MAAvB,KAAAL,EAA8B,IAAK,QAAS,CAAE,IAAM,GAAO,EAAE,YAAY,IAAM,aAAea,EAAK,IAAM,CAAE,EAClHC,EAAAC,EAAA,GAAKlB,GAAL,CAAW,OAAQ,YAAa,EAClC,CACF,OAAQH,EAAA,CAER,CACAiB,EAAK,CACP,CACF","names":["SERVER_KEY_HEADER","ssrHeaders","config","headers","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","_a","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","_l","declaredSlots","registryIds","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor","slotId","slotConfigOk","DEFAULT_API_BASE_URL","pathOf","url","e","postAgentFetch","entry","opts","_a","_b","_c","_d","doFetch","p","captureAgentRequest","req","userAgent","botName","matchedAgentToken","sentientAgentMiddleware","_res","next","raw","ua","__spreadProps","__spreadValues"]}
1
+ {"version":3,"sources":["../src/server.ts","../src/agent-capture.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\nimport type { SlotConfigEntry } from './snapshot.js';\nimport type { RenderCaps } from './region-skeleton.js';\nimport type { SitePalette } from './blocks.js';\n\nexport type { SlotDeclInput, SlotResult, SlotConfigEntry, SitePalette };\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 /**\n * Optional: this project's SECRET key (sk_...), read from a server-only env\n * var. When set, SSR calls also send it as `X-Sentient-Server-Key`, which\n * proves they come from your server: the API then holds them to your plan's\n * per-key limit instead of the 100 requests/min per-IP cap meant for\n * browsers — without it, all SSR traffic from one server address shares that\n * one cap. Never set this in code that ships to the browser; it is ignored\n * (and not sent) when `window` exists.\n */\n serverKey?: 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 * Ad-platform click IDs (gclid, fbclid, ttclid, …) from the landing URL.\n * Derive both this and `utmParams` with `extractTrackedParams(searchParams)`\n * — the Referer header never carries the landing page's own query string, so\n * without these two fields SSR-minted sessions have no campaign attribution\n * until the client SDK hydrates.\n */\n clickIds?: Record<string, string>;\n /**\n * The landing page's path (no query string). With it the server can tell a\n * paid click to a product page, or a Shopify `/discount/CODE` link, from any\n * other arrival on the FIRST decision of the visit.\n */\n landingPath?: 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/** Header carrying `serverKey` (apps/api lib/rate-limit.ts SERVER_KEY_HEADER). */\nexport const SERVER_KEY_HEADER = 'X-Sentient-Server-Key';\n\n/** Auth headers for an SSR call: the pk_, its Origin, and the optional server proof. */\nfunction ssrHeaders(config: ServerAssignConfig): Record<string, string> {\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 // A secret key must never leave a browser: if this module was bundled\n // client-side by mistake, drop it rather than send it.\n if (config.serverKey && typeof window === 'undefined') headers[SERVER_KEY_HEADER] = config.serverKey;\n return headers;\n}\n\n/** componentId → assigned variantId */\nexport type ServerAssignments = Record<string, string>;\n\ntype AssignResult = { variantId: string; assignmentTtlMs: number; unified?: true };\n\n/** `preloadAssignmentsDetailed`'s answer: the assignments, plus the ids the\n * server handed back as moved to the shared track (only when asked). */\nexport type ServerAssignmentsDetailed = { assignments: ServerAssignments; unified: string[] };\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 return (await preloadAssignmentsDetailed(components, sessionId, config)).assignments;\n}\n\n/**\n * `preloadAssignments`, and also which components were moved onto the shared\n * track. With `opts.unified` each assign says the page can follow such a move:\n * a moved id is then not assigned (nothing is recorded for it) and comes back\n * in `unified`, for the page to render as a slot. Pass those ids to\n * `<AdaptiveProvider initialUnified>`. Without it a moved id is served its\n * frozen result read-only, as for any older SDK.\n */\nexport async function preloadAssignmentsDetailed(\n components: Array<{ id: string; variantIds: string[] }>,\n sessionId: string,\n config: ServerAssignConfig,\n opts?: { unified?: boolean },\n): Promise<ServerAssignmentsDetailed> {\n // Opted-out visitor (DNT/GPC): render defaults, mint no session (audit P4).\n if (config.doNotTrack) return { assignments: {}, unified: [] };\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const headers = ssrHeaders(config);\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 clickIds: config.clickIds,\n appOrigin: config.origin,\n landingPath: config.landingPath,\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 {\n method: 'POST',\n headers,\n body: JSON.stringify({ sessionId, componentId: id, variantIds, ...(opts?.unified ? { caps: { unified: true } } : {}) }),\n },\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, unified: opts?.unified === true && body.unified === true };\n }),\n );\n\n const assignments: ServerAssignments = {};\n const unified: string[] = [];\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n // A moved id's variantId is only its declared baseline, not an\n // assignment: seeding it would settle the page on the frozen run.\n if (result.value.unified) unified.push(result.value.id);\n else assignments[result.value.id] = result.value.variantId;\n }\n }\n return { assignments, unified };\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 /** Registry mode only: content/ops/blocks for server-defined slots. */\n slotConfig?: Record<string, SlotConfigEntry>;\n /** Registry mode only: site palette for block rendering. */\n palette?: SitePalette;\n /** Registry mode only: site styles the served Redesign arms borrow. */\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n /** The visit's funnel stage, raw — projects with stages on, treated visitors\n * only. Pass it through `exposedStage` before it reaches the page. */\n stage?: string;\n /** The visit's serving context. Never for the page. */\n context?: string;\n /** Requested components moved onto the shared track (only with\n * `unifiedCaps`): not in `assignments`; render each as a slot. */\n unified?: string[];\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 /** 'registry' serves the project's published slot_definitions as if declared\n * (and is the only way slotConfig/palette come back). Default 'request'.\n * Requires `registrySlotIds`: the `<Adaptive id>`s THIS page renders. */\n slotsFrom?: 'request' | 'registry';\n /**\n * Registry mode: decide only these published slot ids. Close-out turns\n * every slot decision into a trial without checking an exposure, so an\n * unscoped registry decide accrues trials — and session-level credit — for\n * every published slot on every page, including ones this page never\n * renders (CONTRACTS §2). Omitting it in registry mode is refused: the\n * call downgrades to request mode with one console.error, rather than\n * silently minting those trials.\n */\n registrySlotIds?: string[];\n /**\n * Registry mode: what each slot on this page can render (CONTRACTS §2).\n * The server has no DOM here, so no fingerprint is sent and a Rewrite arm\n * is assumed to match; a real mismatch is reported from the browser as\n * drift. Declare `forms: false` for slots without an `onFormSubmit`, or a\n * form arm can be drawn that this page will refuse. Default per slot:\n * `{ forms: true, compose: true, ops: false }`.\n */\n renderCaps?: Record<string, Omit<RenderCaps, 'fp'>>;\n /** The page renders a moved (unified) component on the shared track: such\n * ids in `components` come back in `unified` instead of `assignments`,\n * with nothing recorded. Without it they are served the frozen result. */\n unifiedCaps?: boolean;\n },\n sessionId: string,\n config: ServerAssignConfig,\n): Promise<DecideResult> {\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const declaredSlots = params.slots ?? [];\n let registryIds: string[] | null = null;\n if (params.slotsFrom === 'registry') {\n if (Array.isArray(params.registrySlotIds)) {\n registryIds = params.registrySlotIds;\n } else {\n console.error(\n \"[SentientUI] preloadDecisions: slotsFrom: 'registry' needs registrySlotIds (the <Adaptive id>s this page renders). \" +\n 'An unscoped registry decide records a trial for every published slot on every page; falling back to request mode.',\n );\n }\n }\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 = ssrHeaders(config);\n\n const sessionBody = {\n ...buildSessionUpsertPayload(sessionId, {\n userAgent: config.userAgent,\n referer: config.referer,\n utmParams: config.utmParams,\n clickIds: config.clickIds,\n appOrigin: config.origin,\n landingPath: config.landingPath,\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 // bootstrap:false — editor goals and the section map are snippet\n // data the React SDK never reads. An EMPTY id list is meaningful\n // (\"nothing published is on this page\"): zero trials, still a decide.\n ...(registryIds !== null\n ? {\n slotsFrom: 'registry',\n registrySlotIds: registryIds,\n bootstrap: false,\n // Always sent, so the server knows this is an SDK that can\n // render Rewrite arms — no `render` field means legacy.\n render: Object.fromEntries(\n // compose: true — the React SDK (the SSR consumer) renders\n // Redesign trees since native generation phase 2.\n // ops: false — nothing here applies `ops`. Without it an\n // SSR'd <Adaptive id> matching a script-tag component was drawn\n // its ops-only version, rendered the original, and booked a trial.\n registryIds.map((id) => [id, params.renderCaps?.[id] ?? { forms: true, compose: true, ops: false }]),\n ),\n }\n : {}),\n ...(config.persona ? { persona: config.persona } : {}),\n ...(params.unifiedCaps ? { caps: { unified: true } } : {}),\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 slotConfig?: Record<string, SlotConfigEntry>;\n palette?: SitePalette;\n vocabulary?: import('./style-vocabulary.js').StyleVocabulary;\n persona?: string;\n confidence?: number;\n stage?: unknown;\n context?: unknown;\n unified?: unknown;\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 // Registry mode returns slots the request never declared — union them in\n // (same rule as the browser client), or an SSR page gets results for none\n // of its registry slots.\n for (const [slotId, result] of Object.entries(data.slots ?? {})) {\n if (!(slotId in slots)) slots[slotId] = result;\n }\n\n // Plain-object guard only (readSnapshot's rule): the server total-validated\n // the config at publish; a deep re-validation here would just drift.\n const slotConfigOk =\n data.slotConfig !== undefined && typeof data.slotConfig === 'object' && data.slotConfig !== null && !Array.isArray(data.slotConfig);\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 ...(slotConfigOk ? { slotConfig: data.slotConfig } : {}),\n ...(data.palette ? { palette: data.palette } : {}),\n ...(data.vocabulary ? { vocabulary: data.vocabulary } : {}),\n ...(typeof data.stage === 'string' ? { stage: data.stage } : {}),\n ...(typeof data.context === 'string' ? { context: data.context } : {}),\n ...(params.unifiedCaps && Array.isArray(data.unified)\n ? { unified: data.unified.filter((id): id is string => typeof id === 'string') }\n : {}),\n };\n } catch (err) {\n console.error('[SentientUI] preloadDecisions: decide threw', err);\n return fallback;\n }\n}\n\n/**\n * Fixed namespace for server-goal ids. It is public (it ships in this file), so\n * it adds no secrecy: the id's uniqueness comes from the session id it hashes\n * (see trackServerGoal). Never change it: a retried delivery must map to the\n * same goal id.\n */\nexport const SERVER_GOAL_NAMESPACE = '3d8f5a21-7c64-4b19-8e0a-5f2c91d7b6e3';\n\n/**\n * Pure-JS SHA-1 (FIPS 180-4) for runtimes without Web Crypto: Node 18 (our\n * engines floor is 18.18) has no unflagged `globalThis.crypto`, and without\n * this every server goal there would end 'failed'. @internal: exported for\n * the test vector only; not re-exported from the entry.\n */\nexport function sha1Fallback(data: Uint8Array): Uint8Array {\n const rotl = (x: number, n: number): number => (x << n) | (x >>> (32 - n));\n const len = data.length;\n const padded = new Uint8Array(((len + 8) >> 6) * 64 + 64);\n padded.set(data);\n padded[len] = 0x80;\n const view = new DataView(padded.buffer);\n view.setUint32(padded.length - 8, Math.floor((len * 8) / 0x100000000));\n view.setUint32(padded.length - 4, (len * 8) >>> 0);\n let h0 = 0x67452301, h1 = 0xefcdab89, h2 = 0x98badcfe, h3 = 0x10325476, h4 = 0xc3d2e1f0;\n const w = new Array<number>(80);\n for (let off = 0; off < padded.length; off += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(off + i * 4);\n for (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3]! ^ w[i - 8]! ^ w[i - 14]! ^ w[i - 16]!, 1);\n let a = h0, b = h1, c = h2, d = h3, e = h4;\n for (let i = 0; i < 80; i++) {\n const [f, k] =\n i < 20 ? [(b & c) | (~b & d), 0x5a827999]\n : i < 40 ? [b ^ c ^ d, 0x6ed9eba1]\n : i < 60 ? [(b & c) | (b & d) | (c & d), 0x8f1bbcdc]\n : [b ^ c ^ d, 0xca62c1d6];\n const t = (rotl(a, 5) + f! + e + k! + w[i]!) | 0;\n e = d; d = c; c = rotl(b, 30); b = a; a = t;\n }\n h0 = (h0 + a) | 0; h1 = (h1 + b) | 0; h2 = (h2 + c) | 0; h3 = (h3 + d) | 0; h4 = (h4 + e) | 0;\n }\n const out = new Uint8Array(20);\n const ov = new DataView(out.buffer);\n [h0, h1, h2, h3, h4].forEach((v, i) => ov.setUint32(i * 4, v >>> 0));\n return out;\n}\n\n/**\n * RFC-4122 v5 UUID (SHA-1 over namespace bytes + name), via Web Crypto so this\n * file stays free of `node:` imports and `Buffer` (it also hosts the SSR\n * helpers, which run on Edge and Deno). @internal: exported for the test vector.\n */\nexport async function uuidV5(name: string, namespace: string): Promise<string> {\n const hex = namespace.replace(/-/g, '');\n const nsBytes = new Uint8Array(16);\n for (let i = 0; i < 16; i++) nsBytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n const nameBytes = new TextEncoder().encode(name);\n const input = new Uint8Array(16 + nameBytes.length);\n input.set(nsBytes, 0);\n input.set(nameBytes, 16);\n const subtle = globalThis.crypto?.subtle;\n const h = (subtle ? new Uint8Array(await subtle.digest('SHA-1', input)) : sha1Fallback(input)).slice(0, 16);\n h[6] = (h[6]! & 0x0f) | 0x50;\n h[8] = (h[8]! & 0x3f) | 0x80;\n const x = Array.from(h, (b) => b.toString(16).padStart(2, '0')).join('');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20, 32)}`;\n}\n\nconst DEFAULT_GOAL_API_BASE = 'https://api.sentient-ui.com/v1';\nconst DEFAULT_GOAL_TIMEOUT_MS = 5000;\n\nexport type TrackServerGoalOptions = {\n /** Project SECRET key (sk_...), from a server-only env var. */\n serverKey: string;\n /** The visitor's session id: `readSessionCookie(cookies, apiKey)` in the same\n * request, or the id you stored from `client.getVisitorId()`. Null/empty\n * means nobody to credit: nothing is sent. */\n sessionId: string | null | undefined;\n /** Goal name, as defined in your project (e.g. 'purchase'). */\n name: string;\n /** Your own id for this conversion (order id, Stripe event id, user id).\n * Calling again with the same session + name + dedupeKey counts once. */\n dedupeKey: string;\n value?: number;\n currency?: string;\n metadata?: Record<string, unknown>;\n /** API base including `/v1`. Defaults to the hosted API. */\n apiBaseUrl?: string;\n fetch?: typeof fetch;\n /** Give up after this many ms. Default 5000. */\n timeoutMs?: number;\n};\n\n/**\n * Records a conversion from your server (route handler, server action,\n * webhook). Never throws; resolves 'recorded', 'skipped_no_visitor' (no\n * session to credit, nothing sent) or 'failed'.\n *\n * Hand-rolling this (cookie, deterministic id, sk_ call) was the only way to\n * count a webhook-confirmed conversion, and few customers would get the dedupe\n * right: a random goal id per attempt counts a retried webhook twice. The id\n * here is derived from session + name + dedupeKey, so replays collapse\n * server-side; dedupeKey is also sent as externalId, which the API dedupes per\n * (project, goal name) on its own.\n */\nexport async function trackServerGoal(\n opts: TrackServerGoalOptions,\n): Promise<'recorded' | 'skipped_no_visitor' | 'failed'> {\n // A secret key must never leave a browser (same rule as ssrHeaders).\n if (typeof window !== 'undefined') {\n console.error('[SentientUI] trackServerGoal is server-only: the secret key was not sent. Call it from a route handler, server action or webhook.');\n return 'failed';\n }\n if (!opts.sessionId) return 'skipped_no_visitor';\n // The id is derived from `${sessionId}:${name}:${dedupeKey}`, so a ':' in the\n // name would let ('a:b','c') and ('a','b:c') collide on one goal id and\n // silently merge two different conversions. Goal names never need one;\n // refuse it.\n if (opts.name.includes(':')) {\n console.error('[SentientUI] trackServerGoal: goal names cannot contain \":\" (nothing was sent).');\n return 'failed';\n }\n const doFetch = opts.fetch ?? fetch;\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const timedOut = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new Error('timeout'));\n }, opts.timeoutMs ?? DEFAULT_GOAL_TIMEOUT_MS);\n });\n // Started before the (async) id hash so the budget covers the whole call;\n // the no-op catch keeps an early expiry from being an unhandled rejection.\n timedOut.catch(() => undefined);\n // The session id is part of the hash because goal_events.goal_id is\n // UNIQUE across ALL projects (migration 060) and the insert is a bare ON\n // CONFLICT DO NOTHING: hashed from name + dedupeKey alone, two tenants that\n // both send ('purchase', order #1001) derived the same id, and the second\n // tenant's conversion was silently dropped while this call still returned\n // 'recorded'; anyone with a pk_ could also pre-burn a guessable order id.\n // The session id is an unguessable per-project visitor key, so the id is\n // now unique per tenant. Retry dedupe does not depend on it alone: the\n // dedupeKey also rides as externalId (unique per project + goal name).\n const goalId = await uuidV5(`${opts.sessionId}:${opts.name}:${opts.dedupeKey}`, SERVER_GOAL_NAMESPACE);\n // Raced as well as aborted: a fetch that ignores its signal must still\n // not hold the caller (a webhook handler) past the timeout.\n const res = await Promise.race([\n doFetch(`${(opts.apiBaseUrl ?? DEFAULT_GOAL_API_BASE).replace(/\\/+$/, '')}/goals`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${opts.serverKey}` },\n body: JSON.stringify({\n sessionId: opts.sessionId,\n name: opts.name,\n goalId,\n externalId: opts.dedupeKey,\n ...(opts.value !== undefined ? { value: opts.value } : {}),\n ...(opts.currency !== undefined ? { currency: opts.currency } : {}),\n ...(opts.metadata !== undefined ? { metadata: opts.metadata } : {}),\n }),\n signal: controller.signal,\n }),\n timedOut,\n ]);\n return res.ok ? 'recorded' : 'failed';\n } catch {\n return 'failed';\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n","// Server-side capture of AI-assistant fetches, for any framework.\n// Spec: docs/superpowers/specs/2026-09-23-server-side-agent-capture-design.md §4.1\n//\n// Assistants that fetch a page without running JavaScript (ChatGPT-User,\n// Claude-User, Perplexity-User, GPTBot, …) never execute the snippet or the\n// React SDK, so only the server that answered can see them. Until this, only\n// Next.js AdaptiveRoot logged them; every other site read \"no AI traffic\",\n// which is wrong rather than empty.\n//\n// OBSERVATION ONLY. Nothing here may change a response based on the user\n// agent: that is cloaking, and SentientUI never claims to adapt serving to\n// agents. These functions return nothing a caller could branch on except\n// \"did this look like an agent\", and log to crawler_requests — never to\n// sessions, never to training, never to billing.\n\nimport { matchedAgentToken } from './session-meta.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type AgentCaptureOptions = {\n /** Your public `pk_` key — the same one the snippet uses. */\n apiKey: string;\n /** API base ending in `/v1`. Defaults to the hosted API. */\n baseUrl?: string;\n /** Which capture path saw the fetch. Shown per row on the dashboard. */\n source?: 'middleware' | 'edge' | 'ssr';\n /**\n * REQUIRED on edge runtimes (Vercel Routing Middleware, Cloudflare Workers,\n * Netlify Edge): they cancel outstanding work once the response is\n * returned, so a fire-and-forget request without it is silently dropped.\n * Pass the platform's `waitUntil` (`ctx.waitUntil.bind(ctx)` on Workers,\n * `waitUntil` from `@vercel/functions`). Node servers do not need it.\n */\n waitUntil?: (p: Promise<unknown>) => void;\n /** Injectable for tests. */\n fetchImpl?: typeof fetch;\n};\n\n/** The minimum of a request both the Fetch API `Request` and hand-rolled\n * objects satisfy. */\nexport type CapturableRequest = {\n url: string;\n headers: { get(name: string): string | null };\n};\n\n/** Pathname only: a query string can carry tokens, emails or campaign ids. */\nfunction pathOf(url: string): string {\n try {\n return new URL(url, 'http://localhost').pathname || '/';\n } catch {\n return url.split(/[?#]/, 1)[0] || '/';\n }\n}\n\n/**\n * Low-level sender: posts one agent fetch to `/v1/crawler-events`. Never\n * throws, never blocks. The API re-derives the agent from `userAgent`\n * itself, so `botName` is advisory.\n */\nexport function postAgentFetch(\n entry: { path: string; userAgent: string; botName: string },\n opts: AgentCaptureOptions,\n): void {\n const doFetch = opts.fetchImpl ?? (typeof fetch === 'function' ? fetch : undefined);\n if (!doFetch || !opts.apiKey) return;\n try {\n const p = doFetch(`${opts.baseUrl ?? DEFAULT_API_BASE_URL}/crawler-events`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.apiKey}` },\n body: JSON.stringify({\n path: entry.path,\n botName: entry.botName,\n userAgent: entry.userAgent,\n source: opts.source ?? 'middleware',\n }),\n }).catch(() => undefined);\n opts.waitUntil?.(p);\n } catch {\n /* capture must never break the page it is observing */\n }\n}\n\n/**\n * Log this request if its user agent is a known AI assistant or crawler.\n * Works with a Fetch API `Request` (edge runtimes, Hono, Remix / React\n * Router, Astro, SvelteKit) or anything with `url` + `headers.get`.\n *\n * Returns whether the request matched, so a caller can skip its own work;\n * it must NOT be used to serve anything different. Non-matching requests —\n * nearly all of them — make no network call.\n */\nexport function captureAgentRequest(req: CapturableRequest, opts: AgentCaptureOptions): boolean {\n let userAgent = '';\n try {\n userAgent = req.headers.get('user-agent') ?? '';\n } catch {\n return false;\n }\n const botName = matchedAgentToken(userAgent);\n if (!botName) return false;\n postAgentFetch({ path: pathOf(req.url), userAgent, botName }, opts);\n return true;\n}\n\ntype ConnectRequest = {\n url?: string;\n originalUrl?: string;\n headers: Record<string, string | string[] | undefined>;\n};\n\n/**\n * Connect-style middleware (Express, Nitro / Nuxt on Node, Fastify via\n * middie, any `(req, res, next)` stack). Calls `next()` synchronously and\n * logs in the background; it never touches the response.\n */\nexport function sentientAgentMiddleware(\n opts: Omit<AgentCaptureOptions, 'waitUntil' | 'source'>,\n): (req: ConnectRequest, res: unknown, next: (err?: unknown) => void) => void {\n return (req, _res, next) => {\n try {\n const raw = req.headers['user-agent'];\n const ua = Array.isArray(raw) ? raw[0] ?? '' : raw ?? '';\n captureAgentRequest(\n { url: req.originalUrl ?? req.url ?? '/', headers: { get: (n) => (n.toLowerCase() === 'user-agent' ? ua : null) } },\n { ...opts, source: 'middleware' },\n );\n } catch {\n /* never block the request */\n }\n next();\n };\n}\n"],"mappings":"sNA0FO,IAAMA,EAAoB,wBAGjC,SAASC,EAAWC,EAAoD,CACtE,IAAMC,EAAkC,CACtC,eAAgB,mBAChB,cAAe,UAAUD,EAAO,MAAM,EACxC,EACA,OAAIA,EAAO,SAAQC,EAAQ,OAASD,EAAO,QAGvCA,EAAO,WAAa,OAAO,QAAW,cAAaC,EAAQH,CAAiB,EAAIE,EAAO,WACpFC,CACT,CAWA,IAAMC,EAAqB,IAE3B,SAASC,EACPC,EACAC,EACAC,EACmB,CACnB,IAAMC,EAAa,IAAI,gBACjBC,EAAQ,WAAW,IAAMD,EAAW,MAAM,EAAGD,CAAS,EAC5D,OAAO,MAAMF,EAAKK,EAAAC,EAAA,GAAKL,GAAL,CAAW,OAAQE,EAAW,MAAO,EAAC,EAAE,QAAQ,IAChE,aAAaC,CAAK,CACpB,CACF,CA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Y,EAC9BQ,EAAK,MAAM,QAAQD,CAAG,GAAId,EAAAc,EAAI,CAAC,IAAL,KAAAd,EAAU,GAAKc,GAAA,KAAAA,EAAO,GACtDR,EACE,CAAE,KAAKJ,GAAAD,EAAAM,EAAI,cAAJ,KAAAN,EAAmBM,EAAI,MAAvB,KAAAL,EAA8B,IAAK,QAAS,CAAE,IAAMc,GAAOA,EAAE,YAAY,IAAM,aAAeD,EAAK,IAAM,CAAE,EAClHE,EAAAC,EAAA,GAAKnB,GAAL,CAAW,OAAQ,YAAa,EAClC,CACF,OAAQH,EAAA,CAER,CACAiB,EAAK,CACP,CACF","names":["SERVER_KEY_HEADER","ssrHeaders","config","headers","DEFAULT_TIMEOUT_MS","fetchWithTimeout","url","init","timeoutMs","controller","timer","__spreadProps","__spreadValues","preloadAssignments","components","sessionId","preloadAssignmentsDetailed","opts","_a","sessionBody","buildSessionUpsertPayload","res","body","err","results","id","variantIds","assignments","unified","result","readSessionCookie","cookies","apiKey","_b","_c","_d","sessionCookieName","LEGACY_SESSION_COOKIE_NAME","preloadDecisions","params","_e","_f","_g","_h","_i","_j","_k","_l","declaredSlots","registryIds","fallback","baselineSlots","sessionRes","toWireSlot","data","slots","d","baselineResultFor","slotId","slotConfigOk","SERVER_GOAL_NAMESPACE","sha1Fallback","rotl","x","n","len","padded","view","h0","h1","h2","h3","h4","w","off","i","a","b","c","e","f","k","t","out","ov","v","uuidV5","name","namespace","hex","nsBytes","nameBytes","input","subtle","h","DEFAULT_GOAL_API_BASE","DEFAULT_GOAL_TIMEOUT_MS","trackServerGoal","doFetch","timedOut","_","reject","goalId","DEFAULT_API_BASE_URL","pathOf","url","e","postAgentFetch","entry","opts","_a","_b","_c","_d","doFetch","p","captureAgentRequest","req","userAgent","botName","matchedAgentToken","sentientAgentMiddleware","_res","next","raw","ua","n","__spreadProps","__spreadValues"]}
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { B as BLOCK_ALIGNS, a as BLOCK_EMPHASES, b as BLOCK_FITS, c as BLOCK_GAPS, d as BLOCK_GRID_COLUMNS, e as BLOCK_HEADING_LEVELS, f as BLOCK_JUSTIFIES, g as BLOCK_MAX_WIDTHS, h as BLOCK_PADS, i as BLOCK_RATIOS, j as BLOCK_SIZES, k as BLOCK_SURFACES, l as BLOCK_TEXT_ALIGNS, m as BLOCK_TONES, n as BLOCK_WEIGHTS, o as BadgeBlock, p as BlockAlign, q as BlockEmphasis, r as BlockFit, s as BlockGap, t as BlockJustify, u as BlockMaxWidth, v as BlockNode, w as BlockPad, x as BlockRatio, y as BlockSize, z as BlockSurface, A as BlockTextAlign, C as BlockTone, D as BlockWeight, E as ButtonBlock, F as ComposeArm, G as DividerBlock, H as FORM_FIELD_KINDS, I as FORM_INPUT_TYPES, J as FormBlock, K as FormField, L as GridBlock, M as HeadingBlock, N as ImageBlock, P as LinkBlock, Q as MAX_BLOCK_ARMS, R as MAX_BLOCK_CHILDREN, S as MAX_BLOCK_DEPTH, T as MAX_BLOCK_NODES, U as MAX_BLOCK_TEXT_LEN, V as MAX_FORM_FIELDS, W as MAX_FORM_SELECT_OPTIONS, _ as SiteImage, $ as SitePalette, a0 as SpacerBlock, a1 as StackBlock, a2 as StyleEntry, a3 as StyleRole, a4 as StyleVocabulary, a5 as TextBlock, a6 as containsFormBlock } from './style-vocabulary-Ba_g6_DD.cjs';
2
- export { A as AssignResult, a as Assignment, c as AuthoredArmReport, C as ComponentGoalOptions, d as ComponentWeightEntry, D as DecideInput, e as DecideOutcome, f as EventType, G as GoalDefinition, g as GoalOptions, i as GraphConfig, j as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, k as LOCAL_MODE_BANNER, M as MicroSignalEmitter, l as MicroSignalType, P as PAGE_SCOPE_RE, m as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, o as RevealOptions, S as SectionMapEntry, p as SentientClient, q as SentientConfig, r as SentientEvent, s as SessionConfig, t as SessionManager, u as SkeletonReport, W as WeightEntry, _ as _registerConsentUpgradeInit, v as applyNonce, w as attachMicroSignalDetectors, x as cspNonce, y as forgetGeneration, z as grantConsent, B as init, F as isDoNotTrackEnabled, H as pageScopeMatches, I as resetRevealStyles, J as reveal, K as routeKey, O as sessionCookieName, T as setCspNonce } from './index-C-meVCmm.cjs';
3
- export { A as AGENT_INTENTS, a as AgentIntent, C as CLICK_ID_KEYS, b as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, d as SlotConfigEntry, e as SlotDeclInput, f as SlotOps, g as agentIntent, h as agentUaList, i as armOfResult, j as baselineResultFor, k as baselineSlots, m as classifiedAgents, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, s as matchedAgentToken, t as readSnapshot, u as referrerDomainFromReferer, v as renderPrePaintScript, w as toWireSlot, x as uaTokenMatch, y as writeSnapshot } from './session-meta-CJ-QAskZ.cjs';
4
- export { A as ArmEdits, M as MAX_SKELETON_LEAVES, a as MAX_SKELETON_NODES, b as MAX_SKELETON_TEXT, R as RegionSkeleton, c as RenderCaps, S as ServedEdits, d as SkeletonNode, e as SkeletonRole } from './region-skeleton-D2ahkcbe.cjs';
2
+ export { A as AssignOptions, a as AssignResult, b as Assignment, d as AuthoredArmReport, C as ComponentGoalOptions, e as ComponentWeightEntry, D as DecideInput, f as DecideOutcome, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, l as LOCAL_MODE_BANNER, M as MicroSignalEmitter, m as MicroSignalType, P as PAGE_SCOPE_RE, n as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, p as RevealOptions, S as STAGE_ATTRIBUTE, q as SectionMapEntry, r as SentientClient, s as SentientConfig, t as SentientEvent, u as SessionConfig, v as SessionManager, w as SkeletonReport, x as StageAttributes, W as WeightEntry, _ as _registerConsentUpgradeInit, y as applyNonce, z as attachMicroSignalDetectors, B as cspNonce, F as exposedStage, H as forgetGeneration, I as grantConsent, J as init, K as isDoNotTrackEnabled, N as normalizeUrlPattern, O as pageScopeMatches, T as resetRevealStyles, U as reveal, V as routeKey, Y as sessionCookieName, Z as setCspNonce, $ as setStageAttribute, a0 as urlMatches } from './index-BAfi7_FG.cjs';
3
+ export { A as AGENT_INTENTS, a as AgentIntent, C as CLICK_ID_KEYS, b as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, d as SlotConfigEntry, e as SlotDeclInput, f as SlotOps, g as agentIntent, h as agentUaList, i as armOfResult, j as baselineResultFor, k as baselineSlots, m as classifiedAgents, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, s as matchedAgentToken, t as readSnapshot, u as referrerDomainFromReferer, v as renderPrePaintScript, w as toWireSlot, x as uaTokenMatch, y as writeSnapshot } from './session-meta-qx4kIL5y.cjs';
4
+ export { A as ArmEdits, M as MAX_SKELETON_LEAVES, a as MAX_SKELETON_NODES, b as MAX_SKELETON_TEXT, R as RegionSkeleton, c as RenderCaps, S as ServedEdits, d as SkeletonNode, e as SkeletonRole } from './region-skeleton-BRIVB-qf.cjs';
5
5
  export { ConsentPreset, ConsentSource, ConsentWatcher, forgetVisitor } from './index-consent.cjs';
6
6
  export { SlotResult } from '@sentientui/policy';
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { B as BLOCK_ALIGNS, a as BLOCK_EMPHASES, b as BLOCK_FITS, c as BLOCK_GAPS, d as BLOCK_GRID_COLUMNS, e as BLOCK_HEADING_LEVELS, f as BLOCK_JUSTIFIES, g as BLOCK_MAX_WIDTHS, h as BLOCK_PADS, i as BLOCK_RATIOS, j as BLOCK_SIZES, k as BLOCK_SURFACES, l as BLOCK_TEXT_ALIGNS, m as BLOCK_TONES, n as BLOCK_WEIGHTS, o as BadgeBlock, p as BlockAlign, q as BlockEmphasis, r as BlockFit, s as BlockGap, t as BlockJustify, u as BlockMaxWidth, v as BlockNode, w as BlockPad, x as BlockRatio, y as BlockSize, z as BlockSurface, A as BlockTextAlign, C as BlockTone, D as BlockWeight, E as ButtonBlock, F as ComposeArm, G as DividerBlock, H as FORM_FIELD_KINDS, I as FORM_INPUT_TYPES, J as FormBlock, K as FormField, L as GridBlock, M as HeadingBlock, N as ImageBlock, P as LinkBlock, Q as MAX_BLOCK_ARMS, R as MAX_BLOCK_CHILDREN, S as MAX_BLOCK_DEPTH, T as MAX_BLOCK_NODES, U as MAX_BLOCK_TEXT_LEN, V as MAX_FORM_FIELDS, W as MAX_FORM_SELECT_OPTIONS, _ as SiteImage, $ as SitePalette, a0 as SpacerBlock, a1 as StackBlock, a2 as StyleEntry, a3 as StyleRole, a4 as StyleVocabulary, a5 as TextBlock, a6 as containsFormBlock } from './style-vocabulary-Ba_g6_DD.js';
2
- export { A as AssignResult, a as Assignment, c as AuthoredArmReport, C as ComponentGoalOptions, d as ComponentWeightEntry, D as DecideInput, e as DecideOutcome, f as EventType, G as GoalDefinition, g as GoalOptions, i as GraphConfig, j as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, k as LOCAL_MODE_BANNER, M as MicroSignalEmitter, l as MicroSignalType, P as PAGE_SCOPE_RE, m as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, o as RevealOptions, S as SectionMapEntry, p as SentientClient, q as SentientConfig, r as SentientEvent, s as SessionConfig, t as SessionManager, u as SkeletonReport, W as WeightEntry, _ as _registerConsentUpgradeInit, v as applyNonce, w as attachMicroSignalDetectors, x as cspNonce, y as forgetGeneration, z as grantConsent, B as init, F as isDoNotTrackEnabled, H as pageScopeMatches, I as resetRevealStyles, J as reveal, K as routeKey, O as sessionCookieName, T as setCspNonce } from './index-DbpGK3Dj.js';
3
- export { A as AGENT_INTENTS, a as AgentIntent, C as CLICK_ID_KEYS, b as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, d as SlotConfigEntry, e as SlotDeclInput, f as SlotOps, g as agentIntent, h as agentUaList, i as armOfResult, j as baselineResultFor, k as baselineSlots, m as classifiedAgents, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, s as matchedAgentToken, t as readSnapshot, u as referrerDomainFromReferer, v as renderPrePaintScript, w as toWireSlot, x as uaTokenMatch, y as writeSnapshot } from './session-meta-DlCp0tyi.js';
4
- export { A as ArmEdits, M as MAX_SKELETON_LEAVES, a as MAX_SKELETON_NODES, b as MAX_SKELETON_TEXT, R as RegionSkeleton, c as RenderCaps, S as ServedEdits, d as SkeletonNode, e as SkeletonRole } from './region-skeleton-D2ahkcbe.js';
2
+ export { A as AssignOptions, a as AssignResult, b as Assignment, d as AuthoredArmReport, C as ComponentGoalOptions, e as ComponentWeightEntry, D as DecideInput, f as DecideOutcome, g as EventType, G as GoalDefinition, h as GoalOptions, j as GraphConfig, k as GraphSnapshot, L as LEGACY_SESSION_COOKIE_NAME, l as LOCAL_MODE_BANNER, M as MicroSignalEmitter, m as MicroSignalType, P as PAGE_SCOPE_RE, n as PROD_KEYLESS_ERROR, Q as QueueConfig, R as REVEAL_MS, p as RevealOptions, S as STAGE_ATTRIBUTE, q as SectionMapEntry, r as SentientClient, s as SentientConfig, t as SentientEvent, u as SessionConfig, v as SessionManager, w as SkeletonReport, x as StageAttributes, W as WeightEntry, _ as _registerConsentUpgradeInit, y as applyNonce, z as attachMicroSignalDetectors, B as cspNonce, F as exposedStage, H as forgetGeneration, I as grantConsent, J as init, K as isDoNotTrackEnabled, N as normalizeUrlPattern, O as pageScopeMatches, T as resetRevealStyles, U as reveal, V as routeKey, Y as sessionCookieName, Z as setCspNonce, $ as setStageAttribute, a0 as urlMatches } from './index-DyKtujwf.js';
3
+ export { A as AGENT_INTENTS, a as AgentIntent, C as CLICK_ID_KEYS, b as CompoundLocator, D as DecisionSnapshot, S as SNAPSHOT_STORAGE_KEY_PREFIX, d as SlotConfigEntry, e as SlotDeclInput, f as SlotOps, g as agentIntent, h as agentUaList, i as armOfResult, j as baselineResultFor, k as baselineSlots, m as classifiedAgents, n as deriveSessionSegment, o as detectDeviceClass, p as detectTimeOfDay, q as detectTrafficSource, r as extractTrackedParams, s as matchedAgentToken, t as readSnapshot, u as referrerDomainFromReferer, v as renderPrePaintScript, w as toWireSlot, x as uaTokenMatch, y as writeSnapshot } from './session-meta-BtRtwsHI.js';
4
+ export { A as ArmEdits, M as MAX_SKELETON_LEAVES, a as MAX_SKELETON_NODES, b as MAX_SKELETON_TEXT, R as RegionSkeleton, c as RenderCaps, S as ServedEdits, d as SkeletonNode, e as SkeletonRole } from './region-skeleton-BRIVB-qf.js';
5
5
  export { ConsentPreset, ConsentSource, ConsentWatcher, forgetVisitor } from './index-consent.js';
6
6
  export { SlotResult } from '@sentientui/policy';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var An=Object.create;var De=Object.defineProperty,Tn=Object.defineProperties,On=Object.getOwnPropertyDescriptor,Pn=Object.getOwnPropertyDescriptors,Dn=Object.getOwnPropertyNames,Jt=Object.getOwnPropertySymbols,Bn=Object.getPrototypeOf,Zt=Object.prototype.hasOwnProperty,Ln=Object.prototype.propertyIsEnumerable;var Yt=(e,t,n)=>t in e?De(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,A=(e,t)=>{for(var n in t||(t={}))Zt.call(t,n)&&Yt(e,n,t[n]);if(Jt)for(var n of Jt(t))Ln.call(t,n)&&Yt(e,n,t[n]);return e},ve=(e,t)=>Tn(e,Pn(t));var Mn=(e,t)=>{for(var n in t)De(e,n,{get:t[n],enumerable:!0})},en=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let p of Dn(t))!Zt.call(e,p)&&p!==n&&De(e,p,{get:()=>t[p],enumerable:!(i=On(t,p))||i.enumerable});return e};var Nn=(e,t,n)=>(n=e!=null?An(Bn(e)):{},en(t||!e||!e.__esModule?De(n,"default",{value:e,enumerable:!0}):n,e)),Kn=e=>en(De({},"__esModule",{value:!0}),e);var Go={};Mn(Go,{AGENT_INTENTS:()=>ot,BLOCK_ALIGNS:()=>so,BLOCK_EMPHASES:()=>uo,BLOCK_FITS:()=>fo,BLOCK_GAPS:()=>ro,BLOCK_GRID_COLUMNS:()=>mo,BLOCK_HEADING_LEVELS:()=>yo,BLOCK_JUSTIFIES:()=>io,BLOCK_MAX_WIDTHS:()=>vo,BLOCK_PADS:()=>ho,BLOCK_RATIOS:()=>go,BLOCK_SIZES:()=>ao,BLOCK_SURFACES:()=>So,BLOCK_TEXT_ALIGNS:()=>po,BLOCK_TONES:()=>co,BLOCK_WEIGHTS:()=>lo,CLICK_ID_KEYS:()=>wt,FORM_FIELD_KINDS:()=>bo,FORM_INPUT_TYPES:()=>ko,LEGACY_SESSION_COOKIE_NAME:()=>be,LOCAL_MODE_BANNER:()=>Et,MAX_BLOCK_ARMS:()=>Ro,MAX_BLOCK_CHILDREN:()=>Io,MAX_BLOCK_DEPTH:()=>_o,MAX_BLOCK_NODES:()=>Eo,MAX_BLOCK_TEXT_LEN:()=>Co,MAX_FORM_FIELDS:()=>xo,MAX_FORM_SELECT_OPTIONS:()=>wo,MAX_SKELETON_LEAVES:()=>xr,MAX_SKELETON_NODES:()=>kr,MAX_SKELETON_TEXT:()=>wr,PAGE_SCOPE_RE:()=>It,PROD_KEYLESS_ERROR:()=>lt,REVEAL_MS:()=>Ct,SNAPSHOT_STORAGE_KEY_PREFIX:()=>fe,_registerConsentUpgradeInit:()=>Oo,agentIntent:()=>ln,agentUaList:()=>Ne,applyNonce:()=>ze,armOfResult:()=>st,attachMicroSignalDetectors:()=>hn,baselineResultFor:()=>Ae,baselineSlots:()=>un,classifiedAgents:()=>cn,containsFormBlock:()=>mn,cspNonce:()=>St,deriveSessionSegment:()=>dn,detectDeviceClass:()=>Ge,detectTimeOfDay:()=>Fe,detectTrafficSource:()=>Ue,extractTrackedParams:()=>rt,forgetGeneration:()=>ie,forgetVisitor:()=>Ye,grantConsent:()=>No,init:()=>_n,isDoNotTrackEnabled:()=>Bt,matchedAgentToken:()=>xt,pageScopeMatches:()=>fn,readSnapshot:()=>Ee,referrerDomainFromReferer:()=>$e,renderPrePaintScript:()=>tn,resetRevealStyles:()=>yn,reveal:()=>Sn,routeKey:()=>Pt,sessionCookieName:()=>we,setCspNonce:()=>He,toWireSlot:()=>je,uaTokenMatch:()=>Ke,writeSnapshot:()=>_e});module.exports=Kn(Go);function de(e){if(typeof AbortController!="function")return{clear:()=>{}};let t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(n)}}function mt(e,t){return new Promise(n=>{let i=setTimeout(()=>n(!1),t),p=()=>{clearTimeout(i),n(!0)};e.then(p,p)})}var yt;function He(e){yt=typeof e=="string"&&e!==""?e:void 0}function St(e=document){if(yt)return yt;try{let t=e.querySelector("script[nonce]");return(t==null?void 0:t.nonce)||(t==null?void 0:t.getAttribute("nonce"))||void 0}catch(t){return}}function ze(e,t=document){let n=St(t);return n&&e.setAttribute("nonce",n),e}function ge(e){return e?`_${e.slice(0,12)}`:""}var be="_snt_uid";function we(e){return`${be}${ge(e)}`}var Qe="__sntForgetGen",Gn=()=>{try{return window[Qe]}catch(e){return}};function Xe(e){var t,n;try{let i=window,p=(t=i[Qe])!=null?t:i[Qe]={};p[e]=((n=p[e])!=null?n:0)+1}catch(i){}}function ie(e){var t,n;return(n=(t=Gn())==null?void 0:t[e])!=null?n:0}var fe="_snt_snap:";var Un=["low","medium","high"];function Ee(e){try{let t=localStorage.getItem(fe+e);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!Un.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"||!(Date.now()-n.savedAt<2592e6)||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig)))return null;let i=n.vocabulary;return i!==void 0&&(typeof i!="object"||i===null||!Array.isArray(i.entries)||!Array.isArray(i.images))&&delete n.vocabulary,n}catch(t){return null}}function _e(e,t){try{localStorage.setItem(fe+e,JSON.stringify(t))}catch(n){}}function tn(e){return'(function(){try{var N=navigator,W=window;if(N.doNotTrack=="1"||N.doNotTrack=="yes"||W.doNotTrack=="1"||N.msDoNotTrack=="1"||N.globalPrivacyControl)return;var r=localStorage.getItem('+JSON.stringify(fe+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;if(!('+2592e6+'>Date.now()-s.savedAt))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){}})();'}function me(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 qe(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let i=JSON.parse(n);return Array.isArray(i)?(localStorage.removeItem(e),i.slice(-t)):[]}catch(n){return[]}}function Be(e,t,n){try{let i=(()=>{try{let d=localStorage.getItem(n);if(!d)return[];let S=JSON.parse(d);return Array.isArray(S)?S:[]}catch(d){return[]}})(),p=new Map;for(let d of i)p.set(d.id,d);for(let d of e)p.set(d.id,d);localStorage.setItem(n,JSON.stringify([...p.values()].slice(-t)))}catch(i){}}function Je(e,t){try{let n=localStorage.getItem(t);if(!n)return;let i=JSON.parse(n);if(!Array.isArray(i))return;let p=new Set(e),d=i.filter(S=>!p.has(S.id));if(d.length===i.length)return;d.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(d))}catch(n){}}var $n=500,Fn=56*1024;function Le(e){return`_snt_retry_${e.slice(0,12)}`}var jn={push:()=>{},flush:()=>{},destroy:()=>{}};function nn(e){var $,q,ue;if(typeof window=="undefined")return jn;let t=($=e.flushIntervalMs)!=null?$:5e3,n=(q=e.maxBatchSize)!=null?q:20,i=(ue=e.maxRetrySize)!=null?ue:100,p=e.ingestUrl,d=e.apiKey,S=Le(d),o=!1,f=ie(d),a=(...b)=>{!o&&ie(d)===f&&Be(...b)},s=[],l=new Set,h=[],O=b=>{for(let B of b)R.delete(B),!l.has(B)&&(l.add(B),h.push(B));for(;h.length>$n;){let B=h.shift();B&&l.delete(B)}Je(b,S)},R=new Set,D=()=>{for(;s.length>i;){let b=s.shift();b&&R.delete(b.id)}},X=b=>{l.has(b.id)||R.has(b.id)||(R.add(b.id),s.push(b),D())},G=b=>{for(let B of b)l.has(B.id)||(R.add(B.id),s.push(B));D()},z=qe(S,i);for(let b of z)X(b);let j=0,W=0,L=(b,B=!0)=>{if(b.length===0)return;let pe=JSON.stringify(b),ke=b.map(ae=>ae.id),te,ye=de(15e3);try{te=fetch(p,{method:"POST",keepalive:!0,signal:ye.signal,body:pe,headers:{"Content-Type":"application/json",Authorization:`Bearer ${d}`}})}catch(ae){a(b,i,S),G(b),W++,j=Date.now()+me(W);return}Promise.resolve(te).then(ye.clear,ye.clear);let Oe=ae=>{if(Ie(ae)!=="retry"){if(!ae.ok&&B){let Se=b.filter(re=>re.eventType!=="pageview");if(Se.length>0&&Se.length<b.length){O(b.filter(re=>re.eventType==="pageview").map(re=>re.id)),L(Se,!1);return}}O(ke),W=0,j=0;return}a(b,i,S),G(b),W++,j=Date.now()+me(W)};te&&typeof te.then=="function"?te.then(Oe).catch(()=>{a(b,i,S),G(b),W++,j=Date.now()+me(W)}):Oe(te)},ee=typeof TextEncoder!="undefined"?new TextEncoder:null,u=b=>ee?ee.encode(b).length:b.length,m=b=>{let B=[],pe=2;for(let ke of b){let te=u(JSON.stringify(ke))+1;if(B.length>0&&pe+te>Fn||B.length>=n)break;B.push(ke),pe+=te}return B},w=()=>{try{if(Date.now()<j)return;for(;s.length>0&&!(Date.now()<j);){let b=s.filter(pe=>!l.has(pe.id));if(s.length=0,b.length===0)break;let B=m(b);if(B.length===0)break;B.length<b.length&&s.push(...b.slice(B.length)),L(B)}}catch(b){}},g=!0,E=null;E=setInterval(()=>{g&&w()},t);let M=()=>{document.visibilityState==="hidden"&&w()},P=()=>{w()};return document.addEventListener("visibilitychange",M),window.addEventListener("pagehide",P),{push(b){X(b),s.length>=n&&w()},flush:w,destroy(b){b!=null&&b.forget&&(o=!0),g=!1,E!==null&&(clearInterval(E),E=null),document.removeEventListener("visibilitychange",M),window.removeEventListener("pagehide",P),w()}}}var Wn=200;function Me(e){return`_snt_goal_retry_${e.slice(0,12)}`}var Vn={send:()=>{},flush:()=>{},destroy:()=>{}};function on(e){var u,m,w;if(typeof window=="undefined")return Vn;let t=(u=e.flushIntervalMs)!=null?u:5e3,n=(m=e.maxRetrySize)!=null?m:100,i=(w=e.maxPerFlush)!=null?w:5,p=Me(e.apiKey),d=!1,S=ie(e.apiKey),o=(...g)=>{!d&&ie(e.apiKey)===S&&Be(...g)},f=[],a=new Set,s=new Set,l=[],h=0,O=0,R=!1,D=g=>{for(a.delete(g.id),s.has(g.id)||(s.add(g.id),l.push(g.id));l.length>Wn;){let E=l.shift();E&&s.delete(E)}Je([g.id],p)},X=g=>{o([g],n,p),!s.has(g.id)&&!a.has(g.id)&&(a.add(g.id),f.push(g)),Date.now()>=h&&(O++,h=Date.now()+me(O))},G=g=>{let E,M=de(15e3);try{E=fetch(e.url,{method:"POST",keepalive:!0,signal:M.signal,body:g.body,headers:e.headers})}catch($){X(g);return}let P=$=>{var ue;let q=Ie($);if(q==="retry"){X(g);return}q==="dropped"&&((ue=e.onDrop)==null||ue.call(e,g,$.status)),D(g),O=0,h=0};Promise.resolve(E).then(M.clear,M.clear),E&&typeof E.then=="function"?E.then(P).catch(()=>X(g)):P(E)},z=()=>{try{if(R||Date.now()<h)return;let g=0;for(;f.length>0&&g<i&&!(Date.now()<h);){let E=f.shift();a.delete(E.id),!s.has(E.id)&&(g++,G(E))}}catch(g){}},j=qe(p,n);for(let g of j)a.has(g.id)||(a.add(g.id),f.push(g));j.length>0&&Be(j,n,p);let W=setInterval(z,t),L=()=>{document.visibilityState==="hidden"&&z()},ee=()=>z();return document.addEventListener("visibilitychange",L),window.addEventListener("pagehide",ee),{send(g){if(R){s.has(g.id)||o([g],n,p);return}if(!(s.has(g.id)||a.has(g.id))){if(Date.now()<h){o([g],n,p),a.add(g.id),f.push(g);return}G(g)}},flush:z,destroy(g){g!=null&&g.forget&&(d=!0),clearInterval(W),document.removeEventListener("visibilitychange",L),window.removeEventListener("pagehide",ee),z(),R=!0}}}function Ye(e){if(typeof window=="undefined"||!e)return!1;Xe(e);let t=!1,n=we(e);try{if(new RegExp(`(?:^|; )${n}=`).test(document.cookie)){let S=location.protocol==="https:"?"; Secure":"";document.cookie=`${n}=; max-age=0; SameSite=lax; path=/${S}`,t=!0}}catch(S){}let i=ge(e),p=[n,"_snt_graph_edges",fe+e,Le(e),Me(e),`_snt_graph_nodes${i}`],d=[`_snt_asgn${i}_`];for(let S of["localStorage","sessionStorage"])try{let o=window[S];for(let f of p)o.getItem(f)!==null&&(o.removeItem(f),t=!0);for(let f=o.length-1;f>=0;f--){let a=o.key(f);a&&d.some(s=>a.startsWith(s))&&(o.removeItem(a),t=!0)}}catch(o){}try{(new RegExp(`(?:^|; )${be}=[^;]`).test(document.cookie)||localStorage.getItem(be)!==null||sessionStorage.getItem(be)!==null)&&localStorage.setItem(`${be}_tomb${i}`,"1")}catch(S){}return t}function Ze(){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)})}var rn="_snt_uid",Hn=365,Re="_snt_uid";function zn(){return Ze()}function vt(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function kt(){try{return location.protocol==="https:"?"; Secure":""}catch(e){return""}}function Qn(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=lax; path=/${kt()}`}catch(i){}}function et(e){try{return localStorage.getItem(e)}catch(t){return null}}function sn(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function bt(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function Xn(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function qn(e){try{sessionStorage.removeItem(e)}catch(t){}}function Jn(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=lax; path=/${kt()}`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function Yn(e){try{localStorage.removeItem(e)}catch(t){}}function Zn(e){try{document.cookie=`${e}=; max-age=0; SameSite=lax; path=/${kt()}`}catch(t){}}var eo={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function tt(e){var R,D,X,G,z,j,W;if(typeof window=="undefined")return eo;let t=ge(e==null?void 0:e.apiKey),n=(R=e==null?void 0:e.cookieName)!=null?R:we(e==null?void 0:e.apiKey),i=`${Re}${t}`,p=`${Re}_tomb${t}`,S=((D=e==null?void 0:e.cookieTTLDays)!=null?D:Hn)*24*60*60,o=L=>L&&L.length>0?L:null,f=()=>{var L,ee;return t&&!(e!=null&&e.cookieName)&&et(p)===null?(ee=(L=o(vt(rn)))!=null?L:o(et(Re)))!=null?ee:o(bt(Re)):null},a=(W=(j=(z=(G=(X=o(vt(n)))!=null?X:o(et(i)))!=null?G:o(bt(i)))!=null?z:f())!=null?j:o(e==null?void 0:e.ssrSessionId))!=null?W:zn();Qn(n,a,S);let s=sn(i,a),l=Jn(n),h=s?!1:Xn(i,a),O=!s&&!l&&!h;return{getSessionId:()=>a,isEphemeral:()=>O,destroy:()=>{a=null,Zn(n),Yn(i),qn(i),t&&!(e!=null&&e.cookieName)&&(vt(rn)!==null||et(Re)!==null||bt(Re)!==null)&&sn(p,"1")}}}var to=1800*1e3;function nt(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function an(e=to,t){let n=new Map,i=`_snt_asgn${ge(t)}_`,p=(a,s)=>`${i}${encodeURIComponent(a)}:${encodeURIComponent(s)}`,d=a=>{let s=a.slice(i.length),l=s.indexOf(":");if(l<0)return null;try{return{componentId:decodeURIComponent(s.slice(0,l)),segment:decodeURIComponent(s.slice(l+1))}}catch(h){return null}},S=()=>{try{let a=[];for(let s=0;s<localStorage.length;s++){let l=localStorage.key(s);l!=null&&l.startsWith(i)&&a.push(l)}return a}catch(a){return[]}},o=a=>a.assignedAt+(a.ttlMs&&a.ttlMs>0?a.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let a of S())try{let s=localStorage.getItem(a);if(!s)continue;let l=JSON.parse(s);if(o(l)){localStorage.removeItem(a);continue}let h=d(a);if(!h)continue;n.set(nt(h.componentId,h.segment),l)}catch(s){}})(),{get(a,s){let l=n.get(nt(a,s));return l?o(l)?(n.delete(nt(a,s)),null):l:null},set(a,s,l){let h=nt(a,s);n.set(h,l);try{localStorage.setItem(p(a,s),JSON.stringify(l))}catch(O){}},clear(){n.clear();for(let a of S())try{localStorage.removeItem(a)}catch(s){}}}}var Ne=["GPTBot","ChatGPT-User","OAI-SearchBot","ClaudeBot","Claude-User","Claude-SearchBot","PerplexityBot","Perplexity-User","Google-Extended","Applebot-Extended","Meta-ExternalAgent","Bytespider","CCBot","Amazonbot","cohere-ai","Diffbot"];function Ke(e){return xt(e)!==null}function xt(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ne.find(i=>t.includes(i.toLowerCase())))!=null?n:null}var ot={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 ln(e){if(!e)return"other";let t=Ne.find(n=>n.toLowerCase()===e.toLowerCase());return t&&ot[t]||"other"}function cn(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of Ne)e[(t=ot[n])!=null?t:"other"].push(n);return e}function Ge(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 Ue(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 i=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(i)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(i)?"social":"referral"}catch(n){return"direct"}}function $e(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var wt=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function rt(e){let t={},n={};try{let i=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([p,d])=>{let S=Array.isArray(d)?d[0]:d;return S===void 0?[]:[[p,S]]});for(let[p,d]of i)p.startsWith("utm_")?p in t||(t[p]=d):wt.includes(p)&&(p in n||(n[p]=d))}catch(i){}return{utmParams:t,clickIds:n}}function Fe(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function dn(e){let t=no("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function no(e,t){var d,S,o,f,a,s,l,h;let n=(S=(d=t==null?void 0:t.userAgent)==null?void 0:d.trim())!=null?S:"",i=(f=(o=t==null?void 0:t.referer)==null?void 0:o.trim())!=null?f:"",p=(a=t==null?void 0:t.now)!=null?a:new Date;return A({sessionId:e,ephemeral:!1,utmParams:(s=t==null?void 0:t.utmParams)!=null?s:{},clickIds:(l=t==null?void 0:t.clickIds)!=null?l:{},deviceClass:n?Ge(n):"desktop",trafficSource:i?Ue(i,t==null?void 0:t.appOrigin):"direct",referrerDomain:$e(i),timeOfDay:Fe(p),dayOfWeek:(h=["sun","mon","tue","wed","thu","fri","sat"][p.getDay()])!=null?h:"sun",automation:(t==null?void 0:t.webdriver)===!0||Ke(n)},t!=null&&t.landingPath?{landingPath:t.landingPath.split(/[?#]/)[0]}:{})}var Ce=require("@sentientui/policy");function je(e){return A(A(A({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 Ae(e){let t=je(e);return(0,Ce.slotResultFor)(t,(0,Ce.slotBaselineArm)(t))}function un(e){let t={};for(let n of e)t[n.id]=Ae(n);return t}function st(e){return typeof e=="string"?e:(0,Ce.canonicalArm)(e)}var Ot=require("@sentientui/policy");var at=require("@sentientui/policy");var lt="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Et="[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.",pn=!1,it=!1;function oo(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function gn(e){var a;let t=tt({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(a=t.getSessionId())!=null?a:"local",i=oo(),p=import("@sentientui/core/local").then(s=>{let l=s;return l.LOCAL_ENGINE_AVAILABLE?(pn||(pn=!0,console.info(Et)),l):(it||(it=!0,console.error(lt)),null)}).catch(()=>(it||(it=!0,console.error(lt)),null)),d=null,S={low:.15,medium:.5,high:.85},o=(()=>{var l;if(e.initialPersona)return A({},e.initialPersona);let s=Ee(e.apiKey||"local");return s?{persona:s.persona,confidence:(l=S[s.band])!=null?l:.15}:null})();function f(s){let l=document.documentElement;l.dataset.sentientPersona===void 0&&(l.dataset.sentientPersona=s.persona,l.dataset.sentientConfidence=(0,at.confidenceBand)(s.confidence))}return{isLocal:!0,async decide(s){var O,R,D;let l=await p;if(!l)return null;let h=l.createLocalEngine({sessionId:n,forcedPersona:i}).decide(s);return d=ve(A({},h),{layoutOrder:(R=(O=h.layoutOrder)!=null?O:d==null?void 0:d.layoutOrder)!=null?R:null,slots:A(A({},(D=d==null?void 0:d.slots)!=null?D:{}),h.slots)}),_e(e.apiKey||"local",{v:1,persona:d.persona,band:(0,at.confidenceBand)(d.confidence),slots:d.slots,layoutOrder:d.layoutOrder,savedAt:Date.now()}),f(h),h},getSlotResult(s){var l,h,O;return(O=(h=d==null?void 0:d.slots[s])!=null?h:(l=e.initialSlots)==null?void 0:l[s])!=null?O:null},getSlotConfig(s){var l,h;return(h=(l=e.initialSlotConfig)==null?void 0:l[s])!=null?h:null},getSitePalette(){var s;return(s=e.initialPalette)!=null?s:null},reportSlots(){},getPersona(){let s=d!=null?d:o;return s?{persona:s.persona,confidence:s.confidence,band:(0,at.confidenceBand)(s.confidence)}:null},async assign(s,l){var R;let h=await p;return!h||!l||l.length===0?l!=null&&l[0]?{variantId:l[0],assignmentTtlMs:0}:null:{variantId:(R=h.createLocalEngine({sessionId:n,forcedPersona:i}).decide({components:[{id:s,variantIds:l}]}).assignments[s])!=null?R:l[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>t.destroy()}}var It=/^(\*|\/[^\s?#*]*(\/\*)?)$/;function _t(e){let t=e.split(/[?#]/)[0]||"/";return t.length>1?t.replace(/\/+$/,"")||"/":t}function fn(e,t){if(e===void 0||!It.test(e))return!1;if(e==="*")return!0;let n=_t(t);if(e.endsWith("/*")){let i=_t(e.slice(0,-2));return n.startsWith(i==="/"?"/":`${i}/`)&&n!==i}return n===_t(e)}var ro=["none","sm","md","lg"],so=["start","center","end","stretch"],io=["start","center","end","between"],ao=["sm","md","lg"],lo=["normal","medium","bold"],co=["default","muted","accent"],uo=["primary","secondary","ghost"],po=["left","center","right"],go=["auto","square","landscape","wide"],fo=["cover","contain"],mo=[2,3,4],yo=[1,2,3,4],So=["default","raised"],ho=["none","sm","md","lg"],vo=["measure"],bo=["input","textarea","select"],ko=["text","email","number","tel"],xo=5,wo=8,Eo=64,_o=5,Io=12,Ro=4,Co=500;function mn(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.type==="form"?!0:Array.isArray(t.children)?t.children.some(mn):!1}var kr=40,xr=120,wr=300;var Rt="sentient-reveal",Te="sentient-revealed",Ct=240,ct=!1;function yn(){var e;ct=!1,typeof document!="undefined"&&((e=document.getElementById(Rt))==null||e.remove())}function Ao(e){if(ct||e.getElementById(Rt)){ct=!0;return}let t=ze(e.createElement("style"),e);t.id=Rt,t.textContent=`@media (prefers-reduced-motion: no-preference){@keyframes ${Te}{from{opacity:.55;transform:translateY(2px)}to{opacity:1;transform:none}}.${Te}{animation:${Te} ${Ct}ms cubic-bezier(.2,.6,.2,1) both}}`,e.head.appendChild(t),ct=!0}function Sn(e,t={}){var p;let n=(p=t.doc)!=null?p:typeof document!="undefined"?document:void 0;if(!n||!(e instanceof Element)||(t.arm!==void 0&&e.setAttribute("data-sentient-arm",t.arm),t.persona!==void 0&&e.setAttribute("data-sentient-persona",t.persona),t.previous!==void 0&&t.previous===e.textContent))return!1;Ao(n),e.classList.remove(Te),e.offsetWidth,e.classList.add(Te);let i=()=>{e.classList.remove(Te),e.removeEventListener("animationend",i)};return e.addEventListener("animationend",i),!0}function hn(e,t,n,i){let p=[];{let o=!1,f=[],a=()=>{if(o)return;let s=Date.now();for(f.push(s);f.length>0&&s-f[0]>500;)f.shift();f.length>=3&&(o=!0,e("rage_click"))};t.addEventListener("click",a),p.push(()=>t.removeEventListener("click",a))}{let d=!1,S=o=>{if(d||!(o.target instanceof Node)||!t.contains(o.target)&&t!==o.target)return;d=!0;let f=typeof window!="undefined"?window.getSelection():null,a=f?f.toString().length:0;e("text_copy",{selectionLength:a})};document.addEventListener("copy",S),p.push(()=>document.removeEventListener("copy",S))}{let d=!1,S=!1,o=null,f=()=>{o!==null&&(clearTimeout(o),o=null)},a=()=>{d||!S||(f(),o=setTimeout(()=>{!d&&S&&(d=!0,e("scroll_hesitation"))},3e3))},s=()=>{f(),a()},l=O=>{for(let R of O)S=R.intersectionRatio>.3,S?a():f()},h=new IntersectionObserver(l,{threshold:[.3]});h.observe(t),window.addEventListener("scroll",s,{passive:!0}),p.push(()=>{h.disconnect(),window.removeEventListener("scroll",s),f()})}if((i==null?void 0:i.tabLoss)!==!1){let d=!1,S=n!=null?n:Date.now(),o=()=>{if(d||document.visibilityState!=="hidden")return;let f=Date.now()-S;f<15e3&&(d=!0,e("tab_loss",{timeOnPage:f}))};document.addEventListener("visibilitychange",o),p.push(()=>document.removeEventListener("visibilitychange",o))}return()=>{for(let d of p)d()}}function To(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var kn="https://api.sentient-ui.com/v1/events",J=new Map,xn=null;function Oo(e,t){let n=J.get(e);n&&n.upgrade&&(n.reinit=t)}function Po(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var Do=3;function At(){return Ze()}function dt(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function Bo(){let e=new WeakMap,t=new Map,n=!1,i=(o,f,a)=>{let s=o.get(f);return a===null?s?!0:(o.set(f,new Set),!1):s?s.has(a)?!0:(s.add(a),!1):(o.set(f,new Set([a])),!1)},p=typeof window!="undefined"&&"event"in window,d=()=>{if(!p)return;let o=window.event;return typeof Event=="function"&&o instanceof Event?o:void 0},S=()=>{if(p){Promise.resolve().then(()=>{n=!1,t.clear()});return}let o=!1,f=()=>{o||(o=!0,n=!1,t.clear())};if(setTimeout(f,0),typeof MessageChannel=="function"){let a=new MessageChannel;a.port1.onmessage=()=>{a.port1.close(),a.port2.close(),f()},a.port2.postMessage(0)}};return{firedBefore(o,f){let a=d();if(a){let l=e.get(a);return l||(l=new Map,e.set(a,l)),i(l,o,f)}let s=i(t,o,f);return!s&&!n&&(n=!0,S()),s}}}var wn=new Set;function Lo(e,t,n){let i=typeof window=="undefined"?null:window.history;if(!i)return()=>{};let p=!1,d,S=()=>{if(p)return;let a=dt();!a||a===d||(d=a,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${a}`))},o=[];for(let a of["pushState","replaceState"]){let s=i[a],l=function(...h){let O=s.apply(this,h);return S(),O};i[a]=l,o.push([a,s,l])}window.addEventListener("popstate",S);let f=dt();return f&&wn.has(`${t}:${f}`)?d=f:S(),()=>{if(!p){p=!0,window.removeEventListener("popstate",S);for(let[a,s,l]of o)i[a]===l&&(i[a]=s)}}}var We={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}};function Mo(){try{return rt(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function En(e){return e.replace(/\/events\/?$/,"")}function Bt(){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 No(e){var f;if(typeof window=="undefined")return;let t=e!=null?e:xn;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=J.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:i,upgrade:p,reinit:d}=n;if(!p){n.upgradeBlockedReason&&console.warn(n.upgradeBlockedReason);return}if(i.respectDoNotTrack!==!1&&Bt())return;let S=(d!=null?d:_n)(ve(A({},i),{consent:!0}));p(S);let o=(f=J.get(t))==null?void 0:f.dispose;J.set(t,{config:ve(A({},i),{consent:!0}),upgrade:null,dispose:o})}function Ko(e,t){var ee;let n=e.preConsentBehavior==="statistical_winner",i=En((ee=e.ingestUrl)!=null?ee:kn),p={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},d=new Map,S=new Map,o={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(u,m,w){if(!n)return Promise.resolve(null);let g=d.get(u);return g?Promise.resolve(g):Dt(S,u,async()=>{try{let E=new URLSearchParams({componentId:u});for(let q of m!=null?m:[])E.append("variantIds[]",q);let M=de(5e3),P;try{let q=await fetch(`${i}/winner?${E.toString()}`,{headers:p,signal:M.signal});if(!q.ok)return m!=null&&m[0]?{variantId:m[0],assignmentTtlMs:0}:null;P=await q.json()}finally{M.clear()}let $={variantId:P.variantId,assignmentTtlMs:0};return d.set(u,$),$}catch(E){return m!=null&&m[0]?{variantId:m[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}},f=!1,a=new Set,s=[],l=[],h=[],O=()=>{for(let[,,u]of h.splice(0))u(null);R.length=0},R=[],D=!1,X=()=>{if(f)return;D=!0;let u=J.get(e.apiKey);(u==null?void 0:u.upgrade)===L&&J.set(e.apiKey,{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): client released before consent; call init() again"})},G=[],z=()=>{setTimeout(()=>{var u;try{(u=G.shift())==null||u(o)}catch(m){}G.length&&z()})},j=u=>{f?G.length?G.push(u):u(o):!t&&!D&&R.length<100?R.push(u):D&&e.debug&&console.warn("[sentient] goal dropped: client released")},W={get gated(){return!f&&!t},get released(){return D&&!f},takeHeld:()=>R.splice(0),track:u=>o.track(u),goal:((u,m,w,g)=>j(E=>E.goal(u,m,w,g))),componentGoal:(u,m,w)=>o.componentGoal(u,m,w),identify:u=>o.identify(u),getAssignment:(u,m)=>o.getAssignment(u,m),assign:(u,m,w,g)=>o.assign(u,m,w,g),decide:u=>f?o.decide(u):D||t?Promise.resolve(null):new Promise(m=>h.push([u,Pt(),m])),getSlotResult:u=>o.getSlotResult(u),isSlotDecided:u=>{var m,w;return(w=(m=o.isSlotDecided)==null?void 0:m.call(o,u))!=null?w:!0},getSlotConfig:u=>o.getSlotConfig(u),getSitePalette:()=>o.getSitePalette(),getStyleVocabulary:()=>{var u,m;return(m=(u=o.getStyleVocabulary)==null?void 0:u.call(o))!=null?m:null},reportSlots:(u,m,w,g)=>o.reportSlots(u,m,w,g),reportSkeleton:(u,m)=>{var w;return(w=o.reportSkeleton)==null?void 0:w.call(o,u,m)},reportDrift:(u,m,w,g)=>{var E;return(E=o.reportDrift)==null?void 0:E.call(o,u,m,w,g)},requestSlots:(u,m,w)=>{var g;return f?(g=o.requestSlots)==null?void 0:g.call(o,u,m,w):s.push([u,m,w])},decideSlots:u=>{var m;return f?(m=o.decideSlots)==null?void 0:m.call(o,u):l.push(...u)},cancelSlots:u=>{var w;if(f)return(w=o.cancelSlots)==null?void 0:w.call(o,u);let m=new Set(u);for(let g of s)g[0]=g[0].filter(E=>!m.has(E));l=l.filter(g=>!m.has(g.id))},onSlotsChanged:u=>(a.add(u),()=>{a.delete(u)}),getPersona:()=>o.getPersona(),fetchWeights:()=>o.fetchWeights(),getGraph:()=>o.getGraph(),flush:()=>o.flush(),dispose:()=>(X(),O(),o.dispose()),destroy:()=>(X(),O(),f?o.destroy():Ye(e.apiKey))};function L(u){var w,g,E;o=u,f=!0,R.length&&(G.push(...R.splice(0)),z());let m=Pt();for(let[M,P,$]of h.splice(0))P!==m?$(null):u.decide(M).then($,()=>$(null));(w=u.onSlotsChanged)==null||w.call(u,()=>a.forEach(M=>M()));for(let[M,P,$]of s.splice(0))M.length>0&&((g=u.requestSlots)==null||g.call(u,M,P,$));l.length>0&&((E=u.decideSlots)==null||E.call(u,l.splice(0)))}return{proxy:W,setInner:L}}function Pt(){return typeof location=="undefined"?"":location.pathname+(/^#!?\//.test(location.hash)?location.hash:"")}function Dt(e,t,n){let i=e.get(t);if(i)return i;let p=(async()=>{try{return await n()}finally{e.delete(t)}})();return e.set(t,p),p}function _n(e){var Gt,Ut,$t,Ft,jt,Wt,Vt,Ht,zt,Qt;if(typeof window=="undefined")return We;e.nonce&&He(e.nonce),xn=e.apiKey||"local";let t=J.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(r){}let n=e.respectDoNotTrack!==!1&&Bt(),i=e.consent===!1||n,p=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!p&&e.localMode!==!1)return J.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): this client is keyless/local \u2014 there is no hosted client to upgrade to. Configure a pk_ API key to enable tracking."}),i?We:gn(e);if(i){if(!e.apiKey||!e.apiKey.startsWith("pk_"))return e.preConsentBehavior==="statistical_winner"&&console.warn("[sentient] init() called with an invalid apiKey \u2014 expected a pk_ public key. SDK disabled."),J.set(e.apiKey||"local",{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): the client was initialized with an invalid apiKey (expected a pk_ public key) \u2014 consent cannot enable tracking."}),We;let{proxy:r,setInner:c}=Ko(e,n);return J.set(e.apiKey,{config:e,upgrade:n?null:c}),r}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."),We;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),We;let d=(Gt=e.ingestUrl)!=null?Gt:kn,S=Date.now(),o=tt({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),f=an(void 0,e.apiKey),a=!1,s=ie(e.apiKey),l=()=>!a&&ie(e.apiKey)===s,h=ve(A({},f),{set:(...r)=>{l()&&f.set(...r)}}),O=nn({ingestUrl:d,apiKey:e.apiKey}),R=En(d),D={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},X=new Set,G=on({url:`${R}/goals`,apiKey:e.apiKey,headers:D,onDrop:(r,c)=>{if(!e.debug){if(X.has(c))return;X.add(c)}console.warn(`[sentient] goal dropped (HTTP ${c}) \u2014 this will not be retried. `+(c===400?"The session was not found: call init() and let the session upsert complete before firing goals.":c===401||c===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),r)}}),z=Ge((Ut=navigator.userAgent)!=null?Ut:""),j=window.location.origin,W=Ue(($t=document.referrer)!=null?$t:"",j),L=(Ft=e.sessionSegment)!=null?Ft:`${z}:${W}`,ee=new Map,u=new Map,m=new Map,w=new Set,g=new Map,E=null,M=null,P=null,$=new Set,q=new Set,ue=new Map,b=new Map,B=new Set,pe=new Set,ke=new Set,te=null,ye=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,Oe=new Set,ae=new Set,Se=new Set,re=new Map,ut=null,Ve=new Set,Pe=new Map,pt=null,In=2,Lt=new Map,se=!1,Mt=(r,c,v)=>{var y;let _=new Set,C=1;for(let k of r){c.delete(k);let x=((y=Lt.get(k))!=null?y:0)+1;Lt.set(k,x),x<=In&&(_.add(k),x>C&&(C=x))}_.size>0&&setTimeout(()=>{se||v(_)},me(C))},gt=r=>{for(let c of r)m.has(c.id)||m.set(c.id,Ae(c))};if(e.initialSlots)for(let[r,c]of Object.entries(e.initialSlots))m.set(r,c),w.add(r);if(e.initialSlotConfig)for(let[r,c]of Object.entries(e.initialSlotConfig))g.set(r,c);e.initialPalette&&(E=e.initialPalette),e.initialVocabulary&&(M=e.initialVocabulary);let le=Ee(e.apiKey);if(le){for(let[r,c]of Object.entries(le.slots))m.has(r)||m.set(r,c);for(let[r,c]of Object.entries((jt=le.slotConfig)!=null?jt:{}))g.has(r)||g.set(r,c);!E&&le.palette&&(E=le.palette),!M&&le.vocabulary&&(M=le.vocabulary)}let Nt={low:.15,medium:.5,high:.85};if(e.initialPersona)P=A({},e.initialPersona);else{let r=document.documentElement.dataset;r.sentientPersona?P={persona:r.sentientPersona,confidence:(Vt=Nt[(Wt=r.sentientConfidence)!=null?Wt:"low"])!=null?Vt:.15}:le&&(P={persona:le.persona,confidence:(Ht=Nt[le.band])!=null?Ht:.15})}if(e.initialAssignments)for(let[r,c]of Object.entries(e.initialAssignments))h.set(r,L,{variantId:c,assignedAt:Date.now(),segment:L,confidence:1});let he=Promise.resolve(),Kt=o.getSessionId();if(Kt){let r=$e((zt=document.referrer)!=null?zt:""),{utmParams:c,clickIds:v}=Mo(),_=A(A(A(A({sessionId:Kt,deviceClass:z,trafficSource:W,referrerDomain:r,utmParams:c,clickIds:v,landingPath:typeof location!="undefined"?location.pathname:void 0,timeOfDay:Fe(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Ke((Qt=navigator.userAgent)!=null?Qt:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{}),e.sdk?{sdk:e.sdk.name,sdkVersion:e.sdk.version}:{}),C=async()=>{for(let y=0;;y++){if(se||!l())return;let k=de(5e3);try{let x=await fetch(`${R}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(_),headers:D,signal:k.signal});if(x.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(x.ok||Ie(x)==="dropped")return}catch(x){}finally{k.clear()}if(y>=Do){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(x=>setTimeout(x,me(y+1)))}};try{he=C()}catch(y){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:O});let Rn=Bo(),xe=null,ft=!1,U={goal(r,c={},v=1,_=0){var H,F,Y,oe,Z,Q,I;let C=o.getSessionId();if(!C||se||!l())return;let y=Po(c)?c:{metadata:c},k=[r,(H=y.externalId)!=null?H:"",(F=y.stepIndex)!=null?F:_,(Y=y.weight)!=null?Y:v].join("\0"),x=y.value!==void 0?`${y.value}\0${(oe=y.currency)!=null?oe:""}`:null;if(Rn.firedBefore(k,x)){e.debug&&console.log(`[sentient] goal("${r}") already recorded for this action \u2014 not sent twice`);return}let N=At(),T={sessionId:C,name:r,metadata:(Z=y.metadata)!=null?Z:{},weight:(Q=y.weight)!=null?Q:v,stepIndex:(I=y.stepIndex)!=null?I:_,goalId:N,value:y.value,currency:y.currency,externalId:y.externalId};e.debug&&console.log("[sentient] goal",T);let V={id:N,body:JSON.stringify(T)};he.then(()=>G.send(V))},componentGoal(r,c,v){var N,T,V;let _=o.getSessionId();if(!_||se||!l())return;let C=h.get(r,L),y=C?null:(N=m.get(r))!=null?N:null;if(!C&&y===null){e.debug&&console.warn(`[sentient] componentGoal("${r}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}if(!C&&!w.has(r)){e.debug&&console.warn(`[sentient] componentGoal("${r}"): slot not decided this session \u2014 not attributed`);return}let k=C?C.variantId:st(y),x={id:At(),sessionId:_,projectId:e.apiKey,componentId:r,variantId:k,eventType:"goal_achieved",goalType:c,payload:A({reward:(T=v==null?void 0:v.reward)!=null?T:1,goalValue:v==null?void 0:v.value,currency:v==null?void 0:v.currency},(V=v==null?void 0:v.metadata)!=null?V:{}),timestamp:Date.now(),timeInSession:Date.now()-S,path:dt()};e.debug&&console.log("[sentient] componentGoal",x),he.then(()=>{!se&&l()&&O.push(x)})},identify(r){let c=o.getSessionId();!c||se||!l()||he.then(()=>{fetch(`${R}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:c,userId:r,ephemeral:o.isEphemeral()}),headers:D}).catch(()=>{})})},track(r){let c=o.getSessionId();if(!c||se||!l()||r.eventType==="variant_assigned"&&m.get(r.componentId)!==void 0&&!w.has(r.componentId)&&!h.get(r.componentId,L))return;let v=ve(A({path:dt()},r),{id:At(),sessionId:c,timestamp:Date.now(),timeInSession:Date.now()-S});e.debug&&console.log("[sentient] track",v),he.then(()=>O.push(v))},getAssignment(r,c){return h.get(r,c)},async assign(r,c,v,_){let C=o.getSessionId();if(!C)return null;let y=h.get(r,L);if(y&&(c!=null&&c.length||y.content!==void 0)){let k=y.ttlMs&&y.ttlMs>0?Math.max(0,y.assignedAt+y.ttlMs-Date.now()):0;return{variantId:y.variantId,assignmentTtlMs:k,content:y.content}}return Dt(ee,r,async()=>{if(!await mt(he,2500)||se||!l())return null;let k=de(3e4);try{let x={sessionId:C,componentId:r,variantIds:c};_!==void 0?x.agentDataByVariant=_:v!==void 0&&(x.agentData=v);let N=await fetch(`${R}/assign`,{method:"POST",body:JSON.stringify(x),headers:D,signal:k.signal});if(!N.ok)return null;let T=await N.json();return h.set(r,L,A({variantId:T.variantId,assignedAt:Date.now(),segment:L,confidence:1,content:T.content},T.assignmentTtlMs&&T.assignmentTtlMs>0?{ttlMs:T.assignmentTtlMs}:{})),T}catch(x){return null}finally{k.clear()}})},async decide(r){var y,k;let c=o.getSessionId();if(!c)return null;let v=(y=r.slots)!=null?y:[],_={sessionId:c};r.sections&&r.sections.length>0&&(_.sections=r.sections.map(x=>({id:x}))),_.components=(k=r.components)!=null?k:[],v.length>0&&(_.slots=v.map(je)),r.slotsFrom==="registry"&&(_.slotsFrom="registry",r.registrySlotIds&&(_.registrySlotIds=r.registrySlotIds),r.bootstrap===!1&&(_.bootstrap=!1),r.render&&Object.keys(r.render).length>0&&(_.render=r.render)),r.v&&(_.v=r.v),typeof r.pp=="number"&&(_.pp=r.pp),e.persona&&(_.persona=e.persona);let C=JSON.stringify(_);return Dt(u,C,async()=>{var N,T,V,H,F,Y,oe,Z;if(!await mt(he,2500)||se||!l())return gt(v),null;let x=de(3e4);try{let Q=await fetch(`${R}/decide`,{method:"POST",body:C,headers:D,signal:x.signal});if(!Q.ok)return gt(v),null;let I=await Q.json(),ne={};for(let K of v){let ce=(N=I.slots)==null?void 0:N[K.id];if(ce!==void 0){ne[K.id]=ce,m.set(K.id,ce),w.add(K.id);continue}let Xt=m.get(K.id);if(Xt!==void 0)ne[K.id]=Xt;else{let qt=Ae(K);ne[K.id]=qt,m.set(K.id,qt)}}if(I.slots)for(let[K,ce]of Object.entries(I.slots))K in ne||(ne[K]=ce,m.set(K,ce),w.add(K));let Cn=P!=null&&P.persona!=="unknown";I.persona&&!(I.persona==="unknown"&&Cn)?P={persona:I.persona,confidence:(T=I.confidence)!=null?T:0}:P||(P={persona:"unknown",confidence:0});for(let[K,ce]of Object.entries((V=I.assignments)!=null?V:{}))h.set(K,L,{variantId:ce,assignedAt:Date.now(),segment:L,confidence:1});if(I.slotConfig)for(let[K,ce]of Object.entries(I.slotConfig))g.set(K,ce);I.palette&&(E=I.palette),I.vocabulary&&(M=I.vocabulary);for(let K of(H=r.registrySlotIds)!=null?H:[])(F=I.slotConfig)!=null&&F[K]||(g.delete(K),m.delete(K),w.delete(K));return l()&&_e(e.apiKey,A(A(A({v:1,persona:P.persona,band:(0,Ot.confidenceBand)(P.confidence),slots:Object.fromEntries(m),layoutOrder:(Y=I.layoutOrder)!=null?Y:null,savedAt:Date.now()},g.size>0?{slotConfig:Object.fromEntries(g)}:{}),E?{palette:E}:{}),M?{vocabulary:M}:{})),A(A(A(A(A({layoutOrder:(oe=I.layoutOrder)!=null?oe:null,assignments:(Z=I.assignments)!=null?Z:{},slots:ne,persona:P.persona,confidence:P.confidence},I.slotConfig?{slotConfig:I.slotConfig}:{}),I.goals?{goals:I.goals}:{}),I.sectionMap?{sectionMap:I.sectionMap}:{}),I.palette?{palette:I.palette}:{}),I.vocabulary?{vocabulary:I.vocabulary}:{})}catch(Q){return gt(v),null}finally{x.clear()}})},getSlotResult(r){var c;return(c=m.get(r))!=null?c:null},isSlotDecided(r){return w.has(r)},getSlotConfig(r){var c;return(c=g.get(r))!=null?c:null},reportSlots(r,c,v,_){var y;let C={};for(let[k,x]of Object.entries(_!=null?_:{}))for(let N of x){let T=`${k}|${N.key}`;!ye.test(k)||ke.has(T)||(ke.add(T),((y=C[k])!=null?y:C[k]=[]).push(N))}Object.keys(C).length>0&&fetch(`${R}/slots/observed`,{method:"POST",headers:D,body:JSON.stringify({slotIds:Object.keys(C),authoredArms:C})}).catch(()=>{});for(let k of r)if(!(typeof k!="string"||k.length===0)){if(!ye.test(k)){To()&&!Oe.has(k)&&(Oe.add(k),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(k)} will not register \u2014 ids must start with a letter or digit and contain only letters, digits, '_' or '-' (max 128 chars): /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.`));continue}if(!$.has(k)){$.add(k),q.add(k);let x=c==null?void 0:c[k];if(typeof x=="string"){let T=x.replace(/\s+/g," ").trim().slice(0,400);T!==""&&ue.set(k,T)}let N=v==null?void 0:v[k];N!==void 0&&b.set(k,N)}}q.size===0||te!=null||(te=setTimeout(()=>{te=null;let k=[...q];q.clear();for(let x=0;x<k.length;x+=20){let N=k.slice(x,x+20),T={},V={};for(let H of N){let F=ue.get(H);F!==void 0&&(T[H]=F,ue.delete(H));let Y=b.get(H);Y!==void 0&&(V[H]=Y,b.delete(H))}fetch(`${R}/slots/observed`,{method:"POST",headers:D,body:JSON.stringify(A(ve(A(A({slotIds:N},Object.keys(T).length>0?{baselineTexts:T}:{}),Object.keys(V).length>0?{baselineSkeletons:V}:{}),{pagePaths:Object.fromEntries(N.map(H=>[H,location.pathname]))}),Object.keys(T).length>0&&o.getSessionId()?{sessionId:o.getSessionId()}:{}))}).catch(()=>{})}},1e3))},reportSkeleton(r,c){!ye.test(r)||B.has(r)||(B.add(r),fetch(`${R}/slots/observed`,{method:"POST",headers:D,body:JSON.stringify({slotIds:[r],baselineSkeletons:{[r]:c}})}).catch(()=>{}))},reportDrift(r,c,v,_){let C=`${r}|${c}`,y=o.getSessionId();!y||pe.has(C)||(pe.add(C),fetch(`${R}/slots/drift`,{method:"POST",headers:D,body:JSON.stringify({sessionId:y,reports:[{slotId:r,expectedFp:c,observedFp:v,reason:_}]})}).catch(()=>{}))},requestSlots(r,c,v){var _,C;for(let y of r)Se.has(y)||(Se.add(y),ye.test(y)?re.set(y,{text:c==null?void 0:c[y],render:(_=v==null?void 0:v.render)==null?void 0:_[y],skeleton:(C=v==null?void 0:v.skeletons)==null?void 0:C[y]}):U.reportSlots([y]));re.size===0||ut!=null||(ut=setTimeout(()=>{ut=null;let y=[...re];re.clear();for(let k=0;k<y.length;k+=50){let x=y.slice(k,k+50),N={};for(let[T,V]of x)V.render&&(N[T]=V.render);U.decide({slotsFrom:"registry",registrySlotIds:x.map(([T])=>T),bootstrap:!1,render:N}).then(T=>{var V,H;if(T){let F={},Y={},oe=[];for(let[Z,Q]of x){let I=(V=T.slotConfig)==null?void 0:V[Z];if(I){I.needsSkeleton&&Q.skeleton&&((H=U.reportSkeleton)==null||H.call(U,Z,Q.skeleton));continue}oe.push(Z),Q.text&&(F[Z]=Q.text),Q.skeleton&&(Y[Z]=Q.skeleton)}oe.length>0&&U.reportSlots(oe,F,Y)}else Mt(x.map(([F])=>F),Se,F=>{var Q;let Y={},oe={},Z={};for(let[I,ne]of x)F.has(I)&&(ne.text&&(Y[I]=ne.text),ne.render&&(oe[I]=ne.render),ne.skeleton&&(Z[I]=ne.skeleton));(Q=U.requestSlots)==null||Q.call(U,[...F],Y,{render:oe,skeletons:Z})});ae.forEach(F=>F())})}},0))},decideSlots(r){for(let c of r)Ve.has(c.id)||(Ve.add(c.id),Pe.set(c.id,c));Pe.size===0||pt!=null||(pt=setTimeout(()=>{pt=null;let c=[...Pe.values()];Pe.clear();for(let v=0;v<c.length;v+=30){let _=c.slice(v,v+30);U.decide({slots:_}).then(C=>{C||Mt(_.map(y=>y.id),Ve,y=>{var k;return(k=U.decideSlots)==null?void 0:k.call(U,_.filter(x=>y.has(x.id)))}),ae.forEach(y=>y())})}},0))},cancelSlots(r){for(let c of r)re.delete(c)&&Se.delete(c),Pe.delete(c)&&Ve.delete(c)},onSlotsChanged(r){return ae.add(r),()=>{ae.delete(r)}},getStyleVocabulary(){return M},getSitePalette(){return E},getPersona(){return P?{persona:P.persona,confidence:P.confidence,band:(0,Ot.confidenceBand)(P.confidence)}:null},async fetchWeights(){var c;let r=de(5e3);try{let v=await fetch(`${R}/weights`,{headers:D,signal:r.signal});return v.ok?(c=(await v.json()).components)!=null?c:[]:[]}catch(v){return[]}finally{r.clear()}},getGraph(){return{pageNodes:[],capturedAt:0}},flush(){O.flush(),G.flush()},dispose(){var r;xe==null||xe(),ft=!0,se=!0,O.destroy(),G.destroy(),((r=J.get(e.apiKey))==null?void 0:r.dispose)===U.dispose&&J.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var r;xe==null||xe(),ft=!0,se=!0,a=!0,Xe(e.apiKey),O.destroy({forget:!0}),G.destroy({forget:!0}),o.destroy(),h.clear(),((r=J.get(e.apiKey))==null?void 0:r.dispose)===U.dispose&&J.delete(e.apiKey);try{localStorage.removeItem(fe+e.apiKey),localStorage.removeItem(Le(e.apiKey)),localStorage.removeItem(Me(e.apiKey)),localStorage.removeItem(`_snt_graph_nodes${ge(e.apiKey)}`),localStorage.removeItem("_snt_graph_edges")}catch(c){}e.debug&&console.log("[sentient] destroyed")}};if(J.set(e.apiKey,{config:e,upgrade:null,dispose:U.dispose}),xe=Lo(U,e.apiKey,r=>{he.then(()=>{ft||wn.add(r)})}),e.debug){let r=window;r.__sentient&&(r.__sentient.client=U)}return U}0&&(module.exports={AGENT_INTENTS,BLOCK_ALIGNS,BLOCK_EMPHASES,BLOCK_FITS,BLOCK_GAPS,BLOCK_GRID_COLUMNS,BLOCK_HEADING_LEVELS,BLOCK_JUSTIFIES,BLOCK_MAX_WIDTHS,BLOCK_PADS,BLOCK_RATIOS,BLOCK_SIZES,BLOCK_SURFACES,BLOCK_TEXT_ALIGNS,BLOCK_TONES,BLOCK_WEIGHTS,CLICK_ID_KEYS,FORM_FIELD_KINDS,FORM_INPUT_TYPES,LEGACY_SESSION_COOKIE_NAME,LOCAL_MODE_BANNER,MAX_BLOCK_ARMS,MAX_BLOCK_CHILDREN,MAX_BLOCK_DEPTH,MAX_BLOCK_NODES,MAX_BLOCK_TEXT_LEN,MAX_FORM_FIELDS,MAX_FORM_SELECT_OPTIONS,MAX_SKELETON_LEAVES,MAX_SKELETON_NODES,MAX_SKELETON_TEXT,PAGE_SCOPE_RE,PROD_KEYLESS_ERROR,REVEAL_MS,SNAPSHOT_STORAGE_KEY_PREFIX,_registerConsentUpgradeInit,agentIntent,agentUaList,applyNonce,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,containsFormBlock,cspNonce,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,extractTrackedParams,forgetGeneration,forgetVisitor,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,pageScopeMatches,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,resetRevealStyles,reveal,routeKey,sessionCookieName,setCspNonce,toWireSlot,uaTokenMatch,writeSnapshot});
1
+ "use strict";var Gn=Object.create;var Le=Object.defineProperty,Un=Object.defineProperties,$n=Object.getOwnPropertyDescriptor,Fn=Object.getOwnPropertyDescriptors,jn=Object.getOwnPropertyNames,rn=Object.getOwnPropertySymbols,Wn=Object.getPrototypeOf,an=Object.prototype.hasOwnProperty,Vn=Object.prototype.propertyIsEnumerable;var sn=(e,t,n)=>t in e?Le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,A=(e,t)=>{for(var n in t||(t={}))an.call(t,n)&&sn(e,n,t[n]);if(rn)for(var n of rn(t))Vn.call(t,n)&&sn(e,n,t[n]);return e},Se=(e,t)=>Un(e,Fn(t));var Hn=(e,t)=>{for(var n in t)Le(e,n,{get:t[n],enumerable:!0})},ln=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let p of jn(t))!an.call(e,p)&&p!==n&&Le(e,p,{get:()=>t[p],enumerable:!(i=$n(t,p))||i.enumerable});return e};var zn=(e,t,n)=>(n=e!=null?Gn(Wn(e)):{},ln(t||!e||!e.__esModule?Le(n,"default",{value:e,enumerable:!0}):n,e)),Qn=e=>ln(Le({},"__esModule",{value:!0}),e);var Xo={};Hn(Xo,{AGENT_INTENTS:()=>it,BLOCK_ALIGNS:()=>yo,BLOCK_EMPHASES:()=>ko,BLOCK_FITS:()=>Eo,BLOCK_GAPS:()=>mo,BLOCK_GRID_COLUMNS:()=>_o,BLOCK_HEADING_LEVELS:()=>Io,BLOCK_JUSTIFIES:()=>So,BLOCK_MAX_WIDTHS:()=>Co,BLOCK_PADS:()=>Ro,BLOCK_RATIOS:()=>wo,BLOCK_SIZES:()=>ho,BLOCK_SURFACES:()=>Ao,BLOCK_TEXT_ALIGNS:()=>xo,BLOCK_TONES:()=>vo,BLOCK_WEIGHTS:()=>bo,CLICK_ID_KEYS:()=>Ct,FORM_FIELD_KINDS:()=>To,FORM_INPUT_TYPES:()=>Oo,LEGACY_SESSION_COOKIE_NAME:()=>he,LOCAL_MODE_BANNER:()=>Tt,MAX_BLOCK_ARMS:()=>No,MAX_BLOCK_CHILDREN:()=>Mo,MAX_BLOCK_DEPTH:()=>Lo,MAX_BLOCK_NODES:()=>Bo,MAX_BLOCK_TEXT_LEN:()=>Ko,MAX_FORM_FIELDS:()=>Po,MAX_FORM_SELECT_OPTIONS:()=>Do,MAX_SKELETON_LEAVES:()=>Br,MAX_SKELETON_NODES:()=>Dr,MAX_SKELETON_TEXT:()=>Lr,PAGE_SCOPE_RE:()=>Pt,PROD_KEYLESS_ERROR:()=>ft,REVEAL_MS:()=>Bt,SNAPSHOT_STORAGE_KEY_PREFIX:()=>fe,STAGE_ATTRIBUTE:()=>ct,_registerConsentUpgradeInit:()=>$o,agentIntent:()=>mn,agentUaList:()=>Ge,applyNonce:()=>Je,armOfResult:()=>lt,attachMicroSignalDetectors:()=>Rn,baselineResultFor:()=>Oe,baselineSlots:()=>hn,classifiedAgents:()=>yn,containsFormBlock:()=>_n,cspNonce:()=>wt,deriveSessionSegment:()=>Sn,detectDeviceClass:()=>$e,detectTimeOfDay:()=>We,detectTrafficSource:()=>Fe,exposedStage:()=>dt,extractTrackedParams:()=>at,forgetGeneration:()=>se,forgetVisitor:()=>tt,grantConsent:()=>zo,init:()=>Ln,isDoNotTrackEnabled:()=>Ut,matchedAgentToken:()=>Rt,normalizeUrlPattern:()=>En,pageScopeMatches:()=>xn,readSnapshot:()=>Ie,referrerDomainFromReferer:()=>je,renderPrePaintScript:()=>cn,resetRevealStyles:()=>In,reveal:()=>An,routeKey:()=>Kt,sessionCookieName:()=>_e,setCspNonce:()=>Xe,setStageAttribute:()=>ut,toWireSlot:()=>Ve,uaTokenMatch:()=>Ue,urlMatches:()=>wn,writeSnapshot:()=>Ae});module.exports=Qn(Xo);function ue(e){if(typeof AbortController!="function")return{clear:()=>{}};let t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,clear:()=>clearTimeout(n)}}function kt(e,t){return new Promise(n=>{let i=setTimeout(()=>n(!1),t),p=()=>{clearTimeout(i),n(!0)};e.then(p,p)})}var xt;function Xe(e){xt=typeof e=="string"&&e!==""?e:void 0}function wt(e=document){if(xt)return xt;try{let t=e.querySelector("script[nonce]");return(t==null?void 0:t.nonce)||(t==null?void 0:t.getAttribute("nonce"))||void 0}catch(t){return}}function Je(e,t=document){let n=wt(t);return n&&e.setAttribute("nonce",n),e}function pe(e){return e?`_${e.slice(0,12)}`:""}var he="_snt_uid";function _e(e){return`${he}${pe(e)}`}var qe="__sntForgetGen",Xn=()=>{try{return window[qe]}catch(e){return}};function Ye(e){var t,n;try{let i=window,p=(t=i[qe])!=null?t:i[qe]={};p[e]=((n=p[e])!=null?n:0)+1}catch(i){}}function se(e){var t,n;return(n=(t=Xn())==null?void 0:t[e])!=null?n:0}var fe="_snt_snap:";var Jn=["low","medium","high"];function Ie(e){try{let t=localStorage.getItem(fe+e);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||n.v!==1||typeof n.persona!="string"||typeof n.band!="string"||!Jn.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"||!(Date.now()-n.savedAt<2592e6)||!(n.slotConfig===void 0||typeof n.slotConfig=="object"&&n.slotConfig!==null&&!Array.isArray(n.slotConfig)))return null;let i=n.vocabulary;return i!==void 0&&(typeof i!="object"||i===null||!Array.isArray(i.entries)||!Array.isArray(i.images))&&delete n.vocabulary,n.stage!==void 0&&typeof n.stage!="string"&&delete n.stage,n}catch(t){return null}}function Ae(e,t){try{localStorage.setItem(fe+e,JSON.stringify(t))}catch(n){}}function cn(e,t){return'(function(){try{var N=navigator,W=window;if(N.doNotTrack=="1"||N.doNotTrack=="yes"||W.doNotTrack=="1"||N.msDoNotTrack=="1"||N.globalPrivacyControl)return;var r=localStorage.getItem('+JSON.stringify(fe+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;if(!('+2592e6+">Date.now()-s.savedAt))return;var d=document.documentElement;"+(t!=null&&t.stage?'if(typeof s.stage=="string"&&!d.hasAttribute("data-sentient-stage"))d.setAttribute("data-sentient-stage",s.stage);':"")+'if(d.hasAttribute("data-sentient-persona"))return;d.setAttribute("data-sentient-persona",s.persona);d.setAttribute("data-sentient-confidence",s.band);}catch(e){}})();'}function me(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 Ze(e,t){try{let n=localStorage.getItem(e);if(!n)return[];let i=JSON.parse(n);return Array.isArray(i)?(localStorage.removeItem(e),i.slice(-t)):[]}catch(n){return[]}}function Me(e,t,n){try{let i=(()=>{try{let u=localStorage.getItem(n);if(!u)return[];let y=JSON.parse(u);return Array.isArray(y)?y:[]}catch(u){return[]}})(),p=new Map;for(let u of i)p.set(u.id,u);for(let u of e)p.set(u.id,u);localStorage.setItem(n,JSON.stringify([...p.values()].slice(-t)))}catch(i){}}function et(e,t){try{let n=localStorage.getItem(t);if(!n)return;let i=JSON.parse(n);if(!Array.isArray(i))return;let p=new Set(e),u=i.filter(y=>!p.has(y.id));if(u.length===i.length)return;u.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(u))}catch(n){}}var qn=500,Yn=56*1024;function Ne(e){return`_snt_retry_${e.slice(0,12)}`}var Zn={push:()=>{},flush:()=>{},destroy:()=>{}};function dn(e){var O,ee,ie;if(typeof window=="undefined")return Zn;let t=(O=e.flushIntervalMs)!=null?O:5e3,n=(ee=e.maxBatchSize)!=null?ee:20,i=(ie=e.maxRetrySize)!=null?ie:100,p=e.ingestUrl,u=e.apiKey,y=Ne(u),o=!1,f=se(u),a=(...k)=>{!o&&se(u)===f&&Me(...k)},s=[],c=new Set,v=[],T=k=>{for(let B of k)C.delete(B),!c.has(B)&&(c.add(B),v.push(B));for(;v.length>qn;){let B=v.shift();B&&c.delete(B)}et(k,y)},C=new Set,D=()=>{for(;s.length>i;){let k=s.shift();k&&C.delete(k.id)}},M=k=>{c.has(k.id)||C.has(k.id)||(C.add(k.id),s.push(k),D())},V=k=>{for(let B of k)c.has(B.id)||(C.add(B.id),s.push(B));D()},H=Ze(y,i);for(let k of H)M(k);let z=0,X=0,Q=(k,B=!0)=>{if(k.length===0)return;let ge=JSON.stringify(k),be=k.map(oe=>oe.id),te,ke=ue(15e3);try{te=fetch(p,{method:"POST",keepalive:!0,signal:ke.signal,body:ge,headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`}})}catch(oe){a(k,i,y),V(k),X++,z=Date.now()+me(X);return}Promise.resolve(te).then(ke.clear,ke.clear);let xe=oe=>{if(Re(oe)!=="retry"){if(!oe.ok&&B){let we=k.filter(ae=>ae.eventType!=="pageview");if(we.length>0&&we.length<k.length){T(k.filter(ae=>ae.eventType==="pageview").map(ae=>ae.id)),Q(we,!1);return}}T(be),X=0,z=0;return}a(k,i,y),V(k),X++,z=Date.now()+me(X)};te&&typeof te.then=="function"?te.then(xe).catch(()=>{a(k,i,y),V(k),X++,z=Date.now()+me(X)}):xe(te)},$=typeof TextEncoder!="undefined"?new TextEncoder:null,d=k=>$?$.encode(k).length:k.length,m=k=>{let B=[],ge=2;for(let be of k){let te=d(JSON.stringify(be))+1;if(B.length>0&&ge+te>Yn||B.length>=n)break;B.push(be),ge+=te}return B},h=()=>{try{if(Date.now()<z)return;for(;s.length>0&&!(Date.now()<z);){let k=s.filter(ge=>!c.has(ge.id));if(s.length=0,k.length===0)break;let B=m(k);if(B.length===0)break;B.length<k.length&&s.push(...k.slice(B.length)),Q(B)}}catch(k){}},g=!0,_=null;_=setInterval(()=>{g&&h()},t);let N=()=>{document.visibilityState==="hidden"&&h()},F=()=>{h()};return document.addEventListener("visibilitychange",N),window.addEventListener("pagehide",F),{push(k){M(k),s.length>=n&&h()},flush:h,destroy(k){k!=null&&k.forget&&(o=!0),g=!1,_!==null&&(clearInterval(_),_=null),document.removeEventListener("visibilitychange",N),window.removeEventListener("pagehide",F),h()}}}var eo=200;function Ke(e){return`_snt_goal_retry_${e.slice(0,12)}`}var to={send:()=>{},flush:()=>{},destroy:()=>{}};function un(e){var d,m,h;if(typeof window=="undefined")return to;let t=(d=e.flushIntervalMs)!=null?d:5e3,n=(m=e.maxRetrySize)!=null?m:100,i=(h=e.maxPerFlush)!=null?h:5,p=Ke(e.apiKey),u=!1,y=se(e.apiKey),o=(...g)=>{!u&&se(e.apiKey)===y&&Me(...g)},f=[],a=new Set,s=new Set,c=[],v=0,T=0,C=!1,D=g=>{for(a.delete(g.id),s.has(g.id)||(s.add(g.id),c.push(g.id));c.length>eo;){let _=c.shift();_&&s.delete(_)}et([g.id],p)},M=g=>{o([g],n,p),!s.has(g.id)&&!a.has(g.id)&&(a.add(g.id),f.push(g)),Date.now()>=v&&(T++,v=Date.now()+me(T))},V=g=>{let _,N=ue(15e3);try{_=fetch(e.url,{method:"POST",keepalive:!0,signal:N.signal,body:g.body,headers:e.headers})}catch(O){M(g);return}let F=O=>{var ie;let ee=Re(O);if(ee==="retry"){M(g);return}ee==="dropped"&&((ie=e.onDrop)==null||ie.call(e,g,O.status)),D(g),T=0,v=0};Promise.resolve(_).then(N.clear,N.clear),_&&typeof _.then=="function"?_.then(F).catch(()=>M(g)):F(_)},H=()=>{try{if(C||Date.now()<v)return;let g=0;for(;f.length>0&&g<i&&!(Date.now()<v);){let _=f.shift();a.delete(_.id),!s.has(_.id)&&(g++,V(_))}}catch(g){}},z=Ze(p,n);for(let g of z)a.has(g.id)||(a.add(g.id),f.push(g));z.length>0&&Me(z,n,p);let X=setInterval(H,t),Q=()=>{document.visibilityState==="hidden"&&H()},$=()=>H();return document.addEventListener("visibilitychange",Q),window.addEventListener("pagehide",$),{send(g){if(C){s.has(g.id)||o([g],n,p);return}if(!(s.has(g.id)||a.has(g.id))){if(Date.now()<v){o([g],n,p),a.add(g.id),f.push(g);return}V(g)}},flush:H,destroy(g){g!=null&&g.forget&&(u=!0),clearInterval(X),document.removeEventListener("visibilitychange",Q),window.removeEventListener("pagehide",$),H(),C=!0}}}function tt(e){if(typeof window=="undefined"||!e)return!1;Ye(e);let t=!1,n=_e(e);try{if(new RegExp(`(?:^|; )${n}=`).test(document.cookie)){let y=location.protocol==="https:"?"; Secure":"";document.cookie=`${n}=; max-age=0; SameSite=lax; path=/${y}`,t=!0}}catch(y){}let i=pe(e),p=[n,"_snt_graph_edges",fe+e,Ne(e),Ke(e),`_snt_graph_nodes${i}`],u=[`_snt_asgn${i}_`];for(let y of["localStorage","sessionStorage"])try{let o=window[y];for(let f of p)o.getItem(f)!==null&&(o.removeItem(f),t=!0);for(let f=o.length-1;f>=0;f--){let a=o.key(f);a&&u.some(s=>a.startsWith(s))&&(o.removeItem(a),t=!0)}}catch(o){}try{(new RegExp(`(?:^|; )${he}=[^;]`).test(document.cookie)||localStorage.getItem(he)!==null||sessionStorage.getItem(he)!==null)&&localStorage.setItem(`${he}_tomb${i}`,"1")}catch(y){}return t}function nt(){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)})}var gn="_snt_uid",no=365,Ce="_snt_uid";function oo(){return nt()}function _t(e){try{let t=document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return t?decodeURIComponent(t[1]):null}catch(t){return null}}function At(){try{return location.protocol==="https:"?"; Secure":""}catch(e){return""}}function ro(e,t,n){try{document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${n}; SameSite=lax; path=/${At()}`}catch(i){}}function ot(e){try{return localStorage.getItem(e)}catch(t){return null}}function pn(e,t){try{return localStorage.setItem(e,t),!0}catch(n){return!1}}function It(e){try{return sessionStorage.getItem(e)}catch(t){return null}}function so(e,t){try{return sessionStorage.setItem(e,t),!0}catch(n){return!1}}function io(e){try{sessionStorage.removeItem(e)}catch(t){}}function ao(e){try{return document.cookie=`${e}_probe=1; max-age=1; SameSite=lax; path=/${At()}`,document.cookie.indexOf(`${e}_probe=1`)!==-1}catch(t){return!1}}function lo(e){try{localStorage.removeItem(e)}catch(t){}}function co(e){try{document.cookie=`${e}=; max-age=0; SameSite=lax; path=/${At()}`}catch(t){}}var uo={getSessionId:()=>null,isEphemeral:()=>!1,destroy:()=>{}};function rt(e){var C,D,M,V,H,z,X;if(typeof window=="undefined")return uo;let t=pe(e==null?void 0:e.apiKey),n=(C=e==null?void 0:e.cookieName)!=null?C:_e(e==null?void 0:e.apiKey),i=`${Ce}${t}`,p=`${Ce}_tomb${t}`,y=((D=e==null?void 0:e.cookieTTLDays)!=null?D:no)*24*60*60,o=Q=>Q&&Q.length>0?Q:null,f=()=>{var Q,$;return t&&!(e!=null&&e.cookieName)&&ot(p)===null?($=(Q=o(_t(gn)))!=null?Q:o(ot(Ce)))!=null?$:o(It(Ce)):null},a=(X=(z=(H=(V=(M=o(_t(n)))!=null?M:o(ot(i)))!=null?V:o(It(i)))!=null?H:f())!=null?z:o(e==null?void 0:e.ssrSessionId))!=null?X:oo();ro(n,a,y);let s=pn(i,a),c=ao(n),v=s?!1:so(i,a),T=!s&&!c&&!v;return{getSessionId:()=>a,isEphemeral:()=>T,destroy:()=>{a=null,co(n),lo(i),io(i),t&&!(e!=null&&e.cookieName)&&(_t(gn)!==null||ot(Ce)!==null||It(Ce)!==null)&&pn(p,"1")}}}var go=1800*1e3;function st(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function fn(e=go,t){let n=new Map,i=`_snt_asgn${pe(t)}_`,p=(a,s)=>`${i}${encodeURIComponent(a)}:${encodeURIComponent(s)}`,u=a=>{let s=a.slice(i.length),c=s.indexOf(":");if(c<0)return null;try{return{componentId:decodeURIComponent(s.slice(0,c)),segment:decodeURIComponent(s.slice(c+1))}}catch(v){return null}},y=()=>{try{let a=[];for(let s=0;s<localStorage.length;s++){let c=localStorage.key(s);c!=null&&c.startsWith(i)&&a.push(c)}return a}catch(a){return[]}},o=a=>a.assignedAt+(a.ttlMs&&a.ttlMs>0?a.ttlMs:e)<Date.now();return typeof window!="undefined"&&(()=>{for(let a of y())try{let s=localStorage.getItem(a);if(!s)continue;let c=JSON.parse(s);if(o(c)){localStorage.removeItem(a);continue}let v=u(a);if(!v)continue;n.set(st(v.componentId,v.segment),c)}catch(s){}})(),{get(a,s){let c=n.get(st(a,s));return c?o(c)?(n.delete(st(a,s)),null):c:null},set(a,s,c){let v=st(a,s);n.set(v,c);try{localStorage.setItem(p(a,s),JSON.stringify(c))}catch(T){}},clear(){n.clear();for(let a of y())try{localStorage.removeItem(a)}catch(s){}}}}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 Ue(e){return Rt(e)!==null}function Rt(e){var n;if(!e)return null;let t=e.toLowerCase();return(n=Ge.find(i=>t.includes(i.toLowerCase())))!=null?n:null}var it={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 mn(e){if(!e)return"other";let t=Ge.find(n=>n.toLowerCase()===e.toLowerCase());return t&&it[t]||"other"}function yn(){var t;let e={user:[],search:[],training:[],other:[]};for(let n of Ge)e[(t=it[n])!=null?t:"other"].push(n);return e}function $e(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 Fe(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 i=n.hostname.toLowerCase();return/(^|\.)(google|bing|duckduckgo|yahoo)\./.test(i)?"search":/(^|\.)(twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|t\.co)$/.test(i)?"social":"referral"}catch(n){return"direct"}}function je(e){if(!e)return null;try{return new URL(e).hostname}catch(t){return null}}var Ct=["gclid","gbraid","wbraid","fbclid","ttclid","msclkid","twclid","li_fat_id"];function at(e){let t={},n={};try{let i=typeof e=="string"||e instanceof URLSearchParams?new URLSearchParams(e):Object.entries(e).flatMap(([p,u])=>{let y=Array.isArray(u)?u[0]:u;return y===void 0?[]:[[p,y]]});for(let[p,u]of i)p.startsWith("utm_")?p in t||(t[p]=u):Ct.includes(p)&&(p in n||(n[p]=u))}catch(i){}return{utmParams:t,clickIds:n}}function We(e){let t=e.getHours();return t<6?"night":t<12?"morning":t<18?"afternoon":"evening"}function Sn(e){let t=po("__segment__",e);return`${t.deviceClass}:${t.trafficSource}`}function po(e,t){var u,y,o,f,a,s,c,v;let n=(y=(u=t==null?void 0:t.userAgent)==null?void 0:u.trim())!=null?y:"",i=(f=(o=t==null?void 0:t.referer)==null?void 0:o.trim())!=null?f:"",p=(a=t==null?void 0:t.now)!=null?a:new Date;return A({sessionId:e,ephemeral:!1,utmParams:(s=t==null?void 0:t.utmParams)!=null?s:{},clickIds:(c=t==null?void 0:t.clickIds)!=null?c:{},deviceClass:n?$e(n):"desktop",trafficSource:i?Fe(i,t==null?void 0:t.appOrigin):"direct",referrerDomain:je(i),timeOfDay:We(p),dayOfWeek:(v=["sun","mon","tue","wed","thu","fri","sat"][p.getDay()])!=null?v:"sun",automation:(t==null?void 0:t.webdriver)===!0||Ue(n)},t!=null&&t.landingPath?{landingPath:t.landingPath.split(/[?#]/)[0]}:{})}var Te=require("@sentientui/policy");function Ve(e){return A(A(A({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 Oe(e){let t=Ve(e);return(0,Te.slotResultFor)(t,(0,Te.slotBaselineArm)(t))}function hn(e){let t={};for(let n of e)t[n.id]=Oe(n);return t}function lt(e){return typeof e=="string"?e:(0,Te.canonicalArm)(e)}var bn=require("@sentientui/policy"),ct="data-sentient-stage";function dt(e,t){return!t||typeof e!="string"||!(e==="returning"||bn.STAGE_KEYS.includes(e))?null:t!=="detailed"&&(e==="customer"||e==="lapsed")?"returning":e}function ut(e,t=document){try{e?t.documentElement.setAttribute(ct,e):t.documentElement.removeAttribute(ct)}catch(n){}}var Nt=require("@sentientui/policy");var pt=require("@sentientui/policy");var ft="[sentient] No API key configured \u2014 nothing is being learned. Set NEXT_PUBLIC_SENTIENT_API_KEY or pass localMode: true for local development.",Tt="[sentient] Local mode \u2014 decisions are simulated on-device and nothing is sent over the network. Add an API key to learn from real traffic.",vn=!1,gt=!1;function fo(){var e;try{return(e=new URLSearchParams(window.location.search).get("sentient_persona"))!=null?e:void 0}catch(t){return}}function kn(e){var a;let t=rt({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),n=(a=t.getSessionId())!=null?a:"local",i=fo(),p=import("@sentientui/core/local").then(s=>{let c=s;return c.LOCAL_ENGINE_AVAILABLE?(vn||(vn=!0,console.info(Tt)),c):(gt||(gt=!0,console.error(ft)),null)}).catch(()=>(gt||(gt=!0,console.error(ft)),null)),u=null,y={low:.15,medium:.5,high:.85},o=(()=>{var c;if(e.initialPersona)return A({},e.initialPersona);let s=Ie(e.apiKey||"local");return s?{persona:s.persona,confidence:(c=y[s.band])!=null?c:.15}:null})();function f(s){let c=document.documentElement;c.dataset.sentientPersona===void 0&&(c.dataset.sentientPersona=s.persona,c.dataset.sentientConfidence=(0,pt.confidenceBand)(s.confidence))}return{isLocal:!0,async decide(s){var T,C,D;let c=await p;if(!c)return null;let v=c.createLocalEngine({sessionId:n,forcedPersona:i}).decide(s);return u=Se(A({},v),{layoutOrder:(C=(T=v.layoutOrder)!=null?T:u==null?void 0:u.layoutOrder)!=null?C:null,slots:A(A({},(D=u==null?void 0:u.slots)!=null?D:{}),v.slots)}),Ae(e.apiKey||"local",{v:1,persona:u.persona,band:(0,pt.confidenceBand)(u.confidence),slots:u.slots,layoutOrder:u.layoutOrder,savedAt:Date.now()}),f(v),v},getSlotResult(s){var c,v,T;return(T=(v=u==null?void 0:u.slots[s])!=null?v:(c=e.initialSlots)==null?void 0:c[s])!=null?T:null},getSlotConfig(s){var c,v;return(v=(c=e.initialSlotConfig)==null?void 0:c[s])!=null?v:null},getSitePalette(){var s;return(s=e.initialPalette)!=null?s:null},reportSlots(){},getVisitorId:()=>null,getPersona(){let s=u!=null?u:o;return s?{persona:s.persona,confidence:s.confidence,band:(0,pt.confidenceBand)(s.confidence)}:null},async assign(s,c){var C;let v=await p;return!v||!c||c.length===0?c!=null&&c[0]?{variantId:c[0],assignmentTtlMs:0}:null:{variantId:(C=v.createLocalEngine({sessionId:n,forcedPersona:i}).decide({components:[{id:s,variantIds:c}]}).assignments[s])!=null?C:c[0],assignmentTtlMs:0}},track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>t.destroy()}}var Pt=/^(\*|\/[^\s?#*]*(\/\*)?)$/;function Ot(e){let t=e.split(/[?#]/)[0]||"/";return t.length>1?t.replace(/\/+$/,"")||"/":t}function xn(e,t){if(e===void 0||!Pt.test(e))return!1;if(e==="*")return!0;let n=Ot(t);if(e.endsWith("/*")){let i=Ot(e.slice(0,-2));return n.startsWith(i==="/"?"/":`${i}/`)&&n!==i}return n===Ot(e)}function wn(e,t){if(!e)return!1;if(e==="/")return t==="/";let n=e.endsWith("/")?e.slice(0,-1):e;return t===n||t.startsWith(`${n}/`)}function En(e){if(!/^https?:\/\//i.test(e))return e;try{return new URL(e).pathname||"/"}catch(t){return e}}var mo=["none","sm","md","lg"],yo=["start","center","end","stretch"],So=["start","center","end","between"],ho=["sm","md","lg"],bo=["normal","medium","bold"],vo=["default","muted","accent"],ko=["primary","secondary","ghost"],xo=["left","center","right"],wo=["auto","square","landscape","wide"],Eo=["cover","contain"],_o=[2,3,4],Io=[1,2,3,4],Ao=["default","raised"],Ro=["none","sm","md","lg"],Co=["measure"],To=["input","textarea","select"],Oo=["text","email","number","tel"],Po=5,Do=8,Bo=64,Lo=5,Mo=12,No=4,Ko=500;function _n(e){if(e==null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.type==="form"?!0:Array.isArray(t.children)?t.children.some(_n):!1}var Dr=40,Br=120,Lr=300;var Dt="sentient-reveal",Pe="sentient-revealed",Bt=240,mt=!1;function In(){var e;mt=!1,typeof document!="undefined"&&((e=document.getElementById(Dt))==null||e.remove())}function Go(e){if(mt||e.getElementById(Dt)){mt=!0;return}let t=Je(e.createElement("style"),e);t.id=Dt,t.textContent=`@media (prefers-reduced-motion: no-preference){@keyframes ${Pe}{from{opacity:.55;transform:translateY(2px)}to{opacity:1;transform:none}}.${Pe}{animation:${Pe} ${Bt}ms cubic-bezier(.2,.6,.2,1) both}}`,e.head.appendChild(t),mt=!0}function An(e,t={}){var p;let n=(p=t.doc)!=null?p:typeof document!="undefined"?document:void 0;if(!n||!(e instanceof Element)||(t.arm!==void 0&&e.setAttribute("data-sentient-arm",t.arm),t.persona!==void 0&&e.setAttribute("data-sentient-persona",t.persona),t.previous!==void 0&&t.previous===e.textContent))return!1;Go(n),e.classList.remove(Pe),e.offsetWidth,e.classList.add(Pe);let i=()=>{e.classList.remove(Pe),e.removeEventListener("animationend",i)};return e.addEventListener("animationend",i),!0}function Rn(e,t,n,i){let p=[];{let o=!1,f=[],a=()=>{if(o)return;let s=Date.now();for(f.push(s);f.length>0&&s-f[0]>500;)f.shift();f.length>=3&&(o=!0,e("rage_click"))};t.addEventListener("click",a),p.push(()=>t.removeEventListener("click",a))}{let u=!1,y=o=>{if(u||!(o.target instanceof Node)||!t.contains(o.target)&&t!==o.target)return;u=!0;let f=typeof window!="undefined"?window.getSelection():null,a=f?f.toString().length:0;e("text_copy",{selectionLength:a})};document.addEventListener("copy",y),p.push(()=>document.removeEventListener("copy",y))}{let u=!1,y=!1,o=null,f=()=>{o!==null&&(clearTimeout(o),o=null)},a=()=>{u||!y||(f(),o=setTimeout(()=>{!u&&y&&(u=!0,e("scroll_hesitation"))},3e3))},s=()=>{f(),a()},c=T=>{for(let C of T)y=C.intersectionRatio>.3,y?a():f()},v=new IntersectionObserver(c,{threshold:[.3]});v.observe(t),window.addEventListener("scroll",s,{passive:!0}),p.push(()=>{v.disconnect(),window.removeEventListener("scroll",s),f()})}if((i==null?void 0:i.tabLoss)!==!1){let u=!1,y=n!=null?n:Date.now(),o=()=>{if(u||document.visibilityState!=="hidden")return;let f=Date.now()-y;f<15e3&&(u=!0,e("tab_loss",{timeOnPage:f}))};document.addEventListener("visibilitychange",o),p.push(()=>document.removeEventListener("visibilitychange",o))}return()=>{for(let u of p)u()}}function Uo(){var e;return typeof process=="undefined"||((e=process.env)==null?void 0:e.NODE_ENV)!=="production"}var On="https://api.sentient-ui.com/v1/events",q=new Map,Pn=null;function $o(e,t){let n=q.get(e);n&&n.upgrade&&(n.reinit=t)}function Fo(e){return"value"in e||"currency"in e||"externalId"in e||"metadata"in e||"weight"in e||"stepIndex"in e}var jo=3;function Lt(){return nt()}function yt(){var e;if(typeof window!="undefined")return((e=window.location)==null?void 0:e.pathname)||void 0}function Wo(){let e=new WeakMap,t=new Map,n=!1,i=(o,f,a)=>{let s=o.get(f);return a===null?s?!0:(o.set(f,new Set),!1):s?s.has(a)?!0:(s.add(a),!1):(o.set(f,new Set([a])),!1)},p=typeof window!="undefined"&&"event"in window,u=()=>{if(!p)return;let o=window.event;return typeof Event=="function"&&o instanceof Event?o:void 0},y=()=>{if(p){Promise.resolve().then(()=>{n=!1,t.clear()});return}let o=!1,f=()=>{o||(o=!0,n=!1,t.clear())};if(setTimeout(f,0),typeof MessageChannel=="function"){let a=new MessageChannel;a.port1.onmessage=()=>{a.port1.close(),a.port2.close(),f()},a.port2.postMessage(0)}};return{firedBefore(o,f){let a=u();if(a){let c=e.get(a);return c||(c=new Map,e.set(a,c)),i(c,o,f)}let s=i(t,o,f);return!s&&!n&&(n=!0,y()),s}}}var Dn=new Set;function Vo(e,t,n){let i=typeof window=="undefined"?null:window.history;if(!i)return()=>{};let p=!1,u,y=()=>{if(p)return;let a=yt();!a||a===u||(u=a,e.track({projectId:t,componentId:"__page__",eventType:"pageview",payload:{}}),n(`${t}:${a}`))},o=[];for(let a of["pushState","replaceState"]){let s=i[a],c=function(...v){let T=s.apply(this,v);return y(),T};i[a]=c,o.push([a,s,c])}window.addEventListener("popstate",y);let f=yt();return f&&Dn.has(`${t}:${f}`)?u=f:y(),()=>{if(!p){p=!0,window.removeEventListener("popstate",y);for(let[a,s,c]of o)i[a]===c&&(i[a]=s)}}}var He={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,assign:()=>Promise.resolve(null),decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getVisitorId:()=>null,fetchWeights:()=>Promise.resolve([]),getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}};function Ho(){try{return at(window.location.search)}catch(e){return{utmParams:{},clickIds:{}}}}function Bn(e){return e.replace(/\/events\/?$/,"")}function Ut(){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 zo(e){var f;if(typeof window=="undefined")return;let t=e!=null?e:Pn;if(!t){console.warn("[sentient] grantConsent() called before init()");return}let n=q.get(t);if(!n){console.warn("[sentient] grantConsent() called before init()");return}let{config:i,upgrade:p,reinit:u}=n;if(!p){n.upgradeBlockedReason&&console.warn(n.upgradeBlockedReason);return}if(i.respectDoNotTrack!==!1&&Ut())return;let y=(u!=null?u:Ln)(Se(A({},i),{consent:!0}));p(y);let o=(f=q.get(t))==null?void 0:f.dispose;q.set(t,{config:Se(A({},i),{consent:!0}),upgrade:null,dispose:o})}function Qo(e,t){var $;let n=e.preConsentBehavior==="statistical_winner",i=Bn(($=e.ingestUrl)!=null?$:On),p={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},u=new Map,y=new Map,o={track:()=>{},goal:()=>{},componentGoal:()=>{},identify:()=>{},getAssignment:()=>null,fetchWeights:()=>Promise.resolve([]),assign(d,m,h){if(!n)return Promise.resolve(null);let g=u.get(d);return g?Promise.resolve(g):Gt(y,d,async()=>{try{let _=new URLSearchParams({componentId:d});for(let ee of m!=null?m:[])_.append("variantIds[]",ee);let N=ue(5e3),F;try{let ee=await fetch(`${i}/winner?${_.toString()}`,{headers:p,signal:N.signal});if(!ee.ok)return m!=null&&m[0]?{variantId:m[0],assignmentTtlMs:0}:null;F=await ee.json()}finally{N.clear()}let O={variantId:F.variantId,assignmentTtlMs:0};return u.set(d,O),O}catch(_){return m!=null&&m[0]?{variantId:m[0],assignmentTtlMs:0}:null}})},decide:()=>Promise.resolve(null),getSlotResult:()=>null,getSlotConfig:()=>null,getSitePalette:()=>null,reportSlots:()=>{},getPersona:()=>null,getVisitorId:()=>null,getGraph:()=>({pageNodes:[],capturedAt:0}),flush:()=>{},dispose:()=>{},destroy:()=>{}},f=!1,a=new Set,s=[],c=[],v=[],T=()=>{for(let[,,d]of v.splice(0))d(null);C.length=0},C=[],D=!1,M=()=>{if(f)return;D=!0;let d=q.get(e.apiKey);(d==null?void 0:d.upgrade)===Q&&q.set(e.apiKey,{config:e,upgrade:null,upgradeBlockedReason:"[sentient] grantConsent(): client released before consent; call init() again"})},V=[],H=()=>{setTimeout(()=>{var d;try{(d=V.shift())==null||d(o)}catch(m){}V.length&&H()})},z=d=>{f?V.length?V.push(d):d(o):!t&&!D&&C.length<100?C.push(d):D&&e.debug&&console.warn("[sentient] goal dropped: client released")},X={get gated(){return!f&&!t},get released(){return D&&!f},takeHeld:()=>C.splice(0),track:d=>o.track(d),goal:((d,m,h,g)=>z(_=>_.goal(d,m,h,g))),componentGoal:(d,m,h)=>o.componentGoal(d,m,h),identify:d=>o.identify(d),getAssignment:(d,m)=>o.getAssignment(d,m),isUnified:d=>{var m,h;return(h=(m=o.isUnified)==null?void 0:m.call(o,d))!=null?h:!1},assign:(d,m,h,g,_)=>o.assign(d,m,h,g,_),decide:d=>f?o.decide(d):D||t?Promise.resolve(null):new Promise(m=>v.push([d,Kt(),m])),getSlotResult:d=>o.getSlotResult(d),isSlotDecided:d=>{var m,h;return(h=(m=o.isSlotDecided)==null?void 0:m.call(o,d))!=null?h:!0},getSlotConfig:d=>o.getSlotConfig(d),getSitePalette:()=>o.getSitePalette(),getStyleVocabulary:()=>{var d,m;return(m=(d=o.getStyleVocabulary)==null?void 0:d.call(o))!=null?m:null},reportSlots:(d,m,h,g)=>o.reportSlots(d,m,h,g),reportSkeleton:(d,m)=>{var h;return(h=o.reportSkeleton)==null?void 0:h.call(o,d,m)},reportAgentData:(d,m,h)=>{var g;return(g=o.reportAgentData)==null?void 0:g.call(o,d,m,h)},reportDrift:(d,m,h,g)=>{var _;return(_=o.reportDrift)==null?void 0:_.call(o,d,m,h,g)},requestSlots:(d,m,h)=>{var g;return f?(g=o.requestSlots)==null?void 0:g.call(o,d,m,h):s.push([d,m,h])},decideSlots:d=>{var m;return f?(m=o.decideSlots)==null?void 0:m.call(o,d):c.push(...d)},cancelSlots:d=>{var h;if(f)return(h=o.cancelSlots)==null?void 0:h.call(o,d);let m=new Set(d);for(let g of s)g[0]=g[0].filter(_=>!m.has(_));c=c.filter(g=>!m.has(g.id))},onSlotsChanged:d=>(a.add(d),()=>{a.delete(d)}),getPersona:()=>o.getPersona(),getVisitorId:()=>{var d,m;return(m=(d=o.getVisitorId)==null?void 0:d.call(o))!=null?m:null},fetchWeights:()=>o.fetchWeights(),getGraph:()=>o.getGraph(),flush:()=>o.flush(),dispose:()=>(M(),T(),o.dispose()),destroy:()=>(M(),T(),f?o.destroy():tt(e.apiKey))};function Q(d){var h,g,_;o=d,f=!0,C.length&&(V.push(...C.splice(0)),H());let m=Kt();for(let[N,F,O]of v.splice(0))F!==m?O(null):d.decide(N).then(O,()=>O(null));(h=d.onSlotsChanged)==null||h.call(d,()=>a.forEach(N=>N()));for(let[N,F,O]of s.splice(0))N.length>0&&((g=d.requestSlots)==null||g.call(d,N,F,O));c.length>0&&((_=d.decideSlots)==null||_.call(d,c.splice(0)))}return{proxy:X,setInner:Q}}function Kt(){return typeof location=="undefined"?"":location.pathname+(/^#!?\//.test(location.hash)?location.hash:"")}function Gt(e,t,n){let i=e.get(t);if(i)return i;let p=(async()=>{try{return await n()}finally{e.delete(t)}})();return e.set(t,p),p}function Ln(e){var Vt,Ht,zt,Qt,Xt,Jt,qt,Yt,Zt,en,tn;if(typeof window=="undefined")return He;e.nonce&&Xe(e.nonce),Pn=e.apiKey||"local";let t=q.get(e.apiKey||"local");if(t!=null&&t.dispose)try{t.dispose()}catch(r){}let n=e.respectDoNotTrack!==!1&&Ut(),i=e.consent===!1||n,p=typeof e.apiKey=="string"&&e.apiKey.startsWith("pk_");if(e.localMode===!0||!p&&e.localMode!==!1)return q.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."}),i?He:kn(e);if(i){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."),q.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."}),He;let{proxy:r,setInner:l}=Qo(e,n);return q.set(e.apiKey,{config:e,upgrade:n?null:l}),r}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."),He;if(e.ingestUrl==="")return console.warn("[sentient] init() called with an empty ingestUrl. SDK disabled."),He;let u=(Vt=e.ingestUrl)!=null?Vt:On,y=Date.now(),o=rt({ssrSessionId:e.ssrSessionId,apiKey:e.apiKey}),f=fn(void 0,e.apiKey),a=!1,s=se(e.apiKey),c=()=>!a&&se(e.apiKey)===s,v=new Set((Ht=e.initialUnified)!=null?Ht:[]),T=Se(A({},f),{get:(r,l)=>v.has(r)?null:f.get(r,l),set:(...r)=>{c()&&f.set(...r)}}),C=dn({ingestUrl:u,apiKey:e.apiKey}),D=Bn(u),M={"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},V=new Set,H=un({url:`${D}/goals`,apiKey:e.apiKey,headers:M,onDrop:(r,l)=>{if(!e.debug){if(V.has(l))return;V.add(l)}console.warn(`[sentient] goal dropped (HTTP ${l}) \u2014 this will not be retried. `+(l===400?"The session was not found: call init() and let the session upsert complete before firing goals.":l===401||l===403?"Check the API key and that this origin is on the project allowlist.":"See the response status for the cause."),r)}}),z=$e((zt=navigator.userAgent)!=null?zt:""),X=window.location.origin,Q=Fe((Qt=document.referrer)!=null?Qt:"",X),$=(Xt=e.sessionSegment)!=null?Xt:`${z}:${Q}`,d=new Map,m=new Map,h=new Map,g=new Set,_=new Map,N=null,F=null,O=null,ee=new Set,ie=new Set,k=new Map,B=new Map,ge=new Set,be=new Set,te=new Set,ke=new Set,xe=null,oe=/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/,we=new Set,ae=new Set,ze=new Set,De=new Map,St=null,Qe=new Set,Be=new Map,ht=null,Mn=2,$t=new Map,re=!1,Ft=(r,l,S)=>{var b;let I=new Set,R=1;for(let x of r){l.delete(x);let w=((b=$t.get(x))!=null?b:0)+1;$t.set(x,w),w<=Mn&&(I.add(x),w>R&&(R=w))}I.size>0&&setTimeout(()=>{re||S(I)},me(R))},bt=r=>{for(let l of r)h.has(l.id)||h.set(l.id,Oe(l))};if(e.initialSlots)for(let[r,l]of Object.entries(e.initialSlots))h.set(r,l),g.add(r);if(e.initialSlotConfig)for(let[r,l]of Object.entries(e.initialSlotConfig))_.set(r,l);e.initialPalette&&(N=e.initialPalette),e.initialVocabulary&&(F=e.initialVocabulary);let le=Ie(e.apiKey);if(le){for(let[r,l]of Object.entries(le.slots))h.has(r)||h.set(r,l);for(let[r,l]of Object.entries((Jt=le.slotConfig)!=null?Jt:{}))_.has(r)||_.set(r,l);!N&&le.palette&&(N=le.palette),!F&&le.vocabulary&&(F=le.vocabulary)}let jt={low:.15,medium:.5,high:.85};if(e.initialPersona)O=A({},e.initialPersona);else{let r=document.documentElement.dataset;r.sentientPersona?O={persona:r.sentientPersona,confidence:(Yt=jt[(qt=r.sentientConfidence)!=null?qt:"low"])!=null?Yt:.15}:le&&(O={persona:le.persona,confidence:(Zt=jt[le.band])!=null?Zt:.15})}if(e.initialAssignments)for(let[r,l]of Object.entries(e.initialAssignments))T.set(r,$,{variantId:l,assignedAt:Date.now(),segment:$,confidence:1});let ye=Promise.resolve(),Wt=o.getSessionId();if(Wt){let r=je((en=document.referrer)!=null?en:""),{utmParams:l,clickIds:S}=Ho(),I=A(A(A(A({sessionId:Wt,deviceClass:z,trafficSource:Q,referrerDomain:r,utmParams:l,clickIds:S,landingPath:typeof location!="undefined"?location.pathname:void 0,timeOfDay:We(new Date),dayOfWeek:["sun","mon","tue","wed","thu","fri","sat"][new Date().getDay()],ephemeral:o.isEphemeral(),automation:typeof navigator!="undefined"&&navigator.webdriver===!0||Ue((tn=navigator.userAgent)!=null?tn:"")},e.userId?{userId:e.userId}:{}),e.persona?{persona:e.persona}:{}),e.country?{country:e.country}:{}),e.sdk?{sdk:e.sdk.name,sdkVersion:e.sdk.version}:{}),R=async()=>{for(let b=0;;b++){if(re||!c())return;let x=ue(5e3);try{let w=await fetch(`${D}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify(I),headers:M,signal:x.signal});if(w.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(w.ok||Re(w)==="dropped")return}catch(w){}finally{x.clear()}if(b>=jo){console.warn("[SentientUI] Could not register the session after retries. Conversions in this visit may not be recorded.");return}await new Promise(w=>setTimeout(w,me(b+1)))}};try{ye=R()}catch(b){}}e.debug&&(console.log("[sentient] initialized",{context:e.context}),window.__sentient={client:null,queue:C});let Nn=Wo(),ve=null,vt=!1,W={goal(r,l={},S=1,I=0){var j,L,Y,ne,Z,J,E;let R=o.getSessionId();if(!R||re||!c())return;let b=Fo(l)?l:{metadata:l},x=[r,(j=b.externalId)!=null?j:"",(L=b.stepIndex)!=null?L:I,(Y=b.weight)!=null?Y:S].join("\0"),w=b.value!==void 0?`${b.value}\0${(ne=b.currency)!=null?ne:""}`:null;if(Nn.firedBefore(x,w)){e.debug&&console.log(`[sentient] goal("${r}") already recorded for this action \u2014 not sent twice`);return}let K=Lt(),P={sessionId:R,name:r,metadata:(Z=b.metadata)!=null?Z:{},weight:(J=b.weight)!=null?J:S,stepIndex:(E=b.stepIndex)!=null?E:I,goalId:K,value:b.value,currency:b.currency,externalId:b.externalId};e.debug&&console.log("[sentient] goal",P);let G={id:K,body:JSON.stringify(P)};ye.then(()=>H.send(G))},componentGoal(r,l,S){var K,P,G;let I=o.getSessionId();if(!I||re||!c())return;let R=T.get(r,$),b=R?null:(K=h.get(r))!=null?K:null;if(!R&&b===null){e.debug&&console.warn(`[sentient] componentGoal("${r}"): no assignment or slot decision yet \u2014 render its <Adaptive>/adaptive hook or call assign()/decide() before recording a goal.`);return}if(!R&&!g.has(r)){e.debug&&console.warn(`[sentient] componentGoal("${r}"): slot not decided this session \u2014 not attributed`);return}let x=R?R.variantId:lt(b),w={id:Lt(),sessionId:I,projectId:e.apiKey,componentId:r,variantId:x,eventType:"goal_achieved",goalType:l,payload:A({reward:(P=S==null?void 0:S.reward)!=null?P:1,goalValue:S==null?void 0:S.value,currency:S==null?void 0:S.currency},(G=S==null?void 0:S.metadata)!=null?G:{}),timestamp:Date.now(),timeInSession:Date.now()-y,path:yt()};e.debug&&console.log("[sentient] componentGoal",w),ye.then(()=>{!re&&c()&&C.push(w)})},identify(r){let l=o.getSessionId();!l||re||!c()||ye.then(()=>{fetch(`${D}/sessions`,{method:"POST",keepalive:!0,body:JSON.stringify({sessionId:l,userId:r,ephemeral:o.isEphemeral()}),headers:M}).catch(()=>{})})},track(r){let l=o.getSessionId();if(!l||re||!c()||r.eventType==="variant_assigned"&&h.get(r.componentId)!==void 0&&!g.has(r.componentId)&&!T.get(r.componentId,$))return;let S=Se(A({path:yt()},r),{id:Lt(),sessionId:l,timestamp:Date.now(),timeInSession:Date.now()-y});e.debug&&console.log("[sentient] track",S),ye.then(()=>C.push(S))},getAssignment(r,l){return T.get(r,l)},isUnified:r=>v.has(r),async assign(r,l,S,I,R){var K;let b=o.getSessionId();if(!b)return null;let x=(R==null?void 0:R.unified)===!0;if(x&&v.has(r))return{variantId:(K=l==null?void 0:l[0])!=null?K:"",assignmentTtlMs:0,unified:!0};let w=T.get(r,$);if(w&&(l!=null&&l.length||w.content!==void 0)){let P=w.ttlMs&&w.ttlMs>0?Math.max(0,w.assignedAt+w.ttlMs-Date.now()):0;return{variantId:w.variantId,assignmentTtlMs:P,content:w.content}}return Gt(d,x?`${r}\0unified`:r,async()=>{if(!await kt(ye,2500)||re||!c())return null;let P=ue(3e4);try{let G={sessionId:b,componentId:r,variantIds:l};I!==void 0?G.agentDataByVariant=I:S!==void 0&&(G.agentData=S),x&&(G.caps={unified:!0});let j=await fetch(`${D}/assign`,{method:"POST",body:JSON.stringify(G),headers:M,signal:P.signal});if(!j.ok)return null;let L=await j.json();return L.unified===!0?x?(v.add(r),{variantId:L.variantId,assignmentTtlMs:0,unified:!0}):null:(T.set(r,$,A({variantId:L.variantId,assignedAt:Date.now(),segment:$,confidence:1,content:L.content},L.assignmentTtlMs&&L.assignmentTtlMs>0?{ttlMs:L.assignmentTtlMs}:{})),L)}catch(G){return null}finally{P.clear()}})},async decide(r){var b,x;let l=o.getSessionId();if(!l)return null;let S=(b=r.slots)!=null?b:[],I={sessionId:l};r.sections&&r.sections.length>0&&(I.sections=r.sections.map(w=>({id:w}))),I.components=(x=r.components)!=null?x:[],S.length>0&&(I.slots=S.map(Ve)),r.slotsFrom==="registry"&&(I.slotsFrom="registry",r.registrySlotIds&&(I.registrySlotIds=r.registrySlotIds),r.bootstrap===!1&&(I.bootstrap=!1),r.render&&Object.keys(r.render).length>0&&(I.render=r.render)),r.v&&(I.v=r.v),typeof r.pp=="number"&&(I.pp=r.pp),e.persona&&(I.persona=e.persona);let R=JSON.stringify(I);return Gt(m,R,async()=>{var K,P,G,j,L,Y,ne,Z;if(!await kt(ye,2500)||re||!c())return bt(S),null;let w=ue(3e4);try{let J=await fetch(`${D}/decide`,{method:"POST",body:R,headers:M,signal:w.signal});if(!J.ok)return bt(S),null;let E=await J.json(),ce=dt(E.stage,e.stageAttributes);e.stageAttributes&&ut(ce);let Ee={};for(let U of S){let de=(K=E.slots)==null?void 0:K[U.id];if(de!==void 0){Ee[U.id]=de,h.set(U.id,de),g.add(U.id);continue}let nn=h.get(U.id);if(nn!==void 0)Ee[U.id]=nn;else{let on=Oe(U);Ee[U.id]=on,h.set(U.id,on)}}if(E.slots)for(let[U,de]of Object.entries(E.slots))U in Ee||(Ee[U]=de,h.set(U,de),g.add(U));let Kn=O!=null&&O.persona!=="unknown";E.persona&&!(E.persona==="unknown"&&Kn)?O={persona:E.persona,confidence:(P=E.confidence)!=null?P:0}:O||(O={persona:"unknown",confidence:0});for(let[U,de]of Object.entries((G=E.assignments)!=null?G:{}))T.set(U,$,{variantId:de,assignedAt:Date.now(),segment:$,confidence:1});if(E.slotConfig)for(let[U,de]of Object.entries(E.slotConfig))_.set(U,de);E.palette&&(N=E.palette),E.vocabulary&&(F=E.vocabulary);for(let U of(j=r.registrySlotIds)!=null?j:[])(L=E.slotConfig)!=null&&L[U]||(_.delete(U),h.delete(U),g.delete(U));return c()&&Ae(e.apiKey,A(A(A(A({v:1,persona:O.persona,band:(0,Nt.confidenceBand)(O.confidence),slots:Object.fromEntries(h),layoutOrder:(Y=E.layoutOrder)!=null?Y:null,savedAt:Date.now()},_.size>0?{slotConfig:Object.fromEntries(_)}:{}),N?{palette:N}:{}),F?{vocabulary:F}:{}),ce?{stage:ce}:{})),A(A(A(A(A(A(A({layoutOrder:(ne=E.layoutOrder)!=null?ne:null,assignments:(Z=E.assignments)!=null?Z:{},slots:Ee,persona:O.persona,confidence:O.confidence},E.slotConfig?{slotConfig:E.slotConfig}:{}),E.goals?{goals:E.goals}:{}),E.sectionMap?{sectionMap:E.sectionMap}:{}),E.palette?{palette:E.palette}:{}),E.vocabulary?{vocabulary:E.vocabulary}:{}),E.stage?{stage:E.stage}:{}),E.context?{context:E.context}:{})}catch(J){return bt(S),null}finally{w.clear()}})},getSlotResult(r){var l;return(l=h.get(r))!=null?l:null},isSlotDecided(r){return g.has(r)},getSlotConfig(r){var l;return(l=_.get(r))!=null?l:null},reportSlots(r,l,S,I){var b;let R={};for(let[x,w]of Object.entries(I!=null?I:{}))for(let K of w){let P=`${x}|${K.key}`;!oe.test(x)||te.has(P)||(te.add(P),((b=R[x])!=null?b:R[x]=[]).push(K))}Object.keys(R).length>0&&fetch(`${D}/slots/observed`,{method:"POST",headers:M,body:JSON.stringify({slotIds:Object.keys(R),authoredArms:R})}).catch(()=>{});for(let x of r)if(!(typeof x!="string"||x.length===0)){if(!oe.test(x)){Uo()&&!we.has(x)&&(we.add(x),console.warn(`[sentient] reportSlots: slot id ${JSON.stringify(x)} will not register \u2014 ids must start with a letter or digit and contain only letters, digits, '_' or '-' (max 128 chars): /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.`));continue}if(!ee.has(x)){ee.add(x),ie.add(x);let w=l==null?void 0:l[x];if(typeof w=="string"){let P=w.replace(/\s+/g," ").trim().slice(0,400);P!==""&&k.set(x,P)}let K=S==null?void 0:S[x];K!==void 0&&B.set(x,K)}}ie.size===0||xe!=null||(xe=setTimeout(()=>{xe=null;let x=[...ie];ie.clear();for(let w=0;w<x.length;w+=20){let K=x.slice(w,w+20),P={},G={};for(let j of K){let L=k.get(j);L!==void 0&&(P[j]=L,k.delete(j));let Y=B.get(j);Y!==void 0&&(G[j]=Y,B.delete(j))}fetch(`${D}/slots/observed`,{method:"POST",headers:M,body:JSON.stringify(A(Se(A(A({slotIds:K},Object.keys(P).length>0?{baselineTexts:P}:{}),Object.keys(G).length>0?{baselineSkeletons:G}:{}),{pagePaths:Object.fromEntries(K.map(j=>[j,location.pathname]))}),Object.keys(P).length>0&&o.getSessionId()?{sessionId:o.getSessionId()}:{}))}).catch(()=>{})}},1e3))},reportSkeleton(r,l){!oe.test(r)||ge.has(r)||(ge.add(r),fetch(`${D}/slots/observed`,{method:"POST",headers:M,body:JSON.stringify({slotIds:[r],baselineSkeletons:{[r]:l}})}).catch(()=>{}))},reportAgentData(r,l,S){let I=`${r}|${l}`;!oe.test(r)||ke.has(I)||(ke.add(I),fetch(`${D}/slots/observed`,{method:"POST",headers:M,body:JSON.stringify(A({slotIds:[r],agentData:{[r]:{[l]:S}}},l.startsWith("authored.")?{authoredArms:{[r]:[{key:l.slice(9)}]}}:{}))}).catch(()=>{}))},reportDrift(r,l,S,I){let R=`${r}|${l}`,b=o.getSessionId();!b||be.has(R)||(be.add(R),fetch(`${D}/slots/drift`,{method:"POST",headers:M,body:JSON.stringify({sessionId:b,reports:[{slotId:r,expectedFp:l,observedFp:S,reason:I}]})}).catch(()=>{}))},requestSlots(r,l,S){var I,R;for(let b of r)ze.has(b)||(ze.add(b),oe.test(b)?De.set(b,{text:l==null?void 0:l[b],render:(I=S==null?void 0:S.render)==null?void 0:I[b],skeleton:(R=S==null?void 0:S.skeletons)==null?void 0:R[b]}):W.reportSlots([b]));De.size===0||St!=null||(St=setTimeout(()=>{St=null;let b=[...De];De.clear();for(let x=0;x<b.length;x+=50){let w=b.slice(x,x+50),K={};for(let[P,G]of w)G.render&&(K[P]=G.render);W.decide({slotsFrom:"registry",registrySlotIds:w.map(([P])=>P),bootstrap:!1,render:K}).then(P=>{var G,j;if(P){let L={},Y={},ne=[];for(let[Z,J]of w){let E=(G=P.slotConfig)==null?void 0:G[Z];if(E){E.needsSkeleton&&J.skeleton&&((j=W.reportSkeleton)==null||j.call(W,Z,J.skeleton));continue}ne.push(Z),J.text&&(L[Z]=J.text),J.skeleton&&(Y[Z]=J.skeleton)}ne.length>0&&W.reportSlots(ne,L,Y)}else Ft(w.map(([L])=>L),ze,L=>{var J;let Y={},ne={},Z={};for(let[E,ce]of w)L.has(E)&&(ce.text&&(Y[E]=ce.text),ce.render&&(ne[E]=ce.render),ce.skeleton&&(Z[E]=ce.skeleton));(J=W.requestSlots)==null||J.call(W,[...L],Y,{render:ne,skeletons:Z})});ae.forEach(L=>L())})}},0))},decideSlots(r){for(let l of r)Qe.has(l.id)||(Qe.add(l.id),Be.set(l.id,l));Be.size===0||ht!=null||(ht=setTimeout(()=>{ht=null;let l=[...Be.values()];Be.clear();for(let S=0;S<l.length;S+=30){let I=l.slice(S,S+30);W.decide({slots:I}).then(R=>{R||Ft(I.map(b=>b.id),Qe,b=>{var x;return(x=W.decideSlots)==null?void 0:x.call(W,I.filter(w=>b.has(w.id)))}),ae.forEach(b=>b())})}},0))},cancelSlots(r){for(let l of r)De.delete(l)&&ze.delete(l),Be.delete(l)&&Qe.delete(l)},onSlotsChanged(r){return ae.add(r),()=>{ae.delete(r)}},getStyleVocabulary(){return F},getSitePalette(){return N},getVisitorId:()=>c()?o.getSessionId():null,getPersona(){return O?{persona:O.persona,confidence:O.confidence,band:(0,Nt.confidenceBand)(O.confidence)}:null},async fetchWeights(){var l;let r=ue(5e3);try{let S=await fetch(`${D}/weights`,{headers:M,signal:r.signal});return S.ok?(l=(await S.json()).components)!=null?l:[]:[]}catch(S){return[]}finally{r.clear()}},getGraph(){return{pageNodes:[],capturedAt:0}},flush(){C.flush(),H.flush()},dispose(){var r;ve==null||ve(),vt=!0,re=!0,C.destroy(),H.destroy(),((r=q.get(e.apiKey))==null?void 0:r.dispose)===W.dispose&&q.delete(e.apiKey),e.debug&&console.log("[sentient] disposed")},destroy(){var r;ve==null||ve(),vt=!0,re=!0,a=!0,Ye(e.apiKey),C.destroy({forget:!0}),H.destroy({forget:!0}),o.destroy(),T.clear(),((r=q.get(e.apiKey))==null?void 0:r.dispose)===W.dispose&&q.delete(e.apiKey);try{localStorage.removeItem(fe+e.apiKey),localStorage.removeItem(Ne(e.apiKey)),localStorage.removeItem(Ke(e.apiKey)),localStorage.removeItem(`_snt_graph_nodes${pe(e.apiKey)}`),localStorage.removeItem("_snt_graph_edges")}catch(l){}e.debug&&console.log("[sentient] destroyed")}};if(q.set(e.apiKey,{config:e,upgrade:null,dispose:W.dispose}),ve=Vo(W,e.apiKey,r=>{ye.then(()=>{vt||Dn.add(r)})}),e.debug){let r=window;r.__sentient&&(r.__sentient.client=W)}return W}0&&(module.exports={AGENT_INTENTS,BLOCK_ALIGNS,BLOCK_EMPHASES,BLOCK_FITS,BLOCK_GAPS,BLOCK_GRID_COLUMNS,BLOCK_HEADING_LEVELS,BLOCK_JUSTIFIES,BLOCK_MAX_WIDTHS,BLOCK_PADS,BLOCK_RATIOS,BLOCK_SIZES,BLOCK_SURFACES,BLOCK_TEXT_ALIGNS,BLOCK_TONES,BLOCK_WEIGHTS,CLICK_ID_KEYS,FORM_FIELD_KINDS,FORM_INPUT_TYPES,LEGACY_SESSION_COOKIE_NAME,LOCAL_MODE_BANNER,MAX_BLOCK_ARMS,MAX_BLOCK_CHILDREN,MAX_BLOCK_DEPTH,MAX_BLOCK_NODES,MAX_BLOCK_TEXT_LEN,MAX_FORM_FIELDS,MAX_FORM_SELECT_OPTIONS,MAX_SKELETON_LEAVES,MAX_SKELETON_NODES,MAX_SKELETON_TEXT,PAGE_SCOPE_RE,PROD_KEYLESS_ERROR,REVEAL_MS,SNAPSHOT_STORAGE_KEY_PREFIX,STAGE_ATTRIBUTE,_registerConsentUpgradeInit,agentIntent,agentUaList,applyNonce,armOfResult,attachMicroSignalDetectors,baselineResultFor,baselineSlots,classifiedAgents,containsFormBlock,cspNonce,deriveSessionSegment,detectDeviceClass,detectTimeOfDay,detectTrafficSource,exposedStage,extractTrackedParams,forgetGeneration,forgetVisitor,grantConsent,init,isDoNotTrackEnabled,matchedAgentToken,normalizeUrlPattern,pageScopeMatches,readSnapshot,referrerDomainFromReferer,renderPrePaintScript,resetRevealStyles,reveal,routeKey,sessionCookieName,setCspNonce,setStageAttribute,toWireSlot,uaTokenMatch,urlMatches,writeSnapshot});
2
2
  //# sourceMappingURL=index.js.map