@sentientui/react 0.8.5 → 0.10.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 CHANGED
@@ -107,6 +107,7 @@ Imported from `@sentientui/react/next`.
107
107
  | `appOrigin` | `string` *(default `http://localhost:3001`)* | Your app origin (e.g. `https://yourapp.com`). Must be on the project's allowed-origins list. Always set in production. |
108
108
  | `context` | `'landing' \| 'ecommerce' \| 'saas' \| 'marketplace'` | Type of product. Used for segment weighting and analytics grouping. |
109
109
  | `consent` | `boolean` *(default `true`)* | Set `false` to skip SDK init (no cookies, no events). Flip to `true` after the visitor accepts. |
110
+ | `respectDoNotTrack` | `boolean` *(default `true`)* | Honor the browser's Do Not Track signal. When on and DNT is enabled, the SDK sets no cookies and sends no tracking data (overriding `consent: true`), and `grantConsent()` won't re-enable it. Set `false` to make your own consent gate authoritative. |
110
111
  | `ssrFallback` | `'first' \| 'none'` *(default `'first'`)* | What to render in SSR HTML for components not in `components`. `'first'` is safe for SEO. |
111
112
  | `timeoutMs` | `number` *(default `1500`)* | Server-side fetch timeout before falling back to the first variant. |
112
113
  | `debug` | `boolean` | Log assignment and event activity to the console. |
@@ -289,6 +290,18 @@ window.__sentient_overrides = { hero_cta: 'variant_a' };
289
290
 
290
291
  Overrides bypass the bandit entirely — no events recorded, weights unchanged.
291
292
 
293
+ ## Graph mode
294
+
295
+ Pass `enableGraph` to `AdaptiveProvider` (or `AdaptiveRoot`) to turn on DOM graph scanning. The SDK captures your page structure and syncs it to power the dashboard Graph page. The graph code is loaded on demand, so apps that don't set `enableGraph` keep the lean bundle.
296
+
297
+ ```tsx
298
+ <AdaptiveProvider apiKey="pk_…" context="saas" enableGraph>
299
+ <App />
300
+ </AdaptiveProvider>
301
+ ```
302
+
303
+ Direct `@sentientui/core` users enable the same thing by importing `init` from `@sentientui/core/graph` and passing `graph: true`.
304
+
292
305
  ## Consent management (GDPR)
293
306
 
294
307
  SentientUI does not track visitors until consent is granted. To serve the best-performing variant while the cookie banner is pending (rather than freezing the UI), use `preConsentBehavior: 'statistical_winner'`:
package/dist/index.d.cts CHANGED
@@ -41,6 +41,13 @@ type AdaptiveProviderProps = {
41
41
  * @see SentientConfig.preConsentBehavior
42
42
  */
43
43
  preConsentBehavior?: 'statistical_winner' | 'control';
44
+ /**
45
+ * Honor the browser's Do Not Track signal. Defaults to `true`: when DNT is
46
+ * enabled the SDK sets no cookies and sends no tracking data (overriding
47
+ * `consent: true`). Set `false` to make your own consent gate authoritative.
48
+ * @see SentientConfig.respectDoNotTrack
49
+ */
50
+ respectDoNotTrack?: boolean;
44
51
  /**
45
52
  * Called once per component the first time a variant is resolved for that
46
53
  * component in this session. Use to forward assignments to your own analytics
@@ -67,6 +74,14 @@ type AdaptiveProviderProps = {
67
74
  * sessions without client-side geo lookup.
68
75
  */
69
76
  country?: string;
77
+ /**
78
+ * Enable DOM graph scanning + page-structure sync. When `true`, the provider
79
+ * dynamically loads `@sentientui/core/graph` and uses its graph-capable
80
+ * `init()` for the single client, so the SDK scans your page structure and
81
+ * syncs it to power the dashboard graph page. Left off (default), the lean
82
+ * bundle is used and the graph entry is never loaded.
83
+ */
84
+ enableGraph?: boolean;
70
85
  children: ReactNode;
71
86
  };
72
87
  /**
@@ -223,4 +238,63 @@ declare function update(componentId: string, weights: ComponentWeights): void;
223
238
  */
224
239
  declare function getWeights(componentId: string): ComponentWeights | null;
225
240
 
226
- export { Adaptive, type AdaptiveProps, AdaptiveProvider, type AdaptiveProviderProps, AdaptiveText, type AdaptiveTextProps, type AssignmentState, type ClickGoal, type ComponentWeights, type CompositeGoal, type FireGoal, type FormSubmitGoal, type GoalConfig, type MicroSignalGoalConfig, type MicroSignalGoals, type ScrollDepthGoal, type SsrFallback, type VariantWeight, type WeightedCompositeGoal, type WeightedStep, getWeights, subscribe as subscribeWeights, update as updateWeights, useAdaptiveGoal, useAssignment, useInitialAssignments, useLayoutOrder, useSentient };
241
+ /**
242
+ * Agent-readable content feed. Merges SDK-known data (winning variants, layout
243
+ * order) with developer-supplied page content, and renders it either as a
244
+ * server-rendered inline JSON-LD block (read by passive AI crawlers, which do
245
+ * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).
246
+ *
247
+ * No React or DOM APIs — safe to import in server components, route handlers,
248
+ * and middleware.
249
+ */
250
+ type AgentBlock = {
251
+ /** Component ID. */
252
+ id: string;
253
+ /** Winning variant ID currently served. */
254
+ variant: string;
255
+ /** Agent-readable data attached to the served variant, if any. */
256
+ content?: unknown;
257
+ };
258
+ type AgentFeed = {
259
+ page: string;
260
+ title?: string;
261
+ summary?: string;
262
+ layoutOrder?: string[];
263
+ blocks: AgentBlock[];
264
+ /** Developer-supplied extra fields (products, specs, arbitrary JSON). */
265
+ [key: string]: unknown;
266
+ };
267
+ /**
268
+ * Register page-level structured content the SDK can't infer (title, summary,
269
+ * product fields, arbitrary JSON), keyed by page path. Call at module load.
270
+ */
271
+ declare function defineAgentContent(page: string, content: Record<string, unknown>): void;
272
+ /** Look up registered content for a page. */
273
+ declare function getAgentContent(page: string): Record<string, unknown> | undefined;
274
+ /**
275
+ * Merge SDK-known data with developer-supplied content into a single feed.
276
+ * Developer content fills in title/summary/etc. but can never overwrite the
277
+ * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).
278
+ */
279
+ declare function buildAgentFeed(input: {
280
+ page: string;
281
+ blocks: AgentBlock[];
282
+ layoutOrder?: string[];
283
+ content?: Record<string, unknown>;
284
+ }): AgentFeed;
285
+ /**
286
+ * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is
287
+ * escaped to `<` so embedded content cannot break out of the script
288
+ * element. MUST be emitted on the server — passive crawlers never run client JS.
289
+ */
290
+ declare function renderAgentJsonLd(feed: AgentFeed): string;
291
+ /**
292
+ * The escaped JSON-LD body only (no `<script>` wrapper). For React server
293
+ * components, inject via `<script type="application/ld+json"
294
+ * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.
295
+ */
296
+ declare function renderAgentJsonLdBody(feed: AgentFeed): string;
297
+ /** Render the feed as Markdown for agents that negotiate `text/markdown`. */
298
+ declare function renderAgentMarkdown(feed: AgentFeed): string;
299
+
300
+ export { Adaptive, type AdaptiveProps, AdaptiveProvider, type AdaptiveProviderProps, AdaptiveText, type AdaptiveTextProps, type AgentBlock, type AgentFeed, type AssignmentState, type ClickGoal, type ComponentWeights, type CompositeGoal, type FireGoal, type FormSubmitGoal, type GoalConfig, type MicroSignalGoalConfig, type MicroSignalGoals, type ScrollDepthGoal, type SsrFallback, type VariantWeight, type WeightedCompositeGoal, type WeightedStep, buildAgentFeed, defineAgentContent, getAgentContent, getWeights, renderAgentJsonLd, renderAgentJsonLdBody, renderAgentMarkdown, subscribe as subscribeWeights, update as updateWeights, useAdaptiveGoal, useAssignment, useInitialAssignments, useLayoutOrder, useSentient };
package/dist/index.d.ts CHANGED
@@ -41,6 +41,13 @@ type AdaptiveProviderProps = {
41
41
  * @see SentientConfig.preConsentBehavior
42
42
  */
43
43
  preConsentBehavior?: 'statistical_winner' | 'control';
44
+ /**
45
+ * Honor the browser's Do Not Track signal. Defaults to `true`: when DNT is
46
+ * enabled the SDK sets no cookies and sends no tracking data (overriding
47
+ * `consent: true`). Set `false` to make your own consent gate authoritative.
48
+ * @see SentientConfig.respectDoNotTrack
49
+ */
50
+ respectDoNotTrack?: boolean;
44
51
  /**
45
52
  * Called once per component the first time a variant is resolved for that
46
53
  * component in this session. Use to forward assignments to your own analytics
@@ -67,6 +74,14 @@ type AdaptiveProviderProps = {
67
74
  * sessions without client-side geo lookup.
68
75
  */
69
76
  country?: string;
77
+ /**
78
+ * Enable DOM graph scanning + page-structure sync. When `true`, the provider
79
+ * dynamically loads `@sentientui/core/graph` and uses its graph-capable
80
+ * `init()` for the single client, so the SDK scans your page structure and
81
+ * syncs it to power the dashboard graph page. Left off (default), the lean
82
+ * bundle is used and the graph entry is never loaded.
83
+ */
84
+ enableGraph?: boolean;
70
85
  children: ReactNode;
71
86
  };
72
87
  /**
@@ -223,4 +238,63 @@ declare function update(componentId: string, weights: ComponentWeights): void;
223
238
  */
224
239
  declare function getWeights(componentId: string): ComponentWeights | null;
225
240
 
226
- export { Adaptive, type AdaptiveProps, AdaptiveProvider, type AdaptiveProviderProps, AdaptiveText, type AdaptiveTextProps, type AssignmentState, type ClickGoal, type ComponentWeights, type CompositeGoal, type FireGoal, type FormSubmitGoal, type GoalConfig, type MicroSignalGoalConfig, type MicroSignalGoals, type ScrollDepthGoal, type SsrFallback, type VariantWeight, type WeightedCompositeGoal, type WeightedStep, getWeights, subscribe as subscribeWeights, update as updateWeights, useAdaptiveGoal, useAssignment, useInitialAssignments, useLayoutOrder, useSentient };
241
+ /**
242
+ * Agent-readable content feed. Merges SDK-known data (winning variants, layout
243
+ * order) with developer-supplied page content, and renders it either as a
244
+ * server-rendered inline JSON-LD block (read by passive AI crawlers, which do
245
+ * not run JS) or as Markdown (for agents that content-negotiate `text/markdown`).
246
+ *
247
+ * No React or DOM APIs — safe to import in server components, route handlers,
248
+ * and middleware.
249
+ */
250
+ type AgentBlock = {
251
+ /** Component ID. */
252
+ id: string;
253
+ /** Winning variant ID currently served. */
254
+ variant: string;
255
+ /** Agent-readable data attached to the served variant, if any. */
256
+ content?: unknown;
257
+ };
258
+ type AgentFeed = {
259
+ page: string;
260
+ title?: string;
261
+ summary?: string;
262
+ layoutOrder?: string[];
263
+ blocks: AgentBlock[];
264
+ /** Developer-supplied extra fields (products, specs, arbitrary JSON). */
265
+ [key: string]: unknown;
266
+ };
267
+ /**
268
+ * Register page-level structured content the SDK can't infer (title, summary,
269
+ * product fields, arbitrary JSON), keyed by page path. Call at module load.
270
+ */
271
+ declare function defineAgentContent(page: string, content: Record<string, unknown>): void;
272
+ /** Look up registered content for a page. */
273
+ declare function getAgentContent(page: string): Record<string, unknown> | undefined;
274
+ /**
275
+ * Merge SDK-known data with developer-supplied content into a single feed.
276
+ * Developer content fills in title/summary/etc. but can never overwrite the
277
+ * SDK-authoritative fields (`page`, `blocks`, `layoutOrder`).
278
+ */
279
+ declare function buildAgentFeed(input: {
280
+ page: string;
281
+ blocks: AgentBlock[];
282
+ layoutOrder?: string[];
283
+ content?: Record<string, unknown>;
284
+ }): AgentFeed;
285
+ /**
286
+ * Render the feed as a server-rendered inline JSON-LD `<script>` string. `<` is
287
+ * escaped to `<` so embedded content cannot break out of the script
288
+ * element. MUST be emitted on the server — passive crawlers never run client JS.
289
+ */
290
+ declare function renderAgentJsonLd(feed: AgentFeed): string;
291
+ /**
292
+ * The escaped JSON-LD body only (no `<script>` wrapper). For React server
293
+ * components, inject via `<script type="application/ld+json"
294
+ * dangerouslySetInnerHTML={{ __html: renderAgentJsonLdBody(feed) }} />`.
295
+ */
296
+ declare function renderAgentJsonLdBody(feed: AgentFeed): string;
297
+ /** Render the feed as Markdown for agents that negotiate `text/markdown`. */
298
+ declare function renderAgentMarkdown(feed: AgentFeed): string;
299
+
300
+ export { Adaptive, type AdaptiveProps, AdaptiveProvider, type AdaptiveProviderProps, AdaptiveText, type AdaptiveTextProps, type AgentBlock, type AgentFeed, type AssignmentState, type ClickGoal, type ComponentWeights, type CompositeGoal, type FireGoal, type FormSubmitGoal, type GoalConfig, type MicroSignalGoalConfig, type MicroSignalGoals, type ScrollDepthGoal, type SsrFallback, type VariantWeight, type WeightedCompositeGoal, type WeightedStep, buildAgentFeed, defineAgentContent, getAgentContent, getWeights, renderAgentJsonLd, renderAgentJsonLdBody, renderAgentMarkdown, subscribe as subscribeWeights, update as updateWeights, useAdaptiveGoal, useAssignment, useInitialAssignments, useLayoutOrder, useSentient };
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
1
  'use client';
2
- "use strict";var V=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames,ee=Object.getOwnPropertySymbols;var ne=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable;var te=(e,t,n)=>t in e?V(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Y=(e,t)=>{for(var n in t||(t={}))ne.call(t,n)&&te(e,n,t[n]);if(ee)for(var n of ee(t))Ae.call(t,n)&&te(e,n,t[n]);return e};var be=(e,t)=>{for(var n in t)V(e,n,{get:t[n],enumerable:!0})},we=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Se(t))!ne.call(e,i)&&i!==n&&V(e,i,{get:()=>t[i],enumerable:!(o=he(t,i))||o.enumerable});return e};var xe=e=>we(V({},"__esModule",{value:!0}),e);var _e={};be(_e,{Adaptive:()=>de,AdaptiveProvider:()=>re,AdaptiveText:()=>fe,detectSegment:()=>Z.deriveSessionSegment,getWeights:()=>B,subscribeWeights:()=>$,updateWeights:()=>H,useAdaptiveGoal:()=>ve,useAssignment:()=>q,useInitialAssignments:()=>X,useLayoutOrder:()=>se,useSentient:()=>G});module.exports=xe(_e);var p=require("react"),D=require("@sentientui/core");var ie=new Map,j=new Map;function $(e,t){let n=j.get(e);return n||(n=new Set,j.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&j.delete(e)}}function H(e,t){ie.set(e,t);let n=j.get(e);if(n)for(let o of n)try{o(t)}catch(i){}}function B(e){var t;return(t=ie.get(e))!=null?t:null}var ae=require("react/jsx-runtime");function Ce(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{let n=(0,D.detectDeviceClass)((e=navigator.userAgent)!=null?e:""),o=(0,D.detectTrafficSource)((t=document.referrer)!=null?t:"",window.location.origin);return`${n}:${o}`}catch(n){return"desktop:direct"}}var M=(0,p.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null});function re(e){var c;let[t,n]=(0,p.useState)(null),[o]=(0,p.useState)(()=>{var a;return(a=e.sessionSegment)!=null?a:Ce()});(0,p.useEffect)(()=>{if(e.consent===!1&&!e.preConsentBehavior){n(v=>(v==null||v.destroy(),null));return}let a=(0,D.init)({apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:o,consent:e.consent,preConsentBehavior:e.preConsentBehavior,ssrSessionId:e.ssrSessionId,country:e.country});return n(a),()=>{a.destroy()}},[e.consent]),(0,p.useEffect)(()=>{if(!t)return;let a=!1,v=async()=>{if(a)return;let I;try{I=await t.fetchWeights()}catch(s){return}if(!a)for(let s of I){let _={componentId:s.componentId,updatedAt:s.updatedAt,variants:s.variants.map(u=>{var y;return{variantId:u.variantId,pulls:u.pulls,avgReward:(y=u.avgReward)!=null?y:0}})};H(s.componentId,_)}};v();let C=setInterval(()=>{v()},6e4);return()=>{a=!0,clearInterval(C)}},[t]);let i=(c=e.ssrFallback)!=null?c:"first",w=(0,p.useMemo)(()=>{var a,v;return{client:t,apiKey:e.apiKey,initialAssignments:(a=e.initialAssignments)!=null?a:{},sessionSegment:o,ssrFallback:i,onAssignment:e.onAssignment,initialLayoutOrder:(v=e.initialLayoutOrder)!=null?v:null}},[t,e.apiKey,e.initialAssignments,o,i,e.onAssignment,e.initialLayoutOrder]);return(0,ae.jsx)(M.Provider,{value:w,children:e.children})}function G(){return(0,p.useContext)(M).client}function J(){return(0,p.useContext)(M).apiKey}function X(){return(0,p.useContext)(M).initialAssignments}function z(){return(0,p.useContext)(M).sessionSegment}function oe(){return(0,p.useContext)(M).ssrFallback}function U(){return(0,p.useContext)(M).onAssignment}function se(){return(0,p.useContext)(M).initialLayoutOrder}var m=require("react"),ue=require("@sentientui/core");var R=require("react");function Ie(e){var n;if(typeof window=="undefined")return null;let t=(n=window.__sentient_overrides)==null?void 0:n[e];if(t)return t;try{let o=new URLSearchParams(window.location.search);for(let i of o.getAll("sentient_variant")){let w=i.indexOf(":");if(w!==-1&&i.slice(0,w)===e)return i.slice(w+1)}}catch(o){}return null}function le(e,t){var o;let n=null;for(let i of e.variants)t.includes(i.variantId)&&(!n||i.avgReward>n.avgReward)&&(n={variantId:i.variantId,avgReward:i.avgReward});return(o=n==null?void 0:n.variantId)!=null?o:null}function q(e,t,n,o){let i=X(),w=oe(),c=G(),a=z(),v=U(),C=(0,R.useRef)(null),I=Ie(e),s=I&&t.includes(I)?I:null,_=(0,R.useRef)(null);s&&_.current!==s&&(_.current=s,console.info(`[sentient] override active: ${e} -> ${s}`));let u=(()=>{var r,l;if(s)return{variantId:s,content:null,isLoading:!1};if(!c){let g=i[e];return g&&t.includes(g)?{variantId:g,content:null,isLoading:!1}:w==="first"&&t.length>0?{variantId:t[0],content:null,isLoading:!1}:{variantId:null,content:null,isLoading:!0}}let d=c.getAssignment(e,a);if(d&&(t.includes(d.variantId)||d.content))return{variantId:d.variantId,content:(r=d.content)!=null?r:null,isLoading:!1};let h=B(e);if(h){let g=le(h,t);if(g)return{variantId:g,content:null,isLoading:!1}}return{variantId:(l=t[0])!=null?l:null,content:null,isLoading:!1}})(),[y,S]=(0,R.useState)(u),O=d=>{v&&C.current!==d&&(C.current=d,v(e,d))};return(0,R.useEffect)(()=>{var h;if(s||!c)return;let d=c.getAssignment(e,a);if(d&&(t.includes(d.variantId)||d.content)){S({variantId:d.variantId,content:(h=d.content)!=null?h:null,isLoading:!1}),O(d.variantId);return}S(r=>{var l;return r.variantId?r:{variantId:(l=t[0])!=null?l:null,content:null,isLoading:!1}})},[s,c,e,a]),(0,R.useEffect)(()=>{if(s||!c)return;let d=c.getAssignment(e,a);if(d&&t.includes(d.variantId))return;let h=!1;return c.assign(e,t,n,o).then(r=>{var l;h||r&&(!t.includes(r.variantId)&&!r.content||(S({variantId:r.variantId,content:(l=r.content)!=null?l:null,isLoading:!1}),O(r.variantId)))}),()=>{h=!0}},[s,c,e,a]),(0,R.useEffect)(()=>{if(!s&&c)return $(e,d=>{var l;let h=c.getAssignment(e,a);if(h&&(t.includes(h.variantId)||h.content)){S({variantId:h.variantId,content:(l=h.content)!=null?l:null,isLoading:!1});return}let r=le(d,t);r&&S({variantId:r,content:null,isLoading:!1})})},[s,c,e,a]),s?{variantId:s,content:null,isLoading:!1}:y}var ge=require("react/jsx-runtime");function ke(e){return typeof e=="string"?{type:"click"}:e}var Ee=3e4;function Le(e,t){try{let n=`_snt_pv_${e}_${t}`;return sessionStorage.getItem(n)?!1:(sessionStorage.setItem(n,"1"),!0)}catch(n){return!0}}function Ge(e){if(!(e instanceof Element))return!1;let t=e.tagName.toLowerCase();return t==="a"||t==="button"?!0:e.getAttribute("role")==="button"}function ce(e,t,n){if(n){try{let i=e;for(;i&&i!==t;){if(i.matches(n))return!0;i=i.parentElement}}catch(i){}return!1}let o=e;for(;o&&o!==t;){if(Ge(o))return!0;o=o.parentElement}return!1}function Re(e){var d,h;let t=G(),n=J(),o=(0,m.useMemo)(()=>Object.keys(e.variants),[e.variants]),{variantId:i,content:w}=q(e.id,o,e.agentData,e.agentDataByVariant),c=(0,m.useRef)(null),[a,v]=(0,m.useState)(!1);(0,m.useEffect)(()=>{v(!0)},[]);let C=(0,m.useRef)(!1),I=(0,m.useRef)(new Set),s=(0,m.useRef)(null),_=typeof e.goal=="string"?e.goal:JSON.stringify(e.goal),u=(0,m.useMemo)(()=>ke(e.goal),[_]),y=typeof e.goal=="string"?e.goal:u.type;if((0,m.useEffect)(()=>{var g,E;if(!t||!i||!n||s.current===i)return;let r=(E=(g=c.current)==null?void 0:g.innerHTML)!=null?E:"";if(!r)return;s.current=i;let l=r!==""&&Le(e.id,i);t.track({projectId:n,componentId:e.id,variantId:i,eventType:"variant_assigned",payload:l?{previewHtml:r.slice(0,Ee)}:{}})},[t,i,n,e.id,a,w]),(0,m.useEffect)(()=>{C.current=!1,I.current=new Set},[i,u]),(0,m.useEffect)(()=>{if(!t||!i)return;let r=c.current;if(!r)return;let l=null,g=0,E=()=>{g=Date.now(),l=setTimeout(()=>{t.track({projectId:n,componentId:e.id,variantId:i,eventType:"cursor_signal",payload:{hoverDuration:Date.now()-g}}),l=null},800)},A=()=>{l!==null&&(clearTimeout(l),l=null)};return r.addEventListener("mouseenter",E),r.addEventListener("mouseleave",A),()=>{r.removeEventListener("mouseenter",E),r.removeEventListener("mouseleave",A),l!==null&&clearTimeout(l)}},[t,i,n,e.id]),(0,m.useEffect)(()=>{if(!t||!i)return;let r=c.current;if(!r)return;let l=Date.now();return(0,ue.attachMicroSignalDetectors)((g,E={})=>{var f,x,L;t.track({projectId:n,componentId:e.id,variantId:i,eventType:"micro_signal",payload:Y({signalType:g},E)});let A=(f=e.microSignalGoals)==null?void 0:f[g];if(!A||I.current.has(g))return;I.current.add(g);let P=typeof A=="string"?A:A.name,b=typeof A=="string"?1:(x=A.weight)!=null?x:1,k=typeof A=="string"?0:(L=A.stepIndex)!=null?L:0;t.goal(P,Y({signalType:g},E),b,k)},r,l)},[t,i,n,e.id,e.microSignalGoals]),(0,m.useEffect)(()=>{if(!t||!i)return;let r=c.current;if(!r)return;if(u.type==="weighted_composite"){let b=new Set,k=[];return u.steps.forEach(({goal:f,name:x,weight:L},N)=>{let Q=()=>{b.has(N)||(b.add(N),t.track({projectId:n,componentId:e.id,variantId:i,eventType:"goal_achieved",goalType:x,payload:{reward:L}}),t.goal(x,{},L,N))};if(f.type==="click"){let T=W=>{let K=W.target;K instanceof Element&&ce(K,r,f.selector)&&Q()};r.addEventListener("click",T),k.push(()=>r.removeEventListener("click",T));return}if(f.type==="form_submit"){let T=W=>{W.target instanceof HTMLFormElement&&r.contains(W.target)&&Q()};r.addEventListener("submit",T),k.push(()=>r.removeEventListener("submit",T));return}if(f.type==="scroll_depth"){let T=Math.max(0,Math.min(1,f.threshold)),W=new IntersectionObserver(K=>{for(let ye of K)if(ye.intersectionRatio>=T){Q(),W.disconnect();break}},{threshold:[T]});W.observe(r),k.push(()=>W.disconnect())}}),()=>{for(let f of k)f()}}let l=()=>{C.current||(C.current=!0,t.track({projectId:n,componentId:e.id,variantId:i,eventType:"goal_achieved",goalType:y,payload:{reward:1}}),t.goal(y,{componentId:e.id,variantId:i},1,0))},g=u.type==="composite"?u.all:[u],E=new Set(g.map((b,k)=>k)),A=b=>{E.delete(b),E.size===0&&l()},P=[];return g.forEach((b,k)=>{if(b.type==="click"){let f=x=>{let L=x.target;L instanceof Element&&ce(L,r,b.selector)&&(u.type==="composite"?A(k):l())};r.addEventListener("click",f),P.push(()=>r.removeEventListener("click",f));return}if(b.type==="form_submit"){let f=x=>{x.target instanceof HTMLFormElement&&r.contains(x.target)&&(u.type==="composite"?A(k):l())};r.addEventListener("submit",f),P.push(()=>r.removeEventListener("submit",f));return}if(b.type==="scroll_depth"){let f=Math.max(0,Math.min(1,b.threshold)),x=new IntersectionObserver(L=>{for(let N of L)if(N.intersectionRatio>=f){u.type==="composite"?A(k):l(),x.disconnect();break}},{threshold:[f]});x.observe(r),P.push(()=>x.disconnect());return}}),()=>{for(let b of P)b()}},[t,i,n,e.id,u,y]),e.clientOnly&&(!a||!t)||!i)return null;let S=(d=e.variants[i])!=null?d:null,O=S===null?w:null;return((h=process==null?void 0:process.env)==null?void 0:h.NODE_ENV)!=="production"&&S===null&&O===null&&console.warn(`[sentient] <Adaptive id="${e.id}"> was assigned variant "${i}" but no matching key exists in props.variants. If this is a dashboard-managed text variant, use <AdaptiveText id="${e.id}"> instead.`),(0,ge.jsx)("div",{ref:c,"data-sentient-id":e.id,"data-sentient-variant":i,children:S!=null?S:O})}var de=(0,m.memo)(Re,(e,t)=>{if(e.id!==t.id||JSON.stringify(e.goal)!==JSON.stringify(t.goal)||e.microSignalGoals!==t.microSignalGoals)return!1;if(e.variants===t.variants)return!0;let n=Object.keys(e.variants),o=Object.keys(t.variants);return n.length!==o.length?!1:n.every(i=>i in t.variants)});var F=require("react");var me=require("react/jsx-runtime");function fe({id:e,default:t,component:n="span",className:o}){let i=G(),w=J(),c=U(),a=z(),v=(0,F.useRef)(null),[C,I]=(0,F.useState)(()=>{var u,y;return(y=(u=i==null?void 0:i.getAssignment(e,a))==null?void 0:u.content)!=null?y:null}),[s,_]=(0,F.useState)(()=>{var u,y;return(y=(u=i==null?void 0:i.getAssignment(e,a))==null?void 0:u.variantId)!=null?y:null});return(0,F.useEffect)(()=>{var y;if(!i||((y=i.getAssignment(e,a))==null?void 0:y.content)!==void 0)return;let u=!1;return i.assign(e).then(S=>{var O;if(!u){if(!S){((O=process==null?void 0:process.env)==null?void 0:O.NODE_ENV)!=="production"&&console.warn(`[sentient] <AdaptiveText id="${e}"> assignment failed \u2014 showing default text.`);return}_(S.variantId),S.content&&I(S.content)}}),()=>{u=!0}},[i,e,a]),(0,F.useEffect)(()=>{!i||!s||!w||v.current!==s&&(v.current=s,i.track({projectId:w,componentId:e,variantId:s,eventType:"variant_assigned",payload:{}}),c==null||c(e,s))},[i,s,w,e,c]),(0,me.jsx)(n,{className:o,children:C!=null?C:t})}var pe=require("react");function ve(e){let t=G();return(0,pe.useCallback)((n,o)=>{t==null||t.componentGoal(e,n,o)},[t,e])}var Z=require("@sentientui/core");0&&(module.exports={Adaptive,AdaptiveProvider,AdaptiveText,detectSegment,getWeights,subscribeWeights,updateWeights,useAdaptiveGoal,useAssignment,useInitialAssignments,useLayoutOrder,useSentient});
2
+ "use strict";var Ie=Object.create;var K=Object.defineProperty,Le=Object.defineProperties,Re=Object.getOwnPropertyDescriptor,Ge=Object.getOwnPropertyDescriptors,Oe=Object.getOwnPropertyNames,ie=Object.getOwnPropertySymbols,_e=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty,Fe=Object.prototype.propertyIsEnumerable;var re=(e,t,n)=>t in e?K(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,W=(e,t)=>{for(var n in t||(t={}))oe.call(t,n)&&re(e,n,t[n]);if(ie)for(var n of ie(t))Fe.call(t,n)&&re(e,n,t[n]);return e},$=(e,t)=>Le(e,Ge(t));var Te=(e,t)=>{for(var n in t)K(e,n,{get:t[n],enumerable:!0})},se=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Oe(t))!oe.call(e,i)&&i!==n&&K(e,i,{get:()=>t[i],enumerable:!(o=Re(t,i))||o.enumerable});return e};var We=(e,t,n)=>(n=e!=null?Ie(_e(e)):{},se(t||!e||!e.__esModule?K(n,"default",{value:e,enumerable:!0}):n,e)),Me=e=>se(K({},"__esModule",{value:!0}),e);var Be={};Te(Be,{Adaptive:()=>pe,AdaptiveProvider:()=>le,AdaptiveText:()=>ye,buildAgentFeed:()=>we,defineAgentContent:()=>ke,detectSegment:()=>ee.deriveSessionSegment,getAgentContent:()=>te,getWeights:()=>X,renderAgentJsonLd:()=>xe,renderAgentJsonLdBody:()=>ne,renderAgentMarkdown:()=>Ce,subscribeWeights:()=>B,updateWeights:()=>H,useAdaptiveGoal:()=>Se,useAssignment:()=>Y,useInitialAssignments:()=>U,useLayoutOrder:()=>ue,useSentient:()=>R});module.exports=Me(Be);var y=require("react"),P=require("@sentientui/core");var ae=new Map,J=new Map;function B(e,t){let n=J.get(e);return n||(n=new Set,J.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&J.delete(e)}}function H(e,t){ae.set(e,t);let n=J.get(e);if(n)for(let o of n)try{o(t)}catch(i){}}function X(e){var t;return(t=ae.get(e))!=null?t:null}var de=require("react/jsx-runtime");function De(){var e,t;if(typeof window=="undefined")return"desktop:direct";try{let n=(0,P.detectDeviceClass)((e=navigator.userAgent)!=null?e:""),o=(0,P.detectTrafficSource)((t=document.referrer)!=null?t:"",window.location.origin);return`${n}:${o}`}catch(n){return"desktop:direct"}}var M=(0,y.createContext)({client:null,apiKey:"",initialAssignments:{},sessionSegment:"desktop:direct",ssrFallback:"first",onAssignment:void 0,initialLayoutOrder:null});function le(e){var l;let[t,n]=(0,y.useState)(null),[o]=(0,y.useState)(()=>{var s;return(s=e.sessionSegment)!=null?s:De()});(0,y.useEffect)(()=>{if(e.consent===!1&&!e.preConsentBehavior){n(v=>(v==null||v.destroy(),null));return}let s={apiKey:e.apiKey,context:e.context,debug:e.debug,initialAssignments:e.initialAssignments,sessionSegment:o,consent:e.consent,preConsentBehavior:e.preConsentBehavior,respectDoNotTrack:e.respectDoNotTrack,ssrSessionId:e.ssrSessionId,country:e.country},b=!1,f=null;return e.enableGraph?import("@sentientui/core/graph").then(({init:v})=>{b||(f=v($(W({},s),{graph:!0})),n(f))}):(f=(0,P.init)(s),n(f)),()=>{b=!0,f==null||f.destroy()}},[e.consent]),(0,y.useEffect)(()=>{if(!t)return;let s=!1,b=async()=>{if(s)return;let v;try{v=await t.fetchWeights()}catch(a){return}if(!s)for(let a of v){let O={componentId:a.componentId,updatedAt:a.updatedAt,variants:a.variants.map(u=>{var A;return{variantId:u.variantId,pulls:u.pulls,avgReward:(A=u.avgReward)!=null?A:0}})};H(a.componentId,O)}};b();let f=setInterval(()=>{b()},6e4);return()=>{s=!0,clearInterval(f)}},[t]);let i=(l=e.ssrFallback)!=null?l:"first",h=(0,y.useMemo)(()=>{var s,b;return{client:t,apiKey:e.apiKey,initialAssignments:(s=e.initialAssignments)!=null?s:{},sessionSegment:o,ssrFallback:i,onAssignment:e.onAssignment,initialLayoutOrder:(b=e.initialLayoutOrder)!=null?b:null}},[t,e.apiKey,e.initialAssignments,o,i,e.onAssignment,e.initialLayoutOrder]);return(0,de.jsx)(M.Provider,{value:h,children:e.children})}function R(){return(0,y.useContext)(M).client}function z(){return(0,y.useContext)(M).apiKey}function U(){return(0,y.useContext)(M).initialAssignments}function q(){return(0,y.useContext)(M).sessionSegment}function ce(){return(0,y.useContext)(M).ssrFallback}function Q(){return(0,y.useContext)(M).onAssignment}function ue(){return(0,y.useContext)(M).initialLayoutOrder}var p=require("react"),me=require("@sentientui/core");var G=require("react");function Ne(e){var n;if(typeof window=="undefined")return null;let t=(n=window.__sentient_overrides)==null?void 0:n[e];if(t)return t;try{let o=new URLSearchParams(window.location.search);for(let i of o.getAll("sentient_variant")){let h=i.indexOf(":");if(h!==-1&&i.slice(0,h)===e)return i.slice(h+1)}}catch(o){}return null}function ge(e,t){var o;let n=null;for(let i of e.variants)t.includes(i.variantId)&&(!n||i.avgReward>n.avgReward)&&(n={variantId:i.variantId,avgReward:i.avgReward});return(o=n==null?void 0:n.variantId)!=null?o:null}function Y(e,t,n,o){let i=U(),h=ce(),l=R(),s=q(),b=Q(),f=(0,G.useRef)(null),v=Ne(e),a=v&&t.includes(v)?v:null,O=(0,G.useRef)(null);a&&O.current!==a&&(O.current=a,console.info(`[sentient] override active: ${e} -> ${a}`));let u=(()=>{var r,c;if(a)return{variantId:a,content:null,isLoading:!1};if(!l){let g=i[e];return g&&t.includes(g)?{variantId:g,content:null,isLoading:!1}:h==="first"&&t.length>0?{variantId:t[0],content:null,isLoading:!1}:{variantId:null,content:null,isLoading:!0}}let d=l.getAssignment(e,s);if(d&&(t.includes(d.variantId)||d.content))return{variantId:d.variantId,content:(r=d.content)!=null?r:null,isLoading:!1};let S=X(e);if(S){let g=ge(S,t);if(g)return{variantId:g,content:null,isLoading:!1}}return{variantId:(c=t[0])!=null?c:null,content:null,isLoading:!1}})(),[A,k]=(0,G.useState)(u),_=d=>{b&&f.current!==d&&(f.current=d,b(e,d))};return(0,G.useEffect)(()=>{var S;if(a||!l)return;let d=l.getAssignment(e,s);if(d&&(t.includes(d.variantId)||d.content)){k({variantId:d.variantId,content:(S=d.content)!=null?S:null,isLoading:!1}),_(d.variantId);return}k(r=>{var c;return r.variantId?r:{variantId:(c=t[0])!=null?c:null,content:null,isLoading:!1}})},[a,l,e,s]),(0,G.useEffect)(()=>{if(a||!l)return;let d=l.getAssignment(e,s);if(d&&t.includes(d.variantId))return;let S=!1;return l.assign(e,t,n,o).then(r=>{var c;S||r&&(!t.includes(r.variantId)&&!r.content||(k({variantId:r.variantId,content:(c=r.content)!=null?c:null,isLoading:!1}),_(r.variantId)))}),()=>{S=!0}},[a,l,e,s]),(0,G.useEffect)(()=>{if(!a&&l)return B(e,d=>{var c;let S=l.getAssignment(e,s);if(S&&(t.includes(S.variantId)||S.content)){k({variantId:S.variantId,content:(c=S.content)!=null?c:null,isLoading:!1});return}let r=ge(d,t);r&&k({variantId:r,content:null,isLoading:!1})})},[a,l,e,s]),a?{variantId:a,content:null,isLoading:!1}:A}var ve=require("react/jsx-runtime");function Pe(e){return typeof e=="string"?{type:"click"}:e}var je=3e4;function Ke(e,t){try{let n=`_snt_pv_${e}_${t}`;return sessionStorage.getItem(n)?!1:(sessionStorage.setItem(n,"1"),!0)}catch(n){return!0}}function Ve(e){if(!(e instanceof Element))return!1;let t=e.tagName.toLowerCase();return t==="a"||t==="button"?!0:e.getAttribute("role")==="button"}function fe(e,t,n){if(n){try{let i=e;for(;i&&i!==t;){if(i.matches(n))return!0;i=i.parentElement}}catch(i){}return!1}let o=e;for(;o&&o!==t;){if(Ve(o))return!0;o=o.parentElement}return!1}function $e(e){var d,S;let t=R(),n=z(),o=(0,p.useMemo)(()=>Object.keys(e.variants),[e.variants]),{variantId:i,content:h}=Y(e.id,o,e.agentData,e.agentDataByVariant),l=(0,p.useRef)(null),[s,b]=(0,p.useState)(!1);(0,p.useEffect)(()=>{b(!0)},[]);let f=(0,p.useRef)(!1),v=(0,p.useRef)(new Set),a=(0,p.useRef)(null),O=typeof e.goal=="string"?e.goal:JSON.stringify(e.goal),u=(0,p.useMemo)(()=>Pe(e.goal),[O]),A=typeof e.goal=="string"?e.goal:u.type;if((0,p.useEffect)(()=>{var g,I;if(!t||!i||!n||a.current===i)return;let r=(I=(g=l.current)==null?void 0:g.innerHTML)!=null?I:"";if(!r)return;a.current=i;let c=r!==""&&Ke(e.id,i);t.track({projectId:n,componentId:e.id,variantId:i,eventType:"variant_assigned",payload:c?{previewHtml:r.slice(0,je)}:{}})},[t,i,n,e.id,s,h]),(0,p.useEffect)(()=>{f.current=!1,v.current=new Set},[i,u]),(0,p.useEffect)(()=>{if(!t||!i)return;let r=l.current;if(!r)return;let c=null,g=0,I=()=>{g=Date.now(),c=setTimeout(()=>{t.track({projectId:n,componentId:e.id,variantId:i,eventType:"cursor_signal",payload:{hoverDuration:Date.now()-g}}),c=null},800)},w=()=>{c!==null&&(clearTimeout(c),c=null)};return r.addEventListener("mouseenter",I),r.addEventListener("mouseleave",w),()=>{r.removeEventListener("mouseenter",I),r.removeEventListener("mouseleave",w),c!==null&&clearTimeout(c)}},[t,i,n,e.id]),(0,p.useEffect)(()=>{if(!t||!i)return;let r=l.current;if(!r)return;let c=Date.now();return(0,me.attachMicroSignalDetectors)((g,I={})=>{var m,C,L;t.track({projectId:n,componentId:e.id,variantId:i,eventType:"micro_signal",payload:W({signalType:g},I)});let w=(m=e.microSignalGoals)==null?void 0:m[g];if(!w||v.current.has(g))return;v.current.add(g);let N=typeof w=="string"?w:w.name,x=typeof w=="string"?1:(C=w.weight)!=null?C:1,E=typeof w=="string"?0:(L=w.stepIndex)!=null?L:0;t.goal(N,W({signalType:g},I),x,E)},r,c)},[t,i,n,e.id,e.microSignalGoals]),(0,p.useEffect)(()=>{if(!t||!i)return;let r=l.current;if(!r)return;if(u.type==="weighted_composite"){let x=new Set,E=[];return u.steps.forEach(({goal:m,name:C,weight:L},j)=>{let Z=()=>{x.has(j)||(x.add(j),t.track({projectId:n,componentId:e.id,variantId:i,eventType:"goal_achieved",goalType:C,payload:{reward:L}}),t.goal(C,{},L,j))};if(m.type==="click"){let F=T=>{let V=T.target;V instanceof Element&&fe(V,r,m.selector)&&Z()};r.addEventListener("click",F),E.push(()=>r.removeEventListener("click",F));return}if(m.type==="form_submit"){let F=T=>{T.target instanceof HTMLFormElement&&r.contains(T.target)&&Z()};r.addEventListener("submit",F),E.push(()=>r.removeEventListener("submit",F));return}if(m.type==="scroll_depth"){let F=Math.max(0,Math.min(1,m.threshold)),T=new IntersectionObserver(V=>{for(let Ee of V)if(Ee.intersectionRatio>=F){Z(),T.disconnect();break}},{threshold:[F]});T.observe(r),E.push(()=>T.disconnect())}}),()=>{for(let m of E)m()}}let c=()=>{f.current||(f.current=!0,t.track({projectId:n,componentId:e.id,variantId:i,eventType:"goal_achieved",goalType:A,payload:{reward:1}}),t.goal(A,{componentId:e.id,variantId:i},1,0))},g=u.type==="composite"?u.all:[u],I=new Set(g.map((x,E)=>E)),w=x=>{I.delete(x),I.size===0&&c()},N=[];return g.forEach((x,E)=>{if(x.type==="click"){let m=C=>{let L=C.target;L instanceof Element&&fe(L,r,x.selector)&&(u.type==="composite"?w(E):c())};r.addEventListener("click",m),N.push(()=>r.removeEventListener("click",m));return}if(x.type==="form_submit"){let m=C=>{C.target instanceof HTMLFormElement&&r.contains(C.target)&&(u.type==="composite"?w(E):c())};r.addEventListener("submit",m),N.push(()=>r.removeEventListener("submit",m));return}if(x.type==="scroll_depth"){let m=Math.max(0,Math.min(1,x.threshold)),C=new IntersectionObserver(L=>{for(let j of L)if(j.intersectionRatio>=m){u.type==="composite"?w(E):c(),C.disconnect();break}},{threshold:[m]});C.observe(r),N.push(()=>C.disconnect());return}}),()=>{for(let x of N)x()}},[t,i,n,e.id,u,A]),e.clientOnly&&(!s||!t)||!i)return null;let k=(d=e.variants[i])!=null?d:null,_=k===null?h:null;return((S=process==null?void 0:process.env)==null?void 0:S.NODE_ENV)!=="production"&&k===null&&_===null&&console.warn(`[sentient] <Adaptive id="${e.id}"> was assigned variant "${i}" but no matching key exists in props.variants. If this is a dashboard-managed text variant, use <AdaptiveText id="${e.id}"> instead.`),(0,ve.jsx)("div",{ref:l,"data-sentient-id":e.id,"data-sentient-variant":i,children:k!=null?k:_})}var pe=(0,p.memo)($e,(e,t)=>{if(e.id!==t.id||JSON.stringify(e.goal)!==JSON.stringify(t.goal)||e.microSignalGoals!==t.microSignalGoals)return!1;if(e.variants===t.variants)return!0;let n=Object.keys(e.variants),o=Object.keys(t.variants);return n.length!==o.length?!1:n.every(i=>i in t.variants)});var D=require("react");var he=require("react/jsx-runtime");function ye({id:e,default:t,component:n="span",className:o}){let i=R(),h=z(),l=Q(),s=q(),b=(0,D.useRef)(null),[f,v]=(0,D.useState)(()=>{var u,A;return(A=(u=i==null?void 0:i.getAssignment(e,s))==null?void 0:u.content)!=null?A:null}),[a,O]=(0,D.useState)(()=>{var u,A;return(A=(u=i==null?void 0:i.getAssignment(e,s))==null?void 0:u.variantId)!=null?A:null});return(0,D.useEffect)(()=>{var A;if(!i||((A=i.getAssignment(e,s))==null?void 0:A.content)!==void 0)return;let u=!1;return i.assign(e).then(k=>{var _;if(!u){if(!k){((_=process==null?void 0:process.env)==null?void 0:_.NODE_ENV)!=="production"&&console.warn(`[sentient] <AdaptiveText id="${e}"> assignment failed \u2014 showing default text.`);return}O(k.variantId),k.content&&v(k.content)}}),()=>{u=!0}},[i,e,s]),(0,D.useEffect)(()=>{!i||!a||!h||b.current!==a&&(b.current=a,i.track({projectId:h,componentId:e,variantId:a,eventType:"variant_assigned",payload:{}}),l==null||l(e,a))},[i,a,h,e,l]),(0,he.jsx)(n,{className:o,children:f!=null?f:t})}var Ae=require("react");function Se(e){let t=R();return(0,Ae.useCallback)((n,o)=>{t==null||t.componentGoal(e,n,o)},[t,e])}var ee=require("@sentientui/core");var Je=["page","blocks","layoutOrder"],be=new Map;function ke(e,t){be.set(e,t)}function te(e){return be.get(e)}function we(e){var i,h;let t=(h=(i=e.content)!=null?i:te(e.page))!=null?h:{},n={};for(let[l,s]of Object.entries(t))Je.includes(l)||(n[l]=s);let o=$(W({},n),{page:e.page,blocks:e.blocks});return e.layoutOrder&&(o.layoutOrder=e.layoutOrder),o}function xe(e){return`<script type="application/ld+json">${ne(e)}</script>`}function ne(e){return JSON.stringify(W({"@context":"https://schema.org","@type":"WebPage"},e)).replace(/</g,"\\u003c")}function Ce(e){let t=[];e.title&&t.push(`# ${e.title}`,""),e.summary&&t.push(String(e.summary),"");for(let[n,o]of Object.entries(e))["page","title","summary","blocks","layoutOrder"].includes(n)||t.push(`## ${n}`,"","```json",JSON.stringify(o,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(`
3
+ `).trimEnd()+`
4
+ `}0&&(module.exports={Adaptive,AdaptiveProvider,AdaptiveText,buildAgentFeed,defineAgentContent,detectSegment,getAgentContent,getWeights,renderAgentJsonLd,renderAgentJsonLdBody,renderAgentMarkdown,subscribeWeights,updateWeights,useAdaptiveGoal,useAssignment,useInitialAssignments,useLayoutOrder,useSentient});
3
5
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../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":["export { AdaptiveProvider, useSentient, useInitialAssignments, useLayoutOrder } from './provider.js';\nexport type { AdaptiveProviderProps, SsrFallback } from './provider.js';\n\nexport { Adaptive } from './adaptive.js';\nexport type {\n AdaptiveProps,\n GoalConfig,\n ClickGoal,\n ScrollDepthGoal,\n FormSubmitGoal,\n CompositeGoal,\n WeightedStep,\n WeightedCompositeGoal,\n MicroSignalGoals,\n MicroSignalGoalConfig,\n} from './adaptive.js';\n\nexport { AdaptiveText } from './adaptive-text.js';\nexport type { AdaptiveTextProps } from './adaptive-text.js';\n\nexport { useAssignment } from './use-assignment.js';\nexport type { AssignmentState } from './use-assignment.js';\n\nexport { useAdaptiveGoal } from './use-adaptive-goal.js';\nexport type { FireGoal } from './use-adaptive-goal.js';\n\nexport {\n subscribe as subscribeWeights,\n update as updateWeights,\n getWeights,\n} from './weights-store.js';\nexport type { ComponentWeights, VariantWeight } from './weights-store.js';\n\nexport { detectSegment } from './segment.js';\n","'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":";+sBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,cAAAE,GAAA,qBAAAC,GAAA,iBAAAC,GAAA,wDAAAC,EAAA,qBAAAC,EAAA,kBAAAC,EAAA,oBAAAC,GAAA,kBAAAC,EAAA,0BAAAC,EAAA,mBAAAC,GAAA,gBAAAC,IAAA,eAAAC,GAAAb,ICIA,IAAAc,EAAwF,iBACxFC,EAMO,4BCKP,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,OAAOD,CAAE,EACVC,EAAK,OAAS,GAAGJ,EAAU,OAAOE,CAAW,CACnD,CACF,CAMO,SAASG,EAAOH,EAAqBI,EAAiC,CAC3EP,GAAM,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,GAAM,IAAIG,CAAW,IAArB,KAAAO,EAA0B,IACnC,CDu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B,EACA,UAAW,mBACX,QAAS,CAAC,CACZ,CAAC,EACDT,GAAA,MAAAA,EAAeR,EAAIiB,GACrB,EAAG,CAACb,EAAQa,EAAWX,EAAQN,EAAIQ,CAAY,CAAC,KAEzC,QAACN,EAAA,CAAI,UAAWC,EAAY,SAAAU,GAAA,KAAAA,EAAQZ,EAAY,CACzD,CCxEA,IAAAoB,GAA4B,iBAoBrB,SAASC,GAAgBC,EAA+B,CAC7D,IAAMC,EAASC,EAAY,EAC3B,SAAO,gBACL,CAACC,EAAUC,IAAS,CAClBH,GAAA,MAAAA,EAAQ,cAAcD,EAAaG,EAAUC,EAC/C,EACA,CAACH,EAAQD,CAAW,CACtB,CACF,CC3BA,IAAAK,EAAsD","names":["src_exports","__export","Adaptive","AdaptiveProvider","AdaptiveText","getWeights","subscribe","update","useAdaptiveGoal","useAssignment","useInitialAssignments","useLayoutOrder","useSentient","__toCommonJS","import_react","import_core","store","listeners","subscribe","componentId","cb","set","update","weights","e","getWeights","_a","import_jsx_runtime","deriveDefaultSegment","_a","_b","device","source","e","AdaptiveContext","AdaptiveProvider","props","client","setClient","sessionSegment","prev","c","cancelled","poll","entries","entry","weights","v","update","timerId","ssrFallback","value","useSentient","useAdaptiveApiKey","useInitialAssignments","AdaptiveContext","useSessionSegment","useSsrFallback","useOnAssignment","useLayoutOrder","import_react","import_core","import_react","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","devOverride","overrideVariant","overrideLoggedRef","initial","_b","preloaded","cached","getWeights","chosen","state","setState","reportAssignment","variantId","prev","cancelled","result","subscribe","import_jsx_runtime","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","content","useAssignment","containerRef","mounted","setMounted","goalFiredRef","microGoalFiredRef","assignTrackedRef","goalKey","goalLabel","rawHtml","includePreview","node","timerId","hoverStart","onEnter","onLeave","assignedAt","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","prev","next","prevKeys","nextKeys","k","import_react","import_jsx_runtime","AdaptiveText","id","defaultText","Tag","className","client","useSentient","apiKey","useAdaptiveApiKey","onAssignment","useOnAssignment","segment","useSessionSegment","trackedRef","text","setText","_a","_b","variantId","setVariantId","cancelled","result","import_react","useAdaptiveGoal","componentId","client","useSentient","goalType","opts","import_core"]}
1
+ {"version":3,"sources":["../src/index.ts","../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","../src/agent-feed.ts"],"sourcesContent":["export { AdaptiveProvider, useSentient, useInitialAssignments, useLayoutOrder } from './provider.js';\nexport type { AdaptiveProviderProps, SsrFallback } from './provider.js';\n\nexport { Adaptive } from './adaptive.js';\nexport type {\n AdaptiveProps,\n GoalConfig,\n ClickGoal,\n ScrollDepthGoal,\n FormSubmitGoal,\n CompositeGoal,\n WeightedStep,\n WeightedCompositeGoal,\n MicroSignalGoals,\n MicroSignalGoalConfig,\n} from './adaptive.js';\n\nexport { AdaptiveText } from './adaptive-text.js';\nexport type { AdaptiveTextProps } from './adaptive-text.js';\n\nexport { useAssignment } from './use-assignment.js';\nexport type { AssignmentState } from './use-assignment.js';\n\nexport { useAdaptiveGoal } from './use-adaptive-goal.js';\nexport type { FireGoal } from './use-adaptive-goal.js';\n\nexport {\n subscribe as subscribeWeights,\n update as updateWeights,\n getWeights,\n} from './weights-store.js';\nexport type { ComponentWeights, VariantWeight } from './weights-store.js';\n\nexport { detectSegment } from './segment.js';\n\nexport {\n defineAgentContent,\n getAgentContent,\n buildAgentFeed,\n renderAgentJsonLd,\n renderAgentJsonLdBody,\n renderAgentMarkdown,\n} from './agent-feed.js';\nexport type { AgentFeed, AgentBlock } from './agent-feed.js';\n","'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 * 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\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 // 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","/**\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('', ' ```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AAyB,CACzD,MAAO,sCAAsCI,GAAsBJ,CAAI,CAAC,WAC1E,CAOO,SAASI,GAAsBJ,EAAyB,CAC7D,OAAO,KAAK,UAAUE,EAAA,CAAE,WAAY,qBAAsB,QAAS,WAAcF,EAAM,EACpF,QAAQ,KAAM,SAAS,CAC5B,CAGO,SAASK,GAAoBL,EAAyB,CAC3D,IAAMM,EAAkB,CAAC,EACrBN,EAAK,OAAOM,EAAM,KAAK,KAAKN,EAAK,KAAK,GAAI,EAAE,EAC5CA,EAAK,SAASM,EAAM,KAAK,OAAON,EAAK,OAAO,EAAG,EAAE,EAErD,OAAW,CAACH,EAAGC,CAAC,IAAK,OAAO,QAAQE,CAAI,EAClC,CAAC,OAAQ,QAAS,UAAW,SAAU,aAAa,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":["src_exports","__export","Adaptive","AdaptiveProvider","AdaptiveText","buildAgentFeed","defineAgentContent","getAgentContent","getWeights","renderAgentJsonLd","renderAgentJsonLdBody","renderAgentMarkdown","subscribe","update","useAdaptiveGoal","useAssignment","useInitialAssignments","useLayoutOrder","useSentient","__toCommonJS","import_react","import_core","store","listeners","subscribe","componentId","cb","set","update","weights","e","getWeights","_a","import_jsx_runtime","deriveDefaultSegment","_a","_b","device","source","e","AdaptiveContext","AdaptiveProvider","props","client","setClient","sessionSegment","prev","config","cancelled","created","initGraph","__spreadProps","__spreadValues","poll","entries","entry","weights","v","update","timerId","ssrFallback","value","useSentient","useAdaptiveApiKey","useInitialAssignments","AdaptiveContext","useSessionSegment","useSsrFallback","useOnAssignment","useLayoutOrder","import_react","import_core","import_react","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","devOverride","overrideVariant","overrideLoggedRef","initial","_b","preloaded","cached","getWeights","chosen","state","setState","reportAssignment","variantId","prev","cancelled","result","subscribe","import_jsx_runtime","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","content","useAssignment","containerRef","mounted","setMounted","goalFiredRef","microGoalFiredRef","assignTrackedRef","goalKey","goalLabel","rawHtml","includePreview","node","timerId","hoverStart","onEnter","onLeave","assignedAt","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","prev","next","prevKeys","nextKeys","k","import_react","import_jsx_runtime","AdaptiveText","id","defaultText","Tag","className","client","useSentient","apiKey","useAdaptiveApiKey","onAssignment","useOnAssignment","segment","useSessionSegment","trackedRef","text","setText","_a","_b","variantId","setVariantId","cancelled","result","import_react","useAdaptiveGoal","componentId","client","useSentient","goalType","opts","import_core","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"]}