@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.
- package/npm/cloud.js +16 -3
- package/npm/fleet-auth-account.js +61 -0
- package/npm/fleet-auth.js +69 -1
- package/npm/fleet-public-url.js +81 -12
- package/npm/fleet-reconcile.js +46 -11
- package/npm/group-bounded-spawn.js +111 -0
- package/npm/launch-config.js +90 -21
- package/npm/orphan-ssh-reaper.js +81 -0
- package/npm/scenario-playwright.js +107 -6
- package/package.json +5 -5
- package/ui/dist/assets/{ContainerInspector-C7I9wctz.js → ContainerInspector-DiN91foX.js} +1 -1
- package/ui/dist/assets/{EditorShell-CE8iG_EM.css → EditorShell-BEIdHnHd.css} +1 -1
- package/ui/dist/assets/{EditorShell-9aYMeOdZ.js → EditorShell-CPV5vhjo.js} +70 -70
- package/ui/dist/assets/ScenarioDataPanel-DHAHyraq.js +18 -0
- package/ui/dist/assets/{ScenarioDataPanelFullPage-DT0TZC4M.js → ScenarioDataPanelFullPage-CHIWip3n.js} +1 -1
- package/ui/dist/assets/ScenarioRenderer-D9a91iwS.js +21 -0
- package/ui/dist/assets/{index-BRoAenc1.css → index--cE0hUJw.css} +1 -1
- package/ui/dist/assets/{index-iMR5siiG.js → index-sW8wcg7v.js} +2 -2
- package/ui/dist/index.html +2 -2
- package/ui/dist/assets/ScenarioDataPanel-CLwkrex0.js +0 -18
- package/ui/dist/assets/ScenarioRenderer-Bsarhcrl.js +0 -21
package/ui/dist/index.html
CHANGED
|
@@ -5,10 +5,10 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>CodeYam</title>
|
|
7
7
|
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
|
|
8
|
-
<script type="module" crossorigin src="/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-sW8wcg7v.js"></script>
|
|
9
9
|
<link rel="modulepreload" crossorigin href="/assets/react-nrLBr15I.js">
|
|
10
10
|
<link rel="modulepreload" crossorigin href="/assets/markdown-C9tbsVHX.js">
|
|
11
|
-
<link rel="stylesheet" crossorigin href="/assets/index
|
|
11
|
+
<link rel="stylesheet" crossorigin href="/assets/index--cE0hUJw.css">
|
|
12
12
|
</head>
|
|
13
13
|
<body>
|
|
14
14
|
<div id="root"></div>
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import{j as n}from"./markdown-C9tbsVHX.js";import{b as c}from"./react-nrLBr15I.js";import{d as Hr,a as yt,u as vt,C as ue,c as Ur}from"./useServerIdentity-CVuHTzjg.js";import{u as Yr}from"./useEvents-S3Qk1Y_d.js";import{r as Wr,a as Vr}from"./xterm--24IGk-x.js";import{l as H,j as Xr}from"./index-iMR5siiG.js";function le({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 Rs=Object.freeze(Object.defineProperty({__proto__:null,RecoveryActions:le},Symbol.toStringTag,{value:"Module"})),Ve="claude";function Jr(e){return e==="claude"}function fe(e){switch(e){case"codex":return"Codex";case"gemini":return"Gemini";case"opencode":return"OpenCode";default:return"Claude"}}const $e={state:"unknown",provider:Ve,credsPresent:!0,cliInstalled:!0,cliRunnable:null,cliFailure:null,scannedDirs:[],reason:null,expiresAt:null,probeInFlight:!1,probeAttempts:0,backendFieldAbsent:!1};function qr(e){if(e==null)return{...$e,backendFieldAbsent:!0};if(typeof e!="object")return $e;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:Ve,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 Gr=1e3;function Qr(){const[e,t]=c.useState($e),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(qr(o.providerAuth))}catch{}},[]);return c.useEffect(()=>{a()},[a]),c.useEffect(()=>{if(e.state!=="unknown")return;const s=window.setInterval(()=>{r.current==="unknown"&&a()},Gr);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 Zr=Wr(),en=Vr();const tn=3e3;function _t(){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??Ve,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,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()},tn);return()=>clearInterval(u)},[l]),{config:e,apps:(e==null?void 0:e.apps)??[],loading:r,error:s,refetch:l}}function rn(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 nn=20,an=1;function sn(e,t){const r=t===an?e:e/nn;return Math.trunc(r)||Math.sign(r)}function on(){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 ln(e,t,r={}){const a=r.isMac??on(),s=r.onError,o=r.onCopy;let i=null;async function l(b){if(!b)return!1;let g=!1;try{g=await Hr(b)}catch(y){return s==null||s(tt("copy",y)),!1}if(g){try{e.clearSelection()}catch{}o==null||o()}else s==null||s(dn("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(tt("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",_=Ae("Copy",j,!y,()=>{l(y),h()}),k=Ae("Paste",v,!1,()=>{f(),h()}),C=Ae("Select All","",!1,()=>{try{e.selectAll()}catch{}const N=e.hasSelection()?e.getSelection():"";l(N),h()});p.appendChild(_),p.appendChild(k),p.appendChild(C),document.body.appendChild(p),cn(p,b,g);const O=N=>{p.contains(N.target)||h()},I=N=>{N.key==="Escape"&&(N.preventDefault(),h())};document.addEventListener("mousedown",O,!0),document.addEventListener("keydown",I,!0),i={root:p,onDocumentClick:O,onKeyDown:I}}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 Ae(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 cn(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 tt(e,t){const r=t instanceof Error?t.message:String(t);return`Clipboard ${e} failed: ${r}`}function dn(e){return`Clipboard ${e} blocked by the browser.`}function un(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 xe=new Set(["│","┃","║","|"]);function fn(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&&xe.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&&xe.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(!xe.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(!xe.has(b))break;d=m}}return{topRow:h,bottomRow:d,leftBorderCol:f,rightBorderCol:x}}function pn(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 hn=200;function mn(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=fn(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,k=p.rightBorderCol-1,C=$=>pn(o,$,_,k),O=o.cursorY<p.topRow||o.cursorY>p.bottomRow,I=O?p.bottomRow:o.cursorY,N=O?k:o.cursorX,D=m!==I;let E=null;if(D&&(E=C(m),E===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 P=d,T=!1;if(D&&E!==null){const $=Math.max(_,E);d>$&&(P=$,T=!0)}if(m===I&&P===N)return i({targetRow:m,targetCol:P,originalTargetCol:d,snapped:T,box:p,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const S=un(p,I,N,m,P,C);if(S===null)return i({targetRow:m,targetCol:P,originalTargetCol:d,snapped:T,box:p,rejected:"unreadable-row",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(S===0)return i({targetRow:m,targetCol:P,originalTargetCol:d,snapped:T,box:p,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(Math.abs(S)>hn)return i({targetRow:m,targetCol:P,originalTargetCol:d,snapped:T,box:p,rejected:"emit-cap",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const R=S<0?y.repeat(-S):g.repeat(S);return i({targetRow:m,targetCol:P,originalTargetCol:d,snapped:T,box:p,rejected:null,emittedDirection:S<0?"left":"right",emittedByteCount:R.length,predictedCursorY:m,predictedCursorX:P}),R}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 rt=1;function bn(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>rt||v>rt){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 I;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"&&((I=window.localStorage)==null?void 0:I.getItem("codeyam.terminalClickDebug"))==="1";if(_)try{const N=e.buffer.active,D=N.cursorY,E={};for(let P=-2;P<=2;P++){const T=D+P,S=N.getLine(N.baseY+T);if(!S)continue;const R=[];for(let $=0;$<e.cols;$++){const U=S.getCell($);R.push(U?U.getChars():"")}E[`row${T}`]=R.join("|")}console.log("[click-cursor] buffer dump",{cursorY:D,cursorX:N.cursorX,viewportY:N.viewportY,baseY:N.baseY,rows:E})}catch{}let k=null;const C=N=>{k=N,_&&console.log("[click-cursor] result",N)},O=mn({click:{clientX:y.clientX,clientY:y.clientY},terminal:e,cellSurface:u,debug:C});if(O){if(k){const N=k,D=N.box!==null&&N.targetRow!==N.cursorY;if(D&&x){_&&console.log("[click-cursor] suppressed by verification-disabled");return}D&&N.predictedCursorY!==null&&N.predictedCursorX!==null&&(h={y:N.predictedCursorY,x:N.predictedCursorX})}r(O)}}return u.addEventListener("mousedown",b),u.addEventListener("mouseup",g),()=>{u.removeEventListener("mousedown",b),u.removeEventListener("mouseup",g),d==null||d.dispose()}}const nt=20*1024*1024,xn=3e4,gn=3e3;function yn(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 vn(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`drop-${Date.now()}-${Math.random().toString(36).slice(2)}`}function _n(e){return/^[A-Za-z0-9._/\-]+$/.test(e)?e:`"${e.replace(/(["\\$`])/g,"\\$1")}"`}function jt(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 jn(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 wn(e,t){function r(a){const s=jt(a.clipboardData);s.length!==0&&(a.preventDefault(),a.stopPropagation(),t(s))}return e.addEventListener("paste",r,!0),()=>e.removeEventListener("paste",r,!0)}function Sn(){window.focus()}function kn(e,t){Sn(),e==null||e.focus({preventScroll:!0}),t()}function Cn({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),gn);return()=>window.clearTimeout(v)},[s]);const u=c.useCallback(v=>{o(v)},[]),f=c.useCallback((v,_)=>{const k=i.current.get(v);k&&(i.current.delete(v),k.resolve(_))},[]),x=c.useCallback((v,_)=>{const k=i.current.get(v);k&&(i.current.delete(v),k.reject(_))},[]),h=c.useCallback(v=>{for(const[,_]of i.current)_.reject(v);i.current.clear()},[]),d=c.useCallback(async v=>{if(v.size>nt)throw new Error(`File too large (max ${nt/(1024*1024)} MB)`);const _=e.current;if(!_||_.readyState!==WebSocket.OPEN)throw new Error("Not connected — try again in a moment");const k=await yn(v),C=vn(),O=new Promise((I,N)=>{const D=window.setTimeout(()=>{i.current.delete(C)&&N(new Error("Timed out waiting for save to complete"))},xn);i.current.set(C,{resolve:E=>{window.clearTimeout(D),I(E)},reject:E=>{window.clearTimeout(D),N(new Error(E))}})});return _.send(JSON.stringify({type:"drop",id:C,name:v.name||"unnamed",mime:v.type||"application/octet-stream",data:k})),O},[e]),m=c.useCallback(async v=>{if(v.length===0)return;const _=[];for(const k of v)try{_.push(await d(k))}catch(C){const O=C instanceof Error?C.message:String(C);u(`Attach failed: ${O}`);return}t(_.map(_n).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),jn(v.dataTransfer)){u("Folder drops are not supported — drag individual files instead");return}const _=Array.from(v.dataTransfer.files).filter(k=>k.size>0);await m(_)},[m,u]),j=c.useCallback(async v=>{const _=jt(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 wt(){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 Ds=Object.freeze(Object.defineProperty({__proto__:null,TerminalDropOverlay:wt},Symbol.toStringTag,{value:"Module"}));function St({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 Is=Object.freeze(Object.defineProperty({__proto__:null,TerminalDropToast:St},Symbol.toStringTag,{value:"Module"}));async function kt(e=1500){try{return(await fetch("/api/health",{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}function Nn(e,t){let r=!1,a=null;async function s(){if(!r){if(await kt(1500)){r||t();return}r||(a=setTimeout(s,e))}}return a=setTimeout(s,e),()=>{r=!0,a&&(clearTimeout(a),a=null)}}const Tn="The editor server closed the terminal connection with no further detail.";function En(e){if(e&&typeof e=="object"&&"message"in e){const t=e.message;if(typeof t=="string"&&t.length>0)return t}return Tn}let Ct=!1;function Me(e){Ct=e}function On(){return Ct}const An=800,Mn=5e3;function Pn(e){window.dispatchEvent(new CustomEvent("miniagent-send-input",{detail:e}))}function Rn(e,t="plan"){return new Promise(r=>{let a=!1;const s=()=>{a||(a=!0,window.removeEventListener("miniagent-agent-idle",o),clearTimeout(i),r())},o=l=>{const u=l.detail;(u==null?void 0:u.chatName)===t&&s()},i=setTimeout(s,e);window.addEventListener("miniagent-agent-idle",o)})}function Dn(e){return On()?Promise.resolve():new Promise(t=>{let r=!1;const a=()=>{r||(r=!0,window.removeEventListener("miniagent-ws-open",a),clearTimeout(s),t())},s=setTimeout(a,e);window.addEventListener("miniagent-ws-open",a,{once:!0})})}async function In(e,t){await Dn(Mn),await Rn(An,t),Pn(`${e}\r`)}function Nt(){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 Ls=Object.freeze(Object.defineProperty({__proto__:null,TerminalConnectingHint:Nt},Symbol.toStringTag,{value:"Module"}));function Tt({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 $s=Object.freeze(Object.defineProperty({__proto__:null,TerminalReconnectingBanner:Tt},Symbol.toStringTag,{value:"Module"})),Et="Connected to the editor server at ";function Ot(e){const t=e===null?null:e?"in the cloud container":"on this machine";return t?`, running ${t}.`:"."}function Ln(e,t){return e===null?null:`${Et}${e}${Ot(t)}`}function $n({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 Fe(e){return typeof e=="string"?e:typeof e=="number"?String(e):Array.isArray(e)?e.map(Fe).join(""):""}const Fn={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 At({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(yt,{variant:"subtle",text:r,label:a,ariaLabel:`Copy this report: ${e}`})]})}const Fs=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeHeader:At},Symbol.toStringTag,{value:"Module"}));function Mt({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 Bs=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeNextAction:Mt},Symbol.toStringTag,{value:"Module"}));function Pt({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 zs=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeDiagnostics:Pt},Symbol.toStringTag,{value:"Module"}));function Rt({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 Ks=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeActions:Rt},Symbol.toStringTag,{value:"Module"}));function G({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}=vt(),g=Fn[i],y=b?Ln(d,m):null,p=$n({headline:e,explanation:a??Fe(t),nextAction:s??Fe(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(At,{headline:e,palette:g,report:p,copyLabel:f}),n.jsx("p",{style:{color:"var(--text-dim)"},children:t}),n.jsx(Mt,{nextAction:r,palette:g}),o?n.jsx(Pt,{diagnostics:o,testId:x?`${x}-diagnostics`:void 0}):null,n.jsx(Rt,{actions:l,palette:g,actionFeedback:u}),d!==null&&b?n.jsxs("p",{className:"text-xs",style:{color:"var(--text-dim)"},children:[Et,n.jsx("code",{children:d}),Ot(m)]}):null]})}const Hs=Object.freeze(Object.defineProperty({__proto__:null,ErrorNotice:G},Symbol.toStringTag,{value:"Module"})),Bn=350;function se(e,t={}){const{minPendingMs:r=Bn}=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 Dt({onRefresh:e}){const{phase:t,attempts:r,retry:a}=se(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(G,{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 Us=Object.freeze(Object.defineProperty({__proto__:null,TerminalFailedBanner:Dt},Symbol.toStringTag,{value:"Module"}));function It({onReload:e}){const{phase:t,attempts:r,retry:a}=se(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(G,{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 Ys=Object.freeze(Object.defineProperty({__proto__:null,TerminalServerStoppedBanner:It},Symbol.toStringTag,{value:"Module"}));function Lt({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(yt,{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 Ws=Object.freeze(Object.defineProperty({__proto__:null,TerminalServerErrorBanner:Lt},Symbol.toStringTag,{value:"Module"}));function $t({onRefresh:e}){const{phase:t,attempts:r,retry:a}=se(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(G,{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 Vs=Object.freeze(Object.defineProperty({__proto__:null,TerminalEdgeUnreachableBanner:$t},Symbol.toStringTag,{value:"Module"}));function Ft({canRetry:e=!1,onRefresh:t}){const{phase:r,attempts:a,retry:s}=se(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(G,{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 Xs=Object.freeze(Object.defineProperty({__proto__:null,TerminalSessionStaleBanner:Ft},Symbol.toStringTag,{value:"Module"}));function zn(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 Bt({report:e,onRefresh:t}){const{phase:r,attempts:a,retry:s}=se(t),o=zn(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(G,{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 Js=Object.freeze(Object.defineProperty({__proto__:null,TerminalSessionDiedBanner:Bt},Symbol.toStringTag,{value:"Module"}));function zt({status:e,pulseKey:t,onRefresh:r}){return e.kind==="open"||e.kind==="ended"?null:e.kind==="connecting"?n.jsx(Nt,{}):e.kind==="reconnecting"?n.jsx(Tt,{attempt:e.attempt,maxAttempts:e.maxAttempts,pulseKey:t}):e.kind==="server-stopped"?n.jsx(It,{onReload:r}):e.kind==="server-error"?n.jsx(Lt,{message:e.message,onRefresh:r}):e.kind==="edge-unreachable"?n.jsx($t,{onRefresh:r}):e.kind==="session-died"?n.jsx(Bt,{report:e.report,onRefresh:r}):e.kind==="session-stale"?n.jsx(Ft,{canRetry:e.canRetry,onRefresh:r}):n.jsx(Dt,{onRefresh:r})}const qs=Object.freeze(Object.defineProperty({__proto__:null,TerminalDisconnectOverlay:zt},Symbol.toStringTag,{value:"Module"}));function Kt(){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 Gs=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchRetryingHint:Kt},Symbol.toStringTag,{value:"Module"}));function Ht({onRetry:e}){const{phase:t,attempts:r,retry:a}=se(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(G,{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 Qs=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchFailed:Ht},Symbol.toStringTag,{value:"Module"}));function Ut({status:e,onRetry:t}){return e==="retrying"?n.jsx(Kt,{}):e==="failed"?n.jsx(Ht,{onRetry:t}):null}const Zs=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchOverlay:Ut},Symbol.toStringTag,{value:"Module"})),Kn=1e3;let Be=0;function eo(){Be=Date.now()}function ze(){return Be===0?1/0:Date.now()-Be}function to(){return ze()<Kn}const Yt=5e3,at=6e4,Hn=50;function st(e,t=Yt){return e<t}function Un(e,t=Yt){return Math.max(Hn,t-e)}const oe=new Map;async function Yn(e,t,r,a){if(a!=null&&a.aborted)return null;if(!st(ze()))return e;const s=oe.get(t);if(s)return s.label=e,H("dispatch-rename-superseded",{caller:r,label:e}),null;const o={label:e};oe.set(t,o);let i=0;for(;;){if(a!=null&&a.aborted)return oe.delete(t),H("dispatch-rename-cancelled",{caller:r,label:o.label,waitedMs:i}),null;const l=ze();if(!st(l))break;const u=Un(l);if(i+u>at)return oe.delete(t),H("dispatch-rename-abandoned",{caller:r,label:o.label,msSinceKeystroke:l,waitedMs:i,capMs:at}),null;H("dispatch-rename-deferred",{caller:r,label:o.label,msSinceKeystroke:l,retryInMs:u,waitedMs:i}),await new Promise(f=>setTimeout(f,u)),i+=u}return oe.delete(t),o.label}const Wn=40;function Vn(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t&&t.slice(0,Wn).replace(/-+$/,"")||"session"}const ye=new Map;function Xe(e,t){const r=ye.get(e);if(!r){let a;try{a=t()}catch(s){return Promise.reject(s)}return a instanceof Promise?ot(e,a):Promise.resolve()}return ot(e,r.then(()=>t()))}function ot(e,t){const r=t.catch(()=>{});return ye.set(e,r),r.then(()=>{ye.get(e)===r&&ye.delete(e)}),t}let ae=0,re=[];function ro(){if(ae+=1,ae===1&&re.length>0){const e=re;re=[];for(const t of e)t()}}function no(){ae>0&&(ae-=1)}function Xn(){return ae>0}function Jn(e){return ae>0?Promise.resolve(!0):new Promise(t=>{let r=!1;const a=()=>{r||(r=!0,t(!0))};re.push(a),setTimeout(()=>{r||(r=!0,re=re.filter(s=>s!==a),t(!1))},e)})}const Se="build",it="miniagent",lt=3e3;function qn(e){return Xn()?e():Jn(lt).then(t=>{if(t)return e();console.warn(`[terminal] dropped programmatic injection: no terminal-send-input listener attached within ${lt}ms`)})}function Je(e){window.dispatchEvent(new CustomEvent("terminal-send-input",{detail:e}))}function ao(e){Xe(Se,()=>qn(()=>Je(e)))}const ve=50;function Gn(e,t=Je,r=Se){return Xe(r,()=>new Promise(a=>{t(e),setTimeout(()=>{t("\r"),a()},ve)}))}const Pe=3e3;function Qn(e){return e==="codex"?"codex":e==="gemini"?"gemini":e==="opencode"?"opencode":"claude"}function Wt(e,t){const r=Qn(e);return r==="claude"&&t?`${r} --permission-mode auto`:r}function Zn(e,t){return`'${e==="powershell"?t.replaceAll("'","''"):t.replaceAll("'","'\\''")}'`}function ea(e,t,r=!0,a="posix"){const s=Zn(a,t);return e==="opencode"?`opencode${r?" --auto":""} --prompt ${s}\r`:`${Wt(e,r)} ${s}\r`}async function ta(e,t=Je,r=Se,a="dispatch-rename-launch",s){const o=await Yn(Vn(e),r,a,s);o!==null&&await Gn(`/rename ${o}`,t,r)}function ra(e,t,r,a=Se){H("dispatch-rename",{phase:"queued",caller:t,label:e,delayMs:Pe}),setTimeout(()=>{H("dispatch-rename",{phase:"fired",caller:t,label:e,delayMs:Pe}),ta(e,r,a,t)},Pe)}const qe=".codeyam/tmp/inline-prompt.md";function na(e){return e.split(`
|
|
8
|
-
`).map(t=>t.startsWith("'@")?` ${t}`:t).join(`
|
|
9
|
-
`)}function aa(e){return`mkdir -p .codeyam/tmp && cat > ${qe} << 'INLINE_PROMPT_EOF'
|
|
10
|
-
${e}
|
|
11
|
-
INLINE_PROMPT_EOF\r`}function sa(e){return`New-Item -ItemType Directory -Force -Path .codeyam/tmp | Out-Null; @'
|
|
12
|
-
${na(e)}
|
|
13
|
-
'@ | Set-Content -LiteralPath ${qe} -Encoding utf8\r`}function oa(e,t,r=!0,a="posix"){const s=Wt(e,r),o=a==="powershell"?sa(t):aa(t),i=`${s} "Read the file at '${qe}' for your instructions."\r`;return[o,i]}function ia({attempt:e,sawOutput:t}){return t?e===1?"extend":"confirm":e===1?"retry":"fail"}function la({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 ca=350,da=4e3,ct=8e3,ua=500,V={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 fa(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),k=c.useRef(0);c.useEffect(()=>{const T=()=>{_.current+=1};return window.addEventListener("miniagent-output",T),()=>window.removeEventListener("miniagent-output",T)},[]);const C=c.useCallback((T,S)=>{const R=h.current,$=d.current;return Xe(it,()=>{const U=y.current??"posix";if(R){const L=ea(b.current,R,g.current,U),Q=Re(L);return T(Q),new Promise(B=>{setTimeout(()=>{S()&&T("\r"),B()},ve)})}const[z,W]=oa(b.current,$??"",g.current,U),X=Re(z),Y=Re(W);return T(X),new Promise(L=>{setTimeout(()=>{if(!S())return L();T("\r"),setTimeout(()=>{if(!S())return L();T(Y),setTimeout(()=>{S()&&T("\r"),L()},ve)},ua)},ve)})})},[]),O=c.useCallback(()=>{const T=++p.current,S=Date.now();v.current=S,k.current=_.current,f("armed"),H(V.armed,{provider:b.current,slashCommand:h.current,chatName:m.current,hasPrompt:typeof d.current=="string"});function R(){return p.current===T}function $(z){R()&&(f(z===1?"firing":"retrying"),H(z===1?V.fired:V.relaunch,{provider:b.current,slashCommand:h.current,chatName:m.current,attempt:z,elapsedMs:Date.now()-S}),C(x.current,R).then(()=>{R()&&(k.current=_.current)}),!j.current&&Jr(b.current)&&(j.current=!0,ra(m.current,"mini-agent-chat",W=>x.current(W),it)),setTimeout(()=>U(z),ct))}function U(z){if(!R())return;const W=_.current>k.current;switch(ia({attempt:z,sawOutput:W})){case"retry":$(2);return;case"extend":H(V.relaunch,{provider:b.current,slashCommand:h.current,attempt:2,sawOutput:!0,resent:!1,elapsedMs:Date.now()-S}),setTimeout(()=>U(2),ct);return;case"confirm":f("confirmed"),H(V.confirmed,{provider:b.current,slashCommand:h.current,reason:"output-without-banner",sawOutput:!0,elapsedMs:Date.now()-S});return;case"fail":f("failed"),H(V.failed,{provider:b.current,slashCommand:h.current,reason:"banner-timeout",sawOutput:!1,elapsedMs:Date.now()-S})}}la({idleMs:ca,ceilingMs:da}).then(()=>{R()&&$(1)})},[C]),I=c.useCallback(()=>{j.current=!1,O()},[O]),N=c.useCallback(()=>{O()},[O]),D=c.useCallback(()=>{p.current!==0&&(p.current++,f("confirmed"),H(V.confirmed,{elapsedMs:Date.now()-v.current}))},[]),E=c.useCallback(()=>{p.current!==0&&(p.current++,f("failed"),H(V.failed,{reason:"startup-failed",elapsedMs:Date.now()-v.current}))},[]),P=c.useCallback(()=>{p.current++,f("confirmed"),H(V.reattached,{provider:b.current,chatName:m.current})},[]);return c.useEffect(()=>()=>{p.current++},[]),{status:u,arm:I,retry:N,onBannerReady:D,onStartupFailed:E,onReattached:P}}function Re(e){return e.endsWith("\r")?e.slice(0,-1):e}const ke=c.createContext({registerSender:()=>{},setReady:()=>{},sendToAgent:()=>!1,agentReady:!1});function pa({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(ke.Provider,{value:l,children:e})}function ha(){const{sendToAgent:e,agentReady:t}=c.useContext(ke);return{sendToAgent:e,agentReady:t}}function ma(e,t){const{registerSender:r,setReady:a}=c.useContext(ke);c.useEffect(()=>(r(e),()=>r(null)),[r,e]),c.useEffect(()=>(a(t),()=>a(!1)),[a,t])}function Vt(){const{registerSender:e,setReady:t}=c.useContext(ke);return{registerSender:e,setReady:t}}const so=Object.freeze(Object.defineProperty({__proto__:null,AgentInputProvider:pa,useAgentInput:ha,useAgentInputChannel:Vt,useRegisterAgentInput:ma},Symbol.toStringTag,{value:"Module"})),Xt=c.createContext({openPicker:()=>{}});function ba({openPicker:e,children:t}){const r=c.useMemo(()=>({openPicker:e}),[e]);return n.jsx(Xt.Provider,{value:r,children:t})}function Jt(){return c.useContext(Xt)}const oo=Object.freeze(Object.defineProperty({__proto__:null,FilePickerProvider:ba,useFilePicker:Jt},Symbol.toStringTag,{value:"Module"}));function qt({className:e=""}){const{openPicker:t}=Jt();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 io=Object.freeze(Object.defineProperty({__proto__:null,AttachFileButton:qt},Symbol.toStringTag,{value:"Module"})),dt=15;function Gt({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}=_t(),x=(f==null?void 0:f.provider)??"claude",[h,d]=c.useState({kind:"connecting"}),[m,b]=c.useState(0),g=c.useCallback(T=>{const S=l.current;(S==null?void 0:S.readyState)===WebSocket.OPEN&&S.send(JSON.stringify({type:"input",data:T}))},[]),y=Cn({wsRef:l,insertInput:g}),p=c.useRef(y);p.current=y;const{registerSender:j,setReady:v}=Vt(),_=c.useCallback(T=>{var S;return((S=l.current)==null?void 0:S.readyState)===WebSocket.OPEN?(l.current.send(JSON.stringify({type:"input",data:T})),!0):!1},[]),k=h.kind==="open";c.useEffect(()=>(k&&j(_),()=>j(null)),[j,_,k]),c.useEffect(()=>(v(k),()=>v(!1)),[v,k]);const C=c.useCallback(()=>{var T;((T=l.current)==null?void 0:T.readyState)===WebSocket.OPEN&&(j(_),v(!0)),kn(i.current,()=>{var S;return(S=u.current)==null?void 0:S.focus()})},[j,v,_]),{shellDialect:O}=vt(),I=fa({provider:x,slashCommand:r,prompt:t,chatName:e,sendInput:g,permissionModeAuto:(f==null?void 0:f.claudePermissionModeAuto)??!0,shellDialect:O}),N=c.useRef(I);c.useEffect(()=>{N.current=I});const D=c.useRef(e);c.useEffect(()=>{D.current=e});const E=c.useRef(a),P=c.useRef(r);return c.useEffect(()=>{E.current=a,P.current=r}),c.useEffect(()=>{const T=i.current;if(!T)return;const S=new Zr.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}),R=new en.FitAddon;S.loadAddon(R),S.open(T);const $=ln(S,T,{onError:w=>console.warn("[MiniAgentChat]",w)}),U=bn(S,{sendInput:w=>{const A=l.current;(A==null?void 0:A.readyState)===WebSocket.OPEN&&A.send(JSON.stringify({type:"input",data:w}))}}),z=wn(T,w=>{p.current.handleImageFiles(w)});requestAnimationFrame(()=>{try{R.fit()}catch{}}),u.current=S;const W={current:"inline"},X={current:null},Y={current:!1},L={current:!1},Q={current:!1};let B=0,K=null;function Z(){d({kind:"connecting"});const w=rn({mode:W.current,sessionId:X.current??void 0,chatKey:e,cols:S.cols,rows:S.rows}),A=new WebSocket(w);A.binaryType="arraybuffer",l.current=A,A.onopen=()=>{B=0,d({kind:"open"}),Me(!0),window.dispatchEvent(new CustomEvent("miniagent-ws-open")),A.send(JSON.stringify({type:"resize",cols:S.cols,rows:S.rows}))},A.onmessage=F=>{if(F.data instanceof ArrayBuffer){S.write(new Uint8Array(F.data)),window.dispatchEvent(new CustomEvent("miniagent-output"));return}try{const M=JSON.parse(F.data);if(M.type==="error"){L.current=!0,d({kind:"server-error",message:En(M)});return}if(M.type==="drop-complete"){p.current.resolveDrop(M.id,M.path);return}if(M.type==="drop-error"){p.current.rejectDrop(M.id,M.message);return}if(M.type==="session-id"){if(M.sessionId&&(X.current=M.sessionId,W.current="resume"),M.reattached===!0){Y.current=!0,N.current.onReattached();const be=E.current,et=P.current;be&&et&&!Q.current&&(Q.current=!0,In(et,D.current));return}Y.current||(Y.current=!0,N.current.arm());return}if(M.type==="agent-idle"||M.type==="claude-idle"||M.type==="agent-blocked"){window.dispatchEvent(new CustomEvent("miniagent-agent-idle",{detail:{chatName:D.current}}));return}if(M.type==="agent-active"||M.type==="claude-active"){window.dispatchEvent(new CustomEvent("miniagent-agent-active",{detail:{chatName:D.current}}));return}if(M.type==="agent-banner-ready"){N.current.onBannerReady();return}if(M.type==="agent-auth-required"){window.dispatchEvent(new CustomEvent("agent-auth-required"));return}if(M.type==="startup-failed"){N.current.onStartupFailed();return}}catch{S.write(F.data),window.dispatchEvent(new CustomEvent("miniagent-output"))}},A.onerror=()=>{},A.onclose=async()=>{if(Me(!1),p.current.cancelAllDrops("Not connected"),L.current){d(M=>M.kind==="server-error"?M:{kind:"ended"});return}const F=await kt();if(!L.current){if(!F){d({kind:"server-stopped"}),K==null||K(),K=Nn(2e3,()=>{L.current||window.location.reload()});return}if(B<dt){const M=B<4?1e3*Math.pow(2,B):1e4;B++,d({kind:"reconnecting",attempt:B,maxAttempts:dt}),setTimeout(()=>{L.current||Z()},M)}else d({kind:"failed"})}}}try{R.fit()}catch{}Z(),S.onData(w=>{const A=l.current;(A==null?void 0:A.readyState)===WebSocket.OPEN?A.send(JSON.stringify({type:"input",data:w})):b(F=>F+1)});const he=new ResizeObserver(()=>{try{R.fit();const w=l.current;(w==null?void 0:w.readyState)===WebSocket.OPEN&&w.send(JSON.stringify({type:"resize",cols:S.cols,rows:S.rows}))}catch{}});he.observe(T);function me(w){const A=u.current;if(!A)return;const F=w.target;if(F!=null&&F.closest(".xterm-viewport")||A.buffer.active.length<=A.rows)return;const be=sn(w.deltaY,w.deltaMode);be!==0&&(A.scrollLines(be),w.preventDefault(),w.stopPropagation())}T.addEventListener("wheel",me,{passive:!1});function ee(){var w;(w=u.current)==null||w.focus()}window.addEventListener("terminal-focus",ee);function te(w){const A=w.detail,F=l.current;typeof A=="string"&&(F==null?void 0:F.readyState)===WebSocket.OPEN&&F.send(JSON.stringify({type:"input",data:A}))}return window.addEventListener("miniagent-send-input",te),()=>{var A;L.current=!0,Me(!1),K==null||K(),K=null,window.removeEventListener("terminal-focus",ee),window.removeEventListener("miniagent-send-input",te),T.removeEventListener("wheel",me),he.disconnect(),$(),U(),z();const w=l.current;(w==null?void 0:w.readyState)===WebSocket.OPEN&&w.close(),(A=u.current)==null||A.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:fe(x)}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(qt,{}),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:C,onClick:C,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(zt,{status:h,pulseKey:m,onRefresh:()=>window.location.reload()}),n.jsx(Ut,{status:I.status,onRetry:I.retry}),y.dragActive&&n.jsx(wt,{}),y.errorToast&&n.jsx(St,{message:y.errorToast})]})]})}const lo=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentChat:Gt},Symbol.toStringTag,{value:"Module"}));function Qt(e){return e>=500?"transient":"rejected"}function Zt({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=fe(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(Qt(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 co=Object.freeze(Object.defineProperty({__proto__:null,ApiKeyFlow:Zt,classifyApiKeySaveFailure:Qt},Symbol.toStringTag,{value:"Module"})),xa=500,ga=75e3,ut=`
|
|
14
|
-
|
|
15
|
-
--- transcript tail ---
|
|
16
|
-
`;function er(e){const t=e.indexOf(ut);return t===-1?{headline:e}:{headline:e.slice(0,t),tail:e.slice(t+ut.length)}}function tr({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 C=await fetch("/api/auth/status");if(!C.ok)return;const O=await C.json();r(O),O.state==="authenticated"&&!m.current&&(m.current=!0,b.current())}catch{}},[]),y=c.useCallback(async()=>{m.current=!1,x(!1),r({state:"starting"});try{const C=await fetch("/api/auth/start",{method:"POST"});if(!C.ok){const O=await C.json().catch(()=>({}));r({state:"failed",error:O.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 C=window.setInterval(()=>void g(),xa);return()=>window.clearInterval(C)},[g]);const p=t.state!=="failed"&&t.state!=="idle"&&t.state!=="authenticated"&&t.state!=="url-ready";c.useEffect(()=>{if(!p){x(!1);return}const C=window.setTimeout(()=>x(!0),ga);return()=>window.clearTimeout(C)},[p]);const j=c.useCallback(async()=>{if(a.trim()){i(!0);try{const C=await fetch("/api/auth/code",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:a.trim()})});if(C.ok)s("");else{const O=await C.json().catch(()=>({}));r({state:"failed",error:O.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]),k=c.useCallback(()=>{var C;t.url&&((C=navigator.clipboard)==null||C.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(le,{onRetry:()=>void v(),onRecheck:()=>void _(),rechecking:h,retryTestId:"claude-oauth-timeout-retry",recheckTestId:"claude-oauth-timeout-recheck"})]});if(t.state==="failed"){const{headline:C,tail:O}=er(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:C}),O&&n.jsxs("details",{"data-testid":"claude-oauth-failed-transcript",children:[n.jsx("summary",{className:"cursor-pointer text-xs text-[#9CA3AF]",children:"Show login transcript"}),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:O})]}),n.jsx(le,{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(le,{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(le,{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:k,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:C=>s(C.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 uo=Object.freeze(Object.defineProperty({__proto__:null,ClaudeOAuthFlow:tr,splitTranscriptTail:er},Symbol.toStringTag,{value:"Module"}));function rr({provider:e,onAuthenticated:t,onClose:r}){const a=fe(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(tr,{onAuthenticated:t}):n.jsx(Zt,{provider:e,onAuthenticated:t})]})})}const fo=Object.freeze(Object.defineProperty({__proto__:null,ProviderAuthModal:rr},Symbol.toStringTag,{value:"Module"}));function ya(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 nr({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=fe(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 ${ya(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(rr,{provider:e,onAuthenticated:d,onClose:()=>u(!1)}):null]})}const po=Object.freeze(Object.defineProperty({__proto__:null,ProviderAuthenticateCta:nr},Symbol.toStringTag,{value:"Module"}));let De=!1;function ar(e){const{state:t,provider:r,credsPresent:a,reason:s,expiresAt:o,refresh:i}=Qr(),[l]=c.useState(()=>De);return c.useEffect(()=>{t==="authenticated"?De=!0:t==="needs-login"&&(De=!1)},[t]),t==="needs-login"?n.jsx(nr,{provider:r,credsPresent:a,reason:s,expiresAt:o,onAuthenticated:()=>void i(),onAuthorized:()=>{}}):t==="authenticated"||l?n.jsx(Gt,{...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 ho=Object.freeze(Object.defineProperty({__proto__:null,GatedAgentChat:ar},Symbol.toStringTag,{value:"Module"})),va=500,de=new Set;let ie=null,_e=null;async function Ke(){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(de.size!==0){_e=e;for(const t of[...de])t(e)}}function _a(e){return de.add(e),_e&&e(_e),ie===null&&(ie=setInterval(()=>{Ke()},va),Ke()),()=>{de.delete(e),de.size===0&&ie!==null&&(clearInterval(ie),ie=null,_e=null)}}function ja(){Ke()}const Ie=4e3;function ft(e){let t;try{t=JSON.stringify(e,null,2)}catch{t=String(e)}return t.length>Ie?`${t.slice(0,Ie)}
|
|
17
|
-
… (truncated, ${t.length-Ie} more chars)`:t}function wa({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(ft(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(ft(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 He=new Set;let ge=null;const Sa=150;function mo(e){return He.add(e),()=>{He.delete(e)}}function ne(){ge&&clearTimeout(ge),ge=setTimeout(()=>{ge=null;for(const e of He)e()},Sa)}const Ue=new Set;function bo(e){for(const t of Ue)t(e)}function ka(e){return Ue.add(e),()=>{Ue.delete(e)}}function Ca({onSelect:e,onFocus:t}){c.useEffect(()=>ka(({routeKey:r,jsonPath:a})=>{e(r),t(a)}),[e,t])}async function Ce(e){try{const t=await e.json();if(t.error)return t.error}catch{}return`Request failed (${e.status})`}async function Na(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 pt(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 Ce(a))}async function Ta(e,t){const r=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t)}`,a=await fetch(r,{method:"DELETE"});if(!a.ok)throw new Error(await Ce(a))}async function Ea(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 Ce(a))}function J(e){return e.kind==="shared"?`shared:${e.slug}`:e.kind}async function Oa(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 Aa(e,t,r){const a=new URLSearchParams({scenarioSlug:e,routeKey:t,scope:J(r)}),s=await fetch(`/api/mocks/save-scope-impact?${a.toString()}`);if(!s.ok)throw new Error(await Ce(s));return(await s.json()).impactedScenarios??[]}function Ma(){const[e,t]=c.useState(null),[r,a]=c.useState(null),s=c.useRef(null);return c.useEffect(()=>_a(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}`);ja()}catch(i){a(i instanceof Error?i.message:String(i))}}}}function Pa(e){const[t,r]=c.useState([]),[a,s]=c.useState(null),[o,i]=c.useState(!1),[l,u]=c.useState(null),{events:f}=Yr(),{status:x}=Ma(),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 Na(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 pt(e,p),await d())},[e,d]),b=c.useCallback(async p=>{e&&(p.scope.kind==="scenario"?await pt(e,{routeKey:p.routeKey,status:p.status,body:p.body,headers:p.headers}):await Oa({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 Ta(e,p),await d())},[e,d]),y=c.useCallback(async p=>{e&&(await Ea(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 Ra(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 Da(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 Ia(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 La(e,t){return e.length>0?Object.keys(e[0]):t?t.map(r=>r.name):[]}function $a(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?Ia(t[0][o]):"text");return s}function Fa(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 Ba(e,t){const{_metadata:r,...a}=t,s=a.localStorage&&typeof a.localStorage=="object"&&!Array.isArray(a.localStorage)?Ra(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&&Da(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)||za(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 ht(e){return e==="null"?null:e==="true"?!0:e==="false"?!1:e===""?"":isNaN(Number(e))?e:Number(e)}function za(e){return Array.isArray(e)&&e.length>0&&typeof e[0]=="object"&&e[0]!==null}function Ka(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 Ha(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 Ua(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 Ya(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 Wa(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=Ba(Array.isArray(a)?a:[],s);r({data:o.data,tableTabs:o.tabs,scenarioOwnedDataKeys:Ua(o.data,o.tabs),shares:Ya(s),props:Ka(s),browserState:Ha(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 Ge(e,t=""){return`/api/scenarios/${encodeURIComponent(e)}/draft${t}`}async function Va(e){const t=await fetch(Ge(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 Xa(e){const t=await fetch(Ge(e,"/commit"),{method:"POST"});if(!t.ok)throw new Error(`Save failed (${t.status})`)}async function Ja(e){const t=await fetch(Ge(e),{method:"DELETE"});if(!t.ok)throw new Error(`Cancel failed (${t.status})`)}function qa({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 Va(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 Xa(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 Ja(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 Ga={scenario:"Scenario",shared:"Shared",default:"Defaults","catalog-only":"Observed only",passthrough:"Passthrough"},Qa={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 sr(e){return Ga[e]??e}function Za(e){return Qa[e]??null}const es={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 Qe({source:e}){const t=Za(e);return n.jsx("span",{className:`px-1.5 py-0.5 rounded border ${es[e]}`,title:t??`source: ${e}`,children:sr(e)})}const xo=Object.freeze(Object.defineProperty({__proto__:null,MockSourceBadge:Qe},Symbol.toStringTag,{value:"Module"}));function or({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 go=Object.freeze(Object.defineProperty({__proto__:null,SidebarGroupOverrideHeader:or},Symbol.toStringTag,{value:"Module"}));function ir({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 yo=Object.freeze(Object.defineProperty({__proto__:null,SidebarInheritedSection:ir},Symbol.toStringTag,{value:"Module"}));function lr({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 vo=Object.freeze(Object.defineProperty({__proto__:null,MockSharedSlugBadge:lr},Symbol.toStringTag,{value:"Module"})),ts={GET:"text-emerald-400",POST:"text-[#D7FF63]",PUT:"text-amber-400",PATCH:"text-purple-400",DELETE:"text-red-400"};function cr({entry:e,routeKey:t,active:r,onSelect:a}){const s=ts[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(lr,{slug:e.sharedSlug})]})}const _o=Object.freeze(Object.defineProperty({__proto__:null,SidebarMockEntryRow:cr},Symbol.toStringTag,{value:"Module"})),rs=["scenario","shared","default","catalog-only","passthrough"];function q(e){return`${e.method} ${e.pathPattern}`}function dr({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(je,{label:"Browser Environment",count:4,emptyHint:"",children:[n.jsx(ce,{label:"Cookies",active:(r==null?void 0:r.kind)==="browser"&&r.tab==="cookies",onSelect:()=>a({kind:"browser",tab:"cookies"})}),n.jsx(ce,{label:"Local Storage",active:(r==null?void 0:r.kind)==="browser"&&r.tab==="localStorage",onSelect:()=>a({kind:"browser",tab:"localStorage"})}),n.jsx(ce,{label:"Session Storage",active:(r==null?void 0:r.kind)==="browser"&&r.tab==="sessionStorage",onSelect:()=>a({kind:"browser",tab:"sessionStorage"})}),n.jsx(ce,{label:"Request Headers",active:(r==null?void 0:r.kind)==="browser"&&r.tab==="headers",onSelect:()=>a({kind:"browser",tab:"headers"})})]}),n.jsx(je,{label:"Seed & Local",count:e.length,emptyHint:"No seed or localStorage data",override:s?{scenarioCount:s.scenarioSeedCount,inheritedCount:s.inheritedSeedCount,renderInherited:()=>mt({tabs:s.inheritedSeedTabs,selection:r,onSelect:a})}:void 0,children:mt({tabs:e,selection:r,onSelect:a})}),n.jsx(je,{label:"Mock APIs",count:t.length,emptyHint:"No HTTP mocks registered",override:s?{scenarioCount:s.scenarioMockCount,inheritedCount:s.inheritedMockCount,renderInherited:()=>bt({entries:s.inheritedMockEntries,selection:r,onSelect:a})}:void 0,children:bt({entries:t,grouped:o,selection:r,onSelect:a})})]})}function mt({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 ce({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 bt({entries:e,grouped:t,selection:r,onSelect:a}){const s=t??ns(e);return rs.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:[sr(o),n.jsx(Qe,{source:o})]},`hdr-${o}`),...i.map(l=>{const u=q(l),f=(r==null?void 0:r.kind)==="mock"&&r.routeKey===u;return n.jsx(cr,{entry:l,routeKey:u,active:f,onSelect:()=>a({kind:"mock",routeKey:u})},u)})]})}function ns(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 je({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(or,{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(ir,{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 jo=Object.freeze(Object.defineProperty({__proto__:null,BrowserStateButton:ce,ScenarioDataPanelSidebar:dr,SidebarGroup:je,routeKeyFor:q},Symbol.toStringTag,{value:"Module"}));function as({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:q(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:q(t[0])})},[r,t,e,a,s])}function ur(){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 wo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelEmptyState:ur},Symbol.toStringTag,{value:"Module"}));function fr({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 So=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelCloseButton:fr},Symbol.toStringTag,{value:"Module"}));function pr({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 ko=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelEditChatButton:pr},Symbol.toStringTag,{value:"Module"})),Ye=new Set,We=new Set;let hr={isActive:!1,previewSlug:null};function ss(){for(const e of Ye)e()}function Co(e){return Ye.add(e),()=>{Ye.delete(e)}}function No(e){hr=e;for(const t of We)t(e)}function os(e){return We.add(e),()=>{We.delete(e)}}function xt(){return hr}function is(){const[e,t]=c.useState(()=>xt());return c.useEffect(()=>(t(xt()),os(t)),[]),e}function mr({panelSlug:e,scenarioState:t}){const r=is(),{isActive:a,previewSlug:s}=t??r;return s!==e?null:n.jsxs("button",{type:"button","aria-pressed":a,onClick:()=>ss(),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 To=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelInspectButton:mr},Symbol.toStringTag,{value:"Module"}));function br({variant:e,slug:t}){const r=()=>window.open(Xr(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 Eo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelOpenInNewButton:br},Symbol.toStringTag,{value:"Module"}));function xr(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 gr({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:xr(e)}),n.jsxs("div",{className:"flex items-center gap-2",children:[a&&n.jsx(ue,{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 Oo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDraftBar:gr,summarizeDraftDiff:xr},Symbol.toStringTag,{value:"Module"}));function yr({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=fe(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(pr,{variant:o,providerLabel:b,chatOpen:a,onToggleChat:s}),n.jsx(mr,{panelSlug:t}),n.jsx(br,{variant:o,slug:t}),i&&n.jsx(fr,{variant:o,onClose:i})]})]}),g&&d&&m&&n.jsx(gr,{diff:u??null,saving:f??!1,cancelling:x??!1,error:h??null,onSave:d,onCancel:m})]})}const Ao=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelHeader:yr},Symbol.toStringTag,{value:"Module"}));function ls(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 vr({body:e,onBodyChange:t}){const{copied:r,copy:a}=Ur();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 Mo=Object.freeze(Object.defineProperty({__proto__:null,JsonBodyActions:vr},Symbol.toStringTag,{value:"Module"}));function pe(e){return JSON.stringify(e)}function _r(e,t){return e?e instanceof Set?e.has(t):e.includes(t):!1}function cs(e){const t=new Set;function r(a,s){if(a!==null&&typeof a=="object")if(t.add(pe(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 ds(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 us(e){return e===null?"null":typeof e=="string"?`"${e}"`:String(e)}function fs(e){return e===null?"null":typeof e=="string"?e:String(e)}function ps(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 Ne(e){return JSON.parse(JSON.stringify(e))}function hs(e,t,r){if(t.length===0)return r;const a=Ne(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 Ze(e,t){if(t.length===0)return e;const r=Ne(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 ms(e,t){const r=Ne(e);let a=r;for(const s of t)a=a[s];return Array.isArray(a)&&a.push(null),r}function bs(e,t,r){const a=Ne(e);let s=a;for(const o of t)s=s[o];return s&&typeof s=="object"&&!Array.isArray(s)&&(s[r]=""),a}function xs(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 gs(e,t){c.useEffect(()=>{if(!e)return;const r=xs(e);r&&t(a=>{const s=new Set(a);for(let o=0;o<r.length;o++)s.add(pe(r.slice(0,o)));return s})},[e,t])}function Te({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 Po=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeNodeLine:Te},Symbol.toStringTag,{value:"Module"}));function jr(e){const{value:t,path:r,parentKey:a,expanded:s,onToggle:o,readOnly:i}=e,l=pe(r),u=_r(s,l),f=t.length>0;return n.jsxs("div",{children:[n.jsxs(Te,{collapsible:f,isOpen:u,onToggle:()=>o(l),parentKey:a,readOnly:i,onRemove:r.length>0?()=>e.onValueChange(Ze(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(Ee,{...e,key:h,value:x,path:[...r,h],parentKey:h,isLast:h===t.length-1})),!i&&n.jsx("button",{type:"button",onClick:()=>e.onValueChange(ms(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 Ro=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeArrayNode:jr},Symbol.toStringTag,{value:"Module"}));function wr({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 Do=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeAddKeyInput:wr},Symbol.toStringTag,{value:"Module"}));function Sr(e){const{value:t,path:r,parentKey:a,expanded:s,onToggle:o,readOnly:i,addingKeyAtPath:l,onStartAddKey:u,onStopAddKey:f}=e,x=pe(r),h=_r(s,x),d=Object.entries(t),m=d.length>0,b=l===x;return n.jsxs("div",{children:[n.jsxs(Te,{collapsible:m,isOpen:h,onToggle:()=>o(x),parentKey:a,readOnly:i,onRemove:r.length>0?()=>e.onValueChange(Ze(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(Ee,{...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(wr,{onSave:g=>{g.trim()&&e.onValueChange(bs(e.rootValue,r,g.trim())),f()},onCancel:f})]}),h&&n.jsx("div",{className:"text-[var(--text-dim)]",children:"}"})]})}const Io=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeObjectNode:Sr},Symbol.toStringTag,{value:"Module"}));function kr({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 Lo=Object.freeze(Object.defineProperty({__proto__:null,JsonTreePrimitiveEditor:kr},Symbol.toStringTag,{value:"Module"}));function Cr(e){const{value:t,path:r,parentKey:a,readOnly:s,editingPath:o,onStartEdit:i,onStopEdit:l}=e,u=pe(r),f=o===u;return n.jsx(Te,{collapsible:!1,isOpen:!1,parentKey:a,readOnly:s,onToggle:()=>{},onRemove:r.length>0?()=>e.onValueChange(Ze(e.rootValue,r)):null,children:f?n.jsx(kr,{initial:fs(t),onSave:x=>{const h=ps(x);e.onValueChange(hs(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 ${ds(t)} text-left font-mono`,title:s?void 0:"Click to edit",children:us(t)})})}const $o=Object.freeze(Object.defineProperty({__proto__:null,JsonTreePrimitiveNode:Cr},Symbol.toStringTag,{value:"Module"}));function Ee(e){const{value:t}=e;return Array.isArray(t)?n.jsx(jr,{...e,value:t}):t!==null&&typeof t=="object"?n.jsx(Sr,{...e,value:t}):n.jsx(Cr,{...e})}const Fo=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeNode:Ee},Symbol.toStringTag,{value:"Module"}));function Oe({value:e,onChange:t,readOnly:r=!1,focusJsonPath:a}){const[s,o]=c.useState(()=>cs(e)),[i,l]=c.useState(null),[u,f]=c.useState(null);gs(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(Ee,{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 Bo=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeEditor:Oe},Symbol.toStringTag,{value:"Module"}));function Nr({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 zo=Object.freeze(Object.defineProperty({__proto__:null,MockBodyHeadersEditor:Nr},Symbol.toStringTag,{value:"Module"})),Le=5;function ys(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,Le).join(", "),s=e.length>Le?`, +${e.length-Le} more`:"";return`Affects ${e.length} ${r}: ${a}${s}`}function vs(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 _s(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 js(e,t,r){const[a,s]=c.useState({}),o=r.map(i=>J(i.scope)).join("|");return c.useEffect(()=>{let i=!1;return(async()=>{const u={};for(const f of r)u[J(f.scope)]="loading";s(u);for(const f of r)try{const x=await Aa(e,t,f.scope);if(i)return;s(h=>({...h,[J(f.scope)]:x}))}catch{if(i)return;s(x=>({...x,[J(f.scope)]:[]}))}})(),()=>{i=!0}},[e,t,o]),a}function Tr({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 Ko=Object.freeze(Object.defineProperty({__proto__:null,SaveScopeChoiceRow:Tr},Symbol.toStringTag,{value:"Module"}));function Er({entry:e,scenarioSlug:t,routeKey:r,onCancel:a,onConfirm:s}){const o=vs(e),[i,l]=c.useState(()=>_s(e,o)),u=js(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(Tr,{choice:b,selected:i===g,impactLabel:ys(u[J(b.scope)],b.scope),onSelect:()=>l(g)},J(b.scope)))}),h&&n.jsx(ue,{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 Ho=Object.freeze(Object.defineProperty({__proto__:null,SaveScopeModal:Er},Symbol.toStringTag,{value:"Module"}));function Or({entry:e,routeKey:t,scenarioSlug:r,onSave:a,focusJsonPath:s}){const o=ls(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(ue,{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(Nr,{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(vr,{body:o.body,onBodyChange:o.setBody})]}),n.jsx(Oe,{value:o.body,onChange:o.setBody,focusJsonPath:s},t)]}),x&&n.jsx(Er,{entry:e,scenarioSlug:r,routeKey:t,onCancel:()=>h(!1),onConfirm:async b=>{await d(b),h(!1)}})]})}const Uo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockEditable:Or},Symbol.toStringTag,{value:"Module"}));function ws(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 gt={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 Ss(e){return gt[e]??gt.GET}function Ar({entry:e,scenarioHasDefaultFallback:t,onSave:r,onRemove:a,onPassthrough:s}){const o=`${e.method} ${e.pathPattern}`,i=Ss(e.method),l=e.status??e.lastObservedStatus,u=c.useMemo(()=>e.lastObservedMs?ws(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(Qe,{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 Yo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockHeader:Ar},Symbol.toStringTag,{value:"Module"}));function Mr({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(Oe,{value:e.body,onChange:()=>{},readOnly:!0},`${e.method} ${e.pathPattern}`)]})]})}const Wo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockReadOnly:Mr},Symbol.toStringTag,{value:"Module"}));function Pr({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(Ar,{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(Or,{entry:e,routeKey:l,scenarioSlug:t,onSave:a,focusJsonPath:i}):n.jsx(Mr,{entry:e})})]})}const Vo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMock:Pr},Symbol.toStringTag,{value:"Module"}));function ks({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 k=_[v]===null?"":typeof _[v]=="object"?JSON.stringify(_[v]):String(_[v]);f(k),h(k)}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]:ht(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(()=>{ne(),a&&a()}).catch(()=>{})}l(null)}}async function p(j,v,_){const k=[...s];k[j]={...k[j],[v]:ht(_)},o(k);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:_})}),ne(),a&&a()}catch{}}return{rows:s,editingCell:i,editValue:u,handleEditCell:m,handleEditValueChange:b,handleSave:g,handleCancelEdit:y}}function Rr({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 Xo=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCategoryBadge:Rr},Symbol.toStringTag,{value:"Module"}));function Dr({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 Jo=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCellEditor:Dr},Symbol.toStringTag,{value:"Module"}));function Ir({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(Lr,{name:o,type:t[o],isPk:o===r},o))]})}),n.jsx("tbody",{children:a.map((o,i)=>n.jsx($r,{row:o,rowIndex:i,columns:e,pkCol:r,onEditCell:s},i))})]})})}function Lr({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 $r({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(Fr,{value:e[o],isPk:o===a,onEdit:()=>s(t,o)},o))]})}function Fr({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 qo=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCell:Fr,DataViewerColumnHeader:Lr,DataViewerRow:$r,DataViewerTable:Ir},Symbol.toStringTag,{value:"Module"}));function Br({slug:e,tab:t,initialRows:r,onCellEdited:a}){const{rows:s,editingCell:o,editValue:i,handleEditCell:l,handleEditValueChange:u,handleSave:f,handleCancelEdit:x}=ks({slug:e,tab:t,initialRows:r,onCellEdited:a}),h=La(s,t.schemaFields),d=$a(h,s,t.schemaFields),m=Fa(h,t.schemaFields);return n.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[n.jsx(Rr,{tab:t}),n.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:n.jsx(Ir,{columns:h,colTypes:d,pkCol:m,rows:s,onEditCell:l})}),o&&n.jsx(Dr,{editingCell:o,editValue:i,onEditValueChange:u,onSave:f,onCancel:x})]})}const Go=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainTable:Br},Symbol.toStringTag,{value:"Module"}));function Cs({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)})}),ne(),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 zr({slug:e,browserState:t,tab:r,onCellEdited:a}){const{value:s,handleChange:o,label:i,description:l}=Cs({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(Oe,{value:s,onChange:o})})]})}const Qo=Object.freeze(Object.defineProperty({__proto__:null,BrowserStateTab:zr},Symbol.toStringTag,{value:"Module"}));function we({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 Zo=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMockDataBadge:we},Symbol.toStringTag,{value:"Module"}));function Kr({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(we,{label:"This Page",active:t.kind==="this-page",onClick:()=>r({kind:"this-page"})}),e.map(a=>n.jsx(we,{label:a,active:t.kind==="share"&&t.slug===a,onClick:()=>r({kind:"share",slug:a})},a)),n.jsx(we,{label:"Defaults",active:t.kind==="defaults",onClick:()=>r({kind:"defaults"})})]})}const ei=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMockDataStrip:Kr},Symbol.toStringTag,{value:"Module"}));function Ns({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}=Wa(e),{entries:d,loading:m,error:b,upsertScoped:g,remove:y,setPassthrough:p}=Pa(e),{config:j}=_t(),v=(j==null?void 0:j.provider)??"claude",_=qa({slug:e,onPreviewReload:ne}),k=c.useCallback(()=>{_.markDirty(),ne()},[_]),C=c.useCallback(async w=>{await g(w),k()},[g,k]),O=c.useCallback(async w=>{await y(w),k()},[y,k]),I=c.useCallback(async w=>{await p(w),k()},[p,k]),N=c.useCallback(()=>{_.markDirty(),ne()},[_]),D=c.useCallback(()=>{a&&_.confirmIfDirty("Discard unsaved changes to this scenario?")&&a()},[a,_]),[E,P]=c.useState(null),[T,S]=c.useState(null),[R,$]=c.useState(!1),U=c.useCallback(w=>P({kind:"mock",routeKey:w}),[]);Ca({onSelect:U,onFocus:S});const[z,W]=c.useState({kind:"this-page"}),X=x||m,Y=c.useMemo(()=>s==="inline"?i.filter(w=>l.has(w.dataKey)):i,[s,i,l]),L=c.useMemo(()=>{if(s!=="inline")return d;switch(z.kind){case"this-page":return d.filter(w=>w.consumedThisPageLoad);case"defaults":return d.filter(w=>w.source==="default");case"share":return d.filter(w=>w.source==="shared"&&w.sharedSlug===z.slug)}},[s,d,z]);as({seedTabs:Y,mockEntries:L,initialSection:r,selection:E,setSelection:P});const Q=c.useMemo(()=>{const w=new Set;for(const A of d)A.source==="default"&&w.add(q(A));return w},[d]),B=(E==null?void 0:E.kind)==="seed"?Y.find(w=>w.dataKey===E.dataKey)??null:null,K=(E==null?void 0:E.kind)==="mock"?L.find(w=>q(w)===E.routeKey)??null:null,Z=B&&o?o[B.dataKey]??[]:[],he=c.useMemo(()=>wa({slug:e,scenarioName:t,seedTabs:Y,mockEntries:L,selectedMock:K,selectedSeedTab:B,selectedSeedRows:Z}),[e,t,Y,L,K,B,Z]),me=t??e,ee=Y.length>0||L.length>0,te=n.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[n.jsx(yr,{title:me,slug:e,provider:v,chatOpen:R,onToggleChat:()=>$(w=>!w),variant:s,onClose:a?D:void 0,draftDirty:_.isDirty,draftDiff:_.diffSummary,draftSaving:_.saving,draftCancelling:_.cancelling,draftError:_.error,onSave:()=>void _.save(),onCancel:()=>void _.cancel()}),s==="inline"&&n.jsx(Kr,{shares:u,activeBadge:z,onSelect:W}),R&&n.jsx("div",{className:"flex-shrink-0 border-b border-[var(--border-subtle)] bg-[var(--bg-deep)]",children:n.jsx(ar,{chatName:`edit-data-${e}`,prompt:he,height:360,onClose:()=>$(!1)})}),n.jsxs("div",{className:"flex flex-1 min-h-0",children:[n.jsx(dr,{seedTabs:Y,mockEntries:L,selection:E,onSelect:P}),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(ue,{text:`Seed error: ${h}`,className:"text-xs text-red-400",rowClassName:"p-4"}),b&&n.jsx(ue,{text:`Mocks error: ${b}`,className:"text-xs text-red-400",rowClassName:"p-4"}),!X&&!ee&&n.jsx(ur,{}),B&&n.jsx(Br,{slug:e,tab:B,initialRows:Z,onCellEdited:N}),K&&n.jsx(Pr,{entry:K,scenarioSlug:e,scenarioHasDefaultFallback:Q.has(q(K)),onSave:C,onRemove:O,onPassthrough:I,focusJsonPath:T}),(E==null?void 0:E.kind)==="browser"&&n.jsx(zr,{slug:e,browserState:f,tab:E.tab,onCellEdited:N}),!B&&!K&&(E==null?void 0:E.kind)!=="browser"&&ee&&!X&&n.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)] italic",children:"Select a data source from the left to view it."}),X&&!ee&&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:te}):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:te}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-40 bg-black/40",onClick:D,"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:te})]})}const ti=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanel:Ns},Symbol.toStringTag,{value:"Module"}));export{br as $,pa as A,zr as B,Et as C,$r as D,Rt as E,Gt as F,kr as G,Sr as H,Te as I,Cr as J,Ee as K,Oe as L,Nr as M,jr as N,wr as O,vr as P,gr as Q,le as R,Ns as S,Bt as T,lr as U,cr as V,Er as W,Tr as X,dr as Y,Kr as Z,we as _,Qe as a,fo as a$,Ar as a0,Pr as a1,mr as a2,yr as a3,ur as a4,pr as a5,fr as a6,Ir as a7,Dr as a8,Rr as a9,Vs as aA,Is as aB,Ds as aC,qs as aD,Ls as aE,_o as aF,yo as aG,go as aH,Oo as aI,jo as aJ,Eo as aK,ei as aL,Zo as aM,Go as aN,Wo as aO,Yo as aP,Uo as aQ,Vo as aR,To as aS,Ao as aT,wo as aU,ko as aV,So as aW,ti as aX,Ho as aY,Ko as aZ,po as a_,ir as aa,or as ab,It as ac,Dt as ad,Tt as ae,Nt as af,zt as ag,St as ah,wt as ai,qt as aj,Zt as ak,tr as al,rr as am,ar as an,nr as ao,oo as ap,so as aq,Rs as ar,uo as as,co as at,Xs as au,Js as av,Ys as aw,Ws as ax,$s as ay,Us as az,Br as b,No as b$,xo as b0,vo as b1,zo as b2,Gs as b3,Zs as b4,Qs as b5,lo as b6,$o as b7,Lo as b8,Io as b9,ao as bA,ha as bB,Cn as bC,Zr as bD,en as bE,ln as bF,bn as bG,ro as bH,kn as bI,rn as bJ,En as bK,kt as bL,Nn as bM,jt as bN,Sn as bO,eo as bP,no as bQ,Pn as bR,An as bS,to as bT,Jn as bU,lt as bV,Xn as bW,ve as bX,se as bY,Ma as bZ,mo as b_,Po as ba,Fo as bb,Bo as bc,Ro as bd,Do as be,Mo as bf,ho as bg,Bs as bh,Fs as bi,zs as bj,Ks as bk,Hs as bl,qo as bm,Jo as bn,Xo as bo,Qo as bp,io as bq,fe as br,_a as bs,_t as bt,Qt as bu,Je as bv,ta as bw,Jr as bx,Pe as by,Gn as bz,Or as c,Co as c0,bo as c1,Dn as c2,Rn as c3,Mn as c4,gn as c5,nt as c6,yn as c7,jn as c8,_n as c9,Qr as ca,Ve as cb,ba as cc,Mr as d,ne as e,ws as f,qa as g,Wa as h,Pa as i,Ot as j,Kt as k,Ht as l,Pt as m,Mt as n,At as o,ht as p,G as q,Ft as r,$t as s,Lt as t,ma as u,je as v,Lr as w,Fr as x,ce as y,Ut as z};
|