@miadi/stateloom-web 0.2.5 → 0.2.6

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.
Files changed (47) hide show
  1. package/package.json +1 -1
  2. package/server/.next/BUILD_ID +1 -1
  3. package/server/.next/build-manifest.json +2 -2
  4. package/server/.next/server/app/_global-error.html +2 -2
  5. package/server/.next/server/app/_global-error.rsc +1 -1
  6. package/server/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  7. package/server/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  8. package/server/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  9. package/server/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  10. package/server/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  11. package/server/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  12. package/server/.next/server/app/_not-found.html +1 -1
  13. package/server/.next/server/app/_not-found.rsc +2 -2
  14. package/server/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  15. package/server/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  16. package/server/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  17. package/server/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  18. package/server/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  19. package/server/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  20. package/server/.next/server/app/api/docs/route.js.nft.json +1 -1
  21. package/server/.next/server/app/api/file/route.js.nft.json +1 -1
  22. package/server/.next/server/app/api/rispec/route.js.nft.json +1 -1
  23. package/server/.next/server/app/api/watch/route.js.nft.json +1 -1
  24. package/server/.next/server/app/index.html +1 -1
  25. package/server/.next/server/app/index.rsc +3 -3
  26. package/server/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  27. package/server/.next/server/app/index.segments/_full.segment.rsc +3 -3
  28. package/server/.next/server/app/index.segments/_head.segment.rsc +1 -1
  29. package/server/.next/server/app/index.segments/_index.segment.rsc +2 -2
  30. package/server/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  31. package/server/.next/server/app/page.js.nft.json +1 -1
  32. package/server/.next/server/app/page_client-reference-manifest.js +1 -1
  33. package/server/.next/server/chunks/ssr/{[root-of-the-server]__b1b2bf74._.js → [root-of-the-server]__cf0b4d7f._.js} +1 -1
  34. package/server/.next/server/chunks/ssr/[root-of-the-server]__edbb995c._.js +2 -2
  35. package/server/.next/server/pages/404.html +1 -1
  36. package/server/.next/server/pages/500.html +2 -2
  37. package/server/.next/static/chunks/{285279863965ba9b.js → 4237fd3bb3fa88e5.js} +4 -4
  38. package/server/.next/static/chunks/83083561effbd9ca.css +2 -0
  39. package/server/package-lock.json +2 -2
  40. package/server/package.json +1 -1
  41. package/server/src/components/sequence/SequenceReading.tsx +186 -0
  42. package/server/src/components/sequence/SequenceWorkspace.tsx +116 -13
  43. package/server/stateloom-web.json +2 -2
  44. package/server/.next/static/chunks/c86e96e4d6eeb632.css +0 -2
  45. /package/server/.next/static/{1_kqQZahUkpX4bIvXeeqX → bwSt2D1R7aQAKa8P4ErpF}/_buildManifest.js +0 -0
  46. /package/server/.next/static/{1_kqQZahUkpX4bIvXeeqX → bwSt2D1R7aQAKa8P4ErpF}/_clientMiddlewareManifest.json +0 -0
  47. /package/server/.next/static/{1_kqQZahUkpX4bIvXeeqX → bwSt2D1R7aQAKa8P4ErpF}/_ssgManifest.js +0 -0
@@ -8,7 +8,7 @@ ${b.error}`)}}catch(a){m(`# RISE rispec generation failed
8
8
  ${a}`)}l(!0)},W=async()=>{let a=f();try{let b=await fetch("/api/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({definition:a,language:T})});if(b.ok){let a=await b.json();m(a.code)}else{let c=await b.json().catch(()=>({error:"Unknown error"}));m(`// Code generation failed: ${c.error}
9
9
  // Showing definition JSON as fallback:
10
10
  ${a}`)}}catch{m(`// Backend unavailable — showing definition JSON
11
- ${a}`)}l(!0)};return(0,h.jsxs)("div",{className:"flex flex-col gap-1.5 px-2 py-1.5 bg-gray-900 border-b border-gray-800 md:flex-row md:flex-wrap md:items-center md:px-3",children:[(0,h.jsxs)("div",{className:"toolbar-ident",children:[(0,h.jsx)("input",{ref:A,type:"file",accept:".json,.smdf.json",onChange:a=>{let b=a.target.files?.[0];if(!b)return;let c=new FileReader;c.onload=a=>{e(a.target?.result,b.name)},c.readAsText(b),a.target.value=""},className:"hidden"}),(0,h.jsxs)("span",{className:"text-xs text-gray-400 mr-1 truncate max-w-[50vw] md:max-w-none",children:[b??"untitled.smdf.json",d&&(0,h.jsx)("span",{className:"text-yellow-500 ml-0.5",children:"●"})]}),(0,h.jsx)(dk,{}),"synced"===u&&(0,h.jsx)("span",{className:"text-[10px] text-emerald-500",title:"In sync with disk",children:"⌁ synced"}),"remote-changed"===u&&(0,h.jsx)("span",{className:"text-[10px] text-amber-400",title:v??"",children:"↻ remote changed"}),"error"===u&&(0,h.jsx)("span",{className:"text-[10px] text-red-400",title:v??"",children:"⚠ disk error"}),"idle"===u&&(0,h.jsx)("span",{className:"text-[10px] text-gray-600",title:v??"No file bound",children:"○ no disk"}),(0,h.jsx)(dl,{}),(0,h.jsx)("div",{className:"flex-1"})]}),(0,h.jsxs)("div",{className:"toolbar-strip",children:[(0,h.jsx)("button",{onClick:q,disabled:0===s.length,className:"toolbar-btn disabled:opacity-30",title:"Undo (Ctrl+Z)",children:"↩"}),(0,h.jsx)("button",{onClick:r,disabled:0===t.length,className:"toolbar-btn disabled:opacity-30",title:"Redo (Ctrl+Y)",children:"↪"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:p,className:"toolbar-btn",title:"Arrange states into layers (auto-layout)",children:"⤢ Arrange"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:()=>o("select"===n?"transition":"select"),className:`toolbar-btn ${"transition"===n?"!bg-amber-700 !text-white":""}`,title:"transition"===n?"Exit draw mode (Esc)":"Draw transition mode",children:"transition"===n?"✏️ Drawing":"↗ Draw"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:()=>A.current?.click(),className:"toolbar-btn",title:"Open local .smdf.json (browser)",children:"📂"}),(0,h.jsx)("button",{onClick:P,disabled:F,className:"toolbar-btn disabled:opacity-40",title:"Save to disk (STATELOOM_PROJECT_FILE)",children:"💾 Disk"}),(0,h.jsx)("button",{onClick:R,className:"toolbar-btn",title:"Reload from disk",children:"🔄"}),(0,h.jsx)("button",{onClick:()=>{let a=new Blob([f()],{type:"application/json"}),c=URL.createObjectURL(a),d=document.createElement("a");d.href=c,d.download=b??"statemachine.smdf.json",d.click(),URL.revokeObjectURL(c)},className:"toolbar-btn",title:"Download as file",children:"📥"}),(0,h.jsx)("select",{value:H,onChange:a=>{I(a.target.value),O(null),M(null)},className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",title:"Export format",children:c5.map(a=>(0,h.jsx)("option",{value:a,children:c6[a]},a))}),(0,h.jsx)("button",{onClick:Q,disabled:J,className:`toolbar-btn disabled:opacity-40 ${L?"!text-red-400":""}`,title:L??`Export the board as ${c6[H]}`,children:J?"…":"🖼 Export"}),N&&!L&&(0,h.jsxs)("span",{className:"text-[10px] text-emerald-500 truncate max-w-[40vw] md:max-w-[16rem]",title:N,children:["⤓ ",N]}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),B?(0,h.jsxs)("div",{className:"flex items-center gap-1",children:[(0,h.jsx)("input",{autoFocus:!0,className:"bg-gray-800 border border-gray-700 rounded px-2 py-0.5 text-xs text-gray-200 w-32 md:w-24",placeholder:"State name...",value:D,onChange:a=>E(a.target.value),onKeyDown:a=>{"Enter"===a.key&&S(),"Escape"===a.key&&C(!1)}}),(0,h.jsx)("button",{onClick:S,className:"toolbar-btn-sm",children:"✓"}),(0,h.jsx)("button",{onClick:()=>C(!1),className:"toolbar-btn-sm",children:"✕"})]}):(0,h.jsx)("button",{onClick:()=>C(!0),className:"toolbar-btn",children:"+State"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:()=>j(),className:"toolbar-btn",children:"✓ Validate"}),(0,h.jsxs)("select",{value:T,onChange:a=>U(a.target.value),className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",children:[(0,h.jsx)("option",{value:"python",children:"Python"}),(0,h.jsx)("option",{value:"typescript",children:"TypeScript"})]}),(0,h.jsx)("button",{onClick:W,className:"toolbar-btn",children:"⚡ Generate"}),(0,h.jsx)("button",{onClick:V,className:"toolbar-btn",title:"Generate RISE rispec markdown",children:"📜 RISE"}),(0,h.jsxs)("button",{onClick:()=>l(!k),className:`toolbar-btn ${k?"text-blue-400":""}`,children:["</>"," Code"]})]})]})}function dn(){let a=c_(a=>a.generatedCode),b=c_(a=>a.showCodePreview),c=c_(a=>a.setShowCodePreview);return b?(0,h.jsx)("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/60 p-2 md:p-0",children:(0,h.jsxs)("div",{className:"bg-gray-900 border border-gray-700 rounded-lg shadow-xl w-full max-h-[85dvh] md:w-[80%] md:max-w-3xl md:max-h-[80dvh] flex flex-col",children:[(0,h.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-800",children:[(0,h.jsx)("h3",{className:"text-sm font-semibold text-gray-300",children:"Generated Definition (JSON)"}),(0,h.jsx)("button",{onClick:()=>c(!1),className:"text-gray-500 hover:text-gray-300 text-lg min-h-11 min-w-11 md:min-h-0 md:min-w-0","aria-label":"Close preview",children:"✕"})]}),(0,h.jsx)("pre",{className:"flex-1 overflow-auto overscroll-contain p-4 text-[11px] leading-relaxed text-green-400 font-mono md:text-sm",children:a??"No code generated yet"}),(0,h.jsx)("div",{className:"flex justify-end px-4 py-2 border-t border-gray-800",children:(0,h.jsx)("button",{onClick:()=>{a&&navigator.clipboard.writeText(a)},className:"text-xs bg-gray-700 hover:bg-gray-600 text-gray-300 px-4 py-3 rounded md:px-3 md:py-1",children:"Copy to Clipboard"})})]})}):null}function dp(){let a=c_(a=>a.applyRemote),b=c_(a=>a.setRemoteStatus),c=c_(a=>a.setRemoteMtime),d=(0,dj.useRequestedDoc)();return(0,i.useEffect)(()=>{let e=!1,f=(0,dj.docQuery)(d);async function g(){try{let a=await fetch(`/api/file${f}`,{cache:"no-store"});if(!a.ok)return null;return await a.json()}catch{return null}}(async()=>{let c=await g();e||(c?.path&&c_.getState().setDocPath(c.path),c?.exists&&c.content?a(c.content,c.mtime,c.path.split("/").pop()):b("idle",c?`No file at ${c.path}`:null))})();let h=new EventSource(`/api/watch${f}`);return h.addEventListener("hello",a=>{try{let b=JSON.parse(a.data);"number"==typeof b?.mtime&&c(b.mtime)}catch{}}),h.addEventListener("change",async d=>{let e=0;try{e=JSON.parse(d.data)?.mtime??0}catch{}if(e<=(c_.getState().remoteMtime??0))return;let f=await g();f?.exists&&f.content&&(c_.getState().dirty?(b("remote-changed",`Disk changed at ${new Date(f.mtime).toLocaleTimeString()} — local has unsaved edits`),c(f.mtime)):a(f.content,f.mtime,f.path.split("/").pop()))}),h.addEventListener("error",()=>{b("error","Watch stream disconnected")}),()=>{e=!0,h.close()}},[a,b,c,d]),null}function dq({url:a}){let b=(0,dj.useRequestedDoc)();return(0,i.useEffect)(()=>{if(!a)return;let c=!1,d=null,e=null,f=null,g=null;return(async()=>{let h="";try{let a=await fetch(`/api/file${(0,dj.docQuery)(b)}`,{cache:"no-store"});a.ok&&(h=(await a.json())?.path??"")}catch{}c||(h&&c_.getState().setDocPath(h),(d=cQ({url:a,role:"web",docId:h,name:"web-designer",onFull:a=>{c_.getState().applyRemote(JSON.stringify({stateMachine:a.def}),a.mtime??Date.now(),h&&h.split("/").pop()||void 0),g=a.def},onPatch:a=>{c_.getState().applyRemoteOps(a.ops,a.mtime??Date.now(),a.seq),g=c_.getState().definition},onPresence:a=>{c_.getState().setPresence(a)}})).connect(),e=c_.subscribe((a,b)=>{a.definition===b.definition||a._applyingRemote||(f&&clearTimeout(f),f=setTimeout(()=>{var a,b;let c,e;if(!d||"connected"!==d.getSnapshot().status)return;let f=c_.getState().definition;if(null===g){d.emitFull(f),g=f;return}let h=(a=g,b=f,c=a??{settings:{namespace:"",asynchronous:!1},events:[],state:{name:b.state.name,states:[]}},function(a,b,c){let d={},e=!1,f=new Set([...Object.keys(a.settings),...Object.keys(b.settings)]),g=a.settings,h=b.settings;for(let a of f)q(g[a],h[a])||void 0===h[a]||(d[a]=h[a],e=!0);void 0!==a.settings.notes&&void 0===b.settings.notes&&(d.notes="",e=!0),e&&c.push({op:"settings.update",patch:d})}(c,b,e=[]),function(a,b,c){let d=a.events,e=b.events,f=Math.min(d.length,e.length);for(let a=0;a<f;a++)!function(a,b,c,d){let e={},f=!1;for(let a of["name","file","feeder","description","timers"])q(b[a],c[a])||void 0===c[a]||(e[a]=c[a],f=!0);f&&d.push({op:"eventSource.update",index:a,patch:e});let g=b.events??[],h=c.events??[],i=new Set(h.map(a=>a.id));for(let a of g)i.has(a.id)||d.push({op:"event.remove",id:a.id});let j=g.filter(a=>i.has(a.id)),k=0;for(;k<h.length;){let b=h[k];k<j.length&&j[k].id===b.id?(function(a,b,c){let d={},e=!1;for(let c of["name","description","preAction","postAction"])q(a[c],b[c])||void 0===b[c]||(d[c]=b[c],e=!0);e&&c.push({op:"event.update",id:b.id,patch:d})}(j[k],b,d),function(a,b,c,d){let e=Math.min(b.length,c.length);for(let f=0;f<e;f++)if(!q(b[f],c[f])){let e={};b[f].name!==c[f].name&&(e.name=c[f].name),b[f].type!==c[f].type&&(e.type=c[f].type),d.push({op:"parameter.update",eventId:a,index:f,patch:e})}for(let b=e;b<c.length;b++)d.push({op:"parameter.add",eventId:a,parameter:c[b],index:b});for(let e=b.length-1;e>=c.length;e--)d.push({op:"parameter.remove",eventId:a,index:e})}(b.id,j[k].parameters??[],b.parameters??[],d)):(d.push({op:"event.add",sourceIndex:a,event:b,index:k}),j.splice(k,0,b)),k++}}(a,d[a],e[a],c);for(let a=d.length;a<e.length;a++)c.push({op:"eventSource.add",source:e[a]});for(let a=d.length-1;a>=e.length;a--)c.push({op:"eventSource.remove",index:a})}(c,b,e),function(a,b,c){let d=o(a.state),e=o(b.state),f=new Map(d.map(a=>[a.name,a])),g=new Map(e.map(a=>[a.name,a])),h=p(a.state),i=p(b.state),j=[];for(let a of e){if(f.has(a.name))continue;let b=i.get(a.name)??null,{states:d,transitions:e,...g}=a;c.push({op:"state.add",parent:b,state:{...g}}),e&&e.length>0&&j.push({state:a.name,transitions:e})}for(let a of e){if(!f.has(a.name))continue;let b=h.get(a.name)??null,d=i.get(a.name)??null;b!==d&&null!==d&&c.push({op:"state.nest",child:a.name,newParent:d})}for(let a of e){let b=f.get(a.name);if(!b)continue;let d={},e=!1;q(b.kind,a.kind)||void 0===a.kind||(d.kind=a.kind,e=!0),q(b.description,a.description)||void 0===a.description||(d.description=a.description,e=!0),q(b.notes,a.notes)||(d.notes=a.notes??"",e=!0),q(b.prompt,a.prompt)||(d.prompt=a.prompt??"",e=!0),e&&c.push({op:"state.update",name:a.name,patch:d}),r(a.name,"onEntry",b.onEntry?.actions??[],a.onEntry?.actions??[],c),r(a.name,"onExit",b.onExit?.actions??[],a.onExit?.actions??[],c)}for(let a of j)a.transitions.forEach((b,d)=>{c.push({op:"transition.add",state:a.state,transition:b,index:d})});for(let a of e){let b=f.get(a.name);b&&function(a,b,c,d){let e=Math.min(b.length,c.length);for(let f=0;f<e;f++){if(q(b[f],c[f]))continue;let e={};for(let a of["event","nextState","condition","description","actions"])q(b[f][a],c[f][a])||void 0===c[f][a]||(e[a]=c[f][a]);Object.keys(e).length>0&&d.push({op:"transition.update",state:a,index:f,patch:e})}for(let b=e;b<c.length;b++)d.push({op:"transition.add",state:a,transition:c[b],index:b});for(let e=b.length-1;e>=c.length;e--)d.push({op:"transition.remove",state:a,index:e})}(a.name,b.transitions??[],a.transitions??[],c)}for(let a=d.length-1;a>=0;a--){let b=d[a];if(g.has(b.name))continue;let e=b.transitions??[];for(let a=e.length-1;a>=0;a--)c.push({op:"transition.remove",state:b.name,index:a});c.push({op:"state.remove",name:b.name})}}(c,b,e),e);0!==h.length&&(d.emitPatch(h),g=f)},60))}))})(),()=>{c=!0,f&&clearTimeout(f),e&&e(),d&&d.disconnect()}},[a,b]),null}function dr(){let a=process.env.NEXT_PUBLIC_STATELOOM_BRIDGE_URL??process.env.NEXT_PUBLIC_SMCRAFT_BRIDGE_URL;return"string"==typeof a&&a.length>0?a:void 0}let ds=null;function dt(){return ds||(ds=(async()=>{let a=dr()??null;try{let b=await fetch("/api/config",{cache:"no-store"});if(b.ok){let c=await b.json();return{bridgeUrl:c.bridgeUrl||a,projectFile:c.projectFile??null}}}catch{}return{bridgeUrl:a,projectFile:null}})())}function du(){let a=dr(),[b,c]=(0,i.useState)(a);return((0,i.useEffect)(()=>{let a=!0;return dt().then(b=>{a&&b.bridgeUrl&&c(b.bridgeUrl)}),()=>{a=!1}},[]),"string"==typeof b&&b.length>0)?(0,h.jsx)(dq,{url:b}):(0,h.jsx)(dp,{})}function dv(a){return Number.isFinite(a)?Math.min(1.75,Math.max(.75,a)):1}function dw(a){"u">typeof document&&(document.documentElement.style.fontSize=`${16*dv(a)}px`)}let dx=1,dy=!1,dz=new Set;function dA(){return dy||(dy=!0,dx=1),dx}function dB(){return 1}function dC(a){return dz.add(a),()=>{dz.delete(a)}}function dD(a,b){let c=dv(a);if(dw(c),b,dy=!0,c!==dx)for(let a of(dx=c,dz))a()}function dE(a,b){return Math.max(1,Math.hypot(b.clientX-a.clientX,b.clientY-a.clientY))}function dF(a,b){for(let c=0;c<a.length;c++)if(a[c].identifier===b)return a[c];return null}function dG(){let a=(0,i.useSyncExternalStore)(dC,dA,dB),b=(0,i.useRef)(null),c=(0,i.useRef)(null),d=(0,i.useRef)(null);(0,i.useEffect)(()=>{dw(a)},[a]);let e=(0,i.useCallback)(a=>{c.current=a,null===d.current&&(d.current=requestAnimationFrame(()=>{d.current=null,null!==c.current&&dD(c.current,!1)}))},[]),f=(0,i.useCallback)(()=>{c.current=null,dD(1,!0)},[]);return((0,i.useEffect)(()=>{let a=()=>{let a=b.current;if(b.current=null,!a?.engaged)return;null!==d.current&&(cancelAnimationFrame(d.current),d.current=null);let e=c.current??dA();c.current=null,dD(dv(e),!0)},f=c=>{if(2!==c.touches.length){b.current&&a();return}let[d,e]=[c.touches[0],c.touches[1]];c2(d.target)||c2(e.target)||(b.current={a:d.identifier,b:e.identifier,startScale:dA(),startDist:dE(d,e),engaged:!1})},g=a=>{let c=b.current;if(!c)return;let d=dF(a.touches,c.a),f=dF(a.touches,c.b);if(!d||!f)return;a.preventDefault();let g=dE(d,f);if(!c.engaged){if(12>Math.abs(g-c.startDist))return;c.engaged=!0,c.startDist=g;return}e(dv(c.startScale*(g/c.startDist)))},h=c=>{let d=b.current;d&&(dF(c.touches,d.a)&&dF(c.touches,d.b)||a())};return document.addEventListener("touchstart",f,{passive:!0,capture:!0}),document.addEventListener("touchmove",g,{passive:!1,capture:!0}),document.addEventListener("touchend",h,{passive:!0,capture:!0}),document.addEventListener("touchcancel",h,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",f,{capture:!0}),document.removeEventListener("touchmove",g,{capture:!0}),document.removeEventListener("touchend",h,{capture:!0}),document.removeEventListener("touchcancel",h,{capture:!0}),null!==d.current&&cancelAnimationFrame(d.current)}},[e]),1===a)?null:(0,h.jsxs)("div",{className:"ui-scale-pill",role:"status","aria-live":"polite",children:[(0,h.jsxs)("span",{children:["UI ",Math.round(100*a),"%"]}),(0,h.jsx)("button",{type:"button",onClick:f,"aria-label":"Reset interface size to 100 percent",children:"Reset"})]})}var dH=i;class dI extends dH.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,b){console.error(`[stateloom] the ${this.props.what} could not be drawn:`,a,b.componentStack)}componentDidUpdate(a){this.state.error&&a.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){let{error:a}=this.state;return a?(0,h.jsx)("div",{role:"alert",className:"flex h-full w-full items-center justify-center p-6 text-center text-sm text-amber-300",children:(0,h.jsxs)("p",{className:"max-w-md",children:["This ",this.props.what," cannot be drawn: ",a.message,". The file on disk is unchanged — correct it in the panel, in the file, or with the agent that wrote it."]})}):this.props.children}}function dJ({size:a=16}){return(0,h.jsxs)("svg",{width:a,height:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,h.jsx)("path",{d:"M12 4.5 21 19.5H3Z"}),(0,h.jsx)("path",{d:"M12 10v4.5"}),(0,h.jsx)("path",{d:"M12 17.3v.01"})]})}function dK({locked:a,size:b=16}){return(0,h.jsxs)("svg",{width:b,height:b,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,h.jsx)("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),(0,h.jsx)("path",{d:a?"M8 11V8a4 4 0 0 1 8 0v3":"M8 11V8a4 4 0 0 1 7.5-1.9"})]})}function dL(a){let{onClose:b,restVh:c,tallVh:d}=a,[e,f]=(0,i.useState)(!1),[g,h]=(0,i.useState)(null),j=(0,i.useRef)(null),k=()=>{f(!1),b()},l=a=>{let b=j.current;if(!b||b.id!==a.pointerId)return;j.current=null;let c=a.clientY-b.y;if(h(null),6>Math.abs(c))return f(a=>!a);if(c<=-50)return f(!0);if(c>=80){if(e&&c<260)return f(!1);k()}},m=e?d:c,n=null!==g;return{zoneProps:{onPointerDown:a=>{a.target.closest("button")||(j.current={y:a.clientY,id:a.pointerId},a.currentTarget.setPointerCapture(a.pointerId),h(0))},onPointerMove:a=>{let b=j.current;b&&b.id===a.pointerId&&h(a.clientY-b.y)},onPointerUp:l,onPointerCancel:l,style:{touchAction:"none",cursor:"grab"}},sheetStyle:{"--sheet-h":n&&g<0?`min(calc(${m}dvh + ${-g}px), ${d}dvh)`:`${m}dvh`,...n?{transition:"none"}:{},...n&&g>0?{transform:`translateY(${g}px)`}:{}},close:k}}let dM="stateloom:focus-request",dN="stateloom:system-changed",dO="stateloom:strip-note";function dP(a){let[b,c]=(0,i.useState)(null);return(0,i.useEffect)(()=>{let a=()=>c(null);a();let b=["popstate",dj.DOC_CHANGE_EVENT,"stateloom:focus",dM];for(let c of b)window.addEventListener(c,a);return()=>{for(let c of b)window.removeEventListener(c,a)}},[a]),b}function dQ(a){let b=new URL(window.location.href),c=b.searchParams.get("doc")!==a.doc;b.searchParams.set("doc",a.doc);let d=void 0===a.system?b.searchParams.get("system"):a.system;d?b.searchParams.set("system",d):b.searchParams.delete("system"),a.focus?b.searchParams.set("focus",a.focus):b.searchParams.delete("focus"),c?window.history.pushState({},"",b):window.history.replaceState(window.history.state,"",b),c&&window.dispatchEvent(new Event(dj.DOC_CHANGE_EVENT)),window.dispatchEvent(new Event(dM))}function dR(a){}function dS(){let[a,b]=(0,i.useState)({focus:null,nonce:0});return(0,i.useEffect)(()=>{let a=()=>b(a=>({focus:null,nonce:a.nonce+1}));a();let c=["popstate",dj.DOC_CHANGE_EVENT,dM];for(let b of c)window.addEventListener(b,a);return()=>{for(let b of c)window.removeEventListener(b,a)}},[]),a}function dT(a,b,c){try{return a()}catch(d){let a=d instanceof Error?d.message:String(d);return console.warn("[stateloom] skipped on a malformed document:",a),c?.(a),b}}let dU=(a,b)=>"chen"===b?`stateloom:erd-layout:chen:${a}`:`stateloom:erd-layout:${a}`,dV="stateloom:erd-notation",dW="stateloom:erd-lock";function dX(a,b){try{return JSON.parse(localStorage.getItem(dU(a,b))??"{}")}catch{return{}}}async function dY(a){let b=a.slice(0,a.lastIndexOf("/")),c=((await (await fetch("/api/docs",{cache:"no-store"})).json()).docs??[]).map(a=>a.path).filter(a=>a.endsWith(".smdf.json")&&a.slice(0,a.lastIndexOf("/"))===b),d=[];for(let a of c)try{let b=await (await fetch(`/api/file${(0,dj.docQuery)(a)}`,{cache:"no-store"})).json(),c=JSON.parse(b.content??"null"),e=ap(c?.stateMachine??c?.StateMachine??c);e?.state&&d.push({path:a,def:e})}catch{}return d}let dZ="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",d$="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",d_="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function d0(){let a=(0,dj.useRequestedDoc)(),[b,c]=(0,i.useState)(""),[d,e]=(0,i.useState)(null),[f,g]=(0,i.useState)({}),[j,k]=(0,i.useState)("crowsfoot"),[l,m]=(0,i.useState)(!1),[n,o]=(0,i.useState)({...M}),[p,q]=(0,i.useState)(0),[r,s]=(0,i.useState)(null),[t,u]=(0,i.useState)({text:"loading…",tone:"ok"}),v=(0,i.useCallback)((a,b="ok")=>u({text:a,tone:b}),[]),[w,x]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=setTimeout(()=>x(!0),4e3);return()=>{clearTimeout(a),x(!1)}},[t]);let[y,z]=(0,i.useState)("entities"),[A,B]=(0,i.useState)(!1),[C,D]=(0,i.useState)(!1),[E,F]=(0,i.useState)(!1),G=(0,i.useRef)(null),H=dL({onClose:()=>B(!1),restVh:62,tallVh:92}),[I,J]=(0,i.useState)(0),[K,L]=(0,i.useState)(null),N=(0,i.useRef)(null);(0,i.useEffect)(()=>{let b=!1,d=null;return(async()=>{let f=await (await fetch(`/api/file${(0,dj.docQuery)(a)}`,{cache:"no-store"})).json();if(b)return;if(f.error)return v(f.error,"warn");let h=f.path??"",i=null;try{let a=f.content?ap(JSON.parse(f.content)):null;W(a)&&(i={...a,relationships:a.relationships??[]})}catch{}if(f.exists&&!i)return v(`${h} is not a readable ERD definition`,"warn");let j=(h.split("/").pop()??"Untitled").replace(/\.erdf\.json$/i,""),l=function(){try{return"chen"===localStorage.getItem(dV)?"chen":"crowsfoot"}catch{return"crowsfoot"}}();c(h),e(i??{settings:{namespace:"Default",name:j},entities:[],relationships:[]}),k(l),m(function(){try{let a=localStorage.getItem(dW);if(null!==a)return"1"===a;return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}()),g(dX(h,l)),s(null),L(null),q(a=>a+1),v(f.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:n}=await dt();!b&&n&&(N.current=d=cQ({url:n,role:"web",docId:h,name:"web-designer",onFull:a=>{let b=a.def;W(b)&&(e({...b,relationships:b.relationships??[]}),v("updated live"))},onPatch:()=>{},onPresence:a=>J(a.length)}),d.connect())})().catch(a=>!b&&v(String(a),"warn")),()=>{b=!0,N.current=null,d?.disconnect()}},[a,v]);let O=(0,i.useMemo)(()=>{if(!d)return{};let a=dT(()=>(function(a,b={}){let c=b.notation??"crowsfoot",d=b.hSpacing??70,e=b.vSpacing??("chen"===c?130:90),f="chen"===c?ai:ar,g=[],h=new Set;for(let b of a.entities??[])!b?.name||h.has(b.name)||(h.add(b.name),g.push(b));let i=new Map,j=(a,b,c=new Set)=>a===b||!c.has(a)&&(c.add(a),(i.get(a)??[]).some(a=>j(a,b,c)));for(let b of a.relationships??[]){if(!b||!h.has(b.from)||!h.has(b.to)||b.from===b.to)continue;let[a,c]="N:1"===b.cardinality?[b.to,b.from]:[b.from,b.to];if((i.get(a)??[]).includes(c)||j(c,a))continue;let d=i.get(a);d?d.push(c):i.set(a,[c])}let k=new Map,l=(a,b)=>{if(!((k.get(a)??-1)>=b))for(let c of(k.set(a,b),i.get(a)??[]))l(c,b+1)},m=new Set([...i.values()].flat());for(let a of g)m.has(a.name)||l(a.name,0);for(let a of g)k.has(a.name)||l(a.name,0);for(let a of[...g].sort((a,b)=>k.get(b.name)-k.get(a.name))){let b=i.get(a.name)??[];b.length&&k.set(a.name,Math.min(...b.map(a=>k.get(a)))-1)}let n=[],o=new Map,p=(a,b)=>((n[b]??=[]).push(a),o.set(a.id,a),a);for(let a of g)p({id:a.name,entity:a.name,...f(a),upper:[],lower:[],x:0},k.get(a.name)??0);let q=0;for(let[a,b]of i)for(let c of b){let b=a;for(let d=k.get(a)+1;d<k.get(c);d++){let a=p({id:`\u0000lane${q++}`,width:28,height:0,upper:[],lower:[],x:0},d);o.get(b).lower.push(a.id),a.upper.push(b),b=a.id}o.get(b).lower.push(c),o.get(c).upper.push(b)}for(let a=n.length-1;a>=0;a--)n[a]?.length||n.splice(a,1);let r=(a,b)=>a.length?a.reduce((a,c)=>a+b(o.get(c)),0)/a.length:null,s=(a,b)=>{let c=new Map;for(let a of n)a.forEach((a,b)=>c.set(a.id,b));let d=new Map(a.map((a,d)=>[a.id,r(a[b],a=>c.get(a.id))??d]));a.sort((a,b)=>d.get(a.id)-d.get(b.id))};for(let a=0;a<2;a++){for(let a=1;a<n.length;a++)s(n[a],"upper");for(let a=n.length-2;a>=0;a--)s(n[a],"lower")}let t=a=>a.x+a.width/2,u=(a,b)=>{let c=0;for(let e of a){let a=r(e[b],t);e.x=Math.max(c,null===a?c:a-e.width/2),c=e.x+e.width+d}};for(let a of n)u(a,"upper");for(let a=n.length-2;a>=0;a--)u(n[a],"lower");let v=Math.min(0,...[...o.values()].map(a=>a.x)),w={},x=40;for(let a of n){for(let b of a)b.entity&&(w[b.entity]={x:Math.round(b.x-v)+40,y:x,width:b.width,height:b.height});x+=Math.max(0,...a.map(a=>a.height))+e}return w})(d,{notation:j}),{});for(let[b,c]of Object.entries(f))a[b]&&(a[b]={...a[b],...c});return a},[d,f,j]),Q=(0,i.useMemo)(()=>{if(!d)return[];let a="";return dT(()=>X(d),null,b=>a=b)??[{ruleId:"E000",message:`The document could not be checked (${a}): a field is not the shape Spec 80 gives it`}]},[d]),S=(0,i.useMemo)(()=>Q.map(a=>(a.element??"").split(/[.[]/)[0]).filter(Boolean),[Q]),T=(0,i.useCallback)(async a=>{let c;if(d&&b){try{c=a(d)}catch(a){return v(a instanceof Error?a.message:String(a),"warn")}e(c),L(null);try{let a=await fetch(`/api/file${(0,dj.docQuery)(b)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(c,null,2)+"\n"})});if(!a.ok)throw Error((await a.json())?.error??`HTTP ${a.status}`);N.current?.emitFull(c),v("saved")}catch(a){v(`not saved: ${a instanceof Error?a.message:String(a)}`,"warn")}}},[d,b,v]),Y=(0,i.useCallback)((a,c)=>{g(d=>{let e={...d,[a]:{x:Math.round(c.x),y:Math.round(c.y)}};try{localStorage.setItem(dU(b,j),JSON.stringify(e))}catch{}return e})},[b,j]),ae=()=>{g({});try{localStorage.removeItem(dU(b,j))}catch{}q(a=>a+1)},af=async()=>{if(!d)return;v("checking links…");let a=await dY(b);if(0===a.length)return L("none"),z("issues"),B(!0),v("no .smdf.json beside this document to check against","warn");let c=a.flatMap(a=>Z(a.def,d).map(b=>({...b,message:`${a.def.settings?.name??a.path}: ${b.message}`})));c.push(...$(d,a.map(a=>a.def.settings?.name??""))),L(c),z("issues"),B(!0),F(!1),v(`checked ${a.length} machine(s): ${c.length} problem(s)`,c.length?"warn":"ok")},ag=async a=>{let c=(await dY(b)).find(b=>b.def.settings?.name===a);c?(0,dj.navigateToDoc)(c.path):v(`no .smdf.json beside this document defines '${a}'`,"warn")},ah=()=>{let a=G.current?.getBoundingClientRect();return{width:a?.width??0,height:a?.height??0}},ak=a=>{let{width:b,height:c}=ah();o(d=>P(d,a,{x:b/2,y:c/2}))},ao=a=>{let b=O[a],{width:c,height:d}=ah();b&&c&&(o(R([b],c,d,{padding:28,maxScale:1.25})),s(a),H.close())},aq=dS(),as=(0,i.useRef)(-1);(0,i.useEffect)(()=>{if(!d||as.current===aq.nonce)return;as.current=aq.nonce;let a=aq.focus?a7(aq.focus):null,b=a?.kind==="entity"?a.name:a?.kind==="attribute"?a.name.split(".")[0]:null;b&&O[b]&&ao(b)},[d,aq,O]),(0,i.useEffect)(()=>{r&&1&&dR(`entity:${r}`)},[r]);let at=d?.entities.find(a=>a.name===r)??null,au=b.split("/").pop()||"…",av=Array.isArray(K)?K:[],aw=Q.length+av.length,ax=[{id:"entities",label:"Entities",icon:"▭"},{id:"relations",label:"Relations",icon:"⟷"},{id:"notes",label:"Notes",icon:"✎",badge:void 0},{id:"issues",label:"Issues",icon:(0,h.jsx)(dJ,{}),badge:aw||void 0}],ay=a=>y===a?"":"hidden md:block",az=()=>{d&&navigator.clipboard?.writeText(function(a){let b=["erDiagram"],c=" ",d=new Set;for(let e of a.relationships??[]){if(!e?.from||!e?.to)continue;let a=aj[e.cardinality]??aj["1:N"];b.push(`${c}${al(e.from)} ${a} ${al(e.to)} : ${an(e.label??"")}`),d.add(e.from),d.add(e.to)}let e=new Set;for(let f of a.entities??[]){if(!f?.name||e.has(f.name))continue;e.add(f.name);let a=(f.attributes??[]).filter(a=>a?.name);if(0===a.length){d.has(f.name)||b.push(`${c}${al(f.name)}`);continue}for(let d of(b.push(`${c}${al(f.name)} {`),a))b.push(`${c}${c}${function(a){let b=[];"pk"===a.key&&b.push("PK"),"uk"===a.key&&b.push("UK"),a.references&&b.push("FK");let c=[],d=U(a);d.length&&c.push(`stateOf ${d.join(", ")}`),a.description&&c.push(a.description);let e=[am(a.type??"","unknown"),am(a.name,"unnamed")];return b.length&&e.push(b.join(", ")),c.length&&e.push(an(c.join(" — "))),e.join(" ")}(d)}`);b.push(`${c}}`)}return b.join("\n")}(d)).then(()=>v("mermaid copied"))};return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&D(!1),children:[(0,h.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,h.jsx)("span",{className:"font-semibold text-blue-300",children:"ERD"}),(0,h.jsx)(dk,{}),(0,h.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:b,children:[d?.settings.name??au,(0,h.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",au]})]}),(0,h.jsx)("span",{className:"inline-flex shrink-0 overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Notation",children:[["crowsfoot","▤","Crow's foot — attributes listed inside the entity box"],["chen","◇","Chen — attributes as ovals, relationships as diamonds"]].map(([a,c,d])=>(0,h.jsx)("button",{title:d,"aria-label":d,"aria-pressed":j===a,onClick:()=>(a=>{if(a!==j){try{localStorage.setItem(dV,a)}catch{}k(a),g(dX(b,a)),q(a=>a+1)}})(a),className:`px-2.5 py-1.5 text-sm leading-none md:px-2 md:py-1 ${j===a?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:c},a))}),(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,h.jsx)("button",{className:d$,onClick:ae,title:"Forget the dragged positions and lay the board out again",children:"⤢ Arrange"}),(0,h.jsx)("button",{className:d$,onClick:af,title:"Check the state machines beside this document against it",children:"Check links"}),(0,h.jsx)("button",{className:d$,onClick:az,children:"Copy mermaid"}),(0,h.jsx)("button",{className:d$,onClick:()=>F(a=>!a),"aria-pressed":!E,title:E?"Show the panel":"Hide the panel — the board takes the full width",children:E?"⟨ Panel":"Panel ⟩"})]}),(0,h.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,h.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":C,onClick:a=>{a.stopPropagation(),D(a=>!a)},children:"⋯"}),C&&(0,h.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:[["⤢ Arrange the board",ae],["Check links to the machines",af],["Copy as mermaid",az]].map(([a,b])=>(0,h.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{D(!1),b()},children:a},a))})]})]}),(0,h.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,h.jsxs)("div",{ref:G,className:"relative min-w-0 flex-1 overflow-hidden",children:[d&&(0,h.jsx)(dI,{what:"diagram",resetKey:d,children:(0,h.jsx)(bu,{definition:d,notation:j,positions:O,viewport:n,onViewportChange:o,selection:r,readOnly:l,errorElements:S,fitKey:p,onSelect:s,onClearSelection:()=>s(null),onEntityMove:Y,onOpenMachine:ag,emptyHint:"No entities yet — add one in the panel, or let an agent call add_entity."})}),(0,h.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 flex max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===t.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,h.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===t.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,h.jsxs)("span",{className:`truncate transition-opacity duration-500 ${w&&"ok"===t.tone?"opacity-0":"opacity-100"}`,children:[t.text,I>1?` \xb7 ${I} in the room`:""]})]}),(0,h.jsxs)("div",{className:"absolute bottom-3 right-3 flex flex-col overflow-hidden rounded-lg border border-gray-700 bg-gray-900/90 shadow-lg backdrop-blur",children:[(0,h.jsx)("button",{title:l?"Shapes are locked: dragging moves the view. Tap to unlock.":"Lock the shapes in place, so dragging only moves the view","aria-label":"Lock shapes in place","aria-pressed":l,onClick:()=>{let a=!l;m(a);try{localStorage.setItem(dW,a?"1":"0")}catch{}v(a?"shapes locked — a drag anywhere moves the view":"shapes unlocked — drag one to move it")},className:`flex h-10 w-10 items-center justify-center border-b border-gray-800 hover:bg-gray-800 md:h-8 md:w-8 ${l?"bg-blue-950/60 text-blue-300":"text-gray-400"}`,children:(0,h.jsx)(dK,{locked:l})}),[["+","Zoom in",()=>ak(1.25)],["−","Zoom out",()=>ak(.8)],["⛶","Fit the whole diagram",()=>q(a=>a+1)]].map(([a,b,c])=>(0,h.jsx)("button",{title:b,"aria-label":b,onClick:c,className:"h-10 w-10 border-b border-gray-800 text-base leading-none text-gray-200 last:border-b-0 hover:bg-gray-800 md:h-8 md:w-8 md:text-sm",children:a},b))]}),at&&!A&&(0,h.jsxs)("button",{className:"absolute bottom-3 left-1/2 max-w-[60%] -translate-x-1/2 truncate rounded-full border border-blue-500/60 bg-gray-900/95 px-4 py-2 text-sm text-blue-200 shadow-lg md:hidden",onClick:()=>{z("entities"),B(!0)},children:["✎ ",at.name]})]}),A&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:H.close,"aria-hidden":"true"}),d&&(0,h.jsxs)("aside",{style:H.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${A?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${E?"md:hidden":""}`,children:[(0,h.jsxs)("div",{className:"md:hidden",...H.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:ax.find(a=>a.id===y)?.label}),(0,h.jsx)("button",{onClick:H.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,h.jsxs)("section",{className:ay("entities"),children:[(0,h.jsx)("div",{className:d_,style:{marginTop:0},children:"Entities"}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:d.entities.map(a=>(0,h.jsx)("button",{className:`${d$} ${r===a.name?"border-blue-500 text-blue-300":""}`,onClick:()=>s(a.name),children:a.name},a.name))}),(0,h.jsx)(d2,{fields:[{name:"name",placeholder:"new entity"}],submit:"+ Entity",onSubmit:a=>{T(b=>ac(b,{name:a.name.trim()})),s(a.name.trim())}}),at&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:`${d_} flex items-center justify-between gap-2`,children:[(0,h.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:at.name}),(0,h.jsx)("button",{className:`${d$} normal-case tracking-normal`,onClick:()=>ao(at.name),title:"Bring this entity to the middle of the board at a readable size",children:"◎ Show on board"})]}),(0,h.jsxs)("label",{className:"mb-1 flex items-center gap-2 text-[11px] text-gray-400",title:"Exists only through another entity (an order line, without its order). Chen draws it as a double rectangle.",children:[(0,h.jsx)("input",{type:"checkbox",checked:!!at.weak,onChange:a=>T(b=>ad(b,at.name,{weak:a.target.checked}))}),"weak entity"]}),(at.attributes??[]).map(a=>(0,h.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 font-mono text-[11px]",children:[(0,h.jsxs)("span",{className:a.stateOf?"text-blue-300":"text-gray-300",children:[a.name," : ",a.type,(0,h.jsxs)("span",{className:"text-gray-500",children:[a.key?` ${a.key.toUpperCase()}`:"",a.references?` → ${a.references}`:"",a.stateOf?` ◉ ${[a.stateOf].flat().join(", ")}`:""]})]}),(0,h.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove ${a.name}`,onClick:()=>T(b=>(function(a,b,c){let d=_(a),e=aa(d,b),f=e.attributes?.length??0;if(e.attributes=(e.attributes??[]).filter(a=>a.name!==c),e.attributes.length===f)throw Error(`Attribute '${b}.${c}' not found.`);return d})(b,at.name,a.name)),children:"✕"})]},a.name)),(0,h.jsx)(d2,{fields:[{name:"name",placeholder:"attribute"},{name:"type",placeholder:"type",initial:"string"},{name:"key",options:["","pk","uk"]},{name:"references",placeholder:"references Entity.attr"},{name:"stateOf",placeholder:"stateOf Machine"}],submit:"+ Attribute",onSubmit:a=>T(b=>(function(a,b,c){if(!c.name?.trim())throw Error("An attribute needs a name.");let d=_(a),e=aa(d,b);if(e.attributes??=[],e.attributes.some(a=>a.name===c.name))throw Error(`Attribute '${b}.${c.name}' already exists.`);return e.attributes.push(ab({...c})),d})(b,at.name,{name:a.name.trim(),type:a.type.trim()||"string",key:"pk"===a.key||"uk"===a.key?a.key:void 0,references:a.references.trim()||void 0,stateOf:a.stateOf.trim()||void 0}))}),(0,h.jsxs)("button",{className:`${d$} mt-2 text-red-300`,onClick:()=>{T(a=>{var b;let c;return b=at.name,aa(c=_(a),b),c.entities=c.entities.filter(a=>a.name!==b),c.relationships=c.relationships.filter(a=>a.from!==b&&a.to!==b),c}),s(null)},children:["🗑 Delete ",at.name]})]})]}),(0,h.jsxs)("section",{className:ay("relations"),children:[(0,h.jsx)("div",{className:`${d_} max-md:mt-0`,children:"Relationships"}),0===d.relationships.length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),d.relationships.map((a,b)=>(0,h.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 text-[11px] text-gray-300",children:[(0,h.jsxs)("span",{children:[a.from," ",(0,h.jsx)("span",{className:"text-gray-500",children:a.cardinality})," ",a.to,a.label?(0,h.jsxs)("span",{className:"text-gray-500",children:[" : ",a.label]}):null]}),(0,h.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":"Remove relationship",onClick:()=>T(b=>(function(a,b,c,d){let e=_(a),f=e.relationships.length;if(e.relationships=e.relationships.filter(a=>a.from!==b||a.to!==c||void 0!==d&&a.label!==d),e.relationships.length===f)throw Error(`No relationship from '${b}' to '${c}'${void 0===d?"":` labelled '${d}'`}.`);return e})(b,a.from,a.to,a.label)),children:"✕"})]},b)),d.entities.length>0&&(0,h.jsx)(d2,{fields:[{name:"from",options:d.entities.map(a=>a.name)},{name:"cardinality",options:[...V],initial:"1:N"},{name:"to",options:d.entities.map(a=>a.name)},{name:"label",placeholder:"label (a verb)"}],submit:"+ Relationship",onSubmit:a=>T(b=>(function(a,b){let c=_(a);if(aa(c,b.from),aa(c,b.to),!V.includes(b.cardinality))throw Error(`Cardinality '${b.cardinality}' is not one of ${V.join(", ")}.`);return c.relationships.push(ab({...b})),c})(b,{from:a.from,to:a.to,cardinality:a.cardinality,label:a.label.trim()||void 0}))})]}),(0,h.jsxs)("section",{className:ay("notes"),children:[(0,h.jsx)("div",{className:`${d_} max-md:mt-0`,children:"Notes"}),(0,h.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the document, for whoever opens it next — you, or an agent (it reads them with get_notes)."}),(0,h.jsx)(d1,{label:"On this diagram",value:d.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:a=>T(b=>(function(a,b){let c=_(a);for(let a of["description","notes"]){let d=b[a];void 0!==d&&(d.trim()?c.settings[a]=d:delete c.settings[a])}return c})(b,{notes:a}))},"diagram"),at?(0,h.jsx)(d1,{label:`On ${at.name}`,value:at.notes??"",placeholder:`A question or a decision about ${at.name}…`,onSave:a=>T(b=>ad(b,at.name,{notes:a}))},`entity:${at.name}`):(0,h.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select an entity to leave a note on it."}),d.entities.some(a=>a.notes?.trim())&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:d_,children:"Entities with notes"}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:d.entities.filter(a=>a.notes?.trim()).map(a=>(0,h.jsx)("button",{className:`${d$} ${r===a.name?"border-blue-500 text-blue-300":""}`,onClick:()=>s(a.name),children:a.name},a.name))})]})]}),(0,h.jsxs)("section",{className:ay("issues"),children:[(0,h.jsx)("div",{className:`${d_} max-md:mt-0 ${0===aw&&!K?"md:hidden":""}`,children:"Issues"}),Q.map((a,b)=>(0,h.jsxs)("div",{className:"py-0.5 text-[11px] text-red-300",children:["[",a.ruleId,"] ",a.message]},`p${b}`)),av.map((a,b)=>(0,h.jsxs)("div",{className:"py-0.5 text-[11px] text-amber-300",children:["[",a.ruleId,"] ",a.message]},`l${b}`)),"none"===K&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-amber-300",children:"No state machine (.smdf.json) sits beside this document, so there was nothing to check it against."}),0===aw&&"none"!==K&&(0,h.jsx)("div",{className:`py-0.5 text-[11px] ${K?"text-green-400":"text-gray-600 md:hidden"}`,children:K?"Every name the machines use resolves.":"The document is valid. “Check links” (⋯) holds the state machines beside it against it."})]})]})]})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:ax.map(a=>{let b=A&&y===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(A&&y===b?H.close():B(!0),z(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})})]})}function d1({label:a,value:b,placeholder:c,onSave:d}){let[e,f]=(0,i.useState)(b),[g,j]=(0,i.useState)(b),[k,l]=(0,i.useState)(!1);b!==g&&(j(b),k||f(b));let m=(0,i.useRef)(null),n=a=>{m.current&&clearTimeout(m.current),m.current=null,a!==b&&d(a)};return(0,h.jsxs)("label",{className:"mt-2 block",children:[(0,h.jsx)("span",{className:"text-[11px] text-gray-500",children:a}),(0,h.jsx)("textarea",{className:`${dZ} h-24 resize-y leading-snug`,placeholder:c,value:e,onChange:a=>{let b=a.target.value;f(b),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>n(b),900)},onFocus:()=>l(!0),onBlur:()=>{l(!1),n(e)}})]})}function d2({fields:a,submit:b,onSubmit:c}){let d=()=>Object.fromEntries(a.map(a=>[a.name,a.initial??a.options?.[0]??""])),[e,f]=(0,i.useState)(d),g=a[0];return(0,h.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:b=>{b.preventDefault();let h={...d(),...e};h[g.name]?.trim()&&(c(h),f(b=>Object.fromEntries(a.map(a=>[a.name,a.options?b[a.name]??"":a.initial??""]))))},children:[a.map(a=>a.options?(0,h.jsx)("select",{className:dZ,"aria-label":a.name,value:e[a.name]??"",onChange:b=>f(c=>({...c,[a.name]:b.target.value})),children:a.options.map(b=>(0,h.jsx)("option",{value:b,children:b||`(${a.name})`},b))},a.name):(0,h.jsx)("input",{className:dZ,"aria-label":a.name,placeholder:a.placeholder,value:e[a.name]??"",onChange:b=>f(c=>({...c,[a.name]:b.target.value}))},a.name)),(0,h.jsx)("button",{type:"submit",className:`${d$} ${1===a.length?"":"col-span-2"}`,children:b})]})}let d3="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",d4="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",d5="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function d6({id:a,fields:b,submit:c,onSubmit:d,reset:e=!1,required:f}){let g=()=>Object.fromEntries(b.map(a=>[a.name,a.initial??(!a.checkbox&&(a.options?a.options[0]??"":""))])),[j,k]=(0,i.useState)(g),l=(a,b)=>k(c=>({...c,[a]:b}));return(0,h.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:a=>{a.preventDefault();let c={...g(),...j};!(f??[]).some(a=>!String(c[a]??"").trim())&&(d(c),e&&k(a=>Object.fromEntries(b.map(b=>[b.name,b.options||b.checkbox?a[b.name]??"":b.initial??""]))))},children:[b.map(b=>{let c=b.label??b.name;if(b.checkbox)return(0,h.jsxs)("label",{className:"flex items-center gap-2 text-[11px] text-gray-400",children:[(0,h.jsx)("input",{type:"checkbox",checked:!!j[b.name],onChange:a=>l(b.name,a.target.checked)}),c]},b.name);if(b.options)return(0,h.jsx)("select",{className:`${d3} ${b.wide?"col-span-2":""}`,"aria-label":c,title:c,value:String(j[b.name]??""),onChange:a=>l(b.name,a.target.value),children:b.options.map(a=>(0,h.jsx)("option",{value:a,children:a||`(${c})`},a))},b.name);let d=b.suggest?.length?`${a}-${b.name}`:void 0;return(0,h.jsxs)("span",{className:b.wide?"col-span-2":"",children:[(0,h.jsx)("input",{className:d3,"aria-label":c,title:c,placeholder:b.placeholder??c,list:d,value:String(j[b.name]??""),onChange:a=>l(b.name,a.target.value)}),d&&(0,h.jsx)("datalist",{id:d,children:b.suggest.map(a=>(0,h.jsx)("option",{value:a},a))})]},b.name)}),(0,h.jsx)("button",{type:"submit",className:`${d4} col-span-2`,children:c})]})}function d7({kind:a,size:b=16}){return(0,h.jsxs)("svg",{width:b,height:b,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"shrink-0",children:["erd"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("rect",{x:"4",y:"4.5",width:"16",height:"15",rx:"1.5"}),(0,h.jsx)("path",{d:"M4 9h16M8 13h8M8 16.5h6"})]}),"machine"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("rect",{x:"2.5",y:"4",width:"8",height:"6",rx:"2.5"}),(0,h.jsx)("rect",{x:"13.5",y:"14",width:"8",height:"6",rx:"2.5"}),(0,h.jsx)("path",{d:"M6.5 10v4.5a2.5 2.5 0 0 0 2.5 2.5h4.5"}),(0,h.jsx)("path",{d:"M11.5 15l2 2-2 2"})]}),"sequence"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("path",{d:"M6 4v16M18 4v16",strokeDasharray:"2 2.2"}),(0,h.jsx)("path",{d:"M6 9h11M15 7l2 2-2 2"}),(0,h.jsx)("path",{d:"M18 15H7M9 13l-2 2 2 2"})]}),"system"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("rect",{x:"3",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,h.jsx)("rect",{x:"14",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,h.jsx)("rect",{x:"8.5",y:"14.5",width:"7",height:"6",rx:"1.5"}),(0,h.jsx)("path",{d:"M10 6.5h4M7 9.5l3 5M17 9.5l-3 5"})]}),"link"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("path",{d:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1.2 1.2"}),(0,h.jsx)("path",{d:"M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1.2-1.2"})]}),"actor"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("circle",{cx:"12",cy:"7.5",r:"3.5"}),(0,h.jsx)("path",{d:"M5 20a7 7 0 0 1 14 0"})]})]})}async function d8(a){try{let b=await fetch(`/api/file${(0,dj.docQuery)(a)}`,{cache:"no-store"}),c=await b.json();if(!b.ok||c.error)return{path:a??"",content:null,exists:!1,error:c.error??`HTTP ${b.status}`};return{path:c.path??a??"",content:c.content??null,exists:!!c.exists,mtime:c.mtime}}catch(b){return{path:a??"",content:null,exists:!1,error:b instanceof Error?b.message:String(b)}}}class d9 extends Error{constructor(a){super(`${a.split("/").pop()} changed on disk since it was read`)}}async function ea(a,b,c){let d=await fetch(`/api/file${(0,dj.docQuery)(a)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(b,null,2)+"\n",...void 0!==c?{mtime:c}:{}})}),e=await d.json().catch(()=>({}));if(409===d.status)throw new d9(a);if(!d.ok)throw Error(e?.error??`HTTP ${d.status}`);return e?.mtime}async function eb(a){let b=await d8(a),c={path:b.path||a,def:null,members:[],absOf:{},wrapped:{},mtimes:{}};if(b.error)return{...c,error:b.error};if(!b.exists||!b.content)return{...c,error:`${a} does not exist`};let d=null;try{let a=ap(JSON.parse(b.content));aQ(a)&&(d=a)}catch{}if(!d)return{...c,error:`${b.path} is not a readable system definition`};let e={},f={},g={[b.path]:b.mtime??0},h=await Promise.all((d.members??[]).filter(a=>a?.path).map(async a=>{let c=aU(b.path,a.path);e[a.path]=c;let d=aR(a.path),h=await d8(c);if(h.error)return{path:a.path,kind:d,def:null,error:h.error};if(!h.exists||!h.content)return{path:a.path,kind:d,def:null,error:"the file does not exist"};g[a.path]=h.mtime??0;try{let b=JSON.parse(h.content);if("machine"===d&&b&&(b.stateMachine||b.StateMachine))return f[a.path]=!0,{path:a.path,kind:d,def:ap(b.stateMachine??b.StateMachine)};return{path:a.path,kind:d,def:ap(b)}}catch(b){return{path:a.path,kind:d,def:null,error:`not JSON: ${b instanceof Error?b.message:String(b)}`}}}));return{path:b.path,def:d,members:h,absOf:e,wrapped:f,mtimes:g}}function ec(){window.dispatchEvent(new Event(dN))}function ed(a){let[b,c]=(0,i.useState)(null),[d,e]=(0,i.useState)(0),f=(0,i.useCallback)(()=>e(a=>a+1),[]);return(0,i.useEffect)(()=>(window.addEventListener(dN,f),()=>window.removeEventListener(dN,f)),[f]),(0,i.useEffect)(()=>{if(!a)return;let b=!0;return eb(a).then(d=>b&&c({for:a,system:d})),()=>{b=!1}},[a,d]),{system:a&&b?.for===a?b.system:null,reload:f}}function ee(a,b){if(!a||!b)return null;for(let[c,d]of Object.entries(a.absOf))if(d===b)return c;return null}async function ef(a,b,c,d){let{bridgeUrl:e}=await dt();if(!e)return;let f=cO({url:e,role:"web",docId:a,name:"web-reconcile",autoResync:!1});try{let a=await Promise.race([f.join(),new Promise((a,b)=>setTimeout(()=>b(Error("join timeout")),3e3))]),e=a.snapshot?.def,g=a=>(function(a){let b=JSON.stringify(a),c=0x811c9dc5;for(let a=0;a<b.length;a++)c^=b.charCodeAt(a),c=Math.imul(c,0x1000193);return(c>>>0).toString(16).padStart(8,"0")})(a);if(e&&g(e)===g(b))return;await new Promise(a=>{let h=f.on("ack",()=>{h(),a()});d&&e&&g(e)===g(d.from)?f.emitPatch(d.ops,c):f.emitFull(b,c),setTimeout(a,800)})}catch{}finally{f.disconnect()}}async function eg(a,b){let c=[],d=[],e=[],f=async(a,b)=>{try{await b(),c.push(a)}catch(b){b instanceof d9?e.push(a):d.push(`${a}: ${b instanceof Error?b.message:String(b)}`)}};for(let c of b.machines){let b=a.absOf[c.member];b&&c.ops.length&&await f(c.member,async()=>{let d=a.wrapped[c.member]?{stateMachine:c.def}:c.def,e=await ea(b,d,a.mtimes[c.member]),f=a.members.find(a=>a.path===c.member)?.def;await ef(b,c.def,e,{from:f,ops:c.ops})})}for(let c of b.erds){let b=a.absOf[c.member];b&&await f(c.member,async()=>{let d=await ea(b,c.def,a.mtimes[c.member]);await ef(b,c.def,d)})}return b.system&&await f(a.path.split("/").pop()??a.path,async()=>{let c=await ea(a.path,b.system.def,a.mtimes[a.path]);await ef(a.path,b.system.def,c)}),ec(),{written:c,failed:d,conflicts:e}}async function eh(a){let b={result:null,written:[],failed:[],conflicts:[]};for(let c=0;c<2;c+=1){let d=await eb(a);if(!d.def)return{...b,failed:[d.error??"the system could not be read"],retried:c>0};let e=bc(d.def,d.members);if(!e.count)return{...b,result:e,conflicts:c?b.conflicts:[],retried:c>0};let f=await eg(d,e);if(b={result:e,written:[...b.written,...f.written],failed:f.failed,conflicts:f.conflicts},!f.conflicts.length)return{...b,retried:c>0}}return{...b,retried:!0}}let ei=["","actor","service","object"],ej=a=>"string"==typeof a?a.trim():"",ek=a=>ej(a).split(",").map(a=>a.trim()).filter(Boolean);function el(a){return{from:ej(a.from),to:ej(a.to),label:ej(a.label),event:ej(a.event),machine:ej(a.machine),carries:ej(a.carries),state:ej(a.state),description:ej(a.description),optional:!!a.optional||void 0,reply:!!a.reply||void 0}}function em(){let a,b,c,d=(0,dj.useRequestedDoc)(),e=dP("system"),{system:f}=ed(e),g=dS(),[j,k]=(0,i.useState)(""),[l,m]=(0,i.useState)(null),[n,o]=(0,i.useState)({...M}),[p,q]=(0,i.useState)(void 0),[r,s]=(0,i.useState)(null),[t,u]=(0,i.useState)({text:"loading…",tone:"ok"}),v=(0,i.useCallback)((a,b="ok")=>u({text:a,tone:b}),[]),[w,x]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=setTimeout(()=>x(!0),4e3);return()=>{clearTimeout(a),x(!1)}},[t]);let[y,z]=(0,i.useState)("messages"),[A,B]=(0,i.useState)(!1),[C,D]=(0,i.useState)(!1),[E,F]=(0,i.useState)(!1),G=(0,i.useRef)(null),H=dL({onClose:()=>B(!1),restVh:62,tallVh:92}),[I,J]=(0,i.useState)(0),K=(0,i.useRef)(null),L=(0,i.useRef)(!0),O=(0,i.useRef)(-1);(0,i.useEffect)(()=>{let a=!1,b=null;return(async()=>{let c=await (await fetch(`/api/file${(0,dj.docQuery)(d)}`,{cache:"no-store"})).json();if(a)return;if(c.error)return v(c.error,"warn");let e=c.path??"",f=null;try{let a=c.content?ap(JSON.parse(c.content)):null;au(a)&&(f=a)}catch{}if(c.exists&&!f)return v(`${e} is not a readable sequence definition`,"warn");let g=(e.split("/").pop()??"Untitled").replace(/\.sqdf\.json$/i,"");k(e),m(f??av("Default",g)),v(c.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:h}=await dt();!a&&h&&(K.current=b=cQ({url:h,role:"web",docId:e,name:"web-designer",onFull:a=>{let b=a.def;au(b)&&(m(b),v("updated live"))},onPatch:()=>{},onPresence:a=>J(a.length)}),b.connect())})().catch(b=>!a&&v(String(b),"warn")),()=>{a=!0,K.current=null,b?.disconnect()}},[d,v]);let Q=(0,i.useMemo)(()=>l?bA(l):null,[l]),S=(0,i.useMemo)(()=>Q?aK(Q):null,[Q]),T=(0,i.useMemo)(()=>{if(!l)return[];let a="";return dT(()=>az(l),null,b=>a=b)??[{ruleId:"S000",message:`The document could not be checked (${a}): a field is not the shape Spec 81 gives it`}]},[l]),U=ee(f,j),V=(0,i.useMemo)(()=>f?.def&&U&&l?dT(()=>a5(f.def,f.members.map(a=>a.path===U?{...a,def:l,error:void 0}:a)),null):null,[f,U,l]),W=(0,i.useMemo)(()=>(V?.issues??[]).filter(a=>a.member===U&&!/^S0/.test(a.ruleId)),[V,U]),X=V?.replays.find(a=>a.member===U)?.report??null,Y=(0,i.useMemo)(()=>(function(a){let b={events:new Set,states:new Set,machines:new Set,objects:new Set,entities:new Set,actors:new Set};if(!a)return{events:[],states:[],machines:[],objects:[],entities:[],actors:[]};let{machines:c,erds:d}=a4(a.members);for(let{def:a}of(c.forEach(({def:a},c)=>{for(let d of(b.machines.add(a$(a,c)),a.events??[]))for(let a of[...d?.events??[],...d?.timers??[]])a?.id&&b.events.add(a.id);for(let c of a.settings?.objects??[])c?.instance&&b.objects.add(c.instance);let d=a=>{a&&(b.states.add(a.name),(a.states??[]).forEach(d),(a.parallel?.states??[]).forEach(d))};d(a.state)}),d))for(let c of a.entities??[])c?.name&&b.entities.add(c.name);for(let c of a.def?.actors??[])c?.name&&b.actors.add(c.name);let e=a=>[...a].sort((a,b)=>a.localeCompare(b));return{events:e(b.events),states:e(b.states),machines:e(b.machines),objects:e(b.objects),entities:e(b.entities),actors:e(b.actors)}})(f),[f]),Z=(0,i.useMemo)(()=>{let a=a=>a?/^(message|participant):/.test(a)?a:Q?.participants.some(b=>b.name===a)?`participant:${a}`:"":"";return[...T.map(b=>a(b.element)),...W.filter(a=>"error"===a.severity).map(b=>a(b.element))].filter(Boolean)},[T,W,Q]),$=(0,i.useMemo)(()=>W.filter(a=>"warning"===a.severity).map(a=>a.element??""),[W]),_=()=>{let a=G.current?.getBoundingClientRect();return{width:a?.width??0,height:a?.height??0}},aa=(0,i.useCallback)(a=>{let b=G.current?.getBoundingClientRect();if(!b?.width)return;let c=N(Math.max(R([a],b.width,b.height,{padding:24,maxScale:1.1}).scale,.7));o({scale:c,x:b.width/2-(a.x+a.width/2)*c,y:b.height/2-(a.y+a.height/2)*c})},[]),ab=(0,i.useCallback)(a=>{if(S)if("message"===a.kind){let b=S.rows.find(b=>b.ref===a.id);if(!b)return;let c=b.self?b.fromX:Math.min(b.fromX,b.toX),d=b.self?220:Math.abs(b.toX-b.fromX);aa({x:c-10,y:b.y-24,width:d+20,height:40})}else{let b=S.participants.find(b=>b.name===a.id);b&&aa({x:b.left-20,y:b.top,width:b.width+40,height:Math.min(260,S.height-b.top)})}},[S,aa]),ac=(0,i.useCallback)(a=>{s(a),a&&dR(`${a.kind}:${a.id}`)},[]);(0,i.useEffect)(()=>{if(!l||!S||O.current===g.nonce)return;O.current=g.nonce;let a=g.focus?a7(g.focus):null;if(!a)return;let b=null;if("message"===a.kind&&ax(Q??l,a.name)&&(b={kind:"message",id:a.name}),"participant"===a.kind&&(Q??l).participants.some(b=>b.name===a.name)&&(b={kind:"participant",id:a.name}),!b)return v(`${g.focus} is not in this sequence`,"warn");L.current=!1,s(b),ab(b)},[l,Q,S,g,ab,v]),(0,i.useEffect)(()=>{if(!S||!L.current)return;let{width:a,height:b}=_();a&&(L.current=!1,Math.min((a-32)/S.width,(b-32)/S.height)>=.5||0===S.participants.length?q(a=>(a??0)+1):o({x:8,y:8,scale:.6}))},[S]);let ad=(0,i.useCallback)(async a=>{let b;if(l&&j){try{b=a(l)}catch(a){return v(a instanceof Error?a.message:String(a),"warn")}m(b);try{let a=await fetch(`/api/file${(0,dj.docQuery)(j)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(b,null,2)+"\n"})});if(!a.ok)throw Error((await a.json())?.error??`HTTP ${a.status}`);K.current?.emitFull(b),v("saved")}catch(a){return v(`not saved: ${a instanceof Error?a.message:String(a)}`,"warn")}if(f?.def&&U){if("auto"===aN(f.def)){let{result:a,failed:b,conflicts:d}=await eh(f.path);if(a&&a.count>0){var c;return void(c=b.length?`auto: not written — ${b[0]}`:d.length?`auto: ${d.join(", ")} kept changing on disk; not written — save again`:bd(a,"auto"),window.dispatchEvent(new CustomEvent(dO,{detail:{text:c,origin:void 0}})))}}ec()}}},[l,j,v,f,U]),ae=a=>{let{width:b,height:c}=_();o(d=>P(d,a,{x:b/2,y:c/2}))},af=()=>{let a,b,c,d,e,f,g,h,i;l&&navigator.clipboard?.writeText((a=["sequenceDiagram"],b=new Map,(l.participants??[]).forEach((c,d)=>{let e=`p${d+1}`;b.set(c.name,e),a.push(` ${c.actor?"actor":"participant"} ${e} as ${aL(c.name)}`)}),c=a=>b.get(a)??aL(a).replace(/\W+/g,"_"),d=(a,b,d)=>{let e=a.reply?"-->>":"->>",f=[`${b} ${aL(a.label??"")}`,a.event?aL(a.event):""].filter(Boolean).join(" · "),g=`${d}${c(a.from)}${e}${c(a.to)}: ${f}`;return a.optional?[`${d}opt optional`,` ${g}`,`${d}end`]:[g]},e=l.messages??[],f=l.fragments??[],g=a=>f.filter(b=>b?.after===a),h=(b,c)=>(b.messages??[]).forEach((e,g)=>a.push(...d(e,`f${f.indexOf(b)+1}.${g+1}`,c+" "))),(i=(b,c,f)=>{for(let j=b;j<=e.length;j++){let b=j===f?[]:g(j);for(let d of b.filter(a=>"alt"!==a.kind))a.push(`${c}${d.kind} ${aL(d.label??"")}`),h(d,c),a.push(`${c}end`);let k=b.filter(a=>"alt"===a.kind);if(k.length){k.forEach((b,d)=>{a.push(`${c}${0===d?"alt":"else"} ${aL(b.label??"")}`),h(b,c)}),j<e.length&&(a.push(`${c}else as written`),i(j,c+" ",j)),a.push(`${c}end`);return}j<e.length&&a.push(...d(e[j],String(j+1),c))}})(0," ",null),a.join("\n")+"\n")).then(()=>v("mermaid copied"))},ag=a=>{let b=a?a7(a):null;if(!b||"message"!==b.kind&&"participant"!==b.kind)return;let c={kind:b.kind,id:b.name};ac(c),ab(c),H.close()},ah=Q??av("",""),ai=ay(ah),aj=l&&r?.kind==="message"?ax(ah,r.id):null,ak=l&&r?.kind==="participant"?ah.participants.find(a=>a.name===r.id)??null:null,al=ah.participants.map(a=>a.name),am=j.split("/").pop()||"…",an=T.length+W.filter(a=>"error"===a.severity).length,ao=W.filter(a=>"warning"===a.severity).length,aq=[{id:"participants",label:"Participants",icon:(0,h.jsx)(d7,{kind:"actor"})},{id:"messages",label:"Messages",icon:(0,h.jsx)(d7,{kind:"sequence"})},{id:"notes",label:"Notes",icon:"✎"},{id:"issues",label:"Issues",icon:(0,h.jsx)(dJ,{}),badge:an+ao||void 0}],ar=a=>[{name:"from",label:"from",options:al,initial:a?.from??al[0]??""},{name:"to",label:"to",options:al,initial:a?.to??al[1]??al[0]??""},{name:"label",label:"label",placeholder:"what is said or done",initial:a?.label??"",wide:!0},{name:"event",label:"event it fires",suggest:Y.events,initial:a?.event??""},{name:"state",label:"state after",suggest:Y.states,initial:a?.state??""},{name:"carries",label:"entity it carries",suggest:Y.entities,initial:a?.carries??""},{name:"machine",label:"machine",suggest:Y.machines,initial:a?.machine??""},{name:"optional",label:"optional",checkbox:!0,initial:!!a?.optional},{name:"reply",label:"reply (dashed)",checkbox:!0,initial:!!a?.reply}],as=a=>a.actor?"actor":a.object?"object":a.service?"service":"",aw=["main: at the end",...aj&&null===aj.fragment?[`main: after ${aj.index+1}`]:[],...(l?.fragments??[]).map((a,b)=>`fragment ${b+1}: ${a.kind} \xb7 ${a.label}`)];return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&D(!1),children:[(0,h.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,h.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,h.jsx)(d7,{kind:"sequence",size:14}),"SEQ"]}),(0,h.jsx)(dk,{}),(0,h.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:j,children:[l?.settings.name??am,(0,h.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",am]})]}),(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,h.jsx)("button",{className:d4,onClick:af,children:"Copy mermaid"}),(0,h.jsx)("button",{className:d4,onClick:()=>F(a=>!a),"aria-pressed":!E,title:E?"Show the panel":"Hide the panel — the board takes the full width",children:E?"⟨ Panel":"Panel ⟩"})]}),(0,h.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,h.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":C,onClick:a=>{a.stopPropagation(),D(a=>!a)},children:"⋯"}),C&&(0,h.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:(0,h.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{D(!1),af()},children:"Copy as mermaid"})})]})]}),(0,h.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,h.jsxs)("div",{ref:G,className:"relative min-w-0 flex-1 overflow-hidden",children:[l&&S&&(0,h.jsx)(dI,{what:"sequence",resetKey:l,children:(0,h.jsx)(bB,{definition:Q,layout:S,viewport:n,onViewportChange:o,selection:r,errorElements:Z,warningElements:$,fitKey:p,onSelect:(a,b)=>ac({kind:a,id:b}),onClearSelection:()=>s(null),emptyHint:"No participants yet — add them in the panel, or let an agent write the scenario."})}),(0,h.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 flex max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===t.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,h.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===t.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,h.jsxs)("span",{className:`truncate transition-opacity duration-500 ${w&&"ok"===t.tone?"opacity-0":"opacity-100"}`,children:[t.text,I>1?` \xb7 ${I} in the room`:""]})]}),(0,h.jsx)("div",{className:"absolute bottom-3 right-3 flex flex-col overflow-hidden rounded-lg border border-gray-700 bg-gray-900/90 shadow-lg backdrop-blur",children:[["+","Zoom in",()=>ae(1.25)],["−","Zoom out",()=>ae(.8)],["⛶","Fit the whole diagram",()=>q(a=>(a??0)+1)]].map(([a,b,c])=>(0,h.jsx)("button",{title:b,"aria-label":b,onClick:c,className:"h-10 w-10 border-b border-gray-800 text-base leading-none text-gray-200 last:border-b-0 hover:bg-gray-800 md:h-8 md:w-8 md:text-sm",children:a},b))}),r&&!A&&(0,h.jsxs)("button",{className:"absolute bottom-3 left-1/2 max-w-[60%] -translate-x-1/2 truncate rounded-full border border-blue-500/60 bg-gray-900/95 px-4 py-2 text-sm text-blue-200 shadow-lg md:hidden",onClick:()=>{z("message"===r.kind?"messages":"participants"),B(!0)},children:["Edit ","message"===r.kind?`${r.id}. ${aj?.message.label??""}`:r.id]})]}),A&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:H.close,"aria-hidden":"true"}),l&&(0,h.jsxs)("aside",{style:H.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${A?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${E?"md:hidden":""}`,children:[(0,h.jsxs)("div",{className:"md:hidden",...H.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:aq.find(a=>a.id===y)?.label}),(0,h.jsx)("button",{onClick:H.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:aq.map(a=>(0,h.jsxs)("button",{onClick:()=>z(a.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${y===a.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[a.label,void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:a.badge})]},a.id))}),(0,h.jsx)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:(0,h.jsxs)(dI,{what:"panel",resetKey:l,children:[(0,h.jsxs)("section",{className:"participants"===y?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Participants"}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:ah.participants.map(a=>(0,h.jsxs)("button",{className:`${d4} ${r?.kind==="participant"&&r.id===a.name?"border-blue-500 text-blue-300":""}`,onClick:()=>{ac({kind:"participant",id:a.name}),ab({kind:"participant",id:a.name})},title:as(a)||"participant",children:[a.name,as(a)&&(0,h.jsxs)("span",{className:"text-gray-500",children:[" · ",as(a)]})]},a.name))}),(0,h.jsx)(d6,{id:"add-participant",reset:!0,required:["name"],fields:[{name:"name",placeholder:"new participant"},{name:"kind",options:ei,label:"kind"},{name:"value",placeholder:"actor / service / object",suggest:[...Y.actors,...Y.objects]},{name:"holds",placeholder:"holds: Entity, Entity",suggest:Y.entities}],submit:"+ Participant",onSubmit:a=>{let b=ej(a.name),c=ej(a.kind);ad(d=>(function(a,b,c){if(!b.name?.trim())throw Error("A participant needs a name.");let d=aA(a);if(d.participants.some(a=>a.name===b.name))throw Error(`Participant '${b.name}' already exists.`);let e=d.participants.length;return d.participants.splice(e,0,aB({...b})),d})(d,{name:b,...c?{[c]:ej(a.value)||b}:{},holds:ek(a.holds)})),ac({kind:"participant",id:b})}}),ak&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:`${d5} flex items-center justify-between gap-2`,children:[(0,h.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:ak.name}),(0,h.jsx)("button",{className:`${d4} normal-case tracking-normal`,onClick:()=>ab({kind:"participant",id:ak.name}),children:"◎ Show on board"})]}),(a=ah.participants.findIndex(a=>a.name===ak.name),b=ah.participants.length-1,c=a=>ad(b=>{var c;let d,e;return c=ak.name,e=aC(d=aA(b),c),d.participants.splice(d.participants.indexOf(e),1),d.participants.splice(Math.max(0,Math.min(a,d.participants.length)),0,e),d}),(0,h.jsxs)("div",{className:"mb-1 flex items-center gap-1 text-[11px] text-gray-400",children:[(0,h.jsx)("button",{className:`${d4} disabled:opacity-40`,disabled:a<=0,onClick:()=>c(a-1),"aria-label":"Move one column left",children:"← Left"}),(0,h.jsxs)("span",{className:"flex-1 text-center",children:["column ",a+1," of ",b+1]}),(0,h.jsx)("button",{className:`${d4} disabled:opacity-40`,disabled:a>=b,onClick:()=>c(a+1),"aria-label":"Move one column right",children:"Right →"})]})),(0,h.jsx)(d6,{id:"rename-participant",required:["to"],fields:[{name:"to",label:"new name",initial:ak.name}],submit:"Rename (every message follows)",onSubmit:a=>{let b=ej(a.to);b!==ak.name&&(ad(a=>(function(a,b,c){if(!c?.trim())throw Error("A participant needs a name.");let d=aA(a),e=aC(d,b);if(c===b)return d;if(d.participants.some(a=>a.name===c))throw Error(`Participant '${c}' already exists.`);e.name=c;let f=a=>{a.from===b&&(a.from=c),a.to===b&&(a.to=c)};for(let a of(d.messages.forEach(f),d.fragments??[]))a.messages.forEach(f);return d})(a,ak.name,b)),ac({kind:"participant",id:b}))}},`rename:${ak.name}`),(0,h.jsx)(d6,{id:"edit-participant",fields:[{name:"kind",options:ei,label:"kind",initial:as(ak)},{name:"value",placeholder:"actor / service / object",suggest:[...Y.actors,...Y.objects],initial:ak.actor??ak.object??ak.service??""},{name:"holds",placeholder:"holds: Entity, Entity",suggest:Y.entities,initial:(ak.holds??[]).join(", "),wide:!0},{name:"description",placeholder:"description",initial:ak.description??"",wide:!0}],submit:"Save participant",onSubmit:a=>ad(b=>{let c,d;return aF(b,ak.name,{...(c=ej(a.kind),d=ej(a.value)||ak.name,{actor:"actor"===c?d:"",service:"service"===c?d:"",object:"object"===c?d:""}),holds:ek(a.holds),description:ej(a.description)})})},`p:${JSON.stringify(ak)}`),(0,h.jsxs)("button",{className:`${d4} mt-2 text-red-300`,onClick:()=>{ad(a=>{var b;let c,d;return b=ak.name,aC(c=aA(a),b),c.participants=c.participants.filter(a=>a.name!==b),d=a=>a.from!==b&&a.to!==b,c.messages=c.messages.filter(d),c.fragments&&(c.fragments=c.fragments.map(b=>{let c;return{...b,after:Math.max(0,b.after-(c=b.after,a.messages.slice(0,c).filter(a=>!d(a)).length)),messages:b.messages.filter(d)}}).filter(a=>a.messages.length>0),c.fragments.length||delete c.fragments),c}),s(null),dR(null)},title:"Also removes every message it sends or receives",children:["Delete ",ak.name," and its messages"]})]})]}),(0,h.jsxs)("section",{className:"messages"===y?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Messages"}),0===ai.length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),(0,h.jsx)("div",{className:"flex flex-col",children:ai.map(({ref:a,message:b,fragment:c},d)=>{let e=null!==c&&(0===d||ai[d-1].fragment!==c),f=null!==c?ah.fragments?.[c]:void 0,g=r?.kind==="message"&&r.id===a;return(0,h.jsxs)("div",{children:[e&&f&&(0,h.jsxs)("div",{className:"mt-2 border-t border-gray-800 pt-1 text-[11px] text-indigo-300",children:[(0,h.jsx)("span",{className:"font-semibold",children:f.kind})," · after ",f.after," · ",f.label]}),(0,h.jsxs)("button",{className:`block w-full truncate rounded px-1 py-0.5 text-left text-[11px] ${g?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>{ac({kind:"message",id:a}),ab({kind:"message",id:a})},title:`${b.from} → ${b.to}: ${b.label}`,children:[(0,h.jsxs)("span",{className:"text-gray-500",children:[a,"."]})," ",b.from," → ",b.to,": ",b.label,b.event?(0,h.jsxs)("span",{className:"text-blue-300",children:[" [",b.event,"]"]}):null,b.state?(0,h.jsxs)("span",{className:"text-emerald-400",children:[" → ",b.state]}):null,b.optional?(0,h.jsx)("span",{className:"text-gray-500",children:" opt"}):null]})]},a)})}),aj&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:`${d5} flex items-center justify-between gap-2`,children:[(0,h.jsxs)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:["Message ",r.id]}),(0,h.jsxs)("span",{className:"flex gap-1 normal-case tracking-normal",children:[null===aj.fragment&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("button",{className:d4,"aria-label":"Move up",title:"Move up",disabled:0===aj.index,onClick:()=>{ad(a=>aI(a,aj.index,aj.index-1)),ac({kind:"message",id:String(aj.index)})},children:"↑"}),(0,h.jsx)("button",{className:d4,"aria-label":"Move down",title:"Move down",disabled:aj.index>=ah.messages.length-1,onClick:()=>{ad(a=>aI(a,aj.index,aj.index+1)),ac({kind:"message",id:String(aj.index+2)})},children:"↓"})]}),(0,h.jsx)("button",{className:d4,onClick:()=>ab(r),children:"◎ Show"})]})]}),(0,h.jsx)(d6,{id:"edit-message",required:["label"],fields:[...ar(aj.message),{name:"description",placeholder:"description",initial:aj.message.description??"",wide:!0}],submit:"Save message",onSubmit:a=>ad(b=>aH(b,aj.index,el(a),aj.fragment))},`m:${r.id}:${JSON.stringify(aj.message)}`),(0,h.jsxs)("button",{className:`${d4} mt-2 text-red-300`,onClick:()=>{ad(a=>(function(a,b,c=null){let d=aA(a);if(null!==c){let a=aE(d,c);if(!a.messages[b])throw Error(`Message ${b+1} not found in fragment ${c+1}.`);return a.messages.splice(b,1),d}if(!d.messages[b])throw Error(`Message ${b+1} not found. The sequence has ${d.messages.length}.`);if(d.messages.splice(b,1),d.fragments)for(let a of d.fragments)a.after>b&&(a.after-=1);return d})(a,aj.index,aj.fragment)),s(null),dR(null)},children:["Delete message ",r.id]})]}),(0,h.jsx)("div",{className:d5,children:"Add a message"}),(0,h.jsx)(d6,{id:"add-message",reset:!0,required:["label"],fields:[{name:"where",options:aw,label:"where",wide:!0},...ar()],submit:"+ Message",onSubmit:a=>{let b=ej(a.where),c=el(a),d=/^fragment (\d+):/.exec(b),e=/^main: after (\d+)$/.exec(b);d?ad(a=>{var b;let e,f,g;return b=Number(d[1])-1,f=aE(e=aA(a),b),aD(e,c),g=f.messages.length,f.messages.splice(g,0,aB({...c})),e}):e?ad(a=>aG(a,c,Number(e[1]))):ad(a=>aG(a,c))}},`add:${aw.join("|")}:${al.join("|")}`),(0,h.jsx)("div",{className:d5,children:"Fragments"}),0===(ah.fragments??[]).length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None."}),(ah.fragments??[]).map((a,b)=>(0,h.jsxs)("div",{className:"mb-2 rounded border border-gray-800 p-1.5",children:[(0,h.jsxs)("div",{className:"flex items-center justify-between text-[11px] text-indigo-300",children:[(0,h.jsxs)("span",{children:[b+1,". ",(0,h.jsx)("span",{className:"font-semibold",children:a.kind})," · after ",a.after," · ",a.messages.length," message(s)"]}),(0,h.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove fragment ${b+1}`,onClick:()=>ad(a=>{let c;return aE(c=aA(a),b),c.fragments.splice(b,1),c.fragments.length||delete c.fragments,c}),children:"✕"})]}),(0,h.jsx)(d6,{id:`edit-fragment-${b}`,fields:[{name:"kind",options:at,initial:a.kind},{name:"after",placeholder:"after message",initial:String(a.after)},{name:"label",placeholder:"the condition, in words",initial:a.label,wide:!0}],submit:"Save fragment",onSubmit:a=>ad(c=>(function(a,b,c){let d=aA(a),e=aE(d,b);if(void 0!==c.kind&&!at.includes(c.kind))throw Error(`A fragment is one of ${at.join(", ")}; got '${c.kind}'.`);if(void 0!==c.after&&(!Number.isInteger(c.after)||c.after<0||c.after>d.messages.length))throw Error(`A fragment branches after a main message, 0 to ${d.messages.length}; got ${c.after}.`);return d.fragments[b]={...aB({...e,...c,messages:void 0}),messages:e.messages??[]},d})(c,b,{kind:ej(a.kind),after:Number(ej(a.after)),label:ej(a.label)}))})]},`${b}:${JSON.stringify({...a,messages:void 0})}`)),(0,h.jsx)(d6,{id:"add-fragment",reset:!0,required:["label"],fields:[{name:"kind",options:at},{name:"after",placeholder:"after message",initial:String(aj&&null===aj.fragment?aj.index+1:ah.messages.length)},{name:"label",placeholder:"the condition, in words",wide:!0},{name:"from",options:al,label:"first message from"},{name:"to",options:al,label:"to",initial:al[1]??al[0]??""},{name:"first",placeholder:"first message label (optional)",wide:!0}],submit:"+ Fragment",onSubmit:a=>ad(b=>(function(a,b){if(!at.includes(b.kind))throw Error(`A fragment is one of ${at.join(", ")}; got '${b.kind}'.`);if(!b.label?.trim())throw Error("A fragment needs a label: the condition in words.");let c=aA(a);if(!Number.isInteger(b.after)||b.after<0||b.after>c.messages.length)throw Error(`A fragment branches after a main message, 0 to ${c.messages.length}; got ${b.after}.`);for(let a of b.messages??[])aD(c,a);return(c.fragments??=[]).push({...aB({...b,messages:void 0}),messages:(b.messages??[]).map(a=>aB({...a}))}),c})(b,{kind:ej(a.kind),after:Number(ej(a.after)),label:ej(a.label),messages:ej(a.first)?[{from:ej(a.from),to:ej(a.to),label:ej(a.first)}]:[]}))},`add-fragment:${ah.messages.length}:${aj?.index??""}`)]}),(0,h.jsxs)("section",{className:"notes"===y?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Notes"}),(0,h.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the document, for whoever opens it next — you, or an agent."}),(0,h.jsx)(d1,{label:"On this sequence",value:l.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:a=>ad(b=>{var c;let d;return c={notes:a},(d=aA(b)).settings=aB({...d.settings,...c}),d})},"sequence"),ak&&(0,h.jsx)(d1,{label:`On ${ak.name}`,value:ak.notes??"",placeholder:`A question or a decision about ${ak.name}…`,onSave:a=>ad(b=>aF(b,ak.name,{notes:a}))},`participant:${ak.name}`),aj&&(0,h.jsx)(d1,{label:`On message ${r.id}`,value:aj.message.notes??"",placeholder:"A question or a decision about this message…",onSave:a=>ad(b=>aH(b,aj.index,{notes:a},aj.fragment))},`message:${r.id}`),!r&&(0,h.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select a participant or a message to leave a note on it."}),[...ah.participants.filter(a=>a.notes?.trim()),...ai.filter(a=>a.message.notes?.trim())].length>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:d5,children:"With notes"}),(0,h.jsxs)("div",{className:"flex flex-wrap gap-1",children:[ah.participants.filter(a=>a.notes?.trim()).map(a=>(0,h.jsx)("button",{className:d4,onClick:()=>ag(`participant:${a.name}`),children:a.name},`p${a.name}`)),ai.filter(a=>a.message.notes?.trim()).map(a=>(0,h.jsxs)("button",{className:d4,onClick:()=>ag(`message:${a.ref}`),children:["message ",a.ref]},`m${a.ref}`))]})]})]}),(0,h.jsxs)("section",{className:"issues"===y?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Issues"}),T.map((a,b)=>(0,h.jsxs)("button",{className:"block w-full py-0.5 text-left text-[11px] text-red-300",onClick:()=>ag(a.element),children:["[",a.ruleId,"] ",a.message]},`p${b}`)),W.map((a,b)=>(0,h.jsxs)("button",{className:`block w-full py-0.5 text-left text-[11px] ${"error"===a.severity?"text-red-300":"text-amber-300"}`,onClick:()=>ag(a.element),children:["[",a.ruleId,"] ",a.message]},`s${b}`)),0===T.length&&0===W.length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-green-400",children:V?"Valid, and every name it uses resolves in the system.":"The document is valid."}),!e&&(0,h.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Open this sequence from its system to check it against the machines and the data."}),e&&!U&&f&&(0,h.jsx)("p",{className:"mt-2 text-[11px] text-amber-300",children:"This document is not a member of the open system."}),X&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:d5,children:["Replay against ",X.machines.join(", ")||"no machine"]}),X.paths.map(a=>(0,h.jsxs)("div",{className:"mb-2",children:[(0,h.jsxs)("div",{className:`text-[11px] font-semibold ${a.accepted?"text-green-400":"text-amber-300"}`,children:[a.name," — ",a.accepted?"accepted":"stops"]}),a.steps.filter(a=>"data"!==a.result).map(b=>(0,h.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===b.result||"stayed"===b.result?"text-gray-400":"text-amber-300"}`,title:b.note??b.result,onClick:()=>ag(`message:${b.ref}`),children:[b.ref,". ",b.event??""," ",b.from.join("|")||"·"," → ",b.to.join("|")||"·"," ",b.result]},`${a.name}:${b.ref}`))]},a.name))]})]})]})})]})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:aq.map(a=>{let b=A&&y===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(A&&y===b?H.close():B(!0),z(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})})]})}function en(a,b){let c=a?.members.find(a=>a.path===b)?.def;return c?.settings?.name||(b.split("/").pop()??b).replace(/\.(smdf|erdf|sqdf|sysdf)\.json$|\.json$/i,"")}let eo=(a,b)=>a?.members.find(a=>a.path===b)?.kind??"machine";function ep(a){return"message"===a.kind?`message ${a.name}`:`${a.kind} ${a.name}`}function eq({systemPath:a}){let b=dP("doc"),c=dP("focus"),{system:d}=ed(a),[e,f]=(0,i.useState)(!1),[g,j]=(0,i.useState)(null),k=(0,i.useRef)(d);(0,i.useEffect)(()=>{k.current=d},[d]);let l=(0,i.useMemo)(()=>d?dT(()=>a8(d.members),[]):[],[d]),m=ee(d,b),n=!!d&&(b===d.path||b===a),o=m&&c?function(a,b,c){let d=a7(c);if(!d)return[];let e=a=>a.member===b&&a.kind===d.kind&&a.name===d.name,f=[];for(let b of a)e(b.from)?f.push({other:b.to,text:b.text,rule:b.rule}):e(b.to)&&f.push({other:b.from,text:b.back,rule:b.rule});return f}(l,m,c):[],p=function(a,b){if(!b)return[];let c=new Map;for(let d of a)for(let a of[d.from,d.to]){if(a.member!==b)continue;let d=a6(a);c.set(d,(c.get(d)??0)+1)}return[...c.entries()].sort((a,b)=>a[0].localeCompare(b[0]))}(l,m);(0,i.useEffect)(()=>{let a=a=>{let b=a.detail;b?.text&&j({...b,at:Date.now()})};return window.addEventListener(dO,a),()=>window.removeEventListener(dO,a)},[]),(0,i.useEffect)(()=>{if(!g)return;let a=setTimeout(()=>j(null),9e3);return()=>clearTimeout(a)},[g]);let q=d?.path;(0,i.useEffect)(()=>{if(!q)return;let b=!0,c=null,d=null;return(async()=>{let{bridgeUrl:e}=await dt();if(b&&e){var g;let b,h,i,l;(c=cO({url:e,role:"web",docId:q,name:"web-system-strip"})).on("view",b=>{let c=k.current;if(!c)return;let d=b.member?void 0!==c.absOf[b.member]?b.member:Object.keys(c.absOf).find(a=>c.absOf[a]===b.member):void 0;if(b.member&&!d)return void j({text:`ignored a view of ${b.member.split("/").pop()}: it is not a member of this system`,origin:b.origin,at:Date.now()});dQ({doc:d?c.absOf[d]:q,system:a,focus:b.focus??null}),f(!1);let e=[d?en(c,d):"the system map",b.focus].filter(Boolean).join(" · ");j({text:b.note?b.note:`showing ${e}`,origin:b.origin,at:Date.now()})}),c.on("full",()=>ec()),g=c,b=!1,h=!1,i=()=>{g.join().then(()=>{b=!0}).catch(()=>{})},l=g.on("status",a=>{"connected"!==a?h=b:h&&(h=!1,i())}),i(),d=()=>{l()}}})(),()=>{b=!1,d?.(),c?.disconnect()}},[q,a]);let r=b=>{f(!1),d&&dQ({doc:b.member?d.absOf[b.member]??aU(d.path,b.member):d.path,system:a,focus:b.focus??null})},s=d?.def?.members?.filter(a=>a?.path).map(a=>a.path)??[],t=d?.def?.settings?.name??(a.split("/").pop()??"system").replace(/\.sysdf\.json$/i,""),u=o.length;return(0,h.jsxs)("div",{className:"system-strip relative z-50 border-b border-gray-800 bg-gray-950 text-xs text-gray-300",children:[(0,h.jsxs)("div",{className:"flex h-[var(--strip-h)] items-center gap-1 px-1.5 md:px-2",children:[(0,h.jsxs)("button",{onClick:()=>r({}),className:`flex min-w-0 max-w-[30%] shrink-0 items-center gap-1 rounded px-1.5 py-1 md:max-w-[16rem] ${n?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,title:`${a} — the system map`,children:[(0,h.jsx)(d7,{kind:"system",size:15}),(0,h.jsx)("span",{className:"truncate font-semibold",children:t})]}),(0,h.jsx)("span",{className:"h-4 w-px shrink-0 bg-gray-800"}),(0,h.jsxs)("nav",{className:"flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]","aria-label":"Members",children:[s.map(a=>{let b=a===m,c=d?.members.find(b=>b.path===a)?.error;return(0,h.jsxs)("button",{onClick:()=>r({member:a}),"aria-current":b?"page":void 0,title:`${en(d,a)} — ${a}${c?` (cannot be read: ${c})`:""}`,className:`flex shrink-0 items-center gap-1 rounded px-1.5 py-1 ${b?"bg-blue-950/60 text-blue-200":c?"text-red-400 hover:bg-gray-800":"text-gray-400 hover:bg-gray-800 hover:text-gray-200"}`,children:[(0,h.jsx)(d7,{kind:eo(d,a),size:15}),(0,h.jsx)("span",{className:`max-w-[7.5rem] truncate md:max-w-[11rem] ${b?"":"hidden md:inline"}`,children:en(d,a)})]},a)}),!d&&(0,h.jsx)("span",{className:"px-1 text-gray-600",children:"loading…"}),d?.error&&(0,h.jsx)("span",{className:"truncate px-1 text-amber-300",children:d.error})]}),(0,h.jsxs)("button",{onClick:()=>f(a=>!a),disabled:!m,"aria-expanded":e,title:m?c?`What ${c} links to in the other drawings`:"Elements of this drawing that link to the others":"Open a member to follow its links",className:`flex shrink-0 items-center gap-1 rounded px-1.5 py-1 disabled:opacity-40 ${e?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,children:[(0,h.jsx)(d7,{kind:"link",size:15}),(0,h.jsx)("span",{className:"hidden sm:inline",children:"Links"}),u>0&&(0,h.jsx)("span",{className:"rounded-full border border-gray-700 px-1 text-[10px] leading-4 text-gray-300",children:u})]})]}),g&&!e&&(0,h.jsx)("div",{className:"pointer-events-none absolute inset-x-0 top-full flex justify-center px-2 pt-1",role:"status",children:(0,h.jsxs)("span",{className:"max-w-full truncate rounded border border-gray-700 bg-gray-900/95 px-2 py-0.5 text-[11px] text-gray-300 shadow",children:[g.origin?(0,h.jsxs)("span",{className:"text-blue-300",children:[g.origin,": "]}):null,g.text]})}),e&&m&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:"fixed inset-0 z-40",onClick:()=>f(!1),"aria-hidden":"true"}),(0,h.jsxs)("div",{className:"absolute right-1 top-full z-50 mt-1 max-h-[60vh] w-[min(24rem,calc(100vw-0.5rem))] overflow-y-auto rounded-lg border border-gray-700 bg-gray-900 p-2 shadow-xl",children:[c&&a7(c)?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-gray-500",children:[(0,h.jsxs)("span",{className:"truncate",children:[(0,h.jsx)("span",{className:"text-gray-200",children:ep(a7(c))})," in ",en(d,m)]}),(0,h.jsx)("button",{className:"shrink-0 text-gray-500 hover:text-gray-200",onClick:()=>dQ({doc:b,focus:null}),children:"clear"})]}),0===o.length&&(0,h.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"Nothing in the other drawings names it."}),o.map((a,b)=>(0,h.jsxs)("button",{onClick:()=>r({member:a.other.member,focus:a6(a.other)}),className:"flex w-full items-start gap-2 rounded px-1.5 py-1.5 text-left hover:bg-gray-800",children:[(0,h.jsx)("span",{className:"mt-0.5 text-gray-400",children:(0,h.jsx)(d7,{kind:eo(d,a.other.member),size:14})}),(0,h.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,h.jsx)("span",{className:"block text-[12px] text-gray-200",children:a.text}),(0,h.jsxs)("span",{className:"block truncate text-[10.5px] text-gray-500",children:[ep(a.other)," · ",en(d,a.other.member)," · ",a.rule]})]})]},b))]}):null,(!c||!a7(c))&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["Elements of ",en(d,m)," that the other drawings name — pick one to follow it."]}),0===p.length&&(0,h.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"None."}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:p.map(([a,c])=>(0,h.jsxs)("button",{onClick:()=>{f(!0),dQ({doc:b,focus:a})},className:"rounded border border-gray-700 bg-gray-800 px-1.5 py-0.5 text-[11px] text-gray-200 hover:bg-gray-700",children:[a," ",(0,h.jsx)("span",{className:"text-gray-500",children:c})]},a))})]})]})]})]})}let er={erd:"ERD",machine:"STATE MACHINE",sequence:"SEQUENCE",system:"SYSTEM"};function es(a,b,c=!1){if(!b)return"";if("erd"===a)return`${b.entities?.length??0} entities \xb7 ${b.relationships?.length??0} relationships`;if("sequence"===a){let a=b.fragments?.length??0;return`${b.participants?.length??0} participants \xb7 ${b.messages?.length??0} messages${a&&!c?` \xb7 ${a} fragment${a>1?"s":""}`:""}`}let d=0,e=a=>{a&&(d+=1,(a.states??[]).forEach(e),(a.parallel?.states??[]).forEach(e))};(b.state?.states??[]).forEach(e),(b.state?.parallel?.states??[]).forEach(e);let f=(b.events??[]).reduce((a,b)=>a+(b?.events?.length??0)+(b?.timers?.length??0),0);return`${d} states \xb7 ${f} events`}let et=(a,b)=>a<b?`${a}\u0000${b}`:`${b}\u0000${a}`;function eu(a){let b="message"===a.from.kind?`message ${a.from.name}`:`${a.from.kind} ${a.from.name}`;return`${b} ${a.text}`}function ev(){let a=(0,dj.useRequestedDoc)(),[b,c]=(0,i.useState)(a);(0,i.useEffect)(()=>{let b=!0;if(a)c(a);else d8(null).then(a=>b&&c(a.path||null));return()=>{b=!1}},[a]);let{system:d,reload:e}=ed(b),[f,g]=(0,i.useState)("members"),[j,k]=(0,i.useState)(!1),[l,m]=(0,i.useState)(!1),[n,o]=(0,i.useState)(!1),[p,q]=(0,i.useState)(null),[r,s]=(0,i.useState)({text:"loading…",tone:"ok"}),t=(0,i.useCallback)((a,b="ok")=>s({text:a,tone:b}),[]),[u,v]=(0,i.useState)(!1),w=dL({onClose:()=>k(!1),restVh:62,tallVh:92}),x=(0,i.useRef)(null),[y,z]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=x.current;if(!a)return;let b=()=>{let b=a.getBoundingClientRect();b.width&&z(b.height>1.1*b.width)};b();let c=new ResizeObserver(b);return c.observe(a),()=>c.disconnect()},[]);let A=(0,i.useRef)(!1);(0,i.useEffect)(()=>{d&&(d.error?t(d.error,"warn"):A.current||t(`${d.members.length} member${1===d.members.length?"":"s"} loaded`),A.current=!0)},[d,t]);let[B,C]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=setTimeout(()=>C(!0),4e3);return()=>{clearTimeout(a),C(!1)}},[r]);let D=(0,i.useMemo)(()=>d?.def?dT(()=>a5(d.def,d.members),null):null,[d]),E=(0,i.useMemo)(()=>d?dT(()=>a8(d.members),[]):[],[d]),F=(0,i.useMemo)(()=>d?.def?dT(()=>bc(d.def,d.members),null):null,[d]),G=aN(d?.def),H=(0,i.useMemo)(()=>{let a=new Map;for(let b of E){if(b.from.member===b.to.member)continue;let c=et(b.from.member,b.to.member),d=a.get(c)??{a:c.split("\0")[0],b:c.split("\0")[1],links:[]};d.links.push(b),a.set(c,d)}return a},[E]),I=(D?.issues??[]).filter(a=>"error"===a.severity),J=(D?.issues??[]).filter(a=>"warning"===a.severity),K=(b,c)=>{d&&dQ({doc:d.absOf[b]??b,system:a??d.path,focus:c??null})},L=async(a,b)=>{if(d)try{await ea(d.path,a,d.mtimes[d.path]),t(b),ec()}catch(a){a instanceof d9?(t("the system changed on disk — reloaded; make the change again","warn"),ec()):t(`not saved: ${a instanceof Error?a.message:String(a)}`,"warn")}},M=async()=>{if(!d||!F||!F.count)return;v(!0);let{result:a,written:b,failed:c,conflicts:e}=await eh(d.path);v(!1),c.length?t(`not all written: ${c.join("; ")}`,"warn"):e.length?t(`${e.join(", ")} kept changing on disk — not written; apply again`,"warn"):a?.count?t(`${bd(a,"propose").replace(/ proposed/," applied")} — ${b.length} file(s) written`):t("nothing to apply: the drawings on disk already agree")},N=y?420:760,O=y?640:520,P=d?.def?.members?.filter(a=>a?.path).map(a=>a.path)??[],Q=d?.def?.actors??[],R=64*!!Q.length,S=(0,i.useMemo)(()=>{let a=P.length,b=N/2,c=(O-R)/2+6,d=Math.max(0,N/2-98-16),e=Math.max(0,(O-R)/2-46-18),f=new Map;return P.forEach((g,h)=>{if(1===a)return f.set(g,{x:b,y:c});if(y){let b=O-R-46-16;return f.set(g,{x:h%2?.67*N:.33*N,y:62+(b-62)*h/(a-1)})}if(2===a)return f.set(g,y?{x:b,y:h?c+e:c-e}:{x:h?b+d:b-d,y:c});let i=-Math.PI/2+2*h*Math.PI/a;f.set(g,{x:b+d*Math.cos(i),y:c+e*Math.sin(i)})}),f},[P.join("|"),N,O,196,R,y]),T=(0,i.useMemo)(()=>{let a=new Map;for(let{member:b,def:c}of a4(d?.members??[]).sequences)for(let d of c.participants??[]){if(!d?.actor)continue;let c=a.get(d.actor)??[];c.includes(b)||c.push(b),a.set(d.actor,c)}return a},[d]),U=d?.def,V=(d?.path??b??"").split("/").pop()||"…",W=[{id:"members",label:"Members",icon:(0,h.jsx)(d7,{kind:"system"})},{id:"checks",label:"Checks",icon:(0,h.jsx)(dJ,{}),badge:I.length+J.length||void 0},{id:"notes",label:"Notes",icon:"✎"}],X=p?H.get(p):void 0,Y=(0,i.useMemo)(()=>{let a=[];for(let b of["error","warning"]){let c=new Map;for(let a of D?.issues??[])a.severity===b&&c.set(a.ruleId,[...c.get(a.ruleId)??[],a]);for(let[d,e]of[...c.entries()].sort((a,b)=>a[0].localeCompare(b[0])))a.push({key:`${b}:${d}`,ruleId:d,severity:b,issues:e})}return a},[D]);return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>l&&m(!1),children:[(0,h.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,h.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,h.jsx)(d7,{kind:"system",size:14}),"SYS"]}),(0,h.jsx)(dk,{}),(0,h.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:d?.path,children:[U?.settings?.name??V,(0,h.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",V]})]}),(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,h.jsx)("button",{className:d4,onClick:e,title:"Read the system and every member again",children:"Re-check"}),(0,h.jsx)("button",{className:d4,onClick:()=>o(a=>!a),"aria-pressed":!n,children:n?"⟨ Panel":"Panel ⟩"})]}),(0,h.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,h.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":l,onClick:a=>{a.stopPropagation(),m(a=>!a)},children:"⋯"}),l&&(0,h.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:(0,h.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{m(!1),e()},children:"Re-check the system"})})]})]}),(0,h.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,h.jsxs)("div",{ref:x,className:"relative min-w-0 flex-1 overflow-hidden bg-[#030712]",children:[d&&U&&(0,h.jsx)(dI,{what:"system map",resetKey:d,children:(0,h.jsxs)("svg",{className:"h-full w-full",viewBox:`0 0 ${N} ${O}`,preserveAspectRatio:"xMidYMid meet",role:"img","aria-label":`System map of ${U.settings?.name}`,children:[[...H.entries()].map(([a,b])=>{let c=S.get(b.a),d=S.get(b.b);if(!c||!d)return null;let e=(c.x+d.x)/2,f=(c.y+d.y)/2,i=`${b.links.length} link${1===b.links.length?"":"s"}`,j=6.4*i.length+16,l=p===a;return(0,h.jsxs)("g",{className:"cursor-pointer",onClick:()=>{q(l?null:a),g("members"),k(!0)},children:[(0,h.jsx)("line",{x1:c.x,y1:c.y,x2:d.x,y2:d.y,stroke:"transparent",strokeWidth:18}),(0,h.jsx)("line",{x1:c.x,y1:c.y,x2:d.x,y2:d.y,stroke:l?"#3b82f6":"#475569",strokeWidth:l?2.5:1.6}),(0,h.jsx)("rect",{x:e-j/2,y:f-11,width:j,height:22,rx:11,fill:"#0f172a",stroke:l?"#3b82f6":"#334155"}),(0,h.jsx)("text",{x:e,y:f+4,textAnchor:"middle",fontSize:11.5,fill:l?"#93c5fd":"#cbd5e1",children:i})]},a)}),Q.map((a,b)=>{let c=(b+1)*N/(Q.length+1),d=O-30;return(0,h.jsxs)("g",{children:[(T.get(a.name)??[]).map(a=>{let b=S.get(a);return b?(0,h.jsx)("line",{x1:c,y1:d-14,x2:b.x,y2:b.y+46,stroke:"#334155",strokeDasharray:"3 4"},a):null}),(0,h.jsx)("title",{children:[`${a.kind}`,a.description??"",a.wheelNode??""].filter(Boolean).join(" — ")}),(0,h.jsx)("rect",{x:c-62,y:d-14,width:124,height:28,rx:14,fill:"#0c1020",stroke:"#6366f1"}),(0,h.jsx)("g",{transform:`translate(${c-54} ${d-8})`,color:"#a5b4fc",children:(0,h.jsx)(d7,{kind:"actor",size:16})}),(0,h.jsx)("text",{x:c-34,y:d-1,fontSize:11.5,fontWeight:600,fill:"#e2e8f0",children:a.name.length>12?`${a.name.slice(0,11)}…`:a.name}),(0,h.jsx)("text",{x:c-34,y:d+9,fontSize:8.5,fill:"#94a3b8",children:a.kind})]},a.name)}),P.map(a=>{let b=S.get(a),c=d.members.find(b=>b.path===a);if(!b||!c)return null;let e=c.kind,f=(D?.issues??[]).filter(b=>b.member===a),g=f.filter(a=>"error"===a.severity).length,i=f.filter(a=>"warning"===a.severity).length,j=b.x-98,k=b.y-46,l=en(d,a),m=X&&(X.a===a||X.b===a);return(0,h.jsxs)("g",{className:"cursor-pointer",onClick:()=>K(a),children:[(0,h.jsx)("title",{children:`${a}${c.error?` — cannot be read: ${c.error}`:""}
12
- Tap to open it inside the system.`}),(0,h.jsx)("rect",{x:j,y:k,width:196,height:92,rx:10,fill:"#0f172a",stroke:c.error?"#ef4444":m?"#3b82f6":g?"#b91c1c":"#475569",strokeWidth:m?2.2:1.5,strokeDasharray:c.error?"5 4":void 0}),(0,h.jsx)("g",{transform:`translate(${j+10} ${k+9})`,color:"#93c5fd",children:(0,h.jsx)(d7,{kind:e,size:16})}),(0,h.jsx)("text",{x:j+32,y:k+21,fontSize:9,fontWeight:700,letterSpacing:"0.06em",fill:"#64748b",children:er[e]}),(0,h.jsx)("text",{x:j+10,y:k+43,fontSize:14,fontWeight:600,fill:"#e2e8f0",children:l.length>22?`${l.slice(0,21)}…`:l}),(0,h.jsx)("text",{x:j+10,y:k+60,fontSize:10.5,fill:"#94a3b8",children:c.error?"cannot be read":es(e,c.def,!0)}),(0,h.jsx)("text",{x:j+10,y:k+79,fontSize:10.5,fill:g?"#fca5a5":i?"#fcd34d":"#4ade80",children:c.error?c.error.length>30?`${c.error.slice(0,29)}…`:c.error:g||i?[g?`${g} error${g>1?"s":""}`:"",i?`${i} warning${i>1?"s":""}`:""].filter(Boolean).join(" · "):"checks pass"}),(0,h.jsx)("text",{x:j+196-10,y:k+79,fontSize:10.5,textAnchor:"end",fill:"#64748b",children:"open ›"})]},a)})]})}),d&&!U&&(0,h.jsx)("div",{className:"absolute inset-0 flex items-center justify-center p-6 text-center text-sm text-amber-300",children:d.error}),(0,h.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 flex max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===r.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,h.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===r.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,h.jsx)("span",{className:`truncate transition-opacity duration-500 ${B&&"ok"===r.tone?"opacity-0":"opacity-100"}`,children:r.text})]})]}),j&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:w.close,"aria-hidden":"true"}),d&&U&&(0,h.jsxs)("aside",{style:w.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${j?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-96 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${n?"md:hidden":""}`,children:[(0,h.jsxs)("div",{className:"md:hidden",...w.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:W.find(a=>a.id===f)?.label}),(0,h.jsx)("button",{onClick:w.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:W.map(a=>(0,h.jsxs)("button",{onClick:()=>g(a.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${f===a.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[a.label,void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:a.badge})]},a.id))}),(0,h.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,h.jsxs)("section",{className:"members"===f?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Members"}),P.map(a=>{let b=d.members.find(b=>b.path===a),c=U.members.find(b=>b.path===a)?.notes;return(0,h.jsxs)("div",{className:"mb-1 rounded border border-gray-800",children:[(0,h.jsxs)("button",{onClick:()=>K(a),className:"flex w-full items-start gap-2 p-2 text-left hover:bg-gray-800",children:[(0,h.jsx)("span",{className:"mt-0.5 text-blue-300",children:(0,h.jsx)(d7,{kind:b?.kind??"machine"})}),(0,h.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,h.jsx)("span",{className:"block truncate text-[12px] font-semibold text-gray-200",children:en(d,a)}),(0,h.jsx)("span",{className:"block truncate text-[10.5px] text-gray-500",children:a}),(0,h.jsx)("span",{className:`block text-[11px] ${b?.error?"text-red-300":"text-gray-400"}`,children:b?.error?`cannot be read: ${b.error}`:es(b?.kind??"machine",b?.def)})]}),(0,h.jsx)("span",{className:"shrink-0 text-[11px] text-gray-500",children:"open ›"})]}),(0,h.jsx)("div",{className:"px-2 pb-2 [&_label]:mt-0",children:(0,h.jsx)(d1,{label:"Note on this member, in the system",value:c??"",placeholder:`Why ${en(d,a)} is part of this system, what is open…`,onSave:b=>void L(function(a,b,c){let d=aW(a),e=d.members.findIndex(a=>a.path===b);if(e<0)throw Error(`'${b}' is not a member. Members: ${a.members.map(a=>a.path).join(", ")||"none"}.`);return d.members[e]=aX({...d.members[e],...c}),d}(U,a,{notes:b}),"saved")},`member:${a}`)})]},a)}),(0,h.jsx)("div",{className:d5,children:"Links between members"}),0===H.size&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"No name crosses between the members yet."}),[...H.entries()].map(([a,b])=>(0,h.jsxs)("div",{className:"mb-1",children:[(0,h.jsxs)("button",{className:`flex w-full items-center justify-between rounded px-1.5 py-1 text-left text-[11px] ${p===a?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>q(p===a?null:a),children:[(0,h.jsxs)("span",{className:"truncate",children:[en(d,b.a)," ↔ ",en(d,b.b)]}),(0,h.jsx)("span",{className:"shrink-0 text-gray-500",children:b.links.length})]}),p===a&&(0,h.jsx)("div",{className:"ml-2 border-l border-gray-800 pl-2",children:b.links.map((a,b)=>(0,h.jsxs)("button",{className:"block w-full truncate py-0.5 text-left text-[11px] text-gray-400 hover:text-gray-200",title:`${eu(a)} — ${a.rule}`,onClick:()=>{let b;return K((b=a.from).member,a6(b))},children:[(0,h.jsx)("span",{className:"text-gray-600",children:a.rule})," ",eu(a)]},b))})]},a)),Q.length>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:d5,children:"Actors"}),Q.map(a=>(0,h.jsxs)("div",{className:"py-0.5 text-[11px] text-gray-300",children:[a.name," ",(0,h.jsxs)("span",{className:"text-gray-500",children:["· ",a.kind]}),a.description?(0,h.jsxs)("span",{className:"text-gray-500",children:[" — ",a.description]}):null]},a.name))]})]}),(0,h.jsxs)("section",{className:"checks"===f?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Checks"}),(0,h.jsxs)("div",{className:`text-[11px] ${I.length?"text-red-300":J.length?"text-amber-300":"text-green-400"}`,children:[I.length," error",1===I.length?"":"s"," · ",J.length," warning",1===J.length?"":"s"]}),Y.map(a=>(0,h.jsxs)("div",{className:"mt-2",children:[(0,h.jsxs)("div",{className:`text-[11px] font-semibold ${"error"===a.severity?"text-red-300":"text-amber-300"}`,children:[a.ruleId," · ",a.issues.length," ",a.severity,1===a.issues.length?"":"s"]}),a.issues.map((a,b)=>(0,h.jsxs)("button",{className:"block w-full py-0.5 pl-2 text-left text-[11px] text-gray-300 hover:text-white",onClick:()=>{a.member&&K(a.member,a.element&&/^[a-z]+:/.test(a.element)?a.element:null)},title:a.member?`Open ${a.member}${a.element?` at ${a.element}`:""}`:void 0,children:[a.message,a.member&&(0,h.jsxs)("span",{className:"text-gray-500",children:[" — ",en(d,a.member)]})]},b))]},a.key)),(0,h.jsx)("div",{className:d5,children:"Reconcile"}),(0,h.jsxs)("p",{className:"mb-1 text-[11px] text-gray-500",children:["What the scenarios imply for the machines and the data. ",(0,h.jsx)("b",{className:"text-gray-400",children:"propose"})," lists it here to apply by hand; ",(0,h.jsx)("b",{className:"text-gray-400",children:"auto"})," writes it each time a scenario is saved."]}),(0,h.jsx)("span",{className:"inline-flex overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Reconcile mode",children:aM.map(a=>(0,h.jsx)("button",{"aria-pressed":G===a,onClick:()=>{d?.def&&a!==G&&L(function(a,b){if(!aM.includes(b))throw Error(`The reconcile mode is ${aM.join(" or ")}; got '${b}'.`);return aY(a,{reconcile:b})}(d.def,a),`reconcile mode: ${a}`)},className:`px-3 py-1 text-xs ${G===a?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:a},a))}),(0,h.jsx)("div",{className:"mt-2 text-[11px] font-semibold text-gray-400",children:"Scenario changes"}),F&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:"text-[11px] text-gray-500",children:bd(F,"propose")}),F.machines.map(a=>(0,h.jsxs)("div",{className:"mt-1",children:[(0,h.jsxs)("div",{className:"text-[11px] text-gray-300",children:[a.machine," ",(0,h.jsxs)("span",{className:"text-gray-500",children:["· ",a.member]})]}),a.reasons.map((a,b)=>(0,h.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",a]},b))]},a.member)),F.erds.map(a=>(0,h.jsxs)("div",{className:"mt-1",children:[(0,h.jsxs)("div",{className:"text-[11px] text-gray-300",children:[a.def.settings?.name??a.member," ",(0,h.jsxs)("span",{className:"text-gray-500",children:["· ",a.member]})]}),a.reasons.map((a,b)=>(0,h.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",a]},b))]},a.member)),F.system&&(0,h.jsxs)("div",{className:"mt-1",children:[(0,h.jsx)("div",{className:"text-[11px] text-gray-300",children:"the system"}),F.system.reasons.map((a,b)=>(0,h.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",a]},b))]}),F.unresolved.map((a,b)=>(0,h.jsxs)("div",{className:"mt-1 text-[11px] text-amber-300",children:["left open: ",a]},b)),(0,h.jsx)("button",{className:`${d4} mt-2 disabled:opacity-40`,disabled:!F.count||u,onClick:M,children:u?"Applying…":`Apply${F.count?` ${F.count} change${1===F.count?"":"s"}`:""}`})]}),(D?.replays??[]).map(({member:a,report:b})=>(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:d5,children:["Replay · ",en(d,a)]}),(0,h.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["against ",b.machines.join(", ")||"no machine"]}),b.paths.map(b=>(0,h.jsxs)("div",{className:"mb-2",children:[(0,h.jsxs)("div",{className:`text-[11px] font-semibold ${b.accepted?"text-green-400":"text-amber-300"}`,children:[b.name," — ",b.accepted?"accepted":"stops"]}),b.steps.filter(a=>"data"!==a.result).map(c=>(0,h.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===c.result||"stayed"===c.result?"text-gray-400":"text-amber-300"}`,title:c.note??c.result,onClick:()=>K(a,`message:${c.ref}`),children:[c.ref,". ",c.event??""," ",c.from.join("|")||"·"," → ",c.to.join("|")||"·"," ",c.result]},`${b.name}:${c.ref}`))]},b.name))]},a))]}),(0,h.jsxs)("section",{className:"notes"===f?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Notes"}),(0,h.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the system file, for whoever opens it next."}),(0,h.jsx)(d1,{label:"On this system",value:U.settings?.notes??"",placeholder:"What the system is for, what is still open…",onSave:a=>void L(aY(U,{notes:a}),"saved")},"system"),U.settings?.description&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:d5,children:"Description"}),(0,h.jsx)("p",{className:"text-[11px] text-gray-400",children:U.settings.description})]})]})]})]})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:W.map(a=>{let b=j&&f===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(j&&f===b?w.close():k(!0),g(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})})]})}let ew=a=>a.parallel?a.parallel.states:a.states??[];function ex(a,b){if(!a)return null;if(a.name===b)return[a.name];for(let c of ew(a)){let d=ex(c,b);if(d)return[a.name,...d]}return null}function ey(){let a=(0,dj.useRequestedDoc)(),b=dP("system"),[c,d]=(0,i.useState)(null);(0,i.useEffect)(()=>{let a=!0;return dt().then(b=>{a&&d(b.projectFile?aR(b.projectFile):"machine")}),()=>{a=!1}},[]);let e=a?aR(a):c;if(null===e)return(0,h.jsx)("div",{className:"app-shell bg-gray-950"});let f=a??"default",g="erd"===e?(0,h.jsx)(d0,{},f):"sequence"===e?(0,h.jsx)(em,{},f):"system"===e?(0,h.jsx)(ev,{},f):(0,h.jsx)(ez,{}),j=(0,h.jsx)(dI,{what:"document",resetKey:a,children:g});return b&&aP(b)?(0,h.jsxs)("div",{className:"system-frame",children:[(0,h.jsx)(eq,{systemPath:b}),j]}):j}function ez(){let a,b;a=dS(),b=(0,i.useRef)(null),(0,i.useEffect)(()=>{let c=()=>{let a=b.current;if(!a)return;let c=c_.getState(),d=null;if(d&&c.docPath!==d||a.docAt!==c.docPath&&c.definition===a.defAt)return;b.current=null;let e=a7(a.focus);if(!e)return;let f=null,g=null;if("state"===e.kind)(f=ex(c.definition.state,e.name))&&(g={kind:"state",id:e.name});else if("event"===e.kind){let a=function a(b,c){if(!b)return null;let d=(b.transitions??[]).findIndex(a=>a?.event===c);if(d>=0)return{state:b.name,index:d};for(let d of ew(b)){let b=a(d,c);if(b)return b}return null}(c.definition.state,e.name);a&&(f=ex(c.definition.state,a.state),g={kind:"transition",id:`${a.state}:${a.index}`})}if(!f||!g)return;let h=f.length>1?f.slice(0,-1):f;c_.setState({navigationPath:h,currentParent:h[h.length-1]}),c.select(g.kind,g.id);let i=()=>{let a=c_.getState().layout.positions[f[f.length-1]],b=document.getElementById(c3)?.getBoundingClientRect();if(!a||!b?.width)return;let c=R([a],b.width,b.height,{padding:60,maxScale:1});c_.getState().setViewport(c)};requestAnimationFrame(i),setTimeout(i,450)};if(a.nonce>0){let d=c_.getState();b.current=a.focus?{focus:a.focus,docAt:d.docPath,defAt:d.definition}:null,c()}return c_.subscribe(c)},[a]),(0,i.useEffect)(()=>c_.subscribe((a,b)=>{if(a.selection===b.selection||!a.selection.id)return;let{kind:c,id:d}=a.selection;if("state"===c)dR(`state:${d}`);else if("event"===c)dR(`event:${d}`);else if("transition"===c){let b=function(a,b){let c=b.lastIndexOf(":"),d=ex(a.state,b.slice(0,c));if(!d)return null;let e=a.state;for(let a of d.slice(1))e=ew(e).find(b=>b.name===a);return e?.transitions?.[Number(b.slice(c+1))]?.event??null}(a.definition,d);b&&dR(`event:${b}`)}}),[]);let[c,d]=(0,i.useState)("properties"),[e,f]=(0,i.useState)(!1),g=dL({onClose:()=>f(!1),restVh:70,tallVh:92}),j=c_(a=>a.errors),k=c_(a=>a.contextMenu),l=c_(a=>a.hideContextMenu),m=c_(a=>a.addState),n=c_(a=>a.removeState),o=c_(a=>a.setDrawMode),p=c_(a=>a.setDrawSource),q=[{id:"properties",label:"Properties",icon:"🎛"},{id:"events",label:"Events",icon:"⚡"},{id:"settings",label:"Settings",icon:"⚙"},{id:"validation",label:"Errors",icon:(0,h.jsx)(dJ,{}),badge:j.length||void 0}],r=q.find(a=>a.id===c)?.label??"";return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden",onClick:()=>k.visible&&l(),children:[(0,h.jsx)(du,{}),(0,h.jsx)(dG,{}),(0,h.jsx)(dm,{}),(0,h.jsxs)("div",{className:"flex flex-1 min-h-0 overflow-hidden relative",children:[(0,h.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,h.jsx)(dI,{what:"state machine",children:(0,h.jsx)(dc,{})})}),e&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:g.close,"aria-hidden":"true"}),(0,h.jsxs)("aside",{style:g.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 h-[var(--sheet-h)] flex flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${e?"translate-y-0":"translate-y-full pointer-events-none"} md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:pointer-events-auto md:rounded-none md:border-t-0 md:border-l md:shadow-none md:transition-none`,children:[(0,h.jsxs)("div",{className:"md:hidden",...g.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pt-2 pb-1",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:r}),(0,h.jsx)("button",{onClick:g.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:q.map(a=>(0,h.jsxs)("button",{onClick:()=>d(a.id),className:`flex-1 text-xs py-2 px-1 text-center transition-colors relative ${c===a.id?"text-blue-400 border-b-2 border-blue-400 bg-gray-800/50":"text-gray-500 hover:text-gray-300"}`,children:[a.label,void 0!==a.badge&&a.badge>0&&(0,h.jsx)("span",{className:"absolute top-1 right-1 bg-red-600 text-white text-[9px] rounded-full px-1 min-w-[14px]",children:a.badge})]},a.id))}),(0,h.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain",children:["properties"===c&&(0,h.jsx)(de,{}),"events"===c&&(0,h.jsx)(dg,{}),"settings"===c&&(0,h.jsx)(dh,{}),"validation"===c&&(0,h.jsx)(di,{})]})]}),(0,h.jsx)(dn,{})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:q.map(a=>{let b=e&&c===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(e&&c===b?g.close():f(!0),d(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&a.badge>0&&(0,h.jsx)("span",{className:"absolute top-1 right-1/2 translate-x-4 rounded-full bg-red-600 px-1 text-[10px] leading-4 text-white min-w-[16px]",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})}),k.visible&&(0,h.jsx)("div",{className:"fixed z-50 bg-gray-900 border border-gray-700 rounded-lg shadow-xl py-1 min-w-[180px] md:min-w-[140px]",style:{left:k.x,top:k.y,maxWidth:"calc(100vw - 1rem)",maxHeight:"calc(100dvh - 1rem)",overflowY:"auto",transform:"translate(0, 0)"},onClick:a=>a.stopPropagation(),children:k.target?.kind==="state"?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("button",{className:"block w-full text-left text-sm text-gray-300 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{o("transition"),p(k.target.id),l()},children:"↗ Draw transition from here"}),(0,h.jsx)("button",{className:"block w-full text-left text-sm text-red-400 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{k.target?.id&&n(k.target.id),l()},children:"🗑 Delete state"})]}):(0,h.jsx)(h.Fragment,{children:(0,h.jsx)("button",{className:"block w-full text-left text-sm text-gray-300 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{let a=prompt("State name:");a&&m(null,{name:a,kind:"normal"}),l()},children:"+ Add state here"})})})]})}a.s(["default",()=>ey],95421)}];
11
+ ${a}`)}l(!0)};return(0,h.jsxs)("div",{className:"flex flex-col gap-1.5 px-2 py-1.5 bg-gray-900 border-b border-gray-800 md:flex-row md:flex-wrap md:items-center md:px-3",children:[(0,h.jsxs)("div",{className:"toolbar-ident",children:[(0,h.jsx)("input",{ref:A,type:"file",accept:".json,.smdf.json",onChange:a=>{let b=a.target.files?.[0];if(!b)return;let c=new FileReader;c.onload=a=>{e(a.target?.result,b.name)},c.readAsText(b),a.target.value=""},className:"hidden"}),(0,h.jsxs)("span",{className:"text-xs text-gray-400 mr-1 truncate max-w-[50vw] md:max-w-none",children:[b??"untitled.smdf.json",d&&(0,h.jsx)("span",{className:"text-yellow-500 ml-0.5",children:"●"})]}),(0,h.jsx)(dk,{}),"synced"===u&&(0,h.jsx)("span",{className:"text-[10px] text-emerald-500",title:"In sync with disk",children:"⌁ synced"}),"remote-changed"===u&&(0,h.jsx)("span",{className:"text-[10px] text-amber-400",title:v??"",children:"↻ remote changed"}),"error"===u&&(0,h.jsx)("span",{className:"text-[10px] text-red-400",title:v??"",children:"⚠ disk error"}),"idle"===u&&(0,h.jsx)("span",{className:"text-[10px] text-gray-600",title:v??"No file bound",children:"○ no disk"}),(0,h.jsx)(dl,{}),(0,h.jsx)("div",{className:"flex-1"})]}),(0,h.jsxs)("div",{className:"toolbar-strip",children:[(0,h.jsx)("button",{onClick:q,disabled:0===s.length,className:"toolbar-btn disabled:opacity-30",title:"Undo (Ctrl+Z)",children:"↩"}),(0,h.jsx)("button",{onClick:r,disabled:0===t.length,className:"toolbar-btn disabled:opacity-30",title:"Redo (Ctrl+Y)",children:"↪"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:p,className:"toolbar-btn",title:"Arrange states into layers (auto-layout)",children:"⤢ Arrange"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:()=>o("select"===n?"transition":"select"),className:`toolbar-btn ${"transition"===n?"!bg-amber-700 !text-white":""}`,title:"transition"===n?"Exit draw mode (Esc)":"Draw transition mode",children:"transition"===n?"✏️ Drawing":"↗ Draw"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:()=>A.current?.click(),className:"toolbar-btn",title:"Open local .smdf.json (browser)",children:"📂"}),(0,h.jsx)("button",{onClick:P,disabled:F,className:"toolbar-btn disabled:opacity-40",title:"Save to disk (STATELOOM_PROJECT_FILE)",children:"💾 Disk"}),(0,h.jsx)("button",{onClick:R,className:"toolbar-btn",title:"Reload from disk",children:"🔄"}),(0,h.jsx)("button",{onClick:()=>{let a=new Blob([f()],{type:"application/json"}),c=URL.createObjectURL(a),d=document.createElement("a");d.href=c,d.download=b??"statemachine.smdf.json",d.click(),URL.revokeObjectURL(c)},className:"toolbar-btn",title:"Download as file",children:"📥"}),(0,h.jsx)("select",{value:H,onChange:a=>{I(a.target.value),O(null),M(null)},className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",title:"Export format",children:c5.map(a=>(0,h.jsx)("option",{value:a,children:c6[a]},a))}),(0,h.jsx)("button",{onClick:Q,disabled:J,className:`toolbar-btn disabled:opacity-40 ${L?"!text-red-400":""}`,title:L??`Export the board as ${c6[H]}`,children:J?"…":"🖼 Export"}),N&&!L&&(0,h.jsxs)("span",{className:"text-[10px] text-emerald-500 truncate max-w-[40vw] md:max-w-[16rem]",title:N,children:["⤓ ",N]}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),B?(0,h.jsxs)("div",{className:"flex items-center gap-1",children:[(0,h.jsx)("input",{autoFocus:!0,className:"bg-gray-800 border border-gray-700 rounded px-2 py-0.5 text-xs text-gray-200 w-32 md:w-24",placeholder:"State name...",value:D,onChange:a=>E(a.target.value),onKeyDown:a=>{"Enter"===a.key&&S(),"Escape"===a.key&&C(!1)}}),(0,h.jsx)("button",{onClick:S,className:"toolbar-btn-sm",children:"✓"}),(0,h.jsx)("button",{onClick:()=>C(!1),className:"toolbar-btn-sm",children:"✕"})]}):(0,h.jsx)("button",{onClick:()=>C(!0),className:"toolbar-btn",children:"+State"}),(0,h.jsx)("div",{className:"w-px h-4 bg-gray-700"}),(0,h.jsx)("button",{onClick:()=>j(),className:"toolbar-btn",children:"✓ Validate"}),(0,h.jsxs)("select",{value:T,onChange:a=>U(a.target.value),className:"bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 px-1 py-0.5",children:[(0,h.jsx)("option",{value:"python",children:"Python"}),(0,h.jsx)("option",{value:"typescript",children:"TypeScript"})]}),(0,h.jsx)("button",{onClick:W,className:"toolbar-btn",children:"⚡ Generate"}),(0,h.jsx)("button",{onClick:V,className:"toolbar-btn",title:"Generate RISE rispec markdown",children:"📜 RISE"}),(0,h.jsxs)("button",{onClick:()=>l(!k),className:`toolbar-btn ${k?"text-blue-400":""}`,children:["</>"," Code"]})]})]})}function dn(){let a=c_(a=>a.generatedCode),b=c_(a=>a.showCodePreview),c=c_(a=>a.setShowCodePreview);return b?(0,h.jsx)("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-black/60 p-2 md:p-0",children:(0,h.jsxs)("div",{className:"bg-gray-900 border border-gray-700 rounded-lg shadow-xl w-full max-h-[85dvh] md:w-[80%] md:max-w-3xl md:max-h-[80dvh] flex flex-col",children:[(0,h.jsxs)("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-800",children:[(0,h.jsx)("h3",{className:"text-sm font-semibold text-gray-300",children:"Generated Definition (JSON)"}),(0,h.jsx)("button",{onClick:()=>c(!1),className:"text-gray-500 hover:text-gray-300 text-lg min-h-11 min-w-11 md:min-h-0 md:min-w-0","aria-label":"Close preview",children:"✕"})]}),(0,h.jsx)("pre",{className:"flex-1 overflow-auto overscroll-contain p-4 text-[11px] leading-relaxed text-green-400 font-mono md:text-sm",children:a??"No code generated yet"}),(0,h.jsx)("div",{className:"flex justify-end px-4 py-2 border-t border-gray-800",children:(0,h.jsx)("button",{onClick:()=>{a&&navigator.clipboard.writeText(a)},className:"text-xs bg-gray-700 hover:bg-gray-600 text-gray-300 px-4 py-3 rounded md:px-3 md:py-1",children:"Copy to Clipboard"})})]})}):null}function dp(){let a=c_(a=>a.applyRemote),b=c_(a=>a.setRemoteStatus),c=c_(a=>a.setRemoteMtime),d=(0,dj.useRequestedDoc)();return(0,i.useEffect)(()=>{let e=!1,f=(0,dj.docQuery)(d);async function g(){try{let a=await fetch(`/api/file${f}`,{cache:"no-store"});if(!a.ok)return null;return await a.json()}catch{return null}}(async()=>{let c=await g();e||(c?.path&&c_.getState().setDocPath(c.path),c?.exists&&c.content?a(c.content,c.mtime,c.path.split("/").pop()):b("idle",c?`No file at ${c.path}`:null))})();let h=new EventSource(`/api/watch${f}`);return h.addEventListener("hello",a=>{try{let b=JSON.parse(a.data);"number"==typeof b?.mtime&&c(b.mtime)}catch{}}),h.addEventListener("change",async d=>{let e=0;try{e=JSON.parse(d.data)?.mtime??0}catch{}if(e<=(c_.getState().remoteMtime??0))return;let f=await g();f?.exists&&f.content&&(c_.getState().dirty?(b("remote-changed",`Disk changed at ${new Date(f.mtime).toLocaleTimeString()} — local has unsaved edits`),c(f.mtime)):a(f.content,f.mtime,f.path.split("/").pop()))}),h.addEventListener("error",()=>{b("error","Watch stream disconnected")}),()=>{e=!0,h.close()}},[a,b,c,d]),null}function dq({url:a}){let b=(0,dj.useRequestedDoc)();return(0,i.useEffect)(()=>{if(!a)return;let c=!1,d=null,e=null,f=null,g=null;return(async()=>{let h="";try{let a=await fetch(`/api/file${(0,dj.docQuery)(b)}`,{cache:"no-store"});a.ok&&(h=(await a.json())?.path??"")}catch{}c||(h&&c_.getState().setDocPath(h),(d=cQ({url:a,role:"web",docId:h,name:"web-designer",onFull:a=>{c_.getState().applyRemote(JSON.stringify({stateMachine:a.def}),a.mtime??Date.now(),h&&h.split("/").pop()||void 0),g=a.def},onPatch:a=>{c_.getState().applyRemoteOps(a.ops,a.mtime??Date.now(),a.seq),g=c_.getState().definition},onPresence:a=>{c_.getState().setPresence(a)}})).connect(),e=c_.subscribe((a,b)=>{a.definition===b.definition||a._applyingRemote||(f&&clearTimeout(f),f=setTimeout(()=>{var a,b;let c,e;if(!d||"connected"!==d.getSnapshot().status)return;let f=c_.getState().definition;if(null===g){d.emitFull(f),g=f;return}let h=(a=g,b=f,c=a??{settings:{namespace:"",asynchronous:!1},events:[],state:{name:b.state.name,states:[]}},function(a,b,c){let d={},e=!1,f=new Set([...Object.keys(a.settings),...Object.keys(b.settings)]),g=a.settings,h=b.settings;for(let a of f)q(g[a],h[a])||void 0===h[a]||(d[a]=h[a],e=!0);void 0!==a.settings.notes&&void 0===b.settings.notes&&(d.notes="",e=!0),e&&c.push({op:"settings.update",patch:d})}(c,b,e=[]),function(a,b,c){let d=a.events,e=b.events,f=Math.min(d.length,e.length);for(let a=0;a<f;a++)!function(a,b,c,d){let e={},f=!1;for(let a of["name","file","feeder","description","timers"])q(b[a],c[a])||void 0===c[a]||(e[a]=c[a],f=!0);f&&d.push({op:"eventSource.update",index:a,patch:e});let g=b.events??[],h=c.events??[],i=new Set(h.map(a=>a.id));for(let a of g)i.has(a.id)||d.push({op:"event.remove",id:a.id});let j=g.filter(a=>i.has(a.id)),k=0;for(;k<h.length;){let b=h[k];k<j.length&&j[k].id===b.id?(function(a,b,c){let d={},e=!1;for(let c of["name","description","preAction","postAction"])q(a[c],b[c])||void 0===b[c]||(d[c]=b[c],e=!0);e&&c.push({op:"event.update",id:b.id,patch:d})}(j[k],b,d),function(a,b,c,d){let e=Math.min(b.length,c.length);for(let f=0;f<e;f++)if(!q(b[f],c[f])){let e={};b[f].name!==c[f].name&&(e.name=c[f].name),b[f].type!==c[f].type&&(e.type=c[f].type),d.push({op:"parameter.update",eventId:a,index:f,patch:e})}for(let b=e;b<c.length;b++)d.push({op:"parameter.add",eventId:a,parameter:c[b],index:b});for(let e=b.length-1;e>=c.length;e--)d.push({op:"parameter.remove",eventId:a,index:e})}(b.id,j[k].parameters??[],b.parameters??[],d)):(d.push({op:"event.add",sourceIndex:a,event:b,index:k}),j.splice(k,0,b)),k++}}(a,d[a],e[a],c);for(let a=d.length;a<e.length;a++)c.push({op:"eventSource.add",source:e[a]});for(let a=d.length-1;a>=e.length;a--)c.push({op:"eventSource.remove",index:a})}(c,b,e),function(a,b,c){let d=o(a.state),e=o(b.state),f=new Map(d.map(a=>[a.name,a])),g=new Map(e.map(a=>[a.name,a])),h=p(a.state),i=p(b.state),j=[];for(let a of e){if(f.has(a.name))continue;let b=i.get(a.name)??null,{states:d,transitions:e,...g}=a;c.push({op:"state.add",parent:b,state:{...g}}),e&&e.length>0&&j.push({state:a.name,transitions:e})}for(let a of e){if(!f.has(a.name))continue;let b=h.get(a.name)??null,d=i.get(a.name)??null;b!==d&&null!==d&&c.push({op:"state.nest",child:a.name,newParent:d})}for(let a of e){let b=f.get(a.name);if(!b)continue;let d={},e=!1;q(b.kind,a.kind)||void 0===a.kind||(d.kind=a.kind,e=!0),q(b.description,a.description)||void 0===a.description||(d.description=a.description,e=!0),q(b.notes,a.notes)||(d.notes=a.notes??"",e=!0),q(b.prompt,a.prompt)||(d.prompt=a.prompt??"",e=!0),e&&c.push({op:"state.update",name:a.name,patch:d}),r(a.name,"onEntry",b.onEntry?.actions??[],a.onEntry?.actions??[],c),r(a.name,"onExit",b.onExit?.actions??[],a.onExit?.actions??[],c)}for(let a of j)a.transitions.forEach((b,d)=>{c.push({op:"transition.add",state:a.state,transition:b,index:d})});for(let a of e){let b=f.get(a.name);b&&function(a,b,c,d){let e=Math.min(b.length,c.length);for(let f=0;f<e;f++){if(q(b[f],c[f]))continue;let e={};for(let a of["event","nextState","condition","description","actions"])q(b[f][a],c[f][a])||void 0===c[f][a]||(e[a]=c[f][a]);Object.keys(e).length>0&&d.push({op:"transition.update",state:a,index:f,patch:e})}for(let b=e;b<c.length;b++)d.push({op:"transition.add",state:a,transition:c[b],index:b});for(let e=b.length-1;e>=c.length;e--)d.push({op:"transition.remove",state:a,index:e})}(a.name,b.transitions??[],a.transitions??[],c)}for(let a=d.length-1;a>=0;a--){let b=d[a];if(g.has(b.name))continue;let e=b.transitions??[];for(let a=e.length-1;a>=0;a--)c.push({op:"transition.remove",state:b.name,index:a});c.push({op:"state.remove",name:b.name})}}(c,b,e),e);0!==h.length&&(d.emitPatch(h),g=f)},60))}))})(),()=>{c=!0,f&&clearTimeout(f),e&&e(),d&&d.disconnect()}},[a,b]),null}function dr(){let a=process.env.NEXT_PUBLIC_STATELOOM_BRIDGE_URL??process.env.NEXT_PUBLIC_SMCRAFT_BRIDGE_URL;return"string"==typeof a&&a.length>0?a:void 0}let ds=null;function dt(){return ds||(ds=(async()=>{let a=dr()??null;try{let b=await fetch("/api/config",{cache:"no-store"});if(b.ok){let c=await b.json();return{bridgeUrl:c.bridgeUrl||a,projectFile:c.projectFile??null}}}catch{}return{bridgeUrl:a,projectFile:null}})())}function du(){let a=dr(),[b,c]=(0,i.useState)(a);return((0,i.useEffect)(()=>{let a=!0;return dt().then(b=>{a&&b.bridgeUrl&&c(b.bridgeUrl)}),()=>{a=!1}},[]),"string"==typeof b&&b.length>0)?(0,h.jsx)(dq,{url:b}):(0,h.jsx)(dp,{})}function dv(a){return Number.isFinite(a)?Math.min(1.75,Math.max(.75,a)):1}function dw(a){"u">typeof document&&(document.documentElement.style.fontSize=`${16*dv(a)}px`)}let dx=1,dy=!1,dz=new Set;function dA(){return dy||(dy=!0,dx=1),dx}function dB(){return 1}function dC(a){return dz.add(a),()=>{dz.delete(a)}}function dD(a,b){let c=dv(a);if(dw(c),b,dy=!0,c!==dx)for(let a of(dx=c,dz))a()}function dE(a,b){return Math.max(1,Math.hypot(b.clientX-a.clientX,b.clientY-a.clientY))}function dF(a,b){for(let c=0;c<a.length;c++)if(a[c].identifier===b)return a[c];return null}function dG(){let a=(0,i.useSyncExternalStore)(dC,dA,dB),b=(0,i.useRef)(null),c=(0,i.useRef)(null),d=(0,i.useRef)(null);(0,i.useEffect)(()=>{dw(a)},[a]);let e=(0,i.useCallback)(a=>{c.current=a,null===d.current&&(d.current=requestAnimationFrame(()=>{d.current=null,null!==c.current&&dD(c.current,!1)}))},[]),f=(0,i.useCallback)(()=>{c.current=null,dD(1,!0)},[]);return((0,i.useEffect)(()=>{let a=()=>{let a=b.current;if(b.current=null,!a?.engaged)return;null!==d.current&&(cancelAnimationFrame(d.current),d.current=null);let e=c.current??dA();c.current=null,dD(dv(e),!0)},f=c=>{if(2!==c.touches.length){b.current&&a();return}let[d,e]=[c.touches[0],c.touches[1]];c2(d.target)||c2(e.target)||(b.current={a:d.identifier,b:e.identifier,startScale:dA(),startDist:dE(d,e),engaged:!1})},g=a=>{let c=b.current;if(!c)return;let d=dF(a.touches,c.a),f=dF(a.touches,c.b);if(!d||!f)return;a.preventDefault();let g=dE(d,f);if(!c.engaged){if(12>Math.abs(g-c.startDist))return;c.engaged=!0,c.startDist=g;return}e(dv(c.startScale*(g/c.startDist)))},h=c=>{let d=b.current;d&&(dF(c.touches,d.a)&&dF(c.touches,d.b)||a())};return document.addEventListener("touchstart",f,{passive:!0,capture:!0}),document.addEventListener("touchmove",g,{passive:!1,capture:!0}),document.addEventListener("touchend",h,{passive:!0,capture:!0}),document.addEventListener("touchcancel",h,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",f,{capture:!0}),document.removeEventListener("touchmove",g,{capture:!0}),document.removeEventListener("touchend",h,{capture:!0}),document.removeEventListener("touchcancel",h,{capture:!0}),null!==d.current&&cancelAnimationFrame(d.current)}},[e]),1===a)?null:(0,h.jsxs)("div",{className:"ui-scale-pill",role:"status","aria-live":"polite",children:[(0,h.jsxs)("span",{children:["UI ",Math.round(100*a),"%"]}),(0,h.jsx)("button",{type:"button",onClick:f,"aria-label":"Reset interface size to 100 percent",children:"Reset"})]})}var dH=i;class dI extends dH.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,b){console.error(`[stateloom] the ${this.props.what} could not be drawn:`,a,b.componentStack)}componentDidUpdate(a){this.state.error&&a.resetKey!==this.props.resetKey&&this.setState({error:null})}render(){let{error:a}=this.state;return a?(0,h.jsx)("div",{role:"alert",className:"flex h-full w-full items-center justify-center p-6 text-center text-sm text-amber-300",children:(0,h.jsxs)("p",{className:"max-w-md",children:["This ",this.props.what," cannot be drawn: ",a.message,". The file on disk is unchanged — correct it in the panel, in the file, or with the agent that wrote it."]})}):this.props.children}}function dJ({size:a=16}){return(0,h.jsxs)("svg",{width:a,height:a,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,h.jsx)("path",{d:"M12 4.5 21 19.5H3Z"}),(0,h.jsx)("path",{d:"M12 10v4.5"}),(0,h.jsx)("path",{d:"M12 17.3v.01"})]})}function dK({locked:a,size:b=16}){return(0,h.jsxs)("svg",{width:b,height:b,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,h.jsx)("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),(0,h.jsx)("path",{d:a?"M8 11V8a4 4 0 0 1 8 0v3":"M8 11V8a4 4 0 0 1 7.5-1.9"})]})}function dL(a){let{onClose:b,restVh:c,tallVh:d}=a,[e,f]=(0,i.useState)(!1),[g,h]=(0,i.useState)(null),j=(0,i.useRef)(null),k=()=>{f(!1),b()},l=a=>{let b=j.current;if(!b||b.id!==a.pointerId)return;j.current=null;let c=a.clientY-b.y;if(h(null),6>Math.abs(c))return f(a=>!a);if(c<=-50)return f(!0);if(c>=80){if(e&&c<260)return f(!1);k()}},m=e?d:c,n=null!==g;return{zoneProps:{onPointerDown:a=>{a.target.closest("button")||(j.current={y:a.clientY,id:a.pointerId},a.currentTarget.setPointerCapture(a.pointerId),h(0))},onPointerMove:a=>{let b=j.current;b&&b.id===a.pointerId&&h(a.clientY-b.y)},onPointerUp:l,onPointerCancel:l,style:{touchAction:"none",cursor:"grab"}},sheetStyle:{"--sheet-h":n&&g<0?`min(calc(${m}dvh + ${-g}px), ${d}dvh)`:`${m}dvh`,...n?{transition:"none"}:{},...n&&g>0?{transform:`translateY(${g}px)`}:{}},close:k}}let dM="stateloom:focus-request",dN="stateloom:system-changed",dO="stateloom:strip-note";function dP(a){let[b,c]=(0,i.useState)(null);return(0,i.useEffect)(()=>{let a=()=>c(null);a();let b=["popstate",dj.DOC_CHANGE_EVENT,"stateloom:focus",dM];for(let c of b)window.addEventListener(c,a);return()=>{for(let c of b)window.removeEventListener(c,a)}},[a]),b}function dQ(a){let b=new URL(window.location.href),c=b.searchParams.get("doc")!==a.doc;b.searchParams.set("doc",a.doc);let d=void 0===a.system?b.searchParams.get("system"):a.system;d?b.searchParams.set("system",d):b.searchParams.delete("system"),a.focus?b.searchParams.set("focus",a.focus):b.searchParams.delete("focus"),c?window.history.pushState({},"",b):window.history.replaceState(window.history.state,"",b),c&&window.dispatchEvent(new Event(dj.DOC_CHANGE_EVENT)),window.dispatchEvent(new Event(dM))}function dR(a){}function dS(){let[a,b]=(0,i.useState)({focus:null,nonce:0});return(0,i.useEffect)(()=>{let a=()=>b(a=>({focus:null,nonce:a.nonce+1}));a();let c=["popstate",dj.DOC_CHANGE_EVENT,dM];for(let b of c)window.addEventListener(b,a);return()=>{for(let b of c)window.removeEventListener(b,a)}},[]),a}function dT(a,b,c){try{return a()}catch(d){let a=d instanceof Error?d.message:String(d);return console.warn("[stateloom] skipped on a malformed document:",a),c?.(a),b}}let dU=(a,b)=>"chen"===b?`stateloom:erd-layout:chen:${a}`:`stateloom:erd-layout:${a}`,dV="stateloom:erd-notation",dW="stateloom:erd-lock";function dX(a,b){try{return JSON.parse(localStorage.getItem(dU(a,b))??"{}")}catch{return{}}}async function dY(a){let b=a.slice(0,a.lastIndexOf("/")),c=((await (await fetch("/api/docs",{cache:"no-store"})).json()).docs??[]).map(a=>a.path).filter(a=>a.endsWith(".smdf.json")&&a.slice(0,a.lastIndexOf("/"))===b),d=[];for(let a of c)try{let b=await (await fetch(`/api/file${(0,dj.docQuery)(a)}`,{cache:"no-store"})).json(),c=JSON.parse(b.content??"null"),e=ap(c?.stateMachine??c?.StateMachine??c);e?.state&&d.push({path:a,def:e})}catch{}return d}let dZ="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",d$="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",d_="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function d0(){let a=(0,dj.useRequestedDoc)(),[b,c]=(0,i.useState)(""),[d,e]=(0,i.useState)(null),[f,g]=(0,i.useState)({}),[j,k]=(0,i.useState)("crowsfoot"),[l,m]=(0,i.useState)(!1),[n,o]=(0,i.useState)({...M}),[p,q]=(0,i.useState)(0),[r,s]=(0,i.useState)(null),[t,u]=(0,i.useState)({text:"loading…",tone:"ok"}),v=(0,i.useCallback)((a,b="ok")=>u({text:a,tone:b}),[]),[w,x]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=setTimeout(()=>x(!0),4e3);return()=>{clearTimeout(a),x(!1)}},[t]);let[y,z]=(0,i.useState)("entities"),[A,B]=(0,i.useState)(!1),[C,D]=(0,i.useState)(!1),[E,F]=(0,i.useState)(!1),G=(0,i.useRef)(null),H=dL({onClose:()=>B(!1),restVh:62,tallVh:92}),[I,J]=(0,i.useState)(0),[K,L]=(0,i.useState)(null),N=(0,i.useRef)(null);(0,i.useEffect)(()=>{let b=!1,d=null;return(async()=>{let f=await (await fetch(`/api/file${(0,dj.docQuery)(a)}`,{cache:"no-store"})).json();if(b)return;if(f.error)return v(f.error,"warn");let h=f.path??"",i=null;try{let a=f.content?ap(JSON.parse(f.content)):null;W(a)&&(i={...a,relationships:a.relationships??[]})}catch{}if(f.exists&&!i)return v(`${h} is not a readable ERD definition`,"warn");let j=(h.split("/").pop()??"Untitled").replace(/\.erdf\.json$/i,""),l=function(){try{return"chen"===localStorage.getItem(dV)?"chen":"crowsfoot"}catch{return"crowsfoot"}}();c(h),e(i??{settings:{namespace:"Default",name:j},entities:[],relationships:[]}),k(l),m(function(){try{let a=localStorage.getItem(dW);if(null!==a)return"1"===a;return window.matchMedia("(pointer: coarse)").matches}catch{return!1}}()),g(dX(h,l)),s(null),L(null),q(a=>a+1),v(f.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:n}=await dt();!b&&n&&(N.current=d=cQ({url:n,role:"web",docId:h,name:"web-designer",onFull:a=>{let b=a.def;W(b)&&(e({...b,relationships:b.relationships??[]}),v("updated live"))},onPatch:()=>{},onPresence:a=>J(a.length)}),d.connect())})().catch(a=>!b&&v(String(a),"warn")),()=>{b=!0,N.current=null,d?.disconnect()}},[a,v]);let O=(0,i.useMemo)(()=>{if(!d)return{};let a=dT(()=>(function(a,b={}){let c=b.notation??"crowsfoot",d=b.hSpacing??70,e=b.vSpacing??("chen"===c?130:90),f="chen"===c?ai:ar,g=[],h=new Set;for(let b of a.entities??[])!b?.name||h.has(b.name)||(h.add(b.name),g.push(b));let i=new Map,j=(a,b,c=new Set)=>a===b||!c.has(a)&&(c.add(a),(i.get(a)??[]).some(a=>j(a,b,c)));for(let b of a.relationships??[]){if(!b||!h.has(b.from)||!h.has(b.to)||b.from===b.to)continue;let[a,c]="N:1"===b.cardinality?[b.to,b.from]:[b.from,b.to];if((i.get(a)??[]).includes(c)||j(c,a))continue;let d=i.get(a);d?d.push(c):i.set(a,[c])}let k=new Map,l=(a,b)=>{if(!((k.get(a)??-1)>=b))for(let c of(k.set(a,b),i.get(a)??[]))l(c,b+1)},m=new Set([...i.values()].flat());for(let a of g)m.has(a.name)||l(a.name,0);for(let a of g)k.has(a.name)||l(a.name,0);for(let a of[...g].sort((a,b)=>k.get(b.name)-k.get(a.name))){let b=i.get(a.name)??[];b.length&&k.set(a.name,Math.min(...b.map(a=>k.get(a)))-1)}let n=[],o=new Map,p=(a,b)=>((n[b]??=[]).push(a),o.set(a.id,a),a);for(let a of g)p({id:a.name,entity:a.name,...f(a),upper:[],lower:[],x:0},k.get(a.name)??0);let q=0;for(let[a,b]of i)for(let c of b){let b=a;for(let d=k.get(a)+1;d<k.get(c);d++){let a=p({id:`\u0000lane${q++}`,width:28,height:0,upper:[],lower:[],x:0},d);o.get(b).lower.push(a.id),a.upper.push(b),b=a.id}o.get(b).lower.push(c),o.get(c).upper.push(b)}for(let a=n.length-1;a>=0;a--)n[a]?.length||n.splice(a,1);let r=(a,b)=>a.length?a.reduce((a,c)=>a+b(o.get(c)),0)/a.length:null,s=(a,b)=>{let c=new Map;for(let a of n)a.forEach((a,b)=>c.set(a.id,b));let d=new Map(a.map((a,d)=>[a.id,r(a[b],a=>c.get(a.id))??d]));a.sort((a,b)=>d.get(a.id)-d.get(b.id))};for(let a=0;a<2;a++){for(let a=1;a<n.length;a++)s(n[a],"upper");for(let a=n.length-2;a>=0;a--)s(n[a],"lower")}let t=a=>a.x+a.width/2,u=(a,b)=>{let c=0;for(let e of a){let a=r(e[b],t);e.x=Math.max(c,null===a?c:a-e.width/2),c=e.x+e.width+d}};for(let a of n)u(a,"upper");for(let a=n.length-2;a>=0;a--)u(n[a],"lower");let v=Math.min(0,...[...o.values()].map(a=>a.x)),w={},x=40;for(let a of n){for(let b of a)b.entity&&(w[b.entity]={x:Math.round(b.x-v)+40,y:x,width:b.width,height:b.height});x+=Math.max(0,...a.map(a=>a.height))+e}return w})(d,{notation:j}),{});for(let[b,c]of Object.entries(f))a[b]&&(a[b]={...a[b],...c});return a},[d,f,j]),Q=(0,i.useMemo)(()=>{if(!d)return[];let a="";return dT(()=>X(d),null,b=>a=b)??[{ruleId:"E000",message:`The document could not be checked (${a}): a field is not the shape Spec 80 gives it`}]},[d]),S=(0,i.useMemo)(()=>Q.map(a=>(a.element??"").split(/[.[]/)[0]).filter(Boolean),[Q]),T=(0,i.useCallback)(async a=>{let c;if(d&&b){try{c=a(d)}catch(a){return v(a instanceof Error?a.message:String(a),"warn")}e(c),L(null);try{let a=await fetch(`/api/file${(0,dj.docQuery)(b)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(c,null,2)+"\n"})});if(!a.ok)throw Error((await a.json())?.error??`HTTP ${a.status}`);N.current?.emitFull(c),v("saved")}catch(a){v(`not saved: ${a instanceof Error?a.message:String(a)}`,"warn")}}},[d,b,v]),Y=(0,i.useCallback)((a,c)=>{g(d=>{let e={...d,[a]:{x:Math.round(c.x),y:Math.round(c.y)}};try{localStorage.setItem(dU(b,j),JSON.stringify(e))}catch{}return e})},[b,j]),ae=()=>{g({});try{localStorage.removeItem(dU(b,j))}catch{}q(a=>a+1)},af=async()=>{if(!d)return;v("checking links…");let a=await dY(b);if(0===a.length)return L("none"),z("issues"),B(!0),v("no .smdf.json beside this document to check against","warn");let c=a.flatMap(a=>Z(a.def,d).map(b=>({...b,message:`${a.def.settings?.name??a.path}: ${b.message}`})));c.push(...$(d,a.map(a=>a.def.settings?.name??""))),L(c),z("issues"),B(!0),F(!1),v(`checked ${a.length} machine(s): ${c.length} problem(s)`,c.length?"warn":"ok")},ag=async a=>{let c=(await dY(b)).find(b=>b.def.settings?.name===a);c?(0,dj.navigateToDoc)(c.path):v(`no .smdf.json beside this document defines '${a}'`,"warn")},ah=()=>{let a=G.current?.getBoundingClientRect();return{width:a?.width??0,height:a?.height??0}},ak=a=>{let{width:b,height:c}=ah();o(d=>P(d,a,{x:b/2,y:c/2}))},ao=a=>{let b=O[a],{width:c,height:d}=ah();b&&c&&(o(R([b],c,d,{padding:28,maxScale:1.25})),s(a),H.close())},aq=dS(),as=(0,i.useRef)(-1);(0,i.useEffect)(()=>{if(!d||as.current===aq.nonce)return;as.current=aq.nonce;let a=aq.focus?a7(aq.focus):null,b=a?.kind==="entity"?a.name:a?.kind==="attribute"?a.name.split(".")[0]:null;b&&O[b]&&ao(b)},[d,aq,O]),(0,i.useEffect)(()=>{r&&1&&dR(`entity:${r}`)},[r]);let at=d?.entities.find(a=>a.name===r)??null,au=b.split("/").pop()||"…",av=Array.isArray(K)?K:[],aw=Q.length+av.length,ax=[{id:"entities",label:"Entities",icon:"▭"},{id:"relations",label:"Relations",icon:"⟷"},{id:"notes",label:"Notes",icon:"✎",badge:void 0},{id:"issues",label:"Issues",icon:(0,h.jsx)(dJ,{}),badge:aw||void 0}],ay=a=>y===a?"":"hidden md:block",az=()=>{d&&navigator.clipboard?.writeText(function(a){let b=["erDiagram"],c=" ",d=new Set;for(let e of a.relationships??[]){if(!e?.from||!e?.to)continue;let a=aj[e.cardinality]??aj["1:N"];b.push(`${c}${al(e.from)} ${a} ${al(e.to)} : ${an(e.label??"")}`),d.add(e.from),d.add(e.to)}let e=new Set;for(let f of a.entities??[]){if(!f?.name||e.has(f.name))continue;e.add(f.name);let a=(f.attributes??[]).filter(a=>a?.name);if(0===a.length){d.has(f.name)||b.push(`${c}${al(f.name)}`);continue}for(let d of(b.push(`${c}${al(f.name)} {`),a))b.push(`${c}${c}${function(a){let b=[];"pk"===a.key&&b.push("PK"),"uk"===a.key&&b.push("UK"),a.references&&b.push("FK");let c=[],d=U(a);d.length&&c.push(`stateOf ${d.join(", ")}`),a.description&&c.push(a.description);let e=[am(a.type??"","unknown"),am(a.name,"unnamed")];return b.length&&e.push(b.join(", ")),c.length&&e.push(an(c.join(" — "))),e.join(" ")}(d)}`);b.push(`${c}}`)}return b.join("\n")}(d)).then(()=>v("mermaid copied"))};return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&D(!1),children:[(0,h.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,h.jsx)("span",{className:"font-semibold text-blue-300",children:"ERD"}),(0,h.jsx)(dk,{}),(0,h.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:b,children:[d?.settings.name??au,(0,h.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",au]})]}),(0,h.jsx)("span",{className:"inline-flex shrink-0 overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Notation",children:[["crowsfoot","▤","Crow's foot — attributes listed inside the entity box"],["chen","◇","Chen — attributes as ovals, relationships as diamonds"]].map(([a,c,d])=>(0,h.jsx)("button",{title:d,"aria-label":d,"aria-pressed":j===a,onClick:()=>(a=>{if(a!==j){try{localStorage.setItem(dV,a)}catch{}k(a),g(dX(b,a)),q(a=>a+1)}})(a),className:`px-2.5 py-1.5 text-sm leading-none md:px-2 md:py-1 ${j===a?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:c},a))}),(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,h.jsx)("button",{className:d$,onClick:ae,title:"Forget the dragged positions and lay the board out again",children:"⤢ Arrange"}),(0,h.jsx)("button",{className:d$,onClick:af,title:"Check the state machines beside this document against it",children:"Check links"}),(0,h.jsx)("button",{className:d$,onClick:az,children:"Copy mermaid"}),(0,h.jsx)("button",{className:d$,onClick:()=>F(a=>!a),"aria-pressed":!E,title:E?"Show the panel":"Hide the panel — the board takes the full width",children:E?"⟨ Panel":"Panel ⟩"})]}),(0,h.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,h.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":C,onClick:a=>{a.stopPropagation(),D(a=>!a)},children:"⋯"}),C&&(0,h.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:[["⤢ Arrange the board",ae],["Check links to the machines",af],["Copy as mermaid",az]].map(([a,b])=>(0,h.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{D(!1),b()},children:a},a))})]})]}),(0,h.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,h.jsxs)("div",{ref:G,className:"relative min-w-0 flex-1 overflow-hidden",children:[d&&(0,h.jsx)(dI,{what:"diagram",resetKey:d,children:(0,h.jsx)(bu,{definition:d,notation:j,positions:O,viewport:n,onViewportChange:o,selection:r,readOnly:l,errorElements:S,fitKey:p,onSelect:s,onClearSelection:()=>s(null),onEntityMove:Y,onOpenMachine:ag,emptyHint:"No entities yet — add one in the panel, or let an agent call add_entity."})}),(0,h.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 flex max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===t.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,h.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===t.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,h.jsxs)("span",{className:`truncate transition-opacity duration-500 ${w&&"ok"===t.tone?"opacity-0":"opacity-100"}`,children:[t.text,I>1?` \xb7 ${I} in the room`:""]})]}),(0,h.jsxs)("div",{className:"absolute bottom-3 right-3 flex flex-col overflow-hidden rounded-lg border border-gray-700 bg-gray-900/90 shadow-lg backdrop-blur",children:[(0,h.jsx)("button",{title:l?"Shapes are locked: dragging moves the view. Tap to unlock.":"Lock the shapes in place, so dragging only moves the view","aria-label":"Lock shapes in place","aria-pressed":l,onClick:()=>{let a=!l;m(a);try{localStorage.setItem(dW,a?"1":"0")}catch{}v(a?"shapes locked — a drag anywhere moves the view":"shapes unlocked — drag one to move it")},className:`flex h-10 w-10 items-center justify-center border-b border-gray-800 hover:bg-gray-800 md:h-8 md:w-8 ${l?"bg-blue-950/60 text-blue-300":"text-gray-400"}`,children:(0,h.jsx)(dK,{locked:l})}),[["+","Zoom in",()=>ak(1.25)],["−","Zoom out",()=>ak(.8)],["⛶","Fit the whole diagram",()=>q(a=>a+1)]].map(([a,b,c])=>(0,h.jsx)("button",{title:b,"aria-label":b,onClick:c,className:"h-10 w-10 border-b border-gray-800 text-base leading-none text-gray-200 last:border-b-0 hover:bg-gray-800 md:h-8 md:w-8 md:text-sm",children:a},b))]}),at&&!A&&(0,h.jsxs)("button",{className:"absolute bottom-3 left-1/2 max-w-[60%] -translate-x-1/2 truncate rounded-full border border-blue-500/60 bg-gray-900/95 px-4 py-2 text-sm text-blue-200 shadow-lg md:hidden",onClick:()=>{z("entities"),B(!0)},children:["✎ ",at.name]})]}),A&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:H.close,"aria-hidden":"true"}),d&&(0,h.jsxs)("aside",{style:H.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${A?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${E?"md:hidden":""}`,children:[(0,h.jsxs)("div",{className:"md:hidden",...H.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:ax.find(a=>a.id===y)?.label}),(0,h.jsx)("button",{onClick:H.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,h.jsxs)("section",{className:ay("entities"),children:[(0,h.jsx)("div",{className:d_,style:{marginTop:0},children:"Entities"}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:d.entities.map(a=>(0,h.jsx)("button",{className:`${d$} ${r===a.name?"border-blue-500 text-blue-300":""}`,onClick:()=>s(a.name),children:a.name},a.name))}),(0,h.jsx)(d2,{fields:[{name:"name",placeholder:"new entity"}],submit:"+ Entity",onSubmit:a=>{T(b=>ac(b,{name:a.name.trim()})),s(a.name.trim())}}),at&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:`${d_} flex items-center justify-between gap-2`,children:[(0,h.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:at.name}),(0,h.jsx)("button",{className:`${d$} normal-case tracking-normal`,onClick:()=>ao(at.name),title:"Bring this entity to the middle of the board at a readable size",children:"◎ Show on board"})]}),(0,h.jsxs)("label",{className:"mb-1 flex items-center gap-2 text-[11px] text-gray-400",title:"Exists only through another entity (an order line, without its order). Chen draws it as a double rectangle.",children:[(0,h.jsx)("input",{type:"checkbox",checked:!!at.weak,onChange:a=>T(b=>ad(b,at.name,{weak:a.target.checked}))}),"weak entity"]}),(at.attributes??[]).map(a=>(0,h.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 font-mono text-[11px]",children:[(0,h.jsxs)("span",{className:a.stateOf?"text-blue-300":"text-gray-300",children:[a.name," : ",a.type,(0,h.jsxs)("span",{className:"text-gray-500",children:[a.key?` ${a.key.toUpperCase()}`:"",a.references?` → ${a.references}`:"",a.stateOf?` ◉ ${[a.stateOf].flat().join(", ")}`:""]})]}),(0,h.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove ${a.name}`,onClick:()=>T(b=>(function(a,b,c){let d=_(a),e=aa(d,b),f=e.attributes?.length??0;if(e.attributes=(e.attributes??[]).filter(a=>a.name!==c),e.attributes.length===f)throw Error(`Attribute '${b}.${c}' not found.`);return d})(b,at.name,a.name)),children:"✕"})]},a.name)),(0,h.jsx)(d2,{fields:[{name:"name",placeholder:"attribute"},{name:"type",placeholder:"type",initial:"string"},{name:"key",options:["","pk","uk"]},{name:"references",placeholder:"references Entity.attr"},{name:"stateOf",placeholder:"stateOf Machine"}],submit:"+ Attribute",onSubmit:a=>T(b=>(function(a,b,c){if(!c.name?.trim())throw Error("An attribute needs a name.");let d=_(a),e=aa(d,b);if(e.attributes??=[],e.attributes.some(a=>a.name===c.name))throw Error(`Attribute '${b}.${c.name}' already exists.`);return e.attributes.push(ab({...c})),d})(b,at.name,{name:a.name.trim(),type:a.type.trim()||"string",key:"pk"===a.key||"uk"===a.key?a.key:void 0,references:a.references.trim()||void 0,stateOf:a.stateOf.trim()||void 0}))}),(0,h.jsxs)("button",{className:`${d$} mt-2 text-red-300`,onClick:()=>{T(a=>{var b;let c;return b=at.name,aa(c=_(a),b),c.entities=c.entities.filter(a=>a.name!==b),c.relationships=c.relationships.filter(a=>a.from!==b&&a.to!==b),c}),s(null)},children:["🗑 Delete ",at.name]})]})]}),(0,h.jsxs)("section",{className:ay("relations"),children:[(0,h.jsx)("div",{className:`${d_} max-md:mt-0`,children:"Relationships"}),0===d.relationships.length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),d.relationships.map((a,b)=>(0,h.jsxs)("div",{className:"flex items-center justify-between gap-2 py-0.5 text-[11px] text-gray-300",children:[(0,h.jsxs)("span",{children:[a.from," ",(0,h.jsx)("span",{className:"text-gray-500",children:a.cardinality})," ",a.to,a.label?(0,h.jsxs)("span",{className:"text-gray-500",children:[" : ",a.label]}):null]}),(0,h.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":"Remove relationship",onClick:()=>T(b=>(function(a,b,c,d){let e=_(a),f=e.relationships.length;if(e.relationships=e.relationships.filter(a=>a.from!==b||a.to!==c||void 0!==d&&a.label!==d),e.relationships.length===f)throw Error(`No relationship from '${b}' to '${c}'${void 0===d?"":` labelled '${d}'`}.`);return e})(b,a.from,a.to,a.label)),children:"✕"})]},b)),d.entities.length>0&&(0,h.jsx)(d2,{fields:[{name:"from",options:d.entities.map(a=>a.name)},{name:"cardinality",options:[...V],initial:"1:N"},{name:"to",options:d.entities.map(a=>a.name)},{name:"label",placeholder:"label (a verb)"}],submit:"+ Relationship",onSubmit:a=>T(b=>(function(a,b){let c=_(a);if(aa(c,b.from),aa(c,b.to),!V.includes(b.cardinality))throw Error(`Cardinality '${b.cardinality}' is not one of ${V.join(", ")}.`);return c.relationships.push(ab({...b})),c})(b,{from:a.from,to:a.to,cardinality:a.cardinality,label:a.label.trim()||void 0}))})]}),(0,h.jsxs)("section",{className:ay("notes"),children:[(0,h.jsx)("div",{className:`${d_} max-md:mt-0`,children:"Notes"}),(0,h.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the document, for whoever opens it next — you, or an agent (it reads them with get_notes)."}),(0,h.jsx)(d1,{label:"On this diagram",value:d.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:a=>T(b=>(function(a,b){let c=_(a);for(let a of["description","notes"]){let d=b[a];void 0!==d&&(d.trim()?c.settings[a]=d:delete c.settings[a])}return c})(b,{notes:a}))},"diagram"),at?(0,h.jsx)(d1,{label:`On ${at.name}`,value:at.notes??"",placeholder:`A question or a decision about ${at.name}…`,onSave:a=>T(b=>ad(b,at.name,{notes:a}))},`entity:${at.name}`):(0,h.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select an entity to leave a note on it."}),d.entities.some(a=>a.notes?.trim())&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:d_,children:"Entities with notes"}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:d.entities.filter(a=>a.notes?.trim()).map(a=>(0,h.jsx)("button",{className:`${d$} ${r===a.name?"border-blue-500 text-blue-300":""}`,onClick:()=>s(a.name),children:a.name},a.name))})]})]}),(0,h.jsxs)("section",{className:ay("issues"),children:[(0,h.jsx)("div",{className:`${d_} max-md:mt-0 ${0===aw&&!K?"md:hidden":""}`,children:"Issues"}),Q.map((a,b)=>(0,h.jsxs)("div",{className:"py-0.5 text-[11px] text-red-300",children:["[",a.ruleId,"] ",a.message]},`p${b}`)),av.map((a,b)=>(0,h.jsxs)("div",{className:"py-0.5 text-[11px] text-amber-300",children:["[",a.ruleId,"] ",a.message]},`l${b}`)),"none"===K&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-amber-300",children:"No state machine (.smdf.json) sits beside this document, so there was nothing to check it against."}),0===aw&&"none"!==K&&(0,h.jsx)("div",{className:`py-0.5 text-[11px] ${K?"text-green-400":"text-gray-600 md:hidden"}`,children:K?"Every name the machines use resolves.":"The document is valid. “Check links” (⋯) holds the state machines beside it against it."})]})]})]})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:ax.map(a=>{let b=A&&y===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(A&&y===b?H.close():B(!0),z(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})})]})}function d1({label:a,value:b,placeholder:c,onSave:d}){let[e,f]=(0,i.useState)(b),[g,j]=(0,i.useState)(b),[k,l]=(0,i.useState)(!1);b!==g&&(j(b),k||f(b));let m=(0,i.useRef)(null),n=a=>{m.current&&clearTimeout(m.current),m.current=null,a!==b&&d(a)};return(0,h.jsxs)("label",{className:"mt-2 block",children:[(0,h.jsx)("span",{className:"text-[11px] text-gray-500",children:a}),(0,h.jsx)("textarea",{className:`${dZ} h-24 resize-y leading-snug`,placeholder:c,value:e,onChange:a=>{let b=a.target.value;f(b),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>n(b),900)},onFocus:()=>l(!0),onBlur:()=>{l(!1),n(e)}})]})}function d2({fields:a,submit:b,onSubmit:c}){let d=()=>Object.fromEntries(a.map(a=>[a.name,a.initial??a.options?.[0]??""])),[e,f]=(0,i.useState)(d),g=a[0];return(0,h.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:b=>{b.preventDefault();let h={...d(),...e};h[g.name]?.trim()&&(c(h),f(b=>Object.fromEntries(a.map(a=>[a.name,a.options?b[a.name]??"":a.initial??""]))))},children:[a.map(a=>a.options?(0,h.jsx)("select",{className:dZ,"aria-label":a.name,value:e[a.name]??"",onChange:b=>f(c=>({...c,[a.name]:b.target.value})),children:a.options.map(b=>(0,h.jsx)("option",{value:b,children:b||`(${a.name})`},b))},a.name):(0,h.jsx)("input",{className:dZ,"aria-label":a.name,placeholder:a.placeholder,value:e[a.name]??"",onChange:b=>f(c=>({...c,[a.name]:b.target.value}))},a.name)),(0,h.jsx)("button",{type:"submit",className:`${d$} ${1===a.length?"":"col-span-2"}`,children:b})]})}let d3="w-full rounded border border-gray-700 bg-gray-950 px-2 py-1 text-xs text-gray-200 placeholder:text-gray-600",d4="rounded border border-gray-700 bg-gray-800 px-2 py-1 text-xs text-gray-200 hover:bg-gray-700",d5="mb-1 mt-3 text-[11px] font-semibold uppercase tracking-wide text-gray-500";function d6({id:a,fields:b,submit:c,onSubmit:d,reset:e=!1,required:f}){let g=()=>Object.fromEntries(b.map(a=>[a.name,a.initial??(!a.checkbox&&(a.options?a.options[0]??"":""))])),[j,k]=(0,i.useState)(g),l=(a,b)=>k(c=>({...c,[a]:b}));return(0,h.jsxs)("form",{className:"mt-1 grid grid-cols-2 gap-1",onSubmit:a=>{a.preventDefault();let c={...g(),...j};!(f??[]).some(a=>!String(c[a]??"").trim())&&(d(c),e&&k(a=>Object.fromEntries(b.map(b=>[b.name,b.options||b.checkbox?a[b.name]??"":b.initial??""]))))},children:[b.map(b=>{let c=b.label??b.name;if(b.checkbox)return(0,h.jsxs)("label",{className:"flex items-center gap-2 text-[11px] text-gray-400",children:[(0,h.jsx)("input",{type:"checkbox",checked:!!j[b.name],onChange:a=>l(b.name,a.target.checked)}),c]},b.name);if(b.options)return(0,h.jsx)("select",{className:`${d3} ${b.wide?"col-span-2":""}`,"aria-label":c,title:c,value:String(j[b.name]??""),onChange:a=>l(b.name,a.target.value),children:b.options.map(a=>(0,h.jsx)("option",{value:a,children:a||`(${c})`},a))},b.name);let d=b.suggest?.length?`${a}-${b.name}`:void 0;return(0,h.jsxs)("span",{className:b.wide?"col-span-2":"",children:[(0,h.jsx)("input",{className:d3,"aria-label":c,title:c,placeholder:b.placeholder??c,list:d,value:String(j[b.name]??""),onChange:a=>l(b.name,a.target.value)}),d&&(0,h.jsx)("datalist",{id:d,children:b.suggest.map(a=>(0,h.jsx)("option",{value:a},a))})]},b.name)}),(0,h.jsx)("button",{type:"submit",className:`${d4} col-span-2`,children:c})]})}function d7({kind:a,size:b=16}){return(0,h.jsxs)("svg",{width:b,height:b,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"shrink-0",children:["erd"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("rect",{x:"4",y:"4.5",width:"16",height:"15",rx:"1.5"}),(0,h.jsx)("path",{d:"M4 9h16M8 13h8M8 16.5h6"})]}),"machine"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("rect",{x:"2.5",y:"4",width:"8",height:"6",rx:"2.5"}),(0,h.jsx)("rect",{x:"13.5",y:"14",width:"8",height:"6",rx:"2.5"}),(0,h.jsx)("path",{d:"M6.5 10v4.5a2.5 2.5 0 0 0 2.5 2.5h4.5"}),(0,h.jsx)("path",{d:"M11.5 15l2 2-2 2"})]}),"sequence"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("path",{d:"M6 4v16M18 4v16",strokeDasharray:"2 2.2"}),(0,h.jsx)("path",{d:"M6 9h11M15 7l2 2-2 2"}),(0,h.jsx)("path",{d:"M18 15H7M9 13l-2 2 2 2"})]}),"system"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("rect",{x:"3",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,h.jsx)("rect",{x:"14",y:"3.5",width:"7",height:"6",rx:"1.5"}),(0,h.jsx)("rect",{x:"8.5",y:"14.5",width:"7",height:"6",rx:"1.5"}),(0,h.jsx)("path",{d:"M10 6.5h4M7 9.5l3 5M17 9.5l-3 5"})]}),"link"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("path",{d:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1.2 1.2"}),(0,h.jsx)("path",{d:"M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1.2-1.2"})]}),"actor"===a&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("circle",{cx:"12",cy:"7.5",r:"3.5"}),(0,h.jsx)("path",{d:"M5 20a7 7 0 0 1 14 0"})]})]})}let d8=["text-sky-300","text-emerald-300","text-amber-300","text-rose-300","text-violet-300","text-cyan-300","text-lime-300","text-orange-300"],d9=a=>`seq-read-${a.kind}-${a.id}`;function ea({definition:a,selection:b,issues:c,onSelect:d,onShowInDiagram:e}){let f=new Map(a.participants.map((a,b)=>[a.name,d8[b%d8.length]])),g=ay(a),i=g.filter(a=>null===a.fragment),j=(a.fragments??[]).map((a,b)=>({f:a,fi:b,rows:g.filter(a=>a.fragment===b)})),k=(a,c)=>b?.kind===a&&b.id===c,l=a=>(0,h.jsx)("span",{className:`font-semibold ${f.get(a)??"text-gray-300"}`,children:a||"?"}),m=(a,b)=>{let f={kind:"message",id:a},g=c.get(`message:${a}`)??[],i=g.some(a=>"error"===a.severity)?"error":g.length?"warning":null,j=k("message",a);return(0,h.jsx)("li",{id:d9(f),className:"scroll-mt-16 scroll-mb-24",children:(0,h.jsxs)("div",{role:"button",tabIndex:0,"aria-pressed":j,onClick:()=>d(f),onKeyDown:a=>("Enter"===a.key||" "===a.key)&&(a.preventDefault(),d(f)),className:`flex gap-3 rounded-lg border-l-2 px-3 py-2.5 ${j?"bg-blue-950/60 ring-1 ring-blue-500/60":"hover:bg-gray-900"} ${"error"===i?"border-red-500":"warning"===i?"border-amber-400":"border-transparent"}`,children:[(0,h.jsx)("span",{className:"mt-0.5 flex h-6 min-w-6 shrink-0 items-center justify-center rounded-full border border-gray-700 bg-gray-900 px-1 font-mono text-[11px] text-gray-300",children:a}),(0,h.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,h.jsxs)("div",{className:"text-[13px] leading-5 text-gray-400",children:[l(b.from),b.from===b.to?(0,h.jsx)("span",{children:" to itself"}):(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("span",{className:"px-1.5 text-gray-500",children:b.reply?"⇠":"→"}),l(b.to)]}),b.reply&&(0,h.jsx)("span",{className:"ml-2 text-[11px] text-gray-500",children:"reply"}),b.optional&&(0,h.jsx)("span",{className:"ml-2 rounded border border-gray-700 px-1 text-[11px] text-gray-400",children:"optional"})]}),(0,h.jsx)("div",{className:`mt-0.5 break-words text-[15px] leading-6 ${b.reply?"text-gray-300":"text-gray-100"}`,children:b.label||(0,h.jsx)("span",{className:"text-gray-500",children:"no label"})}),(b.event||b.state||b.carries)&&(0,h.jsxs)("div",{className:"mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] leading-5",children:[b.event&&(0,h.jsx)("span",{className:"rounded border border-blue-500/50 bg-blue-950/50 px-1.5 font-mono text-blue-200",children:b.event}),b.event&&b.machine&&(0,h.jsxs)("span",{className:"text-gray-400",children:["on ",b.machine]}),b.state&&(0,h.jsxs)("span",{className:"text-emerald-300",children:["→ ",b.state]}),b.carries&&(0,h.jsxs)("span",{className:"text-gray-400",children:["carries ",b.carries]})]}),g.map((a,b)=>(0,h.jsx)("p",{className:`mt-1.5 text-[12px] leading-5 ${"error"===a.severity?"text-red-300":"text-amber-300"}`,children:a.text},b)),j&&(0,h.jsx)("button",{className:"mt-2 rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-[12px] text-gray-200",onClick:a=>{a.stopPropagation(),e(f)},children:"Show in the diagram"})]})]})},a)};return(0,h.jsx)("div",{className:"h-full overflow-y-auto overscroll-contain",children:(0,h.jsxs)("div",{className:"mx-auto max-w-2xl px-4 pb-28 pt-10",children:[a.participants.length>0&&(0,h.jsx)("ul",{className:"mb-4 flex flex-wrap gap-2","aria-label":"Participants",children:a.participants.map(a=>{let b={kind:"participant",id:a.name},e=a.actor?"actor":a.object?"object":a.service?"service":"",f=c.get(`participant:${a.name}`)??[];return(0,h.jsx)("li",{id:d9(b),children:(0,h.jsxs)("button",{onClick:()=>d(b),"aria-pressed":k("participant",a.name),title:f.map(a=>a.text).join("\n")||void 0,className:`rounded-full border px-3 py-1 text-[13px] ${k("participant",a.name)?"border-blue-500 bg-blue-950/60":"border-gray-700 bg-gray-900"} ${f.length?"ring-1 ring-amber-400/70":""}`,children:[l(a.name),e&&(0,h.jsx)("span",{className:"ml-1.5 text-[11px] text-gray-400",children:e})]})},a.name)})}),0===g.length&&(0,h.jsx)("p",{className:"text-sm text-gray-400",children:"No messages yet — add them in the panel, or let an agent write the scenario."}),(0,h.jsx)("ol",{className:"flex flex-col gap-1",children:i.map(({ref:a,message:b})=>m(a,b))}),j.map(({f:a,fi:b,rows:c})=>(0,h.jsxs)("section",{className:"mt-5 rounded-xl border border-indigo-500/50 bg-indigo-950/20 p-1.5",children:[(0,h.jsxs)("header",{className:"px-3 pb-1.5 pt-2",children:[(0,h.jsxs)("div",{className:"text-[12px] text-indigo-200",children:[(0,h.jsx)("span",{className:"font-semibold uppercase tracking-wide",children:a.kind}),(0,h.jsxs)("span",{className:"text-indigo-300",children:[" · after ",a.after]})]}),(0,h.jsx)("div",{className:"mt-0.5 break-words text-[14px] leading-5 text-gray-100",children:a.label})]}),0===c.length?(0,h.jsx)("p",{className:"px-3 pb-2 text-[12px] text-gray-400",children:"No messages in this fragment."}):(0,h.jsx)("ol",{className:"flex flex-col gap-1",children:c.map(({ref:a,message:b})=>m(a,b))})]},b))]})})}async function eb(a){try{let b=await fetch(`/api/file${(0,dj.docQuery)(a)}`,{cache:"no-store"}),c=await b.json();if(!b.ok||c.error)return{path:a??"",content:null,exists:!1,error:c.error??`HTTP ${b.status}`};return{path:c.path??a??"",content:c.content??null,exists:!!c.exists,mtime:c.mtime}}catch(b){return{path:a??"",content:null,exists:!1,error:b instanceof Error?b.message:String(b)}}}class ec extends Error{constructor(a){super(`${a.split("/").pop()} changed on disk since it was read`)}}async function ed(a,b,c){let d=await fetch(`/api/file${(0,dj.docQuery)(a)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(b,null,2)+"\n",...void 0!==c?{mtime:c}:{}})}),e=await d.json().catch(()=>({}));if(409===d.status)throw new ec(a);if(!d.ok)throw Error(e?.error??`HTTP ${d.status}`);return e?.mtime}async function ee(a){let b=await eb(a),c={path:b.path||a,def:null,members:[],absOf:{},wrapped:{},mtimes:{}};if(b.error)return{...c,error:b.error};if(!b.exists||!b.content)return{...c,error:`${a} does not exist`};let d=null;try{let a=ap(JSON.parse(b.content));aQ(a)&&(d=a)}catch{}if(!d)return{...c,error:`${b.path} is not a readable system definition`};let e={},f={},g={[b.path]:b.mtime??0},h=await Promise.all((d.members??[]).filter(a=>a?.path).map(async a=>{let c=aU(b.path,a.path);e[a.path]=c;let d=aR(a.path),h=await eb(c);if(h.error)return{path:a.path,kind:d,def:null,error:h.error};if(!h.exists||!h.content)return{path:a.path,kind:d,def:null,error:"the file does not exist"};g[a.path]=h.mtime??0;try{let b=JSON.parse(h.content);if("machine"===d&&b&&(b.stateMachine||b.StateMachine))return f[a.path]=!0,{path:a.path,kind:d,def:ap(b.stateMachine??b.StateMachine)};return{path:a.path,kind:d,def:ap(b)}}catch(b){return{path:a.path,kind:d,def:null,error:`not JSON: ${b instanceof Error?b.message:String(b)}`}}}));return{path:b.path,def:d,members:h,absOf:e,wrapped:f,mtimes:g}}function ef(){window.dispatchEvent(new Event(dN))}function eg(a){let[b,c]=(0,i.useState)(null),[d,e]=(0,i.useState)(0),f=(0,i.useCallback)(()=>e(a=>a+1),[]);return(0,i.useEffect)(()=>(window.addEventListener(dN,f),()=>window.removeEventListener(dN,f)),[f]),(0,i.useEffect)(()=>{if(!a)return;let b=!0;return ee(a).then(d=>b&&c({for:a,system:d})),()=>{b=!1}},[a,d]),{system:a&&b?.for===a?b.system:null,reload:f}}function eh(a,b){if(!a||!b)return null;for(let[c,d]of Object.entries(a.absOf))if(d===b)return c;return null}async function ei(a,b,c,d){let{bridgeUrl:e}=await dt();if(!e)return;let f=cO({url:e,role:"web",docId:a,name:"web-reconcile",autoResync:!1});try{let a=await Promise.race([f.join(),new Promise((a,b)=>setTimeout(()=>b(Error("join timeout")),3e3))]),e=a.snapshot?.def,g=a=>(function(a){let b=JSON.stringify(a),c=0x811c9dc5;for(let a=0;a<b.length;a++)c^=b.charCodeAt(a),c=Math.imul(c,0x1000193);return(c>>>0).toString(16).padStart(8,"0")})(a);if(e&&g(e)===g(b))return;await new Promise(a=>{let h=f.on("ack",()=>{h(),a()});d&&e&&g(e)===g(d.from)?f.emitPatch(d.ops,c):f.emitFull(b,c),setTimeout(a,800)})}catch{}finally{f.disconnect()}}async function ej(a,b){let c=[],d=[],e=[],f=async(a,b)=>{try{await b(),c.push(a)}catch(b){b instanceof ec?e.push(a):d.push(`${a}: ${b instanceof Error?b.message:String(b)}`)}};for(let c of b.machines){let b=a.absOf[c.member];b&&c.ops.length&&await f(c.member,async()=>{let d=a.wrapped[c.member]?{stateMachine:c.def}:c.def,e=await ed(b,d,a.mtimes[c.member]),f=a.members.find(a=>a.path===c.member)?.def;await ei(b,c.def,e,{from:f,ops:c.ops})})}for(let c of b.erds){let b=a.absOf[c.member];b&&await f(c.member,async()=>{let d=await ed(b,c.def,a.mtimes[c.member]);await ei(b,c.def,d)})}return b.system&&await f(a.path.split("/").pop()??a.path,async()=>{let c=await ed(a.path,b.system.def,a.mtimes[a.path]);await ei(a.path,b.system.def,c)}),ef(),{written:c,failed:d,conflicts:e}}async function ek(a){let b={result:null,written:[],failed:[],conflicts:[]};for(let c=0;c<2;c+=1){let d=await ee(a);if(!d.def)return{...b,failed:[d.error??"the system could not be read"],retried:c>0};let e=bc(d.def,d.members);if(!e.count)return{...b,result:e,conflicts:c?b.conflicts:[],retried:c>0};let f=await ej(d,e);if(b={result:e,written:[...b.written,...f.written],failed:f.failed,conflicts:f.conflicts},!f.conflicts.length)return{...b,retried:c>0}}return{...b,retried:!0}}let el="stateloom.sequence.view",em=["","actor","service","object"],en=a=>"string"==typeof a?a.trim():"",eo=a=>en(a).split(",").map(a=>a.trim()).filter(Boolean);function ep(a){return{from:en(a.from),to:en(a.to),label:en(a.label),event:en(a.event),machine:en(a.machine),carries:en(a.carries),state:en(a.state),description:en(a.description),optional:!!a.optional||void 0,reply:!!a.reply||void 0}}function eq(){let a,b,c,d=(0,dj.useRequestedDoc)(),e=dP("system"),{system:f}=eg(e),g=dS(),[j,k]=(0,i.useState)(""),[l,m]=(0,i.useState)(null),[n,o]=(0,i.useState)({...M}),[p,q]=(0,i.useState)(void 0),[r,s]=(0,i.useState)(null),[t,u]=(0,i.useState)({text:"loading…",tone:"ok"}),v=(0,i.useCallback)((a,b="ok")=>u({text:a,tone:b}),[]),[w,x]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=setTimeout(()=>x(!0),4e3);return()=>{clearTimeout(a),x(!1)}},[t]);let[y,z]=(0,i.useState)("messages"),[A,B]=(0,i.useState)(!1),[C,D]=(0,i.useState)(!1),[E,F]=(0,i.useState)(!1),[G,H]=(0,i.useState)("diagram"),I=(0,i.useRef)("diagram");(0,i.useEffect)(()=>{let a=null;try{a=window.localStorage.getItem(el)}catch{}let b="list"===a||"diagram"===a?a:window.matchMedia("(max-width: 767px)").matches?"list":"diagram";I.current=b,H(b)},[]);let J=(0,i.useCallback)(a=>{I.current=a,H(a);try{window.localStorage.setItem(el,a)}catch{}},[]),K=(0,i.useRef)(null),L=dL({onClose:()=>B(!1),restVh:62,tallVh:92}),[O,Q]=(0,i.useState)(0),S=(0,i.useRef)(null),T=(0,i.useRef)(!0),U=(0,i.useRef)(-1);(0,i.useEffect)(()=>{let a=!1,b=null;return(async()=>{let c=await (await fetch(`/api/file${(0,dj.docQuery)(d)}`,{cache:"no-store"})).json();if(a)return;if(c.error)return v(c.error,"warn");let e=c.path??"",f=null;try{let a=c.content?ap(JSON.parse(c.content)):null;au(a)&&(f=a)}catch{}if(c.exists&&!f)return v(`${e} is not a readable sequence definition`,"warn");let g=(e.split("/").pop()??"Untitled").replace(/\.sqdf\.json$/i,"");k(e),m(f??av("Default",g)),v(c.exists?"loaded":"new document — the first edit writes it");let{bridgeUrl:h}=await dt();!a&&h&&(S.current=b=cQ({url:h,role:"web",docId:e,name:"web-designer",onFull:a=>{let b=a.def;au(b)&&(m(b),v("updated live"))},onPatch:()=>{},onPresence:a=>Q(a.length)}),b.connect())})().catch(b=>!a&&v(String(b),"warn")),()=>{a=!0,S.current=null,b?.disconnect()}},[d,v]);let V=(0,i.useMemo)(()=>l?bA(l):null,[l]),W=(0,i.useMemo)(()=>V?aK(V):null,[V]),X=(0,i.useMemo)(()=>{if(!l)return[];let a="";return dT(()=>az(l),null,b=>a=b)??[{ruleId:"S000",message:`The document could not be checked (${a}): a field is not the shape Spec 81 gives it`}]},[l]),Y=eh(f,j),Z=(0,i.useMemo)(()=>f?.def&&Y&&l?dT(()=>a5(f.def,f.members.map(a=>a.path===Y?{...a,def:l,error:void 0}:a)),null):null,[f,Y,l]),$=(0,i.useMemo)(()=>(Z?.issues??[]).filter(a=>a.member===Y&&!/^S0/.test(a.ruleId)),[Z,Y]),_=Z?.replays.find(a=>a.member===Y)?.report??null,aa=(0,i.useMemo)(()=>(function(a){let b={events:new Set,states:new Set,machines:new Set,objects:new Set,entities:new Set,actors:new Set};if(!a)return{events:[],states:[],machines:[],objects:[],entities:[],actors:[]};let{machines:c,erds:d}=a4(a.members);for(let{def:a}of(c.forEach(({def:a},c)=>{for(let d of(b.machines.add(a$(a,c)),a.events??[]))for(let a of[...d?.events??[],...d?.timers??[]])a?.id&&b.events.add(a.id);for(let c of a.settings?.objects??[])c?.instance&&b.objects.add(c.instance);let d=a=>{a&&(b.states.add(a.name),(a.states??[]).forEach(d),(a.parallel?.states??[]).forEach(d))};d(a.state)}),d))for(let c of a.entities??[])c?.name&&b.entities.add(c.name);for(let c of a.def?.actors??[])c?.name&&b.actors.add(c.name);let e=a=>[...a].sort((a,b)=>a.localeCompare(b));return{events:e(b.events),states:e(b.states),machines:e(b.machines),objects:e(b.objects),entities:e(b.entities),actors:e(b.actors)}})(f),[f]),ab=(0,i.useMemo)(()=>{let a=a=>a?/^(message|participant):/.test(a)?a:V?.participants.some(b=>b.name===a)?`participant:${a}`:"":"";return[...X.map(b=>a(b.element)),...$.filter(a=>"error"===a.severity).map(b=>a(b.element))].filter(Boolean)},[X,$,V]),ac=(0,i.useMemo)(()=>$.filter(a=>"warning"===a.severity).map(a=>a.element??""),[$]),ad=(0,i.useMemo)(()=>{let a=new Map,b=(b,c)=>{let d=b?/^(message|participant):/.test(b)?b:V?.participants.some(a=>a.name===b)?`participant:${b}`:"":"";d&&a.set(d,[...a.get(d)??[],c])};return X.forEach(a=>b(a.element,{severity:"error",text:a.message})),$.forEach(a=>b(a.element,{severity:"error"===a.severity?"error":"warning",text:a.message})),a},[X,$,V]),ae=()=>{let a=K.current?.getBoundingClientRect();return{width:a?.width??0,height:a?.height??0}},af=(0,i.useCallback)(a=>{let b=K.current?.getBoundingClientRect();if(!b?.width)return;let c=N(Math.max(R([a],b.width,b.height,{padding:24,maxScale:1.1}).scale,.7));o({scale:c,x:b.width/2-(a.x+a.width/2)*c,y:b.height/2-(a.y+a.height/2)*c})},[]),ag=(0,i.useCallback)(a=>{if(W)if("message"===a.kind){let b=W.rows.find(b=>b.ref===a.id);if(!b)return;let c=b.self?b.fromX:Math.min(b.fromX,b.toX),d=b.self?220:Math.abs(b.toX-b.fromX);af({x:c-10,y:b.y-24,width:d+20,height:40})}else{let b=W.participants.find(b=>b.name===a.id);b&&af({x:b.left-20,y:b.top,width:b.width+40,height:Math.min(260,W.height-b.top)})}},[W,af]),ah=(0,i.useCallback)(a=>{if("diagram"===I.current)return ag(a);requestAnimationFrame(()=>document.getElementById(d9(a))?.scrollIntoView({block:"center",behavior:"smooth"}))},[ag]),ai=(0,i.useCallback)(a=>{s(a),a&&dR(`${a.kind}:${a.id}`)},[]);(0,i.useEffect)(()=>{if(!l||!W||U.current===g.nonce)return;U.current=g.nonce;let a=g.focus?a7(g.focus):null;if(!a)return;let b=null;if("message"===a.kind&&ax(V??l,a.name)&&(b={kind:"message",id:a.name}),"participant"===a.kind&&(V??l).participants.some(b=>b.name===a.name)&&(b={kind:"participant",id:a.name}),!b)return v(`${g.focus} is not in this sequence`,"warn");T.current=!1,s(b),ah(b)},[l,V,W,g,ah,v]),(0,i.useEffect)(()=>{if(!W||!T.current||"diagram"!==G)return;let{width:a,height:b}=ae();a&&(T.current=!1,Math.min((a-32)/W.width,(b-32)/W.height)>=.5||0===W.participants.length?q(a=>(a??0)+1):o({x:8,y:8,scale:.6}))},[W,G]);let aj=(0,i.useCallback)(async a=>{let b;if(l&&j){try{b=a(l)}catch(a){return v(a instanceof Error?a.message:String(a),"warn")}m(b);try{let a=await fetch(`/api/file${(0,dj.docQuery)(j)}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify({content:JSON.stringify(b,null,2)+"\n"})});if(!a.ok)throw Error((await a.json())?.error??`HTTP ${a.status}`);S.current?.emitFull(b),v("saved")}catch(a){return v(`not saved: ${a instanceof Error?a.message:String(a)}`,"warn")}if(f?.def&&Y){if("auto"===aN(f.def)){let{result:a,failed:b,conflicts:d}=await ek(f.path);if(a&&a.count>0){var c;return void(c=b.length?`auto: not written — ${b[0]}`:d.length?`auto: ${d.join(", ")} kept changing on disk; not written — save again`:bd(a,"auto"),window.dispatchEvent(new CustomEvent(dO,{detail:{text:c,origin:void 0}})))}}ef()}}},[l,j,v,f,Y]),ak=a=>{let{width:b,height:c}=ae();o(d=>P(d,a,{x:b/2,y:c/2}))},al=()=>{let a,b,c,d,e,f,g,h,i;l&&navigator.clipboard?.writeText((a=["sequenceDiagram"],b=new Map,(l.participants??[]).forEach((c,d)=>{let e=`p${d+1}`;b.set(c.name,e),a.push(` ${c.actor?"actor":"participant"} ${e} as ${aL(c.name)}`)}),c=a=>b.get(a)??aL(a).replace(/\W+/g,"_"),d=(a,b,d)=>{let e=a.reply?"-->>":"->>",f=[`${b} ${aL(a.label??"")}`,a.event?aL(a.event):""].filter(Boolean).join(" · "),g=`${d}${c(a.from)}${e}${c(a.to)}: ${f}`;return a.optional?[`${d}opt optional`,` ${g}`,`${d}end`]:[g]},e=l.messages??[],f=l.fragments??[],g=a=>f.filter(b=>b?.after===a),h=(b,c)=>(b.messages??[]).forEach((e,g)=>a.push(...d(e,`f${f.indexOf(b)+1}.${g+1}`,c+" "))),(i=(b,c,f)=>{for(let j=b;j<=e.length;j++){let b=j===f?[]:g(j);for(let d of b.filter(a=>"alt"!==a.kind))a.push(`${c}${d.kind} ${aL(d.label??"")}`),h(d,c),a.push(`${c}end`);let k=b.filter(a=>"alt"===a.kind);if(k.length){k.forEach((b,d)=>{a.push(`${c}${0===d?"alt":"else"} ${aL(b.label??"")}`),h(b,c)}),j<e.length&&(a.push(`${c}else as written`),i(j,c+" ",j)),a.push(`${c}end`);return}j<e.length&&a.push(...d(e[j],String(j+1),c))}})(0," ",null),a.join("\n")+"\n")).then(()=>v("mermaid copied"))},am=a=>{let b=a?a7(a):null;if(!b||"message"!==b.kind&&"participant"!==b.kind)return;let c={kind:b.kind,id:b.name};ai(c),ah(c),L.close()},an=V??av("",""),ao=ay(an),aq=l&&r?.kind==="message"?ax(an,r.id):null,ar=l&&r?.kind==="participant"?an.participants.find(a=>a.name===r.id)??null:null,as=an.participants.map(a=>a.name),aw=j.split("/").pop()||"…",aJ=X.length+$.filter(a=>"error"===a.severity).length,aM=$.filter(a=>"warning"===a.severity).length,aO=[{id:"participants",label:"Participants",icon:(0,h.jsx)(d7,{kind:"actor"})},{id:"messages",label:"Messages",icon:(0,h.jsx)(d7,{kind:"sequence"})},{id:"notes",label:"Notes",icon:"✎"},{id:"issues",label:"Issues",icon:(0,h.jsx)(dJ,{}),badge:aJ+aM||void 0}],aP=a=>[{name:"from",label:"from",options:as,initial:a?.from??as[0]??""},{name:"to",label:"to",options:as,initial:a?.to??as[1]??as[0]??""},{name:"label",label:"label",placeholder:"what is said or done",initial:a?.label??"",wide:!0},{name:"event",label:"event it fires",suggest:aa.events,initial:a?.event??""},{name:"state",label:"state after",suggest:aa.states,initial:a?.state??""},{name:"carries",label:"entity it carries",suggest:aa.entities,initial:a?.carries??""},{name:"machine",label:"machine",suggest:aa.machines,initial:a?.machine??""},{name:"optional",label:"optional",checkbox:!0,initial:!!a?.optional},{name:"reply",label:"reply (dashed)",checkbox:!0,initial:!!a?.reply}],aQ=a=>a.actor?"actor":a.object?"object":a.service?"service":"",aR=["main: at the end",...aq&&null===aq.fragment?[`main: after ${aq.index+1}`]:[],...(l?.fragments??[]).map((a,b)=>`fragment ${b+1}: ${a.kind} \xb7 ${a.label}`)];return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>C&&D(!1),children:[(0,h.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,h.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,h.jsx)(d7,{kind:"sequence",size:14}),"SEQ"]}),(0,h.jsx)(dk,{}),(0,h.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:j,children:[l?.settings.name??aw,(0,h.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",aw]})]}),(0,h.jsx)("div",{className:"flex shrink-0 overflow-hidden rounded border border-gray-700 text-[12px] leading-none",role:"group","aria-label":"View",children:[["list","List","Read the messages in order, one under the other"],["diagram","Diagram","The lifelines and arrows"]].map(([a,b,c])=>(0,h.jsx)("button",{title:c,"aria-pressed":G===a,onClick:()=>{G!==a&&(r&&(T.current=!1),J(a),r&&requestAnimationFrame(()=>ah(r)))},className:`px-2.5 py-1.5 ${G===a?"bg-gray-700 text-gray-100":"bg-gray-800 text-gray-400 hover:text-gray-200"}`,children:b},a))}),(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,h.jsx)("button",{className:d4,onClick:al,children:"Copy mermaid"}),(0,h.jsx)("button",{className:d4,onClick:()=>F(a=>!a),"aria-pressed":!E,title:E?"Show the panel":"Hide the panel — the board takes the full width",children:E?"⟨ Panel":"Panel ⟩"})]}),(0,h.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,h.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":C,onClick:a=>{a.stopPropagation(),D(a=>!a)},children:"⋯"}),C&&(0,h.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:(0,h.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{D(!1),al()},children:"Copy as mermaid"})})]})]}),(0,h.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,h.jsxs)("div",{ref:K,className:"relative min-w-0 flex-1 overflow-hidden",children:[l&&W&&"list"===G&&V&&(0,h.jsx)(dI,{what:"sequence",resetKey:l,children:(0,h.jsx)(ea,{definition:V,selection:r,issues:ad,onSelect:a=>ai(a),onShowInDiagram:a=>{T.current=!1,J("diagram"),requestAnimationFrame(()=>ag(a))}})}),l&&W&&"diagram"===G&&(0,h.jsx)(dI,{what:"sequence",resetKey:l,children:(0,h.jsx)(bB,{definition:V,layout:W,viewport:n,onViewportChange:o,selection:r,errorElements:ab,warningElements:ac,fitKey:p,onSelect:(a,b)=>ai({kind:a,id:b}),onClearSelection:()=>s(null),emptyHint:"No participants yet — add them in the panel, or let an agent write the scenario."})}),(0,h.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===t.tone?"text-amber-300":"text-gray-500"} ${"list"===G&&w&&"ok"===t.tone?"hidden":"flex"}`,role:"status",children:[(0,h.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===t.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,h.jsxs)("span",{className:`truncate transition-opacity duration-500 ${w&&"ok"===t.tone?"opacity-0":"opacity-100"}`,children:[t.text,O>1?` \xb7 ${O} in the room`:""]})]}),(0,h.jsx)("div",{className:`absolute bottom-3 right-3 flex-col overflow-hidden rounded-lg border border-gray-700 bg-gray-900/90 shadow-lg backdrop-blur ${"diagram"===G?"flex":"hidden"}`,children:[["+","Zoom in",()=>ak(1.25)],["−","Zoom out",()=>ak(.8)],["⛶","Fit the whole diagram",()=>q(a=>(a??0)+1)]].map(([a,b,c])=>(0,h.jsx)("button",{title:b,"aria-label":b,onClick:c,className:"h-10 w-10 border-b border-gray-800 text-base leading-none text-gray-200 last:border-b-0 hover:bg-gray-800 md:h-8 md:w-8 md:text-sm",children:a},b))}),r&&!A&&(0,h.jsxs)("button",{className:"absolute bottom-3 left-1/2 max-w-[60%] -translate-x-1/2 truncate rounded-full border border-blue-500/60 bg-gray-900/95 px-4 py-2 text-sm text-blue-200 shadow-lg md:hidden",onClick:()=>{z("message"===r.kind?"messages":"participants"),B(!0)},children:["Edit ","message"===r.kind?`${r.id}. ${aq?.message.label??""}`:r.id]})]}),A&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:L.close,"aria-hidden":"true"}),l&&(0,h.jsxs)("aside",{style:L.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${A?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${E?"md:hidden":""}`,children:[(0,h.jsxs)("div",{className:"md:hidden",...L.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:aO.find(a=>a.id===y)?.label}),(0,h.jsx)("button",{onClick:L.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:aO.map(a=>(0,h.jsxs)("button",{onClick:()=>z(a.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${y===a.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[a.label,void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:a.badge})]},a.id))}),(0,h.jsx)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:(0,h.jsxs)(dI,{what:"panel",resetKey:l,children:[(0,h.jsxs)("section",{className:"participants"===y?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Participants"}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:an.participants.map(a=>(0,h.jsxs)("button",{className:`${d4} ${r?.kind==="participant"&&r.id===a.name?"border-blue-500 text-blue-300":""}`,onClick:()=>{ai({kind:"participant",id:a.name}),ah({kind:"participant",id:a.name})},title:aQ(a)||"participant",children:[a.name,aQ(a)&&(0,h.jsxs)("span",{className:"text-gray-500",children:[" · ",aQ(a)]})]},a.name))}),(0,h.jsx)(d6,{id:"add-participant",reset:!0,required:["name"],fields:[{name:"name",placeholder:"new participant"},{name:"kind",options:em,label:"kind"},{name:"value",placeholder:"actor / service / object",suggest:[...aa.actors,...aa.objects]},{name:"holds",placeholder:"holds: Entity, Entity",suggest:aa.entities}],submit:"+ Participant",onSubmit:a=>{let b=en(a.name),c=en(a.kind);aj(d=>(function(a,b,c){if(!b.name?.trim())throw Error("A participant needs a name.");let d=aA(a);if(d.participants.some(a=>a.name===b.name))throw Error(`Participant '${b.name}' already exists.`);let e=d.participants.length;return d.participants.splice(e,0,aB({...b})),d})(d,{name:b,...c?{[c]:en(a.value)||b}:{},holds:eo(a.holds)})),ai({kind:"participant",id:b})}}),ar&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:`${d5} flex items-center justify-between gap-2`,children:[(0,h.jsx)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:ar.name}),(0,h.jsx)("button",{className:`${d4} normal-case tracking-normal`,onClick:()=>ah({kind:"participant",id:ar.name}),children:"◎ Show on board"})]}),(a=an.participants.findIndex(a=>a.name===ar.name),b=an.participants.length-1,c=a=>aj(b=>{var c;let d,e;return c=ar.name,e=aC(d=aA(b),c),d.participants.splice(d.participants.indexOf(e),1),d.participants.splice(Math.max(0,Math.min(a,d.participants.length)),0,e),d}),(0,h.jsxs)("div",{className:"mb-1 flex items-center gap-1 text-[11px] text-gray-400",children:[(0,h.jsx)("button",{className:`${d4} disabled:opacity-40`,disabled:a<=0,onClick:()=>c(a-1),"aria-label":"Move one column left",children:"← Left"}),(0,h.jsxs)("span",{className:"flex-1 text-center",children:["column ",a+1," of ",b+1]}),(0,h.jsx)("button",{className:`${d4} disabled:opacity-40`,disabled:a>=b,onClick:()=>c(a+1),"aria-label":"Move one column right",children:"Right →"})]})),(0,h.jsx)(d6,{id:"rename-participant",required:["to"],fields:[{name:"to",label:"new name",initial:ar.name}],submit:"Rename (every message follows)",onSubmit:a=>{let b=en(a.to);b!==ar.name&&(aj(a=>(function(a,b,c){if(!c?.trim())throw Error("A participant needs a name.");let d=aA(a),e=aC(d,b);if(c===b)return d;if(d.participants.some(a=>a.name===c))throw Error(`Participant '${c}' already exists.`);e.name=c;let f=a=>{a.from===b&&(a.from=c),a.to===b&&(a.to=c)};for(let a of(d.messages.forEach(f),d.fragments??[]))a.messages.forEach(f);return d})(a,ar.name,b)),ai({kind:"participant",id:b}))}},`rename:${ar.name}`),(0,h.jsx)(d6,{id:"edit-participant",fields:[{name:"kind",options:em,label:"kind",initial:aQ(ar)},{name:"value",placeholder:"actor / service / object",suggest:[...aa.actors,...aa.objects],initial:ar.actor??ar.object??ar.service??""},{name:"holds",placeholder:"holds: Entity, Entity",suggest:aa.entities,initial:(ar.holds??[]).join(", "),wide:!0},{name:"description",placeholder:"description",initial:ar.description??"",wide:!0}],submit:"Save participant",onSubmit:a=>aj(b=>{let c,d;return aF(b,ar.name,{...(c=en(a.kind),d=en(a.value)||ar.name,{actor:"actor"===c?d:"",service:"service"===c?d:"",object:"object"===c?d:""}),holds:eo(a.holds),description:en(a.description)})})},`p:${JSON.stringify(ar)}`),(0,h.jsxs)("button",{className:`${d4} mt-2 text-red-300`,onClick:()=>{aj(a=>{var b;let c,d;return b=ar.name,aC(c=aA(a),b),c.participants=c.participants.filter(a=>a.name!==b),d=a=>a.from!==b&&a.to!==b,c.messages=c.messages.filter(d),c.fragments&&(c.fragments=c.fragments.map(b=>{let c;return{...b,after:Math.max(0,b.after-(c=b.after,a.messages.slice(0,c).filter(a=>!d(a)).length)),messages:b.messages.filter(d)}}).filter(a=>a.messages.length>0),c.fragments.length||delete c.fragments),c}),s(null),dR(null)},title:"Also removes every message it sends or receives",children:["Delete ",ar.name," and its messages"]})]})]}),(0,h.jsxs)("section",{className:"messages"===y?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Messages"}),0===ao.length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None yet."}),(0,h.jsx)("div",{className:"flex flex-col",children:ao.map(({ref:a,message:b,fragment:c},d)=>{let e=null!==c&&(0===d||ao[d-1].fragment!==c),f=null!==c?an.fragments?.[c]:void 0,g=r?.kind==="message"&&r.id===a;return(0,h.jsxs)("div",{children:[e&&f&&(0,h.jsxs)("div",{className:"mt-2 border-t border-gray-800 pt-1 text-[11px] text-indigo-300",children:[(0,h.jsx)("span",{className:"font-semibold",children:f.kind})," · after ",f.after," · ",f.label]}),(0,h.jsxs)("button",{className:`block w-full truncate rounded px-1 py-0.5 text-left text-[11px] ${g?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>{ai({kind:"message",id:a}),ah({kind:"message",id:a})},title:`${b.from} → ${b.to}: ${b.label}`,children:[(0,h.jsxs)("span",{className:"text-gray-500",children:[a,"."]})," ",b.from," → ",b.to,": ",b.label,b.event?(0,h.jsxs)("span",{className:"text-blue-300",children:[" [",b.event,"]"]}):null,b.state?(0,h.jsxs)("span",{className:"text-emerald-400",children:[" → ",b.state]}):null,b.optional?(0,h.jsx)("span",{className:"text-gray-500",children:" opt"}):null]})]},a)})}),aq&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:`${d5} flex items-center justify-between gap-2`,children:[(0,h.jsxs)("span",{className:"truncate text-sm normal-case tracking-normal text-gray-200",children:["Message ",r.id]}),(0,h.jsxs)("span",{className:"flex gap-1 normal-case tracking-normal",children:[null===aq.fragment&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("button",{className:d4,"aria-label":"Move up",title:"Move up",disabled:0===aq.index,onClick:()=>{aj(a=>aI(a,aq.index,aq.index-1)),ai({kind:"message",id:String(aq.index)})},children:"↑"}),(0,h.jsx)("button",{className:d4,"aria-label":"Move down",title:"Move down",disabled:aq.index>=an.messages.length-1,onClick:()=>{aj(a=>aI(a,aq.index,aq.index+1)),ai({kind:"message",id:String(aq.index+2)})},children:"↓"})]}),(0,h.jsx)("button",{className:d4,onClick:()=>ah(r),children:"◎ Show"})]})]}),(0,h.jsx)(d6,{id:"edit-message",required:["label"],fields:[...aP(aq.message),{name:"description",placeholder:"description",initial:aq.message.description??"",wide:!0}],submit:"Save message",onSubmit:a=>aj(b=>aH(b,aq.index,ep(a),aq.fragment))},`m:${r.id}:${JSON.stringify(aq.message)}`),(0,h.jsxs)("button",{className:`${d4} mt-2 text-red-300`,onClick:()=>{aj(a=>(function(a,b,c=null){let d=aA(a);if(null!==c){let a=aE(d,c);if(!a.messages[b])throw Error(`Message ${b+1} not found in fragment ${c+1}.`);return a.messages.splice(b,1),d}if(!d.messages[b])throw Error(`Message ${b+1} not found. The sequence has ${d.messages.length}.`);if(d.messages.splice(b,1),d.fragments)for(let a of d.fragments)a.after>b&&(a.after-=1);return d})(a,aq.index,aq.fragment)),s(null),dR(null)},children:["Delete message ",r.id]})]}),(0,h.jsx)("div",{className:d5,children:"Add a message"}),(0,h.jsx)(d6,{id:"add-message",reset:!0,required:["label"],fields:[{name:"where",options:aR,label:"where",wide:!0},...aP()],submit:"+ Message",onSubmit:a=>{let b=en(a.where),c=ep(a),d=/^fragment (\d+):/.exec(b),e=/^main: after (\d+)$/.exec(b);d?aj(a=>{var b;let e,f,g;return b=Number(d[1])-1,f=aE(e=aA(a),b),aD(e,c),g=f.messages.length,f.messages.splice(g,0,aB({...c})),e}):e?aj(a=>aG(a,c,Number(e[1]))):aj(a=>aG(a,c))}},`add:${aR.join("|")}:${as.join("|")}`),(0,h.jsx)("div",{className:d5,children:"Fragments"}),0===(an.fragments??[]).length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"None."}),(an.fragments??[]).map((a,b)=>(0,h.jsxs)("div",{className:"mb-2 rounded border border-gray-800 p-1.5",children:[(0,h.jsxs)("div",{className:"flex items-center justify-between text-[11px] text-indigo-300",children:[(0,h.jsxs)("span",{children:[b+1,". ",(0,h.jsx)("span",{className:"font-semibold",children:a.kind})," · after ",a.after," · ",a.messages.length," message(s)"]}),(0,h.jsx)("button",{className:"text-gray-500 hover:text-red-400","aria-label":`Remove fragment ${b+1}`,onClick:()=>aj(a=>{let c;return aE(c=aA(a),b),c.fragments.splice(b,1),c.fragments.length||delete c.fragments,c}),children:"✕"})]}),(0,h.jsx)(d6,{id:`edit-fragment-${b}`,fields:[{name:"kind",options:at,initial:a.kind},{name:"after",placeholder:"after message",initial:String(a.after)},{name:"label",placeholder:"the condition, in words",initial:a.label,wide:!0}],submit:"Save fragment",onSubmit:a=>aj(c=>(function(a,b,c){let d=aA(a),e=aE(d,b);if(void 0!==c.kind&&!at.includes(c.kind))throw Error(`A fragment is one of ${at.join(", ")}; got '${c.kind}'.`);if(void 0!==c.after&&(!Number.isInteger(c.after)||c.after<0||c.after>d.messages.length))throw Error(`A fragment branches after a main message, 0 to ${d.messages.length}; got ${c.after}.`);return d.fragments[b]={...aB({...e,...c,messages:void 0}),messages:e.messages??[]},d})(c,b,{kind:en(a.kind),after:Number(en(a.after)),label:en(a.label)}))})]},`${b}:${JSON.stringify({...a,messages:void 0})}`)),(0,h.jsx)(d6,{id:"add-fragment",reset:!0,required:["label"],fields:[{name:"kind",options:at},{name:"after",placeholder:"after message",initial:String(aq&&null===aq.fragment?aq.index+1:an.messages.length)},{name:"label",placeholder:"the condition, in words",wide:!0},{name:"from",options:as,label:"first message from"},{name:"to",options:as,label:"to",initial:as[1]??as[0]??""},{name:"first",placeholder:"first message label (optional)",wide:!0}],submit:"+ Fragment",onSubmit:a=>aj(b=>(function(a,b){if(!at.includes(b.kind))throw Error(`A fragment is one of ${at.join(", ")}; got '${b.kind}'.`);if(!b.label?.trim())throw Error("A fragment needs a label: the condition in words.");let c=aA(a);if(!Number.isInteger(b.after)||b.after<0||b.after>c.messages.length)throw Error(`A fragment branches after a main message, 0 to ${c.messages.length}; got ${b.after}.`);for(let a of b.messages??[])aD(c,a);return(c.fragments??=[]).push({...aB({...b,messages:void 0}),messages:(b.messages??[]).map(a=>aB({...a}))}),c})(b,{kind:en(a.kind),after:Number(en(a.after)),label:en(a.label),messages:en(a.first)?[{from:en(a.from),to:en(a.to),label:en(a.first)}]:[]}))},`add-fragment:${an.messages.length}:${aq?.index??""}`)]}),(0,h.jsxs)("section",{className:"notes"===y?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Notes"}),(0,h.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the document, for whoever opens it next — you, or an agent."}),(0,h.jsx)(d1,{label:"On this sequence",value:l.settings.notes??"",placeholder:"What was discussed, what is still open…",onSave:a=>aj(b=>{var c;let d;return c={notes:a},(d=aA(b)).settings=aB({...d.settings,...c}),d})},"sequence"),ar&&(0,h.jsx)(d1,{label:`On ${ar.name}`,value:ar.notes??"",placeholder:`A question or a decision about ${ar.name}…`,onSave:a=>aj(b=>aF(b,ar.name,{notes:a}))},`participant:${ar.name}`),aq&&(0,h.jsx)(d1,{label:`On message ${r.id}`,value:aq.message.notes??"",placeholder:"A question or a decision about this message…",onSave:a=>aj(b=>aH(b,aq.index,{notes:a},aq.fragment))},`message:${r.id}`),!r&&(0,h.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Select a participant or a message to leave a note on it."}),[...an.participants.filter(a=>a.notes?.trim()),...ao.filter(a=>a.message.notes?.trim())].length>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:d5,children:"With notes"}),(0,h.jsxs)("div",{className:"flex flex-wrap gap-1",children:[an.participants.filter(a=>a.notes?.trim()).map(a=>(0,h.jsx)("button",{className:d4,onClick:()=>am(`participant:${a.name}`),children:a.name},`p${a.name}`)),ao.filter(a=>a.message.notes?.trim()).map(a=>(0,h.jsxs)("button",{className:d4,onClick:()=>am(`message:${a.ref}`),children:["message ",a.ref]},`m${a.ref}`))]})]})]}),(0,h.jsxs)("section",{className:"issues"===y?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Issues"}),X.map((a,b)=>(0,h.jsxs)("button",{className:"block w-full py-0.5 text-left text-[11px] text-red-300",onClick:()=>am(a.element),children:["[",a.ruleId,"] ",a.message]},`p${b}`)),$.map((a,b)=>(0,h.jsxs)("button",{className:`block w-full py-0.5 text-left text-[11px] ${"error"===a.severity?"text-red-300":"text-amber-300"}`,onClick:()=>am(a.element),children:["[",a.ruleId,"] ",a.message]},`s${b}`)),0===X.length&&0===$.length&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-green-400",children:Z?"Valid, and every name it uses resolves in the system.":"The document is valid."}),!e&&(0,h.jsx)("p",{className:"mt-2 text-[11px] text-gray-600",children:"Open this sequence from its system to check it against the machines and the data."}),e&&!Y&&f&&(0,h.jsx)("p",{className:"mt-2 text-[11px] text-amber-300",children:"This document is not a member of the open system."}),_&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:d5,children:["Replay against ",_.machines.join(", ")||"no machine"]}),_.paths.map(a=>(0,h.jsxs)("div",{className:"mb-2",children:[(0,h.jsxs)("div",{className:`text-[11px] font-semibold ${a.accepted?"text-green-400":"text-amber-300"}`,children:[a.name," — ",a.accepted?"accepted":"stops"]}),a.steps.filter(a=>"data"!==a.result).map(b=>(0,h.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===b.result||"stayed"===b.result?"text-gray-400":"text-amber-300"}`,title:b.note??b.result,onClick:()=>am(`message:${b.ref}`),children:[b.ref,". ",b.event??""," ",b.from.join("|")||"·"," → ",b.to.join("|")||"·"," ",b.result]},`${a.name}:${b.ref}`))]},a.name))]})]})]})})]})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:aO.map(a=>{let b=A&&y===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(A&&y===b?L.close():B(!0),z(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})})]})}function er(a,b){let c=a?.members.find(a=>a.path===b)?.def;return c?.settings?.name||(b.split("/").pop()??b).replace(/\.(smdf|erdf|sqdf|sysdf)\.json$|\.json$/i,"")}let es=(a,b)=>a?.members.find(a=>a.path===b)?.kind??"machine";function et(a){return"message"===a.kind?`message ${a.name}`:`${a.kind} ${a.name}`}function eu({systemPath:a}){let b=dP("doc"),c=dP("focus"),{system:d}=eg(a),[e,f]=(0,i.useState)(!1),[g,j]=(0,i.useState)(null),k=(0,i.useRef)(d);(0,i.useEffect)(()=>{k.current=d},[d]);let l=(0,i.useMemo)(()=>d?dT(()=>a8(d.members),[]):[],[d]),m=eh(d,b),n=!!d&&(b===d.path||b===a),o=m&&c?function(a,b,c){let d=a7(c);if(!d)return[];let e=a=>a.member===b&&a.kind===d.kind&&a.name===d.name,f=[];for(let b of a)e(b.from)?f.push({other:b.to,text:b.text,rule:b.rule}):e(b.to)&&f.push({other:b.from,text:b.back,rule:b.rule});return f}(l,m,c):[],p=function(a,b){if(!b)return[];let c=new Map;for(let d of a)for(let a of[d.from,d.to]){if(a.member!==b)continue;let d=a6(a);c.set(d,(c.get(d)??0)+1)}return[...c.entries()].sort((a,b)=>a[0].localeCompare(b[0]))}(l,m);(0,i.useEffect)(()=>{let a=a=>{let b=a.detail;b?.text&&j({...b,at:Date.now()})};return window.addEventListener(dO,a),()=>window.removeEventListener(dO,a)},[]),(0,i.useEffect)(()=>{if(!g)return;let a=setTimeout(()=>j(null),9e3);return()=>clearTimeout(a)},[g]);let q=d?.path;(0,i.useEffect)(()=>{if(!q)return;let b=!0,c=null,d=null;return(async()=>{let{bridgeUrl:e}=await dt();if(b&&e){var g;let b,h,i,l;(c=cO({url:e,role:"web",docId:q,name:"web-system-strip"})).on("view",b=>{let c=k.current;if(!c)return;let d=b.member?void 0!==c.absOf[b.member]?b.member:Object.keys(c.absOf).find(a=>c.absOf[a]===b.member):void 0;if(b.member&&!d)return void j({text:`ignored a view of ${b.member.split("/").pop()}: it is not a member of this system`,origin:b.origin,at:Date.now()});dQ({doc:d?c.absOf[d]:q,system:a,focus:b.focus??null}),f(!1);let e=[d?er(c,d):"the system map",b.focus].filter(Boolean).join(" · ");j({text:b.note?b.note:`showing ${e}`,origin:b.origin,at:Date.now()})}),c.on("full",()=>ef()),g=c,b=!1,h=!1,i=()=>{g.join().then(()=>{b=!0}).catch(()=>{})},l=g.on("status",a=>{"connected"!==a?h=b:h&&(h=!1,i())}),i(),d=()=>{l()}}})(),()=>{b=!1,d?.(),c?.disconnect()}},[q,a]);let r=b=>{f(!1),d&&dQ({doc:b.member?d.absOf[b.member]??aU(d.path,b.member):d.path,system:a,focus:b.focus??null})},s=d?.def?.members?.filter(a=>a?.path).map(a=>a.path)??[],t=d?.def?.settings?.name??(a.split("/").pop()??"system").replace(/\.sysdf\.json$/i,""),u=o.length;return(0,h.jsxs)("div",{className:"system-strip relative z-50 border-b border-gray-800 bg-gray-950 text-xs text-gray-300",children:[(0,h.jsxs)("div",{className:"flex h-[var(--strip-h)] items-center gap-1 px-1.5 md:px-2",children:[(0,h.jsxs)("button",{onClick:()=>r({}),className:`flex min-w-0 max-w-[30%] shrink-0 items-center gap-1 rounded px-1.5 py-1 md:max-w-[16rem] ${n?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,title:`${a} — the system map`,children:[(0,h.jsx)(d7,{kind:"system",size:15}),(0,h.jsx)("span",{className:"truncate font-semibold",children:t})]}),(0,h.jsx)("span",{className:"h-4 w-px shrink-0 bg-gray-800"}),(0,h.jsxs)("nav",{className:"flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto [scrollbar-width:none]","aria-label":"Members",children:[s.map(a=>{let b=a===m,c=d?.members.find(b=>b.path===a)?.error;return(0,h.jsxs)("button",{onClick:()=>r({member:a}),"aria-current":b?"page":void 0,title:`${er(d,a)} — ${a}${c?` (cannot be read: ${c})`:""}`,className:`flex shrink-0 items-center gap-1 rounded px-1.5 py-1 ${b?"bg-blue-950/60 text-blue-200":c?"text-red-400 hover:bg-gray-800":"text-gray-400 hover:bg-gray-800 hover:text-gray-200"}`,children:[(0,h.jsx)(d7,{kind:es(d,a),size:15}),(0,h.jsx)("span",{className:`max-w-[7.5rem] truncate md:max-w-[11rem] ${b?"":"hidden md:inline"}`,children:er(d,a)})]},a)}),!d&&(0,h.jsx)("span",{className:"px-1 text-gray-600",children:"loading…"}),d?.error&&(0,h.jsx)("span",{className:"truncate px-1 text-amber-300",children:d.error})]}),(0,h.jsxs)("button",{onClick:()=>f(a=>!a),disabled:!m,"aria-expanded":e,title:m?c?`What ${c} links to in the other drawings`:"Elements of this drawing that link to the others":"Open a member to follow its links",className:`flex shrink-0 items-center gap-1 rounded px-1.5 py-1 disabled:opacity-40 ${e?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,children:[(0,h.jsx)(d7,{kind:"link",size:15}),(0,h.jsx)("span",{className:"hidden sm:inline",children:"Links"}),u>0&&(0,h.jsx)("span",{className:"rounded-full border border-gray-700 px-1 text-[10px] leading-4 text-gray-300",children:u})]})]}),g&&!e&&(0,h.jsx)("div",{className:"pointer-events-none absolute inset-x-0 top-full flex justify-center px-2 pt-1",role:"status",children:(0,h.jsxs)("span",{className:"max-w-full truncate rounded border border-gray-700 bg-gray-900/95 px-2 py-0.5 text-[11px] text-gray-300 shadow",children:[g.origin?(0,h.jsxs)("span",{className:"text-blue-300",children:[g.origin,": "]}):null,g.text]})}),e&&m&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:"fixed inset-0 z-40",onClick:()=>f(!1),"aria-hidden":"true"}),(0,h.jsxs)("div",{className:"absolute right-1 top-full z-50 mt-1 max-h-[60vh] w-[min(24rem,calc(100vw-0.5rem))] overflow-y-auto rounded-lg border border-gray-700 bg-gray-900 p-2 shadow-xl",children:[c&&a7(c)?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:"mb-1 flex items-center justify-between gap-2 text-[11px] text-gray-500",children:[(0,h.jsxs)("span",{className:"truncate",children:[(0,h.jsx)("span",{className:"text-gray-200",children:et(a7(c))})," in ",er(d,m)]}),(0,h.jsx)("button",{className:"shrink-0 text-gray-500 hover:text-gray-200",onClick:()=>dQ({doc:b,focus:null}),children:"clear"})]}),0===o.length&&(0,h.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"Nothing in the other drawings names it."}),o.map((a,b)=>(0,h.jsxs)("button",{onClick:()=>r({member:a.other.member,focus:a6(a.other)}),className:"flex w-full items-start gap-2 rounded px-1.5 py-1.5 text-left hover:bg-gray-800",children:[(0,h.jsx)("span",{className:"mt-0.5 text-gray-400",children:(0,h.jsx)(d7,{kind:es(d,a.other.member),size:14})}),(0,h.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,h.jsx)("span",{className:"block text-[12px] text-gray-200",children:a.text}),(0,h.jsxs)("span",{className:"block truncate text-[10.5px] text-gray-500",children:[et(a.other)," · ",er(d,a.other.member)," · ",a.rule]})]})]},b))]}):null,(!c||!a7(c))&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["Elements of ",er(d,m)," that the other drawings name — pick one to follow it."]}),0===p.length&&(0,h.jsx)("div",{className:"py-1 text-[11px] text-gray-500",children:"None."}),(0,h.jsx)("div",{className:"flex flex-wrap gap-1",children:p.map(([a,c])=>(0,h.jsxs)("button",{onClick:()=>{f(!0),dQ({doc:b,focus:a})},className:"rounded border border-gray-700 bg-gray-800 px-1.5 py-0.5 text-[11px] text-gray-200 hover:bg-gray-700",children:[a," ",(0,h.jsx)("span",{className:"text-gray-500",children:c})]},a))})]})]})]})]})}let ev={erd:"ERD",machine:"STATE MACHINE",sequence:"SEQUENCE",system:"SYSTEM"};function ew(a,b,c=!1){if(!b)return"";if("erd"===a)return`${b.entities?.length??0} entities \xb7 ${b.relationships?.length??0} relationships`;if("sequence"===a){let a=b.fragments?.length??0;return`${b.participants?.length??0} participants \xb7 ${b.messages?.length??0} messages${a&&!c?` \xb7 ${a} fragment${a>1?"s":""}`:""}`}let d=0,e=a=>{a&&(d+=1,(a.states??[]).forEach(e),(a.parallel?.states??[]).forEach(e))};(b.state?.states??[]).forEach(e),(b.state?.parallel?.states??[]).forEach(e);let f=(b.events??[]).reduce((a,b)=>a+(b?.events?.length??0)+(b?.timers?.length??0),0);return`${d} states \xb7 ${f} events`}let ex=(a,b)=>a<b?`${a}\u0000${b}`:`${b}\u0000${a}`;function ey(a){let b="message"===a.from.kind?`message ${a.from.name}`:`${a.from.kind} ${a.from.name}`;return`${b} ${a.text}`}function ez(){let a=(0,dj.useRequestedDoc)(),[b,c]=(0,i.useState)(a);(0,i.useEffect)(()=>{let b=!0;if(a)c(a);else eb(null).then(a=>b&&c(a.path||null));return()=>{b=!1}},[a]);let{system:d,reload:e}=eg(b),[f,g]=(0,i.useState)("members"),[j,k]=(0,i.useState)(!1),[l,m]=(0,i.useState)(!1),[n,o]=(0,i.useState)(!1),[p,q]=(0,i.useState)(null),[r,s]=(0,i.useState)({text:"loading…",tone:"ok"}),t=(0,i.useCallback)((a,b="ok")=>s({text:a,tone:b}),[]),[u,v]=(0,i.useState)(!1),w=dL({onClose:()=>k(!1),restVh:62,tallVh:92}),x=(0,i.useRef)(null),[y,z]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=x.current;if(!a)return;let b=()=>{let b=a.getBoundingClientRect();b.width&&z(b.height>1.1*b.width)};b();let c=new ResizeObserver(b);return c.observe(a),()=>c.disconnect()},[]);let A=(0,i.useRef)(!1);(0,i.useEffect)(()=>{d&&(d.error?t(d.error,"warn"):A.current||t(`${d.members.length} member${1===d.members.length?"":"s"} loaded`),A.current=!0)},[d,t]);let[B,C]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let a=setTimeout(()=>C(!0),4e3);return()=>{clearTimeout(a),C(!1)}},[r]);let D=(0,i.useMemo)(()=>d?.def?dT(()=>a5(d.def,d.members),null):null,[d]),E=(0,i.useMemo)(()=>d?dT(()=>a8(d.members),[]):[],[d]),F=(0,i.useMemo)(()=>d?.def?dT(()=>bc(d.def,d.members),null):null,[d]),G=aN(d?.def),H=(0,i.useMemo)(()=>{let a=new Map;for(let b of E){if(b.from.member===b.to.member)continue;let c=ex(b.from.member,b.to.member),d=a.get(c)??{a:c.split("\0")[0],b:c.split("\0")[1],links:[]};d.links.push(b),a.set(c,d)}return a},[E]),I=(D?.issues??[]).filter(a=>"error"===a.severity),J=(D?.issues??[]).filter(a=>"warning"===a.severity),K=(b,c)=>{d&&dQ({doc:d.absOf[b]??b,system:a??d.path,focus:c??null})},L=async(a,b)=>{if(d)try{await ed(d.path,a,d.mtimes[d.path]),t(b),ef()}catch(a){a instanceof ec?(t("the system changed on disk — reloaded; make the change again","warn"),ef()):t(`not saved: ${a instanceof Error?a.message:String(a)}`,"warn")}},M=async()=>{if(!d||!F||!F.count)return;v(!0);let{result:a,written:b,failed:c,conflicts:e}=await ek(d.path);v(!1),c.length?t(`not all written: ${c.join("; ")}`,"warn"):e.length?t(`${e.join(", ")} kept changing on disk — not written; apply again`,"warn"):a?.count?t(`${bd(a,"propose").replace(/ proposed/," applied")} — ${b.length} file(s) written`):t("nothing to apply: the drawings on disk already agree")},N=y?420:760,O=y?640:520,P=d?.def?.members?.filter(a=>a?.path).map(a=>a.path)??[],Q=d?.def?.actors??[],R=64*!!Q.length,S=(0,i.useMemo)(()=>{let a=P.length,b=N/2,c=(O-R)/2+6,d=Math.max(0,N/2-98-16),e=Math.max(0,(O-R)/2-46-18),f=new Map;return P.forEach((g,h)=>{if(1===a)return f.set(g,{x:b,y:c});if(y){let b=O-R-46-16;return f.set(g,{x:h%2?.67*N:.33*N,y:62+(b-62)*h/(a-1)})}if(2===a)return f.set(g,y?{x:b,y:h?c+e:c-e}:{x:h?b+d:b-d,y:c});let i=-Math.PI/2+2*h*Math.PI/a;f.set(g,{x:b+d*Math.cos(i),y:c+e*Math.sin(i)})}),f},[P.join("|"),N,O,196,R,y]),T=(0,i.useMemo)(()=>{let a=new Map;for(let{member:b,def:c}of a4(d?.members??[]).sequences)for(let d of c.participants??[]){if(!d?.actor)continue;let c=a.get(d.actor)??[];c.includes(b)||c.push(b),a.set(d.actor,c)}return a},[d]),U=d?.def,V=(d?.path??b??"").split("/").pop()||"…",W=[{id:"members",label:"Members",icon:(0,h.jsx)(d7,{kind:"system"})},{id:"checks",label:"Checks",icon:(0,h.jsx)(dJ,{}),badge:I.length+J.length||void 0},{id:"notes",label:"Notes",icon:"✎"}],X=p?H.get(p):void 0,Y=(0,i.useMemo)(()=>{let a=[];for(let b of["error","warning"]){let c=new Map;for(let a of D?.issues??[])a.severity===b&&c.set(a.ruleId,[...c.get(a.ruleId)??[],a]);for(let[d,e]of[...c.entries()].sort((a,b)=>a[0].localeCompare(b[0])))a.push({key:`${b}:${d}`,ruleId:d,severity:b,issues:e})}return a},[D]);return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden bg-gray-950 text-gray-200",onClick:()=>l&&m(!1),children:[(0,h.jsxs)("header",{className:"relative z-40 flex items-center gap-2 border-b border-gray-800 bg-gray-900 px-2 py-1.5 text-xs md:px-3 md:py-2",children:[(0,h.jsxs)("span",{className:"flex items-center gap-1 font-semibold text-blue-300",children:[(0,h.jsx)(d7,{kind:"system",size:14}),"SYS"]}),(0,h.jsx)(dk,{}),(0,h.jsxs)("span",{className:"min-w-0 flex-1 truncate text-gray-400",title:d?.path,children:[U?.settings?.name??V,(0,h.jsxs)("span",{className:"hidden text-gray-600 lg:inline",children:[" · ",V]})]}),(0,h.jsxs)("div",{className:"hidden shrink-0 items-center gap-2 md:flex",children:[(0,h.jsx)("button",{className:d4,onClick:e,title:"Read the system and every member again",children:"Re-check"}),(0,h.jsx)("button",{className:d4,onClick:()=>o(a=>!a),"aria-pressed":!n,children:n?"⟨ Panel":"Panel ⟩"})]}),(0,h.jsxs)("div",{className:"relative shrink-0 md:hidden",children:[(0,h.jsx)("button",{className:"rounded border border-gray-700 bg-gray-800 px-3 py-1.5 text-sm leading-none text-gray-200","aria-label":"More actions","aria-expanded":l,onClick:a=>{a.stopPropagation(),m(a=>!a)},children:"⋯"}),l&&(0,h.jsx)("div",{className:"absolute right-0 top-full z-50 mt-1 w-56 overflow-hidden rounded-lg border border-gray-700 bg-gray-900 py-1 shadow-xl",children:(0,h.jsx)("button",{className:"block w-full px-4 py-3 text-left text-sm text-gray-200 hover:bg-gray-800",onClick:()=>{m(!1),e()},children:"Re-check the system"})})]})]}),(0,h.jsxs)("div",{className:"relative flex min-h-0 flex-1",children:[(0,h.jsxs)("div",{ref:x,className:"relative min-w-0 flex-1 overflow-hidden bg-[#030712]",children:[d&&U&&(0,h.jsx)(dI,{what:"system map",resetKey:d,children:(0,h.jsxs)("svg",{className:"h-full w-full",viewBox:`0 0 ${N} ${O}`,preserveAspectRatio:"xMidYMid meet",role:"img","aria-label":`System map of ${U.settings?.name}`,children:[[...H.entries()].map(([a,b])=>{let c=S.get(b.a),d=S.get(b.b);if(!c||!d)return null;let e=(c.x+d.x)/2,f=(c.y+d.y)/2,i=`${b.links.length} link${1===b.links.length?"":"s"}`,j=6.4*i.length+16,l=p===a;return(0,h.jsxs)("g",{className:"cursor-pointer",onClick:()=>{q(l?null:a),g("members"),k(!0)},children:[(0,h.jsx)("line",{x1:c.x,y1:c.y,x2:d.x,y2:d.y,stroke:"transparent",strokeWidth:18}),(0,h.jsx)("line",{x1:c.x,y1:c.y,x2:d.x,y2:d.y,stroke:l?"#3b82f6":"#475569",strokeWidth:l?2.5:1.6}),(0,h.jsx)("rect",{x:e-j/2,y:f-11,width:j,height:22,rx:11,fill:"#0f172a",stroke:l?"#3b82f6":"#334155"}),(0,h.jsx)("text",{x:e,y:f+4,textAnchor:"middle",fontSize:11.5,fill:l?"#93c5fd":"#cbd5e1",children:i})]},a)}),Q.map((a,b)=>{let c=(b+1)*N/(Q.length+1),d=O-30;return(0,h.jsxs)("g",{children:[(T.get(a.name)??[]).map(a=>{let b=S.get(a);return b?(0,h.jsx)("line",{x1:c,y1:d-14,x2:b.x,y2:b.y+46,stroke:"#334155",strokeDasharray:"3 4"},a):null}),(0,h.jsx)("title",{children:[`${a.kind}`,a.description??"",a.wheelNode??""].filter(Boolean).join(" — ")}),(0,h.jsx)("rect",{x:c-62,y:d-14,width:124,height:28,rx:14,fill:"#0c1020",stroke:"#6366f1"}),(0,h.jsx)("g",{transform:`translate(${c-54} ${d-8})`,color:"#a5b4fc",children:(0,h.jsx)(d7,{kind:"actor",size:16})}),(0,h.jsx)("text",{x:c-34,y:d-1,fontSize:11.5,fontWeight:600,fill:"#e2e8f0",children:a.name.length>12?`${a.name.slice(0,11)}…`:a.name}),(0,h.jsx)("text",{x:c-34,y:d+9,fontSize:8.5,fill:"#94a3b8",children:a.kind})]},a.name)}),P.map(a=>{let b=S.get(a),c=d.members.find(b=>b.path===a);if(!b||!c)return null;let e=c.kind,f=(D?.issues??[]).filter(b=>b.member===a),g=f.filter(a=>"error"===a.severity).length,i=f.filter(a=>"warning"===a.severity).length,j=b.x-98,k=b.y-46,l=er(d,a),m=X&&(X.a===a||X.b===a);return(0,h.jsxs)("g",{className:"cursor-pointer",onClick:()=>K(a),children:[(0,h.jsx)("title",{children:`${a}${c.error?` — cannot be read: ${c.error}`:""}
12
+ Tap to open it inside the system.`}),(0,h.jsx)("rect",{x:j,y:k,width:196,height:92,rx:10,fill:"#0f172a",stroke:c.error?"#ef4444":m?"#3b82f6":g?"#b91c1c":"#475569",strokeWidth:m?2.2:1.5,strokeDasharray:c.error?"5 4":void 0}),(0,h.jsx)("g",{transform:`translate(${j+10} ${k+9})`,color:"#93c5fd",children:(0,h.jsx)(d7,{kind:e,size:16})}),(0,h.jsx)("text",{x:j+32,y:k+21,fontSize:9,fontWeight:700,letterSpacing:"0.06em",fill:"#64748b",children:ev[e]}),(0,h.jsx)("text",{x:j+10,y:k+43,fontSize:14,fontWeight:600,fill:"#e2e8f0",children:l.length>22?`${l.slice(0,21)}…`:l}),(0,h.jsx)("text",{x:j+10,y:k+60,fontSize:10.5,fill:"#94a3b8",children:c.error?"cannot be read":ew(e,c.def,!0)}),(0,h.jsx)("text",{x:j+10,y:k+79,fontSize:10.5,fill:g?"#fca5a5":i?"#fcd34d":"#4ade80",children:c.error?c.error.length>30?`${c.error.slice(0,29)}…`:c.error:g||i?[g?`${g} error${g>1?"s":""}`:"",i?`${i} warning${i>1?"s":""}`:""].filter(Boolean).join(" · "):"checks pass"}),(0,h.jsx)("text",{x:j+196-10,y:k+79,fontSize:10.5,textAnchor:"end",fill:"#64748b",children:"open ›"})]},a)})]})}),d&&!U&&(0,h.jsx)("div",{className:"absolute inset-0 flex items-center justify-center p-6 text-center text-sm text-amber-300",children:d.error}),(0,h.jsxs)("div",{className:`pointer-events-none absolute left-2 top-2 flex max-w-[75%] items-center gap-1.5 rounded bg-gray-950/70 px-1.5 py-0.5 text-[11px] ${"warn"===r.tone?"text-amber-300":"text-gray-500"}`,role:"status",children:[(0,h.jsx)("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${"warn"===r.tone?"bg-amber-400":"bg-emerald-500"}`}),(0,h.jsx)("span",{className:`truncate transition-opacity duration-500 ${B&&"ok"===r.tone?"opacity-0":"opacity-100"}`,children:r.text})]})]}),j&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:w.close,"aria-hidden":"true"}),d&&U&&(0,h.jsxs)("aside",{style:w.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 flex h-[var(--sheet-h)] flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${j?"translate-y-0":"pointer-events-none translate-y-full"} md:pointer-events-auto md:static md:z-auto md:h-auto md:w-96 md:translate-y-0 md:rounded-none md:border-l md:border-t-0 md:shadow-none md:transition-none ${n?"md:hidden":""}`,children:[(0,h.jsxs)("div",{className:"md:hidden",...w.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pb-1 pt-2",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:W.find(a=>a.id===f)?.label}),(0,h.jsx)("button",{onClick:w.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:W.map(a=>(0,h.jsxs)("button",{onClick:()=>g(a.id),className:`relative flex-1 px-1 py-2 text-center text-xs transition-colors ${f===a.id?"border-b-2 border-blue-400 bg-gray-800/50 text-blue-400":"text-gray-500 hover:text-gray-300"}`,children:[a.label,void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1 top-1 min-w-[14px] rounded-full bg-red-900 px-1 text-[9px] text-red-100",children:a.badge})]},a.id))}),(0,h.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain p-3",children:[(0,h.jsxs)("section",{className:"members"===f?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Members"}),P.map(a=>{let b=d.members.find(b=>b.path===a),c=U.members.find(b=>b.path===a)?.notes;return(0,h.jsxs)("div",{className:"mb-1 rounded border border-gray-800",children:[(0,h.jsxs)("button",{onClick:()=>K(a),className:"flex w-full items-start gap-2 p-2 text-left hover:bg-gray-800",children:[(0,h.jsx)("span",{className:"mt-0.5 text-blue-300",children:(0,h.jsx)(d7,{kind:b?.kind??"machine"})}),(0,h.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,h.jsx)("span",{className:"block truncate text-[12px] font-semibold text-gray-200",children:er(d,a)}),(0,h.jsx)("span",{className:"block truncate text-[10.5px] text-gray-500",children:a}),(0,h.jsx)("span",{className:`block text-[11px] ${b?.error?"text-red-300":"text-gray-400"}`,children:b?.error?`cannot be read: ${b.error}`:ew(b?.kind??"machine",b?.def)})]}),(0,h.jsx)("span",{className:"shrink-0 text-[11px] text-gray-500",children:"open ›"})]}),(0,h.jsx)("div",{className:"px-2 pb-2 [&_label]:mt-0",children:(0,h.jsx)(d1,{label:"Note on this member, in the system",value:c??"",placeholder:`Why ${er(d,a)} is part of this system, what is open…`,onSave:b=>void L(function(a,b,c){let d=aW(a),e=d.members.findIndex(a=>a.path===b);if(e<0)throw Error(`'${b}' is not a member. Members: ${a.members.map(a=>a.path).join(", ")||"none"}.`);return d.members[e]=aX({...d.members[e],...c}),d}(U,a,{notes:b}),"saved")},`member:${a}`)})]},a)}),(0,h.jsx)("div",{className:d5,children:"Links between members"}),0===H.size&&(0,h.jsx)("div",{className:"py-0.5 text-[11px] text-gray-600",children:"No name crosses between the members yet."}),[...H.entries()].map(([a,b])=>(0,h.jsxs)("div",{className:"mb-1",children:[(0,h.jsxs)("button",{className:`flex w-full items-center justify-between rounded px-1.5 py-1 text-left text-[11px] ${p===a?"bg-blue-950/60 text-blue-200":"text-gray-300 hover:bg-gray-800"}`,onClick:()=>q(p===a?null:a),children:[(0,h.jsxs)("span",{className:"truncate",children:[er(d,b.a)," ↔ ",er(d,b.b)]}),(0,h.jsx)("span",{className:"shrink-0 text-gray-500",children:b.links.length})]}),p===a&&(0,h.jsx)("div",{className:"ml-2 border-l border-gray-800 pl-2",children:b.links.map((a,b)=>(0,h.jsxs)("button",{className:"block w-full truncate py-0.5 text-left text-[11px] text-gray-400 hover:text-gray-200",title:`${ey(a)} — ${a.rule}`,onClick:()=>{let b;return K((b=a.from).member,a6(b))},children:[(0,h.jsx)("span",{className:"text-gray-600",children:a.rule})," ",ey(a)]},b))})]},a)),Q.length>0&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:d5,children:"Actors"}),Q.map(a=>(0,h.jsxs)("div",{className:"py-0.5 text-[11px] text-gray-300",children:[a.name," ",(0,h.jsxs)("span",{className:"text-gray-500",children:["· ",a.kind]}),a.description?(0,h.jsxs)("span",{className:"text-gray-500",children:[" — ",a.description]}):null]},a.name))]})]}),(0,h.jsxs)("section",{className:"checks"===f?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Checks"}),(0,h.jsxs)("div",{className:`text-[11px] ${I.length?"text-red-300":J.length?"text-amber-300":"text-green-400"}`,children:[I.length," error",1===I.length?"":"s"," · ",J.length," warning",1===J.length?"":"s"]}),Y.map(a=>(0,h.jsxs)("div",{className:"mt-2",children:[(0,h.jsxs)("div",{className:`text-[11px] font-semibold ${"error"===a.severity?"text-red-300":"text-amber-300"}`,children:[a.ruleId," · ",a.issues.length," ",a.severity,1===a.issues.length?"":"s"]}),a.issues.map((a,b)=>(0,h.jsxs)("button",{className:"block w-full py-0.5 pl-2 text-left text-[11px] text-gray-300 hover:text-white",onClick:()=>{a.member&&K(a.member,a.element&&/^[a-z]+:/.test(a.element)?a.element:null)},title:a.member?`Open ${a.member}${a.element?` at ${a.element}`:""}`:void 0,children:[a.message,a.member&&(0,h.jsxs)("span",{className:"text-gray-500",children:[" — ",er(d,a.member)]})]},b))]},a.key)),(0,h.jsx)("div",{className:d5,children:"Reconcile"}),(0,h.jsxs)("p",{className:"mb-1 text-[11px] text-gray-500",children:["What the scenarios imply for the machines and the data. ",(0,h.jsx)("b",{className:"text-gray-400",children:"propose"})," lists it here to apply by hand; ",(0,h.jsx)("b",{className:"text-gray-400",children:"auto"})," writes it each time a scenario is saved."]}),(0,h.jsx)("span",{className:"inline-flex overflow-hidden rounded border border-gray-700",role:"group","aria-label":"Reconcile mode",children:aM.map(a=>(0,h.jsx)("button",{"aria-pressed":G===a,onClick:()=>{d?.def&&a!==G&&L(function(a,b){if(!aM.includes(b))throw Error(`The reconcile mode is ${aM.join(" or ")}; got '${b}'.`);return aY(a,{reconcile:b})}(d.def,a),`reconcile mode: ${a}`)},className:`px-3 py-1 text-xs ${G===a?"bg-blue-900/60 text-blue-200":"bg-gray-800 text-gray-400 hover:bg-gray-700"}`,children:a},a))}),(0,h.jsx)("div",{className:"mt-2 text-[11px] font-semibold text-gray-400",children:"Scenario changes"}),F&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:"text-[11px] text-gray-500",children:bd(F,"propose")}),F.machines.map(a=>(0,h.jsxs)("div",{className:"mt-1",children:[(0,h.jsxs)("div",{className:"text-[11px] text-gray-300",children:[a.machine," ",(0,h.jsxs)("span",{className:"text-gray-500",children:["· ",a.member]})]}),a.reasons.map((a,b)=>(0,h.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",a]},b))]},a.member)),F.erds.map(a=>(0,h.jsxs)("div",{className:"mt-1",children:[(0,h.jsxs)("div",{className:"text-[11px] text-gray-300",children:[a.def.settings?.name??a.member," ",(0,h.jsxs)("span",{className:"text-gray-500",children:["· ",a.member]})]}),a.reasons.map((a,b)=>(0,h.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",a]},b))]},a.member)),F.system&&(0,h.jsxs)("div",{className:"mt-1",children:[(0,h.jsx)("div",{className:"text-[11px] text-gray-300",children:"the system"}),F.system.reasons.map((a,b)=>(0,h.jsxs)("div",{className:"pl-2 text-[11px] text-gray-400",children:["+ ",a]},b))]}),F.unresolved.map((a,b)=>(0,h.jsxs)("div",{className:"mt-1 text-[11px] text-amber-300",children:["left open: ",a]},b)),(0,h.jsx)("button",{className:`${d4} mt-2 disabled:opacity-40`,disabled:!F.count||u,onClick:M,children:u?"Applying…":`Apply${F.count?` ${F.count} change${1===F.count?"":"s"}`:""}`})]}),(D?.replays??[]).map(({member:a,report:b})=>(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:d5,children:["Replay · ",er(d,a)]}),(0,h.jsxs)("div",{className:"mb-1 text-[11px] text-gray-500",children:["against ",b.machines.join(", ")||"no machine"]}),b.paths.map(b=>(0,h.jsxs)("div",{className:"mb-2",children:[(0,h.jsxs)("div",{className:`text-[11px] font-semibold ${b.accepted?"text-green-400":"text-amber-300"}`,children:[b.name," — ",b.accepted?"accepted":"stops"]}),b.steps.filter(a=>"data"!==a.result).map(c=>(0,h.jsxs)("button",{className:`block w-full truncate py-0.5 pl-2 text-left font-mono text-[10.5px] ${"moved"===c.result||"stayed"===c.result?"text-gray-400":"text-amber-300"}`,title:c.note??c.result,onClick:()=>K(a,`message:${c.ref}`),children:[c.ref,". ",c.event??""," ",c.from.join("|")||"·"," → ",c.to.join("|")||"·"," ",c.result]},`${b.name}:${c.ref}`))]},b.name))]},a))]}),(0,h.jsxs)("section",{className:"notes"===f?"":"hidden",children:[(0,h.jsx)("div",{className:d5,style:{marginTop:0},children:"Notes"}),(0,h.jsx)("p",{className:"mb-1 text-[11px] text-gray-600",children:"Saved in the system file, for whoever opens it next."}),(0,h.jsx)(d1,{label:"On this system",value:U.settings?.notes??"",placeholder:"What the system is for, what is still open…",onSave:a=>void L(aY(U,{notes:a}),"saved")},"system"),U.settings?.description&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("div",{className:d5,children:"Description"}),(0,h.jsx)("p",{className:"text-[11px] text-gray-400",children:U.settings.description})]})]})]})]})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:W.map(a=>{let b=j&&f===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(j&&f===b?w.close():k(!0),g(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&(0,h.jsx)("span",{className:"absolute right-1/2 top-1 min-w-[16px] translate-x-5 rounded-full border border-red-900/80 bg-red-950/80 px-1 text-[10px] leading-4 text-red-200",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})})]})}let eA=a=>a.parallel?a.parallel.states:a.states??[];function eB(a,b){if(!a)return null;if(a.name===b)return[a.name];for(let c of eA(a)){let d=eB(c,b);if(d)return[a.name,...d]}return null}function eC(){let a=(0,dj.useRequestedDoc)(),b=dP("system"),[c,d]=(0,i.useState)(null);(0,i.useEffect)(()=>{let a=!0;return dt().then(b=>{a&&d(b.projectFile?aR(b.projectFile):"machine")}),()=>{a=!1}},[]);let e=a?aR(a):c;if(null===e)return(0,h.jsx)("div",{className:"app-shell bg-gray-950"});let f=a??"default",g="erd"===e?(0,h.jsx)(d0,{},f):"sequence"===e?(0,h.jsx)(eq,{},f):"system"===e?(0,h.jsx)(ez,{},f):(0,h.jsx)(eD,{}),j=(0,h.jsx)(dI,{what:"document",resetKey:a,children:g});return b&&aP(b)?(0,h.jsxs)("div",{className:"system-frame",children:[(0,h.jsx)(eu,{systemPath:b}),j]}):j}function eD(){let a,b;a=dS(),b=(0,i.useRef)(null),(0,i.useEffect)(()=>{let c=()=>{let a=b.current;if(!a)return;let c=c_.getState(),d=null;if(d&&c.docPath!==d||a.docAt!==c.docPath&&c.definition===a.defAt)return;b.current=null;let e=a7(a.focus);if(!e)return;let f=null,g=null;if("state"===e.kind)(f=eB(c.definition.state,e.name))&&(g={kind:"state",id:e.name});else if("event"===e.kind){let a=function a(b,c){if(!b)return null;let d=(b.transitions??[]).findIndex(a=>a?.event===c);if(d>=0)return{state:b.name,index:d};for(let d of eA(b)){let b=a(d,c);if(b)return b}return null}(c.definition.state,e.name);a&&(f=eB(c.definition.state,a.state),g={kind:"transition",id:`${a.state}:${a.index}`})}if(!f||!g)return;let h=f.length>1?f.slice(0,-1):f;c_.setState({navigationPath:h,currentParent:h[h.length-1]}),c.select(g.kind,g.id);let i=()=>{let a=c_.getState().layout.positions[f[f.length-1]],b=document.getElementById(c3)?.getBoundingClientRect();if(!a||!b?.width)return;let c=R([a],b.width,b.height,{padding:60,maxScale:1});c_.getState().setViewport(c)};requestAnimationFrame(i),setTimeout(i,450)};if(a.nonce>0){let d=c_.getState();b.current=a.focus?{focus:a.focus,docAt:d.docPath,defAt:d.definition}:null,c()}return c_.subscribe(c)},[a]),(0,i.useEffect)(()=>c_.subscribe((a,b)=>{if(a.selection===b.selection||!a.selection.id)return;let{kind:c,id:d}=a.selection;if("state"===c)dR(`state:${d}`);else if("event"===c)dR(`event:${d}`);else if("transition"===c){let b=function(a,b){let c=b.lastIndexOf(":"),d=eB(a.state,b.slice(0,c));if(!d)return null;let e=a.state;for(let a of d.slice(1))e=eA(e).find(b=>b.name===a);return e?.transitions?.[Number(b.slice(c+1))]?.event??null}(a.definition,d);b&&dR(`event:${b}`)}}),[]);let[c,d]=(0,i.useState)("properties"),[e,f]=(0,i.useState)(!1),g=dL({onClose:()=>f(!1),restVh:70,tallVh:92}),j=c_(a=>a.errors),k=c_(a=>a.contextMenu),l=c_(a=>a.hideContextMenu),m=c_(a=>a.addState),n=c_(a=>a.removeState),o=c_(a=>a.setDrawMode),p=c_(a=>a.setDrawSource),q=[{id:"properties",label:"Properties",icon:"🎛"},{id:"events",label:"Events",icon:"⚡"},{id:"settings",label:"Settings",icon:"⚙"},{id:"validation",label:"Errors",icon:(0,h.jsx)(dJ,{}),badge:j.length||void 0}],r=q.find(a=>a.id===c)?.label??"";return(0,h.jsxs)("div",{className:"app-shell dock-offset flex flex-col overflow-hidden",onClick:()=>k.visible&&l(),children:[(0,h.jsx)(du,{}),(0,h.jsx)(dG,{}),(0,h.jsx)(dm,{}),(0,h.jsxs)("div",{className:"flex flex-1 min-h-0 overflow-hidden relative",children:[(0,h.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,h.jsx)(dI,{what:"state machine",children:(0,h.jsx)(dc,{})})}),e&&(0,h.jsx)("div",{className:"fixed inset-0 z-20 bg-black/50 md:hidden",onClick:g.close,"aria-hidden":"true"}),(0,h.jsxs)("aside",{style:g.sheetStyle,className:`safe-x fixed inset-x-0 bottom-0 z-30 h-[var(--sheet-h)] flex flex-col overflow-hidden rounded-t-2xl border-t border-gray-800 bg-gray-900 shadow-2xl transition-[transform,height] duration-200 ease-out ${e?"translate-y-0":"translate-y-full pointer-events-none"} md:static md:z-auto md:h-auto md:w-80 md:translate-y-0 md:pointer-events-auto md:rounded-none md:border-t-0 md:border-l md:shadow-none md:transition-none`,children:[(0,h.jsxs)("div",{className:"md:hidden",...g.zoneProps,children:[(0,h.jsx)("div",{className:"flex justify-center pt-2 pb-1",children:(0,h.jsx)("span",{className:"h-1.5 w-12 rounded-full bg-gray-600"})}),(0,h.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-800 px-4 pb-2",children:[(0,h.jsx)("h2",{className:"text-sm font-semibold text-gray-300",children:r}),(0,h.jsx)("button",{onClick:g.close,className:"-mr-2 px-3 py-2 text-lg text-gray-400","aria-label":"Close panel",children:"✕"})]})]}),(0,h.jsx)("div",{className:"hidden border-b border-gray-800 md:flex",children:q.map(a=>(0,h.jsxs)("button",{onClick:()=>d(a.id),className:`flex-1 text-xs py-2 px-1 text-center transition-colors relative ${c===a.id?"text-blue-400 border-b-2 border-blue-400 bg-gray-800/50":"text-gray-500 hover:text-gray-300"}`,children:[a.label,void 0!==a.badge&&a.badge>0&&(0,h.jsx)("span",{className:"absolute top-1 right-1 bg-red-600 text-white text-[9px] rounded-full px-1 min-w-[14px]",children:a.badge})]},a.id))}),(0,h.jsxs)("div",{className:"touch-targets dock-offset flex-1 overflow-y-auto overscroll-contain",children:["properties"===c&&(0,h.jsx)(de,{}),"events"===c&&(0,h.jsx)(dg,{}),"settings"===c&&(0,h.jsx)(dh,{}),"validation"===c&&(0,h.jsx)(di,{})]})]}),(0,h.jsx)(dn,{})]}),(0,h.jsx)("nav",{className:"dock-safe safe-x fixed inset-x-0 bottom-0 z-40 flex border-t border-gray-800 bg-gray-900/95 backdrop-blur-md md:hidden",children:q.map(a=>{let b=e&&c===a.id;return(0,h.jsxs)("button",{onClick:()=>{var b;return b=a.id,void(e&&c===b?g.close():f(!0),d(b))},"aria-pressed":b,className:`relative flex h-14 flex-1 flex-col items-center justify-center gap-0.5 text-[11px] transition-colors ${b?"text-blue-400":"text-gray-500"}`,children:[(0,h.jsx)("span",{className:"flex h-4 items-center text-base leading-none",children:a.icon}),(0,h.jsx)("span",{children:a.label}),void 0!==a.badge&&a.badge>0&&(0,h.jsx)("span",{className:"absolute top-1 right-1/2 translate-x-4 rounded-full bg-red-600 px-1 text-[10px] leading-4 text-white min-w-[16px]",children:a.badge}),b&&(0,h.jsx)("span",{className:"absolute inset-x-4 top-0 h-0.5 rounded-full bg-blue-400"})]},a.id)})}),k.visible&&(0,h.jsx)("div",{className:"fixed z-50 bg-gray-900 border border-gray-700 rounded-lg shadow-xl py-1 min-w-[180px] md:min-w-[140px]",style:{left:k.x,top:k.y,maxWidth:"calc(100vw - 1rem)",maxHeight:"calc(100dvh - 1rem)",overflowY:"auto",transform:"translate(0, 0)"},onClick:a=>a.stopPropagation(),children:k.target?.kind==="state"?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("button",{className:"block w-full text-left text-sm text-gray-300 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{o("transition"),p(k.target.id),l()},children:"↗ Draw transition from here"}),(0,h.jsx)("button",{className:"block w-full text-left text-sm text-red-400 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{k.target?.id&&n(k.target.id),l()},children:"🗑 Delete state"})]}):(0,h.jsx)(h.Fragment,{children:(0,h.jsx)("button",{className:"block w-full text-left text-sm text-gray-300 hover:bg-gray-800 px-4 py-3 md:text-xs md:px-3 md:py-1.5",onClick:()=>{let a=prompt("State name:");a&&m(null,{name:a,kind:"normal"}),l()},children:"+ Add state here"})})})]})}a.s(["default",()=>eC],95421)}];
13
13
 
14
14
  //# sourceMappingURL=%5Broot-of-the-server%5D__edbb995c._.js.map