@sentientui/react 0.8.5 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -0
- package/dist/devtools.d.cts +5 -0
- package/dist/devtools.d.ts +5 -0
- package/dist/devtools.js +3 -0
- package/dist/devtools.js.map +1 -0
- package/dist/devtools.mjs +3 -0
- package/dist/devtools.mjs.map +1 -0
- package/dist/index.d.cts +75 -1
- package/dist/index.d.ts +75 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3 -1
- package/dist/index.mjs.map +1 -1
- package/dist/next/adaptive-root.d.ts +95 -1
- package/dist/next/adaptive-root.js +3 -1
- package/dist/next/adaptive-root.js.map +1 -1
- package/package.json +7 -2
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provider.tsx","../src/weights-store.ts","../src/adaptive.tsx","../src/use-assignment.ts","../src/adaptive-text.tsx","../src/use-adaptive-goal.ts","../src/segment.ts"],"sourcesContent":["'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';\nimport {\n detectDeviceClass,\n detectTrafficSource,\n init,\n type SentientClient,\n type SentientConfig,\n} from '@sentientui/core';\nimport { update as updateWeightsStore, type ComponentWeights } from './weights-store.js';\n\n/**\n * Mirrors the segment derivation inside core `init()` so the cache key used\n * by `useAssignment` always matches the key `assign()` writes under. Before\n * this, the context defaulted to 'desktop:direct' while core used the\n * detected segment — a systematic cache miss for every integration that\n * didn't pass `sessionSegment` explicitly.\n */\nfunction deriveDefaultSegment(): string {\n if (typeof window === 'undefined') return 'desktop:direct';\n try {\n const device = detectDeviceClass(navigator.userAgent ?? '');\n const source = detectTrafficSource(document.referrer ?? '', window.location.origin);\n return `${device}:${source}`;\n } catch {\n return 'desktop:direct';\n }\n}\n\n/** How to render adaptive slots during SSR when assignments are not preloaded. */\nexport type SsrFallback = 'first' | 'none';\n\ntype AdaptiveContextValue = {\n client: SentientClient | null;\n // The publishable API key (pk_…). Historically named `projectId` because the\n // API uses it as the project identifier on the wire, but it is the API key,\n // not the project UUID. Field renamed for clarity.\n apiKey: string;\n initialAssignments: Record<string, string>;\n sessionSegment: string;\n ssrFallback: SsrFallback;\n onAssignment: ((componentId: string, variantId: string) => void) | undefined;\n initialLayoutOrder: string[] | null;\n};\n\nconst AdaptiveContext = createContext<AdaptiveContextValue>({\n client: null,\n apiKey: '',\n initialAssignments: {},\n sessionSegment: 'desktop:direct',\n ssrFallback: 'first',\n onAssignment: undefined,\n initialLayoutOrder: null,\n});\n\nexport type AdaptiveProviderProps = {\n apiKey: string;\n context: SentientConfig['context'];\n debug?: boolean;\n /**\n * SSR-preloaded assignments from `preloadAssignments()` / `loadAdaptiveAssignments()`.\n * Passed through to `useAssignment` as synchronous initial state so crawlers and\n * the first paint see real content (recommended for SEO).\n */\n initialAssignments?: Record<string, string>;\n /**\n * Bandit segment from SSR (`device:source`). Keeps cache, assign, and worker\n * weights on one row — must match `loadAdaptiveAssignments` / session upsert.\n */\n sessionSegment?: string;\n /**\n * When no `initialAssignments` exist for a component, `'first'` renders\n * `variantIds[0]` in server HTML (safe default for SEO). Use `'none'` only for\n * decorative slots marked `clientOnly`.\n * @default 'first'\n */\n ssrFallback?: SsrFallback;\n /**\n * Consent gate. When `false` the SDK is not initialised and no events are\n * sent. Flip to `true` (e.g. after the user accepts the cookie banner) to\n * initialise and begin tracking.\n */\n consent?: boolean;\n /**\n * Behavior before consent is granted. Pass `'statistical_winner'` to serve the\n * best-performing variant via `GET /v1/winner` with zero tracking while the\n * consent banner is showing. Requires `consent: false`.\n * @see SentientConfig.preConsentBehavior\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Called once per component the first time a variant is resolved for that\n * component in this session. Use to forward assignments to your own analytics\n * (Mixpanel, PostHog, Segment, etc.) without having to wrap `useAssignment`.\n */\n onAssignment?: (componentId: string, variantId: string) => void;\n /**\n * SSR-preloaded section order from `loadAdaptiveDecision()`.\n * Pass the `layoutOrder` field from `DecideResult`. When set,\n * `useLayoutOrder()` returns this on first render so there is no layout shift.\n */\n initialLayoutOrder?: string[] | null;\n /**\n * Session ID generated during SSR (the `sessionId` field returned by\n * `loadAdaptiveAssignments` / `loadAdaptiveDecision`). When provided and no\n * existing session cookie or localStorage entry is found, the client adopts\n * this ID so events and goals are attributed to the same session the server\n * used for variant assignment.\n */\n ssrSessionId?: string;\n /**\n * ISO 3166-1 alpha-2 country code. Pass the value of the `CF-IPCountry`\n * header from your Next.js server component to populate country on landing\n * sessions without client-side geo lookup.\n */\n country?: string;\n children: ReactNode;\n};\n\n/**\n * Initialises the Sentient core SDK in a useEffect (SSR-safe) and exposes the\n * client via React context. Re-initialises when `consent` changes.\n */\nexport function AdaptiveProvider(props: AdaptiveProviderProps): JSX.Element {\n const [client, setClient] = useState<SentientClient | null>(null);\n // Derived once per mount: identical to what core init() computes, so cache\n // reads (context segment) and cache writes (core segment) always agree.\n const [sessionSegment] = useState(() => props.sessionSegment ?? deriveDefaultSegment());\n\n useEffect(() => {\n // When consent is explicitly false with no preConsentBehavior, tear down any existing client.\n if (props.consent === false && !props.preConsentBehavior) {\n setClient((prev: SentientClient | null) => {\n prev?.destroy();\n return null;\n });\n return;\n }\n\n const c = init({\n apiKey: props.apiKey,\n context: props.context,\n debug: props.debug,\n initialAssignments: props.initialAssignments,\n sessionSegment,\n consent: props.consent,\n preConsentBehavior: props.preConsentBehavior,\n ssrSessionId: props.ssrSessionId,\n country: props.country,\n });\n setClient(c);\n return () => {\n c.destroy();\n };\n // Re-init when consent changes. Other props are intentionally stable.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.consent]);\n\n // Poll /v1/weights every 60 s so long-lived sessions see updated bandit weights\n // without a page reload. useAssignment subscribers react via weights-store.\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n const poll = async (): Promise<void> => {\n if (cancelled) return;\n let entries;\n try {\n entries = await client.fetchWeights();\n } catch {\n // Network/transient error: skip this cycle and retry on the next\n // interval. Swallowed deliberately so a failed poll never surfaces as\n // an unhandled rejection.\n return;\n }\n if (cancelled) return;\n for (const entry of entries) {\n const weights: ComponentWeights = {\n componentId: entry.componentId,\n updatedAt: entry.updatedAt,\n variants: entry.variants.map((v) => ({\n variantId: v.variantId,\n pulls: v.pulls,\n avgReward: v.avgReward ?? 0,\n })),\n };\n updateWeightsStore(entry.componentId, weights);\n }\n };\n void poll();\n const timerId = setInterval(() => void poll(), 60_000);\n return () => {\n cancelled = true;\n clearInterval(timerId);\n };\n }, [client]);\n\n const ssrFallback = props.ssrFallback ?? 'first';\n\n // Memoized so unrelated parent re-renders don't cascade through every\n // useSentient / useAssignment consumer via a fresh context object.\n const value = useMemo<AdaptiveContextValue>(\n () => ({\n client,\n apiKey: props.apiKey,\n initialAssignments: props.initialAssignments ?? {},\n sessionSegment,\n ssrFallback,\n onAssignment: props.onAssignment,\n initialLayoutOrder: props.initialLayoutOrder ?? null,\n }),\n [\n client,\n props.apiKey,\n props.initialAssignments,\n sessionSegment,\n ssrFallback,\n props.onAssignment,\n props.initialLayoutOrder,\n ],\n );\n\n return (\n <AdaptiveContext.Provider value={value}>\n {props.children}\n </AdaptiveContext.Provider>\n );\n}\n\n/**\n * Returns the SentientClient, or null until the provider has finished\n * initialising on the client.\n */\nexport function useSentient(): SentientClient | null {\n return useContext(AdaptiveContext).client;\n}\n\n/** Internal: publishable API key carried alongside the client. */\nexport function useAdaptiveApiKey(): string {\n return useContext(AdaptiveContext).apiKey;\n}\n\n/**\n * @deprecated Renamed to `useAdaptiveApiKey`. Kept as an alias so external\n * imports from earlier versions of this package keep working. Will be removed\n * in 1.0.0.\n */\nlet warnedProjectIdAlias = false;\nexport function useAdaptiveProjectId(): string {\n if (\n !warnedProjectIdAlias &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'production'\n ) {\n warnedProjectIdAlias = true;\n console.warn(\n '[@sentientui/react] useAdaptiveProjectId is deprecated; use useAdaptiveApiKey. Will be removed in 1.0.0.',\n );\n }\n return useAdaptiveApiKey();\n}\n\n/** Internal: SSR-preloaded assignments for hydration-safe first render. */\nexport function useInitialAssignments(): Record<string, string> {\n return useContext(AdaptiveContext).initialAssignments;\n}\n\n/** Internal: bandit segment aligned with SSR session upsert. */\nexport function useSessionSegment(): string {\n return useContext(AdaptiveContext).sessionSegment;\n}\n\n/** Internal: SSR fallback strategy when a slot has no preloaded assignment. */\nexport function useSsrFallback(): SsrFallback {\n return useContext(AdaptiveContext).ssrFallback;\n}\n\n/** Internal: forwarding hook for consumer analytics integration. */\nexport function useOnAssignment(): ((componentId: string, variantId: string) => void) | undefined {\n return useContext(AdaptiveContext).onAssignment;\n}\n\n/**\n * Returns the persona-specific section order from SSR, or null when no\n * sections were declared on AdaptiveRoot or reliability is below threshold.\n */\nexport function useLayoutOrder(): string[] | null {\n return useContext(AdaptiveContext).initialLayoutOrder;\n}\n","/** Per-component weights store with isolated subscriptions. */\n\nexport type VariantWeight = {\n variantId: string;\n pulls: number;\n avgReward: number;\n};\n\nexport type ComponentWeights = {\n componentId: string;\n variants: VariantWeight[];\n updatedAt: number;\n};\n\ntype Listener = (weights: ComponentWeights) => void;\n\nconst store = new Map<string, ComponentWeights>();\nconst listeners = new Map<string, Set<Listener>>();\n\n/**\n * Subscribes a listener to a single component. Returns an unsubscribe function.\n * Updates to other components never trigger this listener.\n */\nexport function subscribe(componentId: string, cb: Listener): () => void {\n let set = listeners.get(componentId);\n if (!set) {\n set = new Set();\n listeners.set(componentId, set);\n }\n set.add(cb);\n return () => {\n set!.delete(cb);\n if (set!.size === 0) listeners.delete(componentId);\n };\n}\n\n/**\n * Replaces the weights for a component and notifies only that component's\n * subscribers.\n */\nexport function update(componentId: string, weights: ComponentWeights): void {\n store.set(componentId, weights);\n const set = listeners.get(componentId);\n if (!set) return;\n for (const cb of set) {\n try {\n cb(weights);\n } catch {\n /* never throw to other listeners */\n }\n }\n}\n\n/**\n * Returns the latest known weights for a component, or null if none seen.\n */\nexport function getWeights(componentId: string): ComponentWeights | null {\n return store.get(componentId) ?? null;\n}\n\n/** Test-only: wipe the entire store. */\nexport function _resetWeightsStore(): void {\n store.clear();\n listeners.clear();\n}\n","'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { memo, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport { attachMicroSignalDetectors, type MicroSignalType } from '@sentientui/core';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { useAssignment } from './use-assignment.js';\n\nexport type ScrollDepthGoal = { type: 'scroll_depth'; threshold: number };\nexport type ClickGoal = { type: 'click'; selector?: string };\nexport type FormSubmitGoal = { type: 'form_submit' };\nexport type CompositeGoal = { type: 'composite'; all: GoalConfig[] };\nexport type WeightedStep = { goal: GoalConfig; name: string; weight: number };\nexport type WeightedCompositeGoal = { type: 'weighted_composite'; steps: WeightedStep[] };\nexport type GoalConfig = ScrollDepthGoal | ClickGoal | FormSubmitGoal | CompositeGoal | WeightedCompositeGoal;\n\n/** Maps a detected micro-signal to a named session goal (`client.goal`). */\nexport type MicroSignalGoalConfig = string | { name: string; weight?: number; stepIndex?: number };\nexport type MicroSignalGoals = Partial<Record<MicroSignalType, MicroSignalGoalConfig>>;\n\nexport type AdaptiveProps = {\n id: string;\n variants: Record<string, ReactNode>;\n goal: string | GoalConfig;\n /**\n * When a passive micro-signal fires on this component, also record a named goal.\n * Use for inferred goals surfaced in the dashboard (e.g. rage_click → 'confused_by_hero').\n */\n microSignalGoals?: MicroSignalGoals;\n /**\n * When true, renders nothing during SSR and before client hydration.\n * Use when you cannot pass `initialAssignments` and prefer a blank slot over\n * a hydration mismatch. Tradeoff: minor CLS on first paint.\n */\n clientOnly?: boolean;\n /**\n * Variant-specific structured data for AI agent consumption via /sentient.json and\n * GET /v1/agent/layout. Keyed by variant ID — only the assigned variant's entry is stored,\n * so agents see only the content currently being served to visitors.\n *\n * Prefer this over `agentData` when variants have meaningfully different content.\n */\n agentDataByVariant?: Record<string, unknown>;\n /** @deprecated Use agentDataByVariant for variant-specific content. Stored as-is for the assigned variant. */\n agentData?: unknown;\n};\n\nfunction normalize(goal: string | GoalConfig): GoalConfig {\n if (typeof goal === 'string') return { type: 'click' };\n return goal;\n}\n\nconst PREVIEW_HTML_MAX_CHARS = 30_000;\n\n/**\n * previewHtml is the largest payload the SDK sends (up to 30 KB). The server\n * keeps the first-seen preview per (component, variant), so re-sending it on\n * every mount/navigation is pure waste — send it once per browser session.\n */\nfunction shouldSendPreviewHtml(componentId: string, variantId: string): boolean {\n try {\n const key = `_snt_pv_${componentId}_${variantId}`;\n if (sessionStorage.getItem(key)) return false;\n sessionStorage.setItem(key, '1');\n return true;\n } catch {\n // Storage unavailable (private mode, quota) — keep prior behavior.\n return true;\n }\n}\n\nfunction isClickableTarget(el: EventTarget | null): boolean {\n if (!(el instanceof Element)) return false;\n const tag = el.tagName.toLowerCase();\n if (tag === 'a' || tag === 'button') return true;\n const role = el.getAttribute('role');\n return role === 'button';\n}\n\nfunction findClickable(start: Element, container: Element, selector?: string): boolean {\n if (selector) {\n try {\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (cursor.matches(selector)) return true;\n cursor = cursor.parentElement;\n }\n } catch {\n // Invalid CSS selector — treat as no match rather than breaking all click handlers.\n }\n return false;\n }\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (isClickableTarget(cursor)) return true;\n cursor = cursor.parentElement;\n }\n return false;\n}\n\nfunction AdaptiveImpl(props: AdaptiveProps): JSX.Element | null {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const variantIds = useMemo(() => Object.keys(props.variants), [props.variants]);\n const { variantId, content } = useAssignment(props.id, variantIds, props.agentData, props.agentDataByVariant);\n const containerRef = useRef<HTMLDivElement>(null);\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => { setMounted(true); }, []);\n const goalFiredRef = useRef(false);\n const microGoalFiredRef = useRef<Set<MicroSignalType>>(new Set());\n const assignTrackedRef = useRef<string | null>(null);\n const goalKey = typeof props.goal === 'string' ? props.goal : JSON.stringify(props.goal);\n const goal = useMemo(() => normalize(props.goal), [goalKey]);\n const goalLabel = typeof props.goal === 'string' ? props.goal : goal.type;\n\n // Track variant_assigned exactly once per (component, variant) mount.\n // Captures innerHTML as previewHtml so the dashboard can render a live preview\n // without requiring manual registry calls. First-seen wins on the server.\n // `mounted` is in deps so the effect re-runs after clientOnly components hydrate\n // and their container div is actually in the DOM.\n useEffect(() => {\n if (!client || !variantId || !apiKey) return;\n if (assignTrackedRef.current === variantId) return;\n const rawHtml = containerRef.current?.innerHTML ?? '';\n // Wait until content is in the DOM; will re-run when mounted changes.\n if (!rawHtml) return;\n assignTrackedRef.current = variantId;\n const includePreview = rawHtml !== '' && shouldSendPreviewHtml(props.id, variantId);\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId,\n eventType: 'variant_assigned',\n payload: includePreview ? { previewHtml: rawHtml.slice(0, PREVIEW_HTML_MAX_CHARS) } : {},\n });\n }, [client, variantId, apiKey, props.id, mounted, content]);\n\n // Reset goal latch when variant or goal changes.\n useEffect(() => {\n goalFiredRef.current = false;\n microGoalFiredRef.current = new Set();\n }, [variantId, goal]);\n\n // Emit cursor_signal after 800 ms of continuous hover.\n useEffect(() => {\n if (!client || !variantId) return;\n const node = containerRef.current;\n if (!node) return;\n\n let timerId: ReturnType<typeof setTimeout> | null = null;\n let hoverStart = 0;\n\n const onEnter = (): void => {\n hoverStart = Date.now();\n timerId = setTimeout(() => {\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId: variantId!,\n eventType: 'cursor_signal',\n payload: { hoverDuration: Date.now() - hoverStart },\n });\n timerId = null;\n }, 800);\n };\n\n const onLeave = (): void => {\n if (timerId !== null) {\n clearTimeout(timerId);\n timerId = null;\n }\n };\n\n node.addEventListener('mouseenter', onEnter);\n node.addEventListener('mouseleave', onLeave);\n return () => {\n node.removeEventListener('mouseenter', onEnter);\n node.removeEventListener('mouseleave', onLeave);\n if (timerId !== null) clearTimeout(timerId);\n };\n }, [client, variantId, apiKey, props.id]);\n\n // Attach micro-signal detectors passively — rage click, text copy, scroll hesitation, tab loss.\n useEffect(() => {\n if (!client || !variantId) return;\n const node = containerRef.current;\n if (!node) return;\n const assignedAt = Date.now();\n return attachMicroSignalDetectors(\n (signalType, extra = {}) => {\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId: variantId!,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n\n const mapping = props.microSignalGoals?.[signalType];\n if (!mapping || microGoalFiredRef.current.has(signalType)) return;\n microGoalFiredRef.current.add(signalType);\n const name = typeof mapping === 'string' ? mapping : mapping.name;\n const weight = typeof mapping === 'string' ? 1.0 : (mapping.weight ?? 1.0);\n const stepIndex = typeof mapping === 'string' ? 0 : (mapping.stepIndex ?? 0);\n client.goal(name, { signalType, ...extra }, weight, stepIndex);\n },\n node,\n assignedAt,\n );\n }, [client, variantId, apiKey, props.id, props.microSignalGoals]);\n\n // Attach goal tracking.\n useEffect(() => {\n if (!client || !variantId) return;\n const node = containerRef.current;\n if (!node) return;\n\n // --- Weighted composite: each step fires independently as it completes ---\n if (goal.type === 'weighted_composite') {\n const firedSteps = new Set<number>();\n const wcCleanups: Array<() => void> = [];\n\n goal.steps.forEach(({ goal: sub, name: stepName, weight: stepWeight }, idx) => {\n const fireStep = (): void => {\n if (firedSteps.has(idx)) return;\n firedSteps.add(idx);\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId: variantId!,\n eventType: 'goal_achieved',\n goalType: stepName,\n payload: { reward: stepWeight },\n });\n client.goal(stepName, {}, stepWeight, idx);\n };\n\n if (sub.type === 'click') {\n const onClick = (e: MouseEvent): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n fireStep();\n };\n node.addEventListener('click', onClick);\n wcCleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n fireStep();\n };\n node.addEventListener('submit', onSubmit);\n wcCleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n fireStep();\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n wcCleanups.push(() => io.disconnect());\n }\n });\n\n return () => {\n for (const c of wcCleanups) c();\n };\n }\n // --- End weighted composite ---\n\n const fireGoal = (): void => {\n if (goalFiredRef.current) return;\n goalFiredRef.current = true;\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId,\n eventType: 'goal_achieved',\n goalType: goalLabel,\n payload: { reward: 1.0 },\n });\n client.goal(goalLabel, { componentId: props.id, variantId }, 1.0, 0);\n };\n\n const subgoals: GoalConfig[] = goal.type === 'composite' ? goal.all : [goal];\n const remaining = new Set<number>(subgoals.map((_, i) => i));\n const checkComposite = (idx: number): void => {\n remaining.delete(idx);\n if (remaining.size === 0) fireGoal();\n };\n\n const cleanups: Array<() => void> = [];\n\n subgoals.forEach((sub, idx) => {\n if (sub.type === 'click') {\n const onClick = (e: MouseEvent): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else fireGoal();\n };\n node.addEventListener('click', onClick);\n cleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else fireGoal();\n };\n node.addEventListener('submit', onSubmit);\n cleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n if (goal.type === 'composite') checkComposite(idx);\n else fireGoal();\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n cleanups.push(() => io.disconnect());\n return;\n }\n });\n\n return () => {\n for (const c of cleanups) c();\n };\n }, [client, variantId, apiKey, props.id, goal, goalLabel]);\n\n // Decorative slots: empty in SSR HTML and until the client has mounted.\n if (props.clientOnly && (!mounted || !client)) return null;\n if (!variantId) return null;\n\n const jsxContent = props.variants[variantId] ?? null;\n const managedContent = jsxContent === null ? content : null;\n\n if (process?.env?.NODE_ENV !== 'production' && jsxContent === null && managedContent === null) {\n console.warn(\n `[sentient] <Adaptive id=\"${props.id}\"> was assigned variant \"${variantId}\" but no matching key exists in props.variants.` +\n ` If this is a dashboard-managed text variant, use <AdaptiveText id=\"${props.id}\"> instead.`,\n );\n }\n\n return (\n <div ref={containerRef} data-sentient-id={props.id} data-sentient-variant={variantId}>\n {jsxContent ?? managedContent}\n </div>\n );\n}\n\n/** Re-renders only when the chosen variant changes. */\nexport const Adaptive = memo(AdaptiveImpl, (prev, next) => {\n if (prev.id !== next.id) return false;\n if (JSON.stringify(prev.goal) !== JSON.stringify(next.goal)) return false;\n if (prev.microSignalGoals !== next.microSignalGoals) return false;\n if (prev.variants === next.variants) return true;\n const prevKeys = Object.keys(prev.variants);\n const nextKeys = Object.keys(next.variants);\n if (prevKeys.length !== nextKeys.length) return false;\n return prevKeys.every((k) => k in next.variants);\n});\n","import { useEffect, useRef, useState } from 'react';\nimport { type AssignResult } from '@sentientui/core';\nimport { useSentient, useInitialAssignments, useSessionSegment, useSsrFallback, useOnAssignment } from './provider.js';\nimport { subscribe, getWeights, type ComponentWeights } from './weights-store.js';\n\ndeclare global {\n interface Window { __sentient_overrides?: Record<string, string>; }\n}\n\nfunction getDevOverride(componentId: string): string | null {\n if (typeof window === 'undefined') return null;\n const global = window.__sentient_overrides?.[componentId];\n if (global) return global;\n try {\n const params = new URLSearchParams(window.location.search);\n for (const raw of params.getAll('sentient_variant')) {\n // sentient_variant=componentId:variantId (repeatable for multiple components)\n const sep = raw.indexOf(':');\n if (sep === -1) continue;\n if (raw.slice(0, sep) === componentId) return raw.slice(sep + 1);\n }\n } catch { /* non-browser env */ }\n return null;\n}\n\nexport type AssignmentState = {\n variantId: string | null;\n /** Populated when the assigned variant is a dashboard-managed text variant. */\n content: string | null;\n isLoading: boolean;\n};\n\nfunction pickFromWeights(weights: ComponentWeights, variantIds: string[]): string | null {\n let best: { variantId: string; avgReward: number } | null = null;\n for (const v of weights.variants) {\n if (!variantIds.includes(v.variantId)) continue;\n if (!best || v.avgReward > best.avgReward) {\n best = { variantId: v.variantId, avgReward: v.avgReward };\n }\n }\n return best?.variantId ?? null;\n}\n\n/**\n * Returns a sticky variant assignment for a component.\n *\n * First render reads the local SDK cache; if empty, falls back to a\n * deterministic default and asynchronously calls `/v1/assign`. The server\n * picks the actual variant via Thompson Sampling and the result replaces the fallback\n * on the next render. Subsequent paints read synchronously from cache —\n * no flicker, no loading state after first paint.\n */\nexport function useAssignment(componentId: string, variantIds: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): AssignmentState {\n const initialAssignments = useInitialAssignments();\n const ssrFallback = useSsrFallback();\n const client = useSentient();\n const segment = useSessionSegment();\n const onAssignment = useOnAssignment();\n const assignmentReportedRef = useRef<string | null>(null);\n\n // Dev override: URL param ?sentient_variant=componentId:variantId\n // or window.__sentient_overrides[componentId]. Short-circuits the bandit entirely.\n const devOverride = getDevOverride(componentId);\n const overrideVariant = devOverride && variantIds.includes(devOverride) ? devOverride : null;\n const overrideLoggedRef = useRef<string | null>(null);\n if (overrideVariant && overrideLoggedRef.current !== overrideVariant) {\n overrideLoggedRef.current = overrideVariant;\n console.info(`[sentient] override active: ${componentId} -> ${overrideVariant}`);\n }\n\n const initial = (() => {\n if (overrideVariant) {\n return { variantId: overrideVariant, content: null, isLoading: false };\n }\n // SSR / pre-hydration: no client yet. Use initialAssignments if provided so\n // the server and client first render agree on the same variant (no mismatch).\n if (!client) {\n const preloaded = initialAssignments[componentId];\n if (preloaded && variantIds.includes(preloaded)) {\n return { variantId: preloaded, content: null, isLoading: false };\n }\n if (ssrFallback === 'first' && variantIds.length > 0) {\n return { variantId: variantIds[0], content: null, isLoading: false };\n }\n return { variantId: null, content: null, isLoading: true };\n }\n const cached = client.getAssignment(componentId, segment);\n // Allow cached managed variants (content present) even if not in variantIds.\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n return { variantId: cached.variantId, content: cached.content ?? null, isLoading: false };\n }\n const weights = getWeights(componentId);\n if (weights) {\n const chosen = pickFromWeights(weights, variantIds);\n if (chosen) return { variantId: chosen, content: null, isLoading: false };\n }\n return { variantId: variantIds[0] ?? null, content: null, isLoading: false };\n })();\n\n const [state, setState] = useState<AssignmentState>(initial);\n\n // Helper: call onAssignment at most once per resolved variant.\n const reportAssignment = (variantId: string): void => {\n if (!onAssignment) return;\n if (assignmentReportedRef.current === variantId) return;\n assignmentReportedRef.current = variantId;\n onAssignment(componentId, variantId);\n };\n\n // As soon as the client is ready, unblock the UI immediately with variantIds[0]\n // (or a cached value) so the component never stays invisible while assign is\n // in-flight. The async assign call below then swaps to the bandit-chosen variant.\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n const cached = client.getAssignment(componentId, segment);\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n setState({ variantId: cached.variantId, content: cached.content ?? null, isLoading: false });\n reportAssignment(cached.variantId);\n return;\n }\n setState((prev) => prev.variantId ? prev : { variantId: variantIds[0] ?? null, content: null, isLoading: false });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n // Ask the server for a real assignment when we have a client but no cached one.\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n const cached = client.getAssignment(componentId, segment);\n if (cached && variantIds.includes(cached.variantId)) return;\n\n let cancelled = false;\n void client.assign(componentId, variantIds, agentData, agentDataByVariant).then((result: AssignResult | null) => {\n if (cancelled) return;\n if (!result) return;\n // Allow the result if it's a known code variant OR a managed text variant (has content).\n if (!variantIds.includes(result.variantId) && !result.content) return;\n setState({ variantId: result.variantId, content: result.content ?? null, isLoading: false });\n reportAssignment(result.variantId);\n });\n return () => { cancelled = true; };\n // variantIds intentionally excluded — changing variants mid-mount is unsupported\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n // Live weight updates from the dashboard SSE stream (when wired).\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n return subscribe(componentId, (weights) => {\n const cached = client.getAssignment(componentId, segment);\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n setState({ variantId: cached.variantId, content: cached.content ?? null, isLoading: false });\n return;\n }\n const chosen = pickFromWeights(weights, variantIds);\n if (chosen) setState({ variantId: chosen, content: null, isLoading: false });\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n if (overrideVariant) {\n return { variantId: overrideVariant, content: null, isLoading: false };\n }\n\n return state;\n}\n","'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { useEffect, useRef, useState } from 'react';\nimport type { AssignResult } from '@sentientui/core';\nimport { useSentient, useAdaptiveApiKey, useOnAssignment, useSessionSegment } from './provider.js';\n\nexport type AdaptiveTextProps = {\n id: string;\n default: string;\n component?: keyof JSX.IntrinsicElements;\n className?: string;\n};\n\nexport function AdaptiveText({\n id,\n default: defaultText,\n component: Tag = 'span',\n className,\n}: AdaptiveTextProps) {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const onAssignment = useOnAssignment();\n const segment = useSessionSegment();\n const trackedRef = useRef<string | null>(null);\n\n // Seed from cache synchronously so remounts don't flash back to defaultText.\n const [text, setText] = useState<string | null>(() =>\n client?.getAssignment(id, segment)?.content ?? null\n );\n const [variantId, setVariantId] = useState<string | null>(() =>\n client?.getAssignment(id, segment)?.variantId ?? null\n );\n\n useEffect(() => {\n if (!client) return;\n // Skip if content already cached; assign() re-checks internally but this avoids the async round-trip on remount.\n if (client.getAssignment(id, segment)?.content !== undefined) return;\n\n let cancelled = false;\n void client.assign(id).then((result: AssignResult | null) => {\n if (cancelled) return;\n if (!result) {\n if (process?.env?.NODE_ENV !== 'production') {\n console.warn(`[sentient] <AdaptiveText id=\"${id}\"> assignment failed — showing default text.`);\n }\n return;\n }\n setVariantId(result.variantId);\n if (result.content) setText(result.content);\n });\n return () => {\n cancelled = true;\n };\n }, [client, id, segment]);\n\n useEffect(() => {\n if (!client || !variantId || !apiKey) return;\n if (trackedRef.current === variantId) return;\n trackedRef.current = variantId;\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'variant_assigned',\n payload: {},\n });\n onAssignment?.(id, variantId);\n }, [client, variantId, apiKey, id, onAssignment]);\n\n return <Tag className={className}>{text ?? defaultText}</Tag>;\n}\n","import { useCallback } from 'react';\nimport type { ComponentGoalOptions } from '@sentientui/core';\nimport { useSentient } from './provider.js';\n\nexport type FireGoal = (goalType: string, opts?: ComponentGoalOptions) => void;\n\n/**\n * Returns a `fireGoal(goalType, opts?)` callback that records a conversion\n * attributed to the variant currently served for `componentId` — so it shows\n * up in the per-variant CVR funnel with no manual variantId/projectId plumbing.\n *\n * The served variant is resolved from the SDK's assignment cache (the same one\n * `<Adaptive id={componentId}>` populates), so render that component before\n * firing. Use this for imperative handlers (click, form submit, custom events);\n * for purely declarative goals prefer `<Adaptive goal={...}>`.\n *\n * @example\n * const fireContact = useAdaptiveGoal('hero_headline');\n * <button onClick={() => fireContact('hero_contact', { metadata: { method } })}>Call</button>\n */\nexport function useAdaptiveGoal(componentId: string): FireGoal {\n const client = useSentient();\n return useCallback<FireGoal>(\n (goalType, opts) => {\n client?.componentGoal(componentId, goalType, opts);\n },\n [client, componentId],\n );\n}\n","/** @deprecated Use `useSessionSegment()` from the provider, or `deriveSessionSegment` from `@sentientui/core`. */\nexport { deriveSessionSegment as detectSegment } from '@sentientui/core';\n"],"mappings":";+VAIA,OAAS,iBAAAA,GAAe,cAAAC,EAAY,aAAAC,GAAW,WAAAC,GAAS,YAAAC,OAAgC,QACxF,OACE,qBAAAC,GACA,uBAAAC,GACA,QAAAC,OAGK,mBCKP,IAAMC,EAAQ,IAAI,IACZC,EAAY,IAAI,IAMf,SAASC,EAAUC,EAAqBC,EAA0B,CACvE,IAAIC,EAAMJ,EAAU,IAAIE,CAAW,EACnC,OAAKE,IACHA,EAAM,IAAI,IACVJ,EAAU,IAAIE,EAAaE,CAAG,GAEhCA,EAAI,IAAID,CAAE,EACH,IAAM,CACXC,EAAK,OAAOD,CAAE,EACVC,EAAK,OAAS,GAAGJ,EAAU,OAAOE,CAAW,CACnD,CACF,CAMO,SAASG,EAAOH,EAAqBI,EAAiC,CAC3EP,EAAM,IAAIG,EAAaI,CAAO,EAC9B,IAAMF,EAAMJ,EAAU,IAAIE,CAAW,EACrC,GAAKE,EACL,QAAWD,KAAMC,EACf,GAAI,CACFD,EAAGG,CAAO,CACZ,OAAQC,EAAA,CAER,CAEJ,CAKO,SAASC,EAAWN,EAA8C,CAxDzE,IAAAO,EAyDE,OAAOA,EAAAV,EAAM,IAAIG,CAAW,IAArB,KAAAO,EAA0B,IACnC,CDuKI,cAAAC,OAAA,oBA5MJ,SAASC,IAA+B,CArBxC,IAAAC,EAAAC,EAsBE,GAAI,OAAO,QAAW,YAAa,MAAO,iBAC1C,GAAI,CACF,IAAMC,EAASC,IAAkBH,EAAA,UAAU,YAAV,KAAAA,EAAuB,EAAE,EACpDI,EAASC,IAAoBJ,EAAA,SAAS,WAAT,KAAAA,EAAqB,GAAI,OAAO,SAAS,MAAM,EAClF,MAAO,GAAGC,CAAM,IAAIE,CAAM,EAC5B,OAAQE,EAAA,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f,EAAQe,EAAWb,EAAQN,EAAIQ,CAAY,CAAC,EAEzCV,GAACI,EAAA,CAAI,UAAWC,EAAY,SAAAW,GAAA,KAAAA,EAAQb,EAAY,CACzD,CCxEA,OAAS,eAAAuB,OAAmB,QAoBrB,SAASC,GAAgBC,EAA+B,CAC7D,IAAMC,EAASC,EAAY,EAC3B,OAAOC,GACL,CAACC,EAAUC,IAAS,CAClBJ,GAAA,MAAAA,EAAQ,cAAcD,EAAaI,EAAUC,EAC/C,EACA,CAACJ,EAAQD,CAAW,CACtB,CACF,CC3BA,OAAiC,wBAAxBM,OAA6C","names":["createContext","useContext","useEffect","useMemo","useState","detectDeviceClass","detectTrafficSource","init","store","listeners","subscribe","componentId","cb","set","update","weights","e","getWeights","_a","jsx","deriveDefaultSegment","_a","_b","device","detectDeviceClass","source","detectTrafficSource","e","AdaptiveContext","createContext","AdaptiveProvider","props","client","setClient","useState","sessionSegment","useEffect","prev","c","init","cancelled","poll","entries","entry","weights","v","update","timerId","ssrFallback","value","useMemo","useSentient","useContext","useAdaptiveApiKey","useInitialAssignments","useContext","AdaptiveContext","useSessionSegment","useSsrFallback","useOnAssignment","useLayoutOrder","memo","useEffect","useMemo","useRef","useState","attachMicroSignalDetectors","useEffect","useRef","useState","getDevOverride","componentId","_a","global","params","raw","sep","e","pickFromWeights","weights","variantIds","best","v","useAssignment","agentData","agentDataByVariant","initialAssignments","useInitialAssignments","ssrFallback","useSsrFallback","client","useSentient","segment","useSessionSegment","onAssignment","useOnAssignment","assignmentReportedRef","useRef","devOverride","overrideVariant","overrideLoggedRef","initial","_b","preloaded","cached","getWeights","chosen","state","setState","useState","reportAssignment","variantId","useEffect","prev","cancelled","result","subscribe","jsx","normalize","goal","PREVIEW_HTML_MAX_CHARS","shouldSendPreviewHtml","componentId","variantId","key","e","isClickableTarget","el","tag","findClickable","start","container","selector","cursor","AdaptiveImpl","props","_a","_b","client","useSentient","apiKey","useAdaptiveApiKey","variantIds","useMemo","content","useAssignment","containerRef","useRef","mounted","setMounted","useState","useEffect","goalFiredRef","microGoalFiredRef","assignTrackedRef","goalKey","goalLabel","rawHtml","includePreview","node","timerId","hoverStart","onEnter","onLeave","assignedAt","attachMicroSignalDetectors","signalType","extra","_c","__spreadValues","mapping","name","weight","stepIndex","firedSteps","wcCleanups","sub","stepName","stepWeight","idx","fireStep","onClick","target","onSubmit","threshold","io","entries","entry","c","fireGoal","subgoals","remaining","_","i","checkComposite","cleanups","jsxContent","managedContent","Adaptive","memo","prev","next","prevKeys","nextKeys","k","useEffect","useRef","useState","jsx","AdaptiveText","id","defaultText","Tag","className","client","useSentient","apiKey","useAdaptiveApiKey","onAssignment","useOnAssignment","segment","useSessionSegment","trackedRef","useRef","text","setText","useState","_a","_b","variantId","setVariantId","useEffect","cancelled","result","useCallback","useAdaptiveGoal","componentId","client","useSentient","useCallback","goalType","opts","deriveSessionSegment"]}
|
|
1
|
+
{"version":3,"sources":["../src/provider.tsx","../src/weights-store.ts","../src/preview-mode.ts","../src/adaptive.tsx","../src/use-assignment.ts","../src/devtools-registry.ts","../src/adaptive-text.tsx","../src/use-adaptive-goal.ts","../src/segment.ts","../src/agent-feed.ts"],"sourcesContent":["'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';\nimport {\n detectDeviceClass,\n detectTrafficSource,\n init,\n type SentientClient,\n type SentientConfig,\n} from '@sentientui/core';\nimport { update as updateWeightsStore, type ComponentWeights } from './weights-store.js';\nimport { getPreviewMode, subscribePreview, createPreviewClient } from './preview-mode.js';\n\n/**\n * Mirrors the segment derivation inside core `init()` so the cache key used\n * by `useAssignment` always matches the key `assign()` writes under. Before\n * this, the context defaulted to 'desktop:direct' while core used the\n * detected segment — a systematic cache miss for every integration that\n * didn't pass `sessionSegment` explicitly.\n */\nfunction deriveDefaultSegment(): string {\n if (typeof window === 'undefined') return 'desktop:direct';\n try {\n const device = detectDeviceClass(navigator.userAgent ?? '');\n const source = detectTrafficSource(document.referrer ?? '', window.location.origin);\n return `${device}:${source}`;\n } catch {\n return 'desktop:direct';\n }\n}\n\n/** How to render adaptive slots during SSR when assignments are not preloaded. */\nexport type SsrFallback = 'first' | 'none';\n\ntype AdaptiveContextValue = {\n client: SentientClient | null;\n // The publishable API key (pk_…). Historically named `projectId` because the\n // API uses it as the project identifier on the wire, but it is the API key,\n // not the project UUID. Field renamed for clarity.\n apiKey: string;\n initialAssignments: Record<string, string>;\n sessionSegment: string;\n ssrFallback: SsrFallback;\n onAssignment: ((componentId: string, variantId: string) => void) | undefined;\n initialLayoutOrder: string[] | null;\n};\n\nconst AdaptiveContext = createContext<AdaptiveContextValue>({\n client: null,\n apiKey: '',\n initialAssignments: {},\n sessionSegment: 'desktop:direct',\n ssrFallback: 'first',\n onAssignment: undefined,\n initialLayoutOrder: null,\n});\n\nexport type AdaptiveProviderProps = {\n apiKey: string;\n context: SentientConfig['context'];\n debug?: boolean;\n /**\n * SSR-preloaded assignments from `preloadAssignments()` / `loadAdaptiveAssignments()`.\n * Passed through to `useAssignment` as synchronous initial state so crawlers and\n * the first paint see real content (recommended for SEO).\n */\n initialAssignments?: Record<string, string>;\n /**\n * Bandit segment from SSR (`device:source`). Keeps cache, assign, and worker\n * weights on one row — must match `loadAdaptiveAssignments` / session upsert.\n */\n sessionSegment?: string;\n /**\n * When no `initialAssignments` exist for a component, `'first'` renders\n * `variantIds[0]` in server HTML (safe default for SEO). Use `'none'` only for\n * decorative slots marked `clientOnly`.\n * @default 'first'\n */\n ssrFallback?: SsrFallback;\n /**\n * Consent gate. When `false` the SDK is not initialised and no events are\n * sent. Flip to `true` (e.g. after the user accepts the cookie banner) to\n * initialise and begin tracking.\n */\n consent?: boolean;\n /**\n * Behavior before consent is granted. Pass `'statistical_winner'` to serve the\n * best-performing variant via `GET /v1/winner` with zero tracking while the\n * consent banner is showing. Requires `consent: false`.\n * @see SentientConfig.preConsentBehavior\n */\n preConsentBehavior?: 'statistical_winner' | 'control';\n /**\n * Honor the browser's Do Not Track signal. Defaults to `true`: when DNT is\n * enabled the SDK sets no cookies and sends no tracking data (overriding\n * `consent: true`). Set `false` to make your own consent gate authoritative.\n * @see SentientConfig.respectDoNotTrack\n */\n respectDoNotTrack?: boolean;\n /**\n * Called once per component the first time a variant is resolved for that\n * component in this session. Use to forward assignments to your own analytics\n * (Mixpanel, PostHog, Segment, etc.) without having to wrap `useAssignment`.\n */\n onAssignment?: (componentId: string, variantId: string) => void;\n /**\n * SSR-preloaded section order from `loadAdaptiveDecision()`.\n * Pass the `layoutOrder` field from `DecideResult`. When set,\n * `useLayoutOrder()` returns this on first render so there is no layout shift.\n */\n initialLayoutOrder?: string[] | null;\n /**\n * Session ID generated during SSR (the `sessionId` field returned by\n * `loadAdaptiveAssignments` / `loadAdaptiveDecision`). When provided and no\n * existing session cookie or localStorage entry is found, the client adopts\n * this ID so events and goals are attributed to the same session the server\n * used for variant assignment.\n */\n ssrSessionId?: string;\n /**\n * ISO 3166-1 alpha-2 country code. Pass the value of the `CF-IPCountry`\n * header from your Next.js server component to populate country on landing\n * sessions without client-side geo lookup.\n */\n country?: string;\n /**\n * Enable DOM graph scanning + page-structure sync. When `true`, the provider\n * dynamically loads `@sentientui/core/graph` and uses its graph-capable\n * `init()` for the single client, so the SDK scans your page structure and\n * syncs it to power the dashboard graph page. Left off (default), the lean\n * bundle is used and the graph entry is never loaded.\n */\n enableGraph?: boolean;\n children: ReactNode;\n};\n\n/**\n * Initialises the Sentient core SDK in a useEffect (SSR-safe) and exposes the\n * client via React context. Re-initialises when `consent` changes.\n */\nexport function AdaptiveProvider(props: AdaptiveProviderProps): JSX.Element {\n const [client, setClient] = useState<SentientClient | null>(null);\n // Derived once per mount: identical to what core init() computes, so cache\n // reads (context segment) and cache writes (core segment) always agree.\n const [sessionSegment] = useState(() => props.sessionSegment ?? deriveDefaultSegment());\n // Devtools preview: when on, expose an event-suppressing client so previewing\n // variants/personas writes nothing. Off by default (inert in production).\n const [previewOn, setPreviewOn] = useState(getPreviewMode());\n useEffect(() => subscribePreview(() => setPreviewOn(getPreviewMode())), []);\n\n useEffect(() => {\n // When consent is explicitly false with no preConsentBehavior, tear down any existing client.\n if (props.consent === false && !props.preConsentBehavior) {\n setClient((prev: SentientClient | null) => {\n prev?.destroy();\n return null;\n });\n return;\n }\n\n const config = {\n apiKey: props.apiKey,\n context: props.context,\n debug: props.debug,\n initialAssignments: props.initialAssignments,\n sessionSegment,\n consent: props.consent,\n preConsentBehavior: props.preConsentBehavior,\n respectDoNotTrack: props.respectDoNotTrack,\n ssrSessionId: props.ssrSessionId,\n country: props.country,\n };\n\n // Track the client created by this effect run so cleanup destroys exactly\n // the right one, and so a late-resolving dynamic import can bail if the\n // effect was already torn down (unmount / consent change).\n let cancelled = false;\n let created: SentientClient | null = null;\n\n if (props.enableGraph) {\n // Load the graph entry only when asked — keeps the DOM scanner out of the\n // lean bundle. The provider still creates ONE client (graph-capable).\n void import('@sentientui/core/graph').then(({ init: initGraph }) => {\n if (cancelled) return;\n created = initGraph({ ...config, graph: true });\n setClient(created);\n });\n } else {\n created = init(config);\n setClient(created);\n }\n\n return () => {\n cancelled = true;\n created?.destroy();\n };\n // Re-init when consent changes. Other props (incl. enableGraph) are\n // intentionally stable for a session.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.consent]);\n\n // Poll /v1/weights every 60 s so long-lived sessions see updated bandit weights\n // without a page reload. useAssignment subscribers react via weights-store.\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n const poll = async (): Promise<void> => {\n if (cancelled) return;\n let entries;\n try {\n entries = await client.fetchWeights();\n } catch {\n // Network/transient error: skip this cycle and retry on the next\n // interval. Swallowed deliberately so a failed poll never surfaces as\n // an unhandled rejection.\n return;\n }\n if (cancelled) return;\n for (const entry of entries) {\n const weights: ComponentWeights = {\n componentId: entry.componentId,\n updatedAt: entry.updatedAt,\n variants: entry.variants.map((v) => ({\n variantId: v.variantId,\n pulls: v.pulls,\n avgReward: v.avgReward ?? 0,\n })),\n };\n updateWeightsStore(entry.componentId, weights);\n }\n };\n void poll();\n const timerId = setInterval(() => void poll(), 60_000);\n return () => {\n cancelled = true;\n clearInterval(timerId);\n };\n }, [client]);\n\n const ssrFallback = props.ssrFallback ?? 'first';\n\n // The client exposed to consumers — wrapped to suppress events while previewing.\n const exposedClient = useMemo(\n () => (client && previewOn ? createPreviewClient(client) : client),\n [client, previewOn],\n );\n\n // Memoized so unrelated parent re-renders don't cascade through every\n // useSentient / useAssignment consumer via a fresh context object.\n const value = useMemo<AdaptiveContextValue>(\n () => ({\n client: exposedClient,\n apiKey: props.apiKey,\n initialAssignments: props.initialAssignments ?? {},\n sessionSegment,\n ssrFallback,\n onAssignment: props.onAssignment,\n initialLayoutOrder: props.initialLayoutOrder ?? null,\n }),\n [\n exposedClient,\n props.apiKey,\n props.initialAssignments,\n sessionSegment,\n ssrFallback,\n props.onAssignment,\n props.initialLayoutOrder,\n ],\n );\n\n return (\n <AdaptiveContext.Provider value={value}>\n {props.children}\n </AdaptiveContext.Provider>\n );\n}\n\n/**\n * Returns the SentientClient, or null until the provider has finished\n * initialising on the client.\n */\nexport function useSentient(): SentientClient | null {\n return useContext(AdaptiveContext).client;\n}\n\n/** Internal: publishable API key carried alongside the client. */\nexport function useAdaptiveApiKey(): string {\n return useContext(AdaptiveContext).apiKey;\n}\n\n/**\n * @deprecated Renamed to `useAdaptiveApiKey`. Kept as an alias so external\n * imports from earlier versions of this package keep working. Will be removed\n * in 1.0.0.\n */\nlet warnedProjectIdAlias = false;\nexport function useAdaptiveProjectId(): string {\n if (\n !warnedProjectIdAlias &&\n typeof process !== 'undefined' &&\n process.env?.NODE_ENV !== 'production'\n ) {\n warnedProjectIdAlias = true;\n console.warn(\n '[@sentientui/react] useAdaptiveProjectId is deprecated; use useAdaptiveApiKey. Will be removed in 1.0.0.',\n );\n }\n return useAdaptiveApiKey();\n}\n\n/** Internal: SSR-preloaded assignments for hydration-safe first render. */\nexport function useInitialAssignments(): Record<string, string> {\n return useContext(AdaptiveContext).initialAssignments;\n}\n\n/** Internal: bandit segment aligned with SSR session upsert. */\nexport function useSessionSegment(): string {\n return useContext(AdaptiveContext).sessionSegment;\n}\n\n/** Internal: SSR fallback strategy when a slot has no preloaded assignment. */\nexport function useSsrFallback(): SsrFallback {\n return useContext(AdaptiveContext).ssrFallback;\n}\n\n/** Internal: forwarding hook for consumer analytics integration. */\nexport function useOnAssignment(): ((componentId: string, variantId: string) => void) | undefined {\n return useContext(AdaptiveContext).onAssignment;\n}\n\n/**\n * Returns the persona-specific section order from SSR, or null when no\n * sections were declared on AdaptiveRoot or reliability is below threshold.\n */\nexport function useLayoutOrder(): string[] | null {\n return useContext(AdaptiveContext).initialLayoutOrder;\n}\n","/** Per-component weights store with isolated subscriptions. */\n\nexport type VariantWeight = {\n variantId: string;\n pulls: number;\n avgReward: number;\n};\n\nexport type ComponentWeights = {\n componentId: string;\n variants: VariantWeight[];\n updatedAt: number;\n};\n\ntype Listener = (weights: ComponentWeights) => void;\n\nconst store = new Map<string, ComponentWeights>();\nconst listeners = new Map<string, Set<Listener>>();\n\n/**\n * Subscribes a listener to a single component. Returns an unsubscribe function.\n * Updates to other components never trigger this listener.\n */\nexport function subscribe(componentId: string, cb: Listener): () => void {\n let set = listeners.get(componentId);\n if (!set) {\n set = new Set();\n listeners.set(componentId, set);\n }\n set.add(cb);\n return () => {\n set!.delete(cb);\n if (set!.size === 0) listeners.delete(componentId);\n };\n}\n\n/**\n * Replaces the weights for a component and notifies only that component's\n * subscribers.\n */\nexport function update(componentId: string, weights: ComponentWeights): void {\n store.set(componentId, weights);\n const set = listeners.get(componentId);\n if (!set) return;\n for (const cb of set) {\n try {\n cb(weights);\n } catch {\n /* never throw to other listeners */\n }\n }\n}\n\n/**\n * Returns the latest known weights for a component, or null if none seen.\n */\nexport function getWeights(componentId: string): ComponentWeights | null {\n return store.get(componentId) ?? null;\n}\n\n/** Test-only: wipe the entire store. */\nexport function _resetWeightsStore(): void {\n store.clear();\n listeners.clear();\n}\n","import type { SentientClient } from '@sentientui/core';\n\nlet previewOn = false;\nconst listeners = new Set<() => void>();\n\nexport function setPreviewMode(on: boolean): void {\n if (previewOn === on) return;\n previewOn = on;\n for (const fn of listeners) fn();\n}\n\nexport function getPreviewMode(): boolean {\n return previewOn;\n}\n\nexport function subscribePreview(fn: () => void): () => void {\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/**\n * Wraps a client so it writes nothing: reads pass through, all emitters no-op.\n * Used while previewing variants/personas so no `variant_assigned`, goal, or\n * session events are sent.\n */\nexport function createPreviewClient(inner: SentientClient): SentientClient {\n return {\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n fetchWeights: () => Promise.resolve([]),\n getAssignment: (componentId, segment) => inner.getAssignment(componentId, segment),\n assign: (componentId, variantIds, agentData, agentDataByVariant) =>\n inner.assign(componentId, variantIds, agentData, agentDataByVariant),\n getGraph: () => inner.getGraph(),\n destroy: () => inner.destroy(),\n };\n}\n","'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { memo, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport { attachMicroSignalDetectors, type MicroSignalType } from '@sentientui/core';\nimport { useAdaptiveApiKey, useSentient } from './provider.js';\nimport { useAssignment } from './use-assignment.js';\nimport { registerComponent } from './devtools-registry.js';\n\nexport type ScrollDepthGoal = { type: 'scroll_depth'; threshold: number };\nexport type ClickGoal = { type: 'click'; selector?: string };\nexport type FormSubmitGoal = { type: 'form_submit' };\nexport type CompositeGoal = { type: 'composite'; all: GoalConfig[] };\nexport type WeightedStep = { goal: GoalConfig; name: string; weight: number };\nexport type WeightedCompositeGoal = { type: 'weighted_composite'; steps: WeightedStep[] };\nexport type GoalConfig = ScrollDepthGoal | ClickGoal | FormSubmitGoal | CompositeGoal | WeightedCompositeGoal;\n\n/** Maps a detected micro-signal to a named session goal (`client.goal`). */\nexport type MicroSignalGoalConfig = string | { name: string; weight?: number; stepIndex?: number };\nexport type MicroSignalGoals = Partial<Record<MicroSignalType, MicroSignalGoalConfig>>;\n\nexport type AdaptiveProps = {\n id: string;\n variants: Record<string, ReactNode>;\n goal: string | GoalConfig;\n /**\n * When a passive micro-signal fires on this component, also record a named goal.\n * Use for inferred goals surfaced in the dashboard (e.g. rage_click → 'confused_by_hero').\n */\n microSignalGoals?: MicroSignalGoals;\n /**\n * When true, renders nothing during SSR and before client hydration.\n * Use when you cannot pass `initialAssignments` and prefer a blank slot over\n * a hydration mismatch. Tradeoff: minor CLS on first paint.\n */\n clientOnly?: boolean;\n /**\n * Variant-specific structured data for AI agent consumption via /sentient.json and\n * GET /v1/agent/layout. Keyed by variant ID — only the assigned variant's entry is stored,\n * so agents see only the content currently being served to visitors.\n *\n * Prefer this over `agentData` when variants have meaningfully different content.\n */\n agentDataByVariant?: Record<string, unknown>;\n /** @deprecated Use agentDataByVariant for variant-specific content. Stored as-is for the assigned variant. */\n agentData?: unknown;\n};\n\nfunction normalize(goal: string | GoalConfig): GoalConfig {\n if (typeof goal === 'string') return { type: 'click' };\n return goal;\n}\n\nconst PREVIEW_HTML_MAX_CHARS = 30_000;\n\n/**\n * previewHtml is the largest payload the SDK sends (up to 30 KB). The server\n * keeps the first-seen preview per (component, variant), so re-sending it on\n * every mount/navigation is pure waste — send it once per browser session.\n */\nfunction shouldSendPreviewHtml(componentId: string, variantId: string): boolean {\n try {\n const key = `_snt_pv_${componentId}_${variantId}`;\n if (sessionStorage.getItem(key)) return false;\n sessionStorage.setItem(key, '1');\n return true;\n } catch {\n // Storage unavailable (private mode, quota) — keep prior behavior.\n return true;\n }\n}\n\nfunction isClickableTarget(el: EventTarget | null): boolean {\n if (!(el instanceof Element)) return false;\n const tag = el.tagName.toLowerCase();\n if (tag === 'a' || tag === 'button') return true;\n const role = el.getAttribute('role');\n return role === 'button';\n}\n\nfunction findClickable(start: Element, container: Element, selector?: string): boolean {\n if (selector) {\n try {\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (cursor.matches(selector)) return true;\n cursor = cursor.parentElement;\n }\n } catch {\n // Invalid CSS selector — treat as no match rather than breaking all click handlers.\n }\n return false;\n }\n let cursor: Element | null = start;\n while (cursor && cursor !== container) {\n if (isClickableTarget(cursor)) return true;\n cursor = cursor.parentElement;\n }\n return false;\n}\n\nfunction AdaptiveImpl(props: AdaptiveProps): JSX.Element | null {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const variantIds = useMemo(() => Object.keys(props.variants), [props.variants]);\n const { variantId, content } = useAssignment(props.id, variantIds, props.agentData, props.agentDataByVariant);\n const containerRef = useRef<HTMLDivElement>(null);\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => { setMounted(true); }, []);\n const goalFiredRef = useRef(false);\n const microGoalFiredRef = useRef<Set<MicroSignalType>>(new Set());\n const assignTrackedRef = useRef<string | null>(null);\n const goalKey = typeof props.goal === 'string' ? props.goal : JSON.stringify(props.goal);\n const goal = useMemo(() => normalize(props.goal), [goalKey]);\n const goalLabel = typeof props.goal === 'string' ? props.goal : goal.type;\n\n // Register with the devtools registry so the dev widget can list this\n // component + its variants. Inert in production (registry has no UI); the\n // cleanup unregisters on unmount.\n useEffect(() => registerComponent({ id: props.id, variantIds, goal: goalLabel }), [props.id, variantIds, goalLabel]);\n\n // Track variant_assigned exactly once per (component, variant) mount.\n // Captures innerHTML as previewHtml so the dashboard can render a live preview\n // without requiring manual registry calls. First-seen wins on the server.\n // `mounted` is in deps so the effect re-runs after clientOnly components hydrate\n // and their container div is actually in the DOM.\n useEffect(() => {\n if (!client || !variantId || !apiKey) return;\n if (assignTrackedRef.current === variantId) return;\n const rawHtml = containerRef.current?.innerHTML ?? '';\n // Wait until content is in the DOM; will re-run when mounted changes.\n if (!rawHtml) return;\n assignTrackedRef.current = variantId;\n const includePreview = rawHtml !== '' && shouldSendPreviewHtml(props.id, variantId);\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId,\n eventType: 'variant_assigned',\n payload: includePreview ? { previewHtml: rawHtml.slice(0, PREVIEW_HTML_MAX_CHARS) } : {},\n });\n }, [client, variantId, apiKey, props.id, mounted, content]);\n\n // Reset goal latch when variant or goal changes.\n useEffect(() => {\n goalFiredRef.current = false;\n microGoalFiredRef.current = new Set();\n }, [variantId, goal]);\n\n // Emit cursor_signal after 800 ms of continuous hover.\n useEffect(() => {\n if (!client || !variantId) return;\n const node = containerRef.current;\n if (!node) return;\n\n let timerId: ReturnType<typeof setTimeout> | null = null;\n let hoverStart = 0;\n\n const onEnter = (): void => {\n hoverStart = Date.now();\n timerId = setTimeout(() => {\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId: variantId!,\n eventType: 'cursor_signal',\n payload: { hoverDuration: Date.now() - hoverStart },\n });\n timerId = null;\n }, 800);\n };\n\n const onLeave = (): void => {\n if (timerId !== null) {\n clearTimeout(timerId);\n timerId = null;\n }\n };\n\n node.addEventListener('mouseenter', onEnter);\n node.addEventListener('mouseleave', onLeave);\n return () => {\n node.removeEventListener('mouseenter', onEnter);\n node.removeEventListener('mouseleave', onLeave);\n if (timerId !== null) clearTimeout(timerId);\n };\n }, [client, variantId, apiKey, props.id]);\n\n // Attach micro-signal detectors passively — rage click, text copy, scroll hesitation, tab loss.\n useEffect(() => {\n if (!client || !variantId) return;\n const node = containerRef.current;\n if (!node) return;\n const assignedAt = Date.now();\n return attachMicroSignalDetectors(\n (signalType, extra = {}) => {\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId: variantId!,\n eventType: 'micro_signal',\n payload: { signalType, ...extra },\n });\n\n const mapping = props.microSignalGoals?.[signalType];\n if (!mapping || microGoalFiredRef.current.has(signalType)) return;\n microGoalFiredRef.current.add(signalType);\n const name = typeof mapping === 'string' ? mapping : mapping.name;\n const weight = typeof mapping === 'string' ? 1.0 : (mapping.weight ?? 1.0);\n const stepIndex = typeof mapping === 'string' ? 0 : (mapping.stepIndex ?? 0);\n client.goal(name, { signalType, ...extra }, weight, stepIndex);\n },\n node,\n assignedAt,\n );\n }, [client, variantId, apiKey, props.id, props.microSignalGoals]);\n\n // Attach goal tracking.\n useEffect(() => {\n if (!client || !variantId) return;\n const node = containerRef.current;\n if (!node) return;\n\n // --- Weighted composite: each step fires independently as it completes ---\n if (goal.type === 'weighted_composite') {\n const firedSteps = new Set<number>();\n const wcCleanups: Array<() => void> = [];\n\n goal.steps.forEach(({ goal: sub, name: stepName, weight: stepWeight }, idx) => {\n const fireStep = (): void => {\n if (firedSteps.has(idx)) return;\n firedSteps.add(idx);\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId: variantId!,\n eventType: 'goal_achieved',\n goalType: stepName,\n payload: { reward: stepWeight },\n });\n client.goal(stepName, {}, stepWeight, idx);\n };\n\n if (sub.type === 'click') {\n const onClick = (e: MouseEvent): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n fireStep();\n };\n node.addEventListener('click', onClick);\n wcCleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n fireStep();\n };\n node.addEventListener('submit', onSubmit);\n wcCleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n fireStep();\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n wcCleanups.push(() => io.disconnect());\n }\n });\n\n return () => {\n for (const c of wcCleanups) c();\n };\n }\n // --- End weighted composite ---\n\n const fireGoal = (): void => {\n if (goalFiredRef.current) return;\n goalFiredRef.current = true;\n client.track({\n projectId: apiKey,\n componentId: props.id,\n variantId,\n eventType: 'goal_achieved',\n goalType: goalLabel,\n payload: { reward: 1.0 },\n });\n client.goal(goalLabel, { componentId: props.id, variantId }, 1.0, 0);\n };\n\n const subgoals: GoalConfig[] = goal.type === 'composite' ? goal.all : [goal];\n const remaining = new Set<number>(subgoals.map((_, i) => i));\n const checkComposite = (idx: number): void => {\n remaining.delete(idx);\n if (remaining.size === 0) fireGoal();\n };\n\n const cleanups: Array<() => void> = [];\n\n subgoals.forEach((sub, idx) => {\n if (sub.type === 'click') {\n const onClick = (e: MouseEvent): void => {\n const target = e.target;\n if (!(target instanceof Element)) return;\n if (!findClickable(target, node, sub.selector)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else fireGoal();\n };\n node.addEventListener('click', onClick);\n cleanups.push(() => node.removeEventListener('click', onClick));\n return;\n }\n\n if (sub.type === 'form_submit') {\n const onSubmit = (e: Event): void => {\n if (!(e.target instanceof HTMLFormElement)) return;\n if (!node.contains(e.target)) return;\n if (goal.type === 'composite') checkComposite(idx);\n else fireGoal();\n };\n node.addEventListener('submit', onSubmit);\n cleanups.push(() => node.removeEventListener('submit', onSubmit));\n return;\n }\n\n if (sub.type === 'scroll_depth') {\n const threshold = Math.max(0, Math.min(1, sub.threshold));\n const io = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.intersectionRatio >= threshold) {\n if (goal.type === 'composite') checkComposite(idx);\n else fireGoal();\n io.disconnect();\n break;\n }\n }\n },\n { threshold: [threshold] },\n );\n io.observe(node);\n cleanups.push(() => io.disconnect());\n return;\n }\n });\n\n return () => {\n for (const c of cleanups) c();\n };\n }, [client, variantId, apiKey, props.id, goal, goalLabel]);\n\n // Decorative slots: empty in SSR HTML and until the client has mounted.\n if (props.clientOnly && (!mounted || !client)) return null;\n if (!variantId) return null;\n\n const jsxContent = props.variants[variantId] ?? null;\n const managedContent = jsxContent === null ? content : null;\n\n if (process?.env?.NODE_ENV !== 'production' && jsxContent === null && managedContent === null) {\n console.warn(\n `[sentient] <Adaptive id=\"${props.id}\"> was assigned variant \"${variantId}\" but no matching key exists in props.variants.` +\n ` If this is a dashboard-managed text variant, use <AdaptiveText id=\"${props.id}\"> instead.`,\n );\n }\n\n return (\n <div ref={containerRef} data-sentient-id={props.id} data-sentient-variant={variantId}>\n {jsxContent ?? managedContent}\n </div>\n );\n}\n\n/** Re-renders only when the chosen variant changes. */\nexport const Adaptive = memo(AdaptiveImpl, (prev, next) => {\n if (prev.id !== next.id) return false;\n if (JSON.stringify(prev.goal) !== JSON.stringify(next.goal)) return false;\n if (prev.microSignalGoals !== next.microSignalGoals) return false;\n if (prev.variants === next.variants) return true;\n const prevKeys = Object.keys(prev.variants);\n const nextKeys = Object.keys(next.variants);\n if (prevKeys.length !== nextKeys.length) return false;\n return prevKeys.every((k) => k in next.variants);\n});\n","import { useEffect, useRef, useState } from 'react';\nimport { type AssignResult } from '@sentientui/core';\nimport { useSentient, useInitialAssignments, useSessionSegment, useSsrFallback, useOnAssignment } from './provider.js';\nimport { subscribe, getWeights, type ComponentWeights } from './weights-store.js';\n\ndeclare global {\n interface Window { __sentient_overrides?: Record<string, string>; }\n}\n\nfunction getDevOverride(componentId: string): string | null {\n if (typeof window === 'undefined') return null;\n const global = window.__sentient_overrides?.[componentId];\n if (global) return global;\n try {\n const params = new URLSearchParams(window.location.search);\n for (const raw of params.getAll('sentient_variant')) {\n // sentient_variant=componentId:variantId (repeatable for multiple components)\n const sep = raw.indexOf(':');\n if (sep === -1) continue;\n if (raw.slice(0, sep) === componentId) return raw.slice(sep + 1);\n }\n } catch { /* non-browser env */ }\n return null;\n}\n\nexport type AssignmentState = {\n variantId: string | null;\n /** Populated when the assigned variant is a dashboard-managed text variant. */\n content: string | null;\n isLoading: boolean;\n};\n\nfunction pickFromWeights(weights: ComponentWeights, variantIds: string[]): string | null {\n let best: { variantId: string; avgReward: number } | null = null;\n for (const v of weights.variants) {\n if (!variantIds.includes(v.variantId)) continue;\n if (!best || v.avgReward > best.avgReward) {\n best = { variantId: v.variantId, avgReward: v.avgReward };\n }\n }\n return best?.variantId ?? null;\n}\n\n/**\n * Returns a sticky variant assignment for a component.\n *\n * First render reads the local SDK cache; if empty, falls back to a\n * deterministic default and asynchronously calls `/v1/assign`. The server\n * picks the actual variant via Thompson Sampling and the result replaces the fallback\n * on the next render. Subsequent paints read synchronously from cache —\n * no flicker, no loading state after first paint.\n */\nexport function useAssignment(componentId: string, variantIds: string[], agentData?: unknown, agentDataByVariant?: Record<string, unknown>): AssignmentState {\n const initialAssignments = useInitialAssignments();\n const ssrFallback = useSsrFallback();\n const client = useSentient();\n const segment = useSessionSegment();\n const onAssignment = useOnAssignment();\n const assignmentReportedRef = useRef<string | null>(null);\n\n // Dev override: URL param ?sentient_variant=componentId:variantId\n // or window.__sentient_overrides[componentId]. Short-circuits the bandit entirely.\n const devOverride = getDevOverride(componentId);\n const overrideVariant = devOverride && variantIds.includes(devOverride) ? devOverride : null;\n const overrideLoggedRef = useRef<string | null>(null);\n if (overrideVariant && overrideLoggedRef.current !== overrideVariant) {\n overrideLoggedRef.current = overrideVariant;\n console.info(`[sentient] override active: ${componentId} -> ${overrideVariant}`);\n }\n\n const initial = (() => {\n if (overrideVariant) {\n return { variantId: overrideVariant, content: null, isLoading: false };\n }\n // SSR / pre-hydration: no client yet. Use initialAssignments if provided so\n // the server and client first render agree on the same variant (no mismatch).\n if (!client) {\n const preloaded = initialAssignments[componentId];\n if (preloaded && variantIds.includes(preloaded)) {\n return { variantId: preloaded, content: null, isLoading: false };\n }\n if (ssrFallback === 'first' && variantIds.length > 0) {\n return { variantId: variantIds[0], content: null, isLoading: false };\n }\n return { variantId: null, content: null, isLoading: true };\n }\n const cached = client.getAssignment(componentId, segment);\n // Allow cached managed variants (content present) even if not in variantIds.\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n return { variantId: cached.variantId, content: cached.content ?? null, isLoading: false };\n }\n const weights = getWeights(componentId);\n if (weights) {\n const chosen = pickFromWeights(weights, variantIds);\n if (chosen) return { variantId: chosen, content: null, isLoading: false };\n }\n return { variantId: variantIds[0] ?? null, content: null, isLoading: false };\n })();\n\n const [state, setState] = useState<AssignmentState>(initial);\n\n // Helper: call onAssignment at most once per resolved variant.\n const reportAssignment = (variantId: string): void => {\n if (!onAssignment) return;\n if (assignmentReportedRef.current === variantId) return;\n assignmentReportedRef.current = variantId;\n onAssignment(componentId, variantId);\n };\n\n // As soon as the client is ready, unblock the UI immediately with variantIds[0]\n // (or a cached value) so the component never stays invisible while assign is\n // in-flight. The async assign call below then swaps to the bandit-chosen variant.\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n const cached = client.getAssignment(componentId, segment);\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n setState({ variantId: cached.variantId, content: cached.content ?? null, isLoading: false });\n reportAssignment(cached.variantId);\n return;\n }\n setState((prev) => prev.variantId ? prev : { variantId: variantIds[0] ?? null, content: null, isLoading: false });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n // Ask the server for a real assignment when we have a client but no cached one.\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n const cached = client.getAssignment(componentId, segment);\n if (cached && variantIds.includes(cached.variantId)) return;\n\n let cancelled = false;\n void client.assign(componentId, variantIds, agentData, agentDataByVariant).then((result: AssignResult | null) => {\n if (cancelled) return;\n if (!result) return;\n // Allow the result if it's a known code variant OR a managed text variant (has content).\n if (!variantIds.includes(result.variantId) && !result.content) return;\n setState({ variantId: result.variantId, content: result.content ?? null, isLoading: false });\n reportAssignment(result.variantId);\n });\n return () => { cancelled = true; };\n // variantIds intentionally excluded — changing variants mid-mount is unsupported\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n // Live weight updates from the dashboard SSE stream (when wired).\n useEffect(() => {\n if (overrideVariant) return;\n if (!client) return;\n return subscribe(componentId, (weights) => {\n const cached = client.getAssignment(componentId, segment);\n if (cached && (variantIds.includes(cached.variantId) || cached.content)) {\n setState({ variantId: cached.variantId, content: cached.content ?? null, isLoading: false });\n return;\n }\n const chosen = pickFromWeights(weights, variantIds);\n if (chosen) setState({ variantId: chosen, content: null, isLoading: false });\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [overrideVariant, client, componentId, segment]);\n\n if (overrideVariant) {\n return { variantId: overrideVariant, content: null, isLoading: false };\n }\n\n return state;\n}\n","export type RegisteredComponent = { id: string; variantIds: string[]; goal?: string };\n\nconst registry = new Map<string, RegisteredComponent>();\nconst listeners = new Set<() => void>();\n\nfunction emit(): void {\n for (const fn of listeners) fn();\n}\n\n/** Register (or re-register) a component. Returns an unregister function. */\nexport function registerComponent(c: RegisteredComponent): () => void {\n registry.set(c.id, c);\n emit();\n return () => {\n registry.delete(c.id);\n emit();\n };\n}\n\nexport function getRegistered(): RegisteredComponent[] {\n return [...registry.values()];\n}\n\nexport function subscribeRegistry(fn: () => void): () => void {\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n","'use client';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\n\nimport { useEffect, useRef, useState } from 'react';\nimport type { AssignResult } from '@sentientui/core';\nimport { useSentient, useAdaptiveApiKey, useOnAssignment, useSessionSegment } from './provider.js';\n\nexport type AdaptiveTextProps = {\n id: string;\n default: string;\n component?: keyof JSX.IntrinsicElements;\n className?: string;\n};\n\nexport function AdaptiveText({\n id,\n default: defaultText,\n component: Tag = 'span',\n className,\n}: AdaptiveTextProps) {\n const client = useSentient();\n const apiKey = useAdaptiveApiKey();\n const onAssignment = useOnAssignment();\n const segment = useSessionSegment();\n const trackedRef = useRef<string | null>(null);\n\n // Seed from cache synchronously so remounts don't flash back to defaultText.\n const [text, setText] = useState<string | null>(() =>\n client?.getAssignment(id, segment)?.content ?? null\n );\n const [variantId, setVariantId] = useState<string | null>(() =>\n client?.getAssignment(id, segment)?.variantId ?? null\n );\n\n useEffect(() => {\n if (!client) return;\n // Skip if content already cached; assign() re-checks internally but this avoids the async round-trip on remount.\n if (client.getAssignment(id, segment)?.content !== undefined) return;\n\n let cancelled = false;\n void client.assign(id).then((result: AssignResult | null) => {\n if (cancelled) return;\n if (!result) {\n if (process?.env?.NODE_ENV !== 'production') {\n console.warn(`[sentient] <AdaptiveText id=\"${id}\"> assignment failed — showing default text.`);\n }\n return;\n }\n setVariantId(result.variantId);\n if (result.content) setText(result.content);\n });\n return () => {\n cancelled = true;\n };\n }, [client, id, segment]);\n\n useEffect(() => {\n if (!client || !variantId || !apiKey) return;\n if (trackedRef.current === variantId) return;\n trackedRef.current = variantId;\n client.track({\n projectId: apiKey,\n componentId: id,\n variantId,\n eventType: 'variant_assigned',\n payload: {},\n });\n onAssignment?.(id, variantId);\n }, [client, variantId, apiKey, id, onAssignment]);\n\n return <Tag className={className}>{text ?? defaultText}</Tag>;\n}\n","import { useCallback } from 'react';\nimport type { ComponentGoalOptions } from '@sentientui/core';\nimport { useSentient } from './provider.js';\n\nexport type FireGoal = (goalType: string, opts?: ComponentGoalOptions) => void;\n\n/**\n * Returns a `fireGoal(goalType, opts?)` callback that records a conversion\n * attributed to the variant currently served for `componentId` — so it shows\n * up in the per-variant CVR funnel with no manual variantId/projectId plumbing.\n *\n * The served variant is resolved from the SDK's assignment cache (the same one\n * `<Adaptive id={componentId}>` populates), so render that component before\n * firing. Use this for imperative handlers (click, form submit, custom events);\n * for purely declarative goals prefer `<Adaptive goal={...}>`.\n *\n * @example\n * const fireContact = useAdaptiveGoal('hero_headline');\n * <button onClick={() => fireContact('hero_contact', { metadata: { method } })}>Call</button>\n */\nexport function useAdaptiveGoal(componentId: string): FireGoal {\n const client = useSentient();\n return useCallback<FireGoal>(\n (goalType, opts) => {\n client?.componentGoal(componentId, goalType, opts);\n },\n [client, componentId],\n );\n}\n","/** @deprecated Use `useSessionSegment()` from the provider, or `deriveSessionSegment` from `@sentientui/core`. */\nexport { deriveSessionSegment as detectSegment } from '@sentientui/core';\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n"],"mappings":";6bAIA,OAAS,iBAAAA,GAAe,cAAAC,EAAY,aAAAC,EAAW,WAAAC,GAAS,YAAAC,MAAgC,QACxF,OACE,qBAAAC,GACA,uBAAAC,GACA,QAAAC,OAGK,mBCKP,IAAMC,GAAQ,IAAI,IACZC,EAAY,IAAI,IAMf,SAASC,EAAUC,EAAqBC,EAA0B,CACvE,IAAIC,EAAMJ,EAAU,IAAIE,CAAW,EACnC,OAAKE,IACHA,EAAM,IAAI,IACVJ,EAAU,IAAIE,EAAaE,CAAG,GAEhCA,EAAI,IAAID,CAAE,EACH,IAAM,CACXC,EAAK,OAA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a,EAAE,SAASH,CAAC,GACpES,EAAM,KAAK,MAAMT,CAAC,GAAI,GAAI,UAAW,KAAK,UAAUC,EAAG,KAAM,CAAC,EAAG,MAAO,EAAE,EAG5E,GAAIE,EAAK,OAAO,OAAS,EAAG,CAC1BM,EAAM,KAAK,YAAa,EAAE,EAC1B,QAAWC,KAAKP,EAAK,OACnBM,EAAM,KAAK,OAAOC,EAAE,EAAE,uBAAkBA,EAAE,OAAO,IAAI,EACjDA,EAAE,UAAY,QAChBD,EAAM,KAAK,GAAI,YAAa,KAAK,UAAUC,EAAE,QAAS,KAAM,CAAC,EAAG,OAAO,EAG3ED,EAAM,KAAK,EAAE,CACf,CAEA,OAAOA,EAAM,KAAK;AAAA,CAAI,EAAE,QAAQ,EAAI;AAAA,CACtC","names":["createContext","useContext","useEffect","useMemo","useState","detectDeviceClass","detectTrafficSource","init","store","listeners","subscribe","componentId","cb","set","update","weights","e","getWeights","_a","previewOn","listeners","getPreviewMode","previewOn","subscribePreview","fn","listeners","createPreviewClient","inner","componentId","segment","variantIds","agentData","agentDataByVariant","jsx","deriveDefaultSegment","_a","_b","device","detectDeviceClass","source","detectTrafficSource","e","AdaptiveContext","createContext","AdaptiveProvider","props","client","setClient","useState","sessionSegment","previewOn","setPreviewOn","getPreviewMode","useEffect","subscribePreview","prev","config","cancelled","created","initGraph","__spreadProps","__spreadValues","init","poll","entries","entry","weights","v","update","timerId","ssrFallback","exposedClient","useMemo","createPreviewClient","value","useSentient","useContext","useAdaptiveApiKey","useInitialAssignments","useContext","AdaptiveContext","useSessionSegment","useSsrFallback","useOnAssignment","useLayoutOrder","memo","useEffect","useMemo","useRef","useState","attachMicroSignalDetectors","useEffect","useRef","useState","getDevOverride","componentId","_a","global","params","raw","sep","e","pickFromWeights","weights","variantIds","best","v","useAssignment","agentData","agentDataByVariant","initialAssignments","useInitialAssignments","ssrFallback","useSsrFallback","client","useSentient","segment","useSessionSegment","onAssignment","useOnAssignment","assignmentReportedRef","useRef","devOverride","overrideVariant","overrideLoggedRef","initial","_b","preloaded","cached","getWeights","chosen","state","setState","useState","reportAssignment","variantId","useEffect","prev","cancelled","result","subscribe","registry","listeners","emit","fn","registerComponent","c","jsx","normalize","goal","PREVIEW_HTML_MAX_CHARS","shouldSendPreviewHtml","componentId","variantId","key","e","isClickableTarget","el","tag","findClickable","start","container","selector","cursor","AdaptiveImpl","props","_a","_b","client","useSentient","apiKey","useAdaptiveApiKey","variantIds","useMemo","content","useAssignment","containerRef","useRef","mounted","setMounted","useState","useEffect","goalFiredRef","microGoalFiredRef","assignTrackedRef","goalKey","goalLabel","registerComponent","rawHtml","includePreview","node","timerId","hoverStart","onEnter","onLeave","assignedAt","attachMicroSignalDetectors","signalType","extra","_c","__spreadValues","mapping","name","weight","stepIndex","firedSteps","wcCleanups","sub","stepName","stepWeight","idx","fireStep","onClick","target","onSubmit","threshold","io","entries","entry","c","fireGoal","subgoals","remaining","_","i","checkComposite","cleanups","jsxContent","managedContent","Adaptive","memo","prev","next","prevKeys","nextKeys","k","useEffect","useRef","useState","jsx","AdaptiveText","id","defaultText","Tag","className","client","useSentient","apiKey","useAdaptiveApiKey","onAssignment","useOnAssignment","segment","useSessionSegment","trackedRef","useRef","text","setText","useState","_a","_b","variantId","setVariantId","useEffect","cancelled","result","useCallback","useAdaptiveGoal","componentId","client","useSentient","useCallback","goalType","opts","deriveSessionSegment","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLd","renderAgentJsonLdBody","renderAgentMarkdown","lines","b"]}
|
|
@@ -39,6 +39,13 @@ type AdaptiveProviderProps = {
|
|
|
39
39
|
* @see SentientConfig.preConsentBehavior
|
|
40
40
|
*/
|
|
41
41
|
preConsentBehavior?: 'statistical_winner' | 'control';
|
|
42
|
+
/**
|
|
43
|
+
* Honor the browser's Do Not Track signal. Defaults to `true`: when DNT is
|
|
44
|
+
* enabled the SDK sets no cookies and sends no tracking data (overriding
|
|
45
|
+
* `consent: true`). Set `false` to make your own consent gate authoritative.
|
|
46
|
+
* @see SentientConfig.respectDoNotTrack
|
|
47
|
+
*/
|
|
48
|
+
respectDoNotTrack?: boolean;
|
|
42
49
|
/**
|
|
43
50
|
* Called once per component the first time a variant is resolved for that
|
|
44
51
|
* component in this session. Use to forward assignments to your own analytics
|
|
@@ -65,9 +72,84 @@ type AdaptiveProviderProps = {
|
|
|
65
72
|
* sessions without client-side geo lookup.
|
|
66
73
|
*/
|
|
67
74
|
country?: string;
|
|
75
|
+
/**
|
|
76
|
+
* Enable DOM graph scanning + page-structure sync. When `true`, the provider
|
|
77
|
+
* dynamically loads `@sentientui/core/graph` and uses its graph-capable
|
|
78
|
+
* `init()` for the single client, so the SDK scans your page structure and
|
|
79
|
+
* syncs it to power the dashboard graph page. Left off (default), the lean
|
|
80
|
+
* bundle is used and the graph entry is never loaded.
|
|
81
|
+
*/
|
|
82
|
+
enableGraph?: boolean;
|
|
68
83
|
children: ReactNode;
|
|
69
84
|
};
|
|
70
85
|
|
|
86
|
+
/**
|
|
87
|
+
* Agent-readable content feed. Merges SDK-known data (winning variants, layout
|
|
88
|
+
* order) with developer-supplied page content, and renders it either as a
|
|
89
|
+
* server-rendered inline JSON-LD block (read by passive AI crawlers, which do
|
|
90
|
+
* not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).
|
|
91
|
+
*
|
|
92
|
+
* No React or DOM APIs — safe to import in server components, route handlers,
|
|
93
|
+
* and middleware.
|
|
94
|
+
*/
|
|
95
|
+
type AgentBlock = {
|
|
96
|
+
/** Component ID. */
|
|
97
|
+
id: string;
|
|
98
|
+
/** Winning variant ID currently served. */
|
|
99
|
+
variant: string;
|
|
100
|
+
/** Agent-readable data attached to the served variant, if any. */
|
|
101
|
+
content?: unknown;
|
|
102
|
+
};
|
|
103
|
+
type AgentFeed = {
|
|
104
|
+
page: string;
|
|
105
|
+
title?: string;
|
|
106
|
+
summary?: string;
|
|
107
|
+
layoutOrder?: string[];
|
|
108
|
+
blocks: AgentBlock[];
|
|
109
|
+
/** Developer-supplied extra fields (products, specs, arbitrary JSON). */
|
|
110
|
+
[key: string]: unknown;
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Register page-level structured content the SDK can't infer (title, summary,
|
|
114
|
+
* product fields, arbitrary JSON), keyed by page path. Call at module load.
|
|
115
|
+
*/
|
|
116
|
+
declare function defineAgentContent(page: string, content: Record<string, unknown>): void;
|
|
117
|
+
/**
|
|
118
|
+
* Merge SDK-known data with developer-supplied content into a single feed.
|
|
119
|
+
* Developer content fills in title/summary/etc. but can never overwrite the
|
|
120
|
+
* SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).
|
|
121
|
+
*/
|
|
122
|
+
declare function buildAgentFeed(input: {
|
|
123
|
+
page: string;
|
|
124
|
+
blocks: AgentBlock[];
|
|
125
|
+
layoutOrder?: string[];
|
|
126
|
+
content?: Record<string, unknown>;
|
|
127
|
+
}): AgentFeed;
|
|
128
|
+
|
|
129
|
+
type AgentFeedReadEntry = {
|
|
130
|
+
path: string;
|
|
131
|
+
userAgent: string | null;
|
|
132
|
+
botName: string | null;
|
|
133
|
+
};
|
|
134
|
+
type AgentFeedRouteConfig = {
|
|
135
|
+
/** Resolve the feed for a request (winning variants + layout + dev content). */
|
|
136
|
+
getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;
|
|
137
|
+
/** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */
|
|
138
|
+
onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;
|
|
139
|
+
};
|
|
140
|
+
declare function createAgentFeed(config: AgentFeedRouteConfig): (request: Request) => Promise<Response>;
|
|
141
|
+
|
|
142
|
+
type CrawlerRequestEntry = {
|
|
143
|
+
path: string;
|
|
144
|
+
userAgent: string | null;
|
|
145
|
+
botName: string;
|
|
146
|
+
};
|
|
147
|
+
type SentientAgentMiddlewareConfig = {
|
|
148
|
+
/** Best-effort sink — persist to `crawler_requests` here. Failures are swallowed. */
|
|
149
|
+
onCrawler: (entry: CrawlerRequestEntry) => void | Promise<void>;
|
|
150
|
+
};
|
|
151
|
+
declare function sentientAgentMiddleware(config: SentientAgentMiddlewareConfig): (request: Request) => Promise<boolean>;
|
|
152
|
+
|
|
71
153
|
type PreloadComponent = {
|
|
72
154
|
id: string;
|
|
73
155
|
variantIds: string[];
|
|
@@ -93,6 +175,18 @@ type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onA
|
|
|
93
175
|
* Defaults to 1500. Increase if you see unexpected fallbacks in production.
|
|
94
176
|
*/
|
|
95
177
|
timeoutMs?: number;
|
|
178
|
+
/**
|
|
179
|
+
* When set, AdaptiveRoot emits a server-rendered inline JSON-LD block
|
|
180
|
+
* describing the page's winning variants, layout order, and developer-supplied
|
|
181
|
+
* content — readable by passive AI crawlers (which do not run JS). Invisible to
|
|
182
|
+
* humans (a JSON-LD script renders no visible DOM). Omit to emit nothing.
|
|
183
|
+
*/
|
|
184
|
+
agentFeed?: {
|
|
185
|
+
/** Page path for the feed. Falls back to the `x-pathname` request header, then '/'. */
|
|
186
|
+
path?: string;
|
|
187
|
+
/** Structured page content. Falls back to the `defineAgentContent` registry for this path. */
|
|
188
|
+
content?: Record<string, unknown>;
|
|
189
|
+
};
|
|
96
190
|
children: ReactNode;
|
|
97
191
|
};
|
|
98
192
|
/**
|
|
@@ -127,4 +221,4 @@ type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onA
|
|
|
127
221
|
*/
|
|
128
222
|
declare function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element>;
|
|
129
223
|
|
|
130
|
-
export { AdaptiveRoot, type AdaptiveRootProps, type PreloadComponent };
|
|
224
|
+
export { AdaptiveRoot, type AdaptiveRootProps, type AgentFeed, type AgentFeedReadEntry, type AgentFeedRouteConfig, type CrawlerRequestEntry, type PreloadComponent, type SentientAgentMiddlewareConfig, buildAgentFeed as buildAgentFeedFor, createAgentFeed, defineAgentContent, sentientAgentMiddleware };
|
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var V=Object.defineProperty,H=Object.defineProperties;var W=Object.getOwnPropertyDescriptors;var y=Object.getOwnPropertySymbols;var L=Object.prototype.hasOwnProperty,D=Object.prototype.propertyIsEnumerable;var C=(e,t,n)=>t in e?V(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,d=(e,t)=>{for(var n in t||(t={}))L.call(t,n)&&C(e,n,t[n]);if(y)for(var n of y(t))D.call(t,n)&&C(e,n,t[n]);return e},c=(e,t)=>H(e,W(t));var E=(e,t)=>{var n={};for(var r in e)L.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&y)for(var r of y(e))t.indexOf(r)<0&&D.call(e,r)&&(n[r]=e[r]);return n};import{deriveSessionSegment as se}from"@sentientui/core";import{cookies as ie,headers as oe}from"next/headers";import{preloadAssignments as X,readSessionCookie as z}from"@sentientui/core/server";import{preloadDecisions as Ae}from"@sentientui/core/server";function M(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`snt-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}async function U(e,t){var s,o,i;let n=(i=(o=z(t.cookies))!=null?o:(s=t.createSessionId)==null?void 0:s.call(t))!=null?i:M();return{assignments:await X(e,n,{apiKey:t.apiKey,baseUrl:t.baseUrl,origin:t.origin,userAgent:t.userAgent,referer:t.referer,timeoutMs:t.timeoutMs}),sessionId:n}}async function N(e){var o,i,a,p;let{preloadDecisions:t,readSessionCookie:n}=await import("@sentientui/core/server"),r=(a=(i=n(e.cookies))!=null?i:(o=e.createSessionId)==null?void 0:o.call(e))!=null?a:M(),s=await t({sections:e.sections,components:(p=e.components)!=null?p:[]},r,{apiKey:e.apiKey,baseUrl:e.baseUrl,origin:e.origin,userAgent:e.userAgent,referer:e.referer,timeoutMs:e.timeoutMs});return c(d({},s),{sessionId:r})}import{AdaptiveRootClient as ae}from"./adaptive-root-client.js";var G=["page","blocks","layoutOrder"],j=new Map;function Q(e,t){j.set(e,t)}function Y(e){return j.get(e)}function w(e){var s,o;let t=(o=(s=e.content)!=null?s:Y(e.page))!=null?o:{},n={};for(let[i,a]of Object.entries(t))G.includes(i)||(n[i]=a);let r=c(d({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(r.layoutOrder=e.layoutOrder),r}function B(e){return JSON.stringify(d({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function K(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,r]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(r,null,2),"```","");if(e.blocks.length>0){t.push("## blocks","");for(let n of e.blocks)t.push(`- **${n.id}** \u2192 variant \`${n.variant}\``),n.content!==void 0&&t.push(""," ```json",JSON.stringify(n.content,null,2)," ```");t.push("")}return t.join(`
|
|
2
|
+
`).trimEnd()+`
|
|
3
|
+
`}import{matchedAgentToken as Z}from"@sentientui/core";function ee(e,t){return e.pathname.endsWith(".md")||t.toLowerCase().includes("text/markdown")}function te(e){return async t=>{var a;let n=new URL(t.url),r=(a=t.headers.get("accept"))!=null?a:"",s=t.headers.get("user-agent"),o=n.pathname.replace(/\.(md|json)$/,"");if(e.onRead)try{Promise.resolve(e.onRead({path:o,userAgent:s,botName:Z(s!=null?s:"")})).catch(()=>{})}catch(p){}let i=await e.getFeed(t);return ee(n,r)?new Response(K(i),{headers:{"content-type":"text/markdown; charset=utf-8"}}):new Response(JSON.stringify(i),{headers:{"content-type":"application/json; charset=utf-8"}})}}import{matchedAgentToken as ne}from"@sentientui/core";function re(e){return async t=>{let n=t.headers.get("user-agent"),r=ne(n!=null?n:"");if(!r)return!1;try{let s=new URL(t.url).pathname;await Promise.resolve(e.onCrawler({path:s,userAgent:n,botName:r})).catch(()=>{})}catch(s){}return!0}}import{Fragment as ge,jsx as $,jsxs as ce}from"react/jsx-runtime";var _="https://api.sentient-ui.com/v1";function de(e){return Object.entries(e).map(([t,n])=>{var r;return{id:t,variant:typeof n=="string"?n:(r=n==null?void 0:n.variantId)!=null?r:""}})}async function Pe(e){var F,O,I,P;let b=e,{components:t,sections:n,appOrigin:r,initialAssignments:s,ssrSessionId:o,timeoutMs:i,agentFeed:a,children:p}=b,v=E(b,["components","sections","appOrigin","initialAssignments","ssrSessionId","timeoutMs","agentFeed","children"]),m=await oe(),A=m.get("host");!r&&process.env.NODE_ENV==="production"&&!A&&console.error("[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. Pass appOrigin explicitly \u2014 the https://localhost fallback will likely fail allowed_origins validation.");let h=r!=null?r:process.env.NODE_ENV==="production"?`https://${A!=null?A:"localhost"}`:"http://localhost:3001",R=(F=m.get("user-agent"))!=null?F:void 0,k=(O=m.get("referer"))!=null?O:void 0,J=se({userAgent:R,referer:k,appOrigin:h}),S=await ie(),l,u=null,f;if(s)l=s,f=o;else if(n&&n.length>0){let g=await N({sections:n,components:t,cookies:S,apiKey:v.apiKey,baseUrl:_,origin:h,userAgent:R,referer:k,timeoutMs:i});l=g.assignments,u=g.layoutOrder,f=g.sessionId}else{let g=await U(t,{cookies:S,apiKey:v.apiKey,baseUrl:_,origin:h,userAgent:R,referer:k,timeoutMs:i});l=g.assignments,f=g.sessionId}let x=$(ae,c(d({},v),{initialAssignments:l,initialLayoutOrder:u,sessionSegment:J,ssrSessionId:f,children:p}));if(!a)return x;let q=(P=(I=a.path)!=null?I:m.get("x-pathname"))!=null?P:"/",T=w({page:q,blocks:de(l),layoutOrder:u!=null?u:void 0,content:a.content});return ce(ge,{children:[$("script",{type:"application/ld+json",dangerouslySetInnerHTML:{__html:B(T)}}),x]})}export{Pe as AdaptiveRoot,w as buildAgentFeedFor,te as createAgentFeed,Q as defineAgentContent,re as sentientAgentMiddleware};
|
|
2
4
|
//# sourceMappingURL=adaptive-root.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/next/adaptive-root.tsx","../../src/server.ts"],"sourcesContent":["import { deriveSessionSegment } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\nimport type { ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\nexport type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onAssignment'> & {\n /** Components to assign server-side (SEO-safe). */\n components: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n */\n sections?: string[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /** Override: when set no network fetch is made. Useful for tests. */\n initialAssignments?: ServerAssignments;\n /**\n * Milliseconds to wait for the API before rendering default variants.\n * Defaults to 1500. Increase if you see unexpected fallbacks in production.\n */\n timeoutMs?: number;\n children: ReactNode;\n};\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * context=\"landing\"\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components,\n sections,\n appOrigin,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let ssrSessionId: string | undefined;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (sections && sections.length > 0) {\n const decision = await loadAdaptiveDecision({\n sections,\n components,\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl: DEFAULT_API_BASE_URL,\n origin: resolvedOrigin,\n userAgent,\n referer,\n timeoutMs,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl: DEFAULT_API_BASE_URL,\n origin: resolvedOrigin,\n userAgent,\n referer,\n timeoutMs,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n return (\n <AdaptiveRootClient\n {...providerProps}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1500. */\n timeoutMs?: number;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n const sessionId =\n readSessionCookie(options.cookies) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n timeoutMs: options.timeoutMs,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /** Section IDs in default order. Passed to /v1/decide as the candidate layout. */\n sections: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n};\n\n/**\n * SSR helper for pages with a declared section layout. Calls `/v1/decide`\n * instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n const sessionId =\n readSessionCookie(options.cookies) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n timeoutMs: options.timeoutMs,\n },\n );\n\n return { ...result, sessionId };\n}\n"],"mappings":"+kBAAA,OAAS,wBAAAA,MAA4B,mBACrC,OAAS,WAAAC,EAAS,WAAAC,MAAe,eCEjC,OACE,sBAAAC,EACA,qBAAAC,MAGK,0BA8DP,OAAS,oBAAAC,MAAwB,0BAjCjC,SAASC,GAA2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,UAAAT,CACF,CAAC,EACDc,EAAqBK,EAAO,YAC5BH,EAAeG,EAAO,SACxB,CAEA,OACE/B,EAACiC,EAAAC,EAAAC,EAAA,GACKrB,GADL,CAEC,mBAAoBY,EACpB,mBAAoBC,EACpB,eAAgBL,EAChB,aAAcM,EAEb,SAAAf,GACH,CAEJ","names":["deriveSessionSegment","cookies","headers","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","preloadDecisions","result","__spreadProps","__spreadValues","AdaptiveRootClient","jsx","DEFAULT_API_BASE_URL","AdaptiveRoot","props","_b","_c","_a","components","sections","appOrigin","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","sessionSegment","deriveSessionSegment","cookieStore","cookies","initialAssignments","initialLayoutOrder","ssrSessionId","decision","loadAdaptiveDecision","result","loadAdaptiveAssignments","AdaptiveRootClient","__spreadProps","__spreadValues"]}
|
|
1
|
+
{"version":3,"sources":["../../src/next/adaptive-root.tsx","../../src/server.ts","../../src/agent-feed.ts","../../src/next/agent-feed-route.ts","../../src/next/agent-middleware.ts"],"sourcesContent":["import { deriveSessionSegment } from '@sentientui/core';\nimport { cookies, headers } from 'next/headers';\nimport type { ReactNode } from 'react';\nimport type { AdaptiveProviderProps } from '../provider.js';\nimport {\n loadAdaptiveAssignments,\n loadAdaptiveDecision,\n type ServerAssignments,\n} from '../server.js';\nimport { AdaptiveRootClient } from './adaptive-root-client.js';\nimport { buildAgentFeed, renderAgentJsonLdBody, type AgentBlock } from '../agent-feed.js';\n\nexport { createAgentFeed } from './agent-feed-route.js';\nexport type { AgentFeedRouteConfig, AgentFeedReadEntry } from './agent-feed-route.js';\nexport { sentientAgentMiddleware } from './agent-middleware.js';\nexport type { SentientAgentMiddlewareConfig, CrawlerRequestEntry } from './agent-middleware.js';\nexport { defineAgentContent, buildAgentFeed as buildAgentFeedFor } from '../agent-feed.js';\nexport type { AgentFeed } from '../agent-feed.js';\n\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport type PreloadComponent = { id: string; variantIds: string[] };\n\nexport type AdaptiveRootProps = Omit<AdaptiveProviderProps, 'initialAssignments' | 'onAssignment'> & {\n /** Components to assign server-side (SEO-safe). */\n components: PreloadComponent[];\n /**\n * Declare page section IDs in their default order. When provided,\n * AdaptiveRoot calls `/v1/decide` (single round trip) instead of\n * individual `/v1/assign` calls, and `useLayoutOrder()` returns the\n * persona-specific order on first render.\n *\n * @example sections={['hero', 'pricing', 'features', 'social_proof']}\n */\n sections?: string[];\n /** App origin — must be in the project's `allowed_origins`. */\n appOrigin?: string;\n /** Override: when set no network fetch is made. Useful for tests. */\n initialAssignments?: ServerAssignments;\n /**\n * Milliseconds to wait for the API before rendering default variants.\n * Defaults to 1500. Increase if you see unexpected fallbacks in production.\n */\n timeoutMs?: number;\n /**\n * When set, AdaptiveRoot emits a server-rendered inline JSON-LD block\n * describing the page's winning variants, layout order, and developer-supplied\n * content — readable by passive AI crawlers (which do not run JS). Invisible to\n * humans (a JSON-LD script renders no visible DOM). Omit to emit nothing.\n */\n agentFeed?: {\n /** Page path for the feed. Falls back to the `x-pathname` request header, then '/'. */\n path?: string;\n /** Structured page content. Falls back to the `defineAgentContent` registry for this path. */\n content?: Record<string, unknown>;\n };\n children: ReactNode;\n};\n\n/** Build agent blocks from SSR assignments (Record<id, variantId | { variantId }>). */\nfunction assignmentsToBlocks(assignments: ServerAssignments): AgentBlock[] {\n return Object.entries(assignments as Record<string, unknown>).map(([id, v]) => ({\n id,\n variant: typeof v === 'string' ? v : ((v as { variantId?: string })?.variantId ?? ''),\n }));\n}\n\n/**\n * Next.js Server Component that resolves variant assignments (and optionally\n * section layout order) server-side for zero layout shift on first paint.\n *\n * When `sections` is provided, a single `POST /v1/decide` call returns both\n * the persona-specific section order and all component assignments.\n * Without `sections`, individual `/v1/assign` calls are made per component.\n *\n * @example\n * // app/page.tsx — with section layout\n * import { AdaptiveRoot } from '@sentientui/react/next';\n *\n * export default async function Page() {\n * return (\n * <AdaptiveRoot\n * apiKey={process.env.NEXT_PUBLIC_SENTIENT_API_KEY!}\n * context=\"landing\"\n * sections={['hero', 'pricing', 'features', 'social_proof']}\n * components={[\n * { id: 'hero_cta', variantIds: ['default', 'accent'] },\n * ]}\n * >\n * <HeroSection />\n * <PricingSection />\n * <FeaturesSection />\n * <SocialProofSection />\n * </AdaptiveRoot>\n * );\n * }\n */\nexport async function AdaptiveRoot(props: AdaptiveRootProps): Promise<JSX.Element> {\n const {\n components,\n sections,\n appOrigin,\n initialAssignments: initialAssignmentsOverride,\n ssrSessionId: ssrSessionIdProp,\n timeoutMs,\n agentFeed,\n children,\n ...providerProps\n } = props;\n\n const headerStore = await headers();\n const host = headerStore.get('host');\n if (!appOrigin && process.env.NODE_ENV === 'production' && !host) {\n console.error(\n '[SentientUI] AdaptiveRoot: Host header is absent and no appOrigin was provided. ' +\n 'Pass appOrigin explicitly — the https://localhost fallback will likely fail allowed_origins validation.',\n );\n }\n const resolvedOrigin = appOrigin ??\n (process.env.NODE_ENV === 'production'\n ? `https://${host ?? 'localhost'}`\n : 'http://localhost:3001');\n const userAgent = headerStore.get('user-agent') ?? undefined;\n const referer = headerStore.get('referer') ?? undefined;\n const sessionSegment = deriveSessionSegment({ userAgent, referer, appOrigin: resolvedOrigin });\n const cookieStore = await cookies();\n\n let initialAssignments: ServerAssignments;\n let initialLayoutOrder: string[] | null = null;\n let ssrSessionId: string | undefined;\n\n if (initialAssignmentsOverride) {\n initialAssignments = initialAssignmentsOverride;\n ssrSessionId = ssrSessionIdProp;\n } else if (sections && sections.length > 0) {\n const decision = await loadAdaptiveDecision({\n sections,\n components,\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl: DEFAULT_API_BASE_URL,\n origin: resolvedOrigin,\n userAgent,\n referer,\n timeoutMs,\n });\n initialAssignments = decision.assignments;\n initialLayoutOrder = decision.layoutOrder;\n ssrSessionId = decision.sessionId;\n } else {\n const result = await loadAdaptiveAssignments(components, {\n cookies: cookieStore,\n apiKey: providerProps.apiKey,\n baseUrl: DEFAULT_API_BASE_URL,\n origin: resolvedOrigin,\n userAgent,\n referer,\n timeoutMs,\n });\n initialAssignments = result.assignments;\n ssrSessionId = result.sessionId;\n }\n\n const client = (\n <AdaptiveRootClient\n {...providerProps}\n initialAssignments={initialAssignments}\n initialLayoutOrder={initialLayoutOrder}\n sessionSegment={sessionSegment}\n ssrSessionId={ssrSessionId}\n >\n {children}\n </AdaptiveRootClient>\n );\n\n if (!agentFeed) return client;\n\n // Server-rendered inline JSON-LD for AI crawlers. Emitted only on the server\n // path so passive crawlers (no JS) see it in the raw HTML. The body escapes\n // '<' so page content cannot break out of the <script> element.\n const path = agentFeed.path ?? headerStore.get('x-pathname') ?? '/';\n const feed = buildAgentFeed({\n page: path,\n blocks: assignmentsToBlocks(initialAssignments),\n layoutOrder: initialLayoutOrder ?? undefined,\n content: agentFeed.content,\n });\n\n return (\n <>\n <script\n type=\"application/ld+json\"\n dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }}\n />\n {client}\n </>\n );\n}\n","/**\n * Server-only helpers for Next.js / SSR. No React or DOM APIs.\n */\nimport {\n preloadAssignments,\n readSessionCookie,\n type ServerAssignConfig,\n type ServerAssignments,\n} from '@sentientui/core/server';\n\nexport { preloadAssignments, readSessionCookie };\nexport type { ServerAssignConfig, ServerAssignments };\n\n/** Return value of `loadAdaptiveAssignments` — includes the session ID used for SSR. */\nexport type LoadAdaptiveAssignmentsResult = {\n assignments: ServerAssignments;\n /** The session ID used for SSR assignment. Pass as `ssrSessionId` to `<AdaptiveProvider>`. */\n sessionId: string;\n};\n\nexport type LoadAdaptiveAssignmentsOptions = {\n /** Next.js `cookies()` return value, or any object with `get(name)`. */\n cookies: { get(name: string): { value: string } | undefined };\n apiKey: string;\n baseUrl: string;\n /** Used when `_snt_uid` is absent (e.g. first visit, many crawlers). */\n createSessionId?: () => string;\n /** Must match a value in the project's `allowed_origins` (e.g. `http://localhost:3001`). */\n origin?: string;\n /** From Next.js `headers().get('user-agent')` — aligns SSR segment with the client. */\n userAgent?: string;\n /** From Next.js `headers().get('referer')`. */\n referer?: string;\n /** Milliseconds to wait for the API before returning default variants. Defaults to 1500. */\n timeoutMs?: number;\n};\n\nfunction defaultSessionId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `snt-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\n/**\n * Fetches bandit assignments on the server for SEO-safe HTML.\n * Pass `assignments` as `initialAssignments` and `sessionId` as `ssrSessionId`\n * on `<AdaptiveProvider>` so the client adopts the same session on first visit.\n */\nexport async function loadAdaptiveAssignments(\n components: Array<{ id: string; variantIds: string[] }>,\n options: LoadAdaptiveAssignmentsOptions,\n): Promise<LoadAdaptiveAssignmentsResult> {\n const sessionId =\n readSessionCookie(options.cookies) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const assignments = await preloadAssignments(components, sessionId, {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n timeoutMs: options.timeoutMs,\n });\n\n return { assignments, sessionId };\n}\n\nexport { preloadDecisions } from '@sentientui/core/server';\nexport type { DecideResult } from '@sentientui/core/server';\n\n/** Return value of `loadAdaptiveDecision` — includes the session ID used for SSR. */\nexport type LoadAdaptiveDecisionResult = import('@sentientui/core/server').DecideResult & {\n sessionId: string;\n};\n\nexport type LoadAdaptiveDecisionOptions = LoadAdaptiveAssignmentsOptions & {\n /** Section IDs in default order. Passed to /v1/decide as the candidate layout. */\n sections: string[];\n /** Components to assign in the same decide call. */\n components?: Array<{ id: string; variantIds?: string[] }>;\n};\n\n/**\n * SSR helper for pages with a declared section layout. Calls `/v1/decide`\n * instead of multiple `/v1/assign` round trips.\n * Pass `sessionId` as `ssrSessionId` on `<AdaptiveProvider>` so the client\n * adopts the same session on first visit.\n */\nexport async function loadAdaptiveDecision(\n options: LoadAdaptiveDecisionOptions,\n): Promise<LoadAdaptiveDecisionResult> {\n const { preloadDecisions, readSessionCookie } = await import('@sentientui/core/server');\n\n const sessionId =\n readSessionCookie(options.cookies) ??\n options.createSessionId?.() ??\n defaultSessionId();\n\n const result = await preloadDecisions(\n {\n sections: options.sections,\n components: options.components ?? [],\n },\n sessionId,\n {\n apiKey: options.apiKey,\n baseUrl: options.baseUrl,\n origin: options.origin,\n userAgent: options.userAgent,\n referer: options.referer,\n timeoutMs: options.timeoutMs,\n },\n );\n\n return { ...result, sessionId };\n}\n","/**\n * Agent-readable content feed. Merges SDK-known data (winning variants, layout\n * order) with developer-supplied page content, and renders it either as a\n * server-rendered inline JSON-LD block (read by passive AI crawlers, which do\n * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).\n *\n * No React or DOM APIs — safe to import in server components, route handlers,\n * and middleware.\n */\n\nexport type AgentBlock = {\n /** Component ID. */\n id: string;\n /** Winning variant ID currently served. */\n variant: string;\n /** Agent-readable data attached to the served variant, if any. */\n content?: unknown;\n};\n\nexport type AgentFeed = {\n page: string;\n title?: string;\n summary?: string;\n layoutOrder?: string[];\n blocks: AgentBlock[];\n /** Developer-supplied extra fields (products, specs, arbitrary JSON). */\n [key: string]: unknown;\n};\n\n/** Fields the SDK owns — developer content can never overwrite these. */\nconst RESERVED_FIELDS = ['page', 'blocks', 'layoutOrder'] as const;\n\nconst registry = new Map<string, Record<string, unknown>>();\n\n/**\n * Register page-level structured content the SDK can't infer (title, summary,\n * product fields, arbitrary JSON), keyed by page path. Call at module load.\n */\nexport function defineAgentContent(page: string, content: Record<string, unknown>): void {\n registry.set(page, content);\n}\n\n/** Look up registered content for a page. */\nexport function getAgentContent(page: string): Record<string, unknown> | undefined {\n return registry.get(page);\n}\n\n/** Clear the registry — intended for tests. */\nexport function clearAgentContent(): void {\n registry.clear();\n}\n\n/**\n * Merge SDK-known data with developer-supplied content into a single feed.\n * Developer content fills in title/summary/etc. but can never overwrite the\n * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).\n */\nexport function buildAgentFeed(input: {\n page: string;\n blocks: AgentBlock[];\n layoutOrder?: string[];\n content?: Record<string, unknown>;\n}): AgentFeed {\n const supplied = input.content ?? getAgentContent(input.page) ?? {};\n const safe: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(supplied)) {\n if (!(RESERVED_FIELDS as readonly string[]).includes(k)) safe[k] = v;\n }\n const feed: AgentFeed = {\n ...safe,\n page: input.page,\n blocks: input.blocks,\n };\n if (input.layoutOrder) feed.layoutOrder = input.layoutOrder;\n return feed;\n}\n\n/**\n * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is\n * escaped to `<` so embedded content cannot break out of the script\n * element. MUST be emitted on the server — passive crawlers never run client JS.\n */\nexport function renderAgentJsonLd(feed: AgentFeed): string {\n return `<script type=\"application/ld+json\">${renderAgentJsonLdBody(feed)}</script>`;\n}\n\n/**\n * The escaped JSON-LD body only (no `<script>` wrapper). For React server\n * components, inject via `<script type=\"application/ld+json\"\n * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.\n */\nexport function renderAgentJsonLdBody(feed: AgentFeed): string {\n return JSON.stringify({ '@context': 'https://schema.org', '@type': 'WebPage', ...feed })\n .replace(/</g, '\\\\u003c');\n}\n\n/** Render the feed as Markdown for agents that negotiate `text/markdown`. */\nexport function renderAgentMarkdown(feed: AgentFeed): string {\n const lines: string[] = [];\n if (feed.title) lines.push(`# ${feed.title}`, '');\n if (feed.summary) lines.push(String(feed.summary), '');\n\n for (const [k, v] of Object.entries(feed)) {\n if (['page', 'title', 'summary', 'blocks', 'layoutOrder'].includes(k)) continue;\n lines.push(`## ${k}`, '', '```json', JSON.stringify(v, null, 2), '```', '');\n }\n\n if (feed.blocks.length > 0) {\n lines.push('## blocks', '');\n for (const b of feed.blocks) {\n lines.push(`- **${b.id}** → variant \\`${b.variant}\\``);\n if (b.content !== undefined) {\n lines.push('', ' ```json', JSON.stringify(b.content, null, 2), ' ```');\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n').trimEnd() + '\\n';\n}\n","/**\n * `createAgentFeed` — a framework-standard Route Handler (Web `Request` →\n * `Response`) that serves the agent-readable feed via HTTP content negotiation:\n * `text/markdown` (Accept header or `.md` URL) → Markdown, otherwise JSON.\n *\n * This is the secondary channel of the agent-readable design — for agents that\n * *ask* (coding agents, agents the customer controls, future crawlers). The\n * primary channel is the server-rendered inline JSON-LD from `<AdaptiveRoot>`.\n *\n * Every fetch is reported to `onRead` (best-effort) so it can be logged to\n * `crawler_requests` and counted in the dashboard traffic breakdown.\n */\nimport { matchedAgentToken } from '@sentientui/core';\nimport { renderAgentMarkdown, type AgentFeed } from '../agent-feed.js';\n\nexport type AgentFeedReadEntry = {\n path: string;\n userAgent: string | null;\n botName: string | null;\n};\n\nexport type AgentFeedRouteConfig = {\n /** Resolve the feed for a request (winning variants + layout + dev content). */\n getFeed: (request: Request) => Promise<AgentFeed> | AgentFeed;\n /** Best-effort per-fetch hook — log to `crawler_requests` here. Never awaited into the response. */\n onRead?: (entry: AgentFeedReadEntry) => void | Promise<void>;\n};\n\nfunction wantsMarkdown(url: URL, accept: string): boolean {\n return url.pathname.endsWith('.md') || accept.toLowerCase().includes('text/markdown');\n}\n\nexport function createAgentFeed(\n config: AgentFeedRouteConfig,\n): (request: Request) => Promise<Response> {\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const accept = request.headers.get('accept') ?? '';\n const userAgent = request.headers.get('user-agent');\n // Strip the .md/.json suffix so the feed path matches the page path.\n const path = url.pathname.replace(/\\.(md|json)$/, '');\n\n if (config.onRead) {\n try {\n void Promise.resolve(\n config.onRead({ path, userAgent, botName: matchedAgentToken(userAgent ?? '') }),\n ).catch(() => {});\n } catch {\n /* logging must never break the response */\n }\n }\n\n const feed = await config.getFeed(request);\n\n if (wantsMarkdown(url, accept)) {\n return new Response(renderAgentMarkdown(feed), {\n headers: { 'content-type': 'text/markdown; charset=utf-8' },\n });\n }\n return new Response(JSON.stringify(feed), {\n headers: { 'content-type': 'application/json; charset=utf-8' },\n });\n };\n}\n","/**\n * `sentientAgentMiddleware` — additive-discovery middleware. Detects known AI\n * crawler / agent user-agents on page requests and reports them so they can be\n * logged to `crawler_requests` (the only way to observe passive crawlers, which\n * run no JS and never create a session). It NEVER changes the response — the\n * caller composes it into their Next.js middleware and returns `NextResponse.next()`.\n *\n * export async function middleware(request: NextRequest) {\n * await logCrawler(request); // sentientAgentMiddleware instance\n * return NextResponse.next();\n * }\n */\nimport { matchedAgentToken } from '@sentientui/core';\n\nexport type CrawlerRequestEntry = {\n path: string;\n userAgent: string | null;\n botName: string;\n};\n\nexport type SentientAgentMiddlewareConfig = {\n /** Best-effort sink — persist to `crawler_requests` here. Failures are swallowed. */\n onCrawler: (entry: CrawlerRequestEntry) => void | Promise<void>;\n};\n\nexport function sentientAgentMiddleware(\n config: SentientAgentMiddlewareConfig,\n): (request: Request) => Promise<boolean> {\n return async (request: Request): Promise<boolean> => {\n const userAgent = request.headers.get('user-agent');\n const botName = matchedAgentToken(userAgent ?? '');\n if (!botName) return false;\n\n try {\n const path = new URL(request.url).pathname;\n await Promise.resolve(config.onCrawler({ path, userAgent, botName })).catch(() => {});\n } catch {\n /* detection/logging must never break the request */\n }\n return true;\n };\n}\n"],"mappings":"+kBAAA,OAAS,wBAAAA,OAA4B,mBACrC,OAAS,WAAAC,GAAS,WAAAC,OAAe,eCEjC,OACE,sBAAAC,EACA,qBAAAC,MAGK,0BA8DP,OAAS,oBAAAC,OAAwB,0BAjCjC,SAASC,GAA2B,CAClC,OAAI,OAAO,QAAW,aAAe,OAAO,OAAO,YAAe,WACzD,OAAO,WAAW,EAEpB,OAAO,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,EAAG,EAAE,CAAC,EACrE,CAOA,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GAAqB,CAAE,UAAAH,EAAW,QAAAC,EAAS,UAAWF,CAAe,CAAC,EACvFK,EAAc,MAAMC,GAAQ,EAE9BC,EACAC,EAAsC,KACtCC,EAEJ,GAAInB,EACFiB,EAAqBjB,EACrBmB,EAAelB,UACNH,GAAYA,EAAS,OAAS,EAAG,CAC1C,IAAMsB,EAAW,MAAMC,EAAqB,CAC1C,SAAAvB,EACA,WAAAD,EACA,QAASkB,EACT,OAAQV,EAAc,OACtB,QAASpB,EACT,OAAQyB,EACR,UAAAC,EACA,QAAAC,EACA,UAAAV,CACF,CAAC,EACDe,EAAqBG,EAAS,YAC9BF,EAAqBE,EAAS,YAC9BD,EAAeC,EAAS,SAC1B,KAAO,CACL,IAAME,EAAS,MAAMC,EAAwB1B,EAAY,CACvD,QAASkB,EACT,OAAQV,EAAc,OACtB,QAASpB,EACT,OAAQyB,EACR,UAAAC,EACA,QAAAC,EACA,UAAAV,CACF,CAAC,EACDe,EAAqBK,EAAO,YAC5BH,EAAeG,EAAO,SACxB,CAEA,IAAME,EACJzC,EAAC0C,GAAAC,EAAAC,EAAA,GACKtB,GADL,CAEC,mBAAoBY,EACpB,mBAAoBC,EACpB,eAAgBL,EAChB,aAAcM,EAEb,SAAAf,GACH,EAGF,GAAI,CAACD,EAAW,OAAOqB,EAKvB,IAAMI,GAAOhC,GAAAD,EAAAQ,EAAU,OAAV,KAAAR,EAAkBY,EAAY,IAAI,YAAY,IAA9C,KAAAX,EAAmD,IAC1DiC,EAAOC,EAAe,CAC1B,KAAMF,EACN,OAAQ1C,GAAoB+B,CAAkB,EAC9C,YAAaC,GAAA,KAAAA,EAAsB,OACnC,QAASf,EAAU,OACrB,CAAC,EAED,OACEnB,GAAAF,GAAA,CACE,UAAAC,EAAC,UACC,KAAK,sBACL,wBAAyB,CAAE,OAAQgD,EAAsBF,CAAI,CAAE,EACjE,EACCL,GACH,CAEJ","names":["deriveSessionSegment","cookies","headers","preloadAssignments","readSessionCookie","preloadDecisions","defaultSessionId","loadAdaptiveAssignments","components","options","_a","_b","_c","sessionId","readSessionCookie","preloadAssignments","loadAdaptiveDecision","_d","preloadDecisions","result","__spreadProps","__spreadValues","AdaptiveRootClient","RESERVED_FIELDS","registry","defineAgentContent","page","content","getAgentContent","buildAgentFeed","input","_a","_b","supplied","getAgentContent","safe","k","v","RESERVED_FIELDS","feed","__spreadProps","__spreadValues","renderAgentJsonLdBody","feed","__spreadValues","renderAgentMarkdown","lines","k","v","b","matchedAgentToken","wantsMarkdown","url","accept","createAgentFeed","config","request","_a","userAgent","path","matchedAgentToken","e","feed","renderAgentMarkdown","matchedAgentToken","sentientAgentMiddleware","config","request","userAgent","botName","path","e","Fragment","jsx","jsxs","DEFAULT_API_BASE_URL","assignmentsToBlocks","assignments","id","v","_a","AdaptiveRoot","props","_b","_c","_d","_e","components","sections","appOrigin","initialAssignmentsOverride","ssrSessionIdProp","timeoutMs","agentFeed","children","providerProps","__objRest","headerStore","headers","host","resolvedOrigin","userAgent","referer","sessionSegment","deriveSessionSegment","cookieStore","cookies","initialAssignments","initialLayoutOrder","ssrSessionId","decision","loadAdaptiveDecision","result","loadAdaptiveAssignments","client","AdaptiveRootClient","__spreadProps","__spreadValues","path","feed","buildAgentFeed","renderAgentJsonLdBody"]}
|