@codeyam-editor/codeyam-editor 0.1.9 → 0.1.10

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.
@@ -0,0 +1,18 @@
1
+ import{j as n}from"./markdown-C9tbsVHX.js";import{b as c}from"./react-nrLBr15I.js";import{a as jt,u as wt,d as Xr,C as he,c as Jr}from"./useServerIdentity-CVuHTzjg.js";import{u as qr}from"./useEvents-S3Qk1Y_d.js";import{r as Gr,a as Qr}from"./xterm--24IGk-x.js";import{l as U,j as Zr}from"./index-sW8wcg7v.js";const St="Connected to the editor server at ";function kt(e){const t=e===null?null:e?"in the cloud container":"on this machine";return t?`, running ${t}.`:"."}function en(e,t){return e===null?null:`${St}${e}${kt(t)}`}function tn({headline:e,explanation:t,nextAction:r,diagnostics:a,connection:s}){const o=[`CodeYam editor — ${e}`,`What happened
2
+ ${t}`,`What to do
3
+ ${r}`],i=a==null?void 0:a.trim();i&&o.push(`Details
4
+ ${i}`);const l=s==null?void 0:s.trim();return l&&o.push(`Connection
5
+ ${l}`),o.join(`
6
+
7
+ `)}function He(e){return typeof e=="string"?e:typeof e=="number"?String(e):Array.isArray(e)?e.map(He).join(""):""}const rn={error:{accent:"var(--accent-red, #dc2626)",surface:"var(--bg-base)",label:"Error"},warning:{accent:"var(--accent-amber, #d97706)",surface:"var(--bg-base)",label:"Warning"},blocked:{accent:"var(--accent-primary, #2563eb)",surface:"var(--bg-base)",label:"Blocked"}};function Ct({headline:e,palette:t,report:r,copyLabel:a}){return n.jsxs("div",{className:"flex items-start justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide",style:{color:t.accent},children:t.label}),n.jsx("h2",{className:"text-base font-semibold leading-snug",children:e})]}),n.jsx(jt,{variant:"subtle",text:r,label:a,ariaLabel:`Copy this report: ${e}`})]})}const Ks=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeHeader:Ct},Symbol.toStringTag,{value:"Module"}));function Nt({nextAction:e,palette:t}){return n.jsxs("div",{className:"rounded border-l-2 pl-3",style:{borderLeftColor:t.accent},children:[n.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide",style:{color:t.accent},children:"What to do"}),n.jsx("div",{style:{color:"var(--text-primary)"},children:e})]})}const Hs=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeNextAction:Nt},Symbol.toStringTag,{value:"Module"}));function Tt({diagnostics:e,testId:t}){return n.jsx("pre",{"data-testid":t,className:"m-0 max-h-48 overflow-auto whitespace-pre-wrap rounded px-3 py-2 font-mono text-xs leading-snug",style:{background:"var(--bg-surface)",color:"var(--text-secondary)"},children:e})}const Us=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeDiagnostics:Tt},Symbol.toStringTag,{value:"Module"}));function Et({actions:e,palette:t,actionFeedback:r}){return e.length===0&&!r?null:n.jsxs(n.Fragment,{children:[e.length>0?n.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.map(a=>n.jsx("button",{type:"button",onClick:a.onClick,disabled:a.pending,"aria-label":a.ariaLabel,"data-testid":a.testId,className:"rounded px-3 py-1.5 text-sm font-medium disabled:cursor-not-allowed disabled:opacity-70",style:a.variant==="secondary"?{border:"1px solid var(--border-default)",color:"var(--text-primary)"}:{background:t.accent,color:"var(--bg-base)"},children:a.pending?a.pendingLabel??`${a.label}…`:a.label},a.label))}):null,r?n.jsx("div",{className:"text-xs",style:{color:"var(--text-dim)"},children:r}):null]})}const Ys=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeActions:Et},Symbol.toStringTag,{value:"Module"}));function te({headline:e,explanation:t,nextAction:r,explanationText:a,nextActionText:s,diagnostics:o,severity:i="error",actions:l=[],actionFeedback:u,copyLabel:f="Copy this report",testId:x,className:h}){const{projectDir:d,inContainer:m,loaded:b}=wt(),g=rn[i],y=b?en(d,m):null,p=tn({headline:e,explanation:a??He(t),nextAction:s??He(r),diagnostics:o,connection:y});return n.jsxs("div",{role:"alert","aria-label":e,"data-testid":x,className:h??"flex w-full max-w-2xl flex-col gap-3 rounded-lg border border-l-4 p-5 text-sm shadow-lg",style:{background:g.surface,borderColor:"var(--border-default)",borderLeftColor:g.accent,color:"var(--text-primary)"},children:[n.jsx(Ct,{headline:e,palette:g,report:p,copyLabel:f}),n.jsx("p",{style:{color:"var(--text-dim)"},children:t}),n.jsx(Nt,{nextAction:r,palette:g}),o?n.jsx(Tt,{diagnostics:o,testId:x?`${x}-diagnostics`:void 0}):null,n.jsx(Et,{actions:l,palette:g,actionFeedback:u}),d!==null&&b?n.jsxs("p",{className:"text-xs",style:{color:"var(--text-dim)"},children:[St,n.jsx("code",{children:d}),kt(m)]}):null]})}const Ws=Object.freeze(Object.defineProperty({__proto__:null,ErrorNotice:te},Symbol.toStringTag,{value:"Module"})),Ne=c.createContext({openPicker:()=>{},registerFileSink:()=>{}});function nn({fallbackUpload:e,children:t}){const r=c.useRef(null),a=c.useRef(null),s=c.useCallback(u=>{a.current=u},[]),o=c.useCallback(()=>{var u;(u=r.current)==null||u.click()},[]),i=c.useCallback(async u=>{const f=u.target,x=Array.from(f.files??[]).filter(d=>d.size>0);if(f.value="",x.length===0)return;const h=a.current;h&&await h(x)||e(x)},[e]),l=c.useMemo(()=>({openPicker:o,registerFileSink:s}),[o,s]);return n.jsxs(Ne.Provider,{value:l,children:[t,n.jsx("input",{ref:r,type:"file",multiple:!0,onChange:u=>void i(u),style:{display:"none"},"data-testid":"global-file-picker-input"})]})}function Ot(){return c.useContext(Ne)}function an(e,t){const{registerFileSink:r}=c.useContext(Ne);c.useEffect(()=>{if(t)return r(e),()=>r(null)},[r,e,t])}function At(){const{registerFileSink:e}=c.useContext(Ne);return{registerFileSink:e}}const Vs=Object.freeze(Object.defineProperty({__proto__:null,FilePickerProvider:nn,useFilePicker:Ot,useFilePickerChannel:At,useRegisterFilePickerSink:an},Symbol.toStringTag,{value:"Module"}));function ue({onRetry:e,onRecheck:t,rechecking:r,retryLabel:a="Retry",retryTestId:s,recheckTestId:o}){return n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{onClick:e,"data-testid":s,className:"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:a}),n.jsx("button",{onClick:t,"data-testid":o,disabled:r,className:"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:r?"Rechecking…":"I already logged in — recheck"})]})}const Xs=Object.freeze(Object.defineProperty({__proto__:null,RecoveryActions:ue},Symbol.toStringTag,{value:"Module"})),Qe="claude";function sn(e){return e==="claude"}function me(e){switch(e){case"codex":return"Codex";case"gemini":return"Gemini";case"opencode":return"OpenCode";default:return"Claude"}}const Ue={state:"unknown",provider:Qe,credsPresent:!0,cliInstalled:!0,cliRunnable:null,cliFailure:null,scannedDirs:[],reason:null,expiresAt:null,probeInFlight:!1,probeAttempts:0,backendFieldAbsent:!1};function on(e){if(e==null)return{...Ue,backendFieldAbsent:!0};if(typeof e!="object")return Ue;const t=e,r=t.state==="authenticated"||t.state==="needs-login"||t.state==="unknown"?t.state:"unknown",a=t.provider==="claude"||t.provider==="codex"||t.provider==="gemini"||t.provider==="opencode"?t.provider:Qe,s=typeof t.credsPresent=="boolean"?t.credsPresent:!0,o=typeof t.cliInstalled=="boolean"?t.cliInstalled:!0,i=typeof t.cliRunnable=="boolean"?t.cliRunnable:null,l=i===!1&&typeof t.cliFailure=="string"?t.cliFailure:null,u=Array.isArray(t.scannedDirs)?t.scannedDirs.filter(m=>typeof m=="string"):[],f=t.reason==="token-expired"||t.reason==="api-401"||t.reason==="no-credentials"||t.reason==="probe-timeout"||t.reason==="config-corrupt"||t.reason==="cli-not-found"?t.reason:null,x=typeof t.tokenExpiresAt=="string"?t.tokenExpiresAt:typeof t.expiresAt=="string"?t.expiresAt:null,h=typeof t.probeInFlight=="boolean"?t.probeInFlight:!1,d=typeof t.probeAttempts=="number"&&Number.isFinite(t.probeAttempts)&&t.probeAttempts>=0?t.probeAttempts:0;return{state:r,provider:a,credsPresent:s,cliInstalled:o,cliRunnable:i,cliFailure:l,scannedDirs:u,reason:f,expiresAt:x,probeInFlight:h,probeAttempts:d,backendFieldAbsent:!1}}const ln=1e3;function cn(){const[e,t]=c.useState(Ue),r=c.useRef(e.state);r.current=e.state;const a=c.useCallback(async()=>{try{const s=await fetch("/api/config");if(!s.ok)return;const o=await s.json();t(on(o.providerAuth))}catch{}},[]);return c.useEffect(()=>{a()},[a]),c.useEffect(()=>{if(e.state!=="unknown")return;const s=window.setInterval(()=>{r.current==="unknown"&&a()},ln);return()=>window.clearInterval(s)},[e.state,a]),c.useEffect(()=>{const s=()=>{t(o=>({...o,state:"needs-login"})),a()};return window.addEventListener("agent-auth-required",s),()=>window.removeEventListener("agent-auth-required",s)},[a]),c.useEffect(()=>{const s=()=>{t(o=>({...o,state:"authenticated"})),a()};return window.addEventListener("agent-auth-resolved",s),()=>window.removeEventListener("agent-auth-resolved",s)},[a]),{state:e.state,provider:e.provider,credsPresent:e.credsPresent,cliInstalled:e.cliInstalled,cliRunnable:e.cliRunnable,cliFailure:e.cliFailure,scannedDirs:e.scannedDirs,reason:e.reason,expiresAt:e.expiresAt,probeInFlight:e.probeInFlight,probeAttempts:e.probeAttempts,backendFieldAbsent:e.backendFieldAbsent,refresh:a}}var dn=Gr(),un=Qr();function fn(e){if(typeof e!="object"||e===null)return null;const{provider:t,stanza:r,file:a,setupCommand:s}=e;return typeof t!="string"||typeof r!="string"||typeof a!="string"||typeof s!="string"?null:{provider:t,stanza:r,file:a,setupCommand:s}}const pn=3e3;function Mt(){const[e,t]=c.useState(null),[r,a]=c.useState(!0),[s,o]=c.useState(null),i=c.useRef(null),l=c.useCallback(async()=>{try{const u=await fetch("/api/config");if(!u.ok)throw new Error(`HTTP ${u.status}`);const f=await u.json(),x={projectTitle:f.projectTitle??null,projectDescription:f.projectDescription??null,provider:f.provider??Qe,port:f.port??3e3,previewOrigin:f.previewOrigin??null,screenSizes:f.screenSizes??{},defaultScreenSize:f.defaultScreenSize??null,apps:f.apps??[],admin:f.admin??!1,mobileTerminalCommands:f.mobileTerminalCommands??[],launcherUrl:f.launcherUrl??null,projectCount:f.projectCount??0,setupBrowserEnabled:f.setupBrowserEnabled??!1,claudePermissionModeAuto:f.claudePermissionModeAuto??!0,previewDedicatedOriginUnavailable:f.previewDedicatedOriginUnavailable??!1,previewDedicatedOriginHint:fn(f.previewDedicatedOriginHint),onManagedFleetVm:f.onManagedFleetVm??!1},h=JSON.stringify(x);h!==i.current&&(i.current=h,t(x)),o(null)}catch(u){o(u instanceof Error?u.message:"Failed to load config")}finally{a(!1)}},[]);return c.useEffect(()=>{l();const u=setInterval(()=>{l()},pn);return()=>clearInterval(u)},[l]),{config:e,apps:(e==null?void 0:e.apps)??[],loading:r,error:s,refetch:l}}function hn(e){const t=window.location.protocol==="https:"?"wss:":"ws:",r=new URL(`${t}//${window.location.host}/ws/terminal`);return e!=null&&e.provider&&r.searchParams.set("provider",e.provider),e!=null&&e.mode&&r.searchParams.set("mode",e.mode),e!=null&&e.sessionId&&r.searchParams.set("sessionId",e.sessionId),e!=null&&e.chatKey&&r.searchParams.set("chatKey",e.chatKey),e!=null&&e.launch&&r.searchParams.set("launch","1"),e!=null&&e.cols&&e.cols>0&&r.searchParams.set("cols",String(e.cols)),e!=null&&e.rows&&e.rows>0&&r.searchParams.set("rows",String(e.rows)),r.toString()}const mn=20,bn=1;function xn(e,t){const r=t===bn?e:e/mn;return Math.trunc(r)||Math.sign(r)}function gn(){if(typeof navigator>"u")return!1;const e=navigator.platform??"";return e?/Mac|iPhone|iPad|iPod/i.test(e):/Mac|iPhone|iPad|iPod/i.test(navigator.userAgent??"")}function yn(e,t,r={}){const a=r.isMac??gn(),s=r.onError,o=r.onCopy;let i=null;async function l(b){if(!b)return!1;let g=!1;try{g=await Xr(b)}catch(y){return s==null||s(at("copy",y)),!1}if(g){try{e.clearSelection()}catch{}o==null||o()}else s==null||s(_n("copy"));return g}async function u(){return e.hasSelection()?l(e.getSelection()):!1}async function f(){try{const b=await navigator.clipboard.readText();b&&e.paste(b)}catch(b){s==null||s(at("paste",b))}}function x(b){return b.type!=="keydown"?!0:a?(b.metaKey&&!b.ctrlKey&&!b.altKey&&b.key.toLowerCase()==="c"||b.ctrlKey&&!b.metaKey&&!b.altKey&&!b.shiftKey&&b.key.toLowerCase()==="c")&&e.hasSelection()?(u(),!1):!0:(b.ctrlKey&&b.shiftKey&&!b.metaKey&&!b.altKey&&b.key.toLowerCase()==="c"||b.ctrlKey&&!b.shiftKey&&!b.metaKey&&!b.altKey&&b.key.toLowerCase()==="c")&&e.hasSelection()?(u(),!1):!0}e.attachCustomKeyEventHandler(x);function h(){if(!i)return;const{root:b,onDocumentClick:g,onKeyDown:y}=i;document.removeEventListener("mousedown",g,!0),document.removeEventListener("keydown",y,!0),b.remove(),i=null}function d(b,g,y){h();const p=document.createElement("div");p.setAttribute("data-terminal-clipboard-menu","true"),p.style.position="fixed",p.style.left=`${b}px`,p.style.top=`${g}px`,p.style.zIndex="1000",p.style.minWidth="180px",p.style.padding="4px 0",p.style.background="var(--bg-card)",p.style.border="1px solid var(--border-subtle)",p.style.borderRadius="6px",p.style.boxShadow="0 8px 24px rgba(0, 0, 0, 0.35)",p.style.fontSize="12px",p.style.color="var(--text-primary)",p.style.userSelect="none";const j=a?"⌘C":"Ctrl+Shift+C",v=a?"⌘V":"Ctrl+Shift+V",_=Ie("Copy",j,!y,()=>{l(y),h()}),w=Ie("Paste",v,!1,()=>{f(),h()}),S=Ie("Select All","",!1,()=>{try{e.selectAll()}catch{}const C=e.hasSelection()?e.getSelection():"";l(C),h()});p.appendChild(_),p.appendChild(w),p.appendChild(S),document.body.appendChild(p),vn(p,b,g);const T=C=>{p.contains(C.target)||h()},$=C=>{C.key==="Escape"&&(C.preventDefault(),h())};document.addEventListener("mousedown",T,!0),document.addEventListener("keydown",$,!0),i={root:p,onDocumentClick:T,onKeyDown:$}}function m(b){b.preventDefault();const g=e.hasSelection()?e.getSelection():"";d(b.clientX,b.clientY,g)}return t.addEventListener("contextmenu",m),()=>{t.removeEventListener("contextmenu",m),h(),e.attachCustomKeyEventHandler(()=>!0)}}function Ie(e,t,r,a){const s=document.createElement("button");s.type="button",s.disabled=r,s.style.display="flex",s.style.justifyContent="space-between",s.style.alignItems="center",s.style.gap="16px",s.style.width="100%",s.style.padding="6px 12px",s.style.border="none",s.style.background="transparent",s.style.textAlign="left",s.style.fontSize="12px",s.style.cursor=r?"default":"pointer",s.style.color=r?"var(--text-dim)":"var(--text-primary)";const o=document.createElement("span");if(o.textContent=e,s.appendChild(o),t){const i=document.createElement("span");i.textContent=t,i.style.color="var(--text-dim)",i.style.fontSize="11px",s.appendChild(i)}return r||(s.addEventListener("mouseenter",()=>{s.style.background="var(--border-subtle)"}),s.addEventListener("mouseleave",()=>{s.style.background="transparent"}),s.addEventListener("click",()=>a())),s}function vn(e,t,r){const a=typeof window<"u"?window.innerWidth:0,s=typeof window<"u"?window.innerHeight:0;if(!a||!s)return;const o=e.getBoundingClientRect(),i=4;let l=t,u=r;o.width&&t+o.width+i>a&&(l=Math.max(i,a-o.width-i)),o.height&&r+o.height+i>s&&(u=Math.max(i,s-o.height-i)),e.style.left=`${l}px`,e.style.top=`${u}px`}function at(e,t){const r=t instanceof Error?t.message:String(t);return`Clipboard ${e} failed: ${r}`}function _n(e){return`Clipboard ${e} blocked by the browser.`}function jn(e,t,r,a,s,o){const i=e.leftBorderCol+1;if(t===a)return s-r;if(a<t){let f=r-i;f+=1;for(let h=a+1;h<t;h++){const d=o(h);if(d===null)return null;f+=Math.max(1,d-i+1)}const x=o(a);return x===null?null:(f+=Math.max(0,x-s),-f)}const l=o(t);if(l===null)return null;let u=Math.max(0,l-r)+1;for(let f=t+1;f<a;f++){const x=o(f);if(x===null)return null;u+=Math.max(1,x-i+1)}return u+=s-i,u}const ve=new Set(["│","┃","║","|"]);function wn(e,t,r,a){const s=e.baseY,o=(m,b)=>{const g=e.getLine(s+m);if(!g)return null;const y=g.getCell(b);return y?y.getChars():null},i=m=>{let b=-1;for(let y=0;y<r;y++){const p=o(m,y);if(p!==null&&ve.has(p)){b=y;break}}if(b===-1)return null;let g=-1;for(let y=r-1;y>b;y--){const p=o(m,y);if(p!==null&&ve.has(p)){g=y;break}}return g===-1?null:{leftBorderCol:b,rightBorderCol:g}};let l=t,u=i(t);if(!u){const m=i(t-1);if(m)l=t-1,u=m;else{const b=i(t+1);b&&(l=t+1,u=b)}}if(!u)return null;const{leftBorderCol:f,rightBorderCol:x}=u;let h=l;for(let m=l-1;m>=0;m--){const b=o(m,f);if(b===null)break;if(!(b===""||b===" ")){if(!ve.has(b))break;h=m}}let d=l;for(let m=l+1;m<a;m++){const b=o(m,f);if(b===null)break;if(!(b===""||b===" ")){if(!ve.has(b))break;d=m}}return{topRow:h,bottomRow:d,leftBorderCol:f,rightBorderCol:x}}function Sn(e,t,r,a){const s=e.getLine(e.baseY+t);if(!s)return null;for(let o=a;o>=r;o--){const i=s.getCell(o);if(!i)continue;const l=i.getChars();if(l!==""&&l!==" ")return o}return r-1}const kn=200;function Cn(e){const{click:t,terminal:r,cellSurface:a,debug:s}=e,o=r.buffer.active,i=_=>{s==null||s({cursorY:o.cursorY,cursorX:o.cursorX,originalTargetCol:_.originalTargetCol??_.targetCol,snapped:_.snapped??!1,..._})};if(o.type==="alternate")return i({targetRow:-1,targetCol:-1,box:null,rejected:"alt-screen",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(o.viewportY!==o.baseY)return i({targetRow:-1,targetCol:-1,box:null,rejected:"scrollback",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const l=a.getBoundingClientRect();if(l.width===0||l.height===0)return i({targetRow:-1,targetCol:-1,box:null,rejected:"outside-grid",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const u=t.clientX-l.left,f=t.clientY-l.top;if(u<0||f<0||u>=l.width||f>=l.height)return i({targetRow:-1,targetCol:-1,box:null,rejected:"outside-grid",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const x=l.width/r.cols,h=l.height/r.rows,d=Math.floor(u/x),m=Math.floor(f/h),b=r.modes.applicationCursorKeysMode,g=b?"\x1BOC":"\x1B[C",y=b?"\x1BOD":"\x1B[D",p=wn(o,o.cursorY,r.cols,r.rows);if(p){if(m<p.topRow||m>p.bottomRow)return i({targetRow:m,targetCol:d,box:p,rejected:"out-of-box",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(d<=p.leftBorderCol||d>=p.rightBorderCol)return i({targetRow:m,targetCol:d,box:p,rejected:"border",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const _=p.leftBorderCol+1,w=p.rightBorderCol-1,S=k=>Sn(o,k,_,w),T=o.cursorY<p.topRow||o.cursorY>p.bottomRow,$=T?p.bottomRow:o.cursorY,C=T?w:o.cursorX,L=m!==$;let N=null;if(L&&(N=S(m),N===null))return i({targetRow:m,targetCol:d,originalTargetCol:d,snapped:!1,box:p,rejected:"unreadable-row",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;let I=d,P=!1;if(L&&N!==null){const k=Math.max(_,N);d>k&&(I=k,P=!0)}if(m===$&&I===C)return i({targetRow:m,targetCol:I,originalTargetCol:d,snapped:P,box:p,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const D=jn(p,$,C,m,I,S);if(D===null)return i({targetRow:m,targetCol:I,originalTargetCol:d,snapped:P,box:p,rejected:"unreadable-row",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(D===0)return i({targetRow:m,targetCol:I,originalTargetCol:d,snapped:P,box:p,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(Math.abs(D)>kn)return i({targetRow:m,targetCol:I,originalTargetCol:d,snapped:P,box:p,rejected:"emit-cap",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const E=D<0?y.repeat(-D):g.repeat(D);return i({targetRow:m,targetCol:I,originalTargetCol:d,snapped:P,box:p,rejected:null,emittedDirection:D<0?"left":"right",emittedByteCount:E.length,predictedCursorY:m,predictedCursorX:I}),E}if(m!==o.cursorY)return i({targetRow:m,targetCol:d,box:null,rejected:"out-of-box",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const j=d-o.cursorX;if(j===0)return i({targetRow:m,targetCol:d,box:null,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const v=j<0?y.repeat(-j):g.repeat(j);return i({targetRow:m,targetCol:d,box:null,rejected:null,emittedDirection:j<0?"left":"right",emittedByteCount:v.length,predictedCursorY:m,predictedCursorX:d}),v}const st=1;function Nn(e,t){const{sendInput:r,pixelThreshold:a=3,timeThresholdMs:s=300,now:o=()=>Date.now(),onVerificationDisable:i}=t,l=e.element;if(!l)return()=>{};const u=l.querySelector(".xterm-screen")??l;let f=null,x=!1,h=null,d=null;const m=typeof e.onRender=="function"?e.onRender.bind(e):null;m&&(d=m(()=>{const y=h;if(!y)return;h=null;const p=e.buffer.active,j=Math.abs(p.cursorY-y.y),v=Math.abs(p.cursorX-y.x);if(j>st||v>st){x=!0;const _={predicted:y,actual:{y:p.cursorY,x:p.cursorX}};i?i(_):console.warn("[click-cursor] disabled — cursor diverged from prediction",_)}}));function b(y){if(y.button!==0||y.altKey||y.shiftKey||y.metaKey||y.ctrlKey){f=null;return}f={clientX:y.clientX,clientY:y.clientY,at:o()}}function g(y){var $;const p=f;if(f=null,!p)return;const j=y.clientX-p.clientX,v=y.clientY-p.clientY;if(Math.hypot(j,v)>a||o()-p.at>s)return;const _=typeof window<"u"&&(($=window.localStorage)==null?void 0:$.getItem("codeyam.terminalClickDebug"))==="1";if(_)try{const C=e.buffer.active,L=C.cursorY,N={};for(let I=-2;I<=2;I++){const P=L+I,D=C.getLine(C.baseY+P);if(!D)continue;const E=[];for(let k=0;k<e.cols;k++){const z=D.getCell(k);E.push(z?z.getChars():"")}N[`row${P}`]=E.join("|")}console.log("[click-cursor] buffer dump",{cursorY:L,cursorX:C.cursorX,viewportY:C.viewportY,baseY:C.baseY,rows:N})}catch{}let w=null;const S=C=>{w=C,_&&console.log("[click-cursor] result",C)},T=Cn({click:{clientX:y.clientX,clientY:y.clientY},terminal:e,cellSurface:u,debug:S});if(T){if(w){const C=w,L=C.box!==null&&C.targetRow!==C.cursorY;if(L&&x){_&&console.log("[click-cursor] suppressed by verification-disabled");return}L&&C.predictedCursorY!==null&&C.predictedCursorX!==null&&(h={y:C.predictedCursorY,x:C.predictedCursorX})}r(T)}}return u.addEventListener("mousedown",b),u.addEventListener("mouseup",g),()=>{u.removeEventListener("mousedown",b),u.removeEventListener("mouseup",g),d==null||d.dispose()}}const ot=20*1024*1024,Tn=3e4,En=3e3;function On(e){return new Promise((t,r)=>{const a=new FileReader;a.onload=()=>{const s=a.result;if(typeof s!="string"){r(new Error("Unexpected FileReader result"));return}const o=s.indexOf(",");t(o===-1?s:s.slice(o+1))},a.onerror=()=>r(a.error??new Error("read failed")),a.readAsDataURL(e)})}function An(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`drop-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Mn(e){return/^[A-Za-z0-9._/\-]+$/.test(e)?e:`"${e.replace(/(["\\$`])/g,"\\$1")}"`}function Pt(e){const t=e==null?void 0:e.items;if(!t)return[];const r=[];for(const a of Array.from(t)){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;const s=a.getAsFile();s&&r.push(s)}return r}function Pn(e){const t=e.items;if(!t||t.length===0||typeof t[0].webkitGetAsEntry!="function")return!1;for(const a of Array.from(t)){const s=a.webkitGetAsEntry();if(s&&s.isDirectory)return!0}return!1}function Dn(e,t){function r(a){const s=Pt(a.clipboardData);s.length!==0&&(a.preventDefault(),a.stopPropagation(),t(s))}return e.addEventListener("paste",r,!0),()=>e.removeEventListener("paste",r,!0)}function Rn(){window.focus()}function In(e,t){Rn(),e==null||e.focus({preventScroll:!0}),t()}function Ln({wsRef:e,insertInput:t}){const[r,a]=c.useState(!1),[s,o]=c.useState(null),i=c.useRef(new Map),l=c.useRef(0);c.useEffect(()=>{if(s===null)return;const v=window.setTimeout(()=>o(null),En);return()=>window.clearTimeout(v)},[s]);const u=c.useCallback(v=>{o(v)},[]),f=c.useCallback((v,_)=>{const w=i.current.get(v);w&&(i.current.delete(v),w.resolve(_))},[]),x=c.useCallback((v,_)=>{const w=i.current.get(v);w&&(i.current.delete(v),w.reject(_))},[]),h=c.useCallback(v=>{for(const[,_]of i.current)_.reject(v);i.current.clear()},[]),d=c.useCallback(async v=>{if(v.size>ot)throw new Error(`File too large (max ${ot/(1024*1024)} MB)`);const _=e.current;if(!_||_.readyState!==WebSocket.OPEN)throw new Error("Not connected — try again in a moment");const w=await On(v),S=An(),T=new Promise(($,C)=>{const L=window.setTimeout(()=>{i.current.delete(S)&&C(new Error("Timed out waiting for save to complete"))},Tn);i.current.set(S,{resolve:N=>{window.clearTimeout(L),$(N)},reject:N=>{window.clearTimeout(L),C(new Error(N))}})});return _.send(JSON.stringify({type:"drop",id:S,name:v.name||"unnamed",mime:v.type||"application/octet-stream",data:w})),T},[e]),m=c.useCallback(async v=>{if(v.length===0)return;const _=[];for(const w of v)try{_.push(await d(w))}catch(S){const T=S instanceof Error?S.message:String(S);u(`Attach failed: ${T}`);return}t(_.map(Mn).join(" ")+" ")},[d,u,t]),b=c.useCallback(v=>{v.dataTransfer.types.includes("Files")&&(v.preventDefault(),l.current+=1,a(!0))},[]),g=c.useCallback(v=>{v.dataTransfer.types.includes("Files")&&v.preventDefault()},[]),y=c.useCallback(v=>{v.dataTransfer.types.includes("Files")&&(l.current=Math.max(0,l.current-1),l.current===0&&a(!1))},[]),p=c.useCallback(async v=>{if(!v.dataTransfer.types.includes("Files"))return;if(v.preventDefault(),l.current=0,a(!1),Pn(v.dataTransfer)){u("Folder drops are not supported — drag individual files instead");return}const _=Array.from(v.dataTransfer.files).filter(w=>w.size>0);await m(_)},[m,u]),j=c.useCallback(async v=>{const _=Pt(v.clipboardData);_.length!==0&&(v.preventDefault(),await m(_))},[m]);return{dragActive:r,errorToast:s,dropHandlers:{onDragEnter:b,onDragOver:g,onDragLeave:y,onDrop:p},pasteHandler:j,handleImageFiles:m,resolveDrop:f,rejectDrop:x,cancelAllDrops:h,showError:u}}function Dt(){return n.jsx("div",{"data-testid":"terminal-drop-overlay",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(30, 30, 30, 0.85)",color:"#D7FF63",fontFamily:"'IBM Plex Mono', monospace",fontSize:14,border:"2px dashed #D7FF63",borderRadius:6,pointerEvents:"none",zIndex:5},children:"Drop file to attach"})}const Js=Object.freeze(Object.defineProperty({__proto__:null,TerminalDropOverlay:Dt},Symbol.toStringTag,{value:"Module"}));function Rt({message:e}){return n.jsx("div",{"data-testid":"terminal-drop-toast",style:{position:"absolute",bottom:12,left:"50%",transform:"translateX(-50%)",background:"#3a1f1f",color:"#ff9494",border:"1px solid #7a3939",borderRadius:4,padding:"6px 12px",fontFamily:"'IBM Plex Mono', monospace",fontSize:12,zIndex:6,pointerEvents:"none"},children:e})}const qs=Object.freeze(Object.defineProperty({__proto__:null,TerminalDropToast:Rt},Symbol.toStringTag,{value:"Module"}));async function It(e=1500){try{return(await fetch("/api/health",{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}function $n(e,t){let r=!1,a=null;async function s(){if(!r){if(await It(1500)){r||t();return}r||(a=setTimeout(s,e))}}return a=setTimeout(s,e),()=>{r=!0,a&&(clearTimeout(a),a=null)}}const Fn="The editor server closed the terminal connection with no further detail.";function Bn(e){if(e&&typeof e=="object"&&"message"in e){const t=e.message;if(typeof t=="string"&&t.length>0)return t}return Fn}let Lt=!1;function Le(e){Lt=e}function zn(){return Lt}const Kn=800,Hn=5e3;function Un(e){window.dispatchEvent(new CustomEvent("miniagent-send-input",{detail:e}))}function $t(e,t,r){return new Promise(a=>{let s=!1;const o=()=>{s||(s=!0,window.removeEventListener(e,i),clearTimeout(l),a())},i=u=>{r&&!r(u)||o()},l=setTimeout(o,t);window.addEventListener(e,i)})}function Yn(e,t="plan"){return $t("miniagent-agent-idle",e,r=>{const a=r.detail;return(a==null?void 0:a.chatName)===t})}function Wn(e){return zn()?Promise.resolve():$t("miniagent-ws-open",e)}async function Vn(e,t){await Wn(Hn),await Yn(Kn,t),Un(`${e}\r`)}function Ft(){return n.jsx("div",{"data-testid":"terminal-connecting-hint",className:"absolute top-2 right-3 text-xs font-mono text-[#aaa] pointer-events-none z-10 select-none",children:"Connecting…"})}const Gs=Object.freeze(Object.defineProperty({__proto__:null,TerminalConnectingHint:Ft},Symbol.toStringTag,{value:"Module"}));function Bt({attempt:e,maxAttempts:t,pulseKey:r}){return n.jsx("div",{"data-testid":"terminal-reconnecting-banner",className:"absolute inset-0 flex items-start justify-center pt-3 z-10 bg-black/40",children:n.jsxs("div",{"data-testid":"terminal-reconnecting-banner-label",className:"px-4 py-2 rounded font-mono text-sm shadow terminal-disconnect-pulse bg-amber-500/90 text-black",children:["Reconnecting… (attempt ",e," of ",t,")"]},r)})}const Qs=Object.freeze(Object.defineProperty({__proto__:null,TerminalReconnectingBanner:Bt},Symbol.toStringTag,{value:"Module"})),Xn=350;function ie(e,t={}){const{minPendingMs:r=Xn}=t,[a,s]=c.useState("idle"),[o,i]=c.useState(0),l=c.useRef(!0);c.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);const u=c.useCallback(()=>{s("pending"),i(h=>h+1);let f;try{f=Promise.resolve(e())}catch{f=Promise.resolve()}const x=new Promise(h=>setTimeout(h,r));Promise.allSettled([f,x]).then(()=>{l.current&&s("unchanged")})},[e,r]);return{phase:a,attempts:o,retry:u}}function zt({onRefresh:e}){const{phase:t,attempts:r,retry:a}=ie(e);return n.jsx("div",{"data-testid":"terminal-failed-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:n.jsx(te,{severity:"error",testId:"terminal-failed-notice",headline:"The terminal lost its connection",explanation:"The terminal tried to reconnect several times and couldn't get through. Either the editor restarted underneath it, or the connection between your browser and this machine dropped. Your files and your work are untouched — it's only the live terminal view that stopped.",nextAction:"Refresh the page to start a fresh terminal. If this keeps happening, copy this report and send it to whoever set up this machine.",actions:[{label:"Refresh page",onClick:a,pending:t==="pending",pendingLabel:"Refreshing…",testId:"terminal-failed-banner-refresh"}],actionFeedback:t==="unchanged"?n.jsxs("span",{"data-testid":"terminal-failed-banner-unchanged",children:["Tried just now — the terminal still isn’t back",r>1?` (${r} tries)`:"","."]}):null})})}const Zs=Object.freeze(Object.defineProperty({__proto__:null,TerminalFailedBanner:zt},Symbol.toStringTag,{value:"Module"}));function Kt({onReload:e}){const{phase:t,attempts:r,retry:a}=ie(e);return n.jsx("div",{"data-testid":"terminal-server-stopped-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:n.jsx(te,{severity:"error",testId:"terminal-server-stopped-notice",headline:"The editor has stopped",explanation:"The editor program behind this page is no longer running — it was closed, or it stopped on its own. Nothing you were working on is lost; the page just has nothing to talk to.",nextAction:"Start the editor again from your terminal. This page comes back by itself once it's running — you don't need to keep clicking. Reload page only checks early.",actions:[{label:"Reload page",onClick:a,pending:t==="pending",pendingLabel:"Checking…",testId:"terminal-server-stopped-banner-reload"}],actionFeedback:t==="unchanged"?n.jsxs("span",{"data-testid":"terminal-server-stopped-banner-unchanged",children:["Checked just now — the editor isn’t running yet",r>1?` (${r} tries)`:"","."]}):null})})}const eo=Object.freeze(Object.defineProperty({__proto__:null,TerminalServerStoppedBanner:Kt},Symbol.toStringTag,{value:"Module"}));function Ht({message:e,onRefresh:t}){return n.jsx("div",{"data-testid":"terminal-server-error-banner",className:"absolute inset-0 flex items-start justify-center pt-3 z-10 bg-black/60",children:n.jsxs("div",{className:"px-4 py-3 rounded font-mono text-sm shadow flex items-start gap-3 max-w-2xl bg-amber-500/95 text-black border border-amber-700",children:[n.jsx("pre",{"data-testid":"terminal-server-error-banner-message",className:"whitespace-pre-wrap break-words flex-1 m-0 font-mono text-xs leading-snug",children:e}),n.jsxs("div",{className:"flex items-start gap-2 self-start shrink-0",children:[n.jsx(jt,{variant:"subtle",text:e,label:"Copy",className:"px-2 py-1 rounded bg-white text-amber-900 font-medium cursor-pointer hover:bg-amber-50 disabled:opacity-50 disabled:cursor-not-allowed"}),n.jsx("button",{type:"button",onClick:t,"data-testid":"terminal-server-error-banner-refresh",className:"px-2 py-1 rounded bg-white text-amber-900 font-medium cursor-pointer hover:bg-amber-50",children:"Refresh"})]})]})})}const to=Object.freeze(Object.defineProperty({__proto__:null,TerminalServerErrorBanner:Ht},Symbol.toStringTag,{value:"Module"}));function Ut({onRefresh:e}){const{phase:t,attempts:r,retry:a}=ie(e);return n.jsx("div",{"data-testid":"terminal-edge-unreachable-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:n.jsx(te,{severity:"warning",testId:"terminal-edge-unreachable-notice",headline:"The terminal can't reach this machine",explanation:"The editor itself is loading fine and you're signed in — it's the terminal's own live connection that isn't getting through. Nothing you did caused this, and your work isn't lost.",nextAction:"Try Retry. If it keeps failing, this one isn't yours to fix — copy this report and send it to whoever set up this machine.",actions:[{label:"Retry",onClick:a,pending:t==="pending",pendingLabel:"Reconnecting…",testId:"terminal-edge-unreachable-banner-retry"}],actionFeedback:t==="unchanged"?n.jsxs("span",{"data-testid":"terminal-edge-unreachable-banner-unchanged",children:["Checked just now — still not connecting",r>1?` (${r} tries)`:"","."]}):null,diagnostics:"The editor answers over HTTP and the session is valid, but the terminal's live connection channel does not complete. Typically the network path in front of this machine is not carrying it."})})}const ro=Object.freeze(Object.defineProperty({__proto__:null,TerminalEdgeUnreachableBanner:Ut},Symbol.toStringTag,{value:"Module"}));function Yt({canRetry:e=!1,onRefresh:t}){const{phase:r,attempts:a,retry:s}=ie(t);return n.jsx("div",{"data-testid":"terminal-session-stale-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:n.jsx(te,{severity:"warning",testId:"terminal-session-stale-notice",headline:e?"Couldn't get this tab signed back in":"Signing this tab back in",explanation:e?"The editor restarted, which signed this tab out. It tried to sign back in automatically and couldn't.":"The editor restarted, which signed this tab out. It's signing back in and reconnecting the terminal now.",nextAction:e?"Use Retry to try again. If that doesn't take, reload the page — that always gets a fresh session.":"Nothing, unless this sticks around. If the terminal hasn't come back after about ten seconds, reload the page.",actions:e?[{label:"Retry",onClick:s,pending:r==="pending",pendingLabel:"Retrying…",testId:"terminal-session-stale-banner-retry"}]:[],actionFeedback:e&&r==="unchanged"?n.jsxs("span",{"data-testid":"terminal-session-stale-banner-unchanged",children:["Tried just now — still signed out",a>1?` (${a} tries)`:"",". Reloading the page will fix it."]}):null})})}const no=Object.freeze(Object.defineProperty({__proto__:null,TerminalSessionStaleBanner:Yt},Symbol.toStringTag,{value:"Module"}));function Jn(e){if(e.oomSignature)return{headline:"This session was killed because the machine ran out of memory.",body:"The agent did not stop on its own and did not crash — the system killed it to reclaim memory, so nothing it was in the middle of was saved. Free some memory before starting a new session, or the same thing will happen again.",retryLikelyHelps:!1};if(e.externalDeath)return{headline:`This session was stopped from outside the editor (${e.signal??"an external signal"}).`,body:"Something other than the editor ended the agent process. Nothing it was in the middle of was saved. Starting a new session is safe, but if this keeps happening the cause is outside the editor.",retryLikelyHelps:!0};if(e.origin==="broker-initiated")return{headline:"This session was stopped.",body:"The editor ended the agent process — this is what you get after Stop Building, or after a session sits unused long enough to be cleaned up. Start a new session whenever you are ready.",retryLikelyHelps:!0};const t=e.exitCode;return{headline:t===null?"The agent process ended.":`The agent process ended on its own (exit code ${t}).`,body:"The agent was not killed — it exited by itself, so whatever it printed above is the best evidence for why. Starting a new session is safe.",retryLikelyHelps:!0}}function Wt({report:e,onRefresh:t}){const{phase:r,attempts:a,retry:s}=ie(t),o=Jn(e);return n.jsx("div",{"data-testid":"terminal-session-died-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:n.jsx(te,{severity:o.retryLikelyHelps?"warning":"error",testId:"terminal-session-died-notice",headline:o.headline,explanation:o.body,nextAction:o.retryLikelyHelps?"Start a new session when you're ready. Reloading the page gets you a clean one.":"Free up memory first — close other work on this machine — then reload the page to start a new session.",actions:[{label:"Reload",onClick:s,pending:r==="pending",pendingLabel:"Reloading…",testId:"terminal-session-died-banner-reload"}],actionFeedback:r==="unchanged"?n.jsxs("span",{"data-testid":"terminal-session-died-banner-unchanged",children:["Tried just now — still no session",a>1?` (${a} tries)`:"","."]}):null})})}const ao=Object.freeze(Object.defineProperty({__proto__:null,TerminalSessionDiedBanner:Wt},Symbol.toStringTag,{value:"Module"}));function Vt({status:e,pulseKey:t,onRefresh:r}){return e.kind==="open"||e.kind==="ended"?null:e.kind==="connecting"?n.jsx(Ft,{}):e.kind==="reconnecting"?n.jsx(Bt,{attempt:e.attempt,maxAttempts:e.maxAttempts,pulseKey:t}):e.kind==="server-stopped"?n.jsx(Kt,{onReload:r}):e.kind==="server-error"?n.jsx(Ht,{message:e.message,onRefresh:r}):e.kind==="edge-unreachable"?n.jsx(Ut,{onRefresh:r}):e.kind==="session-died"?n.jsx(Wt,{report:e.report,onRefresh:r}):e.kind==="session-stale"?n.jsx(Yt,{canRetry:e.canRetry,onRefresh:r}):n.jsx(zt,{onRefresh:r})}const so=Object.freeze(Object.defineProperty({__proto__:null,TerminalDisconnectOverlay:Vt},Symbol.toStringTag,{value:"Module"}));function Xt(){return n.jsx("div",{"data-testid":"mini-agent-launch-retrying",className:"absolute inset-x-0 top-2 z-10 flex justify-center pointer-events-none",children:n.jsx("span",{className:"font-mono text-xs italic text-[var(--text-dim)] bg-black/40 px-2 py-1 rounded",children:"Launch slow — retrying…"})})}const oo=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchRetryingHint:Xt},Symbol.toStringTag,{value:"Module"}));function Jt({onRetry:e}){const{phase:t,attempts:r,retry:a}=ie(e);return n.jsx("div",{"data-testid":"mini-agent-launch-failed-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:n.jsx(te,{severity:"error",testId:"mini-agent-launch-failed-notice",headline:"The build agent didn't start",explanation:"CodeYam opened a shell to start the build agent and it never became ready. This is the agent failing to start, not your project — nothing in your code has been touched.",nextAction:"Use Retry. If it fails again, copy this report and send it on — a shell that will not come up is a setup problem on this machine rather than something to fix in your project.",actions:[{label:"Retry",onClick:a,pending:t==="pending",pendingLabel:"Starting…",testId:"mini-agent-launch-failed-retry"}],actionFeedback:t==="unchanged"?n.jsxs("span",{"data-testid":"mini-agent-launch-failed-unchanged",children:["Tried just now — the agent still didn’t start",r>1?` (${r} tries)`:"","."]}):null})})}const io=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchFailed:Jt},Symbol.toStringTag,{value:"Module"}));function qt({status:e,onRetry:t}){return e==="retrying"?n.jsx(Xt,{}):e==="failed"?n.jsx(Jt,{onRetry:t}):null}const lo=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchOverlay:qt},Symbol.toStringTag,{value:"Module"})),qn=1e3;let Ye=0;function co(){Ye=Date.now()}function We(){return Ye===0?1/0:Date.now()-Ye}function uo(){return We()<qn}const Gt=5e3,it=6e4,Gn=50;function lt(e,t=Gt){return e<t}function Qn(e,t=Gt){return Math.max(Gn,t-e)}const ce=new Map;async function Zn(e,t,r,a){if(a!=null&&a.aborted)return null;if(!lt(We()))return e;const s=ce.get(t);if(s)return s.label=e,U("dispatch-rename-superseded",{caller:r,label:e}),null;const o={label:e};ce.set(t,o);let i=0;for(;;){if(a!=null&&a.aborted)return ce.delete(t),U("dispatch-rename-cancelled",{caller:r,label:o.label,waitedMs:i}),null;const l=We();if(!lt(l))break;const u=Qn(l);if(i+u>it)return ce.delete(t),U("dispatch-rename-abandoned",{caller:r,label:o.label,msSinceKeystroke:l,waitedMs:i,capMs:it}),null;U("dispatch-rename-deferred",{caller:r,label:o.label,msSinceKeystroke:l,retryInMs:u,waitedMs:i}),await new Promise(f=>setTimeout(f,u)),i+=u}return ce.delete(t),o.label}const ea=40;function ta(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t&&t.slice(0,ea).replace(/-+$/,"")||"session"}const je=new Map;function Te(e,t){const r=je.get(e);if(!r){let a;try{a=t()}catch(s){return Promise.reject(s)}return a instanceof Promise?ct(e,a):Promise.resolve()}return ct(e,r.then(()=>t()))}function ct(e,t){const r=t.catch(()=>{});return je.set(e,r),r.then(()=>{je.get(e)===r&&je.delete(e)}),t}let oe=0,ae=[];function fo(){if(oe+=1,oe===1&&ae.length>0){const e=ae;ae=[];for(const t of e)t()}}function po(){oe>0&&(oe-=1)}function ra(){return oe>0}function na(e){return oe>0?Promise.resolve(!0):new Promise(t=>{let r=!1;const a=()=>{r||(r=!0,t(!0))};ae.push(a),setTimeout(()=>{r||(r=!0,ae=ae.filter(s=>s!==a),t(!1))},e)})}const be="build",dt="miniagent",ut=3e3;function Qt(e,t=!1){return ra()?e():na(ut).then(r=>{if(r)return e();const a=`no terminal-send-input listener attached within ${ut}ms`;if(t)throw new aa(a);console.warn(`[terminal] dropped programmatic injection: ${a}`)})}class aa extends Error{constructor(t){super(t),this.name="TerminalInputDroppedError"}}function Ee(e){window.dispatchEvent(new CustomEvent("terminal-send-input",{detail:e}))}function ho(e){Te(be,()=>Qt(()=>Ee(e)))}function mo(e){return Te(be,()=>Qt(()=>Ee(e),!0))}const we=50;function sa(e,t=Ee,r=be){return Te(r,()=>new Promise(a=>{t(e),setTimeout(()=>{t("\r"),a()},we)}))}const $e=3e3;function oa(e){return e==="codex"?"codex":e==="gemini"?"gemini":e==="opencode"?"opencode":"claude"}function Zt(e,t){const r=oa(e);return r==="claude"&&t?`${r} --permission-mode auto`:r}function ia(e,t){return`'${e==="powershell"?t.replaceAll("'","''"):t.replaceAll("'","'\\''")}'`}function la(e,t,r=!0,a="posix"){const s=ia(a,t);return e==="opencode"?`opencode${r?" --auto":""} --prompt ${s}\r`:`${Zt(e,r)} ${s}\r`}async function ca(e,t=Ee,r=be,a="dispatch-rename-launch",s){const o=await Zn(ta(e),r,a,s);o!==null&&await sa(`/rename ${o}`,t,r)}function da(e,t,r,a=be){U("dispatch-rename",{phase:"queued",caller:t,label:e,delayMs:$e}),setTimeout(()=>{U("dispatch-rename",{phase:"fired",caller:t,label:e,delayMs:$e}),ca(e,r,a,t)},$e)}const Ze=".codeyam/tmp/inline-prompt.md";function ua(e){return e.split(`
8
+ `).map(t=>t.startsWith("'@")?` ${t}`:t).join(`
9
+ `)}function fa(e){return`mkdir -p .codeyam/tmp && cat > ${Ze} << 'INLINE_PROMPT_EOF'
10
+ ${e}
11
+ INLINE_PROMPT_EOF\r`}function pa(e){return`New-Item -ItemType Directory -Force -Path .codeyam/tmp | Out-Null; @'
12
+ ${ua(e)}
13
+ '@ | Set-Content -LiteralPath ${Ze} -Encoding utf8\r`}function ha(e,t,r=!0,a="posix"){const s=Zt(e,r),o=a==="powershell"?pa(t):fa(t),i=`${s} "Read the file at '${Ze}' for your instructions."\r`;return[o,i]}function ma({attempt:e,sawOutput:t}){return t?e===1?"extend":"confirm":e===1?"retry":"fail"}function ba({idleMs:e,ceilingMs:t}){return new Promise(r=>{let a=null,s=null,o=!1;function i(){o||(o=!0,a!==null&&clearTimeout(a),s!==null&&clearTimeout(s),window.removeEventListener("miniagent-output",u),r())}function l(){a!==null&&clearTimeout(a),a=setTimeout(i,e)}function u(){l()}window.addEventListener("miniagent-output",u),s=setTimeout(i,t),l()})}const xa=350,ga=4e3,ft=8e3,ya=500,q={armed:"mini-agent-launch-armed",fired:"mini-agent-launch-fired",confirmed:"mini-agent-launch-confirmed",relaunch:"mini-agent-relaunch",failed:"mini-agent-launch-failed",reattached:"mini-agent-launch-reattached"};function va(e){const{provider:t,slashCommand:r,prompt:a,chatName:s,sendInput:o,permissionModeAuto:i=!0,shellDialect:l=null}=e,[u,f]=c.useState("idle"),x=c.useRef(o),h=c.useRef(r),d=c.useRef(a),m=c.useRef(s),b=c.useRef(t),g=c.useRef(i),y=c.useRef(l);c.useEffect(()=>{x.current=o},[o]),c.useEffect(()=>{g.current=i},[i]),c.useEffect(()=>{y.current=l},[l]),c.useEffect(()=>{h.current=r},[r]),c.useEffect(()=>{d.current=a},[a]),c.useEffect(()=>{m.current=s},[s]),c.useEffect(()=>{b.current=t},[t]);const p=c.useRef(0),j=c.useRef(!1),v=c.useRef(0),_=c.useRef(0),w=c.useRef(0);c.useEffect(()=>{const P=()=>{_.current+=1};return window.addEventListener("miniagent-output",P),()=>window.removeEventListener("miniagent-output",P)},[]);const S=c.useCallback((P,D)=>{const E=h.current,k=d.current;return Te(dt,()=>{const z=y.current??"posix";if(E){const H=la(b.current,E,g.current,z),Q=Fe(H);return P(Q),new Promise(B=>{setTimeout(()=>{D()&&P("\r"),B()},we)})}const[K,X]=ha(b.current,k??"",g.current,z),G=Fe(K),Y=Fe(X);return P(G),new Promise(H=>{setTimeout(()=>{if(!D())return H();P("\r"),setTimeout(()=>{if(!D())return H();P(Y),setTimeout(()=>{D()&&P("\r"),H()},we)},ya)},we)})})},[]),T=c.useCallback(()=>{const P=++p.current,D=Date.now();v.current=D,w.current=_.current,f("armed"),U(q.armed,{provider:b.current,slashCommand:h.current,chatName:m.current,hasPrompt:typeof d.current=="string"});function E(){return p.current===P}function k(K){E()&&(f(K===1?"firing":"retrying"),U(K===1?q.fired:q.relaunch,{provider:b.current,slashCommand:h.current,chatName:m.current,attempt:K,elapsedMs:Date.now()-D}),S(x.current,E).then(()=>{E()&&(w.current=_.current)}),!j.current&&sn(b.current)&&(j.current=!0,da(m.current,"mini-agent-chat",X=>x.current(X),dt)),setTimeout(()=>z(K),ft))}function z(K){if(!E())return;const X=_.current>w.current;switch(ma({attempt:K,sawOutput:X})){case"retry":k(2);return;case"extend":U(q.relaunch,{provider:b.current,slashCommand:h.current,attempt:2,sawOutput:!0,resent:!1,elapsedMs:Date.now()-D}),setTimeout(()=>z(2),ft);return;case"confirm":f("confirmed"),U(q.confirmed,{provider:b.current,slashCommand:h.current,reason:"output-without-banner",sawOutput:!0,elapsedMs:Date.now()-D});return;case"fail":f("failed"),U(q.failed,{provider:b.current,slashCommand:h.current,reason:"banner-timeout",sawOutput:!1,elapsedMs:Date.now()-D})}}ba({idleMs:xa,ceilingMs:ga}).then(()=>{E()&&k(1)})},[S]),$=c.useCallback(()=>{j.current=!1,T()},[T]),C=c.useCallback(()=>{T()},[T]),L=c.useCallback(()=>{p.current!==0&&(p.current++,f("confirmed"),U(q.confirmed,{elapsedMs:Date.now()-v.current}))},[]),N=c.useCallback(()=>{p.current!==0&&(p.current++,f("failed"),U(q.failed,{reason:"startup-failed",elapsedMs:Date.now()-v.current}))},[]),I=c.useCallback(()=>{p.current++,f("confirmed"),U(q.reattached,{provider:b.current,chatName:m.current})},[]);return c.useEffect(()=>()=>{p.current++},[]),{status:u,arm:$,retry:C,onBannerReady:L,onStartupFailed:N,onReattached:I}}function Fe(e){return e.endsWith("\r")?e.slice(0,-1):e}const Oe=c.createContext({registerSender:()=>{},setReady:()=>{},sendToAgent:()=>!1,agentReady:!1});function _a({children:e}){const t=c.useRef(null),[r,a]=c.useState(!1),s=c.useCallback(u=>{t.current=u},[]),o=c.useCallback(u=>{a(u)},[]),i=c.useCallback(u=>{const f=t.current;return f?f(u):!1},[]),l=c.useMemo(()=>({registerSender:s,setReady:o,sendToAgent:i,agentReady:r}),[s,o,i,r]);return n.jsx(Oe.Provider,{value:l,children:e})}function ja(){const{sendToAgent:e,agentReady:t}=c.useContext(Oe);return{sendToAgent:e,agentReady:t}}function wa(e,t){const{registerSender:r,setReady:a}=c.useContext(Oe);c.useEffect(()=>(r(e),()=>r(null)),[r,e]),c.useEffect(()=>(a(t),()=>a(!1)),[a,t])}function er(){const{registerSender:e,setReady:t}=c.useContext(Oe);return{registerSender:e,setReady:t}}const bo=Object.freeze(Object.defineProperty({__proto__:null,AgentInputProvider:_a,useAgentInput:ja,useAgentInputChannel:er,useRegisterAgentInput:wa},Symbol.toStringTag,{value:"Module"}));function Sa(e,t){return c.useCallback(async r=>{var a;return((a=e.current)==null?void 0:a.readyState)!==WebSocket.OPEN?!1:(await t.current.handleImageFiles(r),!0)},[e,t])}function tr({className:e=""}){const{openPicker:t}=Ot();return n.jsxs("button",{type:"button",onClick:t,title:"Attach a file","aria-label":"Attach a file","data-testid":"attach-file-button",className:`inline-flex items-center gap-1 text-xs font-medium cursor-pointer bg-transparent border-none text-[var(--text-dim)] hover:text-[var(--text-primary)] transition ${e}`,children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),"Attach file"]})}const xo=Object.freeze(Object.defineProperty({__proto__:null,AttachFileButton:tr},Symbol.toStringTag,{value:"Module"})),pt=15;function rr({chatName:e,prompt:t,slashCommand:r,seedText:a,height:s=400,onClose:o}){const i=c.useRef(null),l=c.useRef(null),u=c.useRef(null);c.useRef(t);const{config:f}=Mt(),x=(f==null?void 0:f.provider)??"claude",[h,d]=c.useState({kind:"connecting"}),[m,b]=c.useState(0),g=c.useCallback(E=>{const k=l.current;(k==null?void 0:k.readyState)===WebSocket.OPEN&&k.send(JSON.stringify({type:"input",data:E}))},[]),y=Ln({wsRef:l,insertInput:g}),p=c.useRef(y);p.current=y;const{registerSender:j,setReady:v}=er(),_=c.useCallback(E=>{var k;return((k=l.current)==null?void 0:k.readyState)===WebSocket.OPEN?(l.current.send(JSON.stringify({type:"input",data:E})),!0):!1},[]),w=h.kind==="open";c.useEffect(()=>(w&&j(_),()=>j(null)),[j,_,w]),c.useEffect(()=>(v(w),()=>v(!1)),[v,w]);const{registerFileSink:S}=At(),T=Sa(l,p);c.useEffect(()=>(w&&S(T),()=>S(null)),[S,T,w]);const $=c.useCallback(()=>{var E;((E=l.current)==null?void 0:E.readyState)===WebSocket.OPEN&&(j(_),v(!0),S(T)),In(i.current,()=>{var k;return(k=u.current)==null?void 0:k.focus()})},[j,v,_,S,T]),{shellDialect:C}=wt(),L=va({provider:x,slashCommand:r,prompt:t,chatName:e,sendInput:g,permissionModeAuto:(f==null?void 0:f.claudePermissionModeAuto)??!0,shellDialect:C}),N=c.useRef(L);c.useEffect(()=>{N.current=L});const I=c.useRef(e);c.useEffect(()=>{I.current=e});const P=c.useRef(a),D=c.useRef(r);return c.useEffect(()=>{P.current=a,D.current=r}),c.useEffect(()=>{const E=i.current;if(!E)return;const k=new dn.Terminal({theme:{background:"#1a1a1a",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},fontSize:12,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",cursorBlink:!0,scrollback:5e3,allowProposedApi:!0}),z=new un.FitAddon;k.loadAddon(z),k.open(E);const K=yn(k,E,{onError:O=>console.warn("[MiniAgentChat]",O)}),X=Nn(k,{sendInput:O=>{const M=l.current;(M==null?void 0:M.readyState)===WebSocket.OPEN&&M.send(JSON.stringify({type:"input",data:O}))}}),G=Dn(E,O=>{p.current.handleImageFiles(O)});requestAnimationFrame(()=>{try{z.fit()}catch{}}),u.current=k;const Y={current:"inline"},H={current:null},Q={current:!1},B={current:!1},J={current:!1};let W=0,V=null;function ge(){d({kind:"connecting"});const O=hn({mode:Y.current,sessionId:H.current??void 0,chatKey:e,cols:k.cols,rows:k.rows}),M=new WebSocket(O);M.binaryType="arraybuffer",l.current=M,M.onopen=()=>{W=0,d({kind:"open"}),Le(!0),window.dispatchEvent(new CustomEvent("miniagent-ws-open")),M.send(JSON.stringify({type:"resize",cols:k.cols,rows:k.rows}))},M.onmessage=F=>{if(F.data instanceof ArrayBuffer){k.write(new Uint8Array(F.data)),window.dispatchEvent(new CustomEvent("miniagent-output"));return}try{const R=JSON.parse(F.data);if(R.type==="error"){B.current=!0,d({kind:"server-error",message:Bn(R)});return}if(R.type==="drop-complete"){p.current.resolveDrop(R.id,R.path);return}if(R.type==="drop-error"){p.current.rejectDrop(R.id,R.message);return}if(R.type==="session-id"){if(R.sessionId&&(H.current=R.sessionId,Y.current="resume"),R.reattached===!0){Q.current=!0,N.current.onReattached();const ye=P.current,nt=D.current;ye&&nt&&!J.current&&(J.current=!0,Vn(nt,I.current));return}Q.current||(Q.current=!0,N.current.arm());return}if(R.type==="agent-idle"||R.type==="claude-idle"||R.type==="agent-blocked"){window.dispatchEvent(new CustomEvent("miniagent-agent-idle",{detail:{chatName:I.current}}));return}if(R.type==="agent-active"||R.type==="claude-active"){window.dispatchEvent(new CustomEvent("miniagent-agent-active",{detail:{chatName:I.current}}));return}if(R.type==="agent-banner-ready"){N.current.onBannerReady();return}if(R.type==="agent-auth-required"){window.dispatchEvent(new CustomEvent("agent-auth-required"));return}if(R.type==="startup-failed"){N.current.onStartupFailed();return}}catch{k.write(F.data),window.dispatchEvent(new CustomEvent("miniagent-output"))}},M.onerror=()=>{},M.onclose=async()=>{if(Le(!1),p.current.cancelAllDrops("Not connected"),B.current){d(R=>R.kind==="server-error"?R:{kind:"ended"});return}const F=await It();if(!B.current){if(!F){d({kind:"server-stopped"}),V==null||V(),V=$n(2e3,()=>{B.current||window.location.reload()});return}if(W<pt){const R=W<4?1e3*Math.pow(2,W):1e4;W++,d({kind:"reconnecting",attempt:W,maxAttempts:pt}),setTimeout(()=>{B.current||ge()},R)}else d({kind:"failed"})}}}try{z.fit()}catch{}ge(),k.onData(O=>{const M=l.current;(M==null?void 0:M.readyState)===WebSocket.OPEN?M.send(JSON.stringify({type:"input",data:O})):b(F=>F+1)});const re=new ResizeObserver(()=>{try{z.fit();const O=l.current;(O==null?void 0:O.readyState)===WebSocket.OPEN&&O.send(JSON.stringify({type:"resize",cols:k.cols,rows:k.rows}))}catch{}});re.observe(E);function ne(O){const M=u.current;if(!M)return;const F=O.target;if(F!=null&&F.closest(".xterm-viewport")||M.buffer.active.length<=M.rows)return;const ye=xn(O.deltaY,O.deltaMode);ye!==0&&(M.scrollLines(ye),O.preventDefault(),O.stopPropagation())}E.addEventListener("wheel",ne,{passive:!1});function A(){var O;(O=u.current)==null||O.focus()}window.addEventListener("terminal-focus",A);function le(O){const M=O.detail,F=l.current;typeof M=="string"&&(F==null?void 0:F.readyState)===WebSocket.OPEN&&F.send(JSON.stringify({type:"input",data:M}))}return window.addEventListener("miniagent-send-input",le),()=>{var M;B.current=!0,Le(!1),V==null||V(),V=null,window.removeEventListener("terminal-focus",A),window.removeEventListener("miniagent-send-input",le),E.removeEventListener("wheel",ne),re.disconnect(),K(),X(),G();const O=l.current;(O==null?void 0:O.readyState)===WebSocket.OPEN&&O.close(),(M=u.current)==null||M.dispose()}},[x]),n.jsxs("div",{"data-codeyam-hydrated":"MiniAgentChat",className:"mt-2 border border-[var(--border-subtle)] rounded-lg overflow-hidden",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-[var(--bg-card)]",children:[n.jsx("span",{className:"text-xs font-medium text-[var(--accent-active)]",children:me(x)}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(tr,{}),o&&n.jsx("button",{onClick:o,className:"text-[var(--text-dim)] hover:text-[var(--text-primary)] text-xs bg-transparent border-none cursor-pointer",children:"Close"})]})]}),n.jsxs("div",{ref:i,className:"mini-agent-terminal",tabIndex:-1,onPointerDown:$,onClick:$,onDragEnter:y.dropHandlers.onDragEnter,onDragOver:y.dropHandlers.onDragOver,onDragLeave:y.dropHandlers.onDragLeave,onDrop:y.dropHandlers.onDrop,style:{height:s,background:"#1a1a1a",padding:"6px 10px",position:"relative",overflow:"hidden",outline:"none"},children:[n.jsx(Vt,{status:h,pulseKey:m,onRefresh:()=>window.location.reload()}),n.jsx(qt,{status:L.status,onRetry:L.retry}),y.dragActive&&n.jsx(Dt,{}),y.errorToast&&n.jsx(Rt,{message:y.errorToast})]})]})}const go=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentChat:rr},Symbol.toStringTag,{value:"Module"}));function nr(e){return e>=500?"transient":"rejected"}function ar({provider:e,onAuthenticated:t}){const[r,a]=c.useState(""),[s,o]=c.useState(!1),[i,l]=c.useState(null),[u,f]=c.useState(!1),x=me(e),h=c.useCallback(async()=>{if(r.trim()){o(!0),l(null),f(!1);try{const d=await fetch("/api/auth/api-key",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({provider:e,key:r.trim()})});if(!d.ok){if(nr(d.status)==="transient"){f(!0),l(`The editor was briefly unreachable (HTTP ${d.status}). Your key wasn't rejected — try again.`);return}const m=await d.json().catch(()=>({}));l(m.error??`Could not save the key (HTTP ${d.status}).`);return}a(""),t()}catch{f(!0),l("Could not reach the editor to save the key. Try again.")}finally{o(!1)}}},[r,e,t]);return n.jsxs("div",{"data-testid":"api-key-flow",className:"space-y-3",children:[n.jsxs("p",{className:"text-sm text-[#8E8E8E]",children:["Paste your ",x," API key. It is stored locally in",n.jsx("code",{className:"mx-1 text-[#D7FF63]",children:".codeyam/editor.local.json"}),"and never committed."]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"password",value:r,onChange:d=>a(d.target.value),placeholder:`${x} API key`,className:"flex-1 min-w-0 px-2 py-1.5 rounded bg-black border border-[#3A3A3A] text-white text-sm"}),n.jsx("button",{onClick:()=>void h(),disabled:s||!r.trim(),className:"px-3 py-1.5 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer disabled:opacity-50",children:s?"Saving…":"Save"})]}),i?n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-sm text-[#FF8B43]",children:i}),u?n.jsx("button",{"data-testid":"api-key-flow-retry",onClick:()=>void h(),disabled:s||!r.trim(),className:"px-3 py-1.5 text-sm rounded-md border border-[#3A3A3A] text-white font-medium cursor-pointer disabled:opacity-50",children:s?"Saving…":"Retry"}):null]}):null]})}const yo=Object.freeze(Object.defineProperty({__proto__:null,ApiKeyFlow:ar,classifyApiKeySaveFailure:nr},Symbol.toStringTag,{value:"Module"})),ka=500,Ca=75e3,ht=`
14
+
15
+ --- transcript tail ---
16
+ `;function sr(e){const t=e.indexOf(ht);return t===-1?{headline:e}:{headline:e.slice(0,t),tail:e.slice(t+ht.length)}}function or({onAuthenticated:e}){const[t,r]=c.useState({state:"starting"}),[a,s]=c.useState(""),[o,i]=c.useState(!1),[l,u]=c.useState(!1),[f,x]=c.useState(!1),[h,d]=c.useState(!1),m=c.useRef(!1),b=c.useRef(e);b.current=e;const g=c.useCallback(async()=>{try{const S=await fetch("/api/auth/status");if(!S.ok)return;const T=await S.json();r(T),T.state==="authenticated"&&!m.current&&(m.current=!0,b.current())}catch{}},[]),y=c.useCallback(async()=>{m.current=!1,x(!1),r({state:"starting"});try{const S=await fetch("/api/auth/start",{method:"POST"});if(!S.ok){const T=await S.json().catch(()=>({}));r({state:"failed",error:T.error??"Could not start the login process."})}}catch{r({state:"failed",error:"Could not start the login process."})}},[]);c.useEffect(()=>{y()},[y]),c.useEffect(()=>{const S=window.setInterval(()=>void g(),ka);return()=>window.clearInterval(S)},[g]);const p=t.state!=="failed"&&t.state!=="idle"&&t.state!=="authenticated"&&t.state!=="url-ready";c.useEffect(()=>{if(!p){x(!1);return}const S=window.setTimeout(()=>x(!0),Ca);return()=>window.clearTimeout(S)},[p]);const j=c.useCallback(async()=>{if(a.trim()){i(!0);try{const S=await fetch("/api/auth/code",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:a.trim()})});if(S.ok)s("");else{const T=await S.json().catch(()=>({}));r({state:"failed",error:T.error??"Code not accepted — check the value and try again."})}}catch{r({state:"failed",error:"Could not submit the code."})}finally{i(!1)}}},[a]),v=c.useCallback(async()=>{try{await fetch("/api/auth/cancel",{method:"POST"})}catch{}y()},[y]),_=c.useCallback(async()=>{d(!0);try{await fetch("/api/auth/refresh-cache",{method:"POST"}),e()}catch{}finally{d(!1)}},[e]),w=c.useCallback(()=>{var S;t.url&&((S=navigator.clipboard)==null||S.writeText(t.url),u(!0),window.setTimeout(()=>u(!1),1500))},[t.url]);if(f&&p)return n.jsxs("div",{"data-testid":"claude-oauth-timeout",className:"space-y-3",children:[n.jsxs("p",{className:"text-sm text-[#FF8B43]",children:["Login link preparation timed out — the backend may be wedged. Try again, recheck if you already authenticated elsewhere, or open a terminal and run ",n.jsx("code",{className:"text-white",children:"claude /login"})," ","directly."]}),n.jsx(ue,{onRetry:()=>void v(),onRecheck:()=>void _(),rechecking:h,retryTestId:"claude-oauth-timeout-retry",recheckTestId:"claude-oauth-timeout-recheck"})]});if(t.state==="failed"){const{headline:S,tail:T}=sr(t.error??"Login failed.");return n.jsxs("div",{"data-testid":"claude-oauth-failed",className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-[#FF8B43]",children:S}),T&&n.jsxs("details",{open:!0,"data-testid":"claude-oauth-failed-transcript",children:[n.jsx("summary",{className:"cursor-pointer text-xs text-[#9CA3AF]",children:"Login transcript (what claude actually printed)"}),n.jsx("pre",{className:"mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-all rounded bg-[#1A1A1A] p-2 font-mono text-[11px] leading-relaxed text-[#9CA3AF]",children:T})]}),n.jsx(ue,{onRetry:()=>void v(),onRecheck:()=>void _(),rechecking:h,retryLabel:"Try again",recheckTestId:"claude-oauth-failed-recheck"})]})}return t.state==="idle"?n.jsxs("div",{"data-testid":"claude-oauth-idle",className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-[#FF8B43]",children:"No login is running — the login process stopped before it could start. Try again, or recheck if you already authenticated elsewhere."}),n.jsx(ue,{onRetry:()=>void v(),onRecheck:()=>void _(),rechecking:h,retryTestId:"claude-oauth-idle-retry",recheckTestId:"claude-oauth-idle-recheck"})]}):t.state==="authenticated"?n.jsx("p",{"data-testid":"claude-oauth-authenticated",className:"text-sm text-[#D7FF63]",children:"Connected. Opening Build…"}):t.state==="url-ready"&&!t.url?n.jsxs("div",{"data-testid":"claude-oauth-url-missing",className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-[#FF8B43]",children:"The login process reported that a link was ready but did not send a usable one. Try again, or recheck if you already authenticated elsewhere."}),n.jsx(ue,{onRetry:()=>void v(),onRecheck:()=>void _(),rechecking:h,retryTestId:"claude-oauth-url-missing-retry",recheckTestId:"claude-oauth-url-missing-recheck"})]}):t.state==="url-ready"&&t.url?n.jsxs("div",{"data-testid":"claude-oauth-url-ready",className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-[#8E8E8E]",children:"Open this URL in your browser, approve access, then paste the code back here:"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("code",{className:"flex-1 min-w-0 truncate px-2 py-1.5 rounded bg-black text-[#D7FF63] text-xs",children:t.url}),n.jsx("button",{onClick:w,className:"px-2 py-1.5 text-xs rounded-md border border-[#3A3A3A] text-white cursor-pointer",children:l?"Copied":"Copy"}),n.jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",className:"px-2 py-1.5 text-xs rounded-md border border-[#3A3A3A] text-white cursor-pointer",children:"Open"})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"text",value:a,onChange:S=>s(S.target.value),placeholder:"Paste the code from the browser here",className:"flex-1 min-w-0 px-2 py-1.5 rounded bg-black border border-[#3A3A3A] text-white text-sm"}),n.jsx("button",{onClick:()=>void j(),disabled:o||!a.trim(),className:"px-3 py-1.5 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer disabled:opacity-50",children:o?"Submitting…":"Submit"})]})]}):n.jsx("p",{"data-testid":"claude-oauth-starting",className:"text-sm text-[#8E8E8E]",children:"Preparing the login link…"})}const vo=Object.freeze(Object.defineProperty({__proto__:null,ClaudeOAuthFlow:or,splitTranscriptTail:sr},Symbol.toStringTag,{value:"Module"}));function ir({provider:e,onAuthenticated:t,onClose:r}){const a=me(e);return n.jsx("div",{"data-testid":"provider-auth-modal",className:"fixed inset-0 z-[100] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:n.jsxs("div",{className:"w-[32rem] max-w-[90vw] rounded-lg border border-[#3A3A3A] bg-[#1E1E1E] p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("h2",{className:"text-base font-medium text-white",children:["Connect your ",a," account"]}),n.jsx("button",{onClick:r,"aria-label":"Close",className:"text-[#8E8E8E] hover:text-white cursor-pointer",children:"✕"})]}),e==="claude"?n.jsx(or,{onAuthenticated:t}):n.jsx(ar,{provider:e,onAuthenticated:t})]})})}const _o=Object.freeze(Object.defineProperty({__proto__:null,ProviderAuthModal:ir},Symbol.toStringTag,{value:"Module"}));function Na(e){const t=new Date(e).getTime()-Date.now(),r=Math.abs(Math.round(t/36e5));if(r<1)return t<0?"just now":"very soon";if(r<48)return t<0?`${r} h ago`:`in ${r} h`;const a=Math.round(r/24);return t<0?`${a} d ago`:`in ${a} d`}function lr({provider:e,credsPresent:t=!0,reason:r=null,expiresAt:a=null,sessionOngoing:s=!1,onAuthenticated:o,onAuthorized:i}){const[l,u]=c.useState(!1),[f,x]=c.useState(!1),h=me(e),d=c.useCallback(()=>{u(!1),o(),i==null||i()},[o,i]),m=c.useCallback(async()=>{x(!0);try{await fetch("/api/auth/refresh-cache",{method:"POST"}),o()}catch{}finally{x(!1)}},[o]),b=e==="claude"&&!t,g=a?` (token expired ${Na(a)})`:"",y=b?`${h} credentials file is missing`:r==="token-expired"?`Your ${h} token has expired`:r==="api-401"?`${h} authentication rejected (401)`:`Connect your ${h} account`,p=s?" Your Build session stays open — you can finish logging in here or directly in the Build terminal.":"",j=b?"The editor couldn't find ~/.claude/.credentials.json on this machine — likely deleted between editor restarts (operator-side action, a Reconfigure, or a stale image). Re-seed by clicking Authenticate to run OAuth, or — on a fleet VM — copy the file from a donor VM through the dashboard.":r==="token-expired"?`Your ${h} token has expired${g} — click Authenticate to refresh it. On a fleet VM the dashboard can copy a fresh token from a donor VM.${p}`:r==="api-401"?`The ${h} server rejected your credentials (401)${g}. This usually means the token was revoked or expired. Click Authenticate to re-connect.${p}`:s?"You can finish logging in here or directly in the Build terminal — your session stays open either way. On a cloud VM the dashboard usually does this for you; locally you connect once here.":`Authentication used to happen inside the Build terminal. Now it lives here, out of your way. Connect ${h} to unlock the Build tab. On a cloud VM the dashboard usually does this for you; locally you connect once here.`;return n.jsxs("div",{"data-testid":"provider-auth-gate","data-auth-variant":b?"creds-missing":"needs-login","data-auth-card":!0,className:"m-4 rounded-lg border border-[#D7FF63]/40 bg-[#1E1E1E] p-5 space-y-3",children:[n.jsx("h2",{className:"text-base font-medium text-white",children:y}),n.jsx("p",{className:"text-sm text-[#8E8E8E]",children:j}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx("button",{onClick:()=>u(!0),className:"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:"Authenticate"}),n.jsx("button",{onClick:()=>void m(),"data-testid":"provider-auth-gate-recheck",disabled:f,className:"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:f?"Rechecking…":"Already logged in? Recheck"})]}),l?n.jsx(ir,{provider:e,onAuthenticated:d,onClose:()=>u(!1)}):null]})}const jo=Object.freeze(Object.defineProperty({__proto__:null,ProviderAuthenticateCta:lr},Symbol.toStringTag,{value:"Module"}));let Be=!1;function cr(e){const{state:t,provider:r,credsPresent:a,reason:s,expiresAt:o,refresh:i}=cn(),[l]=c.useState(()=>Be);return c.useEffect(()=>{t==="authenticated"?Be=!0:t==="needs-login"&&(Be=!1)},[t]),t==="needs-login"?n.jsx(lr,{provider:r,credsPresent:a,reason:s,expiresAt:o,onAuthenticated:()=>void i(),onAuthorized:()=>{}}):t==="authenticated"||l?n.jsx(rr,{...e}):n.jsxs("div",{"data-testid":"gated-agent-chat-checking",className:"mt-2 flex items-center gap-3 rounded-lg border border-[var(--border-subtle)] px-3 py-4",children:[n.jsx("span",{"aria-hidden":"true",className:"h-4 w-4 rounded-full border-2 border-[var(--text-dim)] border-t-transparent animate-spin"}),n.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:"Checking your account…"})]})}const wo=Object.freeze(Object.defineProperty({__proto__:null,GatedAgentChat:cr},Symbol.toStringTag,{value:"Module"})),Ta=500,pe=new Set;let de=null,Se=null;async function Ve(){let e;try{const t=await fetch("/api/editor-dev-server");t.ok?e={ok:!0,data:await t.json()}:e={ok:!1,error:`Failed to fetch dev server status: ${t.statusText}`}}catch(t){e={ok:!1,error:t instanceof Error?t.message:String(t)}}if(pe.size!==0){Se=e;for(const t of[...pe])t(e)}}function Ea(e){return pe.add(e),Se&&e(Se),de===null&&(de=setInterval(()=>{Ve()},Ta),Ve()),()=>{pe.delete(e),pe.size===0&&de!==null&&(clearInterval(de),de=null,Se=null)}}function Oa(){Ve()}const ze=4e3;function mt(e){let t;try{t=JSON.stringify(e,null,2)}catch{t=String(e)}return t.length>ze?`${t.slice(0,ze)}
17
+ … (truncated, ${t.length-ze} more chars)`:t}function Aa({slug:e,scenarioName:t,seedTabs:r,mockEntries:a,selectedMock:s,selectedSeedTab:o,selectedSeedRows:i}){const l=[],u=t??e;if(l.push(`# Edit Scenario Data: "${u}"`),l.push(""),l.push(`**Slug**: ${e}`),l.push(`**Scenario file**: .codeyam/scenarios/${e}.json`),l.push(""),l.push("## Scenario overview"),r.length>0){l.push("### Seed & Local tables");for(const f of r){const x=f.category?` (${f.category})`:"";l.push(`- **${f.label}**${x} — dataKey \`${f.dataKey}\``)}l.push("")}if(a.length>0){l.push("### HTTP mocks");const f=new Map;for(const x of a){const h=f.get(x.source)??[];h.push(x),f.set(x.source,h)}for(const[x,h]of f){l.push(`**${x}** (${h.length}):`);for(const d of h)l.push(`- \`${d.method} ${d.pathPattern}\``)}l.push("")}if(s){const f=`${s.method} ${s.pathPattern}`;l.push(`## Currently viewing: mock \`${f}\``),l.push(`- **Source**: ${s.source}`),s.status!==void 0&&l.push(`- **Status**: ${s.status}`);const x=s.headers??{},h=Object.entries(x);if(h.length>0){l.push("- **Headers**:");for(const[d,m]of h)l.push(` - \`${d}: ${m}\``)}s.body!==void 0&&s.body!==null?(l.push("- **Body**:"),l.push("```json"),l.push(mt(s.body)),l.push("```")):l.push("- **Body**: (empty)"),l.push("")}else if(o){if(l.push(`## Currently viewing: seed table **${o.label}**`),l.push(`- **dataKey**: \`${o.dataKey}\``),o.category&&l.push(`- **Category**: ${o.category}`),o.description&&l.push(`- **Description**: ${o.description}`),o.schemaFields&&o.schemaFields.length>0){l.push("- **Schema**:");for(const f of o.schemaFields){const x=f.isId?" (PK)":"";l.push(` - \`${f.name}\`: ${f.type}${x}`)}}i&&i.length>0?(l.push(`- **Rows** (${i.length}):`),l.push("```json"),l.push(mt(i)),l.push("```")):l.push("- **Rows**: (none yet)"),l.push("")}return l.push("## Your task"),l.push("The user is looking at the Scenario Data Panel and wants your help adjusting its data. Ask what change they'd like to make."),l.push(""),l.push("Typical edits:"),l.push('- Tweak an HTTP mock body, status, or headers → update `mocks.http["METHOD /path"]` in the scenario JSON'),l.push("- Add or remove seed rows → update the `seed` section"),l.push("- Adjust `localStorage` values → update the `localStorage` section"),l.push(""),l.push("To save changes:"),l.push("1. Write the updated scenario JSON to `.codeyam/tmp/scenario.json`"),l.push("2. Run: `codeyam-editor editor register @.codeyam/tmp/scenario.json`"),l.push("3. The editor will reload automatically and the panel will reflect the new data."),l.join(`
18
+ `)}const Xe=new Set;let _e=null;const Ma=150;function So(e){return Xe.add(e),()=>{Xe.delete(e)}}function se(){_e&&clearTimeout(_e),_e=setTimeout(()=>{_e=null;for(const e of Xe)e()},Ma)}const Je=new Set;function ko(e){for(const t of Je)t(e)}function Pa(e){return Je.add(e),()=>{Je.delete(e)}}function Da({onSelect:e,onFocus:t}){c.useEffect(()=>Pa(({routeKey:r,jsonPath:a})=>{e(r),t(a)}),[e,t])}async function Ae(e){try{const t=await e.json();if(t.error)return t.error}catch{}return`Request failed (${e.status})`}async function Ra(e,t=null){const r=t!=null?`?since_ms=${encodeURIComponent(t)}`:"",s=await(await fetch(`/api/mock-panel/${encodeURIComponent(e)}${r}`)).json();if("error"in s)throw new Error(s.error);return s}async function bt(e,t){const r=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t.routeKey)}`,a=await fetch(r,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t.status,body:t.body,headers:t.headers})});if(!a.ok)throw new Error(await Ae(a))}async function Ia(e,t){const r=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t)}`,a=await fetch(r,{method:"DELETE"});if(!a.ok)throw new Error(await Ae(a))}async function La(e,t){const r=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t)}/passthrough`,a=await fetch(r,{method:"POST"});if(!a.ok)throw new Error(await Ae(a))}function Z(e){return e.kind==="shared"?`shared:${e.slug}`:e.kind}async function $a(e){const t=await fetch("/api/mocks/save-scoped",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json();if(!t.ok||"success"in r&&r.success===!1)throw new Error("error"in r?r.error:`Save failed (${t.status})`);return r}async function Fa(e,t,r){const a=new URLSearchParams({scenarioSlug:e,routeKey:t,scope:Z(r)}),s=await fetch(`/api/mocks/save-scope-impact?${a.toString()}`);if(!s.ok)throw new Error(await Ae(s));return(await s.json()).impactedScenarios??[]}function Ba(){const[e,t]=c.useState(null),[r,a]=c.useState(null),s=c.useRef(null);return c.useEffect(()=>Ea(i=>{if(!i.ok){a(i.error);return}const l=i.data,u=JSON.stringify(l);if(u===s.current){a(null);return}s.current=u,t(l),a(null)}),[]),{status:e,error:r,restart:async()=>{try{const i=await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})});if(!i.ok)throw new Error(`Failed to restart dev server: ${i.statusText}`);Oa()}catch(i){a(i instanceof Error?i.message:String(i))}}}}function za(e){const[t,r]=c.useState([]),[a,s]=c.useState(null),[o,i]=c.useState(!1),[l,u]=c.useState(null),{events:f}=qr(),{status:x}=Ba(),h=(x==null?void 0:x.lastIframeLoadedAtMs)??null,d=c.useCallback(async()=>{if(!e){r([]),s(null);return}i(!0),u(null);try{const p=await Ra(e,h);r(p.entries),s(p.defaultSlug)}catch(p){u(p instanceof Error?p.message:"Failed to load mocks")}finally{i(!1)}},[e,h]);c.useEffect(()=>{d()},[d]),c.useEffect(()=>{const p=f[f.length-1];!p||p.type!=="http_request"||d()},[f,d]);const m=c.useCallback(async p=>{e&&(await bt(e,p),await d())},[e,d]),b=c.useCallback(async p=>{e&&(p.scope.kind==="scenario"?await bt(e,{routeKey:p.routeKey,status:p.status,body:p.body,headers:p.headers}):await $a({scenarioSlug:e,routeKey:p.routeKey,scope:p.scope,status:p.status,body:p.body,headers:p.headers}),await d())},[e,d]),g=c.useCallback(async p=>{e&&(await Ia(e,p),await d())},[e,d]),y=c.useCallback(async p=>{e&&(await La(e,p),await d())},[e,d]);return{entries:t,defaultSlug:a,loading:o,error:l,refresh:d,upsert:m,upsertScoped:b,remove:g,setPassthrough:y}}function Ka(e){const t={};for(const[r,a]of Object.entries(e))if(typeof a=="string")try{const s=JSON.parse(a);Array.isArray(s)?t[r]=s:typeof s=="object"&&s!==null&&(t[r]=[s])}catch{}else Array.isArray(a)&&(t[r]=a);return t}function Ha(e,t){return e.length===0||t.length===0?!1:e.filter(a=>t.includes(a)).length>=Math.min(e.length,t.length)*.5}function Ua(e){return e==null?"null":typeof e=="number"?Number.isInteger(e)?"int4":"float":typeof e=="boolean"?"bool":typeof e=="object"?Array.isArray(e)?"array":"json":"text"}function Ya(e,t){return e.length>0?Object.keys(e[0]):t?t.map(r=>r.name):[]}function Wa(e,t,r){const a=new Map((r||[]).map(o=>[o.name,o.type])),s={};for(const o of e)s[o]=a.get(o)||(t.length>0?Ua(t[0][o]):"text");return s}function Va(e,t){var r;return((r=t==null?void 0:t.find(a=>a.isId))==null?void 0:r.name)||e.find(a=>a==="id")||null}function Xa(e,t){const{_metadata:r,...a}=t,s=a.localStorage&&typeof a.localStorage=="object"&&!Array.isArray(a.localStorage)?Ka(a.localStorage):{},o={};if(a.seed&&typeof a.seed=="object"&&!Array.isArray(a.seed))for(const[d,m]of Object.entries(a.seed))Array.isArray(m)&&(o[d]=m);const i={},l=[],u=new Set,f=new Set,x=new Set;for(const d of e){const m=d.name.charAt(0).toLowerCase()+d.name.slice(1),b=d.fields.map(p=>p.name);let g=null,y=[];for(const p of[d.name,m,`${m}s`])if(p in a&&Array.isArray(a[p])){g=p,y=a[p],f.add(p);break}if(!g){for(const p of[d.name,m,`${m}s`])if(p in o){g=p,y=o[p],x.add(p),p in s&&u.add(p);break}}if(!g){for(const p of[d.name,m,`${m}s`])if(p in s){g=m,y=s[p],u.add(p);break}}if(!g){for(const[p,j]of Object.entries(s))if(!u.has(p)&&j.length>0&&Ha(b,Object.keys(j[0]))){g=m,y=j,u.add(p);break}}g||(g=m),i[g]=y,l.push({label:d.name,dataKey:g,category:d.category,description:d.description,schemaFields:d.fields.map(p=>({name:p.name,type:p.type,isId:p.isId??!1}))})}const h=new Set(["name","id","url","dimensions","componentName","scenarioType","pageFilePath","routeName","description","props","env"]);for(const[d,m]of Object.entries(a))d==="_metadata"||d==="localStorage"||d==="seed"||d==="type"||d==="mocks"||h.has(d)||f.has(d)||Ja(m)&&(i[d]=m,l.push({label:d,dataKey:d}));for(const[d,m]of Object.entries(o))x.has(d)||(i[d]=m,l.push({label:d,dataKey:d}));for(const[d,m]of Object.entries(s))u.has(d)||(i[d]=m,l.push({label:d,dataKey:d}));return{data:i,tabs:l}}function xt(e){return e==="null"?null:e==="true"?!0:e==="false"?!1:e===""?"":isNaN(Number(e))?e:Number(e)}function Ja(e){return Array.isArray(e)&&e.length>0&&typeof e[0]=="object"&&e[0]!==null}function qa(e){if(typeof e!="object"||e===null||!("props"in e))return null;const t=e.props;return typeof t!="object"||t===null||Array.isArray(t)?null:t}function Ga(e){if(typeof e!="object"||e===null||!("browserState"in e))return null;const t=e.browserState;return typeof t!="object"||t===null||Array.isArray(t)?null:t}function Qa(e,t){const r=new Set;for(const a of t){const s=e[a.dataKey];Array.isArray(s)&&s.length>0&&r.add(a.dataKey)}return r}function Za(e){if(typeof e=="object"&&e!==null&&"shares"in e){const t=e.shares;if(Array.isArray(t))return t.filter(r=>typeof r=="string")}return[]}function es(e){const[t,r]=c.useState({data:null,tableTabs:[],scenarioOwnedDataKeys:new Set,shares:[],props:null,browserState:null,loading:!0,error:null});return c.useEffect(()=>{r(a=>({...a,loading:!0,error:null})),Promise.all([fetch("/api/data-structure").then(a=>a.json()).catch(()=>[]),fetch(`/api/scenarios/${encodeURIComponent(e)}`).then(a=>{if(!a.ok)throw new Error(`HTTP ${a.status}`);return a.json()})]).then(([a,s])=>{const o=Xa(Array.isArray(a)?a:[],s);r({data:o.data,tableTabs:o.tabs,scenarioOwnedDataKeys:Qa(o.data,o.tabs),shares:Za(s),props:qa(s),browserState:Ga(s),loading:!1,error:null})}).catch(a=>r({data:null,tableTabs:[],scenarioOwnedDataKeys:new Set,shares:[],props:null,browserState:null,loading:!1,error:a instanceof Error?a.message:"Failed to load"}))},[e]),t}function et(e,t=""){return`/api/scenarios/${encodeURIComponent(e)}/draft${t}`}async function ts(e){const t=await fetch(et(e,"/status"));if(!t.ok)return{isDirty:!1,diffSummary:null};const r=await t.json();return{isDirty:!!r.isDirty,diffSummary:r.diffSummary??null}}async function rs(e){const t=await fetch(et(e,"/commit"),{method:"POST"});if(!t.ok)throw new Error(`Save failed (${t.status})`)}async function ns(e){const t=await fetch(et(e),{method:"DELETE"});if(!t.ok)throw new Error(`Cancel failed (${t.status})`)}function as({slug:e,onPreviewReload:t}){const[r,a]=c.useState(!1),[s,o]=c.useState(null),[i,l]=c.useState(!1),[u,f]=c.useState(!1),[x,h]=c.useState(null),d=c.useRef(null),m=c.useCallback(async()=>{if(!e){a(!1),o(null);return}try{const j=await ts(e);a(j.isDirty),o(j.diffSummary)}catch{}},[e]);c.useEffect(()=>{m()},[m]),c.useEffect(()=>{if(!r)return;const j=v=>{v.preventDefault(),v.returnValue=""};return window.addEventListener("beforeunload",j),()=>window.removeEventListener("beforeunload",j)},[r]);const b=c.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{m()},100)},[m]),g=c.useCallback(async()=>{if(e){l(!0),h(null);try{await rs(e),a(!1),o(null),t&&t()}catch(j){h(j instanceof Error?j.message:"Save failed")}finally{l(!1)}}},[e,t]),y=c.useCallback(async()=>{if(e){f(!0),h(null);try{await ns(e),a(!1),o(null),t&&t()}catch(j){h(j instanceof Error?j.message:"Cancel failed")}finally{f(!1)}}},[e,t]),p=c.useCallback(j=>r?window.confirm(j):!0,[r]);return{isDirty:r,saving:i,cancelling:u,error:x,diffSummary:s,save:g,cancel:y,markDirty:b,confirmIfDirty:p}}const ss={scenario:"Scenario",shared:"Shared",default:"Defaults","catalog-only":"Observed only",passthrough:"Passthrough"},os={scenario:null,shared:null,default:null,"catalog-only":"Observed during live traffic but not mocked yet. Promote it to a scenario mock to capture and edit the response.",passthrough:null};function dr(e){return ss[e]??e}function is(e){return os[e]??null}const ls={scenario:"bg-emerald-500/15 text-emerald-300 border-emerald-500/40",shared:"bg-violet-500/15 text-violet-300 border-violet-500/40",default:"bg-[#D7FF63]/15 text-[#D7FF63] border-[#D7FF63]/40","catalog-only":"bg-slate-500/15 text-slate-300 border-slate-500/40",passthrough:"bg-zinc-500/15 text-zinc-300 border-zinc-500/40"};function tt({source:e}){const t=is(e);return n.jsx("span",{className:`px-1.5 py-0.5 rounded border ${ls[e]}`,title:t??`source: ${e}`,children:dr(e)})}const Co=Object.freeze(Object.defineProperty({__proto__:null,MockSourceBadge:tt},Symbol.toStringTag,{value:"Module"}));function ur({label:e,scenarioCount:t,inheritedCount:r,expanded:a,onToggle:s}){const o=r===0;return n.jsxs("h3",{className:"px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-dim)]",children:[n.jsx("div",{className:"mb-0.5",children:e}),n.jsxs("div",{className:"flex items-center gap-1 normal-case tracking-normal font-normal",children:[n.jsxs("span",{children:[t," scenario-specific"]}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsxs("button",{type:"button",onClick:s,disabled:o,"aria-expanded":a,className:`inline-flex items-center gap-0.5 ${o?"cursor-default text-[var(--text-dim)]":"cursor-pointer hover:text-[var(--text-primary)]"}`,children:[n.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px]",children:o?"":a?"▾":"▸"}),n.jsxs("span",{children:[r," inherited from default"]})]})]})]})}const No=Object.freeze(Object.defineProperty({__proto__:null,SidebarGroupOverrideHeader:ur},Symbol.toStringTag,{value:"Module"}));function fr({children:e}){return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"mx-3 my-1 border-t border-[var(--border-subtle)]"}),n.jsx("div",{className:"px-3 pb-1 text-[9px] uppercase tracking-wider text-[var(--text-dim)]",children:"Inherited from default"}),e]})}const To=Object.freeze(Object.defineProperty({__proto__:null,SidebarInheritedSection:fr},Symbol.toStringTag,{value:"Module"}));function pr({slug:e}){return n.jsx("span",{className:"px-1 py-0.5 rounded border text-[9px] font-mono bg-violet-500/10 text-violet-300 border-violet-500/30",title:`from shared-data set: ${e}`,children:e})}const Eo=Object.freeze(Object.defineProperty({__proto__:null,MockSharedSlugBadge:pr},Symbol.toStringTag,{value:"Module"})),cs={GET:"text-emerald-400",POST:"text-[#D7FF63]",PUT:"text-amber-400",PATCH:"text-purple-400",DELETE:"text-red-400"};function hr({entry:e,routeKey:t,active:r,onSelect:a}){const s=cs[e.method]??"text-[var(--text-muted)]";return n.jsxs("button",{onClick:a,className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 transition-colors cursor-pointer ${r?"bg-[var(--accent-blue)]/10 border-[var(--accent-blue)] text-[var(--text-primary)]":"border-transparent text-[var(--text-muted)] hover:bg-[var(--bg-card)] hover:text-[var(--text-primary)]"}`,title:t,children:[n.jsx("span",{className:`font-mono text-[9px] font-semibold ${s}`,children:e.method}),n.jsx("span",{className:"truncate flex-1 font-mono",children:e.pathPattern}),e.source==="shared"&&e.sharedSlug&&n.jsx(pr,{slug:e.sharedSlug})]})}const Oo=Object.freeze(Object.defineProperty({__proto__:null,SidebarMockEntryRow:hr},Symbol.toStringTag,{value:"Module"})),ds=["scenario","shared","default","catalog-only","passthrough"];function ee(e){return`${e.method} ${e.pathPattern}`}function mr({seedTabs:e,mockEntries:t,selection:r,onSelect:a,overrides:s}){const o=new Map;for(const i of t){const l=o.get(i.source)??[];l.push(i),o.set(i.source,l)}return n.jsxs("nav",{className:"w-56 shrink-0 border-r border-[var(--border-subtle)] bg-[var(--bg-deep)] overflow-y-auto",children:[n.jsxs(ke,{label:"Browser Environment",count:4,emptyHint:"",children:[n.jsx(fe,{label:"Cookies",active:(r==null?void 0:r.kind)==="browser"&&r.tab==="cookies",onSelect:()=>a({kind:"browser",tab:"cookies"})}),n.jsx(fe,{label:"Local Storage",active:(r==null?void 0:r.kind)==="browser"&&r.tab==="localStorage",onSelect:()=>a({kind:"browser",tab:"localStorage"})}),n.jsx(fe,{label:"Session Storage",active:(r==null?void 0:r.kind)==="browser"&&r.tab==="sessionStorage",onSelect:()=>a({kind:"browser",tab:"sessionStorage"})}),n.jsx(fe,{label:"Request Headers",active:(r==null?void 0:r.kind)==="browser"&&r.tab==="headers",onSelect:()=>a({kind:"browser",tab:"headers"})})]}),n.jsx(ke,{label:"Seed & Local",count:e.length,emptyHint:"No seed or localStorage data",override:s?{scenarioCount:s.scenarioSeedCount,inheritedCount:s.inheritedSeedCount,renderInherited:()=>gt({tabs:s.inheritedSeedTabs,selection:r,onSelect:a})}:void 0,children:gt({tabs:e,selection:r,onSelect:a})}),n.jsx(ke,{label:"Mock APIs",count:t.length,emptyHint:"No HTTP mocks registered",override:s?{scenarioCount:s.scenarioMockCount,inheritedCount:s.inheritedMockCount,renderInherited:()=>yt({entries:s.inheritedMockEntries,selection:r,onSelect:a})}:void 0,children:yt({entries:t,grouped:o,selection:r,onSelect:a})})]})}function gt({tabs:e,selection:t,onSelect:r}){return e.map(a=>{const s=(t==null?void 0:t.kind)==="seed"&&t.dataKey===a.dataKey;return n.jsxs("button",{onClick:()=>r({kind:"seed",dataKey:a.dataKey}),className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 transition-colors cursor-pointer ${s?"bg-[var(--accent-active)]/10 border-[var(--accent-active)] text-[var(--text-primary)]":"border-transparent text-[var(--text-muted)] hover:bg-[var(--bg-card)] hover:text-[var(--text-primary)]"}`,children:[n.jsx("span",{className:"truncate flex-1",children:a.label}),a.category&&n.jsx("span",{className:"text-[9px] uppercase tracking-wide text-[var(--text-dim)]",children:a.category==="mock-api"?"API":a.category})]},a.dataKey)})}function fe({label:e,active:t,onSelect:r}){return n.jsxs("button",{onClick:r,className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 transition-colors cursor-pointer ${t?"bg-[var(--accent-active)]/10 border-[var(--accent-active)] text-[var(--text-primary)]":"border-transparent text-[var(--text-muted)] hover:bg-[var(--bg-card)] hover:text-[var(--text-primary)]"}`,children:[n.jsx("span",{className:"truncate flex-1",children:e}),n.jsx("span",{className:"text-[9px] uppercase tracking-wide text-[var(--text-dim)]",children:"ENV"})]})}function yt({entries:e,grouped:t,selection:r,onSelect:a}){const s=t??us(e);return ds.flatMap(o=>{const i=s.get(o)??[];return i.length===0?[]:[n.jsxs("div",{className:"px-3 pt-2 pb-1 text-[9px] uppercase tracking-wider text-[var(--text-dim)] font-semibold flex items-center gap-1.5",children:[dr(o),n.jsx(tt,{source:o})]},`hdr-${o}`),...i.map(l=>{const u=ee(l),f=(r==null?void 0:r.kind)==="mock"&&r.routeKey===u;return n.jsx(hr,{entry:l,routeKey:u,active:f,onSelect:()=>a({kind:"mock",routeKey:u})},u)})]})}function us(e){const t=new Map;for(const r of e){const a=t.get(r.source)??[];a.push(r),t.set(r.source,a)}return t}function ke({label:e,count:t,emptyHint:r,children:a,override:s}){const[o,i]=c.useState(!1);if(s){const{scenarioCount:l,inheritedCount:u,renderInherited:f}=s,x=l+(o?u:0);return n.jsxs("section",{className:"py-2",children:[n.jsx(ur,{label:e,scenarioCount:l,inheritedCount:u,expanded:o,onToggle:()=>i(h=>!h)}),x===0?n.jsx("p",{className:"px-3 py-1 text-[10px] italic text-[var(--text-dim)]",children:r}):n.jsxs("div",{children:[a,o&&u>0&&n.jsx(fr,{children:f()})]})]})}return n.jsxs("section",{className:"py-2",children:[n.jsxs("h3",{className:"px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-dim)] flex items-center justify-between",children:[n.jsx("span",{children:e}),n.jsx("span",{children:t})]}),t===0?n.jsx("p",{className:"px-3 py-1 text-[10px] italic text-[var(--text-dim)]",children:r}):n.jsx("div",{children:a})]})}const Ao=Object.freeze(Object.defineProperty({__proto__:null,BrowserStateButton:fe,ScenarioDataPanelSidebar:mr,SidebarGroup:ke,routeKeyFor:ee},Symbol.toStringTag,{value:"Module"}));function fs({seedTabs:e,mockEntries:t,initialSection:r,selection:a,setSelection:s}){c.useEffect(()=>{if(a)return;const o=r==="mocks",i=r==="seed";if(o&&t.length>0){s({kind:"mock",routeKey:ee(t[0])});return}if(i&&e.length>0){s({kind:"seed",dataKey:e[0].dataKey});return}e.length>0?s({kind:"seed",dataKey:e[0].dataKey}):t.length>0&&s({kind:"mock",routeKey:ee(t[0])})},[r,t,e,a,s])}function br(){return n.jsx("div",{className:"flex h-full items-center justify-center p-6",children:n.jsxs("div",{className:"max-w-xs text-center space-y-2",children:[n.jsx("p",{className:"text-sm text-[var(--text-muted)]",children:"No scenario data yet."}),n.jsx("p",{className:"text-xs text-[var(--text-dim)]",children:"Seed data and HTTP mocks will appear here as the scenario captures them, or add them with the scenario editor."})]})})}const Mo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelEmptyState:br},Symbol.toStringTag,{value:"Module"}));function xr({variant:e,onClose:t}){return e!=="slideOver"?null:n.jsx("button",{onClick:t,className:"rounded border border-[var(--border-default)] bg-transparent px-2 py-1 text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:"Close"})}const Po=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelCloseButton:xr},Symbol.toStringTag,{value:"Module"}));function gr({variant:e,providerLabel:t,chatOpen:r,onToggleChat:a}){const s=e==="inline",o=s?"flex items-center gap-1.5 px-3 py-1.5 rounded border text-xs font-medium cursor-pointer transition-colors":"flex items-center gap-1.5 px-2.5 py-1 rounded border text-xs cursor-pointer transition-colors",i=r?"border-[var(--accent-active)] bg-[var(--accent-active)]/15 text-[var(--accent-active)]":s?"border-[var(--accent-active)] bg-[var(--accent-active)] text-black hover:bg-[var(--accent-active)]/90":"border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:border-[var(--accent-active)]/40";return n.jsxs("button",{type:"button",onClick:a,className:`${o} ${i}`,title:`Open a chat with ${t} seeded with this scenario's context`,children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),"Edit with ",t]})}const Do=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelEditChatButton:gr},Symbol.toStringTag,{value:"Module"})),qe=new Set,Ge=new Set;let yr={isActive:!1,previewSlug:null};function ps(){for(const e of qe)e()}function Ro(e){return qe.add(e),()=>{qe.delete(e)}}function Io(e){yr=e;for(const t of Ge)t(e)}function hs(e){return Ge.add(e),()=>{Ge.delete(e)}}function vt(){return yr}function ms(){const[e,t]=c.useState(()=>vt());return c.useEffect(()=>(t(vt()),hs(t)),[]),e}function vr({panelSlug:e,scenarioState:t}){const r=ms(),{isActive:a,previewSlug:s}=t??r;return s!==e?null:n.jsxs("button",{type:"button","aria-pressed":a,onClick:()=>ps(),title:a?"Exit inspect data source":"Inspect data source — click a value in the live preview to see its mock",className:a?"flex items-center gap-1.5 px-2.5 py-1 rounded border text-xs cursor-pointer transition-colors border-[var(--accent-active)] bg-[var(--accent-active)]/15 text-[var(--accent-active)]":"flex items-center gap-1.5 px-2.5 py-1 rounded border text-xs cursor-pointer transition-colors border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:border-[var(--accent-active)]/40",children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),a?"Inspecting…":"Inspect data"]})}const Lo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelInspectButton:vr},Symbol.toStringTag,{value:"Module"}));function _r({variant:e,slug:t}){const r=()=>window.open(Zr(t),"_blank");return e==="slideOver"?n.jsx("button",{type:"button",onClick:r,className:"p-1.5 rounded text-[var(--text-dim)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-card)] transition-colors cursor-pointer",title:"Open in new window",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n.jsx("polyline",{points:"15 3 21 3 21 9"}),n.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}):e==="inline"?n.jsxs("button",{type:"button",onClick:r,className:"flex items-center gap-1.5 px-2.5 py-1 rounded border border-[var(--border-default)] bg-transparent text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:border-[var(--accent-active)]/40 transition-colors cursor-pointer",title:"Open the full data editor in a new browser tab",children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n.jsx("polyline",{points:"15 3 21 3 21 9"}),n.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),"Open in new tab"]}):null}const $o=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelOpenInNewButton:_r},Symbol.toStringTag,{value:"Module"}));function jr(e){if(!e)return"Unsaved changes";const t=[];e.mocks.length>0&&t.push(`${e.mocks.length} mock${e.mocks.length===1?"":"s"}`);const r=e.seed.length;return r>0&&t.push(`${r} seed ${r===1?"table":"tables"}`),t.length>0?`Unsaved changes (${t.join(", ")})`:"Unsaved changes"}function wr({diff:e,saving:t,cancelling:r,error:a,onSave:s,onCancel:o}){return n.jsxs("div",{className:"flex items-center justify-between gap-2 rounded border border-amber-500/40 bg-amber-500/10 px-2 py-1.5","data-testid":"scenario-draft-bar",children:[n.jsx("span",{className:"text-xs text-amber-300 font-medium",children:jr(e)}),n.jsxs("div",{className:"flex items-center gap-2",children:[a&&n.jsx(he,{text:a,className:"text-xs text-red-400"}),n.jsx("button",{type:"button",onClick:o,disabled:r||t,className:"px-2 py-0.5 text-xs rounded border border-[var(--border-default)] bg-[var(--bg-surface)] text-[var(--text-primary)] hover:bg-[var(--bg-input)] disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",children:r?"Discarding…":"Cancel"}),n.jsx("button",{type:"button",onClick:s,disabled:r||t,className:"px-3 py-0.5 text-xs rounded border border-[var(--accent-blue)] bg-[var(--accent-blue)]/20 text-[var(--accent-blue)] hover:bg-[var(--accent-blue)]/30 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",children:t?"Saving…":"Save"})]})]})}const Fo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDraftBar:wr,summarizeDraftDiff:jr},Symbol.toStringTag,{value:"Module"}));function Sr({title:e,slug:t,provider:r,chatOpen:a,onToggleChat:s,variant:o,onClose:i,draftDirty:l,draftDiff:u,draftSaving:f,draftCancelling:x,draftError:h,onSave:d,onCancel:m}){const b=me(r),g=!!l&&!!d&&!!m;return n.jsxs("header",{className:"flex flex-col gap-2 border-b border-[var(--border-subtle)] bg-[var(--bg-deep)] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("div",{className:"min-w-0",children:n.jsxs("h2",{className:"text-sm font-medium text-[var(--text-primary)] truncate",children:["Scenario data: ",e]})}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(gr,{variant:o,providerLabel:b,chatOpen:a,onToggleChat:s}),n.jsx(vr,{panelSlug:t}),n.jsx(_r,{variant:o,slug:t}),i&&n.jsx(xr,{variant:o,onClose:i})]})]}),g&&d&&m&&n.jsx(wr,{diff:u??null,saving:f??!1,cancelling:x??!1,error:h??null,onSave:d,onCancel:m})]})}const Bo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelHeader:Sr},Symbol.toStringTag,{value:"Module"}));function bs(e,t){const[r,a]=c.useState(e.status??200),[s,o]=c.useState(e.body??null),[i,l]=c.useState(()=>Object.entries(e.headers??{}).map(([h,d])=>({name:h,value:d})));c.useEffect(()=>{a(e.status??200),o(e.body??null),l(Object.entries(e.headers??{}).map(([h,d])=>({name:h,value:d})))},[t,e.status,e.body,e.headers]);const u=c.useMemo(()=>e.headers??{},[e.headers]),f=c.useMemo(()=>{if((e.status??200)!==r||JSON.stringify(e.body??null)!==JSON.stringify(s))return!0;const h={};for(const g of i)g.name.trim()&&(h[g.name.trim()]=g.value);const d=u,m=Object.keys(d),b=Object.keys(h);if(m.length!==b.length)return!0;for(const g of b)if(d[g]!==h[g])return!0;return!1},[r,s,i,e.status,e.body,u]);return{status:r,setStatus:a,body:s,setBody:o,headers:i,setHeaders:l,isDirty:f,buildPayload:()=>{const h={};for(const d of i)d.name.trim()&&(h[d.name.trim()]=d.value);return{status:r,body:s,headers:h}}}}function kr({body:e,onBodyChange:t}){const{copied:r,copy:a}=Jr();async function s(){try{const i=await navigator.clipboard.readText(),l=JSON.parse(i);t(l)}catch{}}function o(){a(JSON.stringify(e,null,2))}return n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void s(),className:"text-[10px] px-2 py-0.5 rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:"Paste"}),n.jsx("button",{type:"button",onClick:o,className:"text-[10px] px-2 py-0.5 rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:r?"Copied":"Copy"})]})}const zo=Object.freeze(Object.defineProperty({__proto__:null,JsonBodyActions:kr},Symbol.toStringTag,{value:"Module"}));function xe(e){return JSON.stringify(e)}function Cr(e,t){return e?e instanceof Set?e.has(t):e.includes(t):!1}function xs(e){const t=new Set;function r(a,s){if(a!==null&&typeof a=="object")if(t.add(xe(s)),Array.isArray(a))a.forEach((o,i)=>r(o,[...s,i]));else for(const[o,i]of Object.entries(a))r(i,[...s,o])}return r(e,[]),t}function gs(e){return e===null?"text-slate-400 italic":typeof e=="string"?"text-emerald-300":typeof e=="number"?"text-amber-300":typeof e=="boolean"?"text-[#D7FF63]":"text-[var(--text-primary)]"}function ys(e){return e===null?"null":typeof e=="string"?`"${e}"`:String(e)}function vs(e){return e===null?"null":typeof e=="string"?e:String(e)}function _s(e){const t=e.trim();if(t==="")return"";if(t==="null")return null;if(t==="true")return!0;if(t==="false")return!1;try{return JSON.parse(t)}catch{return e}}function Me(e){return JSON.parse(JSON.stringify(e))}function js(e,t,r){if(t.length===0)return r;const a=Me(e);let s=a;for(let o=0;o<t.length-1;o++)s=s[t[o]];return s[t[t.length-1]]=r,a}function rt(e,t){if(t.length===0)return e;const r=Me(e);let a=r;for(let o=0;o<t.length-1;o++)a=a[t[o]];const s=t[t.length-1];return Array.isArray(a)?a.splice(s,1):delete a[s],r}function ws(e,t){const r=Me(e);let a=r;for(const s of t)a=a[s];return Array.isArray(a)&&a.push(null),r}function Ss(e,t,r){const a=Me(e);let s=a;for(const o of t)s=s[o];return s&&typeof s=="object"&&!Array.isArray(s)&&(s[r]=""),a}function ks(e){if(typeof e!="string"||e.length===0||e!=="$"&&!e.startsWith("$.")&&!e.startsWith("$["))return null;const t=[];let r=e[0]==="$"?1:0;for(;r<e.length;){const a=e[r];if(a==="."){r+=1;const s=r;for(;r<e.length&&e[r]!=="."&&e[r]!=="[";)r+=1;const o=e.slice(s,r);if(o.length===0)return null;t.push(o)}else if(a==="["){const s=e.indexOf("]",r);if(s===-1)return null;const o=e.slice(r+1,s);if(o.length===0)return null;const i=Number(o);if(!Number.isInteger(i)||i<0)return null;t.push(i),r=s+1}else return null}return t}function Cs(e,t){c.useEffect(()=>{if(!e)return;const r=ks(e);r&&t(a=>{const s=new Set(a);for(let o=0;o<r.length;o++)s.add(xe(r.slice(0,o)));return s})},[e,t])}function Pe({collapsible:e,isOpen:t,onToggle:r,parentKey:a,readOnly:s,onRemove:o,children:i}){return n.jsxs("div",{className:"group/row flex items-center gap-1 min-h-[1.5em] hover:bg-[var(--bg-card)]/30 rounded px-1",children:[e?n.jsx("button",{type:"button",onClick:r,className:"w-4 h-4 flex items-center justify-center text-[var(--text-dim)] hover:text-[var(--text-primary)] bg-transparent border-none cursor-pointer p-0","aria-label":t?"Collapse":"Expand",children:n.jsx("span",{className:"text-[10px]",children:t?"▾":"▸"})}):n.jsx("span",{className:"w-4"}),a!==null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-cyan-300",children:typeof a=="number"?`[${a}]`:a}),n.jsx("span",{className:"text-[var(--text-dim)]",children:":"})]}),n.jsx("div",{className:"flex-1 min-w-0 flex items-center gap-1",children:i}),!s&&o&&n.jsx("button",{type:"button",onClick:o,className:"opacity-0 group-hover/row:opacity-100 text-[10px] text-[var(--text-dim)] hover:text-red-400 bg-transparent border-none cursor-pointer px-1",title:"Remove",children:"×"})]})}const Ko=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeNodeLine:Pe},Symbol.toStringTag,{value:"Module"}));function Nr(e){const{value:t,path:r,parentKey:a,expanded:s,onToggle:o,readOnly:i}=e,l=xe(r),u=Cr(s,l),f=t.length>0;return n.jsxs("div",{children:[n.jsxs(Pe,{collapsible:f,isOpen:u,onToggle:()=>o(l),parentKey:a,readOnly:i,onRemove:r.length>0?()=>e.onValueChange(rt(e.rootValue,r)):null,children:[n.jsx("span",{className:"text-[var(--text-dim)]",children:"["}),!u&&n.jsxs(n.Fragment,{children:[f&&n.jsxs("span",{className:"text-[var(--text-dim)] italic",children:[" ","…",t.length," item",t.length===1?"":"s"," "]}),n.jsx("span",{className:"text-[var(--text-dim)]",children:"]"})]})]}),u&&n.jsxs("div",{className:"ml-4 border-l border-[var(--border-subtle)] pl-2",children:[t.map((x,h)=>c.createElement(De,{...e,key:h,value:x,path:[...r,h],parentKey:h,isLast:h===t.length-1})),!i&&n.jsx("button",{type:"button",onClick:()=>e.onValueChange(ws(e.rootValue,r)),className:"text-[10px] text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer py-0.5",children:"+ Add item"})]}),u&&n.jsx("div",{className:"text-[var(--text-dim)]",children:"]"})]})}const Ho=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeArrayNode:Nr},Symbol.toStringTag,{value:"Module"}));function Tr({onSave:e,onCancel:t}){const[r,a]=c.useState("");return n.jsxs("div",{className:"flex items-center gap-1 py-0.5",children:[n.jsx("span",{className:"text-[var(--text-dim)] text-[10px]",children:"+ key:"}),n.jsx("input",{autoFocus:!0,value:r,onChange:s=>a(s.target.value),onBlur:()=>e(r),onKeyDown:s=>{s.key==="Enter"?(s.preventDefault(),e(r)):s.key==="Escape"&&(s.preventDefault(),t())},placeholder:"keyName",className:"rounded border border-[var(--accent-active)]/50 bg-[var(--bg-surface)] px-1 py-0 text-xs font-mono text-[var(--text-primary)] min-w-[6rem]"})]})}const Uo=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeAddKeyInput:Tr},Symbol.toStringTag,{value:"Module"}));function Er(e){const{value:t,path:r,parentKey:a,expanded:s,onToggle:o,readOnly:i,addingKeyAtPath:l,onStartAddKey:u,onStopAddKey:f}=e,x=xe(r),h=Cr(s,x),d=Object.entries(t),m=d.length>0,b=l===x;return n.jsxs("div",{children:[n.jsxs(Pe,{collapsible:m,isOpen:h,onToggle:()=>o(x),parentKey:a,readOnly:i,onRemove:r.length>0?()=>e.onValueChange(rt(e.rootValue,r)):null,children:[n.jsx("span",{className:"text-[var(--text-dim)]",children:"{"}),!h&&n.jsxs(n.Fragment,{children:[m&&n.jsxs("span",{className:"text-[var(--text-dim)] italic",children:[" ","…",d.length," key",d.length===1?"":"s"," "]}),n.jsx("span",{className:"text-[var(--text-dim)]",children:"}"})]})]}),h&&n.jsxs("div",{className:"ml-4 border-l border-[var(--border-subtle)] pl-2",children:[d.map(([g,y],p)=>c.createElement(De,{...e,key:g,value:y,path:[...r,g],parentKey:g,isLast:p===d.length-1})),!i&&!b&&n.jsx("button",{type:"button",onClick:()=>u(x),className:"text-[10px] text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer py-0.5",children:"+ Add key"}),!i&&b&&n.jsx(Tr,{onSave:g=>{g.trim()&&e.onValueChange(Ss(e.rootValue,r,g.trim())),f()},onCancel:f})]}),h&&n.jsx("div",{className:"text-[var(--text-dim)]",children:"}"})]})}const Yo=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeObjectNode:Er},Symbol.toStringTag,{value:"Module"}));function Or({initial:e,onSave:t,onCancel:r}){const[a,s]=c.useState(e);return n.jsx("input",{autoFocus:!0,value:a,onChange:o=>s(o.target.value),onBlur:()=>t(a),onKeyDown:o=>{o.key==="Enter"?(o.preventDefault(),t(a)):o.key==="Escape"&&(o.preventDefault(),r())},className:"flex-1 min-w-[4rem] rounded border border-[var(--accent-active)]/50 bg-[var(--bg-surface)] px-1 py-0 text-xs font-mono text-[var(--text-primary)]"})}const Wo=Object.freeze(Object.defineProperty({__proto__:null,JsonTreePrimitiveEditor:Or},Symbol.toStringTag,{value:"Module"}));function Ar(e){const{value:t,path:r,parentKey:a,readOnly:s,editingPath:o,onStartEdit:i,onStopEdit:l}=e,u=xe(r),f=o===u;return n.jsx(Pe,{collapsible:!1,isOpen:!1,parentKey:a,readOnly:s,onToggle:()=>{},onRemove:r.length>0?()=>e.onValueChange(rt(e.rootValue,r)):null,children:f?n.jsx(Or,{initial:vs(t),onSave:x=>{const h=_s(x);e.onValueChange(js(e.rootValue,r,h)),l()},onCancel:l}):n.jsx("button",{type:"button",onClick:s?void 0:()=>i(u),disabled:s,className:`${s?"":"hover:bg-[var(--bg-card)] cursor-pointer"} bg-transparent border-none px-1 py-0 rounded ${gs(t)} text-left font-mono`,title:s?void 0:"Click to edit",children:ys(t)})})}const Vo=Object.freeze(Object.defineProperty({__proto__:null,JsonTreePrimitiveNode:Ar},Symbol.toStringTag,{value:"Module"}));function De(e){const{value:t}=e;return Array.isArray(t)?n.jsx(Nr,{...e,value:t}):t!==null&&typeof t=="object"?n.jsx(Er,{...e,value:t}):n.jsx(Ar,{...e})}const Xo=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeNode:De},Symbol.toStringTag,{value:"Module"}));function Re({value:e,onChange:t,readOnly:r=!1,focusJsonPath:a}){const[s,o]=c.useState(()=>xs(e)),[i,l]=c.useState(null),[u,f]=c.useState(null);Cs(a,o);function x(h){o(d=>{const m=new Set(d);return m.has(h)?m.delete(h):m.add(h),m})}return n.jsx("div",{className:"flex flex-col h-full min-h-0",children:n.jsx("div",{className:"flex-1 min-h-0 overflow-auto font-mono text-xs leading-relaxed text-[var(--text-primary)] bg-[var(--bg-input)] border border-[var(--border-default)] rounded p-3",children:n.jsx(De,{value:e,path:[],parentKey:null,isLast:!0,readOnly:r,expanded:s,editingPath:i,addingKeyAtPath:u,onToggle:x,onStartEdit:l,onStopEdit:()=>l(null),onStartAddKey:f,onStopAddKey:()=>f(null),onValueChange:t,rootValue:e})})})}const Jo=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeEditor:Re},Symbol.toStringTag,{value:"Module"}));function Mr({headers:e,onChange:t}){function r(o,i){t(e.map((l,u)=>u===o?{...l,...i}:l))}function a(){t([...e,{name:"",value:""}])}function s(o){t(e.filter((i,l)=>l!==o))}return n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Headers"}),n.jsx("button",{type:"button",onClick:a,className:"text-xs text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer",children:"+ Add"})]}),e.length===0&&n.jsx("p",{className:"text-xs text-[var(--text-dim)] italic",children:"No headers"}),e.map((o,i)=>n.jsxs("div",{className:"flex gap-2",children:[n.jsx("input",{value:o.name,onChange:l=>r(i,{name:l.target.value}),placeholder:"Name",className:"flex-1 rounded border border-[var(--border-default)] bg-[var(--bg-surface)] px-2 py-1 text-xs font-mono"}),n.jsx("input",{value:o.value,onChange:l=>r(i,{value:l.target.value}),placeholder:"Value",className:"flex-1 rounded border border-[var(--border-default)] bg-[var(--bg-surface)] px-2 py-1 text-xs font-mono"}),n.jsx("button",{type:"button",onClick:()=>s(i),className:"px-2 text-xs text-[var(--text-dim)] hover:text-red-400 bg-transparent border-none cursor-pointer",children:"×"})]},i))]})}const qo=Object.freeze(Object.defineProperty({__proto__:null,MockBodyHeadersEditor:Mr},Symbol.toStringTag,{value:"Module"})),Ke=5;function Ns(e,t){if(e==="loading")return"Computing impact…";if(e==null)return"";if(t.kind==="scenario")return"Affects only this scenario.";if(e.length===0)return"Affects no other scenarios.";const r=e.length===1?"scenario":"scenarios",a=e.slice(0,Ke).join(", "),s=e.length>Ke?`, +${e.length-Ke} more`:"";return`Affects ${e.length} ${r}: ${a}${s}`}function Ts(e){const t=[{label:"This scenario only",description:"Write to this scenario's mocks file. The row's source flips to scenario.",scope:{kind:"scenario"}}];return e.source==="shared"&&e.sharedSlug&&t.push({label:`Shared data set "${e.sharedSlug}"`,description:"Write to the shared set this row came from. Affects every scenario opted into it.",scope:{kind:"shared",slug:e.sharedSlug}}),(e.source==="default"||e.source==="shared")&&t.push({label:"Defaults",description:"Write to _default.json. Affects every scenario that falls through to defaults for this route.",scope:{kind:"default"}}),t}function Es(e,t){if(e.source==="default"){const r=t.findIndex(a=>a.scope.kind==="default");if(r>=0)return r}if(e.source==="shared"){const r=t.findIndex(a=>a.scope.kind==="shared"&&a.scope.slug===(e.sharedSlug??""));if(r>=0)return r}return 0}function Os(e,t,r){const[a,s]=c.useState({}),o=r.map(i=>Z(i.scope)).join("|");return c.useEffect(()=>{let i=!1;return(async()=>{const u={};for(const f of r)u[Z(f.scope)]="loading";s(u);for(const f of r)try{const x=await Fa(e,t,f.scope);if(i)return;s(h=>({...h,[Z(f.scope)]:x}))}catch{if(i)return;s(x=>({...x,[Z(f.scope)]:[]}))}})(),()=>{i=!0}},[e,t,o]),a}function Pr({choice:e,selected:t,impactLabel:r,onSelect:a}){return n.jsxs("label",{className:`flex cursor-pointer flex-col rounded border p-3 text-xs transition-colors ${t?"border-violet-500 bg-violet-500/10":"border-[var(--border-subtle)] hover:bg-[var(--bg-elevated)]"}`,children:[n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"radio",name:"save-scope",checked:t,onChange:a}),n.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:e.label})]}),n.jsx("span",{className:"mt-1 pl-6 text-[var(--text-muted)]",children:e.description}),n.jsx("span",{className:"mt-1 pl-6 text-[var(--text-dim)] italic",children:r})]})}const Go=Object.freeze(Object.defineProperty({__proto__:null,SaveScopeChoiceRow:Pr},Symbol.toStringTag,{value:"Module"}));function Dr({entry:e,scenarioSlug:t,routeKey:r,onCancel:a,onConfirm:s}){const o=Ts(e),[i,l]=c.useState(()=>Es(e,o)),u=Os(t,r,o),[f,x]=c.useState(!1),[h,d]=c.useState(null),m=async()=>{const b=o[i];if(b){x(!0),d(null);try{await s(b.scope)}catch(g){d(g instanceof Error?g.message:"Save failed")}finally{x(!1)}}};return n.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"save-scope-modal-title",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",children:n.jsxs("div",{className:"w-[28rem] max-w-[90vw] rounded-lg border border-[var(--border-default)] bg-[var(--bg-surface)] p-5 shadow-xl",children:[n.jsx("h2",{id:"save-scope-modal-title",className:"text-sm font-semibold text-[var(--text-primary)]",children:"Where should this save land?"}),n.jsx("p",{className:"mt-1 text-xs text-[var(--text-muted)]",children:r}),n.jsx("div",{className:"mt-4 space-y-2",children:o.map((b,g)=>n.jsx(Pr,{choice:b,selected:i===g,impactLabel:Ns(u[Z(b.scope)],b.scope),onSelect:()=>l(g)},Z(b.scope)))}),h&&n.jsx(he,{text:h,className:"text-xs text-red-400",rowClassName:"mt-3"}),n.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:a,disabled:f,className:"rounded border border-[var(--border-default)] px-3 py-1.5 text-xs text-[var(--text-primary)] hover:bg-[var(--bg-elevated)] disabled:opacity-50",children:"Cancel"}),n.jsx("button",{type:"button",onClick:()=>void m(),disabled:f,className:"rounded bg-violet-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-violet-400 disabled:opacity-50",children:f?"Saving…":"Save"})]})]})})}const Qo=Object.freeze(Object.defineProperty({__proto__:null,SaveScopeModal:Dr},Symbol.toStringTag,{value:"Module"}));function Rr({entry:e,routeKey:t,scenarioSlug:r,onSave:a,focusJsonPath:s}){const o=bs(e,t),[i,l]=c.useState(null),[u,f]=c.useState(!1),[x,h]=c.useState(!1);c.useEffect(()=>{l(null),h(!1)},[t]);const d=async b=>{f(!0),l(null);try{const g=o.buildPayload();await a({routeKey:t,...g,scope:b})}catch(g){throw l(g instanceof Error?g.message:"Save failed"),g}finally{f(!1)}},m=async()=>{if(o.isDirty){if(e.source==="scenario"){try{await d({kind:"scenario"})}catch{}return}h(!0)}};return n.jsxs("div",{className:"flex flex-col gap-3 h-full min-h-0",children:[i&&n.jsx(he,{text:i,className:"text-xs text-red-400"}),n.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[n.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Status"}),n.jsx("input",{type:"number",value:o.status,onChange:b=>o.setStatus(Number(b.target.value)),className:"w-20 rounded border border-[var(--border-default)] bg-[var(--bg-surface)] px-2 py-1 text-xs font-mono"}),n.jsx("div",{className:"flex-1"}),n.jsx("button",{type:"button",onClick:()=>void m(),disabled:!o.isDirty||u,className:"rounded bg-violet-500 px-3 py-1 text-xs font-medium text-white hover:bg-violet-400 disabled:opacity-50",children:u?"Saving…":o.isDirty?"Save changes":"Saved"})]}),n.jsx(Mr,{headers:o.headers,onChange:o.setHeaders}),n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[n.jsxs("div",{className:"flex items-center gap-2 pb-1",children:[n.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Body"}),n.jsx(kr,{body:o.body,onBodyChange:o.setBody})]}),n.jsx(Re,{value:o.body,onChange:o.setBody,focusJsonPath:s},t)]}),x&&n.jsx(Dr,{entry:e,scenarioSlug:r,routeKey:t,onCancel:()=>h(!1),onConfirm:async b=>{await d(b),h(!1)}})]})}const Zo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockEditable:Rr},Symbol.toStringTag,{value:"Module"}));function As(e,t){if(e==null)return"never";const r=Math.max(0,Math.floor((t-e)/1e3));if(r<60)return`${r}s ago`;const a=Math.floor(r/60);return a<60?`${a}m ago`:`${Math.floor(a/60)}h ago`}const _t={GET:"text-emerald-400 border-emerald-400/40",POST:"text-[#D7FF63] border-[#D7FF63]/40",PUT:"text-amber-400 border-amber-400/40",PATCH:"text-purple-400 border-purple-400/40",DELETE:"text-red-400 border-red-400/40"};function Ms(e){return _t[e]??_t.GET}function Ir({entry:e,scenarioHasDefaultFallback:t,onSave:r,onRemove:a,onPassthrough:s}){const o=`${e.method} ${e.pathPattern}`,i=Ms(e.method),l=e.status??e.lastObservedStatus,u=c.useMemo(()=>e.lastObservedMs?As(e.lastObservedMs,Date.now()):null,[e.lastObservedMs]),f="px-3 py-1 rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer text-xs";return n.jsxs("header",{className:"border-b border-[var(--border-subtle)] bg-[var(--bg-deep)] px-4 py-3 space-y-2 flex-shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:`px-2 py-0.5 rounded border font-mono text-xs ${i}`,children:e.method}),n.jsx("span",{className:"font-mono text-sm text-[var(--text-primary)] break-all",children:e.pathPattern}),n.jsx(tt,{source:e.source}),l!==void 0&&n.jsx("span",{className:"px-1.5 py-0.5 rounded border border-[var(--border-default)] text-[var(--text-muted)] font-mono text-xs",children:l}),e.observedCount>0&&n.jsxs("span",{className:"ml-auto text-xs text-[var(--text-dim)]",children:[e.observedCount,"× ",u?`· ${u}`:""]})]}),e.variants.length>1&&n.jsxs("div",{className:"text-[10px] text-[var(--text-dim)] font-mono",children:["variants: ",e.variants.filter(x=>x!==o).join(", ")]}),n.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.source==="scenario"&&t&&n.jsx("button",{onClick:()=>void a(o),className:f,title:"Remove this scenario mock and fall back to the default",children:"Revert to default"}),e.source==="scenario"&&n.jsx("button",{onClick:()=>void s(o),className:f,children:"Mark passthrough"}),e.source==="default"&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>void r({routeKey:o,status:e.status??200,body:e.body,headers:e.headers??{},scope:{kind:"scenario"}}),className:"px-3 py-1 rounded border border-emerald-500/50 bg-emerald-500/10 text-emerald-300 hover:bg-emerald-500/20 cursor-pointer text-xs",title:"Copy default body into this scenario",children:"Promote to scenario"}),n.jsx("button",{onClick:()=>void s(o),className:f,children:"Mark passthrough"})]}),e.source==="passthrough"&&n.jsx("button",{onClick:()=>void a(o),className:f,children:"Undo passthrough"})]})]})}const ei=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockHeader:Ir},Symbol.toStringTag,{value:"Module"}));function Lr({entry:e}){const t=Object.entries(e.headers??{}),r=e.body!==void 0&&e.body!==null;return!r&&t.length===0?n.jsx("p",{className:"text-xs italic text-[var(--text-dim)]",children:e.source==="catalog-only"?"No mock body yet — this endpoint has only been observed, not mocked. Promote it to a scenario to start editing.":e.source==="passthrough"?"This endpoint passes through to the upstream service.":"No body configured."}):n.jsxs("div",{className:"space-y-3 h-full min-h-0 flex flex-col",children:[t.length>0&&n.jsxs("section",{className:"space-y-1 flex-shrink-0",children:[n.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:"Headers"}),n.jsx("dl",{className:"text-xs font-mono space-y-0.5",children:t.map(([a,s])=>n.jsxs("div",{className:"flex gap-2",children:[n.jsxs("dt",{className:"text-[var(--text-muted)]",children:[a,":"]}),n.jsx("dd",{className:"text-[var(--text-primary)] break-all",children:s})]},a))})]}),r&&n.jsxs("section",{className:"flex-1 min-h-0 flex flex-col",children:[n.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)] pb-1",children:"Body"}),n.jsx(Re,{value:e.body,onChange:()=>{},readOnly:!0},`${e.method} ${e.pathPattern}`)]})]})}const ti=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockReadOnly:Lr},Symbol.toStringTag,{value:"Module"}));function $r({entry:e,scenarioSlug:t,scenarioHasDefaultFallback:r,onSave:a,onRemove:s,onPassthrough:o,focusJsonPath:i}){const l=`${e.method} ${e.pathPattern}`,u=e.source==="scenario"||e.source==="default"||e.source==="shared";return n.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[n.jsx(Ir,{entry:e,scenarioHasDefaultFallback:r,onSave:a,onRemove:s,onPassthrough:o}),n.jsx("div",{className:"flex-1 min-h-0 overflow-auto p-4",children:u?n.jsx(Rr,{entry:e,routeKey:l,scenarioSlug:t,onSave:a,focusJsonPath:i}):n.jsx(Lr,{entry:e})})]})}const ri=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMock:$r},Symbol.toStringTag,{value:"Module"}));function Ps({slug:e,tab:t,initialRows:r,onCellEdited:a}){const[s,o]=c.useState(r),[i,l]=c.useState(null),[u,f]=c.useState(""),[x,h]=c.useState(""),d=c.useRef(null);c.useEffect(()=>{o(r),l(null)},[t.dataKey,r]);function m(j,v){const _=s[j];l({row:j,col:v});const w=_[v]===null?"":typeof _[v]=="object"?JSON.stringify(_[v]):String(_[v]);f(w),h(w)}function b(j){if(f(j),d.current&&clearTimeout(d.current),!i)return;const v=i;d.current=setTimeout(()=>{p(v.row,v.col,j)},600)}function g(){i&&(d.current&&clearTimeout(d.current),p(i.row,i.col,u),l(null))}function y(){if(d.current&&clearTimeout(d.current),!!i){if(u!==x){const j=[...s];j[i.row]={...j[i.row],[i.col]:xt(x)},o(j),fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({table:t.dataKey,rowIndex:i.row,column:i.col,value:x})}).then(()=>{se(),a&&a()}).catch(()=>{})}l(null)}}async function p(j,v,_){const w=[...s];w[j]={...w[j],[v]:xt(_)},o(w);try{await fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({table:t.dataKey,rowIndex:j,column:v,value:_})}),se(),a&&a()}catch{}}return{rows:s,editingCell:i,editValue:u,handleEditCell:m,handleEditValueChange:b,handleSave:g,handleCancelEdit:y}}function Fr({tab:e}){return!e.description&&!e.category?null:n.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-[var(--bg-deep)] border-b border-[var(--border-subtle)]",children:[e.category&&n.jsx("span",{className:`text-[9px] rounded px-1.5 py-0 border ${e.category==="datastore"?"text-[var(--accent-active)]/80 bg-[var(--accent-active)]/10 border-[var(--accent-active)]/30":e.category==="mock-api"?"text-[#D7FF63]/80 bg-[#D7FF63]/10 border-[#D7FF63]/30":"text-[var(--text-muted)] bg-[var(--bg-surface)]/30 border-[var(--text-dim)]/30"}`,children:e.category==="mock-api"?"API Mock":e.category}),e.description&&n.jsx("span",{className:"text-[10px] text-[var(--text-dim)]",children:e.description})]})}const ni=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCategoryBadge:Fr},Symbol.toStringTag,{value:"Module"}));function Br({editingCell:e,editValue:t,onEditValueChange:r,onSave:a,onCancel:s}){return n.jsxs("div",{className:"border-t border-[var(--border-default)] bg-[var(--bg-deep)] px-3 py-2",children:[n.jsx("div",{className:"flex items-center gap-2 mb-1.5",children:n.jsxs("span",{className:"text-[10px] text-[var(--text-muted)]",children:["Editing"," ",n.jsx("strong",{className:"text-[var(--text-secondary)]",children:e.col})," ","in row ",e.row+1]})}),n.jsx("textarea",{value:t,onChange:o=>r(o.target.value),className:"w-full px-2 py-1.5 text-[11px] bg-[var(--bg-card)] text-[var(--text-primary)] border border-[var(--border-default)] rounded outline-none focus:border-[var(--accent-active)]/50 resize-y min-h-[60px] max-h-[200px] font-mono",autoFocus:!0,rows:t.length>100?4:2,onKeyDown:o=>{o.key==="Escape"&&s(),o.key==="Enter"&&(o.metaKey||o.ctrlKey)&&a()}}),n.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[n.jsx("button",{onClick:a,className:"px-3 py-1 text-[10px] font-medium text-[var(--bg-deep)] bg-[var(--accent-active)] rounded cursor-pointer border-none hover:bg-[var(--accent-active)]/80 transition-colors",children:"Save"}),n.jsx("button",{onClick:s,className:"px-3 py-1 text-[10px] text-[var(--text-muted)] hover:text-[var(--text-primary)] bg-transparent border-none cursor-pointer",children:"Cancel"}),n.jsxs("span",{className:"text-[9px] text-[var(--text-dim)] ml-auto",children:["⌘","+Enter to save, Esc to cancel"]})]})]})}const ai=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCellEditor:Br},Symbol.toStringTag,{value:"Module"}));function zr({columns:e,colTypes:t,pkCol:r,rows:a,onEditCell:s}){return e.length===0?n.jsx("div",{className:"px-3 py-4 text-[10px] text-[var(--text-dim)] text-center",children:"No columns defined for this table"}):n.jsx("div",{className:"overflow-x-auto max-h-[300px] overflow-y-auto",children:n.jsxs("table",{className:"w-full text-[10px] border-collapse table-fixed",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"bg-[var(--bg-deep)] sticky top-0 z-10",children:[n.jsx("th",{className:"text-right text-[var(--text-dim)] font-normal px-2 py-1.5 border-b border-[var(--border-default)] w-8",children:"#"}),e.map(o=>n.jsx(Kr,{name:o,type:t[o],isPk:o===r},o))]})}),n.jsx("tbody",{children:a.map((o,i)=>n.jsx(Hr,{row:o,rowIndex:i,columns:e,pkCol:r,onEditCell:s},i))})]})})}function Kr({name:e,type:t,isPk:r}){return n.jsxs("th",{className:"text-left px-2 py-1.5 border-b border-[var(--border-default)] whitespace-nowrap overflow-hidden",children:[r&&n.jsx("span",{className:"inline-block text-[8px] font-bold text-[var(--bg-deep)] bg-[var(--accent-active)] rounded px-1 py-0 mr-1.5 align-middle",children:"PK"}),n.jsx("span",{className:"text-[var(--text-secondary)] font-medium",children:e}),n.jsx("span",{className:"text-[var(--text-dim)] font-normal ml-1",children:t})]})}function Hr({row:e,rowIndex:t,columns:r,pkCol:a,onEditCell:s}){return n.jsxs("tr",{className:"border-b border-[var(--border-subtle)] hover:bg-[var(--bg-card)] group/row",children:[n.jsx("td",{className:"text-right text-[var(--text-dim)] px-2 py-1.5 w-8 select-none",children:t+1}),r.map(o=>n.jsx(Ur,{value:e[o],isPk:o===a,onEdit:()=>s(t,o)},o))]})}function Ur({value:e,isPk:t,onEdit:r}){return n.jsxs("td",{className:`px-2 py-1.5 overflow-hidden relative group/cell ${t?"text-[var(--accent-active)] font-medium":"text-[var(--text-secondary)]"}`,title:String(e??""),children:[n.jsx("span",{className:"truncate block whitespace-nowrap",children:e===null?n.jsx("span",{className:"text-[var(--text-dim)] italic",children:"null"}):typeof e=="object"?n.jsx("span",{className:"text-[var(--text-dim)]",children:JSON.stringify(e)}):typeof e=="number"?n.jsx("span",{className:"text-amber-400",children:String(e)}):String(e)}),n.jsx("button",{onClick:a=>{a.stopPropagation(),r()},className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover/cell:opacity-100 text-[var(--text-dim)] hover:text-[var(--text-primary)] bg-[var(--bg-card)] border border-[var(--border-default)] rounded cursor-pointer p-0.5 transition-opacity",title:"Edit",children:n.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]})}const si=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCell:Ur,DataViewerColumnHeader:Kr,DataViewerRow:Hr,DataViewerTable:zr},Symbol.toStringTag,{value:"Module"}));function Yr({slug:e,tab:t,initialRows:r,onCellEdited:a}){const{rows:s,editingCell:o,editValue:i,handleEditCell:l,handleEditValueChange:u,handleSave:f,handleCancelEdit:x}=Ps({slug:e,tab:t,initialRows:r,onCellEdited:a}),h=Ya(s,t.schemaFields),d=Wa(h,s,t.schemaFields),m=Va(h,t.schemaFields);return n.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[n.jsx(Fr,{tab:t}),n.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:n.jsx(zr,{columns:h,colTypes:d,pkCol:m,rows:s,onEditCell:l})}),o&&n.jsx(Br,{editingCell:o,editValue:i,onEditValueChange:u,onSave:f,onCancel:x})]})}const oi=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainTable:Yr},Symbol.toStringTag,{value:"Module"}));function Ds({slug:e,browserState:t,tab:r,onCellEdited:a}){const s=c.useMemo(()=>{if(!t)return{};switch(r){case"cookies":return t.cookies??{};case"localStorage":return t.localStorage??{};case"sessionStorage":return t.sessionStorage??{};case"headers":return t.requestHeaders??{};default:return{}}},[t,r]),o=c.useCallback(async u=>{const f=r==="headers"?"browserState.requestHeaders":`browserState.${r}`;try{await fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:f,value:JSON.stringify(u)})}),se(),a&&a()}catch{}},[e,r,a]),i=c.useMemo(()=>{switch(r){case"cookies":return"Cookies";case"localStorage":return"Local Storage";case"sessionStorage":return"Session Storage";case"headers":return"Request Headers"}},[r]),l=c.useMemo(()=>{switch(r){case"cookies":return"Cookies injected via Set-Cookie headers on the scenario's initial response.";case"localStorage":return"localStorage items set before the app's JavaScript executes.";case"sessionStorage":return"sessionStorage items set before the app's JavaScript executes.";case"headers":return"Custom headers added to every outbound HTTP request from the iframe."}},[r]);return{value:s,handleChange:o,label:i,description:l}}function Wr({slug:e,browserState:t,tab:r,onCellEdited:a}){const{value:s,handleChange:o,label:i,description:l}=Ds({slug:e,browserState:t,tab:r,onCellEdited:a});return n.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[n.jsxs("div",{className:"px-4 py-3 border-b border-[var(--border-subtle)]",children:[n.jsx("h2",{className:"text-sm font-semibold text-[var(--text-primary)]",children:i}),n.jsx("p",{className:"text-xs text-[var(--text-dim)] mt-1",children:l})]}),n.jsx("div",{className:"flex-1 min-h-0 p-4 overflow-auto",children:n.jsx(Re,{value:s,onChange:o})})]})}const ii=Object.freeze(Object.defineProperty({__proto__:null,BrowserStateTab:Wr},Symbol.toStringTag,{value:"Module"}));function Ce({label:e,active:t,onClick:r}){return n.jsx("button",{type:"button",onClick:r,className:`px-2 py-0.5 rounded-full border text-[10px] font-mono transition-colors cursor-pointer ${t?"bg-violet-500/25 text-violet-100 border-violet-400/70":"bg-violet-500/10 text-violet-300 border-violet-500/40 hover:bg-violet-500/20"}`,"aria-pressed":t,children:e})}const li=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMockDataBadge:Ce},Symbol.toStringTag,{value:"Module"}));function Vr({shares:e,activeBadge:t,onSelect:r}){return n.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap border-b border-[var(--border-subtle)] bg-[var(--bg-deep)] px-4 py-2","data-testid":"scenario-mock-data-strip",children:[n.jsx("span",{className:"text-[10px] uppercase tracking-wider text-[var(--text-dim)] font-semibold",children:"Mock Data:"}),n.jsx(Ce,{label:"This Page",active:t.kind==="this-page",onClick:()=>r({kind:"this-page"})}),e.map(a=>n.jsx(Ce,{label:a,active:t.kind==="share"&&t.slug===a,onClick:()=>r({kind:"share",slug:a})},a)),n.jsx(Ce,{label:"Defaults",active:t.kind==="defaults",onClick:()=>r({kind:"defaults"})})]})}const ci=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMockDataStrip:Vr},Symbol.toStringTag,{value:"Module"}));function Rs({slug:e,scenarioName:t,initialSection:r,onClose:a,variant:s="slideOver"}){const{data:o,tableTabs:i,scenarioOwnedDataKeys:l,shares:u,browserState:f,loading:x,error:h}=es(e),{entries:d,loading:m,error:b,upsertScoped:g,remove:y,setPassthrough:p}=za(e),{config:j}=Mt(),v=(j==null?void 0:j.provider)??"claude",_=as({slug:e,onPreviewReload:se}),w=c.useCallback(()=>{_.markDirty(),se()},[_]),S=c.useCallback(async A=>{await g(A),w()},[g,w]),T=c.useCallback(async A=>{await y(A),w()},[y,w]),$=c.useCallback(async A=>{await p(A),w()},[p,w]),C=c.useCallback(()=>{_.markDirty(),se()},[_]),L=c.useCallback(()=>{a&&_.confirmIfDirty("Discard unsaved changes to this scenario?")&&a()},[a,_]),[N,I]=c.useState(null),[P,D]=c.useState(null),[E,k]=c.useState(!1),z=c.useCallback(A=>I({kind:"mock",routeKey:A}),[]);Da({onSelect:z,onFocus:D});const[K,X]=c.useState({kind:"this-page"}),G=x||m,Y=c.useMemo(()=>s==="inline"?i.filter(A=>l.has(A.dataKey)):i,[s,i,l]),H=c.useMemo(()=>{if(s!=="inline")return d;switch(K.kind){case"this-page":return d.filter(A=>A.consumedThisPageLoad);case"defaults":return d.filter(A=>A.source==="default");case"share":return d.filter(A=>A.source==="shared"&&A.sharedSlug===K.slug)}},[s,d,K]);fs({seedTabs:Y,mockEntries:H,initialSection:r,selection:N,setSelection:I});const Q=c.useMemo(()=>{const A=new Set;for(const le of d)le.source==="default"&&A.add(ee(le));return A},[d]),B=(N==null?void 0:N.kind)==="seed"?Y.find(A=>A.dataKey===N.dataKey)??null:null,J=(N==null?void 0:N.kind)==="mock"?H.find(A=>ee(A)===N.routeKey)??null:null,W=B&&o?o[B.dataKey]??[]:[],V=c.useMemo(()=>Aa({slug:e,scenarioName:t,seedTabs:Y,mockEntries:H,selectedMock:J,selectedSeedTab:B,selectedSeedRows:W}),[e,t,Y,H,J,B,W]),ge=t??e,re=Y.length>0||H.length>0,ne=n.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[n.jsx(Sr,{title:ge,slug:e,provider:v,chatOpen:E,onToggleChat:()=>k(A=>!A),variant:s,onClose:a?L:void 0,draftDirty:_.isDirty,draftDiff:_.diffSummary,draftSaving:_.saving,draftCancelling:_.cancelling,draftError:_.error,onSave:()=>void _.save(),onCancel:()=>void _.cancel()}),s==="inline"&&n.jsx(Vr,{shares:u,activeBadge:K,onSelect:X}),E&&n.jsx("div",{className:"flex-shrink-0 border-b border-[var(--border-subtle)] bg-[var(--bg-deep)]",children:n.jsx(cr,{chatName:`edit-data-${e}`,prompt:V,height:360,onClose:()=>k(!1)})}),n.jsxs("div",{className:"flex flex-1 min-h-0",children:[n.jsx(mr,{seedTabs:Y,mockEntries:H,selection:N,onSelect:I}),n.jsx("main",{className:"flex-1 min-w-0 min-h-0 bg-[var(--bg-deep)] flex flex-col",children:n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[h&&n.jsx(he,{text:`Seed error: ${h}`,className:"text-xs text-red-400",rowClassName:"p-4"}),b&&n.jsx(he,{text:`Mocks error: ${b}`,className:"text-xs text-red-400",rowClassName:"p-4"}),!G&&!re&&n.jsx(br,{}),B&&n.jsx(Yr,{slug:e,tab:B,initialRows:W,onCellEdited:C}),J&&n.jsx($r,{entry:J,scenarioSlug:e,scenarioHasDefaultFallback:Q.has(ee(J)),onSave:S,onRemove:T,onPassthrough:$,focusJsonPath:P}),(N==null?void 0:N.kind)==="browser"&&n.jsx(Wr,{slug:e,browserState:f,tab:N.tab,onCellEdited:C}),!B&&!J&&(N==null?void 0:N.kind)!=="browser"&&re&&!G&&n.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)] italic",children:"Select a data source from the left to view it."}),G&&!re&&n.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)]",children:"Loading scenario data…"})]})})]})]});return s==="fullPage"?n.jsx("div",{className:"fixed inset-0 bg-[var(--bg-deep)] text-[var(--text-primary)]",children:ne}):s==="inline"?n.jsx("div",{className:"rounded-md border border-[var(--border-subtle)] bg-[var(--bg-deep)] max-h-[min(640px,70vh)] min-h-0 flex flex-col overflow-hidden",children:ne}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-40 bg-black/40",onClick:L,"aria-label":"Close scenario data panel"}),n.jsx("aside",{className:"fixed right-0 top-0 z-50 h-full w-full max-w-4xl border-l border-[var(--border-default)] bg-[var(--bg-deep)] shadow-2xl",children:ne})]})}const di=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanel:Rs},Symbol.toStringTag,{value:"Module"}));export{mr as $,_a as A,Wr as B,St as C,Hr as D,Et as E,nn as F,fe as G,qt as H,rr as I,Ar as J,Or as K,Er as L,Mr as M,Pe as N,De as O,Re as P,Nr as Q,ue as R,Rs as S,Wt as T,Tr as U,kr as V,wr as W,pr as X,hr as Y,Dr as Z,Pr as _,tt as a,Go as a$,Vr as a0,Ce as a1,_r as a2,Ir as a3,$r as a4,vr as a5,Sr as a6,br as a7,gr as a8,xr as a9,Qs as aA,Zs as aB,ro as aC,qs as aD,Js as aE,so as aF,Gs as aG,Oo as aH,To as aI,No as aJ,Fo as aK,Ao as aL,$o as aM,ci as aN,li as aO,oi as aP,ti as aQ,ei as aR,Zo as aS,ri as aT,Lo as aU,Bo as aV,Mo as aW,Do as aX,Po as aY,di as aZ,Qo as a_,zr as aa,Br as ab,Fr as ac,fr as ad,ur as ae,Kt as af,zt as ag,Bt as ah,Ft as ai,Vt as aj,Rt as ak,Dt as al,ar as am,or as an,ir as ao,cr as ap,lr as aq,Vs as ar,bo as as,Xs as at,vo as au,yo as av,no as aw,ao as ax,eo as ay,to as az,tr as b,ra as b$,jo as b0,_o as b1,Co as b2,Eo as b3,qo as b4,oo as b5,lo as b6,io as b7,go as b8,Vo as b9,$e as bA,sa as bB,ho as bC,ja as bD,Ln as bE,Sa as bF,an as bG,dn as bH,un as bI,yn as bJ,Nn as bK,fo as bL,In as bM,hn as bN,Bn as bO,It as bP,$n as bQ,Pt as bR,Rn as bS,co as bT,po as bU,$t as bV,Un as bW,Kn as bX,uo as bY,na as bZ,ut as b_,Wo as ba,Yo as bb,Ko as bc,Xo as bd,Jo as be,Ho as bf,Uo as bg,zo as bh,wo as bi,Hs as bj,Ks as bk,Us as bl,Ys as bm,Ws as bn,si as bo,ai as bp,ni as bq,ii as br,xo as bs,me as bt,Ea as bu,Mt as bv,nr as bw,Ee as bx,ca as by,sn as bz,At as c,mo as c0,aa as c1,we as c2,ie as c3,Ba as c4,So as c5,Io as c6,Ro as c7,ko as c8,Wn as c9,Yn as ca,Hn as cb,En as cc,ot as cd,On as ce,Pn as cf,Mn as cg,cn as ch,Qe as ci,Yr as d,se as e,As as f,Rr as g,Lr as h,as as i,es as j,za as k,kt as l,Xt as m,Jt as n,Tt as o,xt as p,Nt as q,Ct as r,te as s,Yt as t,wa as u,Ut as v,Ht as w,ke as x,Kr as y,Ur as z};
@@ -1 +1 @@
1
- import{j as c}from"./markdown-C9tbsVHX.js";import{b as o}from"./react-nrLBr15I.js";import{S as l}from"./ScenarioDataPanel-CLwkrex0.js";function m({slug:t}){const[r,i]=o.useState(void 0);return o.useEffect(()=>{let n=!1;return fetch(`/api/scenarios/${encodeURIComponent(t)}`).then(e=>e.ok?e.json():null).then(e=>{if(n||!e)return;const a=typeof e=="object"&&e!==null&&"name"in e?String(e.name):void 0;i(a),a&&(document.title=`${a} · data`)}).catch(()=>{}),()=>{n=!0}},[t]),c.jsx(l,{slug:t,scenarioName:r,variant:"fullPage"})}const p=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelFullPage:m},Symbol.toStringTag,{value:"Module"}));export{m as S,p as _};
1
+ import{j as c}from"./markdown-C9tbsVHX.js";import{b as o}from"./react-nrLBr15I.js";import{S as l}from"./ScenarioDataPanel-DHAHyraq.js";function m({slug:t}){const[r,i]=o.useState(void 0);return o.useEffect(()=>{let n=!1;return fetch(`/api/scenarios/${encodeURIComponent(t)}`).then(e=>e.ok?e.json():null).then(e=>{if(n||!e)return;const a=typeof e=="object"&&e!==null&&"name"in e?String(e.name):void 0;i(a),a&&(document.title=`${a} · data`)}).catch(()=>{}),()=>{n=!0}},[t]),c.jsx(l,{slug:t,scenarioName:r,variant:"fullPage"})}const p=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelFullPage:m},Symbol.toStringTag,{value:"Module"}));export{m as S,p as _};