@sentientui/react 0.26.0 → 0.27.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
@@ -188,7 +188,7 @@ Imported from `@sentientui/react/next`.
188
188
  | Prop | Type | Description |
189
189
  |------|------|-------------|
190
190
  | `components` | `Array<{ id: string; variantIds: string[] }>` *(optional, default `[]`)* | Components to preload server-side. `id` must match `<Adaptive id="…">`. Omit when the tree uses only slots/sections or assigns client-side. |
191
- | `sections` | `string[]` *(optional)* | Page section IDs in default order. When provided, a single `POST /v1/decide` returns both layout order and assignments; `useLayoutOrder()` becomes available. |
191
+ | `sections` | `string[]` *(optional)* | Page section IDs in default order. When provided, a single `POST /v1/decide` returns both layout order and assignments; `useLayoutOrder()` becomes available. Give each section's element `data-sentient-id="<sectionId>"` (optionally an explicit `data-sentient-type`) so the graph scanner can register it — without it the server types the section `generic` and every persona gets the same order. The provider warns about unresolvable ids in development. |
192
192
  | `apiKey` | `string` | `pk_…` key — used by both the browser SDK and server-side SSR requests. |
193
193
  | `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. |
194
194
  | `context` | `'landing' \| 'ecommerce' \| 'saas' \| 'marketplace'` | Type of product. Used for segment weighting and analytics grouping. |
package/dist/devtools.js CHANGED
@@ -1,3 +1,3 @@
1
1
  'use client';
2
- "use strict";"use client";var _e=Object.create;var x=Object.defineProperty,we=Object.defineProperties,be=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyDescriptors,he=Object.getOwnPropertyNames,U=Object.getOwnPropertySymbols,xe=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty,Oe=Object.prototype.propertyIsEnumerable;var Y=(e,t,o)=>t in e?x(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,l=(e,t)=>{for(var o in t||(t={}))z.call(t,o)&&Y(e,o,t[o]);if(U)for(var o of U(t))Oe.call(t,o)&&Y(e,o,t[o]);return e},w=(e,t)=>we(e,Se(t));var Re=(e,t)=>{for(var o in t)x(e,o,{get:t[o],enumerable:!0})},H=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of he(t))!z.call(e,d)&&d!==o&&x(e,d,{get:()=>t[d],enumerable:!(r=be(t,d))||r.enumerable});return e};var ke=(e,t,o)=>(o=e!=null?_e(xe(e)):{},H(t||!e||!e.__esModule?x(o,"default",{value:e,enumerable:!0}):o,e)),Ce=e=>H(x({},"__esModule",{value:!0}),e);var Fe={};Re(Fe,{AdaptiveDevtools:()=>je,LOCAL_MODE_DEVTOOLS_BANNER:()=>ee});module.exports=Ce(Fe);var u=require("react"),b=require("@sentientui/policy"),S=require("@sentientui/core");var Ee={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function O(){if(typeof window=="undefined")return Ee;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function k(){return[...O().components.values()]}function I(){return[...O().slots.values()]}function C(){return[...O().sections]}function J(e){let t=O().listeners;return t.add(e),()=>{t.delete(e)}}function K(){return O().version}function B(){let e=window;return e.__sentient_overrides||(e.__sentient_overrides={}),e.__sentient_overrides}function N(e,t){B()[e]=t}function T(e){delete B()[e]}function E(){return l({},B())}function V(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function M(e,t){V()[e]=t}function X(e){delete V()[e]}function P(){return l({},V())}var Pe={on:!1,listeners:new Set};function $(){if(typeof window=="undefined")return Pe;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function m(e){let t=$();if(t.on!==e){t.on=e;for(let o of t.listeners)o()}}function q(){return $().on}var Ae="sentient:overrides-changed";function p(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(Ae))}function Q(){var e;return typeof window=="undefined"?null:(e=window.__sentient_devtools_config)!=null?e:null}var i=require("react/jsx-runtime"),Z,Le=typeof process!="undefined"&&((Z=process.env)==null?void 0:Z.NODE_ENV)==="production",De="https://api.sentient-ui.com/v1",ee="Local mode \u2014 decisions are simulated; add a key to learn from real traffic";function te(){let e=window.__sentient_layout_override,t=C();return!e||e.length===0?t:[...e,...t.filter(o=>!e.includes(o))]}function We(e,t){let o=te();if(e===t||e<0||t<0||e>=o.length||t>=o.length)return;let r=[...o],[d]=r.splice(e,1);r.splice(t,0,d),window.__sentient_layout_override=r,m(!0),p()}function Ie(){delete window.__sentient_layout_override,p()}function ne(e){var o,r;for(let[d,c]of Object.entries((o=e.assignments)!=null?o:{}))N(d,c);let t=window;e.layoutOrder&&e.layoutOrder.length>0&&(t.__sentient_layout_override=e.layoutOrder),e.slots&&(t.__sentient_slot_overrides=l(l({},(r=t.__sentient_slot_overrides)!=null?r:{}),e.slots)),e.personaAttributes&&(document.documentElement.dataset.sentientPersona=e.personaAttributes.persona,document.documentElement.dataset.sentientConfidence=e.personaAttributes.confidence),m(!0),p()}function Be(e){var o,r;let t=d=>{try{let c=document.cookie.match(new RegExp(`(?:^|; )${d}=([^;]*)`));return c?decodeURIComponent(c[1]):null}catch(c){return null}};return(r=(o=e?t((0,S.sessionCookieName)(e)):null)!=null?o:t(S.LEGACY_SESSION_COOKIE_NAME))!=null?r:"devtools-preview"}function oe(){return I().map(e=>l(l({id:e.id},e.arms?{arms:e.arms}:{}),e.dims?{dims:e.dims}:{}))}async function Ne(e,t,o){var c;let r=await fetch(`${t}/explain`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({persona:o,sections:C().map(g=>({id:g})),components:k().map(g=>({id:g.id,variantIds:g.variantIds})),slots:oe()})});if(!r.ok)return;let d=await r.json();ne(w(l({},d),{personaAttributes:(c=d.personaAttributes)!=null?c:{persona:o,confidence:"high"}}))}async function Te(e,t){let o=await import("@sentientui/core/local");if(!o.LOCAL_ENGINE_AVAILABLE)return;let r=o.createLocalEngine({sessionId:Be(t),forcedPersona:e}).decide({sections:C(),components:k().map(d=>({id:d.id,variantIds:d.variantIds})),slots:oe()});ne({assignments:r.assignments,layoutOrder:r.layoutOrder,slots:r.slots,personaAttributes:{persona:r.persona,confidence:(0,b.confidenceBand)(r.confidence)}})}function Ve(){for(let t of Object.keys(E()))T(t);let e=window;delete e.__sentient_layout_override,delete e.__sentient_slot_overrides,delete document.documentElement.dataset.sentientPersona,delete document.documentElement.dataset.sentientConfidence;try{let t=[];for(let o=0;o<localStorage.length;o++){let r=localStorage.key(o);r&&r.startsWith(S.SNAPSHOT_STORAGE_KEY_PREFIX)&&t.push(r)}for(let o of t)localStorage.removeItem(o)}catch(t){}m(!1),p();try{window.location.reload()}catch(t){}}var y=e=>({padding:"2px 8px",borderRadius:4,border:"1px solid #444",background:e?"#3b82f6":"#222",color:"#eee",cursor:"pointer"});function Me({size:e=26}={}){return(0,i.jsxs)("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"none","aria-hidden":"true",children:[(0,i.jsx)("path",{d:"M21 9H14C11.2 9 9.8 10.8 9.8 13C9.8 15.4 11.6 16.6 14.5 16.6H18.5C20.5 16.6 20.7 18.2 20.4 19.6",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"}),(0,i.jsx)("path",{d:"M10 22H17",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round"}),(0,i.jsx)("circle",{cx:"20.6",cy:"22",r:"2.1",fill:"#fff"})]})}function je({apiKey:e}={}){var F;let[t,o]=(0,u.useState)(!1),[r,d]=(0,u.useState)(null),[c,g]=(0,u.useState)(null),[ie,re]=(0,u.useState)(!1),[,f]=(0,u.useReducer)(n=>n+1,0);if((0,u.useSyncExternalStore)(J,K,()=>0),(0,u.useEffect)(()=>re(!0),[]),Le||!ie)return null;let _=(F=Q())!=null?F:{apiKey:e!=null?e:"",apiBaseUrl:De,isLocal:!1},se=_.isLocal||!_.apiKey,R=k(),A=I(),L=E(),j=P(),D=te(),de=window.__sentient_layout_override!==void 0;function ae(n,s){We(n,s),f()}function le(){Ie(),W(),f()}function W(){Object.keys(E()).length===0&&Object.keys(P()).length===0&&window.__sentient_layout_override===void 0&&m(!1)}function ce(n,s){N(n,s),m(!0),p(),f()}function ue(n){T(n),W(),p(),f()}function pe(n,s){M(n,s),m(!0),p(),f()}function ge(n,s,a,h){let v=P()[n],G=v&&typeof v=="object"?l({},v):Object.fromEntries(Object.entries(h!=null?h:{}).map(([me,ye])=>[me,ye[0]]));G[s]=a,M(n,G),m(!0),p(),f()}function fe(n){X(n),W(),p(),f()}function ve(n){d(n),(se?Te(n,_.apiKey):Ne(_.apiKey,_.apiBaseUrl,n)).then(f).catch(()=>{})}return(0,i.jsxs)("div",{style:{position:"fixed",bottom:16,right:16,zIndex:2147483647,fontFamily:"system-ui"},children:[(0,i.jsx)("div",{"aria-hidden":!t,style:{position:"absolute",bottom:52,right:0,transformOrigin:"bottom right",transition:"opacity .18s ease, transform .2s cubic-bezier(.16,1,.3,1)",opacity:t?1:0,transform:t?"translateY(0) scale(1)":"translateY(6px) scale(.96)",pointerEvents:t?"auto":"none"},children:(0,i.jsxs)("div",{style:{width:300,maxHeight:460,overflowY:"auto",background:"#111",color:"#eee",borderRadius:8,padding:12,boxShadow:"0 8px 30px rgba(0,0,0,.4)",fontSize:12},children:[_.isLocal&&(0,i.jsx)("div",{style:{background:"#1e293b",border:"1px solid #334155",borderRadius:4,padding:"6px 8px",marginBottom:8},children:ee}),(0,i.jsxs)("div",{style:{opacity:.7,marginBottom:8},children:[R.length," component",R.length===1?"":"s"," \xB7 ",q()?"preview \u2014 writing nothing":"live"]}),(0,i.jsxs)("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[(0,i.jsx)("div",{style:{opacity:.7,marginBottom:4},children:"Preview persona"}),(0,i.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[b.PERSONAS.map(n=>(0,i.jsx)("button",{onClick:()=>ve(n),style:y(r===n),children:b.PERSONA_DISPLAY[n]},n)),(r!==null||Object.keys(L).length>0||Object.keys(j).length>0)&&(0,i.jsx)("button",{onClick:Ve,style:w(l({},y(!1)),{color:"#aaa"}),children:"Reset"})]})]}),D.length>0&&(0,i.jsxs)("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[(0,i.jsx)("span",{style:{opacity:.7},children:"Layout \u2014 drag to reorder"}),de&&(0,i.jsx)("button",{"aria-label":"Reset section order",onClick:le,style:w(l({},y(!1)),{color:"#aaa"}),children:"reset"})]}),(0,i.jsx)("ul",{"aria-label":"Section order",style:{listStyle:"none",margin:0,padding:0},children:D.map((n,s)=>(0,i.jsxs)("li",{draggable:!0,onDragStart:()=>g(s),onDragOver:a=>a.preventDefault(),onDrop:a=>{a.preventDefault(),c!==null&&ae(c,s),g(null)},onDragEnd:()=>g(null),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",marginBottom:2,borderRadius:4,border:"1px solid #262626",cursor:"grab",background:c===s?"#1e293b":"#181818",opacity:c!==null&&c!==s?.6:1},children:[(0,i.jsx)("span",{style:{opacity:.4,minWidth:10,fontVariantNumeric:"tabular-nums"},children:s+1}),(0,i.jsx)("span",{"aria-hidden":"true",style:{opacity:.35},children:"\u283F"}),(0,i.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]},n))})]}),R.length===0&&A.length===0&&D.length===0&&(0,i.jsx)("div",{style:{opacity:.6},children:"No components, sections or slots on this page yet."}),R.map(n=>(0,i.jsxs)("div",{style:{borderTop:"1px solid #333",padding:"8px 0"},children:[(0,i.jsxs)("div",{style:{fontWeight:600},children:[n.id,n.goal?` \xB7 goal: ${n.goal}`:""]}),(0,i.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:[n.variantIds.map(s=>(0,i.jsx)("button",{onClick:()=>ce(n.id,s),style:y(L[n.id]===s),children:s},s)),L[n.id]&&(0,i.jsx)("button",{onClick:()=>ue(n.id),style:w(l({},y(!1)),{color:"#aaa"}),children:"reset"})]})]},n.id)),A.length>0&&(0,i.jsxs)("div",{style:{borderTop:"1px solid #333",paddingTop:8,marginTop:4},children:[(0,i.jsx)("div",{style:{opacity:.7,marginBottom:4},children:"Slots"}),A.map(n=>{let s=j[n.id];return(0,i.jsxs)("div",{style:{padding:"6px 0"},children:[(0,i.jsx)("div",{style:{fontWeight:600},children:n.id}),n.arms&&(0,i.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:n.arms.map(a=>(0,i.jsx)("button",{onClick:()=>pe(n.id,a),style:y(s===a),children:a},a))}),n.dims&&Object.entries(n.dims).map(([a,h])=>(0,i.jsxs)("div",{style:{marginTop:4},children:[(0,i.jsx)("div",{style:{opacity:.6,fontSize:11},children:a}),(0,i.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:h.map(v=>(0,i.jsx)("button",{onClick:()=>ge(n.id,a,v,n.dims),style:y(!!s&&typeof s=="object"&&s[a]===v),children:v},v))})]},a)),s!==void 0&&(0,i.jsx)("button",{onClick:()=>fe(n.id),style:w(l({},y(!1)),{color:"#aaa",marginTop:4}),children:"reset"})]},n.id)})]})]})}),(0,i.jsx)("button",{"aria-label":"Sentient DevTools","aria-expanded":t,onClick:()=>o(n=>!n),style:{width:44,height:44,borderRadius:12,border:"1px solid #2a2a2a",background:"#000",display:"flex",alignItems:"center",justifyContent:"center",padding:0,cursor:"pointer",boxShadow:"0 6px 18px rgba(0,0,0,.4)"},children:(0,i.jsx)(Me,{})})]})}0&&(module.exports={AdaptiveDevtools,LOCAL_MODE_DEVTOOLS_BANNER});
2
+ "use strict";"use client";var Ce=Object.create;var k=Object.defineProperty,Ee=Object.defineProperties,Pe=Object.getOwnPropertyDescriptor,Ae=Object.getOwnPropertyDescriptors,De=Object.getOwnPropertyNames,q=Object.getOwnPropertySymbols,Le=Object.getPrototypeOf,Z=Object.prototype.hasOwnProperty,Ve=Object.prototype.propertyIsEnumerable;var Q=(e,t,o)=>t in e?k(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,l=(e,t)=>{for(var o in t||(t={}))Z.call(t,o)&&Q(e,o,t[o]);if(q)for(var o of q(t))Ve.call(t,o)&&Q(e,o,t[o]);return e},b=(e,t)=>Ee(e,Ae(t));var Ne=(e,t)=>{for(var o in t)k(e,o,{get:t[o],enumerable:!0})},ee=(e,t,o,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let d of De(t))!Z.call(e,d)&&d!==o&&k(e,d,{get:()=>t[d],enumerable:!(r=Pe(t,d))||r.enumerable});return e};var We=(e,t,o)=>(o=e!=null?Ce(Le(e)):{},ee(t||!e||!e.__esModule?k(o,"default",{value:e,enumerable:!0}):o,e)),Me=e=>ee(k({},"__esModule",{value:!0}),e);var Xe={};Ne(Xe,{AdaptiveDevtools:()=>Je,LOCAL_MODE_DEVTOOLS_BANNER:()=>ce});module.exports=Me(Xe);var u=require("react"),x=require("@sentientui/policy"),O=require("@sentientui/core");var Be={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function C(){if(typeof window=="undefined")return Be;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function P(){return[...C().components.values()]}function T(){return[...C().slots.values()]}function A(){return[...C().sections]}function te(e){let t=C().listeners;return t.add(e),()=>{t.delete(e)}}function ne(){return C().version}function j(){let e=window;return e.__sentient_overrides||(e.__sentient_overrides={}),e.__sentient_overrides}function z(e,t){j()[e]=t}function F(e){delete j()[e]}function D(){return l({},j())}function U(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function G(e,t){U()[e]=t}function oe(e){delete U()[e]}function L(){return l({},U())}var Ie={on:!1,listeners:new Set};function ie(){if(typeof window=="undefined")return Ie;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function _(e){let t=ie();if(t.on!==e){t.on=e;for(let o of t.listeners)o()}}function re(){return ie().on}var Te="sentient:overrides-changed";function p(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(Te))}function $(){var e;return typeof window=="undefined"?null:(e=window.__sentient_devtools_config)!=null?e:null}var i=require("react/jsx-runtime"),le,se=typeof process!="undefined"&&((le=process.env)==null?void 0:le.NODE_ENV)==="production",de="https://api.sentient-ui.com/v1",ce="Local mode \u2014 decisions are simulated; add a key to learn from real traffic";function ue(){let e=window.__sentient_layout_override,t=A();return!e||e.length===0?t:[...e,...t.filter(o=>!e.includes(o))]}function je(e,t){let o=ue();if(e===t||e<0||t<0||e>=o.length||t>=o.length)return;let r=[...o],[d]=r.splice(e,1);r.splice(t,0,d),window.__sentient_layout_override=r,_(!0),p()}function ze(){delete window.__sentient_layout_override,p()}function pe(e){var o,r;for(let[d,c]of Object.entries((o=e.assignments)!=null?o:{}))z(d,c);let t=window;e.layoutOrder&&e.layoutOrder.length>0&&(t.__sentient_layout_override=e.layoutOrder),e.slots&&(t.__sentient_slot_overrides=l(l({},(r=t.__sentient_slot_overrides)!=null?r:{}),e.slots)),e.personaAttributes&&(document.documentElement.dataset.sentientPersona=e.personaAttributes.persona,document.documentElement.dataset.sentientConfidence=e.personaAttributes.confidence),_(!0),p()}function Fe(e){var o,r;let t=d=>{try{let c=document.cookie.match(new RegExp(`(?:^|; )${d}=([^;]*)`));return c?decodeURIComponent(c[1]):null}catch(c){return null}};return(r=(o=e?t((0,O.sessionCookieName)(e)):null)!=null?o:t(O.LEGACY_SESSION_COOKIE_NAME))!=null?r:"devtools-preview"}function ge(){return T().map(e=>l(l({id:e.id},e.arms?{arms:e.arms}:{}),e.dims?{dims:e.dims}:{}))}var ae=x.PERSONAS.map(e=>({key:e,displayName:x.PERSONA_DISPLAY[e]}));async function Ue(e,t){try{let o=await fetch(`${t}/personas`,{headers:{authorization:`Bearer ${e}`}});if(!o.ok)return null;let r=await o.json(),d=w=>Array.isArray(w)?w.filter(g=>g&&typeof g.key=="string"&&typeof g.displayName=="string"):[],c=d(r.personas);return c.length>0?{personas:c,discovered:d(r.discovered)}:null}catch(o){return null}}async function Ge(e,t,o){var c,w,g;let r=await fetch(`${t}/explain`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({persona:o,sections:A().map(h=>({id:h})),components:P().map(h=>({id:h.id,variantIds:h.variantIds})),slots:ge()})});if(!r.ok)return null;let d=await r.json();return pe(b(l({},d),{personaAttributes:(c=d.personaAttributes)!=null?c:{persona:o,confidence:"high"}})),{recognized:d.recognized!==!1,resolvedDisplay:(g=(w=d.personaDisplay)!=null?w:d.persona)!=null?g:o}}async function $e(e,t){let o=await import("@sentientui/core/local");if(!o.LOCAL_ENGINE_AVAILABLE)return;let r=o.createLocalEngine({sessionId:Fe(t),forcedPersona:e}).decide({sections:A(),components:P().map(d=>({id:d.id,variantIds:d.variantIds})),slots:ge()});pe({assignments:r.assignments,layoutOrder:r.layoutOrder,slots:r.slots,personaAttributes:{persona:r.persona,confidence:(0,x.confidenceBand)(r.confidence)}})}function He(){for(let t of Object.keys(D()))F(t);let e=window;delete e.__sentient_layout_override,delete e.__sentient_slot_overrides,delete document.documentElement.dataset.sentientPersona,delete document.documentElement.dataset.sentientConfidence;try{let t=[];for(let o=0;o<localStorage.length;o++){let r=localStorage.key(o);r&&r.startsWith(O.SNAPSHOT_STORAGE_KEY_PREFIX)&&t.push(r)}for(let o of t)localStorage.removeItem(o)}catch(t){}_(!1),p();try{window.location.reload()}catch(t){}}var y=e=>({padding:"2px 8px",borderRadius:4,border:"1px solid #444",background:e?"#3b82f6":"#222",color:"#eee",cursor:"pointer"});function Ye({size:e=26}={}){return(0,i.jsxs)("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"none","aria-hidden":"true",children:[(0,i.jsx)("path",{d:"M21 9H14C11.2 9 9.8 10.8 9.8 13C9.8 15.4 11.6 16.6 14.5 16.6H18.5C20.5 16.6 20.7 18.2 20.4 19.6",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"}),(0,i.jsx)("path",{d:"M10 22H17",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round"}),(0,i.jsx)("circle",{cx:"20.6",cy:"22",r:"2.1",fill:"#fff"})]})}function Je({apiKey:e}={}){var X;let[t,o]=(0,u.useState)(!1),[r,d]=(0,u.useState)(null),[c,w]=(0,u.useState)(null),[g,h]=(0,u.useState)([]),[H,Y]=(0,u.useState)(null),[R,V]=(0,u.useState)(null),[fe,ve]=(0,u.useState)(!1),[,f]=(0,u.useReducer)(n=>n+1,0);if((0,u.useSyncExternalStore)(te,ne,()=>0),(0,u.useEffect)(()=>ve(!0),[]),(0,u.useEffect)(()=>{var a;if(se)return;let n=(a=$())!=null?a:{apiKey:e!=null?e:"",apiBaseUrl:de,isLocal:!1};if(n.isLocal||!n.apiKey)return;let s=!1;return Ue(n.apiKey,n.apiBaseUrl).then(v=>{s||!v||(w(v.personas),h(v.discovered))}),()=>{s=!0}},[e]),se||!fe)return null;let S=(X=$())!=null?X:{apiKey:e!=null?e:"",apiBaseUrl:de,isLocal:!1},N=S.isLocal||!S.apiKey,E=P(),W=T(),M=D(),J=L(),B=ue(),ye=window.__sentient_layout_override!==void 0;function me(n,s){je(n,s),f()}function _e(){ze(),I(),f()}function I(){Object.keys(D()).length===0&&Object.keys(L()).length===0&&window.__sentient_layout_override===void 0&&_(!1)}function we(n,s){z(n,s),_(!0),p(),f()}function be(n){F(n),I(),p(),f()}function he(n,s){G(n,s),_(!0),p(),f()}function Se(n,s,a,v){let m=L()[n],K=m&&typeof m=="object"?l({},m):Object.fromEntries(Object.entries(v!=null?v:{}).map(([Re,ke])=>[Re,ke[0]]));K[s]=a,G(n,K),_(!0),p(),f()}function xe(n){oe(n),I(),p(),f()}function Oe(n){if(d(n.key),Y(null),N){$e(n.key,S.apiKey).then(f).catch(()=>{});return}Ge(S.apiKey,S.apiBaseUrl,n.key).then(s=>{s&&!s.recognized&&Y(`\u201C${n.displayName}\u201D isn\u2019t in this project\u2019s personas \u2014 the page is showing the default experience.`),f()}).catch(()=>{})}return(0,i.jsxs)("div",{style:{position:"fixed",bottom:16,right:16,zIndex:2147483647,fontFamily:"system-ui"},children:[(0,i.jsx)("div",{"aria-hidden":!t,style:{position:"absolute",bottom:52,right:0,transformOrigin:"bottom right",transition:"opacity .18s ease, transform .2s cubic-bezier(.16,1,.3,1)",opacity:t?1:0,transform:t?"translateY(0) scale(1)":"translateY(6px) scale(.96)",pointerEvents:t?"auto":"none"},children:(0,i.jsxs)("div",{style:{width:300,maxHeight:460,overflowY:"auto",background:"#111",color:"#eee",borderRadius:8,padding:12,boxShadow:"0 8px 30px rgba(0,0,0,.4)",fontSize:12},children:[S.isLocal&&(0,i.jsx)("div",{style:{background:"#1e293b",border:"1px solid #334155",borderRadius:4,padding:"6px 8px",marginBottom:8},children:ce}),(0,i.jsxs)("div",{style:{opacity:.7,marginBottom:8},children:[E.length," component",E.length===1?"":"s"," \xB7 ",re()?"preview \u2014 writing nothing":"live"]}),(0,i.jsxs)("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[(0,i.jsx)("div",{style:{opacity:.7,marginBottom:4},children:"Preview persona"}),(0,i.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[(N?ae:c!=null?c:ae).map(n=>(0,i.jsx)("button",{onClick:()=>Oe(n),style:y(r===n.key),children:n.displayName},n.key)),(r!==null||Object.keys(M).length>0||Object.keys(J).length>0)&&(0,i.jsx)("button",{onClick:He,style:b(l({},y(!1)),{color:"#aaa"}),children:"Reset"})]}),H&&(0,i.jsx)("div",{style:{marginTop:6,fontSize:11,color:"#fbbf24"},children:H}),!N&&g.length>0&&(0,i.jsxs)("div",{style:{marginTop:8},children:[(0,i.jsx)("div",{style:{opacity:.5,fontSize:11,marginBottom:4},children:"Discovered \u2014 not serving yet (promote from the dashboard)"}),(0,i.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:g.map(n=>(0,i.jsx)("span",{title:"Found by clustering your traffic; it starts serving only after promotion.",style:b(l({},y(!1)),{opacity:.45,cursor:"default",display:"inline-block"}),children:n.displayName},n.key))})]})]}),B.length>0&&(0,i.jsxs)("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[(0,i.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[(0,i.jsx)("span",{style:{opacity:.7},children:"Layout \u2014 drag to reorder"}),ye&&(0,i.jsx)("button",{"aria-label":"Reset section order",onClick:_e,style:b(l({},y(!1)),{color:"#aaa"}),children:"reset"})]}),(0,i.jsx)("ul",{"aria-label":"Section order",style:{listStyle:"none",margin:0,padding:0},children:B.map((n,s)=>(0,i.jsxs)("li",{draggable:!0,onDragStart:()=>V(s),onDragOver:a=>a.preventDefault(),onDrop:a=>{a.preventDefault(),R!==null&&me(R,s),V(null)},onDragEnd:()=>V(null),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",marginBottom:2,borderRadius:4,border:"1px solid #262626",cursor:"grab",background:R===s?"#1e293b":"#181818",opacity:R!==null&&R!==s?.6:1},children:[(0,i.jsx)("span",{style:{opacity:.4,minWidth:10,fontVariantNumeric:"tabular-nums"},children:s+1}),(0,i.jsx)("span",{"aria-hidden":"true",style:{opacity:.35},children:"\u283F"}),(0,i.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]},n))})]}),E.length===0&&W.length===0&&B.length===0&&(0,i.jsx)("div",{style:{opacity:.6},children:"No components, sections or slots on this page yet."}),E.map(n=>(0,i.jsxs)("div",{style:{borderTop:"1px solid #333",padding:"8px 0"},children:[(0,i.jsxs)("div",{style:{fontWeight:600},children:[n.id,n.goal?` \xB7 goal: ${n.goal}`:""]}),(0,i.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:[n.variantIds.map(s=>(0,i.jsx)("button",{onClick:()=>we(n.id,s),style:y(M[n.id]===s),children:s},s)),M[n.id]&&(0,i.jsx)("button",{onClick:()=>be(n.id),style:b(l({},y(!1)),{color:"#aaa"}),children:"reset"})]})]},n.id)),W.length>0&&(0,i.jsxs)("div",{style:{borderTop:"1px solid #333",paddingTop:8,marginTop:4},children:[(0,i.jsx)("div",{style:{opacity:.7,marginBottom:4},children:"Slots"}),W.map(n=>{let s=J[n.id];return(0,i.jsxs)("div",{style:{padding:"6px 0"},children:[(0,i.jsx)("div",{style:{fontWeight:600},children:n.id}),n.arms&&(0,i.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:n.arms.map(a=>(0,i.jsx)("button",{onClick:()=>he(n.id,a),style:y(s===a),children:a},a))}),n.dims&&Object.entries(n.dims).map(([a,v])=>(0,i.jsxs)("div",{style:{marginTop:4},children:[(0,i.jsx)("div",{style:{opacity:.6,fontSize:11},children:a}),(0,i.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:v.map(m=>(0,i.jsx)("button",{onClick:()=>Se(n.id,a,m,n.dims),style:y(!!s&&typeof s=="object"&&s[a]===m),children:m},m))})]},a)),s!==void 0&&(0,i.jsx)("button",{onClick:()=>xe(n.id),style:b(l({},y(!1)),{color:"#aaa",marginTop:4}),children:"reset"})]},n.id)})]})]})}),(0,i.jsx)("button",{"aria-label":"Sentient DevTools","aria-expanded":t,onClick:()=>o(n=>!n),style:{width:44,height:44,borderRadius:12,border:"1px solid #2a2a2a",background:"#000",display:"flex",alignItems:"center",justifyContent:"center",padding:0,cursor:"pointer",boxShadow:"0 6px 18px rgba(0,0,0,.4)"},children:(0,i.jsx)(Ye,{})})]})}0&&(module.exports={AdaptiveDevtools,LOCAL_MODE_DEVTOOLS_BANNER});
3
3
  //# sourceMappingURL=devtools.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/devtools/index.tsx","../src/devtools-registry.ts","../src/devtools-overrides.ts","../src/devtools-slot-overrides.ts","../src/preview-mode.ts","../src/override-events.ts","../src/devtools-config.ts"],"sourcesContent":["'use client';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport { useEffect, useReducer, useState, useSyncExternalStore, type CSSProperties, type JSX } from 'react';\nimport { PERSONAS, PERSONA_DISPLAY, confidenceBand } from '@sentientui/policy';\nimport { LEGACY_SESSION_COOKIE_NAME, SNAPSHOT_STORAGE_KEY_PREFIX, sessionCookieName } from '@sentientui/core';\nimport {\n getRegistered,\n getRegisteredSlots,\n getRegisteredSections,\n subscribeRegistry,\n getRegistryVersion,\n type RegisteredSlot,\n} from '../devtools-registry.js';\nimport { setVariantOverride, clearVariantOverride, getOverrides } from '../devtools-overrides.js';\nimport { setSlotOverride, clearSlotOverride, getSlotOverrides } from '../devtools-slot-overrides.js';\nimport { setPreviewMode, getPreviewMode } from '../preview-mode.js';\nimport { notifyOverridesChanged } from '../override-events.js';\nimport { readDevtoolsConfig, type DevtoolsConfig } from '../devtools-config.js';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\nconst IS_PROD = typeof process !== 'undefined' && process.env?.NODE_ENV === 'production';\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport const LOCAL_MODE_DEVTOOLS_BANNER =\n 'Local mode — decisions are simulated; add a key to learn from real traffic';\n\ntype OutcomeToApply = {\n assignments?: Record<string, string>;\n layoutOrder?: string[] | null;\n slots?: Record<string, string | Record<string, string>>;\n personaAttributes?: { persona: string; confidence: 'low' | 'medium' | 'high' };\n};\n\ntype OverrideWindow = Window & {\n __sentient_layout_override?: string[];\n __sentient_slot_overrides?: Record<string, string | Record<string, string>>;\n};\n\n/** The order the page is rendering: a previewed override, else what was registered. */\nfunction currentLayout(): string[] {\n const forced = (window as unknown as OverrideWindow).__sentient_layout_override;\n const registered = getRegisteredSections();\n if (!forced || forced.length === 0) return registered;\n // Registered ids the override omits still render (useLayoutOrder returns the\n // override verbatim, and the app maps whatever ids it is given), so show them\n // trailing rather than dropping them from the list you are dragging.\n return [...forced, ...registered.filter((id) => !forced.includes(id))];\n}\n\n/**\n * Move `from` to `to` within the current order and preview it.\n *\n * Writes the whole order rather than swapping neighbours: the point is to try an\n * arrangement, not to walk one block up a list one press at a time.\n */\nfunction reorderLayout(from: number, to: number): void {\n const order = currentLayout();\n if (from === to || from < 0 || to < 0 || from >= order.length || to >= order.length) return;\n const next = [...order];\n const [moved] = next.splice(from, 1);\n next.splice(to, 0, moved!);\n (window as unknown as OverrideWindow).__sentient_layout_override = next;\n setPreviewMode(true); // an arrangement you are trying must not train the bandit\n notifyOverridesChanged();\n}\n\nfunction resetLayout(): void {\n delete (window as unknown as OverrideWindow).__sentient_layout_override;\n notifyOverridesChanged();\n}\n\n/** Apply a simulated outcome across every surface: variants, layout, slots/tokens, persona attrs. */\nfunction applyOutcome(result: OutcomeToApply): void {\n for (const [id, variantId] of Object.entries(result.assignments ?? {})) {\n setVariantOverride(id, variantId);\n }\n const w = window as unknown as OverrideWindow;\n if (result.layoutOrder && result.layoutOrder.length > 0) {\n w.__sentient_layout_override = result.layoutOrder;\n }\n if (result.slots) {\n w.__sentient_slot_overrides = { ...(w.__sentient_slot_overrides ?? {}), ...result.slots };\n }\n if (result.personaAttributes) {\n document.documentElement.dataset.sentientPersona = result.personaAttributes.persona;\n document.documentElement.dataset.sentientConfidence = result.personaAttributes.confidence;\n }\n setPreviewMode(true); // suppress events while previewing\n notifyOverridesChanged(); // re-render layout/slot consumers\n}\n\n// Reads the SDK's own session cookie — the per-project SUFFIXED name first\n// (that is what the client writes since namespacing; the bare `_snt_uid` this\n// used to read is only written in keyless/local mode), then the bare name as\n// the legacy/local fallback.\nfunction readSessionId(apiKey?: string): string {\n const read = (name: string): string | null => {\n try {\n const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return match ? decodeURIComponent(match[1]!) : null;\n } catch {\n return null;\n }\n };\n return (apiKey ? read(sessionCookieName(apiKey)) : null) ?? read(LEGACY_SESSION_COOKIE_NAME) ?? 'devtools-preview';\n}\n\nfunction slotDecls(): Array<{ id: string; arms?: string[]; dims?: RegisteredSlot['dims'] }> {\n return getRegisteredSlots().map((s) => ({\n id: s.id,\n ...(s.arms ? { arms: s.arms } : {}),\n ...(s.dims ? { dims: s.dims } : {}),\n }));\n}\n\n/** Keyed mode: simulate via /v1/explain (read-only, event-free). */\nasync function forcePersonaKeyed(apiKey: string, apiBaseUrl: string, persona: string): Promise<void> {\n const res = await fetch(`${apiBaseUrl}/explain`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify({\n persona,\n sections: getRegisteredSections().map((id) => ({ id })),\n components: getRegistered().map((c) => ({ id: c.id, variantIds: c.variantIds })),\n slots: slotDecls(),\n }),\n });\n if (!res.ok) return;\n const data = (await res.json()) as OutcomeToApply;\n applyOutcome({\n ...data,\n personaAttributes: data.personaAttributes ?? { persona, confidence: 'high' },\n });\n}\n\n/** Local mode: simulate via the deterministic local engine — zero network. */\nasync function forcePersonaLocal(persona: string, apiKey?: string): Promise<void> {\n const mod = await import('@sentientui/core/local');\n if (!mod.LOCAL_ENGINE_AVAILABLE) return;\n const outcome = mod\n .createLocalEngine({ sessionId: readSessionId(apiKey), forcedPersona: persona })\n .decide({\n sections: getRegisteredSections(),\n components: getRegistered().map((c) => ({ id: c.id, variantIds: c.variantIds })),\n slots: slotDecls(),\n });\n applyOutcome({\n assignments: outcome.assignments,\n layoutOrder: outcome.layoutOrder,\n slots: outcome.slots,\n personaAttributes: {\n persona: outcome.persona,\n confidence: confidenceBand(outcome.confidence),\n },\n });\n}\n\n/** Reset: clear the decision snapshot + every override, then reload to re-decide. */\nfunction resetAll(): void {\n for (const id of Object.keys(getOverrides())) clearVariantOverride(id);\n const w = window as unknown as OverrideWindow;\n delete w.__sentient_layout_override;\n delete w.__sentient_slot_overrides;\n delete document.documentElement.dataset.sentientPersona;\n delete document.documentElement.dataset.sentientConfidence;\n try {\n const stale: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key && key.startsWith(SNAPSHOT_STORAGE_KEY_PREFIX)) stale.push(key);\n }\n for (const key of stale) localStorage.removeItem(key);\n } catch {\n /* ignore */\n }\n setPreviewMode(false);\n notifyOverridesChanged();\n try {\n window.location.reload();\n } catch {\n /* jsdom */\n }\n}\n\nconst btn = (active: boolean): CSSProperties => ({\n padding: '2px 8px',\n borderRadius: 4,\n border: '1px solid #444',\n background: active ? '#3b82f6' : '#222',\n color: '#eee',\n cursor: 'pointer',\n});\n\n/** Sentient \"S.\" wordmark, monoline — white strokes for the black launcher button. */\nfunction SentientMark({ size = 26 }: { size?: number } = {}): JSX.Element {\n return (\n <svg width={size} height={size} viewBox=\"0 0 32 32\" fill=\"none\" aria-hidden=\"true\">\n <path\n d=\"M21 9H14C11.2 9 9.8 10.8 9.8 13C9.8 15.4 11.6 16.6 14.5 16.6H18.5C20.5 16.6 20.7 18.2 20.4 19.6\"\n stroke=\"#fff\"\n strokeWidth=\"2.2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path d=\"M10 22H17\" stroke=\"#fff\" strokeWidth=\"2.2\" strokeLinecap=\"round\" />\n <circle cx=\"20.6\" cy=\"22\" r=\"2.1\" fill=\"#fff\" />\n </svg>\n );\n}\n\nexport function AdaptiveDevtools({ apiKey }: { apiKey?: string } = {}): JSX.Element | null {\n const [open, setOpen] = useState(false);\n const [activePersona, setActivePersona] = useState<string | null>(null);\n const [dragFrom, setDragFrom] = useState<number | null>(null);\n const [mounted, setMounted] = useState(false);\n const [, force] = useReducer((n: number) => n + 1, 0);\n // Re-render when the component/slot registry changes. useSyncExternalStore\n // (not a manual useEffect subscription) so the subscription can't go stale\n // across Next Fast Refresh — a stale listener was why the panel needed a hard\n // refresh to pick up a renamed id.\n useSyncExternalStore(subscribeRegistry, getRegistryVersion, () => 0);\n // Client-mount gate: render nothing during SSR / the first paint so the widget\n // never reads `window` on the server. Lets consumers drop `<AdaptiveDevtools/>`\n // straight into a tree without a `dynamic(..., { ssr: false })` wrapper.\n useEffect(() => setMounted(true), []);\n\n // Never render in production, even if imported by mistake. (Hooks run first\n // so the rules of hooks hold regardless of these early returns.)\n if (IS_PROD) return null;\n if (!mounted) return null;\n\n const config: DevtoolsConfig = readDevtoolsConfig() ?? {\n apiKey: apiKey ?? '',\n apiBaseUrl: DEFAULT_API_BASE_URL,\n isLocal: false,\n };\n const useLocalEngine = config.isLocal || !config.apiKey;\n const components = getRegistered();\n const slots = getRegisteredSlots();\n const overrides = getOverrides();\n const slotOverrides = getSlotOverrides();\n const sections = currentLayout();\n const layoutForced = (window as unknown as OverrideWindow).__sentient_layout_override !== undefined;\n\n function onReorder(from: number, to: number): void {\n reorderLayout(from, to);\n force();\n }\n function onResetLayout(): void {\n resetLayout();\n maybeExitPreview();\n force();\n }\n\n // Preview mode stays on while ANY override (variant, slot or layout) is\n // active. Omitting layout here let clearing the last variant re-enable event\n // recording while a previewed section order was still on screen.\n function maybeExitPreview(): void {\n if (\n Object.keys(getOverrides()).length === 0 &&\n Object.keys(getSlotOverrides()).length === 0 &&\n (window as unknown as OverrideWindow).__sentient_layout_override === undefined\n ) {\n setPreviewMode(false);\n }\n }\n\n function choose(id: string, variantId: string): void {\n setVariantOverride(id, variantId);\n setPreviewMode(true);\n notifyOverridesChanged();\n force();\n }\n function resetVariant(id: string): void {\n clearVariantOverride(id);\n maybeExitPreview();\n notifyOverridesChanged();\n force();\n }\n function chooseSlotArm(id: string, arm: string): void {\n setSlotOverride(id, arm);\n setPreviewMode(true);\n notifyOverridesChanged();\n force();\n }\n function chooseSlotDim(id: string, dim: string, value: string, dims: RegisteredSlot['dims']): void {\n const current = getSlotOverrides()[id];\n // Merge onto the existing forced object, or seed from each dim's baseline\n // (first value) so unset dims stay at baseline instead of vanishing.\n const next: Record<string, string> =\n current && typeof current === 'object'\n ? { ...current }\n : Object.fromEntries(Object.entries(dims ?? {}).map(([d, values]) => [d, values[0]!]));\n next[dim] = value;\n setSlotOverride(id, next);\n setPreviewMode(true);\n notifyOverridesChanged();\n force();\n }\n function resetSlot(id: string): void {\n clearSlotOverride(id);\n maybeExitPreview();\n notifyOverridesChanged();\n force();\n }\n function choosePersona(persona: string): void {\n setActivePersona(persona);\n const apply = useLocalEngine\n ? forcePersonaLocal(persona, config.apiKey)\n : forcePersonaKeyed(config.apiKey, config.apiBaseUrl, persona);\n // .catch: a failed simulate (offline /v1/explain, bad key, failed local\n // dynamic import) is a preview no-op — without the handler it surfaced as\n // an unhandled promise rejection in the console.\n apply.then(force).catch(() => {});\n }\n\n return (\n <div style={{ position: 'fixed', bottom: 16, right: 16, zIndex: 2147483647, fontFamily: 'system-ui' }}>\n {/* Panel stays mounted and animates in/out from the button's corner, so the\n launcher below never shifts. transform-origin is the button (bottom-right). */}\n <div\n aria-hidden={!open}\n style={{\n position: 'absolute',\n bottom: 52,\n right: 0,\n transformOrigin: 'bottom right',\n transition: 'opacity .18s ease, transform .2s cubic-bezier(.16,1,.3,1)',\n opacity: open ? 1 : 0,\n transform: open ? 'translateY(0) scale(1)' : 'translateY(6px) scale(.96)',\n pointerEvents: open ? 'auto' : 'none',\n }}\n >\n <div style={{ width: 300, maxHeight: 460, overflowY: 'auto', background: '#111', color: '#eee',\n borderRadius: 8, padding: 12, boxShadow: '0 8px 30px rgba(0,0,0,.4)', fontSize: 12 }}>\n {config.isLocal && (\n <div style={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 4,\n padding: '6px 8px', marginBottom: 8 }}>\n {LOCAL_MODE_DEVTOOLS_BANNER}\n </div>\n )}\n <div style={{ opacity: .7, marginBottom: 8 }}>\n {components.length} component{components.length === 1 ? '' : 's'} · {getPreviewMode() ? 'preview — writing nothing' : 'live'}\n </div>\n <div style={{ borderBottom: '1px solid #333', paddingBottom: 8, marginBottom: 8 }}>\n <div style={{ opacity: .7, marginBottom: 4 }}>Preview persona</div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>\n {PERSONAS.map((p) => (\n <button key={p} onClick={() => choosePersona(p)} style={btn(activePersona === p)}>\n {PERSONA_DISPLAY[p]}\n </button>\n ))}\n {(activePersona !== null || Object.keys(overrides).length > 0 || Object.keys(slotOverrides).length > 0) && (\n <button onClick={resetAll} style={{ ...btn(false), color: '#aaa' }}>\n Reset\n </button>\n )}\n </div>\n </div>\n {sections.length > 0 && (\n <div style={{ borderBottom: '1px solid #333', paddingBottom: 8, marginBottom: 8 }}>\n <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>\n <span style={{ opacity: .7 }}>Layout — drag to reorder</span>\n {layoutForced && (\n // Distinct accessible name: the per-variant and per-slot resets\n // below are also labelled \"reset\", and three identical buttons\n // in one panel is ambiguous to a screen reader and to tests.\n <button\n aria-label=\"Reset section order\"\n onClick={onResetLayout}\n style={{ ...btn(false), color: '#aaa' }}\n >\n reset\n </button>\n )}\n </div>\n {/* Drop-on-row inserts at that row's position, so any block can go\n anywhere in one gesture. The whole order is written on each\n drop — see reorderLayout. */}\n <ul aria-label=\"Section order\" style={{ listStyle: 'none', margin: 0, padding: 0 }}>\n {sections.map((id, i) => (\n <li\n key={id}\n draggable\n onDragStart={() => setDragFrom(i)}\n onDragOver={(e) => e.preventDefault()}\n onDrop={(e) => {\n e.preventDefault();\n if (dragFrom !== null) onReorder(dragFrom, i);\n setDragFrom(null);\n }}\n onDragEnd={() => setDragFrom(null)}\n style={{\n display: 'flex', alignItems: 'center', gap: 6, padding: '4px 6px', marginBottom: 2,\n borderRadius: 4, border: '1px solid #262626', cursor: 'grab',\n background: dragFrom === i ? '#1e293b' : '#181818',\n opacity: dragFrom !== null && dragFrom !== i ? .6 : 1,\n }}\n >\n <span style={{ opacity: .4, minWidth: 10, fontVariantNumeric: 'tabular-nums' }}>{i + 1}</span>\n <span aria-hidden=\"true\" style={{ opacity: .35 }}>⠿</span>\n <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>\n {id}\n </span>\n </li>\n ))}\n </ul>\n </div>\n )}\n {components.length === 0 && slots.length === 0 && sections.length === 0 && (\n <div style={{ opacity: .6 }}>No components, sections or slots on this page yet.</div>\n )}\n {components.map((c) => (\n <div key={c.id} style={{ borderTop: '1px solid #333', padding: '8px 0' }}>\n <div style={{ fontWeight: 600 }}>{c.id}{c.goal ? ` · goal: ${c.goal}` : ''}</div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>\n {c.variantIds.map((v) => (\n <button key={v} onClick={() => choose(c.id, v)} style={btn(overrides[c.id] === v)}>\n {v}\n </button>\n ))}\n {overrides[c.id] && (\n <button onClick={() => resetVariant(c.id)} style={{ ...btn(false), color: '#aaa' }}>\n reset\n </button>\n )}\n </div>\n </div>\n ))}\n {slots.length > 0 && (\n <div style={{ borderTop: '1px solid #333', paddingTop: 8, marginTop: 4 }}>\n <div style={{ opacity: .7, marginBottom: 4 }}>Slots</div>\n {slots.map((s) => {\n const ov = slotOverrides[s.id];\n return (\n <div key={s.id} style={{ padding: '6px 0' }}>\n <div style={{ fontWeight: 600 }}>{s.id}</div>\n {s.arms && (\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>\n {s.arms.map((arm) => (\n <button key={arm} onClick={() => chooseSlotArm(s.id, arm)} style={btn(ov === arm)}>\n {arm}\n </button>\n ))}\n </div>\n )}\n {s.dims && Object.entries(s.dims).map(([dim, values]) => (\n <div key={dim} style={{ marginTop: 4 }}>\n <div style={{ opacity: .6, fontSize: 11 }}>{dim}</div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>\n {values.map((v) => (\n <button\n key={v}\n onClick={() => chooseSlotDim(s.id, dim, v, s.dims)}\n style={btn(!!ov && typeof ov === 'object' && ov[dim] === v)}\n >\n {v}\n </button>\n ))}\n </div>\n </div>\n ))}\n {ov !== undefined && (\n <button onClick={() => resetSlot(s.id)} style={{ ...btn(false), color: '#aaa', marginTop: 4 }}>\n reset\n </button>\n )}\n </div>\n );\n })}\n </div>\n )}\n </div>\n </div>\n <button\n aria-label=\"Sentient DevTools\"\n aria-expanded={open}\n onClick={() => setOpen((o) => !o)}\n style={{ width: 44, height: 44, borderRadius: 12, border: '1px solid #2a2a2a', background: '#000',\n display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,\n cursor: 'pointer', boxShadow: '0 6px 18px rgba(0,0,0,.4)' }}\n >\n <SentientMark />\n </button>\n </div>\n );\n}\n","import { isDevBuild } from './adaptive-shared.js';\n\nexport type RegisteredComponent = { id: string; variantIds: string[]; goal?: string };\nexport type RegisteredSlot = {\n id: string;\n arms?: string[];\n dims?: Record<string, readonly string[]>;\n};\n\ntype RegistryState = {\n components: Map<string, RegisteredComponent>;\n slots: Map<string, RegisteredSlot>;\n sections: string[];\n listeners: Set<() => void>;\n /** Bumped on every mutation so `useSyncExternalStore` can read a stable, comparable snapshot. */\n version: number;\n};\n\n// Shared through a window global: the main entry and the /devtools entry are\n// separate bundles, each with its own copy of this module — module-local\n// state would give the devtools an always-empty registry in published apps.\nconst ssrFallback: RegistryState = {\n components: new Map(),\n slots: new Map(),\n sections: [],\n listeners: new Set(),\n version: 0,\n};\n\nfunction state(): RegistryState {\n if (typeof window === 'undefined') return ssrFallback;\n const w = window as unknown as { __sentient_registry?: RegistryState };\n if (!w.__sentient_registry) {\n w.__sentient_registry = {\n components: new Map(),\n slots: new Map(),\n sections: [],\n listeners: new Set(),\n version: 0,\n };\n }\n return w.__sentient_registry;\n}\n\nfunction emit(): void {\n // Bump BEFORE notifying so a useSyncExternalStore consumer re-reading its\n // snapshot inside the notification sees the new value and re-renders.\n state().version += 1;\n for (const fn of state().listeners) fn();\n}\n\n// The registry exists solely to feed the opt-in devtools panel, which is a\n// dev-only surface. In a production build there is no panel reading it, so\n// every register call is dead work plus a `window.__sentient_registry`\n// footprint on the customer's page. Short-circuit to a noop in production —\n// every <Adaptive>/useAdaptive/slot mount calls one of these.\nconst NOOP_UNREGISTER = (): void => undefined;\n\n/** Register (or re-register) a component. Returns an unregister function. */\nexport function registerComponent(c: RegisteredComponent): () => void {\n if (!isDevBuild()) return NOOP_UNREGISTER;\n state().components.set(c.id, c);\n emit();\n return () => {\n state().components.delete(c.id);\n emit();\n };\n}\n\n/** Register (or re-register) a slot declaration. Returns an unregister function. */\nexport function registerSlot(s: RegisteredSlot): () => void {\n if (!isDevBuild()) return NOOP_UNREGISTER;\n state().slots.set(s.id, s);\n emit();\n return () => {\n state().slots.delete(s.id);\n emit();\n };\n}\n\n/** Register the page's declared section ids (from AdaptiveRoot/provider). */\nexport function registerSections(sections: string[]): void {\n if (!isDevBuild()) return;\n state().sections = [...sections];\n emit();\n}\n\nexport function getRegistered(): RegisteredComponent[] {\n return [...state().components.values()];\n}\n\nexport function getRegisteredSlots(): RegisteredSlot[] {\n return [...state().slots.values()];\n}\n\nexport function getRegisteredSections(): string[] {\n return [...state().sections];\n}\n\nexport function subscribeRegistry(fn: () => void): () => void {\n const listeners = state().listeners;\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/** Monotonic snapshot for `useSyncExternalStore` — changes on every registry mutation. */\nexport function getRegistryVersion(): number {\n return state().version;\n}\n","function store(): Record<string, string> {\n const w = window as unknown as { __sentient_overrides?: Record<string, string> };\n if (!w.__sentient_overrides) w.__sentient_overrides = {};\n return w.__sentient_overrides;\n}\n\n/** Force `componentId` to render `variantId` — read by `useAssignment`. */\nexport function setVariantOverride(componentId: string, variantId: string): void {\n store()[componentId] = variantId;\n}\n\nexport function clearVariantOverride(componentId: string): void {\n delete store()[componentId];\n}\n\nexport function getOverrides(): Record<string, string> {\n return { ...store() };\n}\n","import type { SlotResult } from '@sentientui/core';\n\n/**\n * Slot-override store — the channel `useSlotResult` reads (`useAdaptiveTokens` /\n * `AdaptiveGroup`). Separate from `__sentient_overrides` (variant components):\n * a slot result is a token object (`{ tone: 'urgent' }`) or an arm string\n * (`'social_first'`), never a bare variant id. Window-backed so the /devtools\n * bundle and the main bundle share one store.\n */\nfunction store(): Record<string, SlotResult> {\n const w = window as unknown as { __sentient_slot_overrides?: Record<string, SlotResult> };\n if (!w.__sentient_slot_overrides) w.__sentient_slot_overrides = {};\n return w.__sentient_slot_overrides;\n}\n\n/** Force `slotId` to resolve to `result` — read by `useSlotResult`. */\nexport function setSlotOverride(slotId: string, result: SlotResult): void {\n store()[slotId] = result;\n}\n\nexport function clearSlotOverride(slotId: string): void {\n delete store()[slotId];\n}\n\nexport function getSlotOverrides(): Record<string, SlotResult> {\n return { ...store() };\n}\n","import type { SentientClient } from '@sentientui/core';\n\ntype PreviewState = { on: boolean; listeners: Set<() => void> };\nconst ssrFallback: PreviewState = { on: false, listeners: new Set() };\n\n// Window-backed: the /devtools entry (a separate bundle) toggles preview mode\n// and the provider (main bundle) must observe it.\nfunction state(): PreviewState {\n if (typeof window === 'undefined') return ssrFallback;\n const w = window as unknown as { __sentient_preview?: PreviewState };\n if (!w.__sentient_preview) w.__sentient_preview = { on: false, listeners: new Set() };\n return w.__sentient_preview;\n}\n\nexport function setPreviewMode(on: boolean): void {\n const s = state();\n if (s.on === on) return;\n s.on = on;\n for (const fn of s.listeners) fn();\n}\n\nexport function getPreviewMode(): boolean {\n return state().on;\n}\n\nexport function subscribePreview(fn: () => void): () => void {\n const listeners = state().listeners;\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/**\n * Wraps a client so it writes nothing: reads pass through, all emitters no-op.\n * Used while previewing variants/personas so no `variant_assigned`, goal, or\n * session events are sent.\n */\nexport function createPreviewClient(inner: SentientClient): SentientClient {\n return {\n isLocal: inner.isLocal,\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n fetchWeights: () => Promise.resolve([]),\n getAssignment: (componentId, segment) => inner.getAssignment(componentId, segment),\n assign: (componentId, variantIds, agentData, agentDataByVariant) =>\n inner.assign(componentId, variantIds, agentData, agentDataByVariant),\n // Reads pass through; decide is a write (slot decisions persist server-side)\n // so preview mode never issues it.\n decide: () => Promise.resolve(null),\n getSlotResult: (slotId) => inner.getSlotResult(slotId),\n getPersona: () => inner.getPersona(),\n getGraph: () => inner.getGraph(),\n dispose: () => inner.dispose(),\n destroy: () => inner.destroy(),\n };\n}\n","/**\n * Cross-bundle re-render bus for devtools overrides. The main entry and the\n * /devtools entry are separate bundles, so state and notifications go through\n * window (a version counter + a DOM event) — never module-local state.\n */\nconst EVENT = 'sentient:overrides-changed';\n\ntype VersionWindow = Window & { __sentient_overrides_version?: number };\n\nexport function getOverridesVersion(): number {\n if (typeof window === 'undefined') return 0;\n return (window as VersionWindow).__sentient_overrides_version ?? 0;\n}\n\nexport function notifyOverridesChanged(): void {\n if (typeof window === 'undefined') return;\n const w = window as VersionWindow;\n w.__sentient_overrides_version = (w.__sentient_overrides_version ?? 0) + 1;\n window.dispatchEvent(new Event(EVENT));\n}\n\nexport function subscribeOverridesChanged(fn: () => void): () => void {\n if (typeof window === 'undefined') return () => undefined;\n window.addEventListener(EVENT, fn);\n return () => window.removeEventListener(EVENT, fn);\n}\n","/** Provider → devtools config handoff. Window-backed: the /devtools entry is a\n * separate bundle and cannot share the provider's React context instance. */\nexport type DevtoolsConfig = {\n apiKey: string;\n apiBaseUrl: string;\n isLocal: boolean;\n};\n\ntype ConfigWindow = Window & { __sentient_devtools_config?: DevtoolsConfig };\n\nexport function publishDevtoolsConfig(config: DevtoolsConfig): void {\n if (typeof window === 'undefined') return;\n (window as ConfigWindow).__sentient_devtools_config = config;\n}\n\nexport function readDevtoolsConfig(): DevtoolsConfig | null {\n if (typeof window === 'undefined') return null;\n return (window as ConfigWindow).__sentient_devtools_config ?? null;\n}\n"],"mappings":";+6BAAA,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AG,EAAG,MAAOhC,EAAI+C,IAAOf,CAAG,EAC7E,SAAAA,GADUA,CAEb,CACD,EACH,EAEDlD,EAAE,MAAQ,OAAO,QAAQA,EAAE,IAAI,EAAE,IAAI,CAAC,CAACqD,EAAKK,CAAM,OACjD,QAAC,OAAc,MAAO,CAAE,UAAW,CAAE,EACnC,oBAAC,OAAI,MAAO,CAAE,QAAS,GAAI,SAAU,EAAG,EAAI,SAAAL,EAAI,KAChD,OAAC,OAAI,MAAO,CAAE,QAAS,OAAQ,SAAU,OAAQ,IAAK,CAAE,EACrD,SAAAK,EAAO,IAAK,MACX,OAAC,UAEC,QAAS,IAAMN,GAAcpD,EAAE,GAAIqD,EAAK,EAAGrD,EAAE,IAAI,EACjD,MAAOkB,EAAI,CAAC,CAAC+C,GAAM,OAAOA,GAAO,UAAYA,EAAGZ,CAAG,IAAM,CAAC,EAEzD,YAJI,CAKP,CACD,EACH,IAZQA,CAaV,CACD,EACAY,IAAO,WACN,OAAC,UAAO,QAAS,IAAMN,GAAU3D,EAAE,EAAE,EAAG,MAAOQ,EAAAjB,EAAA,GAAK2B,EAAI,EAAK,GAAd,CAAiB,MAAO,OAAQ,UAAW,CAAE,GAAG,iBAE/F,IA9BMlB,EAAE,EAgCZ,CAEJ,CAAC,GACH,GAEJ,EACF,KACA,OAAC,UACC,aAAW,oBACX,gBAAeuB,EACf,QAAS,IAAMC,EAAS0C,GAAM,CAACA,CAAC,EAChC,MAAO,CAAE,MAAO,GAAI,OAAQ,GAAI,aAAc,GAAI,OAAQ,oBAAqB,WAAY,OAClF,QAAS,OAAQ,WAAY,SAAU,eAAgB,SAAU,QAAS,EAC1E,OAAQ,UAAW,UAAW,2BAA4B,EAEnE,mBAAC9C,GAAA,EAAa,EAChB,GACF,CAEJ","names":["devtools_exports","__export","AdaptiveDevtools","LOCAL_MODE_DEVTOOLS_BANNER","__toCommonJS","import_react","import_policy","import_core","ssrFallback","state","w","getRegistered","state","getRegisteredSlots","getRegisteredSections","subscribeRegistry","fn","listeners","getRegistryVersion","store","w","setVariantOverride","componentId","variantId","clearVariantOverride","getOverrides","__spreadValues","store","w","setSlotOverride","slotId","result","clearSlotOverride","getSlotOverrides","__spreadValues","ssrFallback","state","w","setPreviewMode","on","s","fn","getPreviewMode","EVENT","notifyOverridesChanged","_a","w","EVENT","readDevtoolsConfig","_a","import_jsx_runtime","_a","IS_PROD","DEFAULT_API_BASE_URL","LOCAL_MODE_DEVTOOLS_BANNER","currentLayout","forced","registered","getRegisteredSections","id","reorderLayout","from","to","order","next","moved","setPreviewMode","notifyOverridesChanged","resetLayout","applyOutcome","result","_b","variantId","setVariantOverride","w","__spreadValues","readSessionId","apiKey","read","name","match","e","slotDecls","getRegisteredSlots","s","forcePersonaKeyed","apiBaseUrl","persona","res","getRegistered","c","data","__spreadProps","forcePersonaLocal","mod","outcome","resetAll","getOverrides","clearVariantOverride","stale","i","key","btn","active","SentientMark","size","AdaptiveDevtools","open","setOpen","activePersona","setActivePersona","dragFrom","setDragFrom","mounted","setMounted","force","subscribeRegistry","getRegistryVersion","config","readDevtoolsConfig","useLocalEngine","components","slots","overrides","slotOverrides","getSlotOverrides","sections","layoutForced","onReorder","onResetLayout","maybeExitPreview","choose","resetVariant","chooseSlotArm","arm","setSlotOverride","chooseSlotDim","dim","value","dims","current","d","values","resetSlot","clearSlotOverride","choosePersona","getPreviewMode","p","v","ov","o"]}
1
+ {"version":3,"sources":["../src/devtools/index.tsx","../src/devtools-registry.ts","../src/devtools-overrides.ts","../src/devtools-slot-overrides.ts","../src/preview-mode.ts","../src/override-events.ts","../src/devtools-config.ts"],"sourcesContent":["'use client';\n// `type JSX` from react, not the global namespace removed in @types/react@19\n// (peers allow react >=18) — see adaptive-text.tsx.\nimport { useEffect, useReducer, useState, useSyncExternalStore, type CSSProperties, type JSX } from 'react';\nimport { PERSONAS, PERSONA_DISPLAY, confidenceBand } from '@sentientui/policy';\nimport { LEGACY_SESSION_COOKIE_NAME, SNAPSHOT_STORAGE_KEY_PREFIX, sessionCookieName } from '@sentientui/core';\nimport {\n getRegistered,\n getRegisteredSlots,\n getRegisteredSections,\n subscribeRegistry,\n getRegistryVersion,\n type RegisteredSlot,\n} from '../devtools-registry.js';\nimport { setVariantOverride, clearVariantOverride, getOverrides } from '../devtools-overrides.js';\nimport { setSlotOverride, clearSlotOverride, getSlotOverrides } from '../devtools-slot-overrides.js';\nimport { setPreviewMode, getPreviewMode } from '../preview-mode.js';\nimport { notifyOverridesChanged } from '../override-events.js';\nimport { readDevtoolsConfig, type DevtoolsConfig } from '../devtools-config.js';\n\ndeclare const process: { env?: { NODE_ENV?: string } } | undefined;\nconst IS_PROD = typeof process !== 'undefined' && process.env?.NODE_ENV === 'production';\nconst DEFAULT_API_BASE_URL = 'https://api.sentient-ui.com/v1';\n\nexport const LOCAL_MODE_DEVTOOLS_BANNER =\n 'Local mode — decisions are simulated; add a key to learn from real traffic';\n\ntype OutcomeToApply = {\n assignments?: Record<string, string>;\n layoutOrder?: string[] | null;\n slots?: Record<string, string | Record<string, string>>;\n personaAttributes?: { persona: string; confidence: 'low' | 'medium' | 'high' };\n};\n\ntype OverrideWindow = Window & {\n __sentient_layout_override?: string[];\n __sentient_slot_overrides?: Record<string, string | Record<string, string>>;\n};\n\n/** The order the page is rendering: a previewed override, else what was registered. */\nfunction currentLayout(): string[] {\n const forced = (window as unknown as OverrideWindow).__sentient_layout_override;\n const registered = getRegisteredSections();\n if (!forced || forced.length === 0) return registered;\n // Registered ids the override omits still render (useLayoutOrder returns the\n // override verbatim, and the app maps whatever ids it is given), so show them\n // trailing rather than dropping them from the list you are dragging.\n return [...forced, ...registered.filter((id) => !forced.includes(id))];\n}\n\n/**\n * Move `from` to `to` within the current order and preview it.\n *\n * Writes the whole order rather than swapping neighbours: the point is to try an\n * arrangement, not to walk one block up a list one press at a time.\n */\nfunction reorderLayout(from: number, to: number): void {\n const order = currentLayout();\n if (from === to || from < 0 || to < 0 || from >= order.length || to >= order.length) return;\n const next = [...order];\n const [moved] = next.splice(from, 1);\n next.splice(to, 0, moved!);\n (window as unknown as OverrideWindow).__sentient_layout_override = next;\n setPreviewMode(true); // an arrangement you are trying must not train the bandit\n notifyOverridesChanged();\n}\n\nfunction resetLayout(): void {\n delete (window as unknown as OverrideWindow).__sentient_layout_override;\n notifyOverridesChanged();\n}\n\n/** Apply a simulated outcome across every surface: variants, layout, slots/tokens, persona attrs. */\nfunction applyOutcome(result: OutcomeToApply): void {\n for (const [id, variantId] of Object.entries(result.assignments ?? {})) {\n setVariantOverride(id, variantId);\n }\n const w = window as unknown as OverrideWindow;\n if (result.layoutOrder && result.layoutOrder.length > 0) {\n w.__sentient_layout_override = result.layoutOrder;\n }\n if (result.slots) {\n w.__sentient_slot_overrides = { ...(w.__sentient_slot_overrides ?? {}), ...result.slots };\n }\n if (result.personaAttributes) {\n document.documentElement.dataset.sentientPersona = result.personaAttributes.persona;\n document.documentElement.dataset.sentientConfidence = result.personaAttributes.confidence;\n }\n setPreviewMode(true); // suppress events while previewing\n notifyOverridesChanged(); // re-render layout/slot consumers\n}\n\n// Reads the SDK's own session cookie — the per-project SUFFIXED name first\n// (that is what the client writes since namespacing; the bare `_snt_uid` this\n// used to read is only written in keyless/local mode), then the bare name as\n// the legacy/local fallback.\nfunction readSessionId(apiKey?: string): string {\n const read = (name: string): string | null => {\n try {\n const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));\n return match ? decodeURIComponent(match[1]!) : null;\n } catch {\n return null;\n }\n };\n return (apiKey ? read(sessionCookieName(apiKey)) : null) ?? read(LEGACY_SESSION_COOKIE_NAME) ?? 'devtools-preview';\n}\n\nfunction slotDecls(): Array<{ id: string; arms?: string[]; dims?: RegisteredSlot['dims'] }> {\n return getRegisteredSlots().map((s) => ({\n id: s.id,\n ...(s.arms ? { arms: s.arms } : {}),\n ...(s.dims ? { dims: s.dims } : {}),\n }));\n}\n\n/** One member of the project's persona vocabulary, as /v1/personas serves it. */\ntype VocabMember = { key: string; displayName: string };\n\nconst DEFAULT_PERSONA_CHOICES: VocabMember[] = PERSONAS.map((key) => ({\n key,\n displayName: PERSONA_DISPLAY[key],\n}));\n\n/**\n * Keyed mode: the project's ACTIVE vocabulary from /v1/personas. Personas are\n * per-project (persona_sets, migration 113) — discovery can promote new ones\n * and retire the pinned four — so hardcoding PERSONAS here offered buttons\n * that silently simulated the default experience on any project whose\n * vocabulary differs. null on any failure → the caller keeps the pinned-four\n * fallback (an old API without the endpoint degrades to today's behavior).\n */\nasync function fetchPersonaVocabulary(\n apiKey: string,\n apiBaseUrl: string,\n): Promise<{ personas: VocabMember[]; discovered: VocabMember[] } | null> {\n try {\n const res = await fetch(`${apiBaseUrl}/personas`, {\n headers: { authorization: `Bearer ${apiKey}` },\n });\n if (!res.ok) return null;\n const data = (await res.json()) as { personas?: VocabMember[]; discovered?: VocabMember[] };\n const valid = (list: VocabMember[] | undefined): VocabMember[] =>\n Array.isArray(list)\n ? list.filter((p) => p && typeof p.key === 'string' && typeof p.displayName === 'string')\n : [];\n const personas = valid(data.personas);\n return personas.length > 0 ? { personas, discovered: valid(data.discovered) } : null;\n } catch {\n return null;\n }\n}\n\n/** Keyed mode: simulate via /v1/explain (read-only, event-free). Returns how\n * the persona RESOLVED so the panel can say when the project didn't\n * recognize it — the page then shows the default experience, and a silently\n * highlighted button claiming otherwise was the old lie. */\nasync function forcePersonaKeyed(\n apiKey: string,\n apiBaseUrl: string,\n persona: string,\n): Promise<{ recognized: boolean; resolvedDisplay: string } | null> {\n const res = await fetch(`${apiBaseUrl}/explain`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify({\n persona,\n sections: getRegisteredSections().map((id) => ({ id })),\n components: getRegistered().map((c) => ({ id: c.id, variantIds: c.variantIds })),\n slots: slotDecls(),\n }),\n });\n if (!res.ok) return null;\n const data = (await res.json()) as OutcomeToApply & {\n recognized?: boolean;\n persona?: string;\n personaDisplay?: string;\n };\n applyOutcome({\n ...data,\n personaAttributes: data.personaAttributes ?? { persona, confidence: 'high' },\n });\n return {\n // An older API omits the field — treat as recognized (no basis to warn).\n recognized: data.recognized !== false,\n resolvedDisplay: data.personaDisplay ?? data.persona ?? persona,\n };\n}\n\n/** Local mode: simulate via the deterministic local engine — zero network. */\nasync function forcePersonaLocal(persona: string, apiKey?: string): Promise<void> {\n const mod = await import('@sentientui/core/local');\n if (!mod.LOCAL_ENGINE_AVAILABLE) return;\n const outcome = mod\n .createLocalEngine({ sessionId: readSessionId(apiKey), forcedPersona: persona })\n .decide({\n sections: getRegisteredSections(),\n components: getRegistered().map((c) => ({ id: c.id, variantIds: c.variantIds })),\n slots: slotDecls(),\n });\n applyOutcome({\n assignments: outcome.assignments,\n layoutOrder: outcome.layoutOrder,\n slots: outcome.slots,\n personaAttributes: {\n persona: outcome.persona,\n confidence: confidenceBand(outcome.confidence),\n },\n });\n}\n\n/** Reset: clear the decision snapshot + every override, then reload to re-decide. */\nfunction resetAll(): void {\n for (const id of Object.keys(getOverrides())) clearVariantOverride(id);\n const w = window as unknown as OverrideWindow;\n delete w.__sentient_layout_override;\n delete w.__sentient_slot_overrides;\n delete document.documentElement.dataset.sentientPersona;\n delete document.documentElement.dataset.sentientConfidence;\n try {\n const stale: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key && key.startsWith(SNAPSHOT_STORAGE_KEY_PREFIX)) stale.push(key);\n }\n for (const key of stale) localStorage.removeItem(key);\n } catch {\n /* ignore */\n }\n setPreviewMode(false);\n notifyOverridesChanged();\n try {\n window.location.reload();\n } catch {\n /* jsdom */\n }\n}\n\nconst btn = (active: boolean): CSSProperties => ({\n padding: '2px 8px',\n borderRadius: 4,\n border: '1px solid #444',\n background: active ? '#3b82f6' : '#222',\n color: '#eee',\n cursor: 'pointer',\n});\n\n/** Sentient \"S.\" wordmark, monoline — white strokes for the black launcher button. */\nfunction SentientMark({ size = 26 }: { size?: number } = {}): JSX.Element {\n return (\n <svg width={size} height={size} viewBox=\"0 0 32 32\" fill=\"none\" aria-hidden=\"true\">\n <path\n d=\"M21 9H14C11.2 9 9.8 10.8 9.8 13C9.8 15.4 11.6 16.6 14.5 16.6H18.5C20.5 16.6 20.7 18.2 20.4 19.6\"\n stroke=\"#fff\"\n strokeWidth=\"2.2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n <path d=\"M10 22H17\" stroke=\"#fff\" strokeWidth=\"2.2\" strokeLinecap=\"round\" />\n <circle cx=\"20.6\" cy=\"22\" r=\"2.1\" fill=\"#fff\" />\n </svg>\n );\n}\n\nexport function AdaptiveDevtools({ apiKey }: { apiKey?: string } = {}): JSX.Element | null {\n const [open, setOpen] = useState(false);\n const [activePersona, setActivePersona] = useState<string | null>(null);\n // The project's vocabulary (keyed mode); null = not loaded → pinned-four\n // fallback. Local mode never fetches: the local engine only knows the\n // pinned four, and its banner already frames everything as simulated.\n const [vocab, setVocab] = useState<VocabMember[] | null>(null);\n // Discovered SHADOW personas — display-only. They never serve until\n // promotion, so there is no button: forcing one would simulate a persona\n // that cannot occur on this project.\n const [discovered, setDiscovered] = useState<VocabMember[]>([]);\n // Set when a forced persona did NOT resolve against the project's\n // vocabulary — the page is showing the default experience and the panel\n // must say so instead of highlighting the button as if the preview worked.\n const [personaNote, setPersonaNote] = useState<string | null>(null);\n const [dragFrom, setDragFrom] = useState<number | null>(null);\n const [mounted, setMounted] = useState(false);\n const [, force] = useReducer((n: number) => n + 1, 0);\n // Re-render when the component/slot registry changes. useSyncExternalStore\n // (not a manual useEffect subscription) so the subscription can't go stale\n // across Next Fast Refresh — a stale listener was why the panel needed a hard\n // refresh to pick up a renamed id.\n useSyncExternalStore(subscribeRegistry, getRegistryVersion, () => 0);\n // Client-mount gate: render nothing during SSR / the first paint so the widget\n // never reads `window` on the server. Lets consumers drop `<AdaptiveDevtools/>`\n // straight into a tree without a `dynamic(..., { ssr: false })` wrapper.\n useEffect(() => setMounted(true), []);\n // Load the project's persona vocabulary once (keyed mode only).\n useEffect(() => {\n if (IS_PROD) return;\n const cfg = readDevtoolsConfig() ?? { apiKey: apiKey ?? '', apiBaseUrl: DEFAULT_API_BASE_URL, isLocal: false };\n if (cfg.isLocal || !cfg.apiKey) return;\n let cancelled = false;\n void fetchPersonaVocabulary(cfg.apiKey, cfg.apiBaseUrl).then((v) => {\n if (cancelled || !v) return;\n setVocab(v.personas);\n setDiscovered(v.discovered);\n });\n return () => { cancelled = true; };\n }, [apiKey]);\n\n // Never render in production, even if imported by mistake. (Hooks run first\n // so the rules of hooks hold regardless of these early returns.)\n if (IS_PROD) return null;\n if (!mounted) return null;\n\n const config: DevtoolsConfig = readDevtoolsConfig() ?? {\n apiKey: apiKey ?? '',\n apiBaseUrl: DEFAULT_API_BASE_URL,\n isLocal: false,\n };\n const useLocalEngine = config.isLocal || !config.apiKey;\n const components = getRegistered();\n const slots = getRegisteredSlots();\n const overrides = getOverrides();\n const slotOverrides = getSlotOverrides();\n const sections = currentLayout();\n const layoutForced = (window as unknown as OverrideWindow).__sentient_layout_override !== undefined;\n\n function onReorder(from: number, to: number): void {\n reorderLayout(from, to);\n force();\n }\n function onResetLayout(): void {\n resetLayout();\n maybeExitPreview();\n force();\n }\n\n // Preview mode stays on while ANY override (variant, slot or layout) is\n // active. Omitting layout here let clearing the last variant re-enable event\n // recording while a previewed section order was still on screen.\n function maybeExitPreview(): void {\n if (\n Object.keys(getOverrides()).length === 0 &&\n Object.keys(getSlotOverrides()).length === 0 &&\n (window as unknown as OverrideWindow).__sentient_layout_override === undefined\n ) {\n setPreviewMode(false);\n }\n }\n\n function choose(id: string, variantId: string): void {\n setVariantOverride(id, variantId);\n setPreviewMode(true);\n notifyOverridesChanged();\n force();\n }\n function resetVariant(id: string): void {\n clearVariantOverride(id);\n maybeExitPreview();\n notifyOverridesChanged();\n force();\n }\n function chooseSlotArm(id: string, arm: string): void {\n setSlotOverride(id, arm);\n setPreviewMode(true);\n notifyOverridesChanged();\n force();\n }\n function chooseSlotDim(id: string, dim: string, value: string, dims: RegisteredSlot['dims']): void {\n const current = getSlotOverrides()[id];\n // Merge onto the existing forced object, or seed from each dim's baseline\n // (first value) so unset dims stay at baseline instead of vanishing.\n const next: Record<string, string> =\n current && typeof current === 'object'\n ? { ...current }\n : Object.fromEntries(Object.entries(dims ?? {}).map(([d, values]) => [d, values[0]!]));\n next[dim] = value;\n setSlotOverride(id, next);\n setPreviewMode(true);\n notifyOverridesChanged();\n force();\n }\n function resetSlot(id: string): void {\n clearSlotOverride(id);\n maybeExitPreview();\n notifyOverridesChanged();\n force();\n }\n function choosePersona(member: VocabMember): void {\n setActivePersona(member.key);\n setPersonaNote(null);\n // .catch: a failed simulate (offline /v1/explain, bad key, failed local\n // dynamic import) is a preview no-op — without the handler it surfaced as\n // an unhandled promise rejection in the console.\n if (useLocalEngine) {\n forcePersonaLocal(member.key, config.apiKey).then(force).catch(() => {});\n return;\n }\n forcePersonaKeyed(config.apiKey, config.apiBaseUrl, member.key)\n .then((r) => {\n if (r && !r.recognized) {\n setPersonaNote(\n `“${member.displayName}” isn’t in this project’s personas — the page is showing the default experience.`,\n );\n }\n force();\n })\n .catch(() => {});\n }\n\n return (\n <div style={{ position: 'fixed', bottom: 16, right: 16, zIndex: 2147483647, fontFamily: 'system-ui' }}>\n {/* Panel stays mounted and animates in/out from the button's corner, so the\n launcher below never shifts. transform-origin is the button (bottom-right). */}\n <div\n aria-hidden={!open}\n style={{\n position: 'absolute',\n bottom: 52,\n right: 0,\n transformOrigin: 'bottom right',\n transition: 'opacity .18s ease, transform .2s cubic-bezier(.16,1,.3,1)',\n opacity: open ? 1 : 0,\n transform: open ? 'translateY(0) scale(1)' : 'translateY(6px) scale(.96)',\n pointerEvents: open ? 'auto' : 'none',\n }}\n >\n <div style={{ width: 300, maxHeight: 460, overflowY: 'auto', background: '#111', color: '#eee',\n borderRadius: 8, padding: 12, boxShadow: '0 8px 30px rgba(0,0,0,.4)', fontSize: 12 }}>\n {config.isLocal && (\n <div style={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 4,\n padding: '6px 8px', marginBottom: 8 }}>\n {LOCAL_MODE_DEVTOOLS_BANNER}\n </div>\n )}\n <div style={{ opacity: .7, marginBottom: 8 }}>\n {components.length} component{components.length === 1 ? '' : 's'} · {getPreviewMode() ? 'preview — writing nothing' : 'live'}\n </div>\n <div style={{ borderBottom: '1px solid #333', paddingBottom: 8, marginBottom: 8 }}>\n <div style={{ opacity: .7, marginBottom: 4 }}>Preview persona</div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>\n {/* Keyed mode renders the project's OWN vocabulary (falling back\n to the pinned four until /v1/personas answers); local mode\n keeps the pinned four the local engine simulates. */}\n {(useLocalEngine ? DEFAULT_PERSONA_CHOICES : vocab ?? DEFAULT_PERSONA_CHOICES).map((p) => (\n <button key={p.key} onClick={() => choosePersona(p)} style={btn(activePersona === p.key)}>\n {p.displayName}\n </button>\n ))}\n {(activePersona !== null || Object.keys(overrides).length > 0 || Object.keys(slotOverrides).length > 0) && (\n <button onClick={resetAll} style={{ ...btn(false), color: '#aaa' }}>\n Reset\n </button>\n )}\n </div>\n {personaNote && (\n <div style={{ marginTop: 6, fontSize: 11, color: '#fbbf24' }}>{personaNote}</div>\n )}\n {!useLocalEngine && discovered.length > 0 && (\n <div style={{ marginTop: 8 }}>\n <div style={{ opacity: .5, fontSize: 11, marginBottom: 4 }}>\n Discovered — not serving yet (promote from the dashboard)\n </div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>\n {discovered.map((p) => (\n <span\n key={p.key}\n title=\"Found by clustering your traffic; it starts serving only after promotion.\"\n style={{ ...btn(false), opacity: .45, cursor: 'default', display: 'inline-block' }}\n >\n {p.displayName}\n </span>\n ))}\n </div>\n </div>\n )}\n </div>\n {sections.length > 0 && (\n <div style={{ borderBottom: '1px solid #333', paddingBottom: 8, marginBottom: 8 }}>\n <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>\n <span style={{ opacity: .7 }}>Layout — drag to reorder</span>\n {layoutForced && (\n // Distinct accessible name: the per-variant and per-slot resets\n // below are also labelled \"reset\", and three identical buttons\n // in one panel is ambiguous to a screen reader and to tests.\n <button\n aria-label=\"Reset section order\"\n onClick={onResetLayout}\n style={{ ...btn(false), color: '#aaa' }}\n >\n reset\n </button>\n )}\n </div>\n {/* Drop-on-row inserts at that row's position, so any block can go\n anywhere in one gesture. The whole order is written on each\n drop — see reorderLayout. */}\n <ul aria-label=\"Section order\" style={{ listStyle: 'none', margin: 0, padding: 0 }}>\n {sections.map((id, i) => (\n <li\n key={id}\n draggable\n onDragStart={() => setDragFrom(i)}\n onDragOver={(e) => e.preventDefault()}\n onDrop={(e) => {\n e.preventDefault();\n if (dragFrom !== null) onReorder(dragFrom, i);\n setDragFrom(null);\n }}\n onDragEnd={() => setDragFrom(null)}\n style={{\n display: 'flex', alignItems: 'center', gap: 6, padding: '4px 6px', marginBottom: 2,\n borderRadius: 4, border: '1px solid #262626', cursor: 'grab',\n background: dragFrom === i ? '#1e293b' : '#181818',\n opacity: dragFrom !== null && dragFrom !== i ? .6 : 1,\n }}\n >\n <span style={{ opacity: .4, minWidth: 10, fontVariantNumeric: 'tabular-nums' }}>{i + 1}</span>\n <span aria-hidden=\"true\" style={{ opacity: .35 }}>⠿</span>\n <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>\n {id}\n </span>\n </li>\n ))}\n </ul>\n </div>\n )}\n {components.length === 0 && slots.length === 0 && sections.length === 0 && (\n <div style={{ opacity: .6 }}>No components, sections or slots on this page yet.</div>\n )}\n {components.map((c) => (\n <div key={c.id} style={{ borderTop: '1px solid #333', padding: '8px 0' }}>\n <div style={{ fontWeight: 600 }}>{c.id}{c.goal ? ` · goal: ${c.goal}` : ''}</div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>\n {c.variantIds.map((v) => (\n <button key={v} onClick={() => choose(c.id, v)} style={btn(overrides[c.id] === v)}>\n {v}\n </button>\n ))}\n {overrides[c.id] && (\n <button onClick={() => resetVariant(c.id)} style={{ ...btn(false), color: '#aaa' }}>\n reset\n </button>\n )}\n </div>\n </div>\n ))}\n {slots.length > 0 && (\n <div style={{ borderTop: '1px solid #333', paddingTop: 8, marginTop: 4 }}>\n <div style={{ opacity: .7, marginBottom: 4 }}>Slots</div>\n {slots.map((s) => {\n const ov = slotOverrides[s.id];\n return (\n <div key={s.id} style={{ padding: '6px 0' }}>\n <div style={{ fontWeight: 600 }}>{s.id}</div>\n {s.arms && (\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>\n {s.arms.map((arm) => (\n <button key={arm} onClick={() => chooseSlotArm(s.id, arm)} style={btn(ov === arm)}>\n {arm}\n </button>\n ))}\n </div>\n )}\n {s.dims && Object.entries(s.dims).map(([dim, values]) => (\n <div key={dim} style={{ marginTop: 4 }}>\n <div style={{ opacity: .6, fontSize: 11 }}>{dim}</div>\n <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>\n {values.map((v) => (\n <button\n key={v}\n onClick={() => chooseSlotDim(s.id, dim, v, s.dims)}\n style={btn(!!ov && typeof ov === 'object' && ov[dim] === v)}\n >\n {v}\n </button>\n ))}\n </div>\n </div>\n ))}\n {ov !== undefined && (\n <button onClick={() => resetSlot(s.id)} style={{ ...btn(false), color: '#aaa', marginTop: 4 }}>\n reset\n </button>\n )}\n </div>\n );\n })}\n </div>\n )}\n </div>\n </div>\n <button\n aria-label=\"Sentient DevTools\"\n aria-expanded={open}\n onClick={() => setOpen((o) => !o)}\n style={{ width: 44, height: 44, borderRadius: 12, border: '1px solid #2a2a2a', background: '#000',\n display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,\n cursor: 'pointer', boxShadow: '0 6px 18px rgba(0,0,0,.4)' }}\n >\n <SentientMark />\n </button>\n </div>\n );\n}\n","import { isDevBuild } from './adaptive-shared.js';\n\nexport type RegisteredComponent = { id: string; variantIds: string[]; goal?: string };\nexport type RegisteredSlot = {\n id: string;\n arms?: string[];\n dims?: Record<string, readonly string[]>;\n};\n\ntype RegistryState = {\n components: Map<string, RegisteredComponent>;\n slots: Map<string, RegisteredSlot>;\n sections: string[];\n listeners: Set<() => void>;\n /** Bumped on every mutation so `useSyncExternalStore` can read a stable, comparable snapshot. */\n version: number;\n};\n\n// Shared through a window global: the main entry and the /devtools entry are\n// separate bundles, each with its own copy of this module — module-local\n// state would give the devtools an always-empty registry in published apps.\nconst ssrFallback: RegistryState = {\n components: new Map(),\n slots: new Map(),\n sections: [],\n listeners: new Set(),\n version: 0,\n};\n\nfunction state(): RegistryState {\n if (typeof window === 'undefined') return ssrFallback;\n const w = window as unknown as { __sentient_registry?: RegistryState };\n if (!w.__sentient_registry) {\n w.__sentient_registry = {\n components: new Map(),\n slots: new Map(),\n sections: [],\n listeners: new Set(),\n version: 0,\n };\n }\n return w.__sentient_registry;\n}\n\nfunction emit(): void {\n // Bump BEFORE notifying so a useSyncExternalStore consumer re-reading its\n // snapshot inside the notification sees the new value and re-renders.\n state().version += 1;\n for (const fn of state().listeners) fn();\n}\n\n// The registry exists solely to feed the opt-in devtools panel, which is a\n// dev-only surface. In a production build there is no panel reading it, so\n// every register call is dead work plus a `window.__sentient_registry`\n// footprint on the customer's page. Short-circuit to a noop in production —\n// every <Adaptive>/useAdaptive/slot mount calls one of these.\nconst NOOP_UNREGISTER = (): void => undefined;\n\n/** Register (or re-register) a component. Returns an unregister function. */\nexport function registerComponent(c: RegisteredComponent): () => void {\n if (!isDevBuild()) return NOOP_UNREGISTER;\n state().components.set(c.id, c);\n emit();\n return () => {\n state().components.delete(c.id);\n emit();\n };\n}\n\n/** Register (or re-register) a slot declaration. Returns an unregister function. */\nexport function registerSlot(s: RegisteredSlot): () => void {\n if (!isDevBuild()) return NOOP_UNREGISTER;\n state().slots.set(s.id, s);\n emit();\n return () => {\n state().slots.delete(s.id);\n emit();\n };\n}\n\n/** Register the page's declared section ids (from AdaptiveRoot/provider). */\nexport function registerSections(sections: string[]): void {\n if (!isDevBuild()) return;\n state().sections = [...sections];\n emit();\n}\n\nexport function getRegistered(): RegisteredComponent[] {\n return [...state().components.values()];\n}\n\nexport function getRegisteredSlots(): RegisteredSlot[] {\n return [...state().slots.values()];\n}\n\nexport function getRegisteredSections(): string[] {\n return [...state().sections];\n}\n\nexport function subscribeRegistry(fn: () => void): () => void {\n const listeners = state().listeners;\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/** Monotonic snapshot for `useSyncExternalStore` — changes on every registry mutation. */\nexport function getRegistryVersion(): number {\n return state().version;\n}\n","function store(): Record<string, string> {\n const w = window as unknown as { __sentient_overrides?: Record<string, string> };\n if (!w.__sentient_overrides) w.__sentient_overrides = {};\n return w.__sentient_overrides;\n}\n\n/** Force `componentId` to render `variantId` — read by `useAssignment`. */\nexport function setVariantOverride(componentId: string, variantId: string): void {\n store()[componentId] = variantId;\n}\n\nexport function clearVariantOverride(componentId: string): void {\n delete store()[componentId];\n}\n\nexport function getOverrides(): Record<string, string> {\n return { ...store() };\n}\n","import type { SlotResult } from '@sentientui/core';\n\n/**\n * Slot-override store — the channel `useSlotResult` reads (`useAdaptiveTokens` /\n * `AdaptiveGroup`). Separate from `__sentient_overrides` (variant components):\n * a slot result is a token object (`{ tone: 'urgent' }`) or an arm string\n * (`'social_first'`), never a bare variant id. Window-backed so the /devtools\n * bundle and the main bundle share one store.\n */\nfunction store(): Record<string, SlotResult> {\n const w = window as unknown as { __sentient_slot_overrides?: Record<string, SlotResult> };\n if (!w.__sentient_slot_overrides) w.__sentient_slot_overrides = {};\n return w.__sentient_slot_overrides;\n}\n\n/** Force `slotId` to resolve to `result` — read by `useSlotResult`. */\nexport function setSlotOverride(slotId: string, result: SlotResult): void {\n store()[slotId] = result;\n}\n\nexport function clearSlotOverride(slotId: string): void {\n delete store()[slotId];\n}\n\nexport function getSlotOverrides(): Record<string, SlotResult> {\n return { ...store() };\n}\n","import type { SentientClient } from '@sentientui/core';\n\ntype PreviewState = { on: boolean; listeners: Set<() => void> };\nconst ssrFallback: PreviewState = { on: false, listeners: new Set() };\n\n// Window-backed: the /devtools entry (a separate bundle) toggles preview mode\n// and the provider (main bundle) must observe it.\nfunction state(): PreviewState {\n if (typeof window === 'undefined') return ssrFallback;\n const w = window as unknown as { __sentient_preview?: PreviewState };\n if (!w.__sentient_preview) w.__sentient_preview = { on: false, listeners: new Set() };\n return w.__sentient_preview;\n}\n\nexport function setPreviewMode(on: boolean): void {\n const s = state();\n if (s.on === on) return;\n s.on = on;\n for (const fn of s.listeners) fn();\n}\n\nexport function getPreviewMode(): boolean {\n return state().on;\n}\n\nexport function subscribePreview(fn: () => void): () => void {\n const listeners = state().listeners;\n listeners.add(fn);\n return () => {\n listeners.delete(fn);\n };\n}\n\n/**\n * Wraps a client so it writes nothing: reads pass through, all emitters no-op.\n * Used while previewing variants/personas so no `variant_assigned`, goal, or\n * session events are sent.\n */\nexport function createPreviewClient(inner: SentientClient): SentientClient {\n return {\n isLocal: inner.isLocal,\n track: () => undefined,\n goal: () => undefined,\n componentGoal: () => undefined,\n identify: () => undefined,\n fetchWeights: () => Promise.resolve([]),\n getAssignment: (componentId, segment) => inner.getAssignment(componentId, segment),\n assign: (componentId, variantIds, agentData, agentDataByVariant) =>\n inner.assign(componentId, variantIds, agentData, agentDataByVariant),\n // Reads pass through; decide is a write (slot decisions persist server-side)\n // so preview mode never issues it.\n decide: () => Promise.resolve(null),\n getSlotResult: (slotId) => inner.getSlotResult(slotId),\n getPersona: () => inner.getPersona(),\n getGraph: () => inner.getGraph(),\n dispose: () => inner.dispose(),\n destroy: () => inner.destroy(),\n };\n}\n","/**\n * Cross-bundle re-render bus for devtools overrides. The main entry and the\n * /devtools entry are separate bundles, so state and notifications go through\n * window (a version counter + a DOM event) — never module-local state.\n */\nconst EVENT = 'sentient:overrides-changed';\n\ntype VersionWindow = Window & { __sentient_overrides_version?: number };\n\nexport function getOverridesVersion(): number {\n if (typeof window === 'undefined') return 0;\n return (window as VersionWindow).__sentient_overrides_version ?? 0;\n}\n\nexport function notifyOverridesChanged(): void {\n if (typeof window === 'undefined') return;\n const w = window as VersionWindow;\n w.__sentient_overrides_version = (w.__sentient_overrides_version ?? 0) + 1;\n window.dispatchEvent(new Event(EVENT));\n}\n\nexport function subscribeOverridesChanged(fn: () => void): () => void {\n if (typeof window === 'undefined') return () => undefined;\n window.addEventListener(EVENT, fn);\n return () => window.removeEventListener(EVENT, fn);\n}\n","/** Provider → devtools config handoff. Window-backed: the /devtools entry is a\n * separate bundle and cannot share the provider's React context instance. */\nexport type DevtoolsConfig = {\n apiKey: string;\n apiBaseUrl: string;\n isLocal: boolean;\n};\n\ntype ConfigWindow = Window & { __sentient_devtools_config?: DevtoolsConfig };\n\nexport function publishDevtoolsConfig(config: DevtoolsConfig): void {\n if (typeof window === 'undefined') return;\n (window as ConfigWindow).__sentient_devtools_config = config;\n}\n\nexport function readDevtoolsConfig(): DevtoolsConfig | null {\n if (typeof window === 'undefined') return null;\n return (window as ConfigWindow).__sentient_devtools_config ?? null;\n}\n"],"mappings":";k7BAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,sBAAAE,GAAA,+BAAAC,KAAA,eAAAC,GAAAJ,IAGA,IAAAK,EAAoG,iBACpGC,EAA0D,8BAC1DC,EAA2F,4BCgB3F,IAAMC,GAA6B,CACjC,WAAY,IAAI,IAChB,MAAO,IAAI,IACX,SAAU,CAAC,EACX,UAAW,IAAI,IACf,QAAS,CACX,EAEA,SAASC,GAAuB,CAC9B,GAAI,OAAO,QAAW,YAAa,OAAOD,GAC1C,IAAME,EAAI,OACV,OAAKA,EAAE,sBACLA,EAAE,oBAAsB,CACtB,WAAY,IAAI,IAChB,MAAO,IAAI,IACX,SAAU,CAAC,EACX,UAAW,IAAI,IACf,QAAS,CACX,GAEKA,EAAE,mBACX,CA6CO,SAASC,GAAuC,CACrD,MAAO,CAAC,GAAGC,EAAM,EAAE,WAAW,OAAO,CAAC,CACxC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A,OAAC,UACC,aAAW,oBACX,gBAAe8B,EACf,QAAS,IAAMC,EAASmD,GAAM,CAACA,CAAC,EAChC,MAAO,CAAE,MAAO,GAAI,OAAQ,GAAI,aAAc,GAAI,OAAQ,oBAAqB,WAAY,OAClF,QAAS,OAAQ,WAAY,SAAU,eAAgB,SAAU,QAAS,EAC1E,OAAQ,UAAW,UAAW,2BAA4B,EAEnE,mBAACvD,GAAA,EAAa,EAChB,GACF,CAEJ","names":["devtools_exports","__export","AdaptiveDevtools","LOCAL_MODE_DEVTOOLS_BANNER","__toCommonJS","import_react","import_policy","import_core","ssrFallback","state","w","getRegistered","state","getRegisteredSlots","getRegisteredSections","subscribeRegistry","fn","listeners","getRegistryVersion","store","w","setVariantOverride","componentId","variantId","clearVariantOverride","getOverrides","__spreadValues","store","w","setSlotOverride","slotId","result","clearSlotOverride","getSlotOverrides","__spreadValues","ssrFallback","state","w","setPreviewMode","on","s","fn","getPreviewMode","EVENT","notifyOverridesChanged","_a","w","EVENT","readDevtoolsConfig","_a","import_jsx_runtime","_a","IS_PROD","DEFAULT_API_BASE_URL","LOCAL_MODE_DEVTOOLS_BANNER","currentLayout","forced","registered","getRegisteredSections","id","reorderLayout","from","to","order","next","moved","setPreviewMode","notifyOverridesChanged","resetLayout","applyOutcome","result","_b","variantId","setVariantOverride","w","__spreadValues","readSessionId","apiKey","read","name","match","e","slotDecls","getRegisteredSlots","s","DEFAULT_PERSONA_CHOICES","key","fetchPersonaVocabulary","apiBaseUrl","res","data","valid","list","p","personas","forcePersonaKeyed","persona","_c","getRegistered","c","__spreadProps","forcePersonaLocal","mod","outcome","resetAll","getOverrides","clearVariantOverride","stale","i","btn","active","SentientMark","size","AdaptiveDevtools","open","setOpen","activePersona","setActivePersona","vocab","setVocab","discovered","setDiscovered","personaNote","setPersonaNote","dragFrom","setDragFrom","mounted","setMounted","force","subscribeRegistry","getRegistryVersion","cfg","readDevtoolsConfig","cancelled","config","useLocalEngine","components","slots","overrides","slotOverrides","getSlotOverrides","sections","layoutForced","onReorder","onResetLayout","maybeExitPreview","choose","resetVariant","chooseSlotArm","arm","setSlotOverride","chooseSlotDim","dim","value","dims","current","d","values","resetSlot","clearSlotOverride","choosePersona","member","r","getPreviewMode","v","ov","o"]}
package/dist/devtools.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  'use client';
2
- "use client";var ge=Object.defineProperty,fe=Object.defineProperties;var ve=Object.getOwnPropertyDescriptors;var F=Object.getOwnPropertySymbols;var me=Object.prototype.hasOwnProperty,ye=Object.prototype.propertyIsEnumerable;var G=(e,t,o)=>t in e?ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,a=(e,t)=>{for(var o in t||(t={}))me.call(t,o)&&G(e,o,t[o]);if(F)for(var o of F(t))ye.call(t,o)&&G(e,o,t[o]);return e},w=(e,t)=>fe(e,ve(t));import{useEffect as Se,useReducer as he,useState as C,useSyncExternalStore as xe}from"react";import{PERSONAS as Oe,PERSONA_DISPLAY as Re,confidenceBand as ke}from"@sentientui/policy";import{LEGACY_SESSION_COOKIE_NAME as Ce,SNAPSHOT_STORAGE_KEY_PREFIX as Ee,sessionCookieName as Pe}from"@sentientui/core";var _e={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function S(){if(typeof window=="undefined")return _e;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function x(){return[...S().components.values()]}function D(){return[...S().slots.values()]}function O(){return[...S().sections]}function U(e){let t=S().listeners;return t.add(e),()=>{t.delete(e)}}function Y(){return S().version}function W(){let e=window;return e.__sentient_overrides||(e.__sentient_overrides={}),e.__sentient_overrides}function I(e,t){W()[e]=t}function B(e){delete W()[e]}function R(){return a({},W())}function N(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function T(e,t){N()[e]=t}function z(e){delete N()[e]}function k(){return a({},N())}var we={on:!1,listeners:new Set};function H(){if(typeof window=="undefined")return we;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function m(e){let t=H();if(t.on!==e){t.on=e;for(let o of t.listeners)o()}}function J(){return H().on}var be="sentient:overrides-changed";function p(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(be))}function K(){var e;return typeof window=="undefined"?null:(e=window.__sentient_devtools_config)!=null?e:null}import{jsx as i,jsxs as l}from"react/jsx-runtime";var X,Ae=typeof process!="undefined"&&((X=process.env)==null?void 0:X.NODE_ENV)==="production",Le="https://api.sentient-ui.com/v1",De="Local mode \u2014 decisions are simulated; add a key to learn from real traffic";function $(){let e=window.__sentient_layout_override,t=O();return!e||e.length===0?t:[...e,...t.filter(o=>!e.includes(o))]}function We(e,t){let o=$();if(e===t||e<0||t<0||e>=o.length||t>=o.length)return;let r=[...o],[u]=r.splice(e,1);r.splice(t,0,u),window.__sentient_layout_override=r,m(!0),p()}function Ie(){delete window.__sentient_layout_override,p()}function q(e){var o,r;for(let[u,c]of Object.entries((o=e.assignments)!=null?o:{}))I(u,c);let t=window;e.layoutOrder&&e.layoutOrder.length>0&&(t.__sentient_layout_override=e.layoutOrder),e.slots&&(t.__sentient_slot_overrides=a(a({},(r=t.__sentient_slot_overrides)!=null?r:{}),e.slots)),e.personaAttributes&&(document.documentElement.dataset.sentientPersona=e.personaAttributes.persona,document.documentElement.dataset.sentientConfidence=e.personaAttributes.confidence),m(!0),p()}function Be(e){var o,r;let t=u=>{try{let c=document.cookie.match(new RegExp(`(?:^|; )${u}=([^;]*)`));return c?decodeURIComponent(c[1]):null}catch(c){return null}};return(r=(o=e?t(Pe(e)):null)!=null?o:t(Ce))!=null?r:"devtools-preview"}function Q(){return D().map(e=>a(a({id:e.id},e.arms?{arms:e.arms}:{}),e.dims?{dims:e.dims}:{}))}async function Ne(e,t,o){var c;let r=await fetch(`${t}/explain`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({persona:o,sections:O().map(g=>({id:g})),components:x().map(g=>({id:g.id,variantIds:g.variantIds})),slots:Q()})});if(!r.ok)return;let u=await r.json();q(w(a({},u),{personaAttributes:(c=u.personaAttributes)!=null?c:{persona:o,confidence:"high"}}))}async function Te(e,t){let o=await import("@sentientui/core/local");if(!o.LOCAL_ENGINE_AVAILABLE)return;let r=o.createLocalEngine({sessionId:Be(t),forcedPersona:e}).decide({sections:O(),components:x().map(u=>({id:u.id,variantIds:u.variantIds})),slots:Q()});q({assignments:r.assignments,layoutOrder:r.layoutOrder,slots:r.slots,personaAttributes:{persona:r.persona,confidence:ke(r.confidence)}})}function Ve(){for(let t of Object.keys(R()))B(t);let e=window;delete e.__sentient_layout_override,delete e.__sentient_slot_overrides,delete document.documentElement.dataset.sentientPersona,delete document.documentElement.dataset.sentientConfidence;try{let t=[];for(let o=0;o<localStorage.length;o++){let r=localStorage.key(o);r&&r.startsWith(Ee)&&t.push(r)}for(let o of t)localStorage.removeItem(o)}catch(t){}m(!1),p();try{window.location.reload()}catch(t){}}var y=e=>({padding:"2px 8px",borderRadius:4,border:"1px solid #444",background:e?"#3b82f6":"#222",color:"#eee",cursor:"pointer"});function Me({size:e=26}={}){return l("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"none","aria-hidden":"true",children:[i("path",{d:"M21 9H14C11.2 9 9.8 10.8 9.8 13C9.8 15.4 11.6 16.6 14.5 16.6H18.5C20.5 16.6 20.7 18.2 20.4 19.6",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"}),i("path",{d:"M10 22H17",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round"}),i("circle",{cx:"20.6",cy:"22",r:"2.1",fill:"#fff"})]})}function it({apiKey:e}={}){var M;let[t,o]=C(!1),[r,u]=C(null),[c,g]=C(null),[Z,ee]=C(!1),[,f]=he(n=>n+1,0);if(xe(U,Y,()=>0),Se(()=>ee(!0),[]),Ae||!Z)return null;let _=(M=K())!=null?M:{apiKey:e!=null?e:"",apiBaseUrl:Le,isLocal:!1},te=_.isLocal||!_.apiKey,h=x(),E=D(),P=R(),V=k(),A=$(),ne=window.__sentient_layout_override!==void 0;function oe(n,s){We(n,s),f()}function ie(){Ie(),L(),f()}function L(){Object.keys(R()).length===0&&Object.keys(k()).length===0&&window.__sentient_layout_override===void 0&&m(!1)}function re(n,s){I(n,s),m(!0),p(),f()}function se(n){B(n),L(),p(),f()}function de(n,s){T(n,s),m(!0),p(),f()}function ae(n,s,d,b){let v=k()[n],j=v&&typeof v=="object"?a({},v):Object.fromEntries(Object.entries(b!=null?b:{}).map(([ue,pe])=>[ue,pe[0]]));j[s]=d,T(n,j),m(!0),p(),f()}function le(n){z(n),L(),p(),f()}function ce(n){u(n),(te?Te(n,_.apiKey):Ne(_.apiKey,_.apiBaseUrl,n)).then(f).catch(()=>{})}return l("div",{style:{position:"fixed",bottom:16,right:16,zIndex:2147483647,fontFamily:"system-ui"},children:[i("div",{"aria-hidden":!t,style:{position:"absolute",bottom:52,right:0,transformOrigin:"bottom right",transition:"opacity .18s ease, transform .2s cubic-bezier(.16,1,.3,1)",opacity:t?1:0,transform:t?"translateY(0) scale(1)":"translateY(6px) scale(.96)",pointerEvents:t?"auto":"none"},children:l("div",{style:{width:300,maxHeight:460,overflowY:"auto",background:"#111",color:"#eee",borderRadius:8,padding:12,boxShadow:"0 8px 30px rgba(0,0,0,.4)",fontSize:12},children:[_.isLocal&&i("div",{style:{background:"#1e293b",border:"1px solid #334155",borderRadius:4,padding:"6px 8px",marginBottom:8},children:De}),l("div",{style:{opacity:.7,marginBottom:8},children:[h.length," component",h.length===1?"":"s"," \xB7 ",J()?"preview \u2014 writing nothing":"live"]}),l("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[i("div",{style:{opacity:.7,marginBottom:4},children:"Preview persona"}),l("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[Oe.map(n=>i("button",{onClick:()=>ce(n),style:y(r===n),children:Re[n]},n)),(r!==null||Object.keys(P).length>0||Object.keys(V).length>0)&&i("button",{onClick:Ve,style:w(a({},y(!1)),{color:"#aaa"}),children:"Reset"})]})]}),A.length>0&&l("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[l("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[i("span",{style:{opacity:.7},children:"Layout \u2014 drag to reorder"}),ne&&i("button",{"aria-label":"Reset section order",onClick:ie,style:w(a({},y(!1)),{color:"#aaa"}),children:"reset"})]}),i("ul",{"aria-label":"Section order",style:{listStyle:"none",margin:0,padding:0},children:A.map((n,s)=>l("li",{draggable:!0,onDragStart:()=>g(s),onDragOver:d=>d.preventDefault(),onDrop:d=>{d.preventDefault(),c!==null&&oe(c,s),g(null)},onDragEnd:()=>g(null),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",marginBottom:2,borderRadius:4,border:"1px solid #262626",cursor:"grab",background:c===s?"#1e293b":"#181818",opacity:c!==null&&c!==s?.6:1},children:[i("span",{style:{opacity:.4,minWidth:10,fontVariantNumeric:"tabular-nums"},children:s+1}),i("span",{"aria-hidden":"true",style:{opacity:.35},children:"\u283F"}),i("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]},n))})]}),h.length===0&&E.length===0&&A.length===0&&i("div",{style:{opacity:.6},children:"No components, sections or slots on this page yet."}),h.map(n=>l("div",{style:{borderTop:"1px solid #333",padding:"8px 0"},children:[l("div",{style:{fontWeight:600},children:[n.id,n.goal?` \xB7 goal: ${n.goal}`:""]}),l("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:[n.variantIds.map(s=>i("button",{onClick:()=>re(n.id,s),style:y(P[n.id]===s),children:s},s)),P[n.id]&&i("button",{onClick:()=>se(n.id),style:w(a({},y(!1)),{color:"#aaa"}),children:"reset"})]})]},n.id)),E.length>0&&l("div",{style:{borderTop:"1px solid #333",paddingTop:8,marginTop:4},children:[i("div",{style:{opacity:.7,marginBottom:4},children:"Slots"}),E.map(n=>{let s=V[n.id];return l("div",{style:{padding:"6px 0"},children:[i("div",{style:{fontWeight:600},children:n.id}),n.arms&&i("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:n.arms.map(d=>i("button",{onClick:()=>de(n.id,d),style:y(s===d),children:d},d))}),n.dims&&Object.entries(n.dims).map(([d,b])=>l("div",{style:{marginTop:4},children:[i("div",{style:{opacity:.6,fontSize:11},children:d}),i("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:b.map(v=>i("button",{onClick:()=>ae(n.id,d,v,n.dims),style:y(!!s&&typeof s=="object"&&s[d]===v),children:v},v))})]},d)),s!==void 0&&i("button",{onClick:()=>le(n.id),style:w(a({},y(!1)),{color:"#aaa",marginTop:4}),children:"reset"})]},n.id)})]})]})}),i("button",{"aria-label":"Sentient DevTools","aria-expanded":t,onClick:()=>o(n=>!n),style:{width:44,height:44,borderRadius:12,border:"1px solid #2a2a2a",background:"#000",display:"flex",alignItems:"center",justifyContent:"center",padding:0,cursor:"pointer",boxShadow:"0 6px 18px rgba(0,0,0,.4)"},children:i(Me,{})})]})}export{it as AdaptiveDevtools,De as LOCAL_MODE_DEVTOOLS_BANNER};
2
+ "use client";var xe=Object.defineProperty,Oe=Object.defineProperties;var Re=Object.getOwnPropertyDescriptors;var X=Object.getOwnPropertySymbols;var ke=Object.prototype.hasOwnProperty,Ce=Object.prototype.propertyIsEnumerable;var K=(e,t,o)=>t in e?xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,l=(e,t)=>{for(var o in t||(t={}))ke.call(t,o)&&K(e,o,t[o]);if(X)for(var o of X(t))Ce.call(t,o)&&K(e,o,t[o]);return e},b=(e,t)=>Oe(e,Re(t));import{useEffect as ne,useReducer as De,useState as h,useSyncExternalStore as Le}from"react";import{PERSONAS as Ve,PERSONA_DISPLAY as Ne,confidenceBand as We}from"@sentientui/policy";import{LEGACY_SESSION_COOKIE_NAME as Me,SNAPSHOT_STORAGE_KEY_PREFIX as Be,sessionCookieName as Ie}from"@sentientui/core";var Ee={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0};function R(){if(typeof window=="undefined")return Ee;let e=window;return e.__sentient_registry||(e.__sentient_registry={components:new Map,slots:new Map,sections:[],listeners:new Set,version:0}),e.__sentient_registry}function C(){return[...R().components.values()]}function B(){return[...R().slots.values()]}function E(){return[...R().sections]}function q(e){let t=R().listeners;return t.add(e),()=>{t.delete(e)}}function Q(){return R().version}function I(){let e=window;return e.__sentient_overrides||(e.__sentient_overrides={}),e.__sentient_overrides}function T(e,t){I()[e]=t}function j(e){delete I()[e]}function P(){return l({},I())}function z(){let e=window;return e.__sentient_slot_overrides||(e.__sentient_slot_overrides={}),e.__sentient_slot_overrides}function F(e,t){z()[e]=t}function Z(e){delete z()[e]}function A(){return l({},z())}var Pe={on:!1,listeners:new Set};function ee(){if(typeof window=="undefined")return Pe;let e=window;return e.__sentient_preview||(e.__sentient_preview={on:!1,listeners:new Set}),e.__sentient_preview}function _(e){let t=ee();if(t.on!==e){t.on=e;for(let o of t.listeners)o()}}function te(){return ee().on}var Ae="sentient:overrides-changed";function p(){var t;if(typeof window=="undefined")return;let e=window;e.__sentient_overrides_version=((t=e.__sentient_overrides_version)!=null?t:0)+1,window.dispatchEvent(new Event(Ae))}function U(){var e;return typeof window=="undefined"?null:(e=window.__sentient_devtools_config)!=null?e:null}import{jsx as i,jsxs as c}from"react/jsx-runtime";var se,oe=typeof process!="undefined"&&((se=process.env)==null?void 0:se.NODE_ENV)==="production",ie="https://api.sentient-ui.com/v1",Te="Local mode \u2014 decisions are simulated; add a key to learn from real traffic";function de(){let e=window.__sentient_layout_override,t=E();return!e||e.length===0?t:[...e,...t.filter(o=>!e.includes(o))]}function je(e,t){let o=de();if(e===t||e<0||t<0||e>=o.length||t>=o.length)return;let s=[...o],[d]=s.splice(e,1);s.splice(t,0,d),window.__sentient_layout_override=s,_(!0),p()}function ze(){delete window.__sentient_layout_override,p()}function ae(e){var o,s;for(let[d,u]of Object.entries((o=e.assignments)!=null?o:{}))T(d,u);let t=window;e.layoutOrder&&e.layoutOrder.length>0&&(t.__sentient_layout_override=e.layoutOrder),e.slots&&(t.__sentient_slot_overrides=l(l({},(s=t.__sentient_slot_overrides)!=null?s:{}),e.slots)),e.personaAttributes&&(document.documentElement.dataset.sentientPersona=e.personaAttributes.persona,document.documentElement.dataset.sentientConfidence=e.personaAttributes.confidence),_(!0),p()}function Fe(e){var o,s;let t=d=>{try{let u=document.cookie.match(new RegExp(`(?:^|; )${d}=([^;]*)`));return u?decodeURIComponent(u[1]):null}catch(u){return null}};return(s=(o=e?t(Ie(e)):null)!=null?o:t(Me))!=null?s:"devtools-preview"}function le(){return B().map(e=>l(l({id:e.id},e.arms?{arms:e.arms}:{}),e.dims?{dims:e.dims}:{}))}var re=Ve.map(e=>({key:e,displayName:Ne[e]}));async function Ue(e,t){try{let o=await fetch(`${t}/personas`,{headers:{authorization:`Bearer ${e}`}});if(!o.ok)return null;let s=await o.json(),d=w=>Array.isArray(w)?w.filter(g=>g&&typeof g.key=="string"&&typeof g.displayName=="string"):[],u=d(s.personas);return u.length>0?{personas:u,discovered:d(s.discovered)}:null}catch(o){return null}}async function Ge(e,t,o){var u,w,g;let s=await fetch(`${t}/explain`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify({persona:o,sections:E().map(S=>({id:S})),components:C().map(S=>({id:S.id,variantIds:S.variantIds})),slots:le()})});if(!s.ok)return null;let d=await s.json();return ae(b(l({},d),{personaAttributes:(u=d.personaAttributes)!=null?u:{persona:o,confidence:"high"}})),{recognized:d.recognized!==!1,resolvedDisplay:(g=(w=d.personaDisplay)!=null?w:d.persona)!=null?g:o}}async function $e(e,t){let o=await import("@sentientui/core/local");if(!o.LOCAL_ENGINE_AVAILABLE)return;let s=o.createLocalEngine({sessionId:Fe(t),forcedPersona:e}).decide({sections:E(),components:C().map(d=>({id:d.id,variantIds:d.variantIds})),slots:le()});ae({assignments:s.assignments,layoutOrder:s.layoutOrder,slots:s.slots,personaAttributes:{persona:s.persona,confidence:We(s.confidence)}})}function He(){for(let t of Object.keys(P()))j(t);let e=window;delete e.__sentient_layout_override,delete e.__sentient_slot_overrides,delete document.documentElement.dataset.sentientPersona,delete document.documentElement.dataset.sentientConfidence;try{let t=[];for(let o=0;o<localStorage.length;o++){let s=localStorage.key(o);s&&s.startsWith(Be)&&t.push(s)}for(let o of t)localStorage.removeItem(o)}catch(t){}_(!1),p();try{window.location.reload()}catch(t){}}var y=e=>({padding:"2px 8px",borderRadius:4,border:"1px solid #444",background:e?"#3b82f6":"#222",color:"#eee",cursor:"pointer"});function Ye({size:e=26}={}){return c("svg",{width:e,height:e,viewBox:"0 0 32 32",fill:"none","aria-hidden":"true",children:[i("path",{d:"M21 9H14C11.2 9 9.8 10.8 9.8 13C9.8 15.4 11.6 16.6 14.5 16.6H18.5C20.5 16.6 20.7 18.2 20.4 19.6",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"}),i("path",{d:"M10 22H17",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round"}),i("circle",{cx:"20.6",cy:"22",r:"2.1",fill:"#fff"})]})}function pt({apiKey:e}={}){var Y;let[t,o]=h(!1),[s,d]=h(null),[u,w]=h(null),[g,S]=h([]),[G,$]=h(null),[O,D]=h(null),[ce,ue]=h(!1),[,f]=De(n=>n+1,0);if(Le(q,Q,()=>0),ne(()=>ue(!0),[]),ne(()=>{var a;if(oe)return;let n=(a=U())!=null?a:{apiKey:e!=null?e:"",apiBaseUrl:ie,isLocal:!1};if(n.isLocal||!n.apiKey)return;let r=!1;return Ue(n.apiKey,n.apiBaseUrl).then(v=>{r||!v||(w(v.personas),S(v.discovered))}),()=>{r=!0}},[e]),oe||!ce)return null;let x=(Y=U())!=null?Y:{apiKey:e!=null?e:"",apiBaseUrl:ie,isLocal:!1},L=x.isLocal||!x.apiKey,k=C(),V=B(),N=P(),H=A(),W=de(),pe=window.__sentient_layout_override!==void 0;function ge(n,r){je(n,r),f()}function fe(){ze(),M(),f()}function M(){Object.keys(P()).length===0&&Object.keys(A()).length===0&&window.__sentient_layout_override===void 0&&_(!1)}function ve(n,r){T(n,r),_(!0),p(),f()}function ye(n){j(n),M(),p(),f()}function me(n,r){F(n,r),_(!0),p(),f()}function _e(n,r,a,v){let m=A()[n],J=m&&typeof m=="object"?l({},m):Object.fromEntries(Object.entries(v!=null?v:{}).map(([he,Se])=>[he,Se[0]]));J[r]=a,F(n,J),_(!0),p(),f()}function we(n){Z(n),M(),p(),f()}function be(n){if(d(n.key),$(null),L){$e(n.key,x.apiKey).then(f).catch(()=>{});return}Ge(x.apiKey,x.apiBaseUrl,n.key).then(r=>{r&&!r.recognized&&$(`\u201C${n.displayName}\u201D isn\u2019t in this project\u2019s personas \u2014 the page is showing the default experience.`),f()}).catch(()=>{})}return c("div",{style:{position:"fixed",bottom:16,right:16,zIndex:2147483647,fontFamily:"system-ui"},children:[i("div",{"aria-hidden":!t,style:{position:"absolute",bottom:52,right:0,transformOrigin:"bottom right",transition:"opacity .18s ease, transform .2s cubic-bezier(.16,1,.3,1)",opacity:t?1:0,transform:t?"translateY(0) scale(1)":"translateY(6px) scale(.96)",pointerEvents:t?"auto":"none"},children:c("div",{style:{width:300,maxHeight:460,overflowY:"auto",background:"#111",color:"#eee",borderRadius:8,padding:12,boxShadow:"0 8px 30px rgba(0,0,0,.4)",fontSize:12},children:[x.isLocal&&i("div",{style:{background:"#1e293b",border:"1px solid #334155",borderRadius:4,padding:"6px 8px",marginBottom:8},children:Te}),c("div",{style:{opacity:.7,marginBottom:8},children:[k.length," component",k.length===1?"":"s"," \xB7 ",te()?"preview \u2014 writing nothing":"live"]}),c("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[i("div",{style:{opacity:.7,marginBottom:4},children:"Preview persona"}),c("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[(L?re:u!=null?u:re).map(n=>i("button",{onClick:()=>be(n),style:y(s===n.key),children:n.displayName},n.key)),(s!==null||Object.keys(N).length>0||Object.keys(H).length>0)&&i("button",{onClick:He,style:b(l({},y(!1)),{color:"#aaa"}),children:"Reset"})]}),G&&i("div",{style:{marginTop:6,fontSize:11,color:"#fbbf24"},children:G}),!L&&g.length>0&&c("div",{style:{marginTop:8},children:[i("div",{style:{opacity:.5,fontSize:11,marginBottom:4},children:"Discovered \u2014 not serving yet (promote from the dashboard)"}),i("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:g.map(n=>i("span",{title:"Found by clustering your traffic; it starts serving only after promotion.",style:b(l({},y(!1)),{opacity:.45,cursor:"default",display:"inline-block"}),children:n.displayName},n.key))})]})]}),W.length>0&&c("div",{style:{borderBottom:"1px solid #333",paddingBottom:8,marginBottom:8},children:[c("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[i("span",{style:{opacity:.7},children:"Layout \u2014 drag to reorder"}),pe&&i("button",{"aria-label":"Reset section order",onClick:fe,style:b(l({},y(!1)),{color:"#aaa"}),children:"reset"})]}),i("ul",{"aria-label":"Section order",style:{listStyle:"none",margin:0,padding:0},children:W.map((n,r)=>c("li",{draggable:!0,onDragStart:()=>D(r),onDragOver:a=>a.preventDefault(),onDrop:a=>{a.preventDefault(),O!==null&&ge(O,r),D(null)},onDragEnd:()=>D(null),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 6px",marginBottom:2,borderRadius:4,border:"1px solid #262626",cursor:"grab",background:O===r?"#1e293b":"#181818",opacity:O!==null&&O!==r?.6:1},children:[i("span",{style:{opacity:.4,minWidth:10,fontVariantNumeric:"tabular-nums"},children:r+1}),i("span",{"aria-hidden":"true",style:{opacity:.35},children:"\u283F"}),i("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n})]},n))})]}),k.length===0&&V.length===0&&W.length===0&&i("div",{style:{opacity:.6},children:"No components, sections or slots on this page yet."}),k.map(n=>c("div",{style:{borderTop:"1px solid #333",padding:"8px 0"},children:[c("div",{style:{fontWeight:600},children:[n.id,n.goal?` \xB7 goal: ${n.goal}`:""]}),c("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:[n.variantIds.map(r=>i("button",{onClick:()=>ve(n.id,r),style:y(N[n.id]===r),children:r},r)),N[n.id]&&i("button",{onClick:()=>ye(n.id),style:b(l({},y(!1)),{color:"#aaa"}),children:"reset"})]})]},n.id)),V.length>0&&c("div",{style:{borderTop:"1px solid #333",paddingTop:8,marginTop:4},children:[i("div",{style:{opacity:.7,marginBottom:4},children:"Slots"}),V.map(n=>{let r=H[n.id];return c("div",{style:{padding:"6px 0"},children:[i("div",{style:{fontWeight:600},children:n.id}),n.arms&&i("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:n.arms.map(a=>i("button",{onClick:()=>me(n.id,a),style:y(r===a),children:a},a))}),n.dims&&Object.entries(n.dims).map(([a,v])=>c("div",{style:{marginTop:4},children:[i("div",{style:{opacity:.6,fontSize:11},children:a}),i("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:v.map(m=>i("button",{onClick:()=>_e(n.id,a,m,n.dims),style:y(!!r&&typeof r=="object"&&r[a]===m),children:m},m))})]},a)),r!==void 0&&i("button",{onClick:()=>we(n.id),style:b(l({},y(!1)),{color:"#aaa",marginTop:4}),children:"reset"})]},n.id)})]})]})}),i("button",{"aria-label":"Sentient DevTools","aria-expanded":t,onClick:()=>o(n=>!n),style:{width:44,height:44,borderRadius:12,border:"1px solid #2a2a2a",background:"#000",display:"flex",alignItems:"center",justifyContent:"center",padding:0,cursor:"pointer",boxShadow:"0 6px 18px rgba(0,0,0,.4)"},children:i(Ye,{})})]})}export{pt as AdaptiveDevtools,Te as LOCAL_MODE_DEVTOOLS_BANNER};
3
3
  //# sourceMappingURL=devtools.mjs.map