@codeyam/codeyam-cli 0.1.29 → 0.1.31

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 (66) hide show
  1. package/analyzer-template/.build-info.json +7 -7
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +1 -1
  4. package/analyzer-template/packages/aws/package.json +1 -1
  5. package/analyzer-template/packages/database/package.json +1 -1
  6. package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js +39 -3
  7. package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js.map +1 -1
  8. package/codeyam-cli/src/commands/editor.js +133 -0
  9. package/codeyam-cli/src/commands/editor.js.map +1 -1
  10. package/codeyam-cli/src/commands/init.js +20 -0
  11. package/codeyam-cli/src/commands/init.js.map +1 -1
  12. package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js +98 -1
  13. package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js.map +1 -1
  14. package/codeyam-cli/src/utils/__tests__/editorRoadmap.test.js +712 -2
  15. package/codeyam-cli/src/utils/__tests__/editorRoadmap.test.js.map +1 -1
  16. package/codeyam-cli/src/utils/__tests__/envFile.test.js +125 -0
  17. package/codeyam-cli/src/utils/__tests__/envFile.test.js.map +1 -0
  18. package/codeyam-cli/src/utils/__tests__/handoffContext.test.js +500 -0
  19. package/codeyam-cli/src/utils/__tests__/handoffContext.test.js.map +1 -0
  20. package/codeyam-cli/src/utils/editorRoadmap.js +290 -17
  21. package/codeyam-cli/src/utils/editorRoadmap.js.map +1 -1
  22. package/codeyam-cli/src/utils/envFile.js +90 -0
  23. package/codeyam-cli/src/utils/envFile.js.map +1 -0
  24. package/codeyam-cli/src/utils/handoffContext.js +257 -0
  25. package/codeyam-cli/src/utils/handoffContext.js.map +1 -0
  26. package/codeyam-cli/src/utils/install-skills.js +36 -6
  27. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  28. package/codeyam-cli/src/utils/techStackConfig.js +38 -0
  29. package/codeyam-cli/src/utils/techStackConfig.js.map +1 -0
  30. package/codeyam-cli/src/utils/techStackConfig.test.js +85 -0
  31. package/codeyam-cli/src/utils/techStackConfig.test.js.map +1 -0
  32. package/codeyam-cli/src/webserver/__tests__/buildPtyEnv.test.js +119 -1
  33. package/codeyam-cli/src/webserver/__tests__/buildPtyEnv.test.js.map +1 -1
  34. package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js +115 -0
  35. package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js.map +1 -1
  36. package/codeyam-cli/src/webserver/app/lib/database.js.map +1 -1
  37. package/codeyam-cli/src/webserver/build/client/assets/{MiniClaudeChat-BusrvT2F.js → MiniClaudeChat-Bs2_Oua4.js} +1 -1
  38. package/codeyam-cli/src/webserver/build/client/assets/api.editor-database-verify-l0sNRNKZ.js +1 -0
  39. package/codeyam-cli/src/webserver/build/client/assets/api.editor-github-verify-l0sNRNKZ.js +1 -0
  40. package/codeyam-cli/src/webserver/build/client/assets/api.editor-handoff-l0sNRNKZ.js +1 -0
  41. package/codeyam-cli/src/webserver/build/client/assets/api.editor-hosting-verify-l0sNRNKZ.js +1 -0
  42. package/codeyam-cli/src/webserver/build/client/assets/editor.entity.(_sha)-DOXe0Qx7.js +161 -0
  43. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-Ce1s4OQ1.js → entity._sha._-pc-vc6wO.js} +1 -1
  44. package/codeyam-cli/src/webserver/build/client/assets/globals-L-aUIeux.css +1 -0
  45. package/codeyam-cli/src/webserver/build/client/assets/manifest-30c44d84.js +1 -0
  46. package/codeyam-cli/src/webserver/build/client/assets/{root-CVjDQwjJ.js → root-CLedrjXQ.js} +7 -7
  47. package/codeyam-cli/src/webserver/build/server/assets/{analysisRunner-CTJYMVFP.js → analysisRunner-CuR5TvUx.js} +1 -1
  48. package/codeyam-cli/src/webserver/build/server/assets/{index-CCth4Hgw.js → index-D4MWAsqb.js} +1 -1
  49. package/codeyam-cli/src/webserver/build/server/assets/init-JObA4lXD.js +14 -0
  50. package/codeyam-cli/src/webserver/build/server/assets/server-build-i8OXK4oL.js +765 -0
  51. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  52. package/codeyam-cli/src/webserver/build-info.json +5 -5
  53. package/codeyam-cli/src/webserver/editorProxy.js +77 -4
  54. package/codeyam-cli/src/webserver/editorProxy.js.map +1 -1
  55. package/codeyam-cli/src/webserver/terminalServer.js +81 -11
  56. package/codeyam-cli/src/webserver/terminalServer.js.map +1 -1
  57. package/codeyam-cli/templates/codeyam-editor-codex.md +61 -0
  58. package/codeyam-cli/templates/codeyam-editor-gemini.md +59 -0
  59. package/codeyam-cli/templates/nextjs-prisma-sqlite/gitignore +1 -0
  60. package/codeyam-cli/templates/seed-adapters/supabase.ts +185 -84
  61. package/package.json +1 -1
  62. package/codeyam-cli/src/webserver/build/client/assets/editor.entity.(_sha)-785deXbZ.js +0 -147
  63. package/codeyam-cli/src/webserver/build/client/assets/globals-Bt7TsgQz.css +0 -1
  64. package/codeyam-cli/src/webserver/build/client/assets/manifest-3d8cde80.js +0 -1
  65. package/codeyam-cli/src/webserver/build/server/assets/init-UXl-3vVp.js +0 -10
  66. package/codeyam-cli/src/webserver/build/server/assets/server-build-DSW2mE30.js +0 -741
@@ -0,0 +1,765 @@
1
+ var Th=Object.defineProperty;var Dl=e=>{throw TypeError(e)};var Mh=(e,t,r)=>t in e?Th(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var vt=(e,t,r)=>Mh(e,typeof t!="symbol"?t+"":t,r),$h=(e,t,r)=>t.has(e)||Dl("Cannot "+r);var Rl=(e,t,r)=>($h(e,t,"read from private field"),r?r.call(e):t.get(e)),Il=(e,t,r)=>t.has(e)?Dl("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r);import{jsx as n,jsxs as c,Fragment as we}from"react/jsx-runtime";import{PassThrough as Fh}from"node:stream";import{createReadableStreamFromReadable as Dh}from"@react-router/node";import{ServerRouter as Rh,useFetcher as Ke,useLocation as Qr,useNavigate as Yt,Link as Ee,UNSAFE_withComponentProps as tt,Meta as Ih,Links as Oh,ScrollRestoration as Lh,Scripts as Bh,UNSAFE_withErrorBoundaryProps as zh,useRouteError as Yh,isRouteErrorResponse as eo,useLoaderData as lt,useRevalidator as Ut,Outlet as $d,data as ue,useSearchParams as dr,useRouteLoaderData as Fd,useParams as Dd,useActionData as Uh,redirect as Wh}from"react-router";import{isbot as Jh}from"isbot";import{renderToPipeableStream as Hh}from"react-dom/server";import{useState as E,useEffect as se,useCallback as le,createContext as ti,useContext as ua,useRef as be,useMemo as fe,forwardRef as Vh,useImperativeHandle as Kh,Component as Gh}from"react";import{Settings as Ol,CheckCircle2 as ni,Bug as Rd,AlertTriangle as Ks,Check as $t,Copy as Bt,Loader2 as Ot,PencilRuler as qh,HomeIcon as Qh,GitCommitIcon as Ll,File as Zh,RefreshCw as Xh,BookOpen as Gs,FlaskConical as em,SettingsIcon as tm,PanelsTopLeftIcon as nm,ComponentIcon as rm,FileText as Bl,Code as zl,Box as sm,List as am,BarChart3 as om,Tag as im,Image as Wr,Code2 as Id,Activity as to,ChevronDown as Tt,CircleEqual as lm,ArrowLeft as cm,Terminal as qs,Search as Zr,ChevronLeft as dm,ChevronRight as xn,Save as um,MessageSquare as pm,Pause as Od,ListTodo as hm,PauseCircle as mm,FileCode as Qs,GripVertical as fm,Ban as gm,CheckCircle as ym,FolderOpen as xm,CodeXml as bm,Zap as vm,Pencil as wm,Trash2 as Nm,X as ur,Folder as Ld,Info as Mo,Plus as ri,Eye as Sm,FolderTree as Cm,ChevronsUpDown as Bd,ChevronsDownUp as zd}from"lucide-react";import"fetch-retry";import km from"better-sqlite3";import{Pool as jm}from"pg";import*as Q from"fs";import ce,{existsSync as At,readdirSync as _m,rmSync as no,readFileSync as Yl}from"fs";import*as G from"path";import ee,{join as Jr}from"path";import{OperationNodeTransformer as Em,sql as wt,Kysely as Yd,ParseJSONResultsPlugin as Pm,SqliteDialect as Am,PostgresDialect as Tm}from"kysely";import*as Mm from"kysely/helpers/sqlite";import*as $m from"kysely/helpers/postgres";import Xe from"typescript";import*as Ae from"fs/promises";import Te,{writeFile as Or,readFile as $o,mkdir as Fm}from"fs/promises";import*as pa from"os";import Fo,{homedir as Dm}from"os";import Rm from"prompts";import Zs from"chalk";import*as si from"crypto";import pr,{randomUUID as ai,createHmac as Im}from"crypto";import{execSync as Me,spawn as kt,exec as oi}from"child_process";import{fileURLToPath as ha}from"url";import{promisify as ii}from"util";import Om from"dotenv";import Lm,{EventEmitter as Xr}from"events";import{v4 as Bm}from"uuid";import li from"http";import Ud from"net";import{WebSocket as ci}from"ws";import"node-pty";import zm from"openai";import Ym from"p-queue";import Ul from"p-retry";import{DynamoDBClient as ma,PutItemCommand as Um}from"@aws-sdk/client-dynamodb";import{LRUCache as di}from"lru-cache";import"pluralize";import"piscina";import Wm from"json5";import{marshall as Jm}from"@aws-sdk/util-dynamodb";import Hm from"v8";import{Prism as Vm}from"react-syntax-highlighter";import{vscDarkPlus as Km}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as Gm}from"node:crypto";import{minimatch as Do}from"minimatch";import qm from"react-markdown";import Qm from"remark-gfm";import Zm from"react-diff-viewer-continued";const Wd=5e3;function Xm(e,t,r,s,a){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let l=!1,d=e.headers.get("user-agent"),u=d&&Jh(d)||s.isSpaMode?"onAllReady":"onShellReady",p=setTimeout(()=>m(),Wd+1e3);const{pipe:h,abort:m}=Hh(n(Rh,{context:s,url:e.url}),{[u](){l=!0;const f=new Fh({final(g){clearTimeout(p),p=void 0,g()}}),y=Dh(f);r.set("Content-Type","text/html"),h(f),o(new Response(y,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const ef=Object.freeze(Object.defineProperty({__proto__:null,default:Xm,streamTimeout:Wd},Symbol.toStringTag,{value:"Module"})),tf=2e3,nf=5e3;function rf(e){return e.startsWith("/editor")?nf:tf}function sf(e){const{now:t,lastRevalidation:r,throttleMs:s}=e;if(r===0)return"immediate";const a=t-r;return a>=s?"immediate":{action:"deferred",delayMs:s-a}}function af({id:e,selected:t,onClick:r,icon:s,name:a}){const[o,i]=E(!1);se(()=>{i(!0)},[]);const l=le(()=>{r==null||r(e)},[r,e]);return c("button",{className:`
2
+ w-full px-1.5 py-2 cursor-pointer focus:outline-none
3
+ flex flex-col items-center justify-center gap-1 transition-colors
4
+ ${t?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
5
+ `,onClick:l,children:[n("div",{className:`${t?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:o&&s}),n("span",{className:`text-[10px] font-normal text-center leading-tight ${t?"text-[#CBF3FA]":""}`,style:t?{color:"#CBF3FA !important"}:void 0,children:a})]})}const fa="/assets/cy-logo-cli-DoA97ML3.svg";function of(e){return e.scenarioName&&e.entityName?`${e.entityName} → "${e.scenarioName}"`:e.entityName?e.entityName:e.scenarioId?`Scenario: ${e.scenarioId.slice(0,8)}...`:e.entitySha?`Entity: ${e.entitySha.slice(0,8)}...`:"General feedback"}function lf({content:e,className:t=""}){const[r,s]=E(!1),a=le(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)}).catch(o=>{console.error("Failed to copy:",o)})},[e]);return n("button",{onClick:a,className:`cursor-pointer flex items-center gap-1 ${t}`,disabled:r,"aria-label":r?"Copied to clipboard":"Copy to clipboard",children:r?c(we,{children:[n($t,{size:14}),"Copied"]}):c(we,{children:[n(Bt,{size:14}),"Copy"]})})}function Jd({isOpen:e,onClose:t,context:r,defaultEmail:s="",screenshotDataUrl:a}){const[o,i]=E(""),[l,d]=E(s),[u,p]=E(!1),[h,m]=E(!1),[f,y]=E(null),[g,x]=E(null),b=Ke(),v=b.state!=="idle",N=!!(r.scenarioId||r.analysisId),w=r.analysisId||r.scenarioId||"",C=()=>{const _=`/codeyam-diagnose ${w}`;return o.trim()?`${_} ${o.trim()}`:_};if(b.data&&!h&&!g){const _=b.data;_.success&&_.reportId?(m(!0),y(_.reportId)):_.error&&x(_.error)}const k=async()=>{x(null);const _=new FormData;if(_.append("issueType","other"),_.append("description",o),_.append("email",l),_.append("source",r.source),_.append("entitySha",r.entitySha||""),_.append("scenarioId",r.scenarioId||""),_.append("analysisId",r.analysisId||""),_.append("currentUrl",r.currentUrl),_.append("entityName",r.entityName||""),_.append("entityType",r.entityType||""),_.append("scenarioName",r.scenarioName||""),_.append("errorMessage",r.errorMessage||""),a)try{const T=await(await fetch(a)).blob();_.append("screenshot",T,"screenshot.jpg")}catch(M){console.error("Failed to convert screenshot:",M)}b.submit(_,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},j=()=>{i(""),p(!1),m(!1),y(null),x(null),t()},A=_=>{_.key==="Escape"&&j()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:A,children:c("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[c("div",{className:"flex items-center justify-between mb-6",children:[c("div",{className:"flex items-center gap-3",children:[v?n("div",{className:"animate-spin",children:n(Ol,{size:24,style:{strokeWidth:1.5}})}):h?n(ni,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(Rd,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:h?"Report Submitted":"Report Issue"})]}),n("button",{onClick:j,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),h?c("div",{children:[c("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[n("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),c("p",{className:"text-xs text-green-700",children:["Report ID:"," ",n("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),n("p",{className:"text-sm text-gray-600 mb-6",children:"The CodeYam team will investigate and may reach out if you provided an email address."}),n("div",{className:"flex justify-end",children:n("button",{onClick:j,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):c("div",{children:[c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[c("div",{className:"flex items-center justify-between",children:[n("div",{className:"text-sm font-medium text-gray-900",title:`${r.source}${r.entitySha?` • Entity: ${r.entitySha}`:""}${r.scenarioId?` • Scenario: ${r.scenarioId}`:""}${r.analysisId?` • Analysis: ${r.analysisId}`:""}`,children:of(r)}),n("button",{type:"button",onClick:()=>p(!u),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:u?"Hide":"Details"})]}),u&&c("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[c("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),c("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&c("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&c("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&c("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),a&&c("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),n("img",{src:a,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),n("textarea",{id:"description",value:o,onChange:_=>i(_.target.value),placeholder:"Optional: Describe what you expected vs what happened...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] resize-none"})]}),N&&c(we,{children:[c("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[c("div",{className:"flex items-center gap-2 mb-2",children:[n("span",{className:"text-lg",children:"🔧"}),n("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),n("p",{className:"text-xs text-purple-700 mb-3",children:"Run this command in Claude Code to investigate the issue locally and potentially fix it. A detailed report will also be uploaded."}),c("div",{className:"relative",children:[n("div",{className:"bg-gray-800 text-gray-50 px-3 py-2.5 pr-20 rounded-md text-xs font-mono overflow-x-auto whitespace-nowrap",children:C()}),n(lf,{content:C(),className:"absolute top-1.5 right-2 px-2 py-1 bg-purple-600 text-white border-none rounded text-[11px] font-medium hover:bg-purple-700 transition-colors"})]})]}),c("div",{className:"relative my-5",children:[n("div",{className:"absolute inset-0 flex items-center",children:n("div",{className:"w-full border-t border-gray-300"})}),n("div",{className:"relative flex justify-center",children:n("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),c("div",{className:N?"opacity-75":"",children:[N&&c("div",{className:"flex items-center gap-2 mb-3",children:[n("span",{className:"text-lg",children:"📤"}),n("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),n("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),n("input",{id:"email",type:"email",value:l,onChange:_=>d(_.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),c("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(Ks,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),c("div",{className:"text-xs text-amber-800",children:[n("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),n("p",{children:"This report includes your project source code, git history, and CodeYam logs. Only submit if you're comfortable sharing this with the CodeYam team."})]})]}),v&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:b.formData?"Uploading report...":"Creating archive..."})}),g&&c("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(Ks,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),c("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:g})]})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:j,disabled:v,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 transition-colors disabled:opacity-50 cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>void k(),disabled:v,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer",children:v?c(we,{children:[n("div",{className:"animate-spin",children:n(Ol,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const Wl={source:"navbar"},ui=ti(void 0);function cf({children:e}){const[t,r]=E(Wl),s=le(o=>{r(o)},[]),a=le(()=>{r(Wl)},[]);return n(ui.Provider,{value:{contextData:t,setContextData:s,resetContextData:a},children:e})}function Wt(e){const t=ua(ui),r=be(t);se(()=>{if(r.current)return r.current.setContextData(e),()=>{var s;(s=r.current)==null||s.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId,e.entityName,e.entityType,e.scenarioName,e.errorMessage])}function df(){const e=ua(ui),t=Qr();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:t.pathname,entityName:e.contextData.entityName,entityType:e.contextData.entityType,scenarioName:e.contextData.scenarioName,errorMessage:e.contextData.errorMessage}:{source:"navbar",currentUrl:t.pathname}}function uf({labs:e,isAdmin:t,editorMode:r}){var k;const s=Qr(),a=Yt(),[o,i]=E(),[l,d]=E(!1),[u,p]=E(!1),[h,m]=E(null),f=Ke();se(()=>{f.state==="idle"&&!f.data&&f.load("/api/generate-report")},[f]);const y=((k=f.data)==null?void 0:k.defaultEmail)||"",g={width:"20px",height:"20px",strokeWidth:1.5},x=(e==null?void 0:e.simulations)??!1,b=[{id:"editor",icon:n(qh,{style:g}),link:"/editor",name:"Editor",hidden:!r,newTab:!0},{id:"dashboard",icon:n(Qh,{style:g}),link:"/",name:"Dashboard",hidden:!x||r},{id:"simulations",icon:c("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:g,children:[n("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6.75 12.7498L11.325 8.17483C11.6067 7.89873 11.9858 7.7447 12.3803 7.7461C12.7747 7.74751 13.1528 7.90423 13.4325 8.18233L16.5 11.2498",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M6 8.25C6.82843 8.25 7.5 7.57843 7.5 6.75C7.5 5.92157 6.82843 5.25 6 5.25C5.17157 5.25 4.5 5.92157 4.5 6.75C4.5 7.57843 5.17157 8.25 6 8.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),n("path",{d:"M15 2.25H3C2.17157 2.25 1.5 2.92157 1.5 3.75V11.25C1.5 12.0784 2.17157 12.75 3 12.75H15C15.8284 12.75 16.5 12.0784 16.5 11.25V3.75C16.5 2.92157 15.8284 2.25 15 2.25Z",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),link:"/simulations",name:"Simulations",hidden:!x||r},{id:"git",icon:n(Ll,{style:g}),link:"/git",name:"Git",hidden:!x||r},{id:"files",icon:n(Zh,{style:g}),link:"/files",name:"Files",hidden:!x||r},{id:"activity",icon:n(Xh,{style:g}),link:"/activity",name:"Activity",hidden:!x||r},{id:"memory",icon:n(Gs,{style:g}),link:"/memory",name:"Memory"},{id:"labs",icon:n(em,{style:g}),link:"/labs",name:"Labs"},{id:"settings",icon:n(tm,{style:g}),link:"/settings",name:"Settings"},{id:"commits",icon:n(Ll,{style:g}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(nm,{style:g}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(rm,{style:g}),link:"/components",name:"Components",hidden:!0}],v=le(j=>{const A=b.find(_=>_.id===j);A!=null&&A.link&&(A.newTab?window.open(A.link,"_blank"):a(A.link)),i(_=>_===j?void 0:j)},[b,a]);se(()=>{const j={editor:["editor"],dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],memory:["memory","agent-transcripts"],files:["files"],labs:["labs"],settings:["settings"],pages:["pages"],components:["components"]};for(const[A,_]of Object.entries(j))if(_.some(M=>M==="/"?s.pathname==="/":s.pathname.includes(M))){i(A);return}i(void 0)},[s]);const N=async()=>{p(!0);try{const{default:j}=await import("html2canvas-pro"),_=(await j(document.body)).toDataURL("image/jpeg",.8);m(_),d(!0)}catch(j){console.error("Screenshot capture failed:",j),d(!0)}finally{p(!1)}},w=()=>{d(!1),m(null)},C=df();return c(we,{children:[c("div",{id:"sidebar",className:"sticky top-0 w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[c("div",{className:"w-full flex flex-col items-center",children:[n("div",{className:"py-3 mt-2 mb-4",children:n(Ee,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:fa,alt:"CodeYam",className:"h-6"})})}),b.filter(j=>!j.hidden).map(j=>n(af,{id:j.id,selected:j.id===o,onClick:v,icon:j.icon,name:j.name},`sidebar-button-${j.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:c("button",{onClick:()=>void N(),disabled:u,className:"w-full px-1.5 py-2 flex flex-col items-center justify-center gap-1 text-[#568B94] hover:text-[#CBF3FA] transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-wait",children:[n("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center",children:u?n(Ot,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(Rd,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:u?"Capturing...":`Report
6
+ Bug`})]})})]}),l&&n(Jd,{isOpen:!0,onClose:w,context:C,defaultEmail:y,screenshotDataUrl:h??void 0})]})}const Hd=ti(void 0);function pf({children:e}){const[t,r]=E([]),s=le((o,i="info",l=5e3)=>{const u={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:l};r(p=>[...p,u])},[]),a=le(o=>{r(i=>i.filter(l=>l.id!==o))},[]);return n(Hd.Provider,{value:{toasts:t,showToast:s,closeToast:a},children:e})}function pi(){const e=ua(Hd);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function hf({toast:e,onClose:t}){se(()=>{const a=e.duration||5e3;if(a>0){const o=setTimeout(()=>{t(e.id)},a);return()=>clearTimeout(o)}},[e.id,e.duration,t]);const r={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return c("div",{className:`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg min-w-[320px] max-w-[500px] animate-[slideIn_0.3s_ease-out] ${{success:"bg-emerald-50 border-emerald-200 text-emerald-900",error:"bg-red-50 border-red-200 text-red-900",info:"bg-blue-50 border-blue-200 text-blue-900",warning:"bg-amber-50 border-amber-200 text-amber-900"}[e.type]}`,children:[n("span",{className:"text-2xl",children:r[e.type]}),n("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),n("button",{onClick:()=>t(e.id),className:"text-gray-500 hover:text-gray-700 text-xl leading-none bg-transparent border-none cursor-pointer p-0 w-6 h-6 flex items-center justify-center rounded transition-colors hover:bg-black/10",children:"×"})]})}function mf({toasts:e,onClose:t}){return e.length===0?null:c("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[n("style",{children:`
7
+ @keyframes slideIn {
8
+ from {
9
+ transform: translateX(400px);
10
+ opacity: 0;
11
+ }
12
+ to {
13
+ transform: translateX(0);
14
+ opacity: 1;
15
+ }
16
+ }
17
+ `}),e.map(r=>n(hf,{toast:r,onClose:t},r.id))]})}function Xt(e,t){const[r,s]=E(""),[a,o]=E(!1),[i,l]=E(null),[d,u]=E(null),[p,h]=E(!1);se(()=>{t&&(h(!1),o(!1),l(null),u(null))},[t]),se(()=>{if(!e||!t){t||s("");return}const f=async()=>{if(!p)try{const g=await fetch(`/api/logs/${e}`);if(g.ok){const b=(await g.text()).trim().split(`
18
+ `).filter(C=>C.length>0);if(b.length<3){o(!1),h(!1),l(null),u(null),s("");return}const v=b.filter(C=>C.includes("CodeYam Log Level 1"));if(v.length>0){const C=v[v.length-1];s(C.replace(/.*CodeYam Log Level 1: /,""))}const N=b.find(C=>C.includes("$$INTERACTIVE_SERVER_URL$$:"));if(N){const C=N.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(C),h(!0)}const w=b.find(C=>C.includes("$$INTERACTIVE_SCENARIO_URLS$$:"));if(w)try{const C=w.split("$$INTERACTIVE_SCENARIO_URLS$$:")[1].trim();u(JSON.parse(C))}catch{}b.some(C=>C.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};f().catch(()=>{});const y=setInterval(()=>{f().catch(()=>{})},500);return()=>clearInterval(y)},[e,t,p]);const m=le(()=>{s(""),o(!1),l(null),u(null),h(!1)},[]);return{lastLine:r,interactiveUrl:i,scenarioUrlMap:d,isCompleted:a,resetLogs:m}}function mn({projectSlug:e,onClose:t}){const[r,s]=E("Loading logs..."),[a,o]=E(!0),[i,l]=E(!0),[d,u]=E("all"),p=be(null);return se(()=>{const h=async()=>{try{const m=await fetch(`/api/logs/${e}`);if(m.ok){const f=await m.text();if(d==="all")s(f);else{const y=f.trim().split(`
19
+ `).filter(g=>{if(g.length===0)return!1;const x=g.match(/^.*CodeYam Log Level (\d+):/);return!!x&&Number(x[1])<=d});s(y.map(g=>g.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
20
+ `))}i&&p.current&&setTimeout(()=>{var y;(y=p.current)==null||y.scrollTo({top:p.current.scrollHeight,behavior:"smooth"})},100)}else s(`Error: ${m.status} - ${await m.text()}`)}catch(m){s(`Error fetching logs: ${m.message}`)}};if(h().catch(()=>{}),a){const m=setInterval(()=>{h().catch(()=>{})},2e3);return()=>clearInterval(m)}},[e,a,i,d]),se(()=>{const h=m=>{m.key==="Escape"&&t()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:c("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:h=>h.stopPropagation(),children:[c("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[c("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),c("div",{className:"flex items-center gap-4",children:[c("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),c("select",{value:d,onChange:h=>u(h.target.value==="all"?"all":Number(h.target.value)),className:"bg-[#333] text-white border border-[#555] rounded px-2 py-1 text-sm cursor-pointer outline-none transition-all hover:border-[#777] hover:bg-[#3a3a3a] focus:border-blue-600",children:[n("option",{value:"1",children:"1"}),n("option",{value:"2",children:"2"}),n("option",{value:"3",children:"3"}),n("option",{value:"4",children:"4"}),n("option",{value:"all",children:"All"})]})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:a,onChange:h=>o(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),c("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[n("input",{type:"checkbox",checked:i,onChange:h=>l(h.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),n("button",{onClick:t,className:"bg-transparent border-none text-[#999] text-2xl cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-all hover:bg-[#333] hover:text-white",title:"Close (Esc)",children:"✕"})]})]}),n("pre",{className:"flex-1 m-0 px-5 py-4 overflow-auto font-mono text-[13px] leading-relaxed text-[#d4d4d4] bg-[#1e1e1e] whitespace-pre-wrap wrap-break-word scrollbar-thin scrollbar-thumb-[#424242] scrollbar-track-[#1e1e1e] hover:scrollbar-thumb-[#4f4f4f]",ref:p,children:r})]})})}function St({type:e,size:t="default"}){const r={visual:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},library:{iconColor:"#06b6d5",bgColor:"bg-[#e6fbff]",bgHex:"#e6fbff"},type:{iconColor:"#db2627",bgColor:"bg-[#ffe1e1]",bgHex:"#ffe1e1"},data:{iconColor:"#2563eb",bgColor:"bg-blue-100",bgHex:"#dbeafe"},index:{iconColor:"#ea580c",bgColor:"bg-orange-100",bgHex:"#ffedd5"},functionCall:{iconColor:"#7c3aed",bgColor:"bg-purple-100",bgHex:"#f3e8ff"},class:{iconColor:"#059669",bgColor:"bg-emerald-100",bgHex:"#d1fae5"},method:{iconColor:"#0891b2",bgColor:"bg-cyan-100",bgHex:"#cffafe"},other:{iconColor:"#6b7280",bgColor:"bg-gray-100",bgHex:"#f3f4f6"}},s=r[e]||r.other,a=t==="large"?18:14,o=t==="large"?32:18,i=()=>{switch(e){case"library":return n(Id,{size:a,color:s.iconColor});case"visual":return n(Wr,{size:a,color:s.iconColor});case"type":return n(im,{size:a,color:s.iconColor});case"data":return n(om,{size:a,color:s.iconColor});case"index":return n(am,{size:a,color:s.iconColor});case"functionCall":return n(zl,{size:a,color:s.iconColor});case"class":return n(sm,{size:a,color:s.iconColor});case"method":return n(zl,{size:a,color:s.iconColor});case"other":return n(Bl,{size:a,color:s.iconColor});default:return n(Bl,{size:a,color:s.iconColor})}};return n("span",{className:`flex items-center justify-center rounded ${s.bgColor}`,style:{width:`${o}px`,height:`${o}px`},children:i()})}function Vd({filePath:e,maxLength:t=60,className:r,style:s}){const o=((l,d)=>{if(l.length<=d)return l;const u="...",p=d-u.length,h=Math.ceil(p*.4),m=Math.floor(p*.6),f=l.slice(0,h),y=l.slice(-m),g=f.lastIndexOf("/"),x=y.indexOf("/"),b=g>h*.5?f.slice(0,g+1):f,v=x!==-1&&x<m*.5?y.slice(x):y;return`${b}${u}${v}`})(e,t),i=o!==e;return n("span",{className:r||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...s,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:o})}function ro({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:s=50,showScenarioCount:a=!1,scenarioCount:o=0,additionalContent:i}){return c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"flex items-center gap-1",children:[n(St,{type:e.entityType||"other"}),c(Ee,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:t,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,a&&o>0&&` (${o})`]}),n(Vd,{filePath:e.filePath,maxLength:s,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const so={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function ff({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:s=!1,queuedJobCount:a=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:l=[]}){var V,F,Y;const[d,u]=E(!1),[p,h]=E(!1),[m,f]=E(null),[y,g]=E(new Set),[x,b]=E(new Set),[v,N]=E(!1),w=!!i||o.length>0,C=!!i,k=(i==null?void 0:i.entities)||r,j=!!(e!=null&&e.analysisCompletedAt),A=(e==null?void 0:e.readyToBeCaptured)??0,_=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||j&&(A===0||_>=A);const M=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,T=w,{lastLine:D}=Xt(t,T),R=C||o.length>0,L=new Set(((V=i==null?void 0:i.entities)==null?void 0:V.map(P=>P.sha))||[]),U=l.filter(P=>!(P.currentEntityShas||[]).some(S=>L.has(S))),W=(()=>{const O=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&M){const S=e.analysisCompletedAt||e.createdAt;if(new Date(S).getTime()>O)return!0}if(U.length>0){const S=U[0],$=S.analysisCompletedAt||S.archivedAt||S.createdAt;if($&&new Date($).getTime()>O)return!0}return!1})();return se(()=>{const P=(i==null?void 0:i.id)||null;w&&!p&&P!==m&&h(!0),!w&&m!==null&&f(null)},[w,i==null?void 0:i.id,p,m]),c(we,{children:[c("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${p?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!p&&c("div",{onClick:()=>{h(!0),f(null)},className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-gray-50 transition-colors",title:"Click to expand",children:[R?n(Ot,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(to,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:R?"Analyzing...":"Activity: No Activity Yet"}),R&&n("button",{onClick:P=>{P.stopPropagation(),u(!0)},className:"ml-auto px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),p&&c("div",{children:[c("div",{className:"flex items-center justify-between px-3 py-2",children:[c("div",{className:"flex items-center gap-2",children:[R?n(Ot,{size:16,className:"animate-spin",style:{color:"#005C75"}}):n("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:n(to,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:R?"Analyzing...":"Activity"})]}),c("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>u(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),n("button",{onClick:()=>{h(!1),f((i==null?void 0:i.id)||null)},className:"p-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC"},title:"Collapse","aria-label":"Collapse",children:n(Tt,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),c("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[R&&i&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(to,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Current Activity"})]}),n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:k.length>0?c("div",{className:"space-y-1.5",children:[(v?k:k.slice(0,3)).map(P=>n(ro,{entity:P,nameSize:"11px",pathSize:"10px",pathMaxLength:150},P.sha)),k.length>3&&n("button",{onClick:()=>N(P=>!P),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:so,"aria-label":v?"Show fewer entities":`Show ${k.length-3} more entities`,children:v?"Show less":`+${k.length-3} more`}),D&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:D})]}):c("div",{children:[i.entityNames&&i.entityNames.length>0?c("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((P,O)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:P},O)),i.entityNames.length>5&&c("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):c("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((F=i.entityShas)==null?void 0:F.length)||0," ",((Y=i.entityShas)==null?void 0:Y.length)===1?"entity":"entities","..."]}),D&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:D})]})})]}),o.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(lm,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:o.map(P=>{var $,I;const O=y.has(P.id),S=O?P.entities:P.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:P.entities.length>0?c("div",{className:"space-y-1.5",children:[S.map(K=>n(ro,{entity:K,nameSize:"10px",pathSize:"9px",pathMaxLength:120},K.sha)),P.entities.length>3&&n("button",{onClick:()=>{g(K=>{const q=new Set(K);return q.has(P.id)?q.delete(P.id):q.add(P.id),q})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:so,"aria-label":O?"Show fewer entities":`Show ${P.entities.length-3} more entities`,children:O?"Show less":`+${P.entities.length-3} more`})]}):c("div",{style:{fontSize:"10px",color:"#343434"},children:[P.type==="analysis"&&n(we,{children:P.entityNames&&P.entityNames.length>0?c("div",{className:"space-y-0.5",children:[P.entityNames.slice(0,5).map((K,q)=>n("div",{children:K},q)),P.entityNames.length>5&&c("div",{className:"italic",children:["+",P.entityNames.length-5," more"]})]}):`Analyzing ${(($=P.entityShas)==null?void 0:$.length)||0} ${((I=P.entityShas)==null?void 0:I.length)===1?"entity":"entities"}`}),P.type==="recapture"&&"Recapturing scenario",P.type==="debug-setup"&&"Setting up debug environment"]})},P.id)})})]}),W&&U.length>0&&c("div",{children:[c("div",{className:"flex items-center gap-1.5 mb-2",children:[n(ni,{size:12,style:{color:"#005C75"}}),n("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Recently Completed"})]}),n("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:U.slice(0,3).map((P,O)=>{const S=P.entities||[],$=P.analysisCompletedAt||P.archivedAt||P.createdAt||"",I=(()=>{if(!$)return"";const z=Date.now()-new Date($).getTime(),B=Math.floor(z/6e4),H=Math.floor(z/36e5);return H>0?`${H}h ago`:B>0?`${B}m ago`:"just now"})(),K=x.has(O),J=(K?S:S.slice(0,3)).map(z=>{var B,H,re;return{...z,scenarioCount:((re=(H=(B=z.analyses)==null?void 0:B[0])==null?void 0:H.scenarios)==null?void 0:re.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:S.length>0&&c("div",{className:"space-y-1.5",children:[J.map((z,B)=>c("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(ro,{entity:z,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:z.scenarioCount})}),B===0&&I&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:I})]},z.sha)),S.length>3&&n("button",{onClick:()=>{b(z=>{const B=new Set(z);return B.has(O)?B.delete(O):B.add(O),B})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:so,"aria-label":K?"Show fewer entities":`Show ${S.length-3} more entities`,children:K?"Show less":`+${S.length-3} more`})]})},O)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(Ee,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&t&&n(mn,{projectSlug:t,onClose:()=>u(!1)})]})}function jt(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function es(e){const{file_id:t,project_id:r,commit_id:s,file_path:a,entity_type:o,entity_branches:i,analyses:l,commit:d,created_at:u,updated_at:p,...h}=e,m=(i??[]).map(g=>g.branch_id),f=l?l.map(en):void 0,y=d?Rn(d):void 0;return jt({...h,fileId:t,projectId:r,commitId:s,filePath:a,entityType:o,commit:y,analyses:f,branchIds:m,createdAt:u,updatedAt:p})}function hi(e){return jt({id:e.id,projectId:e.project_id,name:e.name,path:e.path,deleted:!!e.deleted,metadata:e.metadata??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0})}function ga(e){const{branches:t,files:r,analyzed_at:s,content_changed_at:a,created_at:o,updated_at:i,github_token:l,configuration:d,team_id:u,...p}=e;return jt({...p,branches:t?t.map(In):void 0,files:r?r.map(hi):void 0,analyzedAt:s,contentChangedAt:a,createdAt:o,updatedAt:i})}function gf(e){const{id:t,project_id:r,user_id:s,scenario_id:a,thumbs_up:o,user:i}=e,l=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return jt({id:t,projectId:r,userId:s,scenarioId:a,thumbsUp:!!o,user:l})}function yf(e){const{id:t,project_id:r,user_id:s,scenario_id:a,text:o,created_at:i,updated_at:l,user:d}=e,u=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return jt({id:t,projectId:r,userId:s,scenarioId:a,text:o,createdAt:i,updatedAt:l,user:u})}function Kd(e){const{project_id:t,analysis_id:r,previous_version_id:s,analysis:a,user_scenarios:o,scenario_comments:i,approved:l,...d}=e,u=a?en(a):void 0,p=o?o.map(gf):void 0,h=i?i.map(yf):void 0;return jt({...d,projectId:t,analysisId:r,previousVersionId:s,analysis:u,userScenarios:p,comments:h})}function xf(e){return jt({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?en(e.analysis):void 0,entity:e.entity?es(e.entity):void 0,branch:e.branch?In(e.branch):void 0,createdAt:e.created_at})}function en(e){const{project_id:t,commit_id:r,file_id:s,file_path:a,entity_sha:o,entity_type:i,entity_name:l,previous_analysis_id:d,file:u,entity:p,commit:h,project:m,scenarios:f,analysis_branches:y,dependency_analyzed_tree_sha:g,analyzed_tree_sha:x,branch_commit_sha:b,committed_at:v,completed_at:N,created_at:w,updated_at:C,indirect:k,...j}=e,A=p?es(p):void 0,_=u?hi(u):void 0,M=m?ga(m):void 0,T=h?Rn(h):void 0,D=f?f.map(Kd):void 0,R=y?y.map(xf):void 0,L=R?R.map(U=>U.branch):void 0;return jt({...j,projectId:t,commitId:r,fileId:s,filePath:a,entitySha:o,entityType:i,entityName:l,previousAnalysisId:d,entity:A,file:_,commit:T,project:M,scenarios:D,analysisBranches:R,branches:L,dependencyAnalyzedTreeSha:g,analyzedTreeSha:x,branchCommitSha:b,committedAt:v,completedAt:N,createdAt:w,updatedAt:C,indirect:!!k})}function mi(e){return jt({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?Rn(e.commit):void 0,branch:e.branch?In(e.branch):void 0})}function bf(e){const{project_id:t,commit_id:r,created_at:s,updated_at:a,success:o,...i}=e;return jt({...i,projectId:t,commitId:r,createdAt:s,updatedAt:a,success:!!o})}function Rn(e){const{project_id:t,branch_id:r,branch:s,background_jobs:a,merged_branch_id:o,mergedBranch:i,ai_message:l,html_url:d,author:u,analyses:p,entities:h,commit_branches:m,committed_at:f,analyzed_at:y,...g}=e,x=s?In(s):void 0,b=i?In(i):void 0,v=(a==null?void 0:a.length)>0?bf(a[a.length-1]):void 0,N=(p??[]).map(en),w=(h??[]).map(es),C=(m==null?void 0:m.length)>0?m.map(mi):void 0;return u&&(u.username=u.preferredUsername??u.username),jt({...g,projectId:t,branchId:r,branch:x,backgroundJob:v,mergedBranchId:o,mergedBranch:b,aiMessage:l,htmlUrl:d,author:u,analyses:N,entities:w,commitBranches:C,committedAt:f,analyzedAt:y})}function In(e){const{project_id:t,content_changed_at:r,commits:s,analysis_branches:a,active_at:o,created_at:i,updated_at:l,primary:d,...u}=e,p=s?s.map(Rn):void 0,h=a?a.flatMap(m=>en(m.analysis)):void 0;return jt({...u,projectId:t,contentChangedAt:r,commits:p,analyses:h,activeAt:o,createdAt:i,updatedAt:l,primary:!!d})}var ca;class vf{constructor(){Il(this,ca,new wf)}transformQuery(t){return Rl(this,ca).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}ca=new WeakMap;class wf extends Em{transformValue(t){return{...super.transformValue(t),value:typeof t.value=="boolean"?t.value?1:0:t.value}}transformPrimitiveValueList(t){return{...t,values:t.values.map(r=>typeof r=="boolean"?r?1:0:r)}}}const Se=()=>null;function Be(e=!1){return t=>(t=t.defaultTo(wt`CURRENT_TIMESTAMP`),e&&(t=t.notNull()),t)}const Nf={analyzed_at:Se(),configuration:Se(),content_changed_at:Se(),created_at:Se(),description:Se(),github_token:Se(),id:Se(),metadata:Se(),name:Se(),path:Se(),slug:Se(),team_id:Se(),updated_at:Se()},Sf=Object.keys(Nf);async function Cf(e){await e.schema.createTable("projects").addColumn("id","uuid",t=>t.primaryKey()).addColumn("name","text").addColumn("slug","text",t=>t.notNull()).addColumn("github_token","text").addColumn("description","text").addColumn("path","text").addColumn("configuration","text").addColumn("metadata","text").addColumn("content_changed_at","datetime").addColumn("analyzed_at","datetime").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be()).addColumn("team_id","integer").ifNotExists().execute()}async function kf(e){await e.schema.createTable("analyses").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("file_id","uuid").addColumn("commit_id","uuid").addColumn("entity_sha","varchar").addColumn("entity_name","varchar").addColumn("status","text").addColumn("metadata","text").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be(!0)).addColumn("tree_sha","text").addColumn("analyzed_tree_sha","text").addColumn("dependency_analyzed_tree_sha","text").addColumn("previous_analysis_id","uuid").addColumn("branch_commit_sha","varchar").addColumn("indirect","boolean").addColumn("committed_at","datetime").addColumn("completed_at","datetime").addColumn("file_path","varchar").addColumn("entity_type","varchar").ifNotExists().execute()}const jf={active:Se(),analysis_id:Se(),branch_id:Se(),created_at:Se(),entity_sha:Se(),id:Se()},_f=Object.keys(jf);async function Ef(e){await e.schema.createTable("analysis_branches").addColumn("id","uuid",t=>t.primaryKey()).addColumn("analysis_id","uuid",t=>t.notNull()).addColumn("branch_id","uuid",t=>t.notNull()).addColumn("entity_sha","varchar",t=>t.notNull()).addColumn("active","boolean",t=>t.defaultTo(!0)).addColumn("created_at","datetime",Be()).ifNotExists().execute()}async function Pf(e){await e.schema.createTable("background_jobs").addColumn("commit_id","uuid",t=>t.notNull()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("progress","text").addColumn("success","boolean").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime").addPrimaryKeyConstraint("background_jobs_pkey",["project_id","commit_id"]).ifNotExists().execute()}const Af={active_at:Se(),content_changed_at:Se(),created_at:Se(),id:Se(),metadata:Se(),name:Se(),primary:Se(),project_id:Se(),ref:Se(),sha:Se(),updated_at:Se()},Gd=Object.keys(Af);async function Tf(e){await e.schema.createTable("branches").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("ref","text").addColumn("name","text").addColumn("sha","text").addColumn("primary","boolean",t=>t.notNull().defaultTo(!1)).addColumn("metadata","text").addColumn("content_changed_at","datetime",Be()).addColumn("active_at","datetime").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be()).ifNotExists().execute()}async function Mf(e){await e.schema.createTable("commit_branches").addColumn("id","uuid",t=>t.primaryKey()).addColumn("branch_id","uuid").addColumn("commit_id","uuid").addColumn("active","boolean").addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}const $f={ai_message:Se(),analyzed_at:Se(),author_github_username:Se(),branch_id:Se(),committed_at:Se(),created_at:Se(),files:Se(),html_url:Se(),id:Se(),merged_branch_id:Se(),message:Se(),metadata:Se(),project_id:Se(),sha:Se(),title:Se(),url:Se()},qd=Object.keys($f),Ff=qd.filter(e=>e!=="files");async function Df(e){await e.schema.createTable("commits").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("branch_id","uuid").addColumn("merged_branch_id","uuid").addColumn("message","text").addColumn("ai_message","text").addColumn("title","varchar").addColumn("author_github_username","varchar").addColumn("url","varchar").addColumn("html_url","varchar").addColumn("sha","varchar",t=>t.notNull()).addColumn("files","text").addColumn("metadata","text").addColumn("committed_at","datetime").addColumn("analyzed_at","datetime").addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function Rf(e){await e.schema.createTable("debug_reports").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_slug","varchar",t=>t.notNull()).addColumn("s3_key","varchar",t=>t.notNull()).addColumn("file_size_bytes","bigint").addColumn("metadata","text").addColumn("status","varchar").addColumn("created_at","datetime",Be(!0)).addColumn("uploaded_at","datetime").addColumn("base_sha","varchar").addColumn("delta_size_bytes","bigint").ifNotExists().execute()}async function If(e){await e.schema.createTable("labs_requests").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_slug","varchar",t=>t.notNull().unique()).addColumn("name","varchar",t=>t.notNull()).addColumn("email","varchar",t=>t.notNull()).addColumn("org_name","varchar").addColumn("org_size","varchar").addColumn("project_size","varchar").addColumn("tech_stack","varchar").addColumn("status","varchar").addColumn("unlock_code","varchar").addColumn("created_at","datetime",Be(!0)).addColumn("approved_at","datetime").ifNotExists().execute()}const Of={commit_id:Se(),created_at:Se(),description:Se(),documentation:Se(),entity_type:Se(),file_id:Se(),file_path:Se(),metadata:Se(),name:Se(),project_id:Se(),quality:Se(),sha:Se(),updated_at:Se()},Qd=Object.keys(Of);async function Lf(e){await e.schema.createTable("entities").addColumn("project_id","uuid",t=>t.notNull()).addColumn("file_id","uuid").addColumn("commit_id","uuid").addColumn("name","varchar").addColumn("sha","varchar",t=>t.primaryKey()).addColumn("entity_type","varchar").addColumn("file_path","varchar").addColumn("description","text").addColumn("documentation","text").addColumn("metadata","text").addColumn("quality","text").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime").ifNotExists().execute()}const Bf={active:Se(),branch_id:Se(),entity_sha:Se()},zf=Object.keys(Bf);async function Yf(e){await e.schema.createTable("entity_branches").addColumn("branch_id","uuid",t=>t.notNull()).addColumn("entity_sha","varchar",t=>t.notNull()).addColumn("active","boolean",t=>t.defaultTo(!0)).addPrimaryKeyConstraint("entity_branches_pkey",["branch_id","entity_sha"]).ifNotExists().execute()}async function Uf(e){await e.schema.createTable("entity_statements").addColumn("id","integer",t=>t.autoIncrement().primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("entity_sha","varchar",t=>t.notNull()).addColumn("statement_sha","varchar",t=>t.notNull()).addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}const Wf={created_at:Se(),deleted:Se(),id:Se(),metadata:Se(),name:Se(),path:Se(),project_id:Se(),updated_at:Se()},Jf=Object.keys(Wf);async function Hf(e){await e.schema.createTable("files").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("name","varchar").addColumn("path","varchar",t=>t.notNull()).addColumn("deleted","boolean",t=>t.defaultTo(!1)).addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be()).addColumn("metadata","text").ifNotExists().execute()}async function Vf(e){await e.schema.createTable("github_payloads").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("payload_type","varchar").addColumn("payload","text").addColumn("after","varchar").addColumn("commit_sha","varchar").addColumn("ref","varchar").addColumn("committed_at","datetime").addColumn("error","text").addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function Kf(e){await e.schema.createTable("github_users").addColumn("username","varchar",t=>t.primaryKey()).addColumn("preferred_username","varchar").addColumn("avatar_url","varchar").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be()).ifNotExists().execute()}async function Gf(e){await e.schema.createTable("scenario_comments").addColumn("id","serial",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("scenario_id","uuid").addColumn("user_id","uuid").addColumn("text","text").addColumn("metadata","text").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be(!0)).ifNotExists().execute()}async function qf(e){await e.schema.createTable("editor_scenarios").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("name","varchar",t=>t.notNull()).addColumn("description","text").addColumn("component_name","varchar").addColumn("component_path","varchar").addColumn("url","varchar").addColumn("type","varchar").addColumn("screenshot_path","varchar").addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be(!0)).ifNotExists().execute();for(const t of["component_name","component_path","url","type","screenshot_path"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"varchar").execute()}catch{}for(const t of["viewport_width","viewport_height"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"integer").execute()}catch{}for(const t of["dimensions","screenshot_paths"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"text").execute()}catch{}for(const t of["page_file_path","entity_sha","display_name"])try{await e.schema.alterTable("editor_scenarios").addColumn(t,"varchar").execute()}catch{}try{const t=await e.selectFrom("editor_scenarios").select(["id","dimension","dimensions"]).execute();for(const r of t){const s=r;s.dimension&&!s.dimensions&&await e.updateTable("editor_scenarios").set({dimensions:JSON.stringify([s.dimension])}).where("id","=",s.id).execute()}}catch{}try{const t=await e.selectFrom("editor_scenarios").select(["id","screenshot_path","screenshot_paths","dimensions"]).execute();for(const r of t){const s=r;if(s.screenshot_path&&!s.screenshot_paths){let a="Default";try{const o=s.dimensions?JSON.parse(s.dimensions):null;Array.isArray(o)&&o.length>0&&(a=o[0])}catch{}await e.updateTable("editor_scenarios").set({screenshot_paths:JSON.stringify({[a]:s.screenshot_path})}).where("id","=",s.id).execute()}}}catch{}}const Qf={analysis_id:Se(),approved:Se(),created_at:Se(),description:Se(),id:Se(),metadata:Se(),name:Se(),previous_version_id:Se(),project_id:Se()},Xs=Object.keys(Qf);async function Zf(e){await e.schema.createTable("scenarios").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid").addColumn("analysis_id","uuid").addColumn("name","varchar").addColumn("description","text").addColumn("metadata","text").addColumn("approved","boolean").addColumn("previous_version_id","uuid").addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function Xf(e){await e.schema.createTable("statements").addColumn("sha","varchar",t=>t.primaryKey()).addColumn("text","text",t=>t.notNull()).addColumn("llm_call_id","varchar").addColumn("results","text").addColumn("issues","text").addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function eg(e){await e.schema.createTable("teams").addColumn("id","serial",t=>t.primaryKey()).addColumn("name","varchar",t=>t.notNull()).addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function tg(e){await e.schema.createTable("user_scenarios").addColumn("id","uuid",t=>t.primaryKey()).addColumn("project_id","uuid",t=>t.notNull()).addColumn("scenario_id","uuid",t=>t.notNull()).addColumn("user_id","uuid",t=>t.notNull()).addColumn("thumbs_up","boolean",t=>t.defaultTo(!1)).addColumn("created_at","datetime",Be(!0)).ifNotExists().execute()}async function ng(e){await e.schema.createTable("user_teams").addColumn("team_id","integer",t=>t.notNull()).addColumn("user_auth_id","uuid",t=>t.notNull()).addPrimaryKeyConstraint("user_teams_pkey",["team_id","user_auth_id"]).ifNotExists().execute()}async function rg(e){await e.schema.createTable("users").addColumn("auth_id","uuid",t=>t.primaryKey()).addColumn("email","varchar").addColumn("github_username","varchar").addColumn("github_token","varchar").addColumn("verified","boolean",t=>t.defaultTo(!1)).addColumn("created_at","datetime",Be(!0)).addColumn("updated_at","datetime",Be()).ifNotExists().execute()}const sg=!!On("ENABLE_QUERY_LOGGING"),ag=!!On("ENABLE_QUERY_ERROR_LOGGING");On("USE_LOCAL_POSTGRESQL_FOR_TESTING");let ws;function $e(){if(!ws){const e=Xd();if(e==="sqlite")ws=og();else if(e==="postgresql")ws=ig();else throw new Error(`Unknown database type: ${e}`)}return ws}function og(e){if(e||(e=On("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=Q.existsSync(e),r=G.dirname(e);if(!Q.existsSync(r))Q.mkdirSync(r,{recursive:!0,mode:493});else try{Q.chmodSync(r,493)}catch(a){console.warn(`Warning: Could not set permissions on database directory: ${a.message}`)}const s=new km(e,{readonly:!1,fileMustExist:!1});if(s.pragma("journal_mode = WAL"),s.pragma("busy_timeout = 5000"),s.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const a=s.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();t&&a.count===0&&(console.error("CodeYam DB ERROR: Database file existed but projects table is missing!"),console.error("This likely means SQLite created a new empty database instead of opening the existing one."),console.error("Possible causes: corruption, WAL file issues, or file locking problems."))}catch(a){console.error("CodeYam DB ERROR: Failed to verify database schema:",a)}return new Yd({dialect:new Am({database:s}),plugins:[new Pm,new vf],log:Zd})}function ig(){const e=cg();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new jm({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,s)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Yd({dialect:new Tm({pool:t}),log:Zd})}let ao=null;function zn(){return ao||(ao=lg(Xd())),ao}function Zd(e){e.level==="error"?ag&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):sg&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function lg(e){if(e==="sqlite")return Mm;if(e==="postgresql")return $m;throw new Error(`Unknown database type: ${e}`)}function Xd(){if(On("SQLITE_PATH"))return"sqlite";if(On("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}async function zj(e){await Cf(e),await kf(e),await Ef(e),await Pf(e),await Tf(e),await Mf(e),await Df(e),await Rf(e),await qf(e),await Lf(e),await Yf(e),await Uf(e),await Hf(e),await Vf(e),await Kf(e),await If(e),await Gf(e),await Zf(e),await Xf(e),await eg(e),await tg(e),await ng(e),await rg(e)}function cg(){const e=On("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function On(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}const dg=()=>crypto.randomUUID();function ug(e){const{id:t,projectId:r,activeAt:s,contentChangedAt:a,metadata:o,...i}=e;return delete i.commits,delete i.files,delete i.analyses,delete i.createdAt,delete i.updatedAt,{...i,id:t??dg(),project_id:r,active_at:s,content_changed_at:a,metadata:o?JSON.stringify(o):null}}var rt=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Vite="Vite",e.Expo="Expo",e.Unknown="Unknown",e))(rt||{});const ya="Default Scenario";let pg="<main>";function hg(){return pg}function Jl(e,...t){Oe(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function Oe(...e){const t=hg(),r=e.map(a=>{if(a)return typeof a=="string"?a:a instanceof Error?`${a.name}: ${a.message}
21
+ ${a.stack}`:typeof a=="object"?mg(a):String(a)}).filter(Boolean).join(`
22
+ `),s=`${t} ${r}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(s+`
23
+ `);return}console.log(s.replace(/\n/g,"\r"))}function mg(e,t=2){function r(s,a=new WeakMap){return s===null||typeof s!="object"?s:a.has(s)?`"[Circular: ${s.constructor.name}]"`:(a.set(s,!0),Array.isArray(s)?`[${s.map(l=>{const d=r(l,a);return typeof l=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(s).map(([i,l])=>{let d;return typeof l>"u"?null:(typeof l=="function"?d=`"(function: ${l.name||"anonymous"})"`:l instanceof Date?d=`"${l.toISOString()}"`:typeof l=="object"&&l!==null?d=r(l,a):typeof l=="string"?d=`"${l.replace(/"/g,'\\"')}"`:d=JSON.stringify(l),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,t)}catch(s){const a=r(e);if(!t)return a;try{return JSON.stringify(JSON.parse(r(e)),null,t)}catch(o){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:o,pureStringifyError:s,serialized:a}),a}}}function ea(e,t){try{let r=function(o){var i,l;if(Xe.isFunctionDeclaration(o)&&Mr(o)){const d=((i=o.name)==null?void 0:i.text)||"default",u=o.getText(s),p=oo(o);a.push({name:d,code:u,sha:En(t,d,u),entityType:"function",isDefault:p})}else if(Xe.isClassDeclaration(o)&&Mr(o)){const d=((l=o.name)==null?void 0:l.text)||"default",u=o.getText(s),p=oo(o),h=u.includes("React.")||u.includes("jsx")||u.includes("tsx");a.push({name:d,code:u,sha:En(t,d,u),entityType:h?"component":"class",isDefault:p})}else if(Xe.isInterfaceDeclaration(o)&&Mr(o)){const d=o.name.text,u=o.getText(s);a.push({name:d,code:u,sha:En(t,d,u),entityType:"interface",isDefault:!1})}else if(Xe.isTypeAliasDeclaration(o)&&Mr(o)){const d=o.name.text,u=o.getText(s);a.push({name:d,code:u,sha:En(t,d,u),entityType:"type",isDefault:!1})}else if(Xe.isVariableStatement(o)&&Mr(o)){const d=oo(o);o.declarationList.declarations.forEach(u=>{var p;if(Xe.isIdentifier(u.name)){const h=u.name.text,m=o.getText(s),f=((p=u.initializer)==null?void 0:p.getText(s))||"",y=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));a.push({name:h,code:m,sha:En(t,h,m),entityType:y?"component":"variable",isDefault:d})}})}else if(Xe.isExportAssignment(o)){const d=o.getText(s);a.push({name:"default",code:d,sha:En(t,"default",d),entityType:"unknown",isDefault:!0})}else if(Xe.isExportDeclaration(o)&&o.exportClause&&Xe.isNamedExports(o.exportClause)){const d=o.getText(s);for(const u of o.exportClause.elements){const p=u.name.text;a.push({name:p,code:d,sha:En(t,p,d),entityType:"unknown",isDefault:!1})}}Xe.forEachChild(o,r)};const s=Xe.createSourceFile(t,e,Xe.ScriptTarget.Latest,!0),a=[];return r(s),a}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function Mr(e){if(!Xe.canHaveModifiers(e))return!1;const t=Xe.getModifiers(e);return t?t.some(r=>r.kind===Xe.SyntaxKind.ExportKeyword):!1}function oo(e){if(!Xe.canHaveModifiers(e))return!1;const t=Xe.getModifiers(e);return t?t.some(r=>r.kind===Xe.SyntaxKind.DefaultKeyword):!1}function En(e,t,r){const s=pr.createHash("sha256");return s.update(`${e}:${t}:${r}`),s.digest("hex").substring(0,40)}function fg(e){var u;const{webapp:t,port:r,environmentVariables:s,packageManager:a}=e,o=t==null?void 0:t.startCommand;if(!o)return`${a} ${a==="npm"?"run ":""}dev`;const i=((u=o.args)==null?void 0:u.map(p=>p.replace(/\$PORT/g,String(r))))??[],l=[];for(const p of s)if(p.key&&p.value!==void 0){const h=String(p.value).replace(/'/g,"'\\''");l.push(`${p.key}='${h}'`)}if(o.env)for(const[p,h]of Object.entries(o.env)){const f=String(h).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${p}='${f}'`)}const d=l.length>0?l.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${o.command} ${i.join(" ")}`}function gg(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=G.normalize(e),s=[...t].sort((a,o)=>{var i,l;return(((i=o.path)==null?void 0:i.length)??0)-(((l=a.path)==null?void 0:l.length)??0)});for(const a of s){const o=G.normalize(a.path??".");if(o==="."||r.startsWith(o+G.sep)||r===o)return a}return t[0]}function yg(e){const{filePath:t,webapps:r,environmentVariables:s,port:a,packageManager:o}=e;if(!r||r.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=gg(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=fg({webapp:i,port:a,environmentVariables:s,packageManager:o});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??o,startCommand:l,url:`http://localhost:${a}/static/codeyam-sample`}}function hr(e,t,r=[]){const s=Array.isArray(t)?t:[t];return a=>a.columns(s).doUpdateSet(o=>{const i=Object.keys(e).filter(l=>l!==t&&!r.includes(l));return Object.fromEntries(i.map(l=>[l,o.ref(`excluded.${l}`)]))})}async function xg(e){if(e.length===0)return[];const t=$e(),r=e.map(ug);try{return(await t.insertInto("branches").values(r).onConflict(hr(r[0],"id",["created_at"])).returningAll().execute()).map(In)}catch(s){return Oe("CodeYam Error: Database error upserting branches",s,{branchCount:e.length,branchIds:e.map(a=>a.id)}),[]}}function bg(e){const{jsonObjectFrom:t}=zn();return t(e.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",e.ref("commits.author_github_username")))}async function vg({ids:e,analysisId:t}){const r=$e();try{let s=r.deleteFrom("scenarios");if(e){if(e.length===0)return;s=s.where("id","in",e)}else if(t)s=s.where("analysis_id","=",t);else throw Oe("CodeYam Error: No deletion criteria provided",null,{ids:e,analysisId:t}),new Error("No deletion criteria provided for scenarios");await s.execute()}catch(s){throw Oe("CodeYam Error: Database error deleting scenarios",s,{ids:e,analysisId:t}),s}}function wg(...e){try{const t=pr.createHash("sha256");for(const r of e)t.update(r);return t.digest("hex")}catch(t){throw console.log("CodeYam Error: Error generating sha",e),t}}function io(e,t){return t.map(r=>Ng(e,r))}function Ng(e,t){return wt` ${wt.ref(e)}.${wt.ref(t)}`.as(t)}function Sg(e,t,r){return t.map(s=>Cg(e,s,r))}function Cg(e,t,r){return wt` ${wt.ref(e)}.${wt.ref(t)}`.as(`_cy_${r}:${t}`)}function kg(e,...t){const r={};for(const[s,a]of Object.entries(e)){const o=s.match(/^_cy_(.+?):(.+)$/);if(o){const[,i,l]=o;if(t.includes(i)){r[i]||(r[i]={}),r[i][l]=a;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${s}'`);continue}r[s]=a}return r}const jg=50;function _g(e,t){return e.length<=t?[e]:Array.from({length:Math.ceil(e.length/t)},(r,s)=>e.slice(s*t,s*t+t))}function Hl({projectId:e,ids:t,fileIds:r,entityName:s,entityShas:a,commitIds:o,branchCommitSha:i,limit:l,excludeMetadata:d}){const u=$e(),{jsonObjectFrom:p,jsonArrayFrom:h}=zn();let m=d?u.selectFrom("analyses").select(["analyses.id","analyses.project_id","analyses.file_id","analyses.commit_id","analyses.entity_sha","analyses.entity_name","analyses.entity_type","analyses.file_path","analyses.status","analyses.created_at","analyses.updated_at","analyses.tree_sha","analyses.analyzed_tree_sha","analyses.dependency_analyzed_tree_sha","analyses.previous_analysis_id","analyses.branch_commit_sha","analyses.indirect","analyses.committed_at","analyses.completed_at"]):u.selectFrom("analyses").selectAll("analyses");if(e&&(m=m.where("project_id","=",e)),t){if(t.length===0)return null;m=m.where("id","in",t)}if(r){if(r.length===0)return null;m=m.where("file_id","in",r)}if(o){if(o.length===0)return null;m=m.where("commit_id","in",o)}return s&&(m=m.where("entity_name","=",s)),a&&(m=m.where("entity_sha","in",a)),i&&(m=m.where("branch_commit_sha","=",i)),l&&(m=m.limit(l)),d?u.with("filtered_analyses",()=>m).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[h(f.selectFrom("scenarios").select(io("scenarios",Xs)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):u.with("filtered_analyses",()=>m).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[p(f.selectFrom("entities").select(io("entities",Qd)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),h(f.selectFrom("scenarios").select(io("scenarios",Xs)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),h(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function yn(e){const{ids:t,fileIds:r,entityShas:s,commitIds:a}=e;try{const i=Object.entries({id:{arr:t,key:"ids"},file_id:{arr:r,key:"fileIds"},entity_sha:{arr:s,key:"entityShas"},commit_id:{arr:a,key:"commitIds"}}).find(([d,{arr:u}])=>(u==null?void 0:u.length)>0);let l=[];if(i){const[d,{arr:u,key:p}]=i,h=_g(u,jg),m=[];for(let f=0;f<h.length;f++){const y=h[f],x=await Hl({...e,[p]:y}).execute();x&&m.push(...x)}l=m}else{const u=await Hl(e).execute();if(!u||u.length===0)return Oe("CodeYam: No analyses found",null,e),null;l=u}return l.length===0?null:l.map(en)}catch(o){return Oe("CodeYam Error: Database error in loadAnalyses",o,e),null}}function Eg(e,t){const{jsonArrayFrom:r,jsonObjectFrom:s}=zn();let a=e.selectFrom("analysis_branches").select(_f).select(o=>s(o.selectFrom("branches").select(Gd).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(a=t(a)),r(a)}async function tn({id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:u,includeCommitAndBranch:p,includeScenarios:h,includeBranches:m}){const f=$e(),y=Date.now();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),r&&(g=g.where("project_id","=",r)),i?g=g.where("dependency_analyzed_tree_sha","=",i):l?g=g.where("analyzed_tree_sha","=",l):s&&(g=g.where("file_id","=",s)),o&&(g=g.where("entity_name","=",o)),a?g=g.where("commit_id","=",a):g=g.orderBy("created_at","desc").limit(1),t&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:x,jsonArrayFrom:b}=zn();g=g.select(w=>{const C=[];return C.push(x(w.selectFrom("entities").select(Qd).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&C.push(x(w.selectFrom("files").select(Jf).whereRef("files.id","=","analyses.file_id")).as("file")),u&&C.push(x(w.selectFrom("projects").select(Sf).whereRef("projects.id","=","analyses.project_id")).as("project")),h&&C.push(b(w.selectFrom("scenarios").select(Xs).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),m&&C.push(Eg(w,k=>k.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),p&&C.push(x(w.selectFrom("commits").select(qd).select(k=>bg(k).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),C});const v=await g.executeTakeFirst(),N=Date.now()-y;if(!v)return Oe(!!i?`CodeYam: Analysis cache miss for dependency tree SHA ${i.substring(0,12)}...`:`CodeYam Error: Analysis not found${o?` for ${o}`:""}${e?` (id=${e})`:""}`,null,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:u,includeCommitAndBranch:p,includeScenarios:h,includeBranches:m}),null;if(N>100&&p){const w=v.commit,C=w!=null&&w.files?JSON.stringify(w.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${N}ms (files: ${Math.round(C/1024)}KB)`,{id:v.id,entityName:v.entity_name})}return en(v)}catch(g){return Oe("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:d,includeProject:u,includeCommitAndBranch:p,includeScenarios:h,includeBranches:m}),null}}async function fi({projectId:e,ids:t,names:r,includeInactive:s}){const a=$e();try{let o=a.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(t){if(t.length===0)return[];o=o.where("id","in",t)}if(r){if(r.length===0)return[];o=o.where("name","in",r)}return s||(o=o.where("active_at","is not",null)),(await o.execute()).map(In)}catch(o){return Oe("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:s}),[]}}async function Pg({projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}){const o=$e();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(a,u=>u.select(Sg("branches",Gd,"branch"))).where("branches.project_id","=",e);t&&(i=i.where("commit_branches.commit_id","=",t)),r&&(i=i.where("commit_branches.branch_id","=",r)),s!==void 0&&(i=i.where("commit_branches.active","=",s));const l=await i.execute();return!l||l.length===0?null:l.map(u=>kg(u,"branch")).map(mi)}catch(i){return Oe("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}),null}}async function Ag(e){if(e.length===0)return new Map;const t=$e();try{const r=await t.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),s=new Set;if(r.forEach(o=>{o.branch_id&&s.add(o.branch_id),o.merged_branch_id&&s.add(o.merged_branch_id)}),s.size===0)return new Map;const a=await t.selectFrom("branches").selectAll().where("id","in",Array.from(s)).execute();return new Map(a.map(o=>[o.id,o]))}catch(r){return Oe("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function Tg(e){if(e.length===0)return new Map;const t=$e(),{jsonObjectFrom:r,jsonArrayFrom:s}=zn();try{const a=await t.selectFrom("analyses").selectAll("analyses").select(i=>[r(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),s(i.selectFrom("scenarios").select(Xs).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),o=new Map;return a.forEach(i=>{const l=o.get(i.commit_id)||[];l.push(i),o.set(i.commit_id,l)}),o}catch(a){return Oe("CodeYam Error: Loading analyses for commits",a,{commitIds:e}),new Map}}async function Mg(e){if(e.length===0)return new Map;const t=$e();try{const r=await t.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),s=new Map;return r.forEach(a=>{const o=s.get(a.commit_id)||[];o.push(a),s.set(a.commit_id,o)}),s}catch(r){return Oe("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function ta({projectId:e,branchId:t,ids:r,shas:s,fileNames:a,limit:o=10,skipRelations:i=!1}){if(!e&&!r)throw new Error("Must provide projectId or ids");const l=$e(),{jsonObjectFrom:d}=zn(),u=Date.now();try{let p;if(i){const v=Ff.map(N=>`commits.${N}`);p=l.selectFrom("commits").select(v)}else p=l.selectFrom("commits").selectAll("commits").select(v=>[d(v.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",v.ref("commits.author_github_username"))).as("author")]);if(e&&(p=p.where("project_id","=",e)),r){if(r.length===0)return[];p=p.where("id","in",r)}if(s){if(s.length===0)return[];p=p.where("sha","in",s)}if(a&&a.length>0){const v=wt.join(a.map(N=>wt`${N}`),wt`, `);p=p.where(wt`
24
+ EXISTS (
25
+ SELECT 1
26
+ FROM json_each(${wt.ref("commits.files")}) AS f
27
+ WHERE json_extract(f.value, '$.fileName') IN (${v})
28
+ )
29
+ `)}t&&(p=p.where("branch_id","=",t));const h=await p.orderBy("committed_at","desc").limit(o).execute(),m=Date.now()-u;if(!h||h.length===0)return[];if(m>100){const v=h.reduce((N,w)=>N+(w.files?JSON.stringify(w.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${m}ms (${h.length} commits, totalFiles: ${Math.round(v/1024)}KB)`)}if(i)return h.map(N=>({...N,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(Rn);const f=h.map(v=>v.id),[y,g,x]=await Promise.all([Ag(f),Tg(f),Mg(f)]);return h.map(v=>{const N=v.branch_id?y.get(v.branch_id):void 0,w=v.merged_branch_id?y.get(v.merged_branch_id):void 0,C=g.get(v.id)||[],k=x.get(v.id)||[];return{...v,branch:N,mergedBranch:w,analyses:C,entities:k}}).map(Rn)}catch(p){return Oe("CodeYam Error: Database error loading commits",p,{projectId:e,branchId:t,ids:r,shas:s,limit:o}),[]}}async function et({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:o,excludeMetadata:i}){if(r&&r.length==0||s&&s.length==0||a&&a.length==0||o&&o.length==0)return[];if(o&&o.length>50){const d=[];for(let u=0;u<o.length;u+=50){const p=o.slice(u,u+50),h=await et({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:p,excludeMetadata:i});h&&d.push(...h)}return d}const l=$e();try{const p=await(i?l.selectFrom("entities").select(["entities.project_id","entities.file_id","entities.commit_id","entities.name","entities.sha","entities.entity_type","entities.file_path","entities.description","entities.documentation","entities.quality","entities.created_at","entities.updated_at"]):l.selectFrom("entities").selectAll("entities")).$if(!!t,h=>h.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,h=>h.where("entities.project_id","=",e)).$if(!!o,h=>h.where("entities.sha","in",o)).$if(!!s,h=>h.where("entities.file_path","in",s)).$if(!!a,h=>h.where("entities.name","in",a)).$if(!!r,h=>h.where("entities.file_id","in",r)).execute();return!p||p.length===0?null:p.map(es)}catch(d){return console.log("Load Entities: Error occurred",d,{projectId:e,fileIds:r,filePaths:s,shas:o}),null}}function $g(e,t){const{jsonArrayFrom:r}=zn();let s=e.selectFrom("entity_branches").select(zf);return t&&(s=t(s)),r(s)}async function eu({projectId:e,sha:t,silent:r}){const s=$e();try{const a=await s.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(o=>$g(o,i=>i.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return a?es(a):(!r&&process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&Oe(`CodeYam Error: Load Entity: Entity not found (sha=${t==null?void 0:t.substring(0,12)})`,null,{projectId:e,sha:t}),null)}catch(a){return Oe("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:t}),null}}const lo=1e3;async function tu({projectId:e,filePaths:t,fileIds:r,fileNames:s}){if(t&&t.length>50){const l=[];for(let d=0;d<t.length;d+=50){const u=t.slice(d,d+50),p=await tu({projectId:e,filePaths:u,fileIds:r,fileNames:s});p&&l.push(...p)}return l}const a=$e(),o=[];let i=0;try{for(;;){let l=a.selectFrom("files").selectAll().where("project_id","=",e).limit(lo).offset(i);if(t){if(t.length===0)return[];l=l.where("path","in",t)}if(r){if(r.length===0)return[];l=l.where("id","in",r)}if(s){if(s.length===0)return[];l=l.where("name","in",s)}const d=await l.execute();if(!d||d.length===0||(o.push(...d),d.length<lo))break;i+=lo}return o==null?void 0:o.map(hi)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function gi({id:e,slug:t,withBranches:r,withFiles:s,silent:a}){try{let i=$e().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(t)i=i.where("slug","=",t);else throw new Error("Either id or slug must be provided");const l=await i.executeTakeFirst();if(!l)return null;const d=ga(l);return s&&(d.files=await tu({projectId:d.id})),r&&(d.branches=await fi({projectId:d.id,includeInactive:!1})),d}catch{return null}}function na(e,t){const r={...e};for(const s in t){const a=t[s],o=e[s];a!=null&&typeof a=="object"&&!Array.isArray(a)&&o!==void 0&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[s]=na(o,a):a!==void 0&&(r[s]=a)}return r}async function hn({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:s,archiveCurrentRun:a,updateCallback:o}){for(let d=0;d<=4;d++)try{return await $e().transaction().execute(async u=>{const p=await u.selectFrom("commits").select(["id","metadata"]).$if(!!e,f=>f.where("id","=",e)).$if(!!t,f=>f.where("sha","=",t)).executeTakeFirst();if(!p)return Oe(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const h=p.metadata||{};if(s)s.lastUpdatedAt??(s.lastUpdatedAt=new Date().toISOString()),r=na(r??{},{currentRun:s});else if(!r&&!o)return h;const m=r?na(h,r):h;if(a&&m.currentRun){const f={...m.currentRun,archivedAt:new Date().toISOString()};m.historicalRuns=[...m.historicalRuns||[],f]}o&&await o(m);try{return await u.updateTable("commits").set({metadata:JSON.stringify(m)}).where("id","=",p.id).returning(["id"]).executeTakeFirst()?m:(Oe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),h)}catch(f){return Oe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,f),h}})}catch(u){const p=u instanceof Error&&u.message.includes("database is locked");if(p&&d<4){const h=250*Math.pow(2,d);await new Promise(m=>setTimeout(m,h));continue}return Oe(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}${p?` after ${d+1} attempts`:""}`,u),null}return null}async function nu(e,t,r="analysis"){try{return await $e().transaction().execute(async s=>{const a=await s.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!a)return Oe(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=en(a);return t(o.metadata,o),await s.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(Oe(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(s){return Oe(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,s,{analysisId:e,source:r}),null}}async function mr(e,t,r="capture"){for(let o=0;o<=4;o++)try{return await $e().transaction().execute(async i=>{const l=await i.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!l)return Oe(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const d=en(l);return t(d.status,d),await i.updateTable("analyses").set({status:JSON.stringify(d.status)}).where("id","=",e).returningAll().executeTakeFirst()?d.status:(Oe(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(i){const l=i instanceof Error&&i.message.includes("database is locked");if(l&&o<4){const d=250*Math.pow(2,o);await new Promise(u=>setTimeout(u,d));continue}return Oe(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${r})${l?` after ${o+1} attempts`:""}`,i,{analysisId:e,source:r}),null}return null}async function ir({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:s}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await $e().transaction().execute(async a=>{const o=await a.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!t,d=>d.where("slug","=",t)).executeTakeFirst();if(!o)return Oe(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!s)return i;const l=r?na(i,r):i;s&&await s(l,ga(o));try{return await a.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",o.id).returningAll().executeTakeFirst()?l:(Oe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return Oe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(a){return Oe(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,a),null}}const Fg=()=>crypto.randomUUID();function Dg(e){const{id:t,projectId:r,analysisId:s,previousVersionId:a,analysis:o,metadata:i,data:l,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:t??Fg(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:s,previous_version_id:a}}async function Rg(e){if(e.length===0)return[];const t=$e(),r=e.map(Dg);try{return(await t.insertInto("scenarios").values(r).onConflict(hr(r[0],"id",["created_at"])).returningAll().execute()).map(Kd)}catch(s){return Oe("CodeYam Error: Database error upserting scenarios",s,{scenarioCount:e.length}),null}}const Ig=()=>crypto.randomUUID();function Og(e){const{id:t,commitId:r,branchId:s,...a}=e;return delete a.commit,delete a.branch,{...a,id:t??Ig(),commit_id:r,branch_id:s}}async function Vl(e){if(e.length===0)return[];const t=$e(),r=e.map(Og);try{return(await t.insertInto("commit_branches").values(r).onConflict(hr(r[0],"id",["created_at"])).returningAll().execute()).map(mi)}catch(s){return Oe("CodeYam Error: Database error upserting commit branches",s,{commitBranchCount:e.length,commitBranchIds:e.map(a=>a.id)}),[]}}async function Lg(e,t){const r=$e(),s={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(s).onConflict(hr(s,"username",[])).returningAll().executeTakeFirst()||null}catch(a){return Oe("CodeYam Error: Error upserting github user",a,{username:e,avatarUrl:t}),null}}const Bg=()=>crypto.randomUUID();function zg(e,t){const{id:r,projectId:s,branchId:a,mergedBranchId:o,aiMessage:i,htmlUrl:l,analyzedAt:d,committedAt:u,author:p,metadata:h,files:m,...f}=e;return delete f.branch,delete f.mergedBranch,delete f.backgroundJob,delete f.analyses,delete f.parents,delete f.entities,delete f.commitBranches,{...f,id:r??Bg(),project_id:s??String(t),metadata:h?JSON.stringify(h):void 0,files:m?JSON.stringify(m):void 0,branch_id:a,merged_branch_id:o,author_github_username:p==null?void 0:p.username,html_url:l,ai_message:i,analyzed_at:d,committed_at:u}}async function Yg({projectId:e,commits:t}){const r=$e();try{const s=t.reduce((i,l)=>{const{author:d}=l;return d!=null&&d.username&&(d!=null&&d.avatarUrl)&&(i[d.username]=d.avatarUrl),i},{});for(const i in s)await Lg(i,s[i]);const a=t.map(i=>zg(i,e));return(await r.insertInto("commits").values(a).onConflict(hr(a[0],"id",["created_at"])).returningAll().execute()).map(Rn)}catch(s){return Oe("CodeYam Error: Error saving commits",s,{projectId:e,commitCount:t.length,commitIds:t.map(a=>a.id).filter(Boolean)}),[]}}const Ug=()=>crypto.randomUUID();function Wg(e){const{id:t,files:r,branches:s,team:a,analyzedAt:o,contentChangedAt:i,createdAt:l,updatedAt:d,metadata:u,...p}=e;return{...p,id:t??Ug(),analyzed_at:o||null,content_changed_at:i||null,created_at:l||new Date().toISOString(),updated_at:d||null,metadata:u?JSON.stringify(u):null,github_token:null,configuration:null,team_id:null}}async function Jg(e){try{if(e.length===0)return null;const t=$e(),r=e.map(o=>Wg(o)),s=await t.insertInto("projects").values(r).onConflict(hr(r[0],"id",["created_at"])).returningAll().execute(),a=s==null?void 0:s[0];return a?ga(a):null}catch(t){return console.log("Error saving project",t),null}}const ra=G.join(pa.homedir(),".codeyam","secrets.json"),sa=G.join(process.cwd(),".codeyam","secrets.json");async function bn(){let e={};try{if(Q.existsSync(sa)){const o=await Ae.readFile(sa,"utf8");e=JSON.parse(o)}}catch{console.warn(Zs.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(Q.existsSync(ra)){const o=await Ae.readFile(ra,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(Zs.yellow("⚠ Could not read home secrets file, falling back to environment variables"))}const t={},r=e.OPENAI_API_KEY||process.env.OPENAI_API_KEY;r&&(t.OPENAI_API_KEY=r);const s=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;s&&(t.ANTHROPIC_API_KEY=s);const a=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return a&&(t.GROQ_API_KEY=a),t}async function Hg(e,t=!0){const r=t?ra:sa,s=G.dirname(r);await Ae.mkdir(s,{recursive:!0}),await Ae.writeFile(r,JSON.stringify(e,null,2)),await Ae.chmod(r,384)}function Vg(e=!0){return e?ra:sa}async function Kl(){const e=await bn(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function Kg(e){console.log(),console.log(Zs.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const s=await Rm({type:"password",name:"key",message:"OpenAI API Key",validate:a=>a&&!a.startsWith("sk-")?"OpenAI API key should start with sk-":!0});s.key&&(t.OPENAI_API_KEY=s.key);break}return t}async function Gg(e=!0){const t=await Kl();if(t.isValid)return t.secrets;const r=await Kg(t.missing),a={...await bn(),...r};await Hg(a,e);const o=Vg(e);return console.log(Zs.green(`✓ Configuration saved to ${o}`)),(await Kl()).secrets}function qg(e){const t=G.resolve(e),r=G.parse(t).root;return t===r||t===G.resolve(pa.homedir())}function ru(e=process.cwd()){let t=G.resolve(e);const r=G.parse(t).root;for(;t!==r;){if(qg(t))return null;const s=G.join(t,".codeyam","config.json");if(Q.existsSync(s))return t;t=G.dirname(t)}return null}let su=ru();function Ce(){return su}function Qg(e){su=e}function au(e){const t={...e};for(const r in e)if(r.includes(".")){const s=r.replace(/\./g,"");t[s]=e[r]}return t}const Zg={"Accordion.Item":e=>`<CYAccordion.Root type="single" collapsible>${e}</CYAccordion.Root>`,"Accordion.Header":e=>`<CYAccordion.Root type="single" collapsible><CYAccordion.Item value="item-1">${e}</CYAccordion.Item></CYAccordion.Root>`,"Accordion.Trigger":e=>`<CYAccordion.Root type="single" collapsible><CYAccordion.Item value="item-1"><CYAccordion.Header>${e}</CYAccordion.Header></CYAccordion.Item></CYAccordion.Root>`,"Accordion.Content":e=>`<CYAccordion.Root type="single" collapsible><CYAccordion.Item value="item-1">${e}</CYAccordion.Item></CYAccordion.Root>`,"AlertDialog.Trigger":e=>`<CYAlertDialog.Root>${e}</CYAlertDialog.Root>`,"AlertDialog.Portal":e=>`<CYAlertDialog.Root>${e}</CYAlertDialog.Root>`,"AlertDialog.Overlay":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal>${e}</CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Content":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal>${e}</CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Title":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Description":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Action":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"AlertDialog.Cancel":e=>`<CYAlertDialog.Root><CYAlertDialog.Portal><CYAlertDialog.Content>${e}</CYAlertDialog.Content></CYAlertDialog.Portal></CYAlertDialog.Root>`,"Avatar.Image":e=>`<CYAvatar.Root>${e}</CYAvatar.Root>`,"Avatar.Fallback":e=>`<CYAvatar.Root>${e}</CYAvatar.Root>`,"Checkbox.Indicator":e=>`<CYCheckbox.Root>${e}</CYCheckbox.Root>`,"Collapsible.Trigger":e=>`<CYCollapsible.Root>${e}</CYCollapsible.Root>`,"Collapsible.Content":e=>`<CYCollapsible.Root>${e}</CYCollapsible.Root>`,"ContextMenu.Trigger":e=>`<CYContextMenu.Root>${e}</CYContextMenu.Root>`,"ContextMenu.Portal":e=>`<CYContextMenu.Root>${e}</CYContextMenu.Root>`,"ContextMenu.Content":e=>`<CYContextMenu.Root><CYContextMenu.Portal>${e}</CYContextMenu.Portal></CYContextMenu.Root>`,"ContextMenu.Item":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.CheckboxItem":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.RadioGroup":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.RadioItem":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.RadioGroup value="item-1">${e}</CYContextMenu.RadioGroup></CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.ItemIndicator":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.CheckboxItem checked>${e}</CYContextMenu.CheckboxItem></CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.Label":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.Separator":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.Sub":e=>`<CYContextMenu.Root><CYContextMenu.Content>${e}</CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.SubTrigger":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.Sub>${e}</CYContextMenu.Sub></CYContextMenu.Content></CYContextMenu.Root>`,"ContextMenu.SubContent":e=>`<CYContextMenu.Root><CYContextMenu.Content><CYContextMenu.Sub>${e}</CYContextMenu.Sub></CYContextMenu.Content></CYContextMenu.Root>`,"Dialog.Trigger":e=>`<CYDialog.Root>${e}</CYDialog.Root>`,"Dialog.Portal":e=>`<CYDialog.Root>${e}</CYDialog.Root>`,"Dialog.Overlay":e=>`<CYDialog.Root><CYDialog.Portal>${e}</CYDialog.Portal></CYDialog.Root>`,"Dialog.Content":e=>`<CYDialog.Root><CYDialog.Portal>${e}</CYDialog.Portal></CYDialog.Root>`,"Dialog.Title":e=>`<CYDialog.Root><CYDialog.Portal><CYDialog.Content>${e}</CYDialog.Content></CYDialog.Portal></CYDialog.Root>`,"Dialog.Description":e=>`<CYDialog.Root><CYDialog.Portal><CYDialog.Content>${e}</CYDialog.Content></CYDialog.Portal></CYDialog.Root>`,"Dialog.Close":e=>`<CYDialog.Root><CYDialog.Portal><CYDialog.Content>${e}</CYDialog.Content></CYDialog.Portal></CYDialog.Root>`,"DropdownMenu.Trigger":e=>`<CYDropdownMenu.Root>${e}</CYDropdownMenu.Root>`,"DropdownMenu.Portal":e=>`<CYDropdownMenu.Root>${e}</CYDropdownMenu.Root>`,"DropdownMenu.Content":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Portal>${e}</CYDropdownMenu.Portal></CYDropdownMenu.Root>`,"DropdownMenu.Item":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.CheckboxItem":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.RadioGroup":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.RadioItem":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.RadioGroup value="item-1">${e}</CYDropdownMenu.RadioGroup></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.ItemIndicator":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.CheckboxItem checked>${e}</CYDropdownMenu.CheckboxItem></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.Label":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.Separator":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.Sub":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content>${e}</CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.SubTrigger":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.Sub>${e}</CYDropdownMenu.Sub></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"DropdownMenu.SubContent":e=>`<CYDropdownMenu.Root><CYDropdownMenu.Content><CYDropdownMenu.Sub>${e}</CYDropdownMenu.Sub></CYDropdownMenu.Content></CYDropdownMenu.Root>`,"Form.Field":e=>`<CYForm.Root>${e}</CYForm.Root>`,"Form.Label":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.Control":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.Message":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.ValidityState":e=>`<CYForm.Root><CYForm.Field name="test-field">${e}</CYForm.Field></CYForm.Root>`,"Form.Submit":e=>`<CYForm.Root>${e}</CYForm.Root>`,"HoverCard.Trigger":e=>`<CYHoverCard.Root>${e}</CYHoverCard.Root>`,"HoverCard.Portal":e=>`<CYHoverCard.Root>${e}</CYHoverCard.Root>`,"HoverCard.Content":e=>`<CYHoverCard.Root><CYHoverCard.Portal>${e}</CYHoverCard.Portal></CYHoverCard.Root>`,"Menubar.Menu":e=>`<CYMenubar.Root>${e}</CYMenubar.Root>`,"Menubar.Trigger":e=>`<CYMenubar.Root><CYMenubar.Menu>${e}</CYMenubar.Menu></CYMenubar.Root>`,"Menubar.Portal":e=>`<CYMenubar.Root><CYMenubar.Menu>${e}</CYMenubar.Menu></CYMenubar.Root>`,"Menubar.Content":e=>`<CYMenubar.Root><CYMenubar.Menu>${e}</CYMenubar.Menu></CYMenubar.Root>`,"Menubar.Item":e=>`<CYMenubar.Root><CYMenubar.Menu><CYMenubar.Content>${e}</CYMenubar.Content></CYMenubar.Menu></CYMenubar.Root>`,"NavigationMenu.List":e=>`<CYNavigationMenu.Root>${e}</CYNavigationMenu.Root>`,"NavigationMenu.Item":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List>${e}</CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Trigger":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item>${e}</CYNavigationMenu.Item></CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Content":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item><CYNavigationMenu.Trigger />{/* Dummy trigger for context */}${e}</CYNavigationMenu.Item></CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Link":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item>${e}</CYNavigationMenu.Item></CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Indicator":e=>`<CYNavigationMenu.Root><CYNavigationMenu.List><CYNavigationMenu.Item><CYNavigationMenu.Trigger />{/* Dummy trigger for context */}</CYNavigationMenu.Item>${e}</CYNavigationMenu.List></CYNavigationMenu.Root>`,"NavigationMenu.Viewport":e=>`<CYNavigationMenu.Root>${e}</CYNavigationMenu.Root>`,"Popover.Trigger":e=>`<CYPopover.Root>${e}</CYPopover.Root>`,"Popover.Portal":e=>`<CYPopover.Root>${e}</CYPopover.Root>`,"Popover.Content":e=>`<CYPopover.Root><CYPopover.Portal>${e}</CYPopover.Portal></CYPopover.Root>`,"Popover.Close":e=>`<CYPopover.Root><CYPopover.Content>${e}</CYPopover.Content></CYPopover.Root>`,"Popover.Anchor":e=>`<CYPopover.Root>${e}</CYPopover.Root>`,"Progress.Indicator":e=>`<CYProgress.Root value={50}>${e}</CYProgress.Root>`,"RadioGroup.Item":e=>`<CYRadioGroup.Root>${e}</CYRadioGroup.Root>`,"RadioGroup.Indicator":e=>`<CYRadioGroup.Root><CYRadioGroup.Item value="item-1">${e}</CYRadioGroup.Item></CYRadioGroup.Root>`,"ScrollArea.Viewport":e=>`<CYScrollArea.Root>${e}</CYScrollArea.Root>`,"ScrollArea.Scrollbar":e=>`<CYScrollArea.Root>${e}</CYScrollArea.Root>`,"ScrollArea.Thumb":e=>`<CYScrollArea.Root><CYScrollArea.Scrollbar orientation="vertical">${e}</CYScrollArea.Scrollbar></CYScrollArea.Root>`,"ScrollArea.Corner":e=>`<CYScrollArea.Root>${e}</CYScrollArea.Root>`,"Select.Trigger":e=>`<CYSelect.Root>${e}</CYSelect.Root>`,"Select.Value":e=>`<CYSelect.Root><CYSelect.Trigger>${e}</CYSelect.Trigger></CYSelect.Root>`,"Select.Icon":e=>`<CYSelect.Root><CYSelect.Trigger>${e}</CYSelect.Trigger></CYSelect.Root>`,"Select.Portal":e=>`<CYSelect.Root>${e}</CYSelect.Root>`,"Select.Content":e=>`<CYSelect.Root><CYSelect.Portal>${e}</CYSelect.Portal></CYSelect.Root>`,"Select.Viewport":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Select.Item":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Select.ItemText":e=>`<CYSelect.Root><CYSelect.Content><CYSelect.Item value="item-1">${e}</CYSelect.Item></CYSelect.Content></CYSelect.Root>`,"Select.ItemIndicator":e=>`<CYSelect.Root><CYSelect.Content><CYSelect.Item value="item-1">${e}</CYSelect.Item></CYSelect.Content></CYSelect.Root>`,"Select.Group":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Select.Label":e=>`<CYSelect.Root><CYSelect.Content><CYSelect.Group>${e}</CYSelect.Group></CYSelect.Content></CYSelect.Root>`,"Select.Separator":e=>`<CYSelect.Root><CYSelect.Content>${e}</CYSelect.Content></CYSelect.Root>`,"Slider.Track":e=>`<CYSlider.Root>${e}</CYSlider.Root>`,"Slider.Range":e=>`<CYSlider.Root><CYSlider.Track>${e}</CYSlider.Track></CYSlider.Root>`,"Slider.Thumb":e=>`<CYSlider.Root>${e}</CYSlider.Root>`,"Switch.Thumb":e=>`<CYSwitch.Root>${e}</CYSwitch.Root>`,"Tabs.List":e=>`<CYTabs.Root defaultValue="tab1">${e}</CYTabs.Root>`,"Tabs.Trigger":e=>`<CYTabs.Root defaultValue="tab1"><CYTabs.List>${e}</CYTabs.List></CYTabs.Root>`,"Tabs.Content":e=>`<CYTabs.Root defaultValue="tab1">${e}</CYTabs.Root>`,"Toast.Root":e=>`<CYToast.Provider>${e}</CYToast.Provider>`,"Toast.Title":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Description":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Action":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Close":e=>`<CYToast.Provider><CYToast.Root>${e}</CYToast.Root></CYToast.Provider>`,"Toast.Viewport":e=>`<CYToast.Provider>${e}</CYToast.Provider>`,"ToggleGroup.Item":e=>`<CYToggleGroup.Root type="single">${e}</CYToggleGroup.Root>`,"Toolbar.Button":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.Link":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.Separator":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.ToggleGroup":e=>`<CYToolbar.Root>${e}</CYToolbar.Root>`,"Toolbar.ToggleItem":e=>`<CYToolbar.Root><CYToolbar.ToggleGroup type="single">${e}</CYToolbar.ToggleGroup></CYToolbar.Root>`,"Tooltip.Root":e=>`<CYTooltip.Provider>${e}</CYTooltip.Provider>`,"Tooltip.Trigger":e=>`<CYTooltip.Provider><CYTooltip.Root>${e}</CYTooltip.Root></CYTooltip.Provider>`,"Tooltip.Portal":e=>`<CYTooltip.Provider><CYTooltip.Root>${e}</CYTooltip.Root></CYTooltip.Provider>`,"Tooltip.Content":e=>`<CYTooltip.Provider><CYTooltip.Root><CYTooltip.Portal>${e}</CYTooltip.Portal></CYTooltip.Root></CYTooltip.Provider>`,"Tooltip.Arrow":e=>`<CYTooltip.Provider><CYTooltip.Root><CYTooltip.Content>${e}</CYTooltip.Content></CYTooltip.Root></CYTooltip.Provider>`};au(Zg);const Xg={"Command.Input":e=>`<CYCommand>${e}</CYCommand>`,"Command.List":e=>`<CYCommand>${e}</CYCommand>`,"Command.Item":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Group":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Separator":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Empty":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Loading":e=>`<CYCommand><CYCommand.List>${e}</CYCommand.List></CYCommand>`,"Command.Shortcut":e=>`<CYCommand><CYCommand.List><CYCommand.Item value="x">${e}</CYCommand.Item></CYCommand.List></CYCommand>`,"Command.Dialog":e=>`<CYCommand.Dialog open>${e}</CYCommand.Dialog>`};au(Xg);function Lr(e,t,r=new WeakSet){if(!t)return e;if(!e)return t;try{if(typeof t=="object"&&t!==null){if(r.has(t))throw new Error("Circular reference detected during deep merge");r.add(t)}if(Array.isArray(t)){const a=Array.isArray(e)?e:[],o=[];for(let i=0;i<t.length;i++){const l=t[i];l&&typeof l=="object"&&!Array.isArray(l)||Array.isArray(l)?o[i]=Lr(a[i],l,r):o[i]=l}return o}const s={...e};for(const a in t)if(t[a]===null)s[a]=null;else if(Array.isArray(t[a])){const o=Array.isArray(e[a])?e[a]:[];s[a]=[];for(let i=0;i<t[a].length;i++){const l=t[a][i];typeof l=="object"&&l!==null?s[a][i]=Lr(o[i],l,r):s[a][i]=l}}else typeof t[a]=="object"&&t[a]!==null?s[a]=Lr(s[a]??{},t[a],r):s[a]=t[a];return s}catch(s){throw console.log("CodeYam: Error merging data",e,t),s}}async function e0({projectId:e,commit:t,branch:r}){var l,d,u,p,h,m,f;let s;const a={commitId:t.id,branchId:r.id,active:!0},o=await Pg({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){s=(l=o.sort((g,x)=>{var b,v,N,w;return(((v=(b=g.branch.metadata)==null?void 0:b.permanent)==null?void 0:v.order)??999)-(((w=(N=x.branch.metadata)==null?void 0:N.permanent)==null?void 0:w.order)??999)})[0])==null?void 0:l.branch,s&&((u=(d=r.metadata)==null?void 0:d.permanent)==null?void 0:u.order)!==void 0&&(((h=(p=r.metadata)==null?void 0:p.permanent)==null?void 0:h.order)<=((f=(m=s.metadata)==null?void 0:m.permanent)==null?void 0:f.order)?s=r:a.active=!1);const y=o.filter(g=>g.active&&g.branch.id!==s.id||!g.active&&g.branch.id===s.id);y.length>0&&await Vl(y.map(g=>({...g,active:g.branchId===s.id})))}(o==null?void 0:o.find(y=>y.branchId===a.branchId))||await Vl([a])}let Gl=!1;function vn(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=Ce();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return ee.join(e,".codeyam","db.sqlite3")}async function We(){if(!Gl){Gl=!0;const t=Ce();t&&await n0(t)}const e=await Gg();process.env.SQLITE_PATH=vn(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Yj(){try{return await We(),await gi({slug:"__test_connection__",silent:!0}),!0}catch(e){return console.error("Database connection test failed:",e),!1}}async function Ie(e){await We();const t=await gi({slug:e,silent:!0});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await fi({projectId:t.id,names:["_local"]}),s=r==null?void 0:r[0];if(!s)throw new Error(`Local development branch not found for project "${e}". Please run "codeyam init" to set up local analysis.`);return{project:t,branch:s}}async function Uj(e){await We();const t=await gi({slug:e.slug,silent:!0});if(t)return{project:t,created:!1};const r={id:ai(),name:e.slug,slug:e.slug,path:`local:${process.cwd()}`,metadata:{packageManager:e.packageManager,unapprovedPaths:e.unapprovedPaths,webapps:e.webapps}};try{return{project:await Jg([r]),created:!0}}catch(s){throw new Error(`Failed to create project: ${s.message}`)}}async function Wj(e){await We();const t=await fi({projectId:e.id,names:["_local"]});if(t&&t.length>0)return{branch:t[0],created:!1};const r={projectId:e.id,name:"_local",ref:"_local",primary:!0,activeAt:new Date().toISOString(),contentChangedAt:new Date().toISOString(),metadata:{contributors:[{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"}],commits:{total:0,last7Days:[]},timeline:[{title:"Local branch created",date:new Date().toISOString(),authors:[{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"}],sha:"local-init"}]}},s=await xg([r]);if(!s||s.length===0)throw new Error("Failed to create _local branch");return{branch:s[0],created:!0}}async function t0(e,t,r){await We();const s=Ce(),a=wg(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(d=>{let u="";if(s)try{if(u=Me(`git diff HEAD -- "${d}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!u)try{const p=Me(`cat "${d}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(p){const h=p.split(`
30
+ `);u=`@@ -0,0 +1,${h.length} @@
31
+ ${h.map(m=>`+${m}`).join(`
32
+ `)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:u}}),i={sha:a,projectId:e.id,branchId:t.id,message:`Local analysis: ${r.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${a}`,htmlUrl:`local://codeyam/${e.slug}/${a}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:o,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},l=await Yg({projectId:e.id,commits:[i]});if(!l||l.length===0)throw new Error("Failed to create fake commit");return await e0({projectId:e.id,commit:l[0],branch:t}),l[0]}async function n0(e){const t=ee.join(e,".codeyam","db.sqlite3"),r=ee.join(e,".codeyam","config.json");if(Q.existsSync(t)||!Q.existsSync(r))return!1;const{default:s}=await import("./init-JObA4lXD.js");return await s.handler({force:!0,autoInit:!0,$0:"",_:[]}),!0}async function Yn(){await We();const e=await et({excludeMetadata:!0});if(!e||e.length===0)return[];const t=new Map;for(const d of e){const u=`${d.name}::${d.filePath}`,p=t.get(u);(!p||d.createdAt&&p.createdAt&&d.createdAt>p.createdAt)&&t.set(u,d)}const r=[...t.values()],s=e.map(d=>d.sha),a=await yn({entityShas:s,excludeMetadata:!0}),o=new Map;if(a)for(const d of a)o.has(d.entitySha)||o.set(d.entitySha,[]),o.get(d.entitySha).push(d);const i=new Map;for(const d of e){const u=`${d.name}::${d.filePath}`,p=i.get(u)||[];p.push(d.sha),i.set(u,p)}return r.map(d=>{const u=o.get(d.sha)||[];if(u.length>0)return{...d,analyses:u};const p=`${d.name}::${d.filePath}`,h=i.get(p)||[];for(const m of h){if(m===d.sha)continue;const f=o.get(m);if(f&&f.length>0)return{...d,analyses:f}}return{...d,analyses:[]}})}async function r0(e){await We();const t=await et(e);return!t||t.length===0?[]:t.filter(r=>{var s;return!((s=r.metadata)!=null&&s.isSuperseded)})}async function xa(e,t){await We();const r=await yn({entityShas:[e],limit:1});if(r&&r.length>0&&t){const s=await eu({projectId:r[0].projectId,sha:e});if(s)for(const a of r)a.entity=s}return r||[]}async function ba(e){if(await We(),e.name&&e.projectId){const r=await yn({projectId:e.projectId,entityName:e.name,limit:10});if(r&&r.length>0){const s=r.filter(o=>{const i=o.scenarios&&o.scenarios.length>0,l=!e.filePath||o.filePath===e.filePath;return i&&l});if(s.length>0)return s.sort((o,i)=>{const l=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),s[0];const a=r.filter(o=>o.scenarios&&o.scenarios.length>0);if(a.length>0)return a.sort((o,i)=>{const l=new Date(o.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-l}),a[0]}}const t=await yn({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function ou(e){await We();const t=await yn({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function Ln(e){await We();const t=await ze();if(!t)return null;const{project:r}=await Ie(t);return await eu({projectId:r.id,sha:e})}async function iu(e){var s,a,o,i,l,d,u,p;await We();const t=[],r=[];if((s=e.metadata)!=null&&s.importedExports&&e.metadata.importedExports.length>0){const h=e.metadata.importedExports;for(const m of h){if(!m.filePath||!m.name)continue;const f=m.resolvedFilePath??m.filePath,y=m.resolvedName??m.name;let g=await et({projectId:e.projectId,filePaths:[f],names:[y]});if((!g||g.length===0)&&m.resolvedIsDefault&&(g=await et({projectId:e.projectId,filePaths:[f],names:["default"]})),g&&g.length>0){const x=g[0],b=await yn({entityShas:[x.sha],limit:1});let v,N,w;if(b&&b.length>0&&b[0].scenarios){const C=b[0],k=C.scenarios||[],j=k.length,A=k.find(M=>{var T,D;return(D=(T=M.metadata)==null?void 0:T.screenshotPaths)==null?void 0:D[0]});A&&(v=(o=(a=A.metadata)==null?void 0:a.screenshotPaths)==null?void 0:o[0],N=A.name),w={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||C.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:j,timestamp:C.createdAt?new Date(C.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else w={status:"not_analyzed"};t.push({...x,screenshotPath:v,scenarioName:N,analysisStatus:w})}}}if((l=e.metadata)!=null&&l.importedBy){const h=[];for(const m in e.metadata.importedBy)for(const f in e.metadata.importedBy[m]){const y=e.metadata.importedBy[m][f];y.shas&&h.push(...y.shas)}if(h.length>0){const m=await et({projectId:e.projectId,shas:h});if(m)for(const f of m){const y=await yn({entityShas:[f.sha],limit:1});let g,x,b;if(y&&y.length>0&&y[0].scenarios){const v=y[0],N=v.scenarios||[],w=N.length,C=N.find(j=>{var A,_;return(_=(A=j.metadata)==null?void 0:A.screenshotPaths)==null?void 0:_[0]});C&&(g=(u=(d=C.metadata)==null?void 0:d.screenshotPaths)==null?void 0:u[0],x=C.name),b={status:((p=f.metadata)==null?void 0:p.previousVersionWithAnalyses)||v.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:w,timestamp:v.createdAt?new Date(v.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else b={status:"not_analyzed"};r.push({...f,screenshotPath:g,scenarioName:x,analysisStatus:b})}}}return{importedEntities:t,importingEntities:r}}async function ze(){try{const e=Ce();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await Te.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function fr(){await We();try{const e=await ze();if(!e)return null;const{project:t,branch:r}=await Ie(e),s=await ta({projectId:t.id,branchId:r.id,limit:1,skipRelations:!0});return s&&s.length>0?s[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function va(){try{const e=Ce();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await Te.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function lu(e){try{const t=Ce();if(!t)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const r=ee.join(t,e.filePath);return await Te.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function cu(e){try{const t=Ce();if(!t||!e.filePath)return!1;const r=ee.join(t,e.filePath),a=(await Te.stat(r)).mtime.getTime(),o=e.updatedAt||e.createdAt;if(!o)return!1;const i=new Date(o).getTime();return a>i+1e3}catch{return!1}}async function du(e){if(await We(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await et({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),s=await yn({entityShas:r}),a=new Map;if(s)for(const i of s)a.has(i.entitySha)||a.set(i.entitySha,[]),a.get(i.entitySha).push(i);for(const[i,l]of a.entries())l.sort((d,u)=>{const p=new Date(d.createdAt||0).getTime();return new Date(u.createdAt||0).getTime()-p});const o=t.map(i=>({...i,analyses:a.get(i.sha)||[]}));return o.sort((i,l)=>{var p,h;const d=((p=i.analyses[0])==null?void 0:p.createdAt)||i.createdAt||"",u=((h=l.analyses[0])==null?void 0:h.createdAt)||l.createdAt||"";return new Date(u).getTime()-new Date(d).getTime()}),o}async function uu(e){try{const t=Ce();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=ee.join(t,".codeyam","config.json"),s=await Te.readFile(r,"utf8"),a=JSON.parse(s),o={...a,...e},i=JSON.stringify(o,null,2);if(await Te.writeFile(r,i,"utf8"),a.projectSlug){const l={};e.universalMocks!==void 0&&(l.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(l.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(l.webapps=e.webapps),await ir({projectSlug:a.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const s0=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:Yn,getAnalysesForEntity:xa,getAnalysisForExactEntitySha:ou,getCurrentCommit:fr,getCurrentEntities:r0,getEntityBySha:Ln,getEntityCodeFromFilesystem:lu,getEntityHistory:du,getLatestAnalysisForEntity:ba,getProjectConfig:va,getProjectSlug:ze,getRelatedEntities:iu,hasFileBeenModifiedSinceEntity:cu,requireBranchAndProject:Ie,updateProjectConfig:uu},Symbol.toStringTag,{value:"Module"})),pu="secrets.json";function hu(e){return ee.join(e,".codeyam",pu)}function mu(){return ee.join(Fo.homedir(),".codeyam",pu)}async function wa(e){let t={};try{const r=mu(),s=await Te.readFile(r,"utf-8");t=JSON.parse(s)}catch{}try{const r=hu(e),s=await Te.readFile(r,"utf-8"),a=JSON.parse(s);t={...t,...a}}catch{}return t}async function a0(e,t,r=!0){const s=r?mu():hu(e),a=ee.dirname(s);await Te.mkdir(a,{recursive:!0}),await Te.writeFile(s,JSON.stringify(t,null,2)+`
33
+ `,"utf-8")}async function o0(e){const t=await wa(e);return!!(t.ANTHROPIC_API_KEY&&t.ANTHROPIC_API_KEY.length>0)||!!(t.OPENAI_API_KEY&&t.OPENAI_API_KEY.length>0)||!!(t.GROQ_API_KEY&&t.GROQ_API_KEY.length>0)||!!(t.OPENROUTER_API_KEY&&t.OPENROUTER_API_KEY.length>0)}const i0=3;let $r=0;async function Ns(e){if(!e||e.length===0)return[];if($r>=i0)return console.warn(`[Loader] Circuit breaker open (${$r} consecutive timeouts), skipping entity fetch for ${e.length} entities`),[];const t=Math.min(Math.max(e.length*2e3,1e4),6e4);return new Promise(r=>{let s=!1;const a=setTimeout(()=>{s||(s=!0,$r++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);et({shas:e,excludeMetadata:!0}).then(o=>{s||(s=!0,clearTimeout(a),$r=0,r(o||[]))}).catch(()=>{s||(s=!0,clearTimeout(a),$r++,r([]))})})}function l0({sourcePath:e,destinationPath:t,excludes:r,silent:s}){if(process.platform!=="darwin")return!1;if(At(t))try{if(_m(t).length>0)return!1;no(t,{recursive:!0})}catch{return!1}try{Me(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const a of r)if(a.includes("*"))try{Me(`rm -rf "${Jr(t,a)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const o=Jr(t,a);At(o)&&no(o,{recursive:!0,force:!0})}return s||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if(At(t))try{no(t,{recursive:!0})}catch{}return!1}}async function c0({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:s=!1,silent:a=!1,extraArgs:o=[],timeoutMs:i=3e5}){const l=Date.now();if(!s&&o.length===0&&l0({sourcePath:e,destinationPath:t,excludes:r,silent:a})){if(!a){const u=((Date.now()-l)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${u}s]`)}return}return new Promise((d,u)=>{const p=e.endsWith("/")?e:`${e}/`,h=t.endsWith("/")?t:`${t}/`,m=["-a","--no-specials"];s||m.push("--delete","--force"),m.push(...o);for(const x of r)m.push(`--exclude=${x}`);m.push(p,h);const f=kt("rsync",m);let y=!1;const g=i?setTimeout(()=>{if(!y){y=!0,f.kill("SIGKILL");const x=((Date.now()-l)/1e3).toFixed(1);u(new Error(`rsync timed out after ${x}s syncing ${e} → ${t}`))}},i):void 0;f.on("exit",x=>{if(!y)if(y=!0,g&&clearTimeout(g),x===0){if(!a){const b=((Date.now()-l)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${b}s]`)}d()}else console.error(`CodeYam Error: rsync failed with code: ${x}`,JSON.stringify({rsyncArgs:m},null,2)),u(new Error(`rsync failed with exit code ${x}`))}),f.on("error",x=>{y||(y=!0,g&&clearTimeout(g),a||console.log("Error occurred:",x),u(x))})})}const d0=ii(oi);async function u0(e){return new Promise(t=>setTimeout(t,e))}function p0(e){try{return process.kill(e,0),!0}catch{return!1}}async function fu(e){try{const{stdout:t}=await d0(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),r=t.trim().split(`
34
+ `).filter(a=>a.trim()).map(a=>parseInt(a.trim(),10)).filter(a=>!isNaN(a)),s=[...r];for(const a of r){const o=await fu(a);s.push(...o)}return s}catch{return[]}}function ql(e,t,r){try{process.kill(e,t)}catch(s){r==null||r(`Error sending ${t} to process ${e}: ${s}`)}}async function h0(e,t,r){const s=await fu(e);for(const a of s.reverse())await ql(a,t,r);await ql(e,t,r)}async function Hr(e,t=console.log,r=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let s=0;async function a(o,i){await h0(e,o,t);for(let l=0;l<i;l++)if(await u0(1e3),s+=1e3,!await p0(e))return t(`Process tree ${e} successfully killed with ${o} after ${s/1e3} seconds.`),!0;return t(`Process tree still running after ${o}...`),!1}if(await a("SIGINT",5)||await a("SIGTERM",5))return!0;for(let o=0;o<r;o++)if(await a("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${s/1e3} seconds.`),!1}function m0(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:Gm(),createdAt:t}}Om.config({quiet:!0});var gu=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(gu||{});class f0 extends Lm{constructor(){super(...arguments),this.processes=new Map}register(t){const r=Bm(),{process:s,type:a,name:o,metadata:i,parentId:l}=t,d={id:r,type:a,name:o,pid:s.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:l,children:[]};if(this.processes.set(r,{info:d,process:s}),l){const h=this.processes.get(l);h&&(h.info.children=h.info.children||[],h.info.children.push(r))}const u=(h,m)=>{this.handleProcessExit(r,h,m)},p=h=>{this.handleProcessError(r,h)};return s.on("exit",u),s.on("error",p),s.__cleanup=()=>{s.removeListener("exit",u),s.removeListener("error",p)},this.emit("processStarted",d),r}unregister(t){const r=this.processes.get(t);return r?(r.process.__cleanup&&r.process.__cleanup(),this.processes.delete(t),!0):!1}getInfo(t){const r=this.processes.get(t);return r?{...r.info}:null}listAll(){return Array.from(this.processes.values()).map(t=>({...t.info}))}listByType(t){return this.listAll().filter(r=>r.type===t)}listByState(t){return this.listAll().filter(r=>r.state===t)}findByName(t){return this.listAll().filter(r=>r.name===t)}async shutdown(t,r={}){const s=this.processes.get(t);if(!s)throw new Error(`Process not found: ${t}`);const{info:a,process:o}=s;if(a.state==="completed"||a.state==="failed"||a.state==="killed")return;if(r.shutdownChildren&&a.children&&a.children.length>0&&await Promise.all(a.children.map(l=>this.shutdown(l,r))),o.pid)try{await Hr(o.pid,l=>console.log(`[Process ${t}] ${l}`))}catch(l){console.warn(`Error killing process ${t}:`,l)}await new Promise(l=>setTimeout(l,100)),a.state==="running"&&(a.state="killed",a.endedAt=Date.now());const i=o.__cleanup;i&&i()}async shutdownByType(t,r={}){const s=this.listByType(t);await Promise.all(s.map(a=>this.shutdown(a.id,r)))}async shutdownAll(t={}){const r=this.listAll();await Promise.all(r.map(s=>this.shutdown(s.id,t)))}cleanupCompleted(t={}){const{retentionMs:r=6e4}=t,s=Date.now();for(const[a,o]of this.processes.entries()){const{info:i}=o;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&s-i.endedAt>r){const l=o.process.__cleanup;l&&l(),this.processes.delete(a)}}}handleProcessExit(t,r,s){const a=this.processes.get(t);if(!a)return;const{info:o}=a;o.endedAt=Date.now(),o.exitCode=r,o.signal=s,r===0?o.state="completed":s?o.state="killed":o.state="failed",this.emit("processExited",o)}handleProcessError(t,r){const s=this.processes.get(t);if(!s)return;const{info:a}=s;a.endedAt=Date.now(),a.state="failed",a.metadata={...a.metadata,error:r.message},this.emit("processExited",a)}}let co=null;function g0(){return co||(co=new f0),co}const y0={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function x0({command:e,args:t,workingDir:r,outputOptions:s=y0,processName:a,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${a}`},l=kt(e,t,{cwd:r,env:i});return g0().register({process:l,type:gu.Other,name:a,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(p=>{const h=f=>{const y=ee.join(r,"log.txt");Q.appendFile(y,f,g=>{g&&console.log("Error writing to log file:",g)})},m=(f,y="")=>{const g=new Date().toLocaleString();return f.split(`
35
+ `).map(b=>b.trim()?`[${g}]${y} ${b}`:b).join(`
36
+ `)};l.stdout.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=m(y);s.stdoutToConsole&&console.log(g),s.stdoutToFile&&h(g+`
37
+ `),s.stdoutCallback&&s.stdoutCallback(y)}),l.stderr.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=m(y,"<STDERR>");s.stderrToConsole&&console.error(g),s.stderrToFile&&h(g+`
38
+ `),s.stderrCallback&&s.stderrCallback(y)}),l.on("exit",function(f){p(f)})}),process:l}}function b0(e){const t=[];return Object.keys(e).forEach(r=>{const s=e[r];s!==void 0&&(typeof s=="boolean"?s&&t.push(`--${r}`):s!==null&&t.push(`--${r}`,String(s)))}),t}function v0({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:s}){const a=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
39
+ `);Q.writeFileSync(`${e}/.env`,a);const o=b0(r);return x0({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:s,processName:"analyzer",env:t})}const w0="/tmp/codeyam/local-dev";function yu(e){return G.join(w0,e)}function xu(e){return G.join(yu(e),"codeyam")}function zt(e){return G.join(yu(e),"project")}function ts(e){return G.join(xu(e),"log.txt")}const N0=[".sync-metadata.json","__codeyamMocks__"];async function S0(e,t={}){const{port:r,silent:s=!0}=t,a=zt(e);if(r)try{Me(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}try{Me(`lsof +D "${a}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}await new Promise(o=>setTimeout(o,500))}async function C0(e,t={}){const{killProcesses:r=!0,port:s,silent:a=!0}=t,o=zt(e),i=[],l=[];if(!Q.existsSync(o))return{removed:i,errors:l};r&&await S0(e,{port:s,silent:a});for(const d of N0){const u=G.join(o,d);if(Q.existsSync(u))try{(await Ae.stat(u)).isDirectory()?await Ae.rm(u,{recursive:!0,force:!0}):await Ae.unlink(u),i.push(d)}catch(p){l.push(`${d}: ${p instanceof Error?p.message:String(p)}`)}}return{removed:i,errors:l}}const k0=G.dirname(ha(import.meta.url));function j0(e){let t=e;for(;t!==G.dirname(t);){const r=G.join(t,"package.json");if(Q.existsSync(r))try{if(JSON.parse(Q.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=G.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function Na(){const e=j0(k0);return G.join(e,"analyzer-template")}function gr(e){return xu(e)}function _0(){const e=Na();return Q.existsSync(G.join(e,".finalized"))}async function Ql(e){const t=Na(),r=gr(e),s=Date.now(),a=()=>`${((Date.now()-s)/1e3).toFixed(1)}s`;if(!Q.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Ae.mkdir(G.dirname(r),{recursive:!0}),console.log(`[createAnalyzer] Starting rsync: ${t} → ${r}`),await c0({sourcePath:t,destinationPath:r,silent:!0}),console.log(`[createAnalyzer] rsync completed (${a()})`),Q.existsSync(G.join(r,"dist"))||(console.warn("[createAnalyzer] WARNING: dist/ not found after rsync — template may not be built. Attempting build..."),Me("npm install --include=dev && npm run build",{cwd:r,stdio:"pipe",timeout:3e5}),console.log(`[createAnalyzer] npm install + build completed (${a()})`)),console.log(`[createAnalyzer] Done (${a()})`)}function yr(e,t,r,s){const a=gr(e);if(!Q.existsSync(a))throw new Error(`Analyzer not found at ${a}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const o=void 0;return v0({absoluteCodeyamRootPath:a,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function E0(e){const t=Na(),r=gr(e),s=G.join(t,".build-info.json"),a=G.join(r,".build-info.json");if(!Q.existsSync(s))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!Q.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!Q.existsSync(a))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(Q.readFileSync(s,"utf8")),i=JSON.parse(Q.readFileSync(a,"utf8"));return o.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${o.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(o){return{isFresh:!1,reason:`Error reading build markers: ${o.message}`}}}async function ns(e,t){const r=gr(e);if(!Q.existsSync(r)){t.update("Creating analyzer..."),await Ql(e);return}const s=E0(e);s.isFresh||(t.update(`Updating analyzer (${s.reason})...`),await Ql(e),t.update("Analyzer updated"))}async function yi(e){await C0(e,{killProcesses:!1})}const P0=G.dirname(ha(import.meta.url));function Sa(){let e=P0;for(;e!==G.dirname(e);){const t=G.join(e,"package.json");if(Q.existsSync(t))try{if(JSON.parse(Q.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=G.dirname(e)}return null}function or(e){if(!Q.existsSync(e))return null;try{return JSON.parse(Q.readFileSync(e,"utf8"))}catch{return null}}function A0(){const e=Sa();if(e){const t=[G.join(e,"src/webserver/build-info.json"),G.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const s=or(r);if(s!=null&&s.semanticVersion)return s.semanticVersion}}return"unknown"}function T0(){const e=Sa();if(e){const t=G.join(e,"package.json");try{const r=JSON.parse(Q.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const xi=A0(),uo=T0();function bi(){if(uo!=="unknown"&&uo!=="0.1.0")return uo;const e=Sa();if(e)for(const t of[G.join(e,"src/webserver/build-info.json"),G.join(e,"codeyam-cli/src/webserver/build-info.json")]){const r=or(t);if(r!=null&&r.buildNumber)return`dev (build ${r.buildNumber})`}return"dev"}function bu(e){const t=Sa();let r=null;if(t){const d=[G.join(t,"src/webserver/build-info.json"),G.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const u of d)if(r=or(u),r)break}const s=Na(),a=G.join(s,".build-info.json"),o=or(a);let i=null;if(e){const d=gr(e),u=G.join(d,".build-info.json");i=or(u)}let l=!1;return o&&i?l=o.buildTime>i.buildTime:o&&!i&&e&&(l=!0),{cliVersion:xi,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:l}}function Ca(e){const t=gr(e),r=G.join(t,".build-info.json"),s=or(r);return(s==null?void 0:s.version)??null}function vi(){const e=Ce();return e?G.join(e,".codeyam","server.json"):null}function Jj(e){const t=vi();t&&Q.writeFileSync(t,JSON.stringify(e,null,2))}function ka(){const e=vi();if(!e||!Q.existsSync(e))return null;try{const t=Q.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function wi(){const e=vi();if(e)try{Q.unlinkSync(e)}catch{}}function vu(e){try{return process.kill(e,0),!0}catch{return!1}}function wu(){try{const e=process.platform==="win32",r=Me(e?'tasklist /FI "IMAGENAME eq node.exe" /FO CSV /NH':"ps aux | grep codeyam-server | grep -v grep",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();if(!r)return[];const s=[];if(e)for(const a of r.split(`
40
+ `)){const o=a.match(/"[^"]*","(\d+)"/);if(o){const i=parseInt(o[1],10);if(!isNaN(i))try{Me(`wmic process where "ProcessId=${i}" get CommandLine /FORMAT:LIST`,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).includes("codeyam-server")&&s.push(i)}catch{}}}else for(const a of r.split(`
41
+ `)){const o=a.trim().split(/\s+/);if(o.length>=2){const i=parseInt(o[1],10);isNaN(i)||s.push(i)}}return s}catch{return[]}}function Hj(){const e=ka();if(e)if(!vu(e.pid))wi();else return{running:!0,state:e};const t=wu();return t.length>0?{running:!0,pids:t}:{running:!1}}function M0(e,t=5e3){if(e.length===0)return!0;const r=Date.now()+t;for(;Date.now()<r;){if(!e.some(a=>vu(a)))return!0;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100)}return!1}function Vj(){let e=!1;const t=[],r=ka();if(r){try{process.kill(r.pid,"SIGTERM"),t.push(r.pid),e=!0}catch{}wi()}const s=wu();for(const a of s)try{process.kill(a,"SIGTERM"),t.includes(a)||t.push(a),e=!0}catch{}return M0(t),e}function Kj(e,t,r=10,s=10){if(t(e))return e;for(let a=1;a<=s;a++){const o=e+a*r;if(t(o))return o}throw new Error(`Could not find a free port starting from ${e} (tried ${s} candidates)`)}function Gj(e){try{return Me(`lsof -ti:${e}`,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}),!1}catch{return!0}}const $0="/assets/globals-L-aUIeux.css";function Zl({text:e,subtext:t,linkText:r,linkTo:s}){const[a,o]=E(!1);return a?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:c("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-yellow-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),c("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-blue-900",children:e}),n("p",{className:"text-xs text-blue-700 mt-0.5",children:t})]}),n(Ee,{to:s,className:"shrink-0 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 transition-colors",children:r})]}),n("button",{type:"button",onClick:()=>o(!0),className:"shrink-0 ml-4 p-1 rounded text-blue-600 hover:text-blue-800 hover:bg-blue-100 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function F0({version:e}){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:c("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[c("div",{className:"flex items-center gap-3",children:[n("span",{className:"font-mono text-sm font-semibold tracking-widest text-cyblack-100",children:"CODEYAM"}),e&&n("span",{className:"font-mono text-xs text-gray-400",children:e})]}),c("div",{className:"flex items-center gap-4 font-mono text-xs uppercase tracking-widest",children:[n("a",{href:"https://blog.codeyam.com/",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Read the Blog"}),n("span",{className:"text-cygray-30",children:"|"}),n("a",{href:"https://discord.gg/x4uAgaRdwF",target:"_blank",rel:"noopener noreferrer",className:"text-cyblack-100 underline underline-offset-4 hover:text-primary-100",children:"Join Discord"})]})]})})}function D0({serverVersion:e}){const[t,r]=E("stale"),[s,a]=E(null),o=async()=>{r("restarting"),a(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");r("reconnecting");let l=0;const d=30,u=1e3,p=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}l++,l<d?setTimeout(()=>void p(),u):(a("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void p(),500)}catch(i){a(i instanceof Error?i.message:"Failed to restart server"),r("stale")}};return n("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:n("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-amber-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),c("div",{className:"flex-1",children:[t==="stale"&&c(we,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),c("p",{className:"text-xs text-amber-700 mt-0.5",children:["Server version: ",e,". A newer version of CodeYam CLI is installed. Restart the server to get the latest features."]}),s&&n("p",{className:"text-xs text-red-600 mt-1",children:s})]}),t==="restarting"&&c(we,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),t==="reconnecting"&&c(we,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),n("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),t==="stale"&&n("button",{type:"button",onClick:()=>void o(),className:"shrink-0 px-4 py-2 bg-amber-600 text-white text-sm font-medium rounded hover:bg-amber-700 transition-colors cursor-pointer",children:"Restart Server"}),(t==="restarting"||t==="reconnecting")&&c("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[c("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function xt({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:s="",duration:a=2e3,ariaLabel:o,icon:i=!1,iconSize:l=14}){const[d,u]=E(!1),p=le(()=>{navigator.clipboard.writeText(e).then(()=>{u(!0),setTimeout(()=>u(!1),a)}).catch(h=>{console.error("Failed to copy:",h)})},[e,a]);return n("button",{onClick:p,className:`cursor-pointer ${s}`,disabled:d,"aria-label":o||(d?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?d?n($t,{size:l,className:"text-green-500"}):n(Bt,{size:l}):d?r:t})}function R0({currentVersion:e,latestVersion:t}){const[r,s]=E(!1);if(r)return null;const a="npm install -g @codeyam/codeyam-cli@latest && codeyam stop && codeyam";return n("div",{className:"bg-emerald-100 border rounded border-emerald-700 shadow-sm mx-6 mt-6",children:c("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{className:"shrink-0",children:n("svg",{className:"w-5 h-5 text-emerald-600",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M7 11l5-5m0 0l5 5m-5-5v12"})})}),c("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-emerald-900",children:"A new version of CodeYam CLI is available"}),c("p",{className:"text-xs text-emerald-700 mt-0.5",children:["Current: ",e," → Latest: ",t]})]}),c("div",{className:"shrink-0 flex items-center gap-2",children:[n("code",{className:"text-xs bg-emerald-200 text-emerald-900 px-2 py-1.5 rounded font-mono",children:a}),n(xt,{content:a,label:"Copy",copiedLabel:"Copied!",className:"px-3 py-1.5 bg-emerald-600 text-white text-xs font-medium rounded hover:bg-emerald-700 transition-colors"})]})]}),n("button",{type:"button",onClick:()=>s(!0),className:"shrink-0 ml-4 p-1 rounded text-emerald-600 hover:text-emerald-800 hover:bg-emerald-200 transition-colors cursor-pointer","aria-label":"Dismiss banner",children:n("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}let Fr=null,Ss=0;const I0=3600*1e3;function O0(e,t){const r=e.split(".").map(Number),s=t.split(".").map(Number);for(let a=0;a<Math.max(r.length,s.length);a++){const o=r[a]??0,i=s[a]??0;if(isNaN(o)||isNaN(i))return!1;if(o>i)return!0;if(o<i)return!1}return!1}async function L0(){const e=bi();if(Fr&&Date.now()-Ss<I0)return Fr;try{const t=new AbortController,r=setTimeout(()=>t.abort(),5e3),s=await fetch("https://registry.npmjs.org/@codeyam/codeyam-cli/latest",{signal:t.signal});if(clearTimeout(r),!s.ok){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return Fr=l,Ss=Date.now(),l}const o=(await s.json()).version;if(!o){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return Fr=l,Ss=Date.now(),l}const i={updateAvailable:O0(o,e),latestVersion:o,currentVersion:e};return Fr=i,Ss=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function aa(e){return G.join(e,".codeyam","queue.json")}function Br(e){const t=aa(e);if(!Q.existsSync(t))return{paused:!1,jobs:[]};try{const r=Q.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function B0(e,t){const r=aa(e),s=G.dirname(r);Q.existsSync(s)||Q.mkdirSync(s,{recursive:!0});try{Q.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(a){throw console.error("Failed to save queue state:",a),a}}const da=class da extends Xr{constructor(t){super(),this.watcher=null,this.debounceTimers=new Map,this.DEBOUNCE_MS=300,this.options=t}start(){try{this.watcher=ce.watch(this.options.projectRootPath,{recursive:!0},(t,r)=>{if(!r||!/\.(ts|tsx|js|jsx|css|scss|json|svg|html)$/.test(r)||da.IGNORED_DIRS.some(a=>r.includes(a+"/")||r.includes(a+"\\")))return;const s=this.debounceTimers.get(r);s&&clearTimeout(s),this.debounceTimers.set(r,setTimeout(()=>{this.debounceTimers.delete(r),this.syncFile(r)},this.DEBOUNCE_MS))}),console.log(`[InteractiveSyncWatcher] Watching ${this.options.projectRootPath} for changes`)}catch(t){console.error("[InteractiveSyncWatcher] Failed to start:",t)}}syncFile(t){const r=ee.join(this.options.projectRootPath,t),s=ee.join(this.options.tmpProjectPath,t);try{if(!ce.existsSync(r)){ce.existsSync(s)&&(ce.unlinkSync(s),console.log(`[InteractiveSyncWatcher] Removed: ${t}`));return}const a=ee.dirname(s);ce.existsSync(a)||ce.mkdirSync(a,{recursive:!0}),ce.copyFileSync(r,s);const o=ee.basename(t);console.log(`[InteractiveSyncWatcher] Synced: ${t}`);const i={type:"file-synced",fileName:o,filePath:t,timestamp:Date.now()};this.emit("sync",i)}catch(a){console.error(`[InteractiveSyncWatcher] Error syncing ${t}:`,a);const o={type:"error",fileName:ee.basename(t),filePath:t,timestamp:Date.now()};this.emit("sync",o)}}stop(){this.watcher&&(this.watcher.close(),this.watcher=null);for(const t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),console.log("[InteractiveSyncWatcher] Stopped")}};da.IGNORED_DIRS=["node_modules",".git",".codeyam","__codeyamMocks__",".next","dist","build",".turbo",".vercel","coverage",".cache"];let Ro=da,z0=class extends Xr{constructor(){super(),this.setMaxListeners(20)}emitFileSynced(t,r){this.emit("event",{type:"file-synced",fileName:t,filePath:r,timestamp:Date.now()})}emitError(t,r){this.emit("event",{type:"sync-error",fileName:t,filePath:r,timestamp:Date.now()})}};const Io="__codeyam_dev_mode_event_emitter__";globalThis[Io]||(globalThis[Io]=new z0);const Xl=globalThis[Io],Oo=new Map;async function Y0(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await U0(e,t,r);else if(e.type==="baseline")await W0(e,t,r);else if(e.type==="recapture")await J0(e,t,r);else if(e.type==="capture-only")await H0(e,t,r);else if(e.type==="debug-setup")await V0(e,t,r);else if(e.type==="interactive-start")await K0(e,t,r);else if(e.type==="interactive-stop")await G0(e,t,r);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(s){throw console.error(`[Queue] Job ${e.id} failed:`,s),s}}async function U0(e,t,r){var b,v,N,w;const{projectSlug:s,commitSha:a,entityShas:o}=e;if(!a)throw new Error("Analysis job missing commitSha");const i=o||[],l=e.onlyDataStructure,d=ts(s),u=C=>{const k=`CodeYam Log Level 1: ${C}`;console.log(`[Queue] ${C}`);try{Q.mkdirSync(G.dirname(d),{recursive:!0}),Q.appendFileSync(d,`[${new Date().toLocaleString()}] ${k}
42
+
43
+ `)}catch{}},{project:p}=await Ie(s);u("Preparing project cache..."),await yi(s),u("Preparing simulation engine..."),await ns(s,{update:C=>u(C)});const h=Ca(s),m={...await bn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:vn(),...!l&&i.length>0?{ENTITY_SHAS:i.join(",")}:{},...l?{ONLY_DATA_STRUCTURE:"true"}:{},...h?{ANALYZER_VERSION:h}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},f=(v=(b=p.metadata)==null?void 0:b.webapps)==null?void 0:v[0];if(!f)throw new Error("No webapps found in project metadata");const y={packageManager:((N=p.metadata)==null?void 0:N.packageManager)||"npm",absoluteProjectRootPath:zt(s),port:0,noServer:!0,framework:f.framework,...l?{}:{orchestrateCapture:"local-sequential"}},g=yr(s,m,y),x=C=>{try{return process.kill(C,0),!0}catch{return!1}};await hn({commitSha:a,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((w=e.filePaths)==null?void 0:w.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:g.process.pid}}),r==null||r.notifyChange("commit");try{try{const C=new Promise((k,j)=>setTimeout(()=>j(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([g.promise,C]),await hn({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await hn({commitSha:a,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(k=>setTimeout(k,2e3))}finally{if(g.process.pid)try{x(g.process.pid)&&await Hr(g.process.pid,()=>{})}catch{}}}catch(C){if(console.error(`[Queue] Analysis job ${e.id} failed:`,C),g.process.pid&&x(g.process.pid))try{await Hr(g.process.pid,()=>{})}catch{}try{await hn({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:C instanceof Error?C.message:String(C)}}),r==null||r.notifyChange("commit")}catch(k){console.error("[Queue] Failed to update commit metadata after job failure:",k)}throw C}}async function W0(e,t,r){var m,f,y;const{projectSlug:s,commitSha:a}=e;if(!a)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${s}`);const{project:o}=await Ie(s);await yi(s),await ns(s,{update:g=>console.log(`[Queue] ${g}`)});const i=Ca(s),l={...await bn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:vn(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(m=o.metadata)==null?void 0:m.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const u={packageManager:((y=o.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:zt(s),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},p=yr(s,l,u),h=g=>{try{return process.kill(g,0),!0}catch{return!1}};await hn({commitSha:a,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:p.process.pid}}),r==null||r.notifyChange("commit");try{const g=new Promise((x,b)=>setTimeout(()=>b(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([p.promise,g]),await hn({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${s}`),await new Promise(x=>setTimeout(x,2e3))}finally{if(p.process.pid)try{h(p.process.pid)&&await Hr(p.process.pid,()=>{})}catch{}}}async function J0(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Recapture job missing analysisId");const l=await tn({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:b}=await import("./index-D4MWAsqb.js"),v=b(),N=await v.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let w={};N!=null&&N.metadata&&(typeof N.metadata=="string"?w=JSON.parse(N.metadata):w=N.metadata),w.defaultWidth=i,await v.updateTable("entities").set({metadata:JSON.stringify(w)}).where("sha","=",l.entitySha).execute()}await mr(a,b=>{if(b.readyToBeCaptured=!0,b.scenarios)for(const v of b.scenarios)(!o||v.name===o)&&(delete v.finishedAt,delete v.startedAt,delete v.screenshotStartedAt,delete v.screenshotFinishedAt,delete v.interactiveStartedAt,delete v.interactiveFinishedAt,delete v.error,delete v.errorStack);delete b.finishedAt});const{project:d}=await Ie(s);await ns(s,{update:b=>console.log(`[Queue] ${b}`)});const u=Ca(s),p={...await bn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:vn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...u?{ANALYZER_VERSION:u}:{}},h={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:zt(s),port:void 0,noServer:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??rt.Next,orchestrateCapture:"local-sequential"},m=yr(s,p,h);try{await m.promise}finally{try{m.process.kill("SIGTERM")}catch{}}}async function H0(e,t,r){var f,y,g,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Capture-only job missing analysisId");const l=await tn({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:b}=await import("./index-D4MWAsqb.js"),v=b(),N=await v.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let w={};N!=null&&N.metadata&&(typeof N.metadata=="string"?w=JSON.parse(N.metadata):w=N.metadata),w.defaultWidth=i,await v.updateTable("entities").set({metadata:JSON.stringify(w)}).where("sha","=",l.entitySha).execute()}await mr(a,b=>{if(b.readyToBeCaptured=!0,b.scenarios)for(const v of b.scenarios)(!o||v.name===o)&&(delete v.finishedAt,delete v.startedAt,delete v.screenshotStartedAt,delete v.screenshotFinishedAt,delete v.interactiveStartedAt,delete v.interactiveFinishedAt,delete v.error,delete v.errorStack);delete b.finishedAt});const{project:d}=await Ie(s);await ns(s,{update:b=>console.log(`[Queue] ${b}`)});const u=Ca(s);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const p={...await bn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:vn(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...u?{ANALYZER_VERSION:u}:{}},h={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:zt(s),port:void 0,noServer:!0,fast:!0,framework:((x=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:x.framework)??rt.Next,orchestrateCapture:"local-sequential"},m=yr(s,p,h);try{await m.promise}finally{try{m.process.kill("SIGTERM")}catch{}}}async function V0(e,t,r){var m,f,y,g;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Debug setup job missing analysisId");const i=await tn({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:l}=await Ie(s);await yi(s),await ns(s,{update:x=>console.log(`[Queue] ${x}`)});const d={...await bn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:vn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,PREP_ONLY:"true"};o&&(d.SCENARIO_IDS=o);const u={packageManager:((m=l.metadata)==null?void 0:m.packageManager)||"npm",absoluteProjectRootPath:zt(s),port:void 0,noServer:!1,framework:((g=(y=(f=l.metadata)==null?void 0:f.webapps)==null?void 0:y[0])==null?void 0:g.framework)||rt.Next},h=await yr(s,d,u).promise;if(h!==0)throw new Error(`Prep process exited with code ${h}`)}async function K0(e,t,r){var x,b,v,N;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Interactive start job missing analysisId");const i=await tn({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:l}=await Ie(s),d={...await bn(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:vn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,INTERACTIVE_MODE:"true"};o&&(d.INITIAL_SCENARIO_ID=o),i.scenarios&&i.scenarios.length>0&&(d.SCENARIO_IDS=i.scenarios.map(w=>w.id).join(","));const u=zt(s),p=ee.join(u,".next","dev","lock");if(ce.existsSync(p)){console.log("[Queue] Found stale .next/dev/lock, cleaning up old processes");try{const w=Me(`pgrep -f ${JSON.stringify(u)} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(w)for(const C of w.split(`
44
+ `).filter(Boolean))try{process.kill(parseInt(C,10),"SIGTERM"),console.log(`[Queue] Killed stale process ${C}`)}catch{}}catch{}try{ce.unlinkSync(p),console.log("[Queue] Removed stale lock file")}catch{}}const h=ce.existsSync(u)&&ce.existsSync(ee.join(u,"package.json")),m={packageManager:((x=l.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:u,port:void 0,noServer:!1,fast:h,framework:((N=(v=(b=l.metadata)==null?void 0:b.webapps)==null?void 0:v[0])==null?void 0:N.framework)||rt.Next};await mr(a,w=>{w.readyToBeCaptured=!0});const f=yr(s,d,m);await nu(a,w=>{w.interactiveMode={pid:f.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${a}, PID: ${f.process.pid}`);const y=zt(s),g=new Ro({projectRootPath:t,tmpProjectPath:y});g.on("sync",w=>{w.type==="file-synced"?Xl.emitFileSynced(w.fileName,w.filePath):w.type==="error"&&Xl.emitError(w.fileName,w.filePath)}),g.start(),Oo.set(a,g),console.log(`[Queue] File sync watcher started for analysis ${a}`)}async function G0(e,t,r){var u;const{projectSlug:s,analysisId:a}=e;if(!a)throw new Error("Interactive stop job missing analysisId");const o=await tn({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${a} not found`);const i=(u=o.metadata)==null?void 0:u.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${a}`);return}const l=Oo.get(a);l&&(l.stop(),Oo.delete(a),console.log(`[Queue] File sync watcher stopped for analysis ${a}`));const d=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${a}, killing PID: ${d}`);try{try{process.kill(d,0)}catch{console.log(`[Queue] Process ${d} already exited`);return}await Hr(d,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${d}`)}catch(p){throw console.error(`[Queue] Failed to kill process ${d}:`,p),p}finally{await nu(a,p=>{p.interactiveMode=null})}}class q0{constructor(t,r){this.processing=!1,this.completionCallbacks=new Map,this.completedJobs=new Map,this.projectRoot=t,this.state={paused:!1,jobs:[]},r&&(typeof r=="function"?this.notifier={notifyChange:()=>r()}:this.notifier=r)}start(){this.state=Br(this.projectRoot),this.state.currentlyExecuting&&(console.log(`[Queue] Clearing stale currentlyExecuting job from previous session: ${this.state.currentlyExecuting.id}`),this.state.currentlyExecuting=void 0,this.save()),this.state.jobs.length>0?(this.state.paused=!0,this.save(),console.log(`[Queue] Found ${this.state.jobs.length} queued jobs from previous session (paused)`)):this.state.paused=!1}enqueue(t){const r=t.commitSha||ai(),s={...t,id:r,queuedAt:new Date().toISOString()};this.state.jobs.push(s),this.save(),console.log(`[Queue] Enqueued job ${r} (${s.type})`);const a=new Promise((o,i)=>{this.completionCallbacks.set(r,l=>{l?i(l):o()})});return this.state.paused||this.processNext().catch(o=>{console.error("[Queue] ERROR in processNext():",o)}),{jobId:r,completion:a}}resume(){console.log("[Queue] Resuming queue"),this.state.paused=!1,this.save(),this.processNext()}pause(){console.log("[Queue] Pausing queue"),this.state.paused=!0,this.save()}getState(){return{...this.state}}getJobResult(t){return this.completedJobs.get(t)}removeJob(t){const r=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(a=>a.id!==t);const s=this.state.jobs.length<r;if(s){console.log(`[Queue] Removed job ${t}`),this.save();const a=this.completionCallbacks.get(t);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(t))}else console.log(`[Queue] Job ${t} not found in queue`);return s}clearQueue(){const t=this.state.jobs.length;return t===0?0:(this.state.jobs.forEach(r=>{const s=this.completionCallbacks.get(r.id);s&&(setImmediate(()=>s(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${t} jobs`),this.save(),t)}reorderJob(t,r){const s=this.state.jobs.findIndex(i=>i.id===t);if(s===-1)return console.log(`[Queue] Job ${t} not found in queue`),!1;const a=r==="up"?s-1:s+1;if(a<0||a>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${t} ${r}: at boundary`),!1;const o=this.state.jobs[s];return this.state.jobs[s]=this.state.jobs[a],this.state.jobs[a]=o,console.log(`[Queue] Moved job ${t} ${r} (position ${s} -> ${a})`),this.save(),!0}async processNext(){if(this.state.paused||this.processing)return;if(this.state.jobs.length===0){console.log("[Queue] No jobs to process");return}this.processing=!0;const t=this.state.jobs[0];console.log(`[Queue] Starting job ${t.id} (${t.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await Y0(t,this.projectRoot,this.notifier),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"success",completedAt:new Date().toISOString()});const r=this.completionCallbacks.get(t.id);r&&(r(),this.completionCallbacks.delete(t.id)),console.log(`[Queue] Job ${t.id} completed successfully`)}catch(r){console.error(`[Queue] Job ${t.id} failed:`,r),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(t.id,{id:t.id,status:"error",error:(r==null?void 0:r.message)||"Unknown error",completedAt:new Date().toISOString()});const s=this.completionCallbacks.get(t.id);s&&(s(r),this.completionCallbacks.delete(t.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>void this.processNext())}}save(){B0(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class Q0{constructor(t,r,s=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=s}start(){const t=aa(this.projectRoot);if(!Q.existsSync(t)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(t)}watchDirectory(){const t=aa(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=Q.watch(r,(s,a)=>{a==="queue.json"&&(this.stop(),this.watchFile(t),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(s){console.error("[QueueFileWatcher] Failed to watch directory:",s)}}watchFile(t){try{this.watcher=Q.watch(t,r=>{r==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(r){console.error("[QueueFileWatcher] Failed to watch queue file:",r)}}notifyChange(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.onChange(),this.debounceTimer=null},this.debounceMs)}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}}class Z0{constructor(t,r,s){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=s,this.cachedState=Br(r)}start(){this.cachedState=Br(this.projectRoot),console.log(`[ProxyQueue] Connected to background server at ${this.serverInfo.url}`),console.log(`[ProxyQueue] Current queue has ${this.cachedState.jobs.length} jobs`),this.fileWatcher=new Q0(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(t){let r,s;const a=new Promise((i,l)=>{r=i,s=l}),o=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(t).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),r()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),s(i)}),{jobId:o,completion:a}}async enqueueRemote(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to enqueue: ${r.status} ${s}`)}return r.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(t=>{console.error("[ProxyQueue] Failed to resume:",t)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(t=>{console.error("[ProxyQueue] Failed to pause:",t)})}async sendAction(t){const r=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t})});if(!r.ok){const s=await r.text();throw new Error(`Failed to ${t}: ${r.status} ${s}`)}this.refreshState()}getState(){return this.cachedState=Br(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=Br(this.projectRoot),this.onStateChange&&this.onStateChange()}async isServerAlive(){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),s=await fetch(`${this.serverInfo.url}/api/health`,{signal:t.signal});return clearTimeout(r),s.ok}catch{return!1}}getServerInfo(){return{...this.serverInfo}}stop(){this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null)}}function X0(e){const t=G.join(e,".codeyam","server.json");if(!Q.existsSync(t))return null;try{const r=Q.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function ey(e){try{return process.kill(e,0),!0}catch{return!1}}async function ty(e){try{const t=new AbortController,r=setTimeout(()=>t.abort(),2e3),s=await fetch(`${e}/api/health`,{signal:t.signal});return clearTimeout(r),s.ok}catch{return!1}}async function ny(e){const t=X0(e);return!t||!ey(t.pid)||!await ty(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class ry extends Xr{constructor(){super();vt(this,"watcher",null);vt(this,"dbPath",null);vt(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=vn();const{default:r}=await import("chokidar"),s=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=r.watch(s,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",a=>{const o=Date.now(),i=new Date(o).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${a}`),console.log(`[dbNotifier] Timestamp: ${i} (${o})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:o})}).on("error",a=>{console.error("Database watcher error:",a),this.emit("error",a)}),this.isWatching=!0}catch(r){console.error("Failed to start database watcher:",r),this.emit("error",r)}}notifyChange(r="unknown"){const s=Date.now(),a=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${r}`),console.log(`[dbNotifier] Timestamp: ${a} (${s})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:r,timestamp:s})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const Nt=new ry;let Fn=null,zr=null;async function sy(){if(!Fn){if(zr){await zr;return}zr=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||ru()||process.cwd();if(Qg(e),console.log(`[GlobalQueue] Project root: ${e}`),await We(),process.env.NODE_ENV==="development")try{const r=ee.join(e,".codeyam","config.json"),a=JSON.parse(await ce.promises.readFile(r,"utf8")).projectSlug;a&&(await ir({projectSlug:a,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),console.log("[GlobalQueue] Labs & Simulations auto-enabled for dev mode"))}catch(r){console.warn("[GlobalQueue] Could not auto-enable labs:",r)}const t=await ny(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new Z0(t,e,()=>{Nt.notifyChange("unknown")});await r.start(),Fn=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new q0(e,Nt);await r.start(),Fn=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await zr}}async function nn(){return Fn||await sy(),Fn}function ay(){return Fn||(zr&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const oy=()=>[{rel:"stylesheet",href:$0},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],iy={currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown",npmUpdate:null,labs:null,simulationsEnabled:!1,isSimulationsReady:!1,isAdmin:!1,editorMode:!1,displayVersion:bi()};async function ly({request:e,context:t}){var r,s,a,o,i,l,d,u,p,h,m;try{const f=e.signal,y=()=>{if(f.aborted)throw new Response(null,{status:499})};y();const g=Ce()||process.cwd(),[x,b,v]=await Promise.all([ze(),wa(g),L0().catch(()=>null)]);if(!x)throw new Error("Project slug not found");const{project:N,branch:w}=await Ie(x);y();const C=await ta({projectId:N.id,branchId:w.id,limit:20,skipRelations:!0});y();const k=C.length>0?C[0]:null,j=t.analysisQueue||ay(),A=j==null?void 0:j.getState();y();const _=await Promise.all(((A==null?void 0:A.jobs)||[]).map(async H=>{var ae;const re=await Ns(H.entityShas||[]);return re.length===0&&((ae=H.entityShas)!=null&&ae.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",H.id),{...H,entities:re}}));let M=null;if(A!=null&&A.currentlyExecuting){const H=A.currentlyExecuting,re=await Ns(H.entityShas||[]);re.length===0&&((r=H.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",H.id),M={...H,entities:re}}const T=M?_.filter(H=>H.id!==M.id):_;let D=((a=(s=k==null?void 0:k.metadata)==null?void 0:s.currentRun)==null?void 0:a.currentEntityShas)||[];if(D.length===0){const H=((o=k==null?void 0:k.metadata)==null?void 0:o.historicalRuns)||[];if(H.length>0){const ae=[...H].sort((X,oe)=>{const me=X.archivedAt||X.createdAt||"";return(oe.archivedAt||oe.createdAt||"").localeCompare(me)})[0];if(ae){const X=ae.analysisCompletedAt||ae.createdAt;if(X){const oe=new Date(X).getTime(),ve=Date.now()-1440*60*1e3;oe>ve&&(D=ae.currentEntityShas||[])}}}}const R=await Ns(D),L=[];b.ANTHROPIC_API_KEY&&L.push("ANTHROPIC_API_KEY"),b.GROQ_API_KEY&&L.push("GROQ_API_KEY"),b.OPENAI_API_KEY&&L.push("OPENAI_API_KEY"),b.OPENROUTER_API_KEY&&L.push("OPENROUTER_API_KEY"),y();const U=[];for(const H of C){const re=((i=H.metadata)==null?void 0:i.historicalRuns)||[];for(const ae of re)U.push(ae)}U.sort((H,re)=>{const ae=H.archivedAt||H.analysisCompletedAt||H.createdAt||"";return(re.archivedAt||re.analysisCompletedAt||re.createdAt||"").localeCompare(ae)});const W=new Set(((l=M==null?void 0:M.entities)==null?void 0:l.map(H=>H.sha))||[]),F=U.filter(H=>!(H.currentEntityShas||[]).some(ae=>W.has(ae))).slice(0,3),Y=new Set;for(const H of F)for(const re of H.currentEntityShas||[])Y.add(re);const P=await Ns(Array.from(Y)),O=new Map;for(const H of P)O.set(H.sha,H);const S=F.map(H=>({...H,entities:(H.currentEntityShas||[]).map(re=>O.get(re)).filter(re=>re!=null)})),$=ka(),I=($==null?void 0:$.cliVersion)??"unknown",K=I!=="unknown"&&I!==xi,q=((u=(d=N.metadata)==null?void 0:d.labs)==null?void 0:u.simulations)??!1,J=q?_0():!1,z=((p=N.metadata)==null?void 0:p.editorMode)??!1,B={currentRun:(h=k==null?void 0:k.metadata)==null?void 0:h.currentRun,projectSlug:x,currentEntities:R,availableAPIKeys:L,queuedJobCount:T.length,queueJobs:T,currentlyExecuting:M,historicalRuns:S,isServerOutOfDate:K,serverVersion:I,npmUpdate:v!=null&&v.updateAvailable&&v.latestVersion?{latestVersion:v.latestVersion,currentVersion:v.currentVersion}:null,labs:((m=N.metadata)==null?void 0:m.labs)??null,simulationsEnabled:q,isSimulationsReady:J,isAdmin:!!process.env.CODEYAM_ADMIN,editorMode:z,displayVersion:bi()};return ue(B)}catch(f){return f instanceof Response&&f.status===499||console.error("Failed to load root data:",f),ue(iy)}}function cy(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:s,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:l,isServerOutOfDate:d,serverVersion:u,npmUpdate:p,labs:h,simulationsEnabled:m,isSimulationsReady:f,isAdmin:y,editorMode:g,displayVersion:x}=lt(),{toasts:b,closeToast:v}=pi(),N=Ut(),w=be(N),C=Qr(),k=be(C.pathname);se(()=>{w.current=N},[N]),se(()=>{k.current=C.pathname},[C.pathname]);const j=C.pathname.startsWith("/entity/")&&C.pathname.includes("/edit/")||C.pathname.startsWith("/dev/")||C.pathname.startsWith("/editor"),A=C.pathname.includes("/fullscreen")||C.pathname.startsWith("/editor");return se(()=>{let _=null,M=null,T=0;function D(){_||(_=new EventSource("/api/events"),_.addEventListener("message",U=>{const W=JSON.parse(U.data);(W.type==="queue"||W.type==="db-change")&&W.type;const V=rf(k.current),F=sf({now:Date.now(),lastRevalidation:T,throttleMs:V});F==="immediate"?(w.current.revalidate(),T=Date.now()):(M&&clearTimeout(M),M=setTimeout(()=>{w.current.revalidate(),T=Date.now(),M=null},F.delayMs))}),_.addEventListener("error",()=>{}))}function R(){M&&(clearTimeout(M),M=null),_&&(_.close(),_=null)}function L(){document.hidden?R():(D(),w.current.revalidate())}return document.hidden||D(),document.addEventListener("visibilitychange",L),()=>{document.removeEventListener("visibilitychange",L),R()}},[]),c(we,{children:[c("div",{className:`min-h-screen ${j?"":"grid"} bg-cygray-10`,style:j?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!j&&n(uf,{labs:h,isAdmin:y,editorMode:g}),c("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[d&&n(D0,{serverVersion:u}),p&&p.currentVersion&&n(R0,{currentVersion:p.currentVersion,latestVersion:p.latestVersion}),m&&!g&&s.length===0&&n(Zl,{text:"No AI API keys configured. Please provide an AI API key at your earliest convenience.",subtext:"An API key is required for stable, frequent use of CodeYam",linkText:"Configure API Keys",linkTo:"/settings"}),m&&!g&&!f&&n(Zl,{text:"Simulations enabled but not yet configured",subtext:"Run /codeyam-setup in Claude Code to install the analyzer and configure your dev server",linkText:"View Labs",linkTo:"/labs"}),n("div",{className:"flex-1",children:n($d,{})}),n(F0,{version:x})]})]}),n(mf,{toasts:b,onClose:v}),!A&&m&&n(ff,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:l})]})}const dy=tt(function(){return c("html",{lang:"en",children:[c("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(Ih,{}),n(Oh,{})]}),c("body",{children:[n(pf,{children:n(cf,{children:n(cy,{})})}),n(Lh,{}),n(Bh,{})]})]})});function uy(e){if(e instanceof TypeError&&/fetch/i.test(e.message)||e instanceof Error&&/fetch/i.test(e.message))return!0;const t=String(e);return/failed to fetch|fetch.*failed|load.*chunk/i.test(t)}const py=zh(function(){const t=Yh(),r=!eo(t)&&uy(t),s=eo(t)?t.status:500,a=eo(t)?t.statusText||"Server Error":"Something went wrong";return c("html",{lang:"en",children:[c("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),c("title",{children:[s," - CodeYam"]})]}),n("body",{style:{margin:0,fontFamily:'"IBM Plex Sans", system-ui, -apple-system, sans-serif',backgroundColor:"#1e1e1e",color:"#ffffff",minHeight:"100vh",display:"flex",alignItems:"center"},children:c("div",{style:{maxWidth:700,width:"100%",padding:"64px 80px"},children:[c("div",{style:{fontFamily:'"IBM Plex Mono", monospace',fontSize:32,fontWeight:400,color:"#8E8E8E",lineHeight:1,marginBottom:12},children:["<",s,">"]}),n("h1",{style:{fontSize:42,fontWeight:600,margin:"0 0 20px",color:"#ffffff",lineHeight:1.2},children:r?"Something went wrong :(":a}),r?c("div",{children:[n("p",{style:{fontSize:16,color:"#8E8E8E",lineHeight:1.7,margin:"0 0 28px",maxWidth:480},children:"It looks like the CodeYam server is no longer running. This usually happens when the terminal session that started it was closed."}),c("p",{style:{fontSize:16,color:"#ffffff",margin:0,lineHeight:1.7,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["Run"," ",c("button",{id:"copy-cmd-btn",type:"button",style:{display:"inline-flex",alignItems:"center",gap:8,backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:6,padding:"6px 12px",fontFamily:'"IBM Plex Mono", monospace',fontSize:13,color:"#ffffff",letterSpacing:"0.05em",textTransform:"uppercase",cursor:"pointer",minWidth:172,justifyContent:"center"},children:[n("span",{id:"copy-cmd-label",children:"codeyam editor"}),c("svg",{id:"copy-cmd-icon",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#D7FF63",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})," ","in your project directory to restart the server. Then refresh this page."]}),n("script",{dangerouslySetInnerHTML:{__html:`
45
+ document.getElementById('copy-cmd-btn').addEventListener('click', function() {
46
+ var label = document.getElementById('copy-cmd-label');
47
+ var icon = document.getElementById('copy-cmd-icon');
48
+ navigator.clipboard.writeText('codeyam editor').then(function() {
49
+ label.textContent = 'copied!';
50
+ icon.style.display = 'none';
51
+ setTimeout(function() {
52
+ label.textContent = 'codeyam editor';
53
+ icon.style.display = '';
54
+ }, 2000);
55
+ });
56
+ });
57
+ `}})]}):c("div",{children:[n("p",{style:{fontSize:16,color:"#8E8E8E",lineHeight:1.7,margin:"0 0 28px",maxWidth:480},children:"An unexpected error occurred. Try refreshing the page."}),t instanceof Error&&t.message&&n("pre",{style:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:8,padding:"16px 20px",fontFamily:'"IBM Plex Mono", monospace',fontSize:13,color:"#8E8E8E",textAlign:"left",overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:t.message})]})]})})]})}),hy=Object.freeze(Object.defineProperty({__proto__:null,ErrorBoundary:py,default:dy,links:oy,loader:ly},Symbol.toStringTag,{value:"Module"}));function Cs(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}async function ec(e,t){try{await fetch("/api/interactive-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e,scenarioName:t})})}catch(r){console.error("[useInteractiveMode] Failed to seed scenario:",r)}}function Un({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:o=!0,refreshTrigger:i=0}){const l=Ke(),[d,u]=E(null),[p,h]=E(!1),[m,f]=E(!1),[y,g]=E(!1),x=be(!1),b=be(void 0),v=be(null),N=be(null),w=be(null),C=be(null),[k,j]=E(0),[A,_]=E(0),M=be(null),T=be(!1),D=be(!1),R=be(r),{interactiveUrl:L,scenarioUrlMap:U,resetLogs:W}=Xt(a,o),V=be(t);se(()=>{R.current=r},[r]);const F=be(i);se(()=>{F.current!==i&&(F.current=i,d&&(f(!0),g(!1),j(0),_(S=>S+1),T.current=!1,D.current=!1,M.current&&(clearTimeout(M.current),M.current=null)))},[i,d]),se(()=>{if(V.current===t||(V.current=t,!d||!t))return;f(!0),g(!1),j(0),T.current=!1,D.current=!1,R.current=r,M.current&&(clearTimeout(M.current),M.current=null),(async()=>{await ec(t,r);const $=v.current;let I;if($&&$[t])I=$[t]+"?width=600px";else if(N.current&&w.current&&r){if(I=N.current,C.current&&s){const J=Cs(C.current),z=Cs(s);J!==z&&(I=I.replace(J,z))}const K=Cs(w.current),q=Cs(r);I=I.replace(K,q)}else I=d;u(I),_(K=>K+1)})()},[t,r,s,d]),se(()=>{if(L){const S=L+"?width=600px";U&&(v.current=U),N.current=S,r&&(w.current=r),s&&(C.current=s),h(!1),f(!0),(async()=>{t&&r&&await ec(t,r);const I=v.current,K=t&&I&&I[t]?I[t]+"?width=600px":S;u(K)})()}},[L]);const Y=()=>{g(!0),b.current=t;const S=R.current;requestAnimationFrame(()=>{requestAnimationFrame(()=>{R.current===S&&f(!1)})})};se(()=>{const S=$=>{if($.data.type==="codeyam-resize"){if($.data.name&&R.current&&$.data.name!==R.current)return;T.current||(T.current=!0,M.current&&(clearTimeout(M.current),M.current=null),j(0),D.current&&Y())}};return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[]);const P=()=>{if(D.current=!0,T.current){Y();return}M.current&&clearTimeout(M.current);const S=300*Math.pow(2,k);M.current=setTimeout(()=>{T.current||(k<2?(j($=>$+1),_($=>$+1),f(!0),D.current=!1):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),Y()))},S)};se(()=>{o&&!x.current&&t&&e&&(x.current=!0,h(!0),g(!1),u(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch($){console.error("[useInteractiveMode] Failed to clear log file:",$)}W(),l.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[o,t,e,W,a]),se(()=>{const S=e,$=()=>{if(x.current&&S){const K=new URLSearchParams({action:"stop",analysisId:S});navigator.sendBeacon("/api/interactive-mode",K)||fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:K,keepalive:!0}).catch(J=>console.error("Failed to stop interactive mode:",J))}},I=()=>{$()};return window.addEventListener("beforeunload",I),()=>{window.removeEventListener("beforeunload",I),$()}},[e]);const O=y&&b.current===t;return{interactiveServerUrl:d,isStarting:p,isLoading:m,showIframe:O,iframeKey:A,onIframeLoad:P}}const ks=10,my=1024;function Ni({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:s,onHoverChange:a,hideLabel:o=!1,lightMode:i=!1}){const[l,d]=E(null),u=be(null),p=fe(()=>[...s].sort((v,N)=>v.width-N.width),[s]),{fittingPresets:h,overflowPresets:m}=fe(()=>{const v=[],N=[];for(const w of p)w.width<=my?v.push(w):N.push(w);return N.sort((w,C)=>C.width-w.width),{fittingPresets:v,overflowPresets:N}},[p]),f=le(v=>{if(!u.current)return null;const N=u.current.getBoundingClientRect(),w=v-N.left,C=N.width,k=C/2,A=(h.length>0?h[h.length-1].width:0)/2,_=k-A,M=k+A,T=m.length>0?(m.length-1)*ks:0;if(m.length>0){if(w<_){if(w<=T){const R=Math.min(Math.floor(w/ks),m.length-1);return m[R]}return m[m.length-1]}if(w>M){const R=C-w;if(R<=T){const L=Math.min(Math.floor(R/ks),m.length-1);return m[L]}return m[m.length-1]}}const D=Math.abs(w-k);for(let R=h.length-1;R>=0;R--){const L=h[R],U=h[R-1],W=L.width/2,V=U?U.width/2:0;if(D<=W&&D>=V)return L}return h[0]||m[m.length-1]||null},[h,m]),y=le(v=>{const N=f(v.clientX);d(N),a==null||a(N)},[f,a]),g=le(()=>{d(null),a==null||a(null)},[a]),x=le(v=>{const N=f(v.clientX);N&&r(N)},[f,r]),b=l||{name:t,width:e};return c("div",{ref:u,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:y,onMouseLeave:g,onClick:x,children:[l&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:n("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${l.width}px`}})}),n("div",{className:"absolute inset-0 pointer-events-none",children:h.map(v=>{const N=v.width===e,w=(l==null?void 0:l.name)===v.name,C=v.width/2;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${C}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${C}px)`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${N||w?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},v.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:m.map((v,N)=>{const w=N*ks,C=v.width===e,k=(l==null?void 0:l.name)===v.name;return c("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||k?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),n("div",{className:"absolute top-0 bottom-0",style:{right:`${w}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||k?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},v.name)})}),!o&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:c("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${l?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[b.name," - ",b.width,"px"]})})]})}function fy({currentWidth:e,currentHeight:t,devicePresets:r,customSizes:s,onApply:a,onSave:o,onRemove:i,onClose:l}){const[d,u]=E(String(e)),[p,h]=E(String(t)),[m,f]=E(""),[y,g]=E(!1),x=be(null),b=be(null);se(()=>{const _=M=>{x.current&&!x.current.contains(M.target)&&l()};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[l]),se(()=>{const _=M=>{M.key==="Escape"&&l()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[l]),se(()=>{var _;(_=b.current)==null||_.select()},[]);const v=parseInt(d,10),N=parseInt(p,10),w=v>0&&N>0,C=w&&(v!==e||N!==t),k=()=>{w&&(a({name:"Custom",width:v,height:N}),l())},j=()=>{const _=m.trim();!_||!w||(o(_,v,N),a({name:_,width:v,height:N}),l())},A=_=>{_.key==="Enter"&&(y&&m.trim()?j():C&&k())};return c("div",{ref:x,className:"absolute top-full mt-1 right-0 bg-[#2a2a2a] border border-[#444] rounded-lg shadow-xl z-50 w-64",children:[r&&r.length>0&&c("div",{className:"border-b border-[#444]",children:[n("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-gray-500",children:"Presets"}),r.map(_=>c("button",{onClick:()=>{a(_),l()},className:`w-full px-3 py-1.5 text-left text-xs transition-colors cursor-pointer ${_.width===e&&_.height===t?"text-white bg-[#444]":"text-gray-300 hover:text-white hover:bg-[#333]"}`,children:[n("span",{className:"font-medium",children:_.name}),c("span",{className:"text-gray-500 ml-1.5",children:[_.width,"×",_.height]})]},_.name))]}),s.length>0&&c("div",{className:"border-b border-[#444]",children:[n("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wider text-gray-500",children:"Saved Sizes"}),s.map(_=>c("div",{className:"flex items-center group hover:bg-[#333] transition-colors",children:[c("button",{onClick:()=>{a(_),l()},className:"flex-1 px-3 py-1.5 text-left text-xs text-gray-300 hover:text-white transition-colors cursor-pointer",children:[n("span",{className:"font-medium",children:_.name}),c("span",{className:"text-gray-500 ml-1.5",children:[_.width,"×",_.height]})]}),n("button",{onClick:()=>i(_.name),className:"px-2 py-1.5 text-gray-600 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-all cursor-pointer",title:"Remove",children:n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M18 6L6 18M6 6l12 12"})})})]},_.name))]}),c("div",{className:"p-3",children:[c("div",{className:"flex items-center gap-2 mb-2",children:[n("input",{ref:b,type:"number",value:d,onChange:_=>u(_.target.value),onKeyDown:A,min:"100",max:"7680",className:"w-full px-2 py-1.5 bg-[#1a1a1a] border border-[#555] rounded text-xs text-white text-center focus:outline-none focus:border-[#007a99] [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",placeholder:"Width"}),n("span",{className:"text-gray-500 text-xs flex-shrink-0",children:"×"}),n("input",{type:"number",value:p,onChange:_=>h(_.target.value),onKeyDown:A,min:"100",max:"7680",className:"w-full px-2 py-1.5 bg-[#1a1a1a] border border-[#555] rounded text-xs text-white text-center focus:outline-none focus:border-[#007a99] [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",placeholder:"Height"})]}),c("div",{className:"flex gap-2",children:[n("button",{onClick:k,disabled:!w||!C,className:"flex-1 px-2 py-1.5 bg-[#007a99] text-white text-xs font-medium rounded hover:bg-[#006080] transition-colors cursor-pointer disabled:bg-[#333] disabled:text-gray-600 disabled:cursor-not-allowed",children:"Apply"}),y?c("div",{className:"flex gap-1",children:[n("input",{type:"text",value:m,onChange:_=>f(_.target.value),onKeyDown:A,placeholder:"Name",className:"w-20 px-2 py-1.5 bg-[#1a1a1a] border border-[#555] rounded text-xs text-white focus:outline-none focus:border-[#007a99]",autoFocus:!0}),n("button",{onClick:j,disabled:!m.trim()||!w,className:"px-2 py-1.5 bg-[#007a99] text-white text-xs rounded hover:bg-[#006080] transition-colors cursor-pointer disabled:bg-[#333] disabled:text-gray-600 disabled:cursor-not-allowed",children:"OK"})]}):n("button",{onClick:()=>g(!0),disabled:!w,className:"px-2 py-1.5 bg-[#333] text-gray-300 text-xs rounded hover:bg-[#444] transition-colors cursor-pointer disabled:text-gray-600 disabled:cursor-not-allowed",title:"Save as preset",children:"Save"})]})]})]})}function Si({width:e,height:t,onSave:r,onCancel:s}){const[a,o]=E(""),[i,l]=E(""),d=()=>{const u=a.trim();if(!u){l("Please enter a name");return}r(u)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[c("div",{className:"flex items-center justify-between mb-6",children:[n("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),n("button",{onClick:s,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:n("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),c("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[n("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),c("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),c("div",{className:"mb-6",children:[n("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),n("input",{id:"custom-size-name",type:"text",value:a,onChange:u=>{o(u.target.value),l("")},onKeyDown:u=>{u.key==="Enter"&&a.trim()&&d(),u.key==="Escape"&&s()},placeholder:"e.g., iPhone 15 Pro",className:`w-full px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] ${i?"border-red-300":"border-gray-300"}`,autoFocus:!0}),i&&n("p",{className:"mt-1 text-sm text-red-600",children:i})]}),c("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:s,className:"px-4 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-md hover:bg-gray-200 transition-colors cursor-pointer",children:"Cancel"}),n("button",{onClick:d,disabled:!a.trim(),className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function ja(e){const[t,r]=E([]),s=e?`codeyam-custom-sizes-${e}`:null;se(()=>{if(!s||typeof window>"u"){r([]);return}try{const l=localStorage.getItem(s);if(l){const d=JSON.parse(l);Array.isArray(d)&&r(d)}}catch(l){console.error("[useCustomSizes] Failed to load custom sizes:",l),r([])}},[s]);const a=le(l=>{if(!(!s||typeof window>"u"))try{localStorage.setItem(s,JSON.stringify(l))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[s]),o=le((l,d,u)=>{r(p=>{const h=p.findIndex(y=>y.name===l),m={name:l,width:d,height:u};let f;return h>=0?(f=[...p],f[h]=m):f=[...p,m],a(f),f})},[a]),i=le(l=>{r(d=>{const u=d.filter(p=>p.name!==l);return a(u),u})},[a]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function Qt(){return c("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
58
+ .loader {
59
+ width: 48px;
60
+ height: 48px;
61
+ border: 3px solid rgba(0, 92, 117, 0.2);
62
+ border-radius: 50%;
63
+ display: inline-block;
64
+ position: relative;
65
+ box-sizing: border-box;
66
+ animation: rotation 1s linear infinite;
67
+ }
68
+ .loader::after {
69
+ content: '';
70
+ box-sizing: border-box;
71
+ position: absolute;
72
+ left: 50%;
73
+ top: 50%;
74
+ transform: translate(-50%, -50%);
75
+ width: 56px;
76
+ height: 56px;
77
+ border-radius: 50%;
78
+ border: 3px solid;
79
+ border-color: #005c75 transparent;
80
+ }
81
+
82
+ @keyframes rotation {
83
+ 0% {
84
+ transform: rotate(0deg);
85
+ }
86
+ 100% {
87
+ transform: rotate(360deg);
88
+ }
89
+ }
90
+ `})]})}const tc=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],gy=80;function lr(){const[e,t]=E(0);return se(()=>{const r=setInterval(()=>{t(s=>(s+1)%tc.length)},gy);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:tc[e]})}async function yy({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw ue("Invalid parameters",{status:400});const s=await Ln(t);if(!s)throw ue("Entity not found",{status:404});const a=await ba(s),o=((l=a==null?void 0:a.scenarios)==null?void 0:l.find(d=>d.id===r))||null;if(!o)throw ue("Scenario not found",{status:404});const i=await ze();return ue({entity:s,scenario:o,analysis:a,projectSlug:i})}const po=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1920,height:1080}],xy=tt(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=lt(),o=Yt(),[i]=dr(),[l,d]=E(null),[u,p]=E(1920),[h,m]=E({name:"Desktop",width:1920,height:1080}),[f,y]=E(!1),[g,x]=E(null),{customSizes:b,addCustomSize:v}=ja(a),N=fe(()=>[...po,...b],[b]),w=be(null),[C,k]=E(1),j=le(()=>{if(!w.current)return;const z=32,B=w.current.clientWidth-z,H=w.current.clientHeight-z,re=h.width,ae=h.height??900,X=Math.min(1,B/re,H/ae);k(X)},[h.width,h.height]);se(()=>(j(),window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)),[j]);const{interactiveServerUrl:A,isStarting:_,isLoading:M,showIframe:T,iframeKey:D,onIframeLoad:R}=Un({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0}),{lastLine:L}=Xt(a,_||M),U=()=>{o(`/entity/${t.sha}`)},W=(z,B)=>{p(z);const H=N.find(ae=>ae.width===z&&ae.height===B);d(H||null),m({name:(H==null?void 0:H.name)||"Custom",width:z,height:B})},V=z=>{d(z),p(z.width),m({name:z.name,width:z.width,height:z.height})},F=z=>{v(z,h.width,h.height??900),y(!1),m(B=>({...B,name:z}))},Y=((s==null?void 0:s.scenarios)||[]).filter(z=>{var B;return!((B=z.metadata)!=null&&B.sameAsDefault)}),P=Y.findIndex(z=>z.id===(r==null?void 0:r.id)),O=P+1,S=Y.length,$=P>0,I=P<Y.length-1,K=()=>{if($){const z=Y[P-1],B=encodeURIComponent(`/entity/${t.sha}/scenarios/${z.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${z.id}/fullscreen?from=${B}`)}},q=()=>{if(I){const z=Y[P+1],B=encodeURIComponent(`/entity/${t.sha}/scenarios/${z.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${z.id}/fullscreen?from=${B}`)}},J=_||M||!T;return c("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[c("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:fa,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),c("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:K,disabled:!$,className:`${$?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:"text-gray-400 text-sm",children:[O,"/",S]}),n("button",{onClick:q,disabled:!I,className:`${I?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),c("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&c("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]})]}),n("button",{onClick:U,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),c("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${po[po.length-1].width}px`,width:"100%"},children:n(Ni,{currentViewportWidth:u,currentPresetName:h.name,onDevicePresetClick:V,devicePresets:N,hideLabel:!0,onHoverChange:x,lightMode:!0})})}),c("div",{className:"relative z-10 flex items-center gap-2",children:[c("div",{className:"relative w-28 h-5",children:[c("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(g==null?void 0:g.name)||h.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),c("select",{value:h.name,onChange:z=>{const B=N.find(H=>H.name===z.target.value);B&&V(B)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[N.map(z=>n("option",{value:z.name,children:z.name},z.name)),h.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:h.width,onChange:z=>{const B=parseInt(z.target.value,10);!isNaN(B)&&B>0&&W(B,h.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:h.height??900}),h.name==="Custom"&&n("button",{onClick:()=>y(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{ref:w,className:"flex-1 flex items-center justify-center overflow-hidden p-4",style:{backgroundImage:`
91
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
92
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
93
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
94
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
95
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:A?c("div",{className:"relative bg-white",style:{width:`${h.width}px`,height:`${h.height??900}px`,transform:`scale(${C})`,transformOrigin:"center center"},children:[J&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Qt,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),L&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(lr,{}),L]})]})]})}),n("iframe",{src:A,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:R,style:{opacity:T?1:0}},D)]}):c("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Qt,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),L&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(lr,{}),L]})]})]})}),f&&n(Si,{width:h.width,height:h.height??900,onSave:F,onCancel:()=>y(!1)})]})}),by=Object.freeze(Object.defineProperty({__proto__:null,default:xy,loader:yy},Symbol.toStringTag,{value:"Module"})),sr={sound:"soft-double-tap",systemNotification:!0},vy=[{id:"soft-double-tap",label:"Soft double tap"},{id:"gentle-chime",label:"Gentle chime"},{id:"warm-ding",label:"Warm ding"},{id:"mellow-two-tone",label:"Mellow two-tone"},{id:"triangle-bell",label:"Triangle bell"},{id:"off",label:"No sound"}],Nu="codeyam-editor-notifications";function wy(){try{const e=localStorage.getItem(Nu);if(!e)return sr;const t=JSON.parse(e);return typeof t=="string"?t==="true"?sr:{...sr,sound:"off",systemNotification:!1}:{...sr,...t}}catch{return sr}}function Ny(e){localStorage.setItem(Nu,JSON.stringify(e))}function Su(e){var t;if(e!=="off")try{const r=new AudioContext,s={"soft-double-tap":a=>{[0,.12].forEach(o=>{const i=a.createOscillator(),l=a.createGain();i.connect(l),l.connect(a.destination),i.type="sine",i.frequency.value=392,l.gain.setValueAtTime(.25,a.currentTime+o),l.gain.exponentialRampToValueAtTime(.01,a.currentTime+o+.1),i.start(a.currentTime+o),i.stop(a.currentTime+o+.1)})},"gentle-chime":a=>{const o=a.createOscillator(),i=a.createGain();o.connect(i),i.connect(a.destination),o.type="sine",o.frequency.setValueAtTime(523,a.currentTime),o.frequency.setValueAtTime(659,a.currentTime+.15),i.gain.setValueAtTime(.3,a.currentTime),i.gain.exponentialRampToValueAtTime(.01,a.currentTime+.4),o.start(),o.stop(a.currentTime+.4)},"warm-ding":a=>{const o=a.createOscillator(),i=a.createGain();o.connect(i),i.connect(a.destination),o.type="sine",o.frequency.value=330,i.gain.setValueAtTime(.35,a.currentTime),i.gain.exponentialRampToValueAtTime(.01,a.currentTime+.6),o.start(),o.stop(a.currentTime+.6)},"mellow-two-tone":a=>{const o=a.createOscillator(),i=a.createGain();o.connect(i),i.connect(a.destination),o.type="sine",o.frequency.setValueAtTime(294,a.currentTime),o.frequency.setValueAtTime(440,a.currentTime+.18),i.gain.setValueAtTime(.3,a.currentTime),i.gain.exponentialRampToValueAtTime(.01,a.currentTime+.5),o.start(),o.stop(a.currentTime+.5)},"triangle-bell":a=>{const o=a.createOscillator(),i=a.createGain();o.connect(i),i.connect(a.destination),o.type="triangle",o.frequency.value=523,i.gain.setValueAtTime(.4,a.currentTime),i.gain.exponentialRampToValueAtTime(.01,a.currentTime+.8),o.start(),o.stop(a.currentTime+.8)}};(t=s[e])==null||t.call(s,r)}catch{}}function Cu({serverUrl:e,isStarting:t,projectSlug:r,devServerError:s,onStartServer:a,notificationSettings:o,onChangeNotificationSettings:i}){const[l,d]=E(null),[u,p]=E(!1),h=be(null),m=be(null);se(()=>{if(!r)return;const b=new EventSource("/api/dev-mode-events");return b.onmessage=v=>{try{const N=JSON.parse(v.data);N.type==="file-synced"&&(d(N.fileName),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{d(null)},5e3))}catch{}},()=>{b.close(),m.current&&clearTimeout(m.current)}},[r]),se(()=>{if(!u)return;function b(v){h.current&&!h.current.contains(v.target)&&p(!1)}return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[u]);let f;s?f="error":t?f="starting":e?f="running":f="stopped";const y={starting:"bg-yellow-400",running:"bg-green-400",stopped:"bg-gray-400",error:"bg-red-400"},g={starting:"Starting...",running:e||"Running",stopped:"Stopped",error:"Error"},x=o&&(o.sound!=="off"||o.systemNotification);return c("div",{className:"bg-[#1e1e1e] border-t border-[#3d3d3d] h-7 flex items-center px-4 gap-4 shrink-0 text-xs font-mono",children:[c("div",{className:"flex items-center gap-2",children:[n("div",{className:`w-2 h-2 rounded-full ${y[f]}`}),c("span",{className:"text-gray-400",children:["Server:"," ",n("span",{className:"text-gray-300",children:g[f]})]}),(f==="stopped"||f==="error")&&a&&n("button",{onClick:a,className:"ml-1 px-2.5 py-0.5 bg-[#005c75] hover:bg-[#007a9a] text-white text-[11px] font-medium rounded transition-colors cursor-pointer border-none leading-tight",children:"Start Server"})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"}),l&&c(we,{children:[c("div",{className:"flex items-center gap-1.5",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"#4ade80",strokeWidth:"2",children:n("path",{d:"M20 6L9 17l-5-5"})}),c("span",{className:"text-green-400",children:["Synced: ",l]})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"})]}),n("div",{className:"flex-1"}),i&&o&&c("div",{className:"relative",ref:h,children:[n("button",{onClick:()=>p(!u),className:`text-[11px] rounded transition-colors cursor-pointer ${x?"text-cygreen hover:text-cygreen/80":"text-gray-500 hover:text-gray-300"}`,children:x?"Notifications On":"Notifications Off"}),u&&c("div",{className:"absolute bottom-full right-0 mb-2 w-56 bg-[#2d2d2d] border border-[#4d4d4d] rounded-lg shadow-xl p-3 flex flex-col gap-3 z-50",children:[c("div",{children:[n("div",{className:"text-[11px] text-gray-400 mb-1.5",children:"Notification sound"}),n("div",{className:"flex flex-col gap-0.5",children:vy.map(b=>n("button",{onClick:()=>{i({...o,sound:b.id}),b.id!=="off"&&Su(b.id)},className:`text-left text-[11px] px-2 py-1 rounded cursor-pointer transition-colors ${o.sound===b.id?"bg-[#444] text-white":"text-gray-300 hover:bg-[#3a3a3a]"}`,children:b.label},b.id))})]}),c("div",{className:"border-t border-[#4d4d4d] pt-2",children:[c("label",{className:"flex items-center gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:o.systemNotification,onChange:b=>{const v=b.target.checked;i({...o,systemNotification:v}),v&&typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},className:"accent-green-500"}),n("span",{className:"text-[11px] text-gray-300",children:"System notification"})]}),n("div",{className:"text-[10px] text-gray-500 mt-1 ml-5",children:"Shows when tab is not visible"})]})]})]})]})}async function Sy(e,t){try{const{WebglAddon:s}=await import("@xterm/addon-webgl"),a=new s;return a.onContextLoss(()=>{t==null||t("webgl","canvas",new Error("WebGL context lost")),a.dispose(),nc(e).then(o=>{o||t==null||t("canvas","dom",new Error("Canvas fallback failed after context loss"))})}),e.loadAddon(a),{type:"webgl",dispose:()=>a.dispose()}}catch(s){t==null||t("webgl","canvas",s)}const r=await nc(e);return r||(t==null||t("canvas","dom",new Error("Canvas addon failed")),{type:"dom",dispose:()=>{}})}async function nc(e){try{const{CanvasAddon:t}=await import("@xterm/addon-canvas"),r=new t;return e.loadAddon(r),{type:"canvas",dispose:()=>r.dispose()}}catch{return null}}class Cy{constructor(t,r){vt(this,"deferred",!1);vt(this,"userActiveSinceLastOutput",!1);vt(this,"actions");vt(this,"env");this.actions=t,this.env=r}reportUserActivity(){this.userActiveSinceLastOutput=!0}resetActivityFlag(){this.userActiveSinceLastOutput=!1}onIdle(t,r){return this.deferred=!1,r&&this.env.hasBrowserFocus()&&this.userActiveSinceLastOutput?(this.userActiveSinceLastOutput=!1,"suppressed"):this.notify(t)}onBuildTabChange(t,r){return!t&&this.deferred?(this.deferred=!1,this.notify(r),!0):!1}onActive(){this.deferred=!1}onUserEngagement(){const t=this.deferred;return this.deferred=!1,t}get isDeferred(){return this.deferred}notify(t){const r=!!(t!=null&&t.sound)&&t.sound!=="off";return r&&this.actions.playSound(t.sound),!this.env.hasBrowserFocus()&&(t!=null&&t.systemNotification)&&this.env.hasNotificationPermission()&&this.actions.showSystemNotification(),r?"played":"played-no-sound"}}class ky{constructor(t){vt(this,"_isIdle",!1);vt(this,"_isBuilding",!1);vt(this,"callbacks");this.callbacks=t}get isIdle(){return this._isIdle}get isBuilding(){return this._isBuilding}handleClaudeIdle(t,r,s){console.log("[TerminalIdleHandler] claude-idle, building: %s → false",this._isBuilding),t==null||t.onIdle(r,s),this._isIdle=!0,this._isBuilding=!1,this.callbacks.onIdleChange(!0),this.callbacks.onBuildingChange(!1)}handleClaudeActive(t){console.log("[TerminalIdleHandler] claude-active, building: %s → true",this._isBuilding),this._isIdle=!1,this._isBuilding=!0,this.callbacks.onIdleChange(!1),this.callbacks.onBuildingChange(!0),t==null||t.onActive(),t==null||t.resetActivityFlag(),this.callbacks.onCloseNotification()}handleOutput(t){this.callbacks.onIdleChange(!1),t==null||t.resetActivityFlag()}reset(){this._isBuilding&&(console.log("[TerminalIdleHandler] reset, was building: true"),this._isBuilding=!1,this.callbacks.onBuildingChange(!1))}}const jy=`
96
+ .xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
97
+ .xterm.focus, .xterm:focus { outline: none; }
98
+ .xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
99
+ .xterm .xterm-helper-textarea { padding: 0; border: 0; margin: 0; position: absolute; opacity: 0; left: -9999em; top: 0; width: 0; height: 0; z-index: -5; white-space: nowrap; overflow: hidden; resize: none; caret-color: transparent !important; clip-path: inset(100%) !important; }
100
+ .xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
101
+ .xterm .composition-view.active { display: block; }
102
+ .xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
103
+ .xterm .xterm-screen { position: relative; }
104
+ .xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
105
+ .xterm .xterm-scroll-area { visibility: hidden; }
106
+ .xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
107
+ .xterm.enable-mouse-events { cursor: default; }
108
+ .xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
109
+ .xterm.column-select.focus { cursor: crosshair; }
110
+ .xterm .xterm-accessibility:not(.debug), .xterm .xterm-message { position: absolute; left: 0; top: 0; bottom: 0; right: 0; z-index: 10; color: transparent; pointer-events: none; }
111
+ .xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
112
+ .xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
113
+ .xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
114
+ .xterm-dim { opacity: 1 !important; }
115
+ .xterm-underline-1 { text-decoration: underline; }
116
+ .xterm-underline-2 { text-decoration: double underline; }
117
+ .xterm-underline-3 { text-decoration: wavy underline; }
118
+ .xterm-underline-4 { text-decoration: dotted underline; }
119
+ .xterm-underline-5 { text-decoration: dashed underline; }
120
+ .xterm-overline { text-decoration: overline; }
121
+ .xterm-strikethrough { text-decoration: line-through; }
122
+ .xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
123
+ .xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
124
+ .xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
125
+ .xterm-decoration-top { z-index: 2; position: relative; }
126
+ `;function _y(){let e=document.getElementById("xterm-css");e||(e=document.createElement("style"),e.id="xterm-css",document.head.appendChild(e)),e.textContent=jy}const ku=Vh(function({entityName:t,entityType:r,entitySha:s,entityFilePath:a,scenarioName:o,scenarioDescription:i,analysisId:l,projectSlug:d,onRefreshPreview:u,onShowResults:p,onHideResults:h,onSetViewport:m,editorMode:f,onIdleChange:y,onBuildingChange:g,notificationSettings:x,buildTabActive:b,claudeStartMode:v,claudeSessionId:N,onFeatureComplete:w,onDataMutationForwarded:C,resultsOpen:k,editorStepLabel:j},A){const _=be(null),M=be(null),T=be(null),D=be(null),R=be(null),L=be(!1),U=be(0),W=be(!1),V=be(y);V.current=y;const F=be(g);F.current=g;const Y=be(x);Y.current=x;const P=be(b);P.current=b;const O=be(k);O.current=k;const S=be(null),$=be(!1),I=be(null);I.current||(I.current=new Cy({playSound:B=>Su(B),showSystemNotification:()=>{S.current&&S.current.close();const B=new Notification("Claude is ready for you",{body:"Claude has finished and is waiting for your input.",tag:"claude-idle"});B.onclick=()=>{window.focus(),B.close()},S.current=B}},{hasBrowserFocus:()=>document.hasFocus(),hasNotificationPermission:()=>typeof Notification<"u"&&Notification.permission==="granted"}));const K=be(null);K.current||(K.current=new ky({onIdleChange:B=>{var H;$.current=B,(H=V.current)==null||H.call(V,B)},onCloseNotification:()=>{S.current&&(S.current.close(),S.current=null)},onBuildingChange:B=>{var H;(H=F.current)==null||H.call(F,B)}}));function q(){S.current&&(S.current.close(),S.current=null)}function J(){var B,H;$.current&&($.current=!1,q(),(B=V.current)==null||B.call(V,!1),(H=I.current)==null||H.onUserEngagement())}se(()=>{function B(){var X;document.hasFocus()&&P.current&&J(),P.current&&document.hasFocus()&&((X=I.current)==null||X.reportUserActivity())}function H(){!document.hidden&&P.current&&J()}function re(){var X;document.hasFocus()&&P.current&&J(),P.current&&document.hasFocus()&&((X=I.current)==null||X.reportUserActivity())}function ae(){var X;P.current&&J(),P.current&&((X=I.current)==null||X.reportUserActivity())}return window.addEventListener("focus",ae),document.addEventListener("visibilitychange",H),document.addEventListener("mousemove",B),document.addEventListener("mousedown",re),document.addEventListener("keydown",B),()=>{window.removeEventListener("focus",ae),document.removeEventListener("visibilitychange",H),document.removeEventListener("mousemove",B),document.removeEventListener("mousedown",re),document.removeEventListener("keydown",B)}},[]),se(()=>{var B;b&&$.current&&document.hasFocus()&&J(),(B=I.current)==null||B.onBuildTabChange(!!b,Y.current)},[b]);const z=le(()=>{var B;(B=T.current)==null||B.focus()},[]);return Kh(A,()=>({sendInput(B){const H=D.current;H&&H.readyState===WebSocket.OPEN&&(H.send(JSON.stringify({type:"input",data:B})),setTimeout(()=>{H.readyState===WebSocket.OPEN&&H.send(JSON.stringify({type:"input",data:"\r"}))},100))},focus(){var B;(B=T.current)==null||B.focus()},scrollToBottom(){var H;const B=(H=_.current)==null?void 0:H.querySelector(".xterm-viewport");B&&(B.scrollTop=B.scrollHeight)}})),se(()=>{const B=_.current;if(!B)return;let H=!1;return _y(),Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),import("@xterm/addon-web-links")]).then(([re,ae,X])=>{if(H)return;const oe=new re.Terminal({cursorBlink:!1,cursorInactiveStyle:"none",scrollback:5e3,fontSize:13,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#1e1e1e",selectionBackground:"#264f78"},linkHandler:{activate(de,he){try{const _e=new URL(he),ye=_e.searchParams.get("scenario");if(ye&&_e.pathname.startsWith("/editor")){const Re=new BroadcastChannel("codeyam-editor");Re.postMessage({type:"switch-scenario",scenarioId:ye}),Re.close();return}}catch{}window.open(he,"_blank")}}}),me=new ae.FitAddon;oe.loadAddon(me),oe.loadAddon(new X.WebLinksAddon),oe.open(B),oe.attachCustomKeyEventHandler(de=>{if(O.current&&(de.key==="ArrowLeft"||de.key==="ArrowRight")&&!de.ctrlKey&&!de.altKey&&!de.metaKey&&de.type==="keydown"){const he=de.key==="ArrowLeft"?"\x1B[D":"\x1B[C",_e=D.current;return _e&&_e.readyState===WebSocket.OPEN&&_e.send(JSON.stringify({type:"input",data:he})),!1}return!0}),oe.write("\x1B[?25l");let ve=null;Sy(oe,(de,he,_e)=>{console.warn(`[Terminal] Renderer fallback: ${de} → ${he}`,_e)}).then(de=>{if(H){de.dispose();return}console.log(`[Terminal] Using ${de.type} renderer`),ve=de.dispose}),requestAnimationFrame(()=>{try{me.fit()}catch{}}),T.current=oe,oe.focus(),setTimeout(()=>oe.focus(),100),setTimeout(()=>oe.focus(),500);const je=window.location.protocol==="https:"?"wss:":"ws:",te=window.location.host;function ke(de){const he=new URLSearchParams;return he.set("entityName",t),r&&he.set("entityType",r),s&&he.set("entitySha",s),a&&he.set("entityFilePath",a),o&&he.set("scenarioName",o),i&&he.set("scenarioDescription",i),l&&he.set("analysisId",l),d&&he.set("projectSlug",d),f&&he.set("editorMode","true"),de&&he.set("reconnectId",de),v&&he.set("claudeStartMode",v),N&&he.set("claudeSessionId",N),j&&he.set("editorStepLabel",j),`${je}//${te}/ws/terminal?${he.toString()}`}function Z(de){const he=ke(de),_e=new WebSocket(he);D.current=_e,_e.onopen=()=>{U.current=0,W.current=!1,_e.send(JSON.stringify({type:"resize",cols:oe.cols,rows:oe.rows}))},_e.onmessage=ye=>{var Re,Je,bt;try{const Ge=JSON.parse(ye.data);if(Ge.type==="session-id"){R.current=Ge.sessionId;return}if(Ge.type==="refresh-preview"){u==null||u(Ge.path,Ge.scenarioId);return}if(Ge.type==="show-results"){p==null||p();return}if(Ge.type==="hide-results"){h==null||h();return}if(Ge.type==="feature-complete"){w==null||w();return}if(Ge.type==="data-mutation-forwarded"){C==null||C();return}if(Ge.type==="set-viewport"){m==null||m({name:Ge.name,width:Ge.width,height:Ge.height});return}if(Ge.type==="claude-idle"){(Re=K.current)==null||Re.handleClaudeIdle(I.current,Y.current,P.current??!1);return}if(Ge.type==="claude-active"){(Je=K.current)==null||Je.handleClaudeActive(I.current);return}Ge.type==="output"&&(oe.write(Ge.data),(bt=K.current)==null||bt.handleOutput(I.current))}catch{oe.write(ye.data)}},_e.onclose=()=>{var Re,Je;if(console.log("[Terminal] WS closed, intentional=%s",L.current),L.current){oe.write(`\r
127
+ \x1B[90m[Terminal session ended]\x1B[0m\r
128
+ `),(Re=K.current)==null||Re.reset();return}const ye=U.current;if(ye<5&&R.current){const bt=1e3*Math.pow(2,Math.min(ye,3));U.current=ye+1,oe.write(`\r
129
+ \x1B[33m[Reconnecting...]\x1B[0m\r
130
+ `),setTimeout(()=>{L.current||Z(R.current)},bt)}else W.current?(oe.write(`\r
131
+ \x1B[90m[Terminal session ended]\x1B[0m\r
132
+ `),(Je=K.current)==null||Je.reset()):(W.current=!0,oe.write(`\r
133
+ \x1B[33m[Starting new session...]\x1B[0m\r
134
+ `),R.current=null,U.current=0,Z())},_e.onerror=()=>{}}Z(),oe.onData(de=>{const he=D.current;he&&he.readyState===WebSocket.OPEN&&he.send(JSON.stringify({type:"input",data:de})),J()});let pe=null;const ie=new ResizeObserver(()=>{pe&&clearTimeout(pe),pe=setTimeout(()=>{let de;try{de=me.proposeDimensions()}catch{return}if(!de||de.cols===oe.cols&&de.rows===oe.rows)return;const he=B.querySelector(".xterm-viewport");let _e,ye=!0;he&&(_e=he.scrollTop,ye=he.scrollTop+he.clientHeight>=he.scrollHeight-10),me.fit(),he&&_e!==void 0&&(ye?he.scrollTop=he.scrollHeight:he.scrollTop=_e);const Re=D.current;Re&&Re.readyState===WebSocket.OPEN&&Re.send(JSON.stringify({type:"resize",cols:oe.cols,rows:oe.rows}))},150)});ie.observe(B),M.current=()=>{var de;pe&&clearTimeout(pe),ie.disconnect(),L.current=!0,(de=D.current)==null||de.close(),D.current=null,ve==null||ve(),oe.dispose(),T.current=null}}),()=>{var re;H=!0,(re=M.current)==null||re.call(M),M.current=null}},[]),n("div",{ref:_,onClick:z,className:"w-full h-full relative overflow-hidden",style:{padding:"4px 0 0 8px"}})});function ut({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:a}){const[o,i]=E("loading"),[l,d]=E(!1),u=be(null),p=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,h=()=>{i("success"),d(!0)},m=()=>{i("error"),d(!1)};return se(()=>{i("loading"),d(!1);const f=u.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[p]),e?c("div",{className:"relative w-full h-full flex items-center justify-center",title:a,children:[n("img",{ref:u,src:p,alt:r,onLoad:h,onError:m,className:s||"max-w-full max-h-full object-contain",style:{visibility:l?"visible":"hidden",position:l?"relative":"absolute"}}),o==="loading"&&n("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&c("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n("span",{className:"text-2xl text-gray-400",children:"📷"}),n("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:a,children:n("span",{className:"text-2xl text-gray-400",children:"📷"})})}function Ey({scenarios:e,currentScenarioId:t,entitySha:r,cacheBuster:s}){const a=Yt();return e.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8",children:n("p",{className:"text-gray-500 text-sm",children:"No scenarios found"})}):n("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:e.map(o=>{var d,u;const i=o.id===t,l=(u=(d=o.metadata)==null?void 0:d.screenshotPaths)==null?void 0:u[0];return c("button",{onClick:()=>{a(`/entity/${r}/scenarios/${o.id}/dev`)},className:`w-full text-left rounded-lg overflow-hidden border transition-colors cursor-pointer flex ${i?"border-[#005c75] bg-[#1a3a44]":"border-[#3d3d3d] bg-[#252525] hover:border-[#555]"}`,children:[n("div",{className:"w-24 h-20 shrink-0 bg-[#1a1a1a]",children:n(ut,{screenshotPath:l,cacheBuster:s,alt:o.name,className:"w-full h-full object-cover object-top"})}),c("div",{className:"p-2.5 min-w-0 flex-1",children:[c("div",{className:"text-white text-sm font-medium truncate",children:[i&&n("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-[#005c75] mr-1.5 relative top-[-1px]"}),o.name]}),o.description&&n("div",{className:"text-gray-400 text-xs mt-1 line-clamp-2",children:o.description})]})]},o.id)})})}function Ft(e){var l;if(!e.startsWith("app/")&&!e.startsWith("("))return"/";const r=e.replace(/^app\//,"").split("/"),s=r.pop(),a=((l=s.match(/\.(tsx?|jsx?|js)$/))==null?void 0:l[0])||"",o=s.slice(0,-a.length);let i;return o==="page"||o==="index"?i=r:i=[...r,o],i=i.filter(d=>!d.startsWith("(")),i.length===0?"/":"/"+i.join("/")}function Jt(e){return e==="/"?"Home":e.replace(/^\//,"").split("/").map(r=>r.startsWith("[")?r:r.charAt(0).toUpperCase()+r.slice(1)).join(" / ")}function ju(e,t){if(!e)return null;const r=e.split("?")[0].replace(/\/+$/,"")||"/",s=t.map(l=>({filePath:l,pattern:Ft(l)})),a=r==="/"?[]:r.replace(/^\//,"").split("/");let o=null,i=-1;for(const l of s){const d=l.pattern==="/"?[]:l.pattern.replace(/^\//,"").split("/");if(d.length!==a.length)continue;let u=!0,p=0;for(let h=0;h<d.length;h++){const m=d[h],f=a[h];if(!(m.startsWith("[")&&m.endsWith("]")))if(m===f)p++;else{u=!1;break}}u&&p>i&&(i=p,o=l.filePath)}return o}function _u(e,t){const r=new Map;for(const s of e)s.status!=="deleted"&&(t||s.status==="added"||s.status==="untracked"?r.set(s.path,"new"):s.status==="modified"&&r.set(s.path,"edited"));return r}function Ct(e){if(!e||e==="/")return"Home";const t=e.split("?")[0].replace(/^\//,"");if(!t)return"Home";const r=t.split("/")[0].replace(/\.[^.]+$/,"");return r.charAt(0).toUpperCase()+r.slice(1)}function _a(e){return e?e.includes("/isolated-components")||e.includes("/codeyam-isolate"):!1}function rn(e){return e.componentName?e.componentName:e.pageFilePath?Jt(Ft(e.pageFilePath)):Ct(e.url)}function Eu(e,t,r){var o;const s=[],a=new Set;for(const i of e){let l=null,d=null;if(i.componentName&&i.componentPath)l=i.componentName,d=i.componentPath;else if(!i.componentName&&i.pageFilePath)l=i.displayName||(i.pageFilePath.startsWith("app/")?Jt(Ft(i.pageFilePath)):Ct(i.url)),d=i.pageFilePath;else if(!i.componentName&&i.url!==void 0){const u=Ct(i.url);t[u]&&(l=u,d=t[u])}if(l&&d&&!a.has(l)){a.add(l);const u=r.find(p=>p.name===l)||(d?r.find(p=>p.filePath===d):void 0);s.push({name:l,filePath:d,importedBy:(o=u==null?void 0:u.metadata)==null?void 0:o.importedBy})}}return s}function Py(e,t){const r=[],s=new Set(t);for(const a of e)s.has(a.name)||(s.add(a.name),r.push({name:a.name,filePath:a.filePath}));return r}function Ay(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>t[r.name])}function Ty(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>{if("componentName"in r){const a=rn(r);return!!t[a]}const s=r.name.indexOf(" - ");if(s!==-1){const a=r.name.slice(0,s);return!!t[a]}return!!t.Home})}function My(e){const t=new Set,r=new Map;for(const a of e)t.add(a.name),a.filePath&&r.set(a.filePath,a.name);const s=new Map;for(const a of e){const o=a.importedBy;if(!o||typeof o!="object")continue;const i=new Set;for(const l of Object.keys(o))for(const d of Object.keys(o[l]))if(t.has(d))i.add(d);else{const u=r.get(l);u&&u!==a.name?i.add(u):i.add(d)}i.size>0&&s.set(a.name,i)}return s}function $y(e,t){const r=new Map;for(const s of t){const a=e.get(s.filePath);a&&r.set(s.name,a)}return r}const Fy=20;function Pu(e,t,r=Fy){const s={};if(t.length===0||e.size===0)return s;const a=new Map;for(const u of t)a.set(u.name,u);const o=My(t),i=$y(e,t);for(const[u,p]of i)s[u]={status:p};const l=new Map;for(const[u]of i)l.set(u,new Set([u]));const d=[];for(const[u]of i)d.push({name:u,depth:0});for(;d.length>0;){const{name:u,depth:p}=d.shift();if(p>=r)continue;const h=l.get(u)||new Set,m=o.get(u);if(m)for(const f of m){if(!a.has(f))continue;l.has(f)||l.set(f,new Set);const y=l.get(f);let g=!1;for(const x of h)y.has(x)||(y.add(x),g=!0);g&&d.push({name:f,depth:p+1})}}for(const[u,p]of l){if(i.has(u))continue;const h=[];for(const m of p){const f=a.get(m),y=i.get(m);f&&y&&h.push({name:m,filePath:f.filePath,changeType:y})}h.sort((m,f)=>m.name.localeCompare(f.name)),s[u]={status:"impacted",impactedBy:h.length>0?h:void 0}}return s}function Ea(e){if(Array.isArray(e))return e;if(e&&typeof e=="object"){const t=e;for(const s of["components","entries","functions","glossary"]){const a=t[s];if(Array.isArray(a))return a}for(const s of Object.values(t))if(Array.isArray(s))return s;const r=Object.entries(t);if(r.length>0&&r.every(([,s])=>s&&typeof s=="object"&&!Array.isArray(s)))return r.map(([s,a])=>({...a,filePath:s}))}return[]}function Dy(e){return Ea(e).filter(r=>r.testFile&&r.returnType!=="JSX.Element"&&r.returnType!=="React.ReactNode").map(r=>({name:r.name,filePath:r.filePath,description:r.description||"",testFile:r.testFile,feature:r.feature}))}function rc(e,t){var r,s,a,o,i;return t?!!((r=e.metadata)!=null&&r.executionResult):!!((a=(s=e.metadata)==null?void 0:s.screenshotPaths)!=null&&a[0])&&!((o=e.metadata)!=null&&o.noScreenshotSaved)&&!((i=e.metadata)!=null&&i.sameAsDefault)}function Ry(e,t){return e.filter(r=>r.analyses&&r.analyses.length>0).map(r=>{var h;const s=r.analyses[0],a=s.scenarios||[],o=!((h=s.status)!=null&&h.finishedAt),i=r.entityType||"visual",l=i==="library"||i==="functionCall",d=a.filter(m=>rc(m,l)),u=a.filter(m=>!rc(m,l)),p=t.find(m=>m.filePath===(r.filePath||""));return{sha:r.sha,name:r.name,entityType:i,filePath:r.filePath||"",analysisId:s.id,isAnalyzing:o,scenarioCount:a.length,scenarios:d.map(m=>{var f,y;return{id:m.id,name:m.name,description:m.description||"",screenshotPath:((y=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||null}}),pendingScenarios:u.map(m=>m.name),testFile:p==null?void 0:p.testFile}})}function Iy(e,t){var s;const r={};for(const a of e){const i=(((s=a.metadata)==null?void 0:s.importedExports)||[]).map(l=>l.name).filter(l=>t.has(l));i.length>0&&(r[a.name]=i)}return r}function Oy(e,t,r){const s={...e},a=new Map;for(const o of r)o.filePath&&a.set(o.filePath,o.name);for(const[o,i]of Object.entries(t)){if(s[o])continue;const l=a.get(i);l&&s[l]&&(s[o]=s[l])}return s}function Mt(e,t){const r=new Map;for(const s of e)r.set(t(s),s);return[...r.values()]}function It(e){return e.replace(/[^a-zA-Z0-9_]+/g,"_")}function Au(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function rs(e){return e.replace("T"," ").replace(/\.\d{3}Z$/,"")}function Ci(e,t){return!!(e.created_at&&e.created_at>=t||e.updated_at&&e.updated_at>=t)}const Ly=["defaultScreenSize","screenSizes","projectTitle","projectDescription","appFormats"];function Qj(e){try{const t=JSON.parse(ce.readFileSync(e,"utf8")),r={};for(const s of Ly)t[s]!==void 0&&(r[s]=t[s]);return r}catch{return{}}}function By(e){const t=ee.join(e,".codeyam","editor-step.json");try{ce.unlinkSync(t)}catch{}}function ki(e,t,r){const s=e&&e.startsWith("/");return s&&t?`${t}${e}`:e&&!s?e:t||r||null}function zy(e){var t,r;try{const s=ee.join(e,".codeyam","config.json"),a=JSON.parse(ce.readFileSync(s,"utf8"));if(a.screenSizes&&typeof a.screenSizes=="object")for(const o of Object.values(a.screenSizes)){const i=o;if(i.default&&i.width&&i.height)return{width:i.width,height:i.height}}if((t=a.defaultScreenSize)!=null&&t.width&&((r=a.defaultScreenSize)!=null&&r.height))return{width:a.defaultScreenSize.width,height:a.defaultScreenSize.height}}catch{}return null}function ji(e){try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(ce.readFileSync(t,"utf8"));if(r.screenSizes&&typeof r.screenSizes=="object"&&!Array.isArray(r.screenSizes))return r.screenSizes}catch{}return{}}function Yy(e){var t,r;return{width:e.bodyWidth||((t=e.projectDefault)==null?void 0:t.width)||1280,height:e.bodyHeight||((r=e.projectDefault)==null?void 0:r.height)||720}}function Pa(e){let t=null;if(e.dimension){const a=ji(e.codeyamRoot)[e.dimension];a!=null&&a.width&&(a!=null&&a.height)&&(t={width:a.width,height:a.height})}const r=t||zy(e.codeyamRoot);return Yy({bodyWidth:e.bodyWidth,bodyHeight:e.bodyHeight,projectDefault:r})}async function Uy(e,t){const r=t.dimensions?JSON.stringify(t.dimensions):null,s=t.screenshotPaths?JSON.stringify(t.screenshotPaths):null,a=await e.selectFrom("editor_scenarios").selectAll().where("name","=",t.name).where("project_id","=",t.projectId).orderBy("created_at","desc").execute();if(a.length>0){const d=a[0].id,u={description:t.description,component_name:t.componentName,component_path:t.componentPath,url:t.url,type:t.type,viewport_width:t.viewportWidth,viewport_height:t.viewportHeight,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};t.dimensions!==void 0&&(u.dimensions=r,u.screenshot_paths=s),t.pageFilePath!==void 0&&(u.page_file_path=t.pageFilePath),t.entitySha!==void 0&&(u.entity_sha=t.entitySha),t.displayName!==void 0&&(u.display_name=t.displayName),await e.updateTable("editor_scenarios").set(u).where("id","=",d).execute();const p=a.slice(1).map(h=>h.id);return p.length>0&&await e.deleteFrom("editor_scenarios").where("id","in",p).execute(),{scenarioId:d,isNew:!1,cleanedUpIds:p}}const o=globalThis.crypto.randomUUID(),i={id:o,project_id:t.projectId,name:t.name,description:t.description,component_name:t.componentName,component_path:t.componentPath,url:t.url,type:t.type,viewport_width:t.viewportWidth,viewport_height:t.viewportHeight};return t.dimensions!==void 0&&(i.dimensions=r,i.screenshot_paths=s),t.pageFilePath!==void 0&&(i.page_file_path=t.pageFilePath),t.entitySha!==void 0&&(i.entity_sha=t.entitySha),t.displayName!==void 0&&(i.display_name=t.displayName),await e.insertInto("editor_scenarios").values(i).execute(),{scenarioId:o,isNew:!0,cleanedUpIds:[]}}function Wy(e,t){const r=ee.join(e,".codeyam","editor-scenarios"),s=ee.join(r,"screenshots");for(const a of t){for(const o of[`${a}.json`,`${a}.seed.json`,ee.join("screenshots",`${a}.png`)])try{ce.unlinkSync(ee.join(r,o))}catch{}try{const o=ce.readdirSync(s);for(const i of o)if(i.startsWith(`${a}--`)&&i.endsWith(".png"))try{ce.unlinkSync(ee.join(s,i))}catch{}}catch{}}}function Jy(e){const{lookupFilePath:t,scenarioType:r,projectRoot:s}=e;if(r!=="application"&&r!=="user")return{valid:!0};if(!t)return{valid:!0};const a=ee.join(s,".codeyam","glossary.json");let o=[];try{const l=JSON.parse(ce.readFileSync(a,"utf8"));o=Ea(l)}catch{}if(!o.some(l=>l.filePath===t)){const l=o.length===0?` glossary.json is empty or could not be parsed. It must be a JSON array: [{"name": "...", "filePath": "${t}", ...}]`:` Found ${o.length} entries but none with filePath "${t}".`;return{valid:!1,error:`No glossary entry found for '${t}'.${l} Add this file to .codeyam/glossary.json before registering app scenarios.`}}return{valid:!0,needsAnalysis:!0}}function Hy(e){const{componentName:t,url:r}=e;return!t||!r?{valid:!0}:_a(r)?{valid:!0}:{valid:!1,error:`Scenario has componentName "${t}" but URL "${r}" is not an isolation route. Component scenarios must use an isolation URL like /isolated-components/${t}?s=ScenarioName or /codeyam-isolate/${t}?s=ScenarioName. Either change the URL to an isolation route, or remove componentName to register as an application scenario.`}}const Vy=Tu;async function Tu(e,t){const r=new Map,s=new Map;for(const i of t)if(i.filePath){r.set(`${i.name}::${i.filePath}`,i);const l=s.get(i.filePath);(!l||!l.isDefaultExport||i.isDefaultExport)&&s.set(i.filePath,i)}const a=await e.selectFrom("editor_scenarios").selectAll().where(i=>i.or([i("component_path","is not",null),i("page_file_path","is not",null)])).execute();if(a.length===0)return{updated:0};let o=0;for(const i of a){const l=i,d=l.component_path||l.page_file_path;if(!d)continue;const u=l.component_name&&r.get(`${l.component_name}::${d}`)||s.get(d);if(!u||l.entity_sha===u.sha)continue;let p=null;l.component_name?p=l.component_name:l.page_file_path&&l.page_file_path.startsWith("app/")?p=Jt(Ft(l.page_file_path)):l.url&&(p=Ct(l.url)),await e.updateTable("editor_scenarios").set({entity_sha:u.sha,...p?{display_name:p}:{}}).where("id","=",l.id).execute(),o++}return{updated:o}}async function sc(e,t,r){const s=ee.join(e,".codeyam","editor-scenarios"),a=i=>{const l=ee.join(s,`${i}.seed.json`);if(ce.existsSync(l))try{return JSON.parse(ce.readFileSync(l,"utf-8"))}catch{return null}const d=ee.join(s,`${i}.json`);if(ce.existsSync(d))try{return JSON.parse(ce.readFileSync(d,"utf-8")).seed||null}catch{return null}return null},o=a(r);if(o)return o;try{const i=await t.selectFrom("editor_scenarios").select("id").where("name","=",r).orderBy("created_at","desc").limit(1).executeTakeFirst();if(i)return a(i.id)}catch{}return null}function Ky(e){const{activeAnalyzedScenario:t,analyzedPreviewUrl:r,activeScenarioId:s,scenarios:a,proxyUrl:o,devServerUrl:i,zoomComponent:l}=e;if(t&&r)return r;if(t&&!r)return null;if(s){const u=a.find(p=>p.id===s);if(u!=null&&u.url){const p=o||i;return p?u.url.startsWith("/")?`${p}${u.url}`:u.url:null}}const d=o||i;if(!d)return null;if(l&&s){const u=a.find(h=>h.id===s),p=u?It(u.name):"Default";return`${d}/__codeyam__/${l}/${p}`}return d}function Mu(e,t){if(!e||!t)return e;try{const r=new URL(e),s=t.indexOf("?");return s>=0?(r.pathname=t.slice(0,s),r.search=t.slice(s)):(r.pathname=t,r.search=""),r.href}catch{return e}}function Gy(e,t){return e?e!==t:!1}function js(e){if(e.length!==0)return e.find(t=>t.url==="/")||e.find(t=>t.type==="application")||e[0]}function ho(e,t,r){if(!e.viewportWidth||!e.viewportHeight)return r??null;const s=t.find(a=>a.width===e.viewportWidth&&a.height===e.viewportHeight);return{name:(s==null?void 0:s.name)||"Custom",width:e.viewportWidth,height:e.viewportHeight}}function ac(e,t){const r=t.width,s=t.height??900,a=e.width,o=e.height;return r<=a&&s<=o?1:Math.min(a/r,o/s)}async function qy({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw ue("Invalid parameters",{status:400});const s=await Ln(t);if(!s)throw ue("Entity not found",{status:404});const a=await ba(s),o=((l=a==null?void 0:a.scenarios)==null?void 0:l.find(d=>d.id===r))||null;if(!o)throw ue("Scenario not found",{status:404});const i=await ze();return ue({entity:s,scenario:o,analysis:a,projectSlug:i})}const mo=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Qy=tt(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=lt(),o=Yt(),i=be(null),l=be(null),[d,u]=E(null),[p,h]=E(1440),[m,f]=E({name:"Desktop",width:1440,height:900}),[y,g]=E(!1),[x,b]=E(null),[v,N]=E("chat"),[w,C]=E(0),[k,j]=E(null),A=le(oe=>{j(oe||null),C(me=>me+1)},[]),{customSizes:_,addCustomSize:M}=ja(a),T=fe(()=>[...mo,..._],[_]),{interactiveServerUrl:D,isStarting:R,isLoading:L,showIframe:U,iframeKey:W,onIframeLoad:V}=Un({analysisId:s==null?void 0:s.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:a,enabled:!0,refreshTrigger:w}),F=fe(()=>Mu(D,k),[D,k]),{lastLine:Y}=Xt(a,R||L),P=()=>{o(`/entity/${t.sha}`)},O=(oe,me)=>{h(oe);const ve=T.find(te=>te.width===oe&&te.height===me);u(ve||null),f({name:(ve==null?void 0:ve.name)||"Custom",width:oe,height:me})},S=oe=>{u(oe),h(oe.width),f({name:oe.name,width:oe.width,height:oe.height})},$=oe=>{M(oe,m.width,m.height??900),g(!1),f(me=>({...me,name:oe}))},I=()=>{var me;N("chat"),(me=l.current)==null||me.sendInput("Create a new scenario for this entity based on the work we've just done. Create a name and description that reflects what the live preview is showing. Use the scenario data you've changed to create a new scenario in the database. If the data structure was fixed in any way you need to update that in the database as well and backfill all existing scenarios, then save to the database and capture a screenshot. Remember the database is at `.codeyam/db.sqlite3`, the scenarios table has all scenarios and the analyses table contains the scenariosDataStructure is its metadata.")},K=((s==null?void 0:s.scenarios)||[]).filter(oe=>{var me;return!((me=oe.metadata)!=null&&me.sameAsDefault)}),q=K.findIndex(oe=>oe.id===(r==null?void 0:r.id)),J=q+1,z=K.length,B=q>0,H=q<K.length-1,re=()=>{if(B){const oe=K[q-1];o(`/entity/${t.sha}/scenarios/${oe.id}/dev`)}},ae=()=>{if(H){const oe=K[q+1];o(`/entity/${t.sha}/scenarios/${oe.id}/dev`)}},X=R||L||!U;return c("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[c("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:fa,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),c("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:re,disabled:!B,className:`${B?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:"text-gray-400 text-sm",children:[J,"/",z]}),n("button",{onClick:ae,disabled:!H,className:`${H?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),c("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[n("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:r==null?void 0:r.name}),(r==null?void 0:r.description)&&c("div",{className:"relative group min-w-0",children:[n("span",{className:"text-gray-400 text-xs truncate block",children:r.description}),n("div",{className:"absolute left-0 top-full mt-1 hidden group-hover:block z-50 bg-black text-white text-xs px-3 py-2 rounded shadow-lg max-w-md",children:r.description})]})]}),n("span",{className:"bg-[#005c75] text-white text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider ml-2",children:"Dev Mode"})]}),n("button",{onClick:P,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close dev mode",children:n("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:n("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),c("div",{className:"flex-1 flex min-h-0",children:[c("div",{className:"flex-1 flex flex-col min-w-0",children:[c("div",{className:"bg-[#e5e7eb] border-b border-[rgba(0,0,0,0.1)] shrink-0 z-10 h-6 flex items-center justify-center relative",children:[n("div",{className:"absolute inset-0 flex justify-center",children:n("div",{style:{maxWidth:`${mo[mo.length-1].width}px`,width:"100%"},children:n(Ni,{currentViewportWidth:p,currentPresetName:m.name,onDevicePresetClick:S,devicePresets:T,hideLabel:!0,onHoverChange:b,lightMode:!0})})}),c("div",{className:"relative z-10 flex items-center gap-2",children:[c("div",{className:"relative w-28 h-5",children:[c("div",{className:"absolute inset-0 bg-white text-gray-900 text-xs px-2 rounded flex items-center justify-between pointer-events-none border border-gray-300",children:[n("span",{className:"leading-none",children:(x==null?void 0:x.name)||m.name}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),c("select",{value:m.name,onChange:oe=>{const me=T.find(ve=>ve.name===oe.target.value);me&&S(me)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[T.map(oe=>n("option",{value:oe.name,children:oe.name},oe.name)),m.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:m.width,onChange:oe=>{const me=parseInt(oe.target.value,10);!isNaN(me)&&me>0&&O(me,m.height??900)},className:"bg-white text-gray-900 text-xs px-1 rounded border border-gray-300 outline-none w-16 text-center h-5 leading-none",min:"200",max:"3840"}),n("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"x"}),n("span",{className:"bg-gray-100 text-gray-600 text-xs px-1 rounded w-14 text-center h-5 flex items-center justify-center leading-none",children:m.height??900}),m.name==="Custom"&&n("button",{onClick:()=>g(!0),className:"bg-white text-gray-900 text-xs px-2 rounded h-5 flex items-center leading-none border border-gray-300 hover:bg-gray-50 transition-colors",children:"Save"})]})]}),n("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
135
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
136
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
137
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
138
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
139
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:D?c("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${m.width}px`,maxHeight:`${m.height}px`},children:[X&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Qt,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the dev server to be ready"}),Y&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(lr,{}),Y]})]})]})}),n("iframe",{ref:i,src:F||D,className:"w-full h-full border-none",title:`Dev mode preview: ${r==null?void 0:r.name}`,onLoad:V,style:{opacity:U?1:0}},W)]}):c("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Qt,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Dev Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment with live preview"}),Y&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(lr,{}),Y]})]})]})})]}),c("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-l border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden",children:[c("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[c("div",{className:"flex items-center gap-0",children:[c("button",{onClick:()=>N("chat"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${v==="chat"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Chat",v==="chat"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),c("button",{onClick:()=>N("scenarios"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${v==="scenarios"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Scenarios",v==="scenarios"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),v==="chat"&&n("button",{onClick:I,disabled:!D,className:"px-3 py-1 text-[11px] font-medium rounded bg-[#005c75] text-white hover:bg-[#004a5c] transition-colors disabled:bg-gray-600 disabled:text-gray-400 disabled:cursor-not-allowed cursor-pointer",children:"Save Scenario"})]}),n("div",{style:{display:v==="chat"?"flex":"none"},className:"flex-1 overflow-hidden flex-col",children:n(ku,{ref:l,entityName:t.name,entityType:t.entityType,entitySha:t.sha,entityFilePath:t.filePath||t.localFilePath,scenarioName:r==null?void 0:r.name,scenarioDescription:r==null?void 0:r.description,analysisId:s==null?void 0:s.id,projectSlug:a,onRefreshPreview:A})}),v==="scenarios"&&n(Ey,{scenarios:K,currentScenarioId:r==null?void 0:r.id,entitySha:t.sha,cacheBuster:0})]})]}),n(Cu,{serverUrl:D,isStarting:R,projectSlug:a}),y&&n(Si,{width:m.width,height:m.height??900,onSave:$,onCancel:()=>g(!1)})]})}),Zy=Object.freeze(Object.defineProperty({__proto__:null,default:Qy,loader:qy},Symbol.toStringTag,{value:"Module"})),$u=3e4,Xy="seed-session.json";function ex(e){const t={};try{const r=Q.readFileSync(e,"utf-8");for(const s of r.split(`
140
+ `)){const a=s.trim();if(!a||a.startsWith("#"))continue;const o=a.indexOf("=");if(o===-1)continue;const i=a.slice(0,o).trim();let l=a.slice(o+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),i&&(t[i]=l)}}catch{}return t}function Fu(e){const t=[".env",".env.local",".env.development",".env.development.local"];let r={};for(const s of t){const a=ex(G.join(e,s));r={...r,...a}}return r}function Du(e){const t={};try{const r=G.join(e,".codeyam","config.json"),s=JSON.parse(Q.readFileSync(r,"utf-8"));for(const a of s.environmentVariables||[]){const o=a.key||a.name;o&&a.value!==void 0&&(t[o]=a.value)}}catch{}return t}function tx(e){const t=G.join(e,".codeyam","tmp",Xy);try{if(!Q.existsSync(t))return{};const r=Q.readFileSync(t,"utf-8"),s=JSON.parse(r);Q.unlinkSync(t);const a={};return s.cookies&&Array.isArray(s.cookies)&&(a.sessionCookies=s.cookies),s.externalApis&&typeof s.externalApis=="object"&&(a.externalApis=s.externalApis),a}catch{return{}}}function _i(e,t,r){const s=$u,a=G.basename(G.dirname(e))===".codeyam"?G.dirname(G.dirname(e)):G.dirname(e);return new Promise(o=>{const i=Date.now(),l=e.endsWith(".ts");let d,u;if(l){const b=rx(a);b?(d=b,u=[e,t]):(d="npx",u=["tsx",e,t])}else d=e,u=[t];const p=Fu(a),h=Du(a),m=kt(d,u,{cwd:a,env:{...process.env,...p,...h}});let f="",y="",g=!1;const x=setTimeout(()=>{g=!0,m.kill("SIGTERM")},s);m.stdout.on("data",b=>{f+=b.toString()}),m.stderr.on("data",b=>{y+=b.toString()}),m.on("close",b=>{clearTimeout(x);const v=Date.now()-i;if(g)o({success:!1,output:f,error:`Seed adapter timeout after ${s}ms`,durationMs:v});else if(b===0){const N=tx(a);o({success:!0,output:f,durationMs:v,sessionCookies:N.sessionCookies,externalApis:N.externalApis})}else o({success:!1,output:f,error:y||`Seed adapter exited with code ${b}`,durationMs:v})}),m.on("error",b=>{clearTimeout(x),o({success:!1,output:"",error:b.message,durationMs:Date.now()-i})})})}function nx(e,t,r){const s=$u,a=G.basename(G.dirname(e))===".codeyam"?G.dirname(G.dirname(e)):G.dirname(e);return new Promise(o=>{const i=Date.now(),l=e.endsWith(".ts"),d=l?"npx":e,u=l?["tsx",e,"--export",t]:["--export",t],p=Fu(a),h=Du(a),m=kt(d,u,{cwd:a,env:{...process.env,...p,...h}});let f="",y="",g=!1;const x=setTimeout(()=>{g=!0,m.kill("SIGTERM")},s);m.stdout.on("data",b=>{f+=b.toString()}),m.stderr.on("data",b=>{y+=b.toString()}),m.on("close",b=>{clearTimeout(x);const v=Date.now()-i;o(g?{success:!1,output:f,error:`Seed adapter export timeout after ${s}ms`,durationMs:v}:b===0?{success:!0,output:f,durationMs:v}:{success:!1,output:f,error:y||`Seed adapter export exited with code ${b}`,durationMs:v})}),m.on("error",b=>{clearTimeout(x),o({success:!1,output:"",error:b.message,durationMs:Date.now()-i})})})}function Vr(e){const t=["seed-adapter.ts","seed-adapter.js"];for(const r of t){const s=G.join(e,".codeyam",r);try{return Q.accessSync(s),s}catch{}}return null}function rx(e){const t=[G.join(e,"node_modules",".bin","tsx"),G.join(e,"..","node_modules",".bin","tsx")];for(const r of t)try{return Q.accessSync(r,Q.constants.X_OK),r}catch{}return null}function oc(e,t){const r={};for(const[s,a]of Object.entries(e))r[s]=JSON.parse(JSON.stringify(a));for(const[s,a]of Object.entries(t))r[s]=JSON.parse(JSON.stringify(a));return r}let Pn=null;async function Aa(e){const{scenarioId:t,projectRoot:r}=e,s=ee.join(r,".codeyam"),a=ee.join(s,"editor-scenarios");let o=e.scenarioSlug||null;if(!o)try{const m=ee.join(a,`${t}.json`);ce.existsSync(m)?o=JSON.parse(ce.readFileSync(m,"utf-8")).name||t:o=t}catch{o=t}let i=e.scenarioType||null;if(!i)try{const m=ee.join(a,`${t}.json`);ce.existsSync(m)&&(i=JSON.parse(ce.readFileSync(m,"utf-8")).type||null)}catch{}const l=ee.join(s,"active-scenario.json");ce.mkdirSync(s,{recursive:!0}),ce.writeFileSync(l,JSON.stringify({scenarioSlug:o,scenarioName:e.scenarioName||o,scenarioId:t,type:i,dataFile:`.codeyam/editor-scenarios/${t}.json`,switchedAt:new Date().toISOString()},null,2));let d=null,u,p;const h=i==="application"||i==="user";if(h)if(Pn&&Pn.scenarioId===t)d=await Pn.promise;else{const m=Vr(r),f=ee.join(a,`${t}.seed.json`);if(m&&ce.existsSync(f)){const y=_i(m,f).then(g=>({success:g.success,error:g.error,sessionCookies:g.sessionCookies,externalApis:g.externalApis}));Pn={scenarioId:t,promise:y};try{const g=await y;d={success:g.success,error:g.error},u=g.sessionCookies,p=g.externalApis}finally{Pn&&Pn.scenarioId===t&&(Pn=null)}if(d!=null&&d.success){const g=u&&u.length>0,x=p&&Object.keys(p).length>0;if(g||x)try{const b=ee.join(a,`${t}.json`),v=JSON.parse(ce.readFileSync(b,"utf-8"));g&&(v.sessionCookies=u),x&&(v.externalApis={...v.externalApis,...p}),ce.writeFileSync(b,JSON.stringify(v,null,2))}catch{}}}else m||(d={success:!1,error:"No seed adapter found"})}return{success:!0,scenarioSlug:o,scenarioId:t,type:i,seeded:h,...d?{seedResult:d}:{},...u&&u.length>0?{sessionCookies:u}:{}}}function sx(e){return pr.createHash("sha256").update(JSON.stringify(e)).digest("hex")}function ax(e){const t=e.match(/^(GET|POST|PUT|DELETE|PATCH)\s+(\/\S+)$/);return t?{method:t[1],pathPattern:t[2]}:{method:null,pathPattern:e}}function ox(e){const t=[],r=e.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(s,a)=>(t.push(a),"([^/]+)"));return{regex:new RegExp(`^${r}$`),paramNames:t}}function ix(e,t){if(t.includes(e))return e;const r=e.lastIndexOf("/");if(r>0){const s=e.substring(0,r);if(t.includes(s))return s}return null}function lx(){let e=[],t={},r=null,s=null,a=!1,o=null;function i(u){const p=[],h=u.routes;if(h&&typeof h=="object")for(const[m,f]of Object.entries(h)){const{method:y,pathPattern:g}=ax(m),{regex:x,paramNames:b}=ox(g),v=typeof f=="object"&&f!==null?f:{body:f};p.push({method:y,pathPattern:g,pathRegex:x,paramNames:b,response:{body:v.body,status:typeof v.status=="number"?v.status:200}})}return p}function l(u){const p=u.state;if(p&&typeof p=="object"){a=!0,t={};for(const[h,m]of Object.entries(p))t[h]=Array.isArray(m)?JSON.parse(JSON.stringify(m)):[];r=JSON.stringify(p)}else a=!1,t={},r=null}return{loadScenario(u){const p=sx(u);s&&p===s||(s=p,o=u,e=i(u),l(u))},matchRequest(u,p,h){if(!o&&e.length===0&&!a)return null;const m=Object.keys(t);if(a){const y=ix(p,m);if(y&&u==="GET"&&y===p)return{body:t[y],status:200};if(y){const g=d(u,p);if(u==="POST"&&y===p&&g){const x=t[y],b=typeof h=="object"&&h!==null?{...h}:{};if(!("id"in b)){const v=x.reduce((N,w)=>{const C=typeof w.id=="number"?w.id:0;return Math.max(N,C)},0);b.id=v+1}return x.push(b),{body:b,status:g.response.status}}if(u==="DELETE"&&g&&g.params){const x=g.params.id,b=t[y],v=b.findIndex(N=>String(N.id)===String(x));return v===-1?{body:{error:"Not found"},status:404}:(b.splice(v,1),{body:null,status:g.response.status})}if(u==="PUT"&&g&&g.params){const x=g.params.id,b=t[y],v=b.findIndex(w=>String(w.id)===String(x));if(v===-1)return{body:{error:"Not found"},status:404};const N=typeof h=="object"&&h!==null?{...h}:b[v];return b[v]=N,{body:N,status:g.response.status}}}}const f=d(u,p);if(f)return{body:f.response.body??null,status:f.response.status,params:f.params};if(o&&u==="GET"){const y=p.match(/^\/api\/(.+)$/);if(y){const g=y[1];if(g in o&&g!=="routes"&&g!=="state")return{body:o[g],status:200}}}return null},resetState(){if(r){const u=JSON.parse(r);t={};for(const[p,h]of Object.entries(u))t[p]=Array.isArray(h)?JSON.parse(JSON.stringify(h)):[]}},getState(){return{...t}}};function d(u,p){for(const h of e)if(h.method!==null&&h.method===u&&h.paramNames.length===0&&h.pathRegex.exec(p))return{response:h.response};if(u==="GET"){for(const h of e)if(h.method===null&&h.paramNames.length===0&&h.pathRegex.exec(p))return{response:h.response}}for(const h of e)if(h.paramNames.length>0){if((h.method??"GET")!==u)continue;const f=h.pathRegex.exec(p);if(f){const y={};for(let g=0;g<h.paramNames.length;g++)y[h.paramNames[g]]=f[g+1];return{response:h.response,params:y}}}return null}}function cx(e){var a,o;const t=ee.join(e,"package.json");if(!ce.existsSync(t))return{error:"No package.json found."};let r="npm",s=["run","dev"];try{const i=JSON.parse(ce.readFileSync(t,"utf8"));if(ce.existsSync(ee.join(e,"pnpm-lock.yaml"))?r="pnpm":ce.existsSync(ee.join(e,"yarn.lock"))?r="yarn":ce.existsSync(ee.join(e,"bun.lockb"))&&(r="bun"),!((a=i.scripts)!=null&&a.dev))if((o=i.scripts)!=null&&o.start)s=["run","start"];else return{error:'No "dev" or "start" script found in package.json.'}}catch{}return{command:r,args:s}}function dx(e,t){const r=t.toString(),s={PORT:r},a=ee.join(e,".codeyam","config.json");if(ce.existsSync(a))try{const d=(JSON.parse(ce.readFileSync(a,"utf8")).webapps||[])[0];if(d!=null&&d.startCommand){const{command:u,args:p,env:h}=d.startCommand,m=(p||[]).map(f=>f.includes("$PORT")?f.replace(/\$PORT/g,r):f);if(h)for(const[f,y]of Object.entries(h))typeof y=="string"&&y.includes("$PORT")?s[f]=y.replace(/\$PORT/g,r):typeof y=="string"&&(s[f]=y);return{command:u,args:m,env:s}}}catch{}const o=cx(e);return"error"in o?o:{command:o.command,args:o.args,env:s}}function Ru(e){return{proxyPort:e+1,devServerPort:e+2}}const ux=[/Local:\s+(https?:\/\/[^\s]+)/,/Ready on\s+(https?:\/\/[^\s]+)/i,/started at\s+(https?:\/\/[^\s]+)/i,/listening on\s+(https?:\/\/[^\s]+)/i,/waiting on\s+(https?:\/\/[^\s]+)/i,/http:\/\/localhost:\d+/];function px(e){for(const t of ux){const r=e.match(t);if(r){const s=r[1]||r[0];return hx(s).trim()}}return null}function hx(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function Ei(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}async function mx(e,t={}){const{intervalMs:r=2e3,maxAttempts:s=15}=t,a=`http://localhost:${e}`;for(let o=0;o<s;o++){try{const i=await fetch(a,{method:"HEAD",signal:AbortSignal.timeout(2e3)});if(i.ok||i.status===304)return a}catch{}o<s-1&&await new Promise(i=>setTimeout(i,r))}return null}function fx(e){const{exitCode:t,uptime:r,retryCount:s,wasRunning:a}=e,o=r<1e4;return t!==0&&t!==null&&o&&s===0?{action:"retry"}:t!==0&&t!==null?{action:"error"}:a===!1?{action:"error"}:{action:"stopped"}}class gx extends Xr{emitDataMutationForwarded(t,r){this.emit("event",{type:"data-mutation-forwarded",method:t,pathname:r,timestamp:Date.now()})}}const Lo="__codeyam_mock_state_event_emitter__";if(!globalThis[Lo]){const e=new gx;e.setMaxListeners(20),globalThis[Lo]=e}const yx=globalThis[Lo];function xx(e){try{return new URL(e).toString().replace(/\/$/,"")}catch{return e}}async function bx(e){const t=["127.0.0.1","::1"];for(const r of t)try{if(await new Promise(a=>{const o=new Ud.Socket;o.setTimeout(1e3),o.once("connect",()=>{o.destroy(),a(!0)}),o.once("error",()=>{o.destroy(),a(!1)}),o.once("timeout",()=>{o.destroy(),a(!1)}),o.connect(e,r)}))return r}catch{}return null}const Iu="__codeyam_editor_proxy__",Ou="__codeyam_preview_health__";function Lu(){return globalThis[Ou]??null}function Bu(e){globalThis[Ou]=e}function ic(){return Lu()}function zu(){Bu(null)}const vx=`<script data-codeyam-health>
141
+ (function() {
142
+ var errors = [];
143
+ var reported = false;
144
+ function report(type, msg, stack) {
145
+ errors.push({ type: type, message: msg, stack: stack, timestamp: Date.now() });
146
+ if (!reported) {
147
+ reported = true;
148
+ setTimeout(function() { flush(); }, 500);
149
+ }
150
+ }
151
+ function flush() {
152
+ fetch('/__codeyam__/preview-health', {
153
+ method: 'POST',
154
+ headers: { 'Content-Type': 'application/json' },
155
+ body: JSON.stringify({ errors: errors, url: location.href })
156
+ }).catch(function(){});
157
+ reported = false;
158
+ errors = [];
159
+ }
160
+ window.addEventListener('error', function(e) {
161
+ report('error', e.message, e.error && e.error.stack);
162
+ });
163
+ window.addEventListener('unhandledrejection', function(e) {
164
+ report('unhandledrejection', String(e.reason), e.reason && e.reason.stack);
165
+ });
166
+ var origError = console.error;
167
+ console.error = function() {
168
+ report('console.error', Array.prototype.join.call(arguments, ' '));
169
+ origError.apply(console, arguments);
170
+ };
171
+ window.addEventListener('load', function() {
172
+ setTimeout(function() {
173
+ var hasContent = document.body && document.body.innerText.trim().length > 0;
174
+ fetch('/__codeyam__/preview-health', {
175
+ method: 'POST',
176
+ headers: { 'Content-Type': 'application/json' },
177
+ body: JSON.stringify({
178
+ loaded: true,
179
+ hasContent: hasContent,
180
+ url: location.href,
181
+ errorCount: errors.length
182
+ })
183
+ }).catch(function(){});
184
+ }, 1000);
185
+ });
186
+
187
+ // Network-idle detection: notify the parent editor when all initial
188
+ // fetch requests have completed, so it can show the preview after
189
+ // client-side data (API calls) has arrived — not just when the DOM loads.
190
+ var inflight = 0;
191
+ var settled = false;
192
+ var settleTimer = null;
193
+ var origFetch = window.fetch;
194
+ window.fetch = function() {
195
+ if (!settled) inflight++;
196
+ return origFetch.apply(this, arguments).then(function(resp) {
197
+ if (!settled) { inflight--; checkSettle(); }
198
+ return resp;
199
+ }, function(err) {
200
+ if (!settled) { inflight--; checkSettle(); }
201
+ throw err;
202
+ });
203
+ };
204
+ function checkSettle() {
205
+ if (inflight <= 0 && !settled) {
206
+ clearTimeout(settleTimer);
207
+ // Small delay to allow React to re-render with the fetched data
208
+ settleTimer = setTimeout(function() {
209
+ if (inflight <= 0) {
210
+ settled = true;
211
+ try {
212
+ window.parent.postMessage({ type: 'codeyam-preview-ready' }, '*');
213
+ } catch(e) {}
214
+ }
215
+ }, 100);
216
+ }
217
+ }
218
+ // Fallback: if no fetches happen (static page), settle after load
219
+ window.addEventListener('load', function() {
220
+ setTimeout(function() { checkSettle(); }, 200);
221
+ });
222
+ })();
223
+ <\/script>`,wx=500;let qt={data:null,timestamp:0},Pt,fn,Ta=null,Ma=null,$a=null,Bo=null;const lc=10*1024*1024;function Fa(){return globalThis[Iu]??null}function Yu(e){globalThis[Iu]=e}function Uu(){const e="__codeyam_mock_state__";return globalThis[e]||(globalThis[e]=lx()),globalThis[e]}function Wu(){const e=Fa();return e?`http://localhost:${e.port}`:null}function Nx(){const e=Date.now();if(qt.data!==null&&e-qt.timestamp<wx)return qt.data;const t=Ce()||process.env.CODEYAM_ROOT_PATH||process.cwd(),r=ee.join(t,".codeyam","active-scenario.json");try{if(!ce.existsSync(r))return qt={data:null,timestamp:e},null;const s=JSON.parse(ce.readFileSync(r,"utf-8")),a=s.scenarioId;if(!a)return $a=s.prototypeId||null,qt={data:null,timestamp:e},null;const o=ee.join(t,".codeyam","editor-scenarios",`${a}.json`);if(!ce.existsSync(o))return console.log(`[editorProxy] Scenario data file not found: ${o}`),qt={data:null,timestamp:e},null;const i=JSON.parse(ce.readFileSync(o,"utf-8"));Pt=i.session||null,fn=i.sessionCookies||void 0,Ta=i.localStorage||null,Ma=a;const l=s.type||i.type||null;Bo=l;let d;return(l==="application"||l==="user")&&i.seed?i.externalApis&&typeof i.externalApis=="object"?d={routes:i.externalApis}:d={}:d=i,qt={data:d,timestamp:e},Uu().loadScenario(d),d}catch(s){return console.warn("[editorProxy] Error reading scenario data:",s),qt={data:null,timestamp:e},null}}function Sx(e){return new Promise(t=>{const r=[];let s=0;e.on("data",a=>{s+=a.length,s>lc?(t(null),e.resume()):r.push(a)}),e.on("end",()=>{s>lc||t(Buffer.concat(r))}),e.on("error",()=>{t(null)})})}function Pi(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function cc(e,t,r,s){const a=new URL(r),o=Pi(a.hostname),i={...e.headers,host:`${a.hostname}:${a.port}`};delete i["accept-encoding"],Hu(i),s&&(i["content-length"]=String(s.length));const l={hostname:o,port:a.port,path:e.url,method:e.method,headers:i},d=li.request(l,u=>{const p=u.statusCode||200;p>=300&&p<400&&console.log(`[editorProxy] Target redirect ${p} for ${e.method} ${e.url} → ${u.headers.location}`),p>=400&&console.warn(`[editorProxy] Target returned ${p} for ${e.method} ${e.url}`);const h={...u.headers};if(Ju(h),(u.headers["content-type"]||"").includes("text/html")){zu();const f=[];u.on("data",y=>f.push(y)),u.on("end",()=>{const y=Buffer.concat(f).toString("utf-8"),g=Vu(Ta,Ma||"",$a),x=Ku(y,g);delete h["content-length"],delete h["content-encoding"],h["cache-control"]="no-store, must-revalidate",t.writeHead(p,h),t.end(x)});return}t.writeHead(p,h),u.pipe(t,{end:!0})});d.on("error",u=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${u.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),s&&s.length>0?d.end(s):d.end()}function Cx(e,t,r){const s=new URL(r),a=Pi(s.hostname),{"accept-encoding":o,...i}=e.headers,l={...i,host:`${s.hostname}:${s.port}`};Hu(l);const d={hostname:a,port:s.port,path:e.url,method:e.method,headers:l},u=li.request(d,p=>{const h=p.statusCode||200;h>=300&&h<400&&console.log(`[editorProxy] Target redirect ${h} for ${e.method} ${e.url} → ${p.headers.location}`),h>=400&&console.warn(`[editorProxy] Target returned ${h} for ${e.method} ${e.url}`);const m={...p.headers};if(Ju(m),(p.headers["content-type"]||"").includes("text/html")){zu();const y=[];p.on("data",g=>y.push(g)),p.on("end",()=>{const g=Buffer.concat(y).toString("utf-8"),x=Vu(Ta,Ma||"",$a),b=Ku(g,x);delete m["content-length"],delete m["content-encoding"],m["cache-control"]="no-store, must-revalidate",t.writeHead(h,m),t.end(b)});return}t.writeHead(h,m),p.pipe(t,{end:!0})});u.on("error",p=>{console.warn(`[editorProxy] Forward error for ${e.method} ${e.url}: ${p.message}`),t.headersSent||(t.writeHead(502,{"Content-Type":"text/plain"}),t.end("Bad Gateway — dev server unreachable"))}),e.pipe(u,{end:!0})}function Ju(e){const t=[];if(Pt!==void 0&&(Pt!=null&&Pt.cookieValue?t.push(`session-token=${Pt.cookieValue}; Path=/; SameSite=Lax`):t.push("session-token=; Path=/; Max-Age=0")),fn&&fn.length>0)for(const s of fn){const a=s.path||"/",o=s.sameSite||"Lax";t.push(`${s.name}=${s.value}; Path=${a}; SameSite=${o}`)}if(t.length===0)return;const r=e["set-cookie"];r?e["set-cookie"]=[...Array.isArray(r)?r:[r],...t]:e["set-cookie"]=t}function kx(){const e=[];if(Pt!=null&&Pt.cookieValue&&e.push({name:"session-token",value:Pt.cookieValue}),fn&&fn.length>0)for(const t of fn)e.push({name:t.name,value:t.value});return e.length>0?e:null}function Hu(e){const t=kx();if(!t)return;const r=typeof e.cookie=="string"?e.cookie:"",s=r?r.split(";").map(i=>i.trim()):[],a=new Map;for(const i of s){const l=i.indexOf("=");l!==-1&&a.set(i.slice(0,l),i.slice(l+1))}for(const{name:i,value:l}of t)a.set(i,l);const o=[];for(const[i,l]of a)o.push(`${i}=${l}`);o.length>0&&(e.cookie=o.join("; "))}function jx(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t+e.charCodeAt(r)|0;return(t>>>0).toString(36)}function Vu(e,t,r){if(!e||typeof e!="object"){const d=t?`clear:${t}`:"";return r?`<script data-codeyam-ls>
224
+ (function() {
225
+ if (localStorage.getItem('__codeyam_proto__') === ${JSON.stringify(r)}) return;
226
+ localStorage.clear();
227
+ localStorage.setItem('__codeyam_proto__', ${JSON.stringify(r)});
228
+ })();
229
+ <\/script>`:t?`<script data-codeyam-ls>
230
+ (function() {
231
+ if (localStorage.getItem('__codeyam_ls_sid__') === ${JSON.stringify(d)}) return;
232
+ var prev = JSON.parse(localStorage.getItem('__codeyam_ls_keys__') || '[]');
233
+ for (var i = 0; i < prev.length; i++) localStorage.removeItem(prev[i]);
234
+ localStorage.removeItem('__codeyam_ls_keys__');
235
+ localStorage.setItem('__codeyam_ls_sid__', ${JSON.stringify(d)});
236
+ })();
237
+ <\/script>`:""}const s=Object.entries(e),a=s.map(([d])=>d),o=s.map(([d,u])=>{const p=typeof u=="string"?u:JSON.stringify(u);return`localStorage.setItem(${JSON.stringify(d)}, ${JSON.stringify(p)});`}).join(`
238
+ `),i=jx(JSON.stringify(e)),l=`${t}:${i}`;return`<script data-codeyam-ls>
239
+ (function() {
240
+ if (localStorage.getItem('__codeyam_ls_sid__') === ${JSON.stringify(l)}) return;
241
+ var prev = JSON.parse(localStorage.getItem('__codeyam_ls_keys__') || '[]');
242
+ for (var i = 0; i < prev.length; i++) localStorage.removeItem(prev[i]);
243
+ ${o}
244
+ localStorage.setItem('__codeyam_ls_keys__', ${JSON.stringify(JSON.stringify(a))});
245
+ localStorage.setItem('__codeyam_ls_sid__', ${JSON.stringify(l)});
246
+ })();
247
+ <\/script>`+_x()}function _x(){return`<script data-codeyam-ls-watcher>
248
+ (function() {
249
+ if (window.__codeyam_ls_watcher_installed__) return;
250
+ window.__codeyam_ls_watcher_installed__ = true;
251
+
252
+ var origSet = localStorage.setItem.bind(localStorage);
253
+ var origRemove = localStorage.removeItem.bind(localStorage);
254
+ var origClear = localStorage.clear.bind(localStorage);
255
+ window.__codeyam_orig_setItem__ = origSet;
256
+ window.__codeyam_orig_removeItem__ = origRemove;
257
+ window.__codeyam_orig_clear__ = origClear;
258
+
259
+ function isInternal(key) {
260
+ return typeof key === 'string' && key.indexOf('__codeyam_') === 0;
261
+ }
262
+
263
+ localStorage.setItem = function(key, value) {
264
+ origSet(key, value);
265
+ if (!isInternal(key) && window.parent !== window) {
266
+ window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'set', key: key }, '*');
267
+ }
268
+ };
269
+
270
+ localStorage.removeItem = function(key) {
271
+ origRemove(key);
272
+ if (!isInternal(key) && window.parent !== window) {
273
+ window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'remove', key: key }, '*');
274
+ }
275
+ };
276
+
277
+ localStorage.clear = function() {
278
+ origClear();
279
+ if (window.parent !== window) {
280
+ window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'clear' }, '*');
281
+ }
282
+ };
283
+
284
+ window.addEventListener('message', function(event) {
285
+ if (event.data && event.data.type === 'codeyam-get-localstorage') {
286
+ var data = {};
287
+ for (var i = 0; i < localStorage.length; i++) {
288
+ var k = localStorage.key(i);
289
+ if (k && !isInternal(k)) {
290
+ data[k] = localStorage.getItem(k);
291
+ }
292
+ }
293
+ event.source.postMessage({ type: 'codeyam-localstorage-state', data: data }, '*');
294
+ }
295
+ });
296
+ })();
297
+ <\/script>`}function Ku(e,t){const r=(t||"")+vx;return e.includes("</head>")?e.replace("</head>",r+"</head>"):e.includes("</body>")?e.replace("</body>",r+"</body>"):e+r}function Ex(e,t){const r=[];e.on("data",s=>r.push(s)),e.on("end",()=>{try{const s=JSON.parse(Buffer.concat(r).toString("utf-8")),a=Lu()||{errors:[],loaded:!1,hasContent:!1,url:"",lastUpdated:0};s.errors&&Array.isArray(s.errors)&&(a.errors=a.errors.concat(s.errors)),s.loaded!==void 0&&(a.loaded=s.loaded),s.hasContent!==void 0&&(a.hasContent=s.hasContent),s.url&&(a.url=s.url),a.lastUpdated=Date.now(),Bu(a)}catch{}t.writeHead(204),t.end()})}function Px(e,t,r,s){const a=new URL(s),o=Pi(a.hostname),i=parseInt(a.port,10)||80;console.log(`[editorProxy] WebSocket upgrade: ${e.url} → ${o}:${i}`);const l=Ud.connect(i,o,()=>{const d=`${e.method} ${e.url} HTTP/${e.httpVersion}\r
298
+ `,u=Object.entries(e.headers).filter(([,p])=>p!=null).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(`\r
299
+ `);l.write(d+u+`\r
300
+ \r
301
+ `),r.length>0&&l.write(r),l.pipe(t,{end:!0}),t.pipe(l,{end:!0})});l.on("error",d=>{console.warn(`[editorProxy] WebSocket proxy error: ${d.message}`),t.destroy()}),t.on("error",()=>{l.destroy()})}function Ax(e,t){const r=Ce()||process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","proxy-config.json");try{ce.mkdirSync(ee.dirname(s),{recursive:!0}),ce.writeFileSync(s,JSON.stringify({proxyUrl:`http://localhost:${e}`,devServerUrl:t}),"utf-8"),console.log(`[editorProxy] Wrote proxy config to ${s}`)}catch(a){console.warn("[editorProxy] Failed to write proxy-config.json:",a)}}function Tx(){const e=Ce()||process.env.CODEYAM_ROOT_PATH||process.cwd(),t=ee.join(e,".codeyam","proxy-config.json");try{ce.existsSync(t)&&ce.unlinkSync(t)}catch{}}async function zo(e){const t=Fa();if(t)return console.log(`[editorProxy] Proxy already running on port ${t.port} → ${t.targetUrl}`),{port:t.port};await Gu();let r=xx(e.targetUrl),s=e.port;try{const l=new URL(r);if(l.hostname==="localhost"){const d=parseInt(l.port||"80",10),u=await bx(d);u&&(l.hostname=u,r=l.toString().replace(/\/$/,""),console.log(`[editorProxy] Resolved localhost to ${u} for port ${d}`))}}catch{}console.log(`[editorProxy] Starting proxy (requested port ${s}, target ${r})`);const a=Uu(),o=li.createServer((l,d)=>{(async()=>{const p=new URL(l.url||"/",`http://localhost:${s}`).pathname,h=l.method||"GET";if(h==="OPTIONS"){d.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-Requested-With","Access-Control-Max-Age":"86400"}),d.end();return}if(h==="POST"&&p==="/__codeyam__/preview-health"){Ex(l,d);return}if(Nx(),h==="POST"||h==="PUT"||h==="DELETE"||h==="PATCH"){const y=await Sx(l);if(y===null){cc(l,d,r,null);return}let g;if(y.length>0)try{g=JSON.parse(y.toString("utf-8"))}catch{}const x=a.matchRequest(h,p,g);if(x){console.log(`[editorProxy] Intercepted ${h} ${p} → mock response (status ${x.status})`),d.writeHead(x.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data","Cache-Control":"no-store"}),d.end(x.body!=null?JSON.stringify(x.body):"");return}(Bo==="application"||Bo==="user")&&p.startsWith("/api/")&&yx.emitDataMutationForwarded(h,p),cc(l,d,r,y);return}const f=a.matchRequest(h,p);if(f){console.log(`[editorProxy] Intercepted ${h} ${p} → mock response (status ${f.status})`),d.writeHead(f.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data","Cache-Control":"no-store"}),d.end(f.body!=null?JSON.stringify(f.body):"");return}Cx(l,d,r)})()});o.on("upgrade",(l,d,u)=>{Px(l,d,u,r)});const i=10;for(let l=0;l<i;l++){const d=s+l;try{await new Promise((h,m)=>{o.once("error",m),o.listen(d,"0.0.0.0",()=>{o.removeListener("error",m),h()})});const u=o.address();return s=typeof u=="object"&&u!==null?u.port:d,Yu({server:o,port:s,targetUrl:r}),Ax(s,r),console.log(`[editorProxy] Proxy started on port ${s}, forwarding to ${r}`),{port:s}}catch(u){if((u==null?void 0:u.code)==="EADDRINUSE"&&l<i-1){console.log(`[editorProxy] Port ${d} in use, trying ${d+1}`);continue}return console.error("[editorProxy] Failed to start proxy:",u),null}}return null}async function Gu(){const e=Fa();if(e)return console.log(`[editorProxy] Stopping proxy on port ${e.port}`),Tx(),new Promise(t=>{e.server.close(()=>{console.log("[editorProxy] Proxy stopped"),t()}),Yu(null),setTimeout(t,2e3)})}function Bn(){qt={data:null,timestamp:0},Pt=void 0,fn=void 0,Ta=null,Ma=null,$a=null}async function dc(){const e=Fa();if(!e)return console.warn("[editorProxy] Cannot verify — proxy is not running"),!1;try{const t=await fetch(`http://127.0.0.1:${e.port}/`,{method:"HEAD",signal:AbortSignal.timeout(5e3)});return t.status===502?(console.warn("[editorProxy] Verification failed — proxy returned 502 (target unreachable)"),!1):(console.log(`[editorProxy] Verification passed — proxy forwarding to ${e.targetUrl} (status ${t.status})`),!0)}catch{return console.warn(`[editorProxy] Verification failed — could not reach proxy on port ${e.port}`),!1}}async function Ai(){const e=Wu();if(e)return console.log(`[editorProxy] Proxy already running at ${e}`),e;const t=globalThis.__codeyam_editor_dev_server__;if(!t||t.status!=="running"||!t.url)return console.log("[editorProxy] Cannot start proxy — dev server not running"),null;const r=parseInt(process.env.CODEYAM_PORT||"3111",10),{proxyPort:s}=Ru(r);console.log(`[editorProxy] Proxy not running, starting on-demand (port ${s}, target ${t.url})`);const a=await zo({port:s,targetUrl:t.url});if(a){const o=`http://localhost:${a.port}`;return console.log(`[editorProxy] On-demand proxy started at ${o}`),o}return console.error("[editorProxy] Failed to start on-demand proxy"),null}async function Mx({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioId:r,scenarioName:s,scenarioSlug:a}=t;if(!r||typeof r!="string")return Response.json({error:"scenarioId is required"},{status:400});const o=Ce()||process.cwd(),i=await Aa({scenarioId:r,scenarioName:s,scenarioSlug:a,projectRoot:o});return Bn(),Response.json({success:i.success,seeded:i.seeded,seedResult:i.seedResult})}catch(t){const r=t instanceof Error?t.message:String(t);return Response.json({error:r},{status:500})}}const $x=Object.freeze(Object.defineProperty({__proto__:null,action:Mx},Symbol.toStringTag,{value:"Module"}));async function Fx({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{url:r,filename:s,viewportWidth:a,viewportHeight:o}=t;if(!r||!s)return new Response(JSON.stringify({error:"url and filename are required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=process.env.CODEYAM_ROOT_PATH||process.cwd(),l=G.join(i,".codeyam","journal","screenshots");await Ae.mkdir(l,{recursive:!0});const d=s.replace(/[^a-zA-Z0-9_\-T]/g,"_"),u=G.join(l,`${d}.png`),p=G.dirname(new URL(import.meta.url).pathname);let h=p;for(let v=0;v<5;v++){const N=G.dirname(h);if(G.basename(N)==="webserver"||G.basename(h)==="webserver"){h=G.basename(h)==="webserver"?h:N;break}h=N}const m=[G.join(h,"scripts","journalCapture.ts"),G.join(h,"app","lib","journalCapture.ts"),G.join(i,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),G.resolve(p,"..","lib","journalCapture.ts")];let f="";for(const v of m)try{await Ae.access(v),f=v;break}catch{}f||(console.warn(`[editor-journal-screenshot] journalCapture.ts not found in any of: ${m.join(", ")}`),f=m[0]);const y=Pa({bodyWidth:a,bodyHeight:o,codeyamRoot:i}),g=JSON.stringify({url:r,outputPath:u,viewportWidth:y.width,viewportHeight:y.height}),x=await new Promise(v=>{const N=kt("npx",["tsx",f,g],{cwd:i,env:{...process.env}});let w="",C="";N.stdout.on("data",k=>{w+=k.toString()}),N.stderr.on("data",k=>{C+=k.toString()}),N.on("close",k=>{v(k===0?{success:!0,output:w}:{success:!1,output:w,error:C||`Process exited with code ${k}`})}),N.on("error",k=>{v({success:!1,output:"",error:k.message})})});if(!x.success)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:x.error}),{status:500,headers:{"Content-Type":"application/json"}});const b=`screenshots/${d}.png`;return new Response(JSON.stringify({success:!0,path:b}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-screenshot] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Dx=Object.freeze(Object.defineProperty({__proto__:null,action:Fx},Symbol.toStringTag,{value:"Module"}));async function Rx({request:e}){const t={"Content-Type":"application/json"};try{const r=Ce()||process.cwd(),s=await e.json(),{scenarioId:a,table:o,rowIndex:i,column:l,value:d}=s;if(!a||!o||i==null||!l)return new Response(JSON.stringify({success:!1,error:"Missing required fields"}),{headers:t,status:400});const u=G.join(r,".codeyam","editor-scenarios",`${a}.json`);if(!Q.existsSync(u))return new Response(JSON.stringify({success:!1,error:"Scenario file not found"}),{headers:t,status:404});const p=JSON.parse(Q.readFileSync(u,"utf-8"));if(Array.isArray(p[o])&&i<p[o].length)return p[o][i][l]=d,Q.writeFileSync(u,JSON.stringify(p,null,2)),new Response(JSON.stringify({success:!0}),{headers:t});if(p.seed&&typeof p.seed=="object"){const h=o.charAt(0).toLowerCase()+o.slice(1);for(const m of[o,h,`${h}s`])if(Array.isArray(p.seed[m])&&i<p.seed[m].length){p.seed[m][i][l]=d,Q.writeFileSync(u,JSON.stringify(p,null,2));const f=u.replace(/\.json$/,".seed.json");if(Q.existsSync(f))try{const y=JSON.parse(Q.readFileSync(f,"utf-8"));Array.isArray(y[m])&&(y[m][i][l]=d,Q.writeFileSync(f,JSON.stringify(y,null,2)))}catch{}return new Response(JSON.stringify({success:!0}),{headers:t})}}if(p.localStorage&&typeof p.localStorage=="object"){for(const[h,m]of Object.entries(p.localStorage))if(typeof m=="string")try{let f=JSON.parse(m);const y=!Array.isArray(f)&&typeof f=="object"&&f!==null;if(y&&(f=[f]),!Array.isArray(f))continue;const g=o.charAt(0).toLowerCase()+o.slice(1),x=()=>{f[i][l]=d;const b=y?f[0]:f;p.localStorage[h]=JSON.stringify(b),Q.writeFileSync(u,JSON.stringify(p,null,2))};if((h===o||h===g||h===`${g}s`||h===`${o}s`)&&i<f.length)return x(),new Response(JSON.stringify({success:!0}),{headers:t});if(f.length>0&&l in f[0]&&i<f.length)return x(),new Response(JSON.stringify({success:!0}),{headers:t})}catch{}}return new Response(JSON.stringify({success:!1,error:"Table not found in scenario"}),{headers:t,status:404})}catch(r){return new Response(JSON.stringify({success:!1,error:r instanceof Error?r.message:"Unknown error"}),{headers:t,status:500})}}const Ix=Object.freeze(Object.defineProperty({__proto__:null,action:Rx},Symbol.toStringTag,{value:"Module"})),qu=ti({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),Ti=()=>{const e=ua(qu);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Da=({children:e})=>{const[t,r]=E({height:720,width:1200}),[s,a]=E(1),[o,i]=E(1200),l=be(null),d=le(({height:h,width:m})=>{r(f=>({height:h??f.height,width:m??f.width}))},[]),u=le(h=>{a(h)},[]),p=le(h=>{i(h)},[]);return n(qu.Provider,{value:{dimensions:t,updateDimensions:d,iframeRef:l,scale:s,updateScale:u,maxWidth:o,updateMaxWidth:p},children:e})},Ox=typeof window<"u";function Lx(){const[e,t]=E(null);return se(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const Bx=1200,zx=720,uc=30,Yx=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:s=1440,defaultHeight:a=900,onDataOverride:o,onIframeLoad:i,onScaleChange:l,onDimensionChange:d})=>{const u=Lx(),[p,h]=E(!1),[m,f]=E(!1),[y,g]=E(Bx),[x,b]=E(zx),[v,N]=E(null),[w,C]=E(null),{dimensions:k,updateDimensions:j,iframeRef:A,updateScale:_,updateMaxWidth:M}=Ti(),T=fe(()=>Math.min(1,y/k.width),[y,k.width]),D=w!==null?w:T;se(()=>{p||(_(D),l==null||l(D))},[D,_,l,p]),se(()=>{M(y)},[y,M]);const R=le(()=>{h(!0),C(T)},[T]),L=le(()=>{h(!1),C(null)},[]),U=le((P,O)=>{const S=w!==null?w:1,$=Math.round(O.size.width/S);j({width:$}),d==null||d($,k.height)},[j,w,d,k.height]),W=le(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);se(()=>{const P=O=>{if(O.data.type==="codeyam-resize"){if(t&&O.data.name!==t||k.height===O.data.height||O.data.height===0)return;j({height:O.data.height})}};return window.addEventListener("message",P),()=>{window.removeEventListener("message",P)}},[A,t,s,k,j]),se(()=>{m&&o&&o(A.current)},[m,o,A]),se(()=>{if(!t)return;const P=setInterval(()=>{var O,S;(S=(O=A==null?void 0:A.current)==null?void 0:O.contentWindow)==null||S.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(P)},[t,A]),se(()=>{const P=()=>{const O=document.getElementById("scenario-container");if(!O)return;const S=O.getBoundingClientRect(),$=O.clientWidth-uc*2,I=window.innerHeight-S.top-uc*2,K=Math.max(I,400),q=window.innerHeight-S.top;g($),b(K),N(q)};return P(),window.addEventListener("resize",P),()=>window.removeEventListener("resize",P)},[]),se(()=>{j({width:s,height:a})},[s,a,j]);const V=fe(()=>k.width*D,[k.width,D]),F=fe(()=>{const P=k.height,O=P*D;return P&&P!==720&&P!==900&&O<x?O:x},[k.height,x,D]),Y=le(()=>{window.history.back()},[]);return!Ox||!u?n("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:n("p",{className:"text-gray-500",children:"Loading interactive view..."})}):c("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:v?{height:`${v}px`}:{},children:[p&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
302
+ .react-resizable-handle-e {
303
+ display: flex !important;
304
+ align-items: center !important;
305
+ justify-content: center !important;
306
+ width: 6px !important;
307
+ height: 48px !important;
308
+ right: -8px !important;
309
+ top: 50% !important;
310
+ transform: translateY(-50%) !important;
311
+ cursor: ew-resize !important;
312
+ background: #d1d5db !important;
313
+ border-radius: 3px !important;
314
+ opacity: 0 !important;
315
+ transition: all 0.2s ease !important;
316
+ }
317
+ .react-resizable-handle-e:hover {
318
+ opacity: 0.8 !important;
319
+ background: #9ca3af !important;
320
+ }
321
+ .react-resizable:hover .react-resizable-handle-e {
322
+ opacity: 0.4 !important;
323
+ }
324
+ `}),n(u,{width:V,height:F,minConstraints:[300,200],maxConstraints:[y,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:R,onResizeStop:L,onResize:U,children:n("div",{className:"overflow-auto",style:{width:`${V}px`,height:`${F}px`},children:n("div",{style:{width:`${k.width}px`,height:`${k.height}px`,transform:`scale(${D})`,transformOrigin:"top left"},children:r?n("iframe",{ref:A,className:"w-full h-full rounded-lg",src:r,onLoad:W,sandbox:"allow-scripts allow-same-origin"}):c("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[n("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),n("span",{className:"text-blue-600 cursor-pointer",onClick:Y,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function Ux({presets:e,customSizes:t,currentWidth:r,currentHeight:s,scale:a,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:l,className:d=""}){const[u,p]=E(!1),[h,m]=E(String(r)),[f,y]=E(String(s)),[g,x]=E(!1),[b,v]=E(!1),N=be(null);se(()=>{g||m(String(r))},[r,g]),se(()=>{b||y(String(s))},[s,b]),se(()=>{const D=R=>{N.current&&!N.current.contains(R.target)&&p(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[]);const w=fe(()=>{const D=e.find(L=>L.width===r&&L.height===s);if(D)return D.name;const R=t.find(L=>L.width===r&&L.height===s);return R?R.name:"Custom"},[e,t,r,s]),C=w==="Custom",k=D=>{o(D.width,D.height),p(!1)},j=D=>{const R=D.target.value;m(R);const L=parseInt(R,10);!isNaN(L)&&L>0&&o(L,s)},A=D=>{const R=D.target.value;y(R);const L=parseInt(R,10);!isNaN(L)&&L>0&&o(r,L)},_=()=>{x(!1);const D=parseInt(h,10);(isNaN(D)||D<=0)&&m(String(r))},M=()=>{v(!1);const D=parseInt(f,10);(isNaN(D)||D<=0)&&y(String(s))},T=D=>{(D.key==="Enter"||D.key==="Escape")&&D.target.blur()};return c("div",{className:`flex items-center gap-3 ${d}`,children:[c("div",{className:"relative",ref:N,children:[c("button",{onClick:()=>p(!u),className:"flex items-center gap-2 px-3 py-1.5 bg-white border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 min-w-[120px] justify-between",children:[n("span",{children:w}),n("svg",{className:`w-4 h-4 transition-transform ${u?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),u&&n("div",{className:"absolute top-full left-0 mt-1 min-w-full bg-white border border-gray-200 rounded-md shadow-lg z-50",children:c("div",{className:"py-1",children:[e.length>0&&c(we,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(D=>c("button",{onClick:()=>k(D),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${w===D.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:D.name}),c("span",{className:"text-xs text-gray-500",children:[D.width," x ",D.height]})]},D.name))]}),t.length>0&&c(we,{children:[n("div",{className:"border-t border-gray-100 my-1"}),n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...t].sort((D,R)=>D.width-R.width).map(D=>c("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${w===D.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[c("button",{onClick:()=>k(D),className:"flex-1 text-left px-3 py-2 text-sm flex justify-between items-center gap-4 whitespace-nowrap cursor-pointer",children:[n("span",{children:D.name}),c("span",{className:"text-xs text-gray-500",children:[D.width," x ",D.height]})]}),l&&n("button",{onClick:R=>{R.stopPropagation(),w===D.name&&e.length>0&&o(e[0].width,e[0].height),l(D.name)},className:"p-1.5 mr-1 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded cursor-pointer transition-colors",title:"Remove custom size",children:n("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},D.name))]})]})})]}),c("div",{className:"flex items-center gap-1 text-sm",children:[c("div",{className:"flex items-center",children:[n("input",{type:"text",value:h,onChange:j,onFocus:()=>x(!0),onBlur:_,onKeyDown:T,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),n("span",{className:"text-gray-400 mx-1",children:"×"}),c("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:A,onFocus:()=>v(!0),onBlur:M,onKeyDown:T,className:"w-16 px-2 py-1 text-right border border-gray-300 rounded-l-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"}),n("span",{className:"px-2 py-1 bg-gray-100 border border-l-0 border-gray-300 rounded-r-md text-gray-500 text-sm",children:"px"})]}),a!==void 0&&a<1&&c("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(a*100),"%)"]})]}),C&&n("button",{onClick:i,className:"px-3 py-1.5 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:ring-offset-1 transition-colors",children:"Save Custom Size"})]})}function fo(e,t,r){if(Array.isArray(e)){if(!isNaN(parseInt(t)))return e[parseInt(t)];for(const s of e)if(s.name===t||s.title===t||s.id===t)return s}return e[t]}function Yo(e){return e&&(typeof e=="object"||Array.isArray(e))}function Wx(e){return Array.isArray(e)?e.length:void 0}function Jx(e){const{data:t,structure:r}=e;if(!(!t&&!r)){if(Array.isArray(r))return Array.isArray(t)?t.map((s,a)=>a.toString()):[];if(typeof r=="object")return[...new Set([...Object.keys(t),...Object.keys(r)])].sort((a,o)=>{const i=Yo(t[a]),l=Yo(t[o]);return i&&!l?1:!i&&l?-1:a.localeCompare(o)});if(typeof t=="object")return Object.keys(t).sort((a,o)=>a.localeCompare(o))}}function Hx({scenarioFormData:e,handleInputChange:t}){return c("div",{className:"p-3 flex flex-col gap-3",children:[c("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),n("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),c("div",{className:"grid w-full gap-1.5 pt-2",children:[n("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),n("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:t,required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[100px]"})]}),n("button",{type:"submit",className:"mt-3 w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium",children:"Save Name & Description"})]})}function Vx({path:e,namedPath:t,isArray:r,count:s,onClick:a}){const o=le(()=>{a&&a(e)},[a,e]);return c("div",{className:"bg-blue-50 p-3 rounded-lg flex items-center justify-between cursor-pointer group hover:bg-blue-100 transition-colors border border-blue-200",onClick:o,children:[c("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),c("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],s!==void 0&&` (${s})`]})]}),c("div",{className:"flex items-center gap-3",children:[r&&n("svg",{className:"w-5 h-5 text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),n("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var Qu=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Qu||{});const Kx=({name:e,value:t,options:r,onChange:s})=>{const a=le(o=>{s({target:{name:e,value:o.target.value}})},[e,s]);return n("select",{name:e,value:t,onChange:a,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:r.map((o,i)=>n("option",{value:o.trim(),children:o.trim()},i))})},Gx=({name:e,value:t,onChange:r})=>{const s=le(a=>{const o=a.target.checked;r({target:{name:e,value:o}})},[e,r]);return n("label",{className:"flex items-center gap-2 cursor-pointer",children:n("input",{type:"checkbox",name:e,checked:t,onChange:s,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
325
+ bg-gray-300 checked:bg-blue-600
326
+ after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
327
+ after:bg-white after:rounded-full after:transition-transform
328
+ checked:after:translate-x-4`})})};function qx({dataType:e,path:t,value:r,onChange:s}){const a=fe(()=>t[t.length-1],[t]),o=fe(()=>t.join("-"),[t]),i=le(d=>{s(t,d.target.value)},[s,t]),l=le(d=>{s(t,d.target.value)},[s,t]);return c("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[n("label",{htmlFor:o,className:"capitalize text-sm font-medium text-gray-700",children:a==="~~codeyam-code~~"?"Dynamic Field":a}),e.includes("|")?n(Kx,{name:o,value:r,options:e.split("|"),onChange:i}):e===Qu.BOOLEAN?n(Gx,{name:o,value:r??!1,onChange:l}):n("input",{id:o,name:o,type:"text",value:JSON.stringify(r??"").replace(/"/g,""),onChange:i,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"},`Input-${o}`)]})}function Qx({analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:a}){const[o,i]=E(!1),[l,d]=E(""),u=le(async()=>{if(!a){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const h=e.scenarios.find(x=>x.name===t);if(!h)throw new Error("Scenario not found");const m=e.scenarios.find(x=>x.name===ya),f=await a(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const y=(x,b)=>{const v=Object.assign({},x);return g(x)&&g(b)&&Object.keys(b).forEach(N=>{g(b[N])?N in x?v[N]=y(x[N],b[N]):Object.assign(v,{[N]:b[N]}):Object.assign(v,{[N]:b[N]})}),v},g=x=>x&&typeof x=="object"&&!Array.isArray(x);h.metadata.data=y(y((m==null?void 0:m.metadata.data)||{},h.metadata.data),f.data||{}),s(h),i(!1),d("")}catch(h){console.error("Error generating AI data:",h),i(!1)}},[e,l,r,t,s,a]),p=le(h=>{d(h.target.value)},[]);return c("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[n("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),n("textarea",{className:"peer w-full h-16 p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Type your message here.",onChange:p,value:l}),n("button",{type:"button",disabled:o,className:`w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium ${l.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void u(),children:o?c(we,{children:[c("svg",{className:"animate-spin h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Please wait"]}):"Generate Data"})]})}function Zx({namedPath:e,path:t,last:r,onClick:s}){const a=le(()=>s(r?t.slice(0,-1):t),[r,t,s]);return n("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:a,children:e[e.length-1]})}function Xx({dataItem:e,onClick:t}){const r=le(()=>t([]),[t]),s=fe(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return c("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[n("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:r,children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&c("div",{className:"flex items-center gap-1",children:[n("div",{children:"..."}),n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(s).map((a,o)=>c("div",{className:"flex items-center gap-1",children:[n(Zx,{namedPath:e.namedPath.slice(0,o+s+1),path:e.path.slice(0,o+s+1),last:o+s===e.namedPath.length-1,onClick:t}),o+s<e.namedPath.length-1&&n("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${a}-${o+s}`))]})}function pc({analysis:e,scenarioName:t,dataItem:r,onClick:s,onChange:a,onAIResult:o,onGenerateData:i,saveFeedback:l}){const d=fe(()=>r.data,[r]),u=fe(()=>Jx(r),[r]);return c("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Xx,{dataItem:r,onClick:s}),c("div",{className:"flex flex-col gap-3",children:[n(Qx,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),u==null?void 0:u.map((p,h)=>{var f;if(Yo(d[p])){let y=p;isNaN(Number(p))||(y=d[p].name??d[p].title??d[p].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(p)+1}`);const g=[...r.path,p],x=[...r.namedPath,y];return n(Vx,{path:g,namedPath:x,isArray:Array.isArray(d),count:Wx(d[p]),onClick:s},`data-${p}-${h}`)}if(p==="id")return null;const m=[...r.path,p];return n(qx,{dataType:((f=r.structure)==null?void 0:f[p])??"string",path:m,value:d[p],onChange:a},`InputField-${m.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),c("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const p=document.getElementById("recapture-input");p&&(p.value="false")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:l!=null&&l.isSaving?"Saving...":"Save Changes"}),n("button",{type:"submit",onClick:()=>{const p=document.getElementById("recapture-input");p&&(p.value="true")},disabled:l==null?void 0:l.isSaving,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500 font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save & Recapture"})]}),(l==null?void 0:l.message)&&!(l!=null&&l.isSaving)&&n("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${l.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:l.message})]})}function hc({title:e,children:t,defaultOpen:r=!1,borderT:s=!1,borderB:a=!1}){const[o,i]=E(r),l=[];return s&&l.push("border-t"),a&&l.push("border-b"),c("div",{className:`${l.join(" ")} border-gray-300`,children:[c("button",{type:"button",onClick:()=>i(!o),className:"w-full px-4 py-3 flex items-center justify-between bg-gray-50 hover:bg-gray-100 transition-colors text-left font-semibold text-gray-900",children:[n("span",{children:e}),n("svg",{className:`transition-transform ${o?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"20px",height:"20px",minWidth:"20px",minHeight:"20px",maxWidth:"20px",maxHeight:"20px",flexShrink:0},children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),o&&n("div",{className:"px-4 py-3",children:t})]})}const eb=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:s,shouldCreateNewScenario:a,onSave:o,onNavigate:i,iframeRef:l,onGenerateData:d,saveFeedback:u})=>{const p=le((j,A)=>{const _=Object.assign({},j),M=T=>T&&typeof T=="object"&&!Array.isArray(T);return M(j)&&M(A)&&Object.keys(A).forEach(T=>{M(A[T])?T in j?_[T]=p(j[T],A[T]):Object.assign(_,{[T]:A[T]}):Object.assign(_,{[T]:A[T]})}),_},[]),[h,m]=E({name:e.name,description:e.description,data:p(t.metadata.data,e.metadata.data)}),[f,y]=E(null),g=fe(()=>({...h.data}),[h]),x=fe(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),b=fe(()=>{const j={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(j).reduce((A,_)=>{if(_.includes(".")){const[M,T]=_.split(".");A[M]||(A[M]={}),A[M][T]=j[_]}else A[_]=j[_];return A},{})},[r]),v=le(async j=>{j.preventDefault();const A=j.target.querySelector('input[name="recapture"]'),_=(A==null?void 0:A.value)==="true",M={mockData:h.data.mockData??{},argumentsData:h.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:h.name,shouldRecapture:_,dataToSave:M,rawFormData:h.data,iframePayload:{arguments:g.argumentsData??[],...g.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(M,null,2).substring(0,1e3));const T=s==null?void 0:s.scenarios.map(D=>!a&&D.name===e.name?{...D,name:h.name,description:h.description,metadata:{...D.metadata,data:M}}:D);a&&T.push({name:h.name,description:h.description,metadata:{data:M,interactiveExamplePath:s==null?void 0:s.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",T),o&&await o(T,{recapture:_}),i&&i(h.name)},[s,e.name,h,g,a,o,i]),N=le(j=>{m(A=>({...A,[j.target.name]:j.target.value}))},[]),w=le(j=>{y(A=>{if(!A)return null;for(const _ of[{arguments:j.metadata.data.argumentsData},j.metadata.data.mockData]){let M=_;for(const T of A.path)if(M=fo(M,T),!M)break;M&&(A.data=M)}return{...A}}),m({name:j.name,description:j.description,data:j.metadata.data})},[]),C=le((j,A)=>{m(_=>{for(const M of[{"Function Arguments":_.data.argumentsData},{"Retrieved Data":_.data.mockData}]){let T=M;for(const D of j.slice(0,-1))if(T=fo(T,D),!T)break;if(T){const D=T[j[j.length-1]];y(R=>R?(R.namedPath[R.namedPath.length-1]===D&&(R.namedPath[R.namedPath.length-1]=A.toString()),R.data[j[j.length-1]]=A,{...R}):null),T[j[j.length-1]]=A}}return{..._}})},[]),k=le(j=>{var T,D,R;if(j.length===0){y(null);return}let A=x;const _=[];let M=b;for(const L of j){if(_.push(isNaN(parseInt(L))?L:((T=A[L])==null?void 0:T.name)??((D=A[L])==null?void 0:D.title)??((R=A[L])==null?void 0:R.id)??L),A=fo(A,L),!A){console.log("Data not found",A,L),y(null);return}Array.isArray(M)?M=M[0]:M=M[L]}y({path:j,namedPath:_,data:A,structure:M})},[x,b]);return se(()=>{const j=A=>{var _;A.data.type==="codeyam-log"&&((_=A.data.data)!=null&&_.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",A.data.data)};return window.addEventListener("message",j),()=>window.removeEventListener("message",j)},[]),se(()=>{var j;if((j=l==null?void 0:l.current)!=null&&j.contentWindow){const A={arguments:g.argumentsData??[],...g.mockData??{}},_={type:"codeyam-override-data",name:e.name,data:JSON.stringify(A)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:_.type,name:_.name,dataPreview:JSON.stringify(A).substring(0,200)+"...",fullData:A}),l.current.contentWindow.postMessage(_,"*")}},[g,e,l]),n("form",{method:"post",onSubmit:j=>void v(j),children:f?n(pc,{analysis:s,scenarioName:h.name,dataItem:f,onClick:k,onChange:C,onAIResult:w,onGenerateData:d,saveFeedback:u}):c(we,{children:[n(hc,{title:"Edit Name and Description",borderT:!0,children:n(Hx,{scenarioFormData:h,handleInputChange:N})}),e.metadata.data&&n(hc,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(pc,{analysis:s,scenarioName:h.name,dataItem:{path:[],namedPath:[],data:x,structure:b},onClick:k,onChange:C,onAIResult:w,onGenerateData:d,saveFeedback:u})})]})})};function Ra({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:s,isLoading:a,showIframe:o,iframeKey:i,onIframeLoad:l,onScaleChange:d,onDimensionChange:u,projectSlug:p,defaultWidth:h=1440,defaultHeight:m=900,retryCount:f=0}){const{lastLine:y}=Xt(p??null,s||a);return r?c("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(Yx,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:h,defaultHeight:m,onIframeLoad:l,onScaleChange:d,onDimensionChange:u},i)}),!o&&(s||a)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Qt,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(lr,{}),y]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:c("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[n("div",{className:"mb-4",children:n(Qt,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),n("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&c("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(lr,{}),y]})]})]})})}const tb=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function nb({params:e}){var d,u;const{sha:t,scenarioId:r}=e;if(!t)throw new Response("Entity SHA is required",{status:400});if(!r)throw new Response("Scenario ID is required",{status:400});const s=await xa(t,!0),a=s&&s.length>0?s[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=(d=a.scenarios)==null?void 0:d.find(p=>p.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(u=a.scenarios)==null?void 0:u.find(p=>p.name===ya),l=await ze();return ue({analysis:a,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:l})}function rb(){var L,U,W;const e=lt(),t=e.analysis,r=e.scenario,s=e.defaultScenario,a=e.entitySha,o=e.projectSlug,i=Yt(),{iframeRef:l}=Ti(),[d,u]=E(!1),[p,h]=E(null),[m,f]=E(null),[y,g]=E(!1),[x,b]=E(!1),[v,N]=E(null),{interactiveServerUrl:w,isStarting:C,isLoading:k,showIframe:j,iframeKey:A,onIframeLoad:_}=Un({analysisId:t==null?void 0:t.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),M=le(async(V,F)=>{u(!0),h(null),f(null),console.log("[EditScenario] Starting save with options:",F),console.log("[EditScenario] Scenarios to save:",V);try{const Y={analysis:t,scenarios:V};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:V.length,scenarioNames:V.map(S=>S.name)});const P=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Y)}),O=await P.json();if(console.log("[EditScenario] API response:",O),!P.ok||!O.success)throw new Error(O.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),F!=null&&F.recapture&&r.id&&w){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:w}),h("Changes saved. Capturing screenshot...");const S={serverUrl:w,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",S);const $=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});console.log("[EditScenario] Capture response status:",$.status);const I=await $.json();if(console.log("[EditScenario] Capture response body:",I),!$.ok||!I.success)throw console.error("[EditScenario] Capture failed:",I),new Error(I.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",I),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),h("Recapture successful")}else if(F!=null&&F.recapture&&!w){console.log("[EditScenario] No running server, using queued recapture");const S=new FormData;S.append("analysisId",t.id||""),S.append("scenarioId",r.id||"");const $=await fetch("/api/recapture-scenario",{method:"POST",body:S}),I=await $.json();if(!$.ok||!I.success)throw new Error(I.error||"Failed to trigger recapture");console.log("Recapture queued:",I),f(I.jobId),h("Changes saved. Screenshot recapture queued.")}else h("Changes saved successfully.")}catch(Y){console.error("Error saving scenarios:",Y),h(`Error: ${Y instanceof Error?Y.message:String(Y)}`)}finally{u(!1)}},[t,r.id,w]),T=le(V=>{},[]),D=le(async(V,F)=>{var O;const Y=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:V,existingScenarios:t.scenarios,scenariosDataStructure:(O=t.metadata)==null?void 0:O.scenariosDataStructure,editingMockName:r.name,editingMockData:F==null?void 0:F.data})}),P=await Y.json();if(!Y.ok||!P.success)throw new Error(P.error||"Failed to generate scenario data");return P.data},[t,r.name]),R=le(async()=>{var V;if(!r.id){N("Cannot delete scenario without ID");return}g(!0),N(null);try{const F=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((V=r.metadata)==null?void 0:V.screenshotPaths)||[]})}),Y=await F.json();if(!F.ok||!Y.success)throw new Error(Y.error||"Failed to delete scenario");i(`/entity/${a}`)}catch(F){console.error("[EditScenario] Error deleting scenario:",F),N(F instanceof Error?F.message:"Failed to delete scenario"),b(!1)}finally{g(!1)}},[r.id,(L=r.metadata)==null?void 0:L.screenshotPaths,a,i]);return c("div",{className:"h-screen bg-gray-50 flex flex-col",children:[c("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:c(Ee,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(U=t.entity)==null?void 0:U.name]})}),c("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",r.name]}),r.description&&n("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:r.description})]}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[c("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(eb,{currentScenario:r,defaultScenario:s,dataStructure:((W=t.metadata)==null?void 0:W.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:M,onNavigate:T,iframeRef:l,onGenerateData:D,saveFeedback:{isSaving:d,message:p,isError:(p==null?void 0:p.startsWith("Error"))??!1}}),p==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(Ee,{to:`/entity/${a}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),c("div",{className:"border-t border-gray-200 p-4 mt-4",children:[n("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),x?c("div",{className:"space-y-3",children:[c("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void R(),disabled:y,className:"flex-1 px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors",children:y?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>b(!1),disabled:y,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md text-sm font-medium hover:bg-gray-200 disabled:opacity-50 transition-colors",children:"Cancel"})]})]}):n("button",{onClick:()=>b(!0),className:"w-full px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-md text-sm font-medium hover:bg-red-100 transition-colors",children:"Delete Scenario"}),v&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:v})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(Ra,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:w,isStarting:C,isLoading:k,showIframe:j,iframeKey:A,onIframeLoad:_,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const sb=tt(function(){return n(Da,{children:n(rb,{})})}),ab=Object.freeze(Object.defineProperty({__proto__:null,default:sb,loader:nb,meta:tb},Symbol.toStringTag,{value:"Module"})),ob=["/api/health","/__codeyam__/preview-health"];function Zu(e){const t=[];for(const r of e.split(`
329
+ `))if(r.includes("[JournalCapture] HTTP error:"))t.push(r.replace(/.*\[JournalCapture\] /,""));else if(r.includes("[JournalCapture] API response error:"))t.push(r.replace(/.*\[JournalCapture\] /,""));else if(r.includes("[JournalCapture] Page console.error:"))t.push(r.replace(/.*\[JournalCapture\] Page console\.error:\s*/,""));else if(r.includes("[JournalCapture] Network failed:")){if(ob.some(s=>r.includes(s)))continue;t.push(r.replace(/.*\[JournalCapture\] /,""))}return t}function ib(e){for(const t of e.split(`
330
+ `))if(t.includes("[JournalCapture] Visible text: "))return t.replace(/.*\[JournalCapture\] Visible text: /,"");return null}async function Xu(e,t,r,s){const a=G.join(e,".codeyam","editor-scenarios","client-errors.json");let o={};try{const i=await Ae.readFile(a,"utf8");o=JSON.parse(i)}catch{}for(const[i,l]of Object.entries(o))i!==t&&l.scenarioName===r&&delete o[i];o[t]={scenarioName:r,capturedAt:new Date().toISOString(),errors:s},await Ae.mkdir(G.dirname(a),{recursive:!0}),await Ae.writeFile(a,JSON.stringify(o,null,2),"utf8")}async function ep(e){const t=G.join(e,".codeyam","editor-scenarios","client-errors.json");try{const r=await Ae.readFile(t,"utf8");return JSON.parse(r)}catch{return{}}}function Mi(e){let r=G.dirname(new URL(e).pathname);for(let s=0;s<5;s++){const a=G.dirname(r);if(G.basename(a)==="webserver"||G.basename(r)==="webserver")return G.basename(r)==="webserver"?r:a;r=a}return r}async function $i(e,t){const r=[G.join(e,"scripts","journalCapture.ts"),G.join(e,"app","lib","journalCapture.ts"),G.join(t,"codeyam-cli","src","webserver","app","lib","journalCapture.ts")];for(const s of r)try{return await Ae.access(s),s}catch{}return r[0]}function Fi(e,t,r){return new Promise(s=>{const a=e.endsWith(".ts"),l=kt(a?"npx":e,a?["tsx",e,t]:[t],{cwd:r,env:{...process.env}});let d="",u="";l.stdout.on("data",p=>{d+=p.toString()}),l.stderr.on("data",p=>{u+=p.toString()}),l.on("close",p=>{s(p===0?{success:!0,output:d}:{success:!1,output:d,error:u||`Process exited with code ${p}`})}),l.on("error",p=>{s({success:!1,output:"",error:p.message})})})}function lb(e){const t=G.join(e,".codeyam","editor-scenarios");let r;try{r=Q.readdirSync(t)}catch{return[]}const s=[];for(const a of r){if(!a.endsWith(".json")||a.endsWith(".seed.json")||a==="client-errors.json")continue;const o=G.join(t,a);try{if(!Q.statSync(o).isFile())continue;const l=JSON.parse(Q.readFileSync(o,"utf8"));if(l._metadata){const d=a.replace(/\.json$/,"");s.push({id:d,metadata:l._metadata})}}catch{}}return s}function tp(e,t,r){const s=G.join(e,".codeyam","editor-scenarios",`${t}.json`);let a={};try{a=JSON.parse(Q.readFileSync(s,"utf8"))}catch{return}a._metadata=r,Q.writeFileSync(s,JSON.stringify(a,null,2),"utf8")}function cb(e,t,r){const s=G.join(e,".codeyam","editor-scenarios",`${t}.json`);let a={};try{a=JSON.parse(Q.readFileSync(s,"utf8"))}catch{return}a._metadata&&typeof a._metadata=="object"&&(a._metadata.screenshotPath=r,a._metadata.updatedAt=new Date().toISOString(),Q.writeFileSync(s,JSON.stringify(a,null,2),"utf8"))}function db(e,t,r,s={}){const a=G.join(e,".codeyam","editor-scenarios");Q.mkdirSync(a,{recursive:!0});const o=G.join(a,`${t}.json`);let i={};try{i=JSON.parse(Q.readFileSync(o,"utf8"))}catch{}const l={...i,_metadata:r,...s};Q.writeFileSync(o,JSON.stringify(l,null,2),"utf8")}function ub(e,t){const r=G.join(e,".codeyam","editor-scenarios");for(const s of[".json",".seed.json"]){const a=G.join(r,`${t}${s}`);try{Q.unlinkSync(a)}catch{}}}const Di=globalThis.__codeyamTerminalSessions??(globalThis.__codeyamTerminalSessions=new Set);globalThis.__codeyamDetachedPtys??(globalThis.__codeyamDetachedPtys=new Map);function Ri(e,t){const r=JSON.stringify({type:"refresh-preview",...e&&{path:e},...t&&{scenarioId:t}});let s=0;for(const a of Di)try{a.ws.readyState===ci.OPEN&&(a.ws.send(r),s++)}catch{}return s}function pb(){const e=JSON.stringify({type:"hide-results"});let t=0;for(const r of Di)try{r.ws.readyState===ci.OPEN&&(r.ws.send(e),t++)}catch{}return t}function Ii(e){const t=JSON.stringify({type:"set-viewport",...e});let r=0;for(const s of Di)try{s.ws.readyState===ci.OPEN&&(s.ws.send(t),r++)}catch{}return r}const hb=Object.freeze(Object.defineProperty({__proto__:null,broadcastHideResults:pb,broadcastPreviewRefresh:Ri,broadcastSetViewport:Ii},Symbol.toStringTag,{value:"Module"}));function mb(e){if(e.dimension)try{Ii({name:e.dimension,width:e.viewport.width,height:e.viewport.height})}catch{}Ri(e.refreshPath,e.scenarioId)}function fb(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=Me("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return gb(r)}catch{return[]}}function gb(e){const t=e.trim().split(`
331
+ `).filter(s=>s.length>0),r=[];for(const s of t){const a=s[0],o=s[1];let i=s.slice(2).replace(/^[ \t]+/,""),l,d=!1,u;if(a==="A"||o==="A")l="added",d=a==="A";else if(a==="M"||o==="M")l="modified",d=a==="M";else if(a==="D"||o==="D")l="deleted",d=a==="D";else if(a==="R"||o==="R"){l="renamed",d=a==="R";const p=i.indexOf(" -> ");p!==-1&&(u=i.slice(0,p).trim(),i=i.slice(p+4).trim())}else o==="?"?(l="untracked",d=!1):(l="modified",d=a!==" "&&a!=="?");if(i.endsWith("/")){const p=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=ee.join(p,i);try{const m=(y,g)=>{const x=ce.readdirSync(y,{withFileTypes:!0}),b=[];for(const v of x){const N=ee.join(y,v.name),w=ee.relative(p,N);v.isDirectory()?b.push(...m(N,g)):v.isFile()&&b.push(w)}return b},f=m(h,p);for(const y of f)r.push({path:y,status:l,staged:d,...u&&{oldPath:u}})}catch(m){console.error(`Failed to expand directory ${i}:`,m)}}else r.push({path:i,status:l,staged:d,...u&&{oldPath:u}})}return r}function yb(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me("git branch --show-current",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch(r){return console.error("Failed to get current branch:",r),null}}function xb(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const s=Me('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(s)return s[1];try{return Me("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Me("git show-ref --verify --quiet refs/heads/master",{cwd:t,stdio:["pipe","pipe","ignore"]}),"master"}catch{return"main"}}}catch(r){return console.error("Failed to get default branch:",r),"main"}}function bb(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
332
+ `).filter(s=>s.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function xr(){const e=Ce();return e?fb(e):[]}function vb(){const e=Ce();return e?yb(e):null}function wb(){const e=Ce();return e?xb(e):"main"}function Nb(){const e=Ce();return e?bb(e):[]}function np(e,t){const r=Ce();return r?Sb(e,t,r):[]}function Sb(e,t,r){const s=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me(`git diff --name-status ${e}...${t}`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
333
+ `).filter(i=>i.length>0).map(i=>{const l=i.split(" "),d=l[0];let u=l[1],p,h;return d==="A"?h="added":d==="M"?h="modified":d==="D"?h="deleted":d.startsWith("R")?(h="renamed",p=l[1],u=l[2]):h="modified",{path:u,status:h,...p&&{oldPath:p}}})}catch(a){return console.error("Failed to get branch diff:",a),[]}}function rp(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=Me(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let a="";try{a=ce.readFileSync(ee.join(r,e),"utf8")}catch(o){console.error(`Failed to read current file ${e}:`,o),a=""}return{oldContent:s,newContent:a,fileName:e}}catch(s){return console.error(`Failed to get diff for ${e}:`,s),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Cb(e){const t=Ce();return t?rp(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function kb(e,t,r,s){const a=s||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=Me(`git show ${t}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=Me(`git show ${r}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:o,newContent:i,fileName:e}}catch(o){return console.error(`Failed to get branch diff for ${e}:`,o),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function Ys(e,t,r){const s=Ce();return s?kb(e,t,r,s):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}async function jb(e,t,r){const s=G.join(e,".codeyam","journal"),a=G.join(s,"index.json");G.join(s,"screenshots");let o;try{const l=await Ae.readFile(a,"utf8");o=JSON.parse(l)}catch{return}let i=!1;for(const l of o.entries)if(!l.commitSha&&l.scenarioScreenshots)for(let d=0;d<l.scenarioScreenshots.length;d++){const u=l.scenarioScreenshots[d];if(u.name!==t)continue;const p=G.join(s,u.path);try{await Ae.copyFile(r,p),i=!0,console.log(`[editor-register-scenario] Updated journal screenshot for "${t}" in entry "${l.title}"`)}catch(h){console.warn(`[editor-register-scenario] Failed to update journal screenshot: ${h instanceof Error?h.message:h}`)}}i&&Nt.notifyChange("journal")}const mc=Ei;async function _b({request:e}){var t,r;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const s=await e.json();s.url=s.url||s.path||void 0;const a=Hy({componentName:s.componentName,url:s.url,type:s.type});if(!a.valid)return new Response(JSON.stringify({error:a.error}),{status:400,headers:{"Content-Type":"application/json"}});const{name:o,description:i,componentName:l,componentPath:d}=s;if(!o)return new Response(JSON.stringify({error:"name is required"}),{status:400,headers:{"Content-Type":"application/json"}});if(l&&!d)return new Response(JSON.stringify({error:`componentPath is required when componentName is provided. Add "componentPath": "app/components/${l}.tsx" (or the actual file path) to the registration JSON.`}),{status:400,headers:{"Content-Type":"application/json"}});const u=await ze();if(!u)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:p}=await Ie(u),h=$e(),m=process.env.CODEYAM_ROOT_PATH||process.cwd();let f,y,g;if(!s.viewportWidth&&!s.viewportHeight&&!s.dimension&&!s.dimensions){const q=await h.selectFrom("editor_scenarios").selectAll().where("name","=",o).where("project_id","=",p.id).orderBy("created_at","desc").executeTakeFirst();if(q){f=q.viewport_width||void 0,y=q.viewport_height||void 0;try{const J=q.dimensions?JSON.parse(q.dimensions):void 0;Array.isArray(J)&&(g=J)}catch{}}}let x=null;s.dimensions&&s.dimensions.length>0?x=s.dimensions:s.dimension?x=[s.dimension]:g&&g.length>0&&(x=g);const b=(x==null?void 0:x[0])||void 0,v=Pa({bodyWidth:s.viewportWidth||f,bodyHeight:s.viewportHeight||y,dimension:b,codeyamRoot:m});let N=null;if(!l){if(s.pageFilePath)N=s.pageFilePath;else if(s.url){const{scanPageFilePaths:q}=await Promise.resolve().then(()=>Pb),J=Ce()||process.cwd(),{allFiles:z}=q(J);if(N=ju(s.url,z),!N){const B=await import("fs"),H=await import("path"),re=["src/App.tsx","src/App.jsx","src/app/App.tsx","src/popup/App.tsx","src/pages/index.tsx","src/pages/index.jsx","src/routes/index.tsx","app/root.tsx"];for(const ae of re)if(B.existsSync(H.join(J,ae))){N=ae;break}}}}let w=null,C=null;const k=d||N;if(k)try{await We();const J=(await et({})||[]).filter(H=>H.filePath===k),B=J.find(H=>{var re,ae;return((re=H.metadata)==null?void 0:re.notExported)===!1&&((ae=H.metadata)==null?void 0:ae.namedExport)===!1})||J[0];B&&(w=B.sha)}catch{}const j=s.type==="application"||s.type==="user";if(!w&&j&&k){const q=Ce()||process.cwd(),J=Jy({lookupFilePath:k,scenarioType:s.type||null,projectRoot:q});if(!J.valid)return Response.json({error:J.error},{status:400});if(J.needsAnalysis)try{const{runAnalysisForEntities:z}=await import("./analysisRunner-CuR5TvUx.js");await z({projectRoot:q,filePaths:[k],onlyDataStructure:!0});try{const H=(await et({})||[]).filter(X=>X.filePath===k),ae=H.find(X=>{var oe,me;return((oe=X.metadata)==null?void 0:oe.notExported)===!1&&((me=X.metadata)==null?void 0:me.namedExport)===!1})||H[0];ae&&(w=ae.sha)}catch{}if(w)try{const B=await et({});await Vy(h,(B||[]).map(H=>{var re,ae;return{sha:H.sha,name:H.name,filePath:H.filePath||"",isDefaultExport:((re=H.metadata)==null?void 0:re.notExported)===!1&&((ae=H.metadata)==null?void 0:ae.namedExport)===!1}}))}catch{}}catch(z){console.warn(`[editor-register-scenario] Auto analyze-imports failed for ${k}: ${z.message}`)}}l?C=l:N&&N.startsWith("app/")?C=Jt(Ft(N)):s.url&&(C=Ct(s.url));const A=await Uy(h,{projectId:p.id,name:o,description:i||null,componentName:l||null,componentPath:d||null,url:s.url||null,type:s.type||null,viewportWidth:v.width,viewportHeight:v.height,dimensions:x,screenshotPaths:null,pageFilePath:N,entitySha:w,displayName:C}),_=A.scenarioId;if(A.cleanedUpIds.length>0&&(Wy(m,A.cleanedUpIds),console.log(`[editor-register-scenario] Cleaned up ${A.cleanedUpIds.length} duplicate(s) for "${o}"`)),s.seedFrom&&!s.seed){const q=await sc(m,h,s.seedFrom);q?(s.seed=q,s.type||(s.type="application"),console.log(`[editor-register-scenario] Resolved seed data from "${s.seedFrom}"`)):console.warn(`[editor-register-scenario] seedFrom "${s.seedFrom}" not found — no seed data will be used`)}else if(s.seedFrom&&s.seed){const q=await sc(m,h,s.seedFrom);q&&(s.seed=oc(q,s.seed),console.log(`[editor-register-scenario] Merged seed data: base from "${s.seedFrom}", overlay from registration`))}const M=s.type==="application"||s.type==="user",T=new Date().toISOString(),D={name:o,description:i||null,componentName:l||null,componentPath:d||null,url:s.url||null,type:s.type||(M?null:"component"),screenshotPath:null,viewportWidth:v.width,viewportHeight:v.height,dimensions:x,screenshotPaths:null,pageFilePath:N,entitySha:w,displayName:C,createdAt:T,updatedAt:T},R={};if(M&&s.seed){let q=s.seed;if(s.type==="user"&&s.baseScenario)try{const z=G.join(m,".codeyam","editor-scenarios",`${s.baseScenario}.json`),B=await Ae.readFile(z,"utf-8"),H=JSON.parse(B);H.seed&&(q=oc(H.seed,s.seed),console.log(`[editor-register-scenario] Merged seed data from base scenario ${s.baseScenario}`))}catch(z){console.warn(`[editor-register-scenario] Could not read base scenario ${s.baseScenario}: ${z instanceof Error?z.message:z}`)}R.type=s.type,R.seed=q,s.externalApis&&(R.externalApis=s.externalApis),s.session&&(R.session=s.session),s.auth&&(R.auth=s.auth),s.localStorage&&(R.localStorage=s.localStorage);const J=G.join(m,".codeyam","editor-scenarios");await Ae.mkdir(J,{recursive:!0}),await Ae.writeFile(G.join(J,`${_}.seed.json`),JSON.stringify(q,null,2))}else(s.mockData||s.localStorage)&&(s.mockData&&Object.assign(R,s.mockData),s.localStorage&&(R.localStorage=s.localStorage));let L=null;if(M&&!s.seed&&Vr(m)){const J=G.join(m,".codeyam","editor-scenarios",`${_}.json`);let z=!1;try{z=!!JSON.parse(await Ae.readFile(J,"utf-8")).seed}catch{}z||(L='WARNING: This application scenario has no seed data. A seed adapter exists — include "seed":{...} in registration so the page has database rows to render. Without seed data, the page will likely be empty.',console.warn(`[editor-register-scenario] ${L}`))}db(m,_,D,R);let U=null;if(M&&s.seed){const q=Vr(m);if(q){const J=G.join(m,".codeyam","editor-scenarios",`${_}.seed.json`);console.log(`[editor-register-scenario] Running seed adapter: ${q}`);const z=await _i(q,J);if(U={success:z.success,error:z.error},z.success){console.log(`[editor-register-scenario] Seed adapter completed in ${z.durationMs}ms`);const B=z.sessionCookies&&z.sessionCookies.length>0,H=z.externalApis&&Object.keys(z.externalApis).length>0;if(B||H)try{const re=G.join(m,".codeyam","editor-scenarios",`${_}.json`),ae=JSON.parse(await Ae.readFile(re,"utf-8"));B&&(ae.sessionCookies=z.sessionCookies),H&&(ae.externalApis={...ae.externalApis,...z.externalApis}),await Ae.writeFile(re,JSON.stringify(ae,null,2)),console.log("[editor-register-scenario] Saved seed adapter auth data to scenario")}catch(re){console.warn(`[editor-register-scenario] Failed to save seed adapter auth data: ${re}`)}}else console.warn(`[editor-register-scenario] Seed adapter failed: ${z.error}`)}else console.warn(`[editor-register-scenario] No seed adapter found at ${m}/.codeyam/seed-adapter.ts`),U={success:!1,error:"No seed adapter found. Create .codeyam/seed-adapter.ts to use seed-based scenarios."}}Nt.notifyChange("scenario"),console.log(`[editor-register-scenario] Starting auto-capture for scenario "${o}" (id: ${_})`);const W=s.url&&s.url.startsWith("/"),V=!s.url||W?await Ai():null,F=mc(),Y=ki(s.url||null,V,F);console.log(`[editor-register-scenario] Capture URL resolution: explicit=${s.url||"none"}, isPath=${W}, proxy=${V||"none"}, devServer=${F||"none"} → using ${Y||"none"}`);let P=null,O=null,S=[],$=null,I=null,K={};if(Y){const q=It(o),J=await Aa({scenarioId:_,scenarioSlug:q,scenarioType:s.type||void 0,projectRoot:m});Bn(),!U&&J.seedResult&&(U=J.seedResult),console.log(`[editor-register-scenario] Active scenario set to "${q}" (${_}), type=${J.type}, seeded=${J.seeded}, seedResult=${JSON.stringify(J.seedResult??null)}, cache invalidated`),await new Promise(me=>setTimeout(me,300));const z=(t=s.url)!=null&&t.startsWith("/")?`${mc()||"http://localhost:3113"}${s.url}`:Y;for(let me=0;me<5;me++){try{const ve=await fetch(z,{method:"GET",signal:AbortSignal.timeout(3e3)});if(ve.status<500)break;console.log(`[editor-register-scenario] Route returned ${ve.status}, waiting for HMR (attempt ${me+1}/5)...`)}catch{console.log(`[editor-register-scenario] Route not reachable, waiting for HMR (attempt ${me+1}/5)...`)}await new Promise(ve=>setTimeout(ve,2e3))}const B=G.join(m,".codeyam","editor-scenarios","screenshots");await Ae.mkdir(B,{recursive:!0});const H=Mi(import.meta.url),re=await $i(H,m);console.log(`[editor-register-scenario] Capture script: ${re}`);const ae=ji(m),X=x&&x.length>0?x:[null];K={};let oe=null;for(let me=0;me<X.length;me++){const ve=X[me];let je=v;if(ve){const ye=ae[ve];ye!=null&&ye.width&&(ye!=null&&ye.height)&&(je={width:ye.width,height:ye.height})}const te=ve?Au(ve):null,ke=te&&X.length>1?`${_}--${te}.png`:`${_}.png`,Z=G.join(B,ke),pe=`screenshots/${ke}`;me===0&&(I=je,oe=Z);const ie=JSON.stringify({url:Y,outputPath:Z,viewportWidth:je.width,viewportHeight:je.height,...l?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Capture ${ve||"default"}: ${je.width}×${je.height} → ${ke}`);const de=Date.now(),he=await Fi(re,ie,m),_e=Date.now()-de;console.log(`[editor-register-scenario] Capture ${ve||"default"} ${he.success?"succeeded":"FAILED"} in ${_e}ms`),he.success||(console.warn(`[editor-register-scenario] Capture stdout: ${he.output.slice(0,500)}`),console.warn(`[editor-register-scenario] Capture stderr: ${(he.error||"").slice(0,500)}`)),me===0&&(S=Zu(he.output),$=ib(he.output),await Xu(m,_,o,S),S.length>0&&console.warn(`[editor-register-scenario] ${S.length} client-side error(s) detected:`,S)),he.success?(ve&&(K[ve]=pe),me===0&&(P=pe)):me===0&&(O=he.error||"Unknown capture error",console.warn(`[editor-register-scenario] Screenshot capture failed (non-blocking): ${O}`))}if(P){try{await h.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}const me={screenshot_path:P,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};Object.keys(K).length>0&&(me.screenshot_paths=JSON.stringify(K)),await h.updateTable("editor_scenarios").set(me).where("id","=",_).execute(),Nt.notifyChange("scenario"),oe&&await jb(m,o,oe)}}else console.log("[editor-register-scenario] Skipping screenshot — no capture URL available (dev server not running?)");if(console.log(`[editor-register-scenario] Done: scenario="${o}", screenshot=${P?"captured":"skipped"}`),Y&&P)try{const q=Ce()||process.cwd(),J=G.join(q,".codeyam","editor-step.json");let z=null;try{const B=Q.readFileSync(J,"utf8");z=JSON.parse(B).featureStartedAt||null}catch{}if(z){const B=rs(z),H=await h.selectFrom("editor_scenarios").selectAll().where("project_id","=",p.id).orderBy("created_at","asc").execute(),re=Mt(H,X=>`${X.name}::${X.url||"/"}`),ae=xr();if(ae.length>0){let X=!1;try{const{execSync:de}=await import("child_process"),he=de("git rev-list --count HEAD",{cwd:q,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();X=parseInt(he,10)<=1}catch{X=!0}const oe=_u(ae,X),me={},ve=G.join(q,"app");if(Q.existsSync(ve)){const de=(he,_e)=>{for(const ye of Q.readdirSync(he,{withFileTypes:!0}))if(ye.name!=="isolated-components"){if(ye.isDirectory())de(G.join(he,ye.name),_e?`${_e}/${ye.name}`:ye.name);else if(ye.name==="page.tsx"||ye.name==="page.js"){const Re=Ct(_e?`/${_e}`:"/");me[Re]=_e?`app/${_e}/${ye.name}`:`app/${ye.name}`}}};de(ve,"")}let je=[];try{await We(),je=await et({})||[]}catch{}const te=re.map(de=>({componentName:de.component_name||null,componentPath:de.component_path||null,pageFilePath:de.page_file_path??null,url:de.url??null,displayName:de.display_name??null})),ke=Eu(te,me,je),Z=Pu(oe,ke),pe=re.filter(de=>de.created_at<B),ie=new Map;for(const de of pe){const he=rn({componentName:de.component_name,pageFilePath:de.page_file_path,url:de.url});((r=Z[he])==null?void 0:r.status)==="impacted"&&ie.set(he,de)}if(ie.size>0){console.log(`[editor-register-scenario] Recapturing ${ie.size} impacted older scenario(s): ${[...ie.keys()].join(", ")}`);const{recaptureScenarios:de}=await Promise.resolve().then(()=>dv),he=[...ie.values()].map(ye=>({id:ye.id,name:ye.name,url:ye.url,component_name:ye.component_name,dimensions:ye.dimensions,viewport_width:ye.viewport_width,viewport_height:ye.viewport_height}));await de({scenarios:he,codeyamRoot:m,proxyUrl:V,devUrl:F,db:h,importMetaUrl:import.meta.url});const _e=G.join(m,".codeyam","active-scenario.json");await Ae.writeFile(_e,JSON.stringify({scenarioId:_,scenarioSlug:It(o),type:s.type||null,timestamp:new Date().toISOString()})),Bn(),Nt.notifyChange("scenario")}}}}catch(q){console.warn(`[editor-register-scenario] Recapture of impacted scenarios failed (non-blocking): ${q instanceof Error?q.message:q}`)}try{const q=new Date().toISOString(),J=Object.keys(K).length>0?K:null;tp(m,_,{name:o,description:i||null,componentName:l||null,componentPath:d||null,url:s.url||null,type:s.type||null,screenshotPath:P||null,viewportWidth:v.width,viewportHeight:v.height,dimensions:x,screenshotPaths:J,pageFilePath:N,createdAt:q,updatedAt:q})}catch(q){console.warn(`[editor-register-scenario] Failed to update scenario metadata (non-blocking): ${q instanceof Error?q.message:q}`)}try{mb({dimension:b,viewport:v,refreshPath:s.url||void 0,scenarioId:_})}catch{}return new Response(JSON.stringify({success:!0,scenario:{id:_,name:o,description:i,componentName:l||null,componentPath:d||null,screenshotPath:P,url:s.url||null,type:s.type||null,viewportWidth:v.width,viewportHeight:v.height,dimensions:x,screenshotPaths:Object.keys(K).length>0?K:null},updated:!A.isNew,screenshotCaptured:P!==null,capturedViewport:I,captureError:O,clientErrors:S,...$?{visibleText:$}:{},...U?{seedResult:U}:{},...L?{missingSeedWarning:L}:{}}),{headers:{"Content-Type":"application/json"}})}catch(s){const a=s instanceof Error?s.message:String(s);return console.error("[editor-register-scenario] Error:",s),new Response(JSON.stringify({error:a}),{status:500,headers:{"Content-Type":"application/json"}})}}const Eb=Object.freeze(Object.defineProperty({__proto__:null,action:_b},Symbol.toStringTag,{value:"Module"}));function Oi(e){const t={},r=[],s=G.join(e,"app");if(!Q.existsSync(s))return{map:t,allFiles:r};const a=d=>d.split("/").filter(u=>!u.startsWith("(")).join("/"),o=new Set(["_layout.tsx","_layout.ts","_layout.js","layout.tsx","layout.ts","layout.js"]),i=new Set([".tsx",".ts",".jsx",".js"]),l=(d,u)=>{for(const p of Q.readdirSync(d,{withFileTypes:!0}))if(p.name!=="isolated-components")if(p.isDirectory())l(G.join(d,p.name),u?`${u}/${p.name}`:p.name);else if(p.name==="page.tsx"||p.name==="page.js"){const h=u?`app/${u}/${p.name}`:`app/${p.name}`;r.push(h);const m=a(u);t[Ct(m?`/${m}`:"/")]=h}else{if(o.has(p.name))continue;{const h=G.extname(p.name);if(!i.has(h))continue;const m=G.basename(p.name,h),f=u?`app/${u}/${p.name}`:`app/${p.name}`,y=a(u);let g;m==="index"?g=y?`/${y}`:"/":g=y?`/${y}/${m}`:`/${m}`,r.push(f);const x=Ct(g);t[x]||(t[x]=f)}}};return l(s,""),{map:t,allFiles:r}}function sp(e){try{const t=Me("git rev-list --count HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();return parseInt(t,10)<=1}catch{return!0}}function ap(e){try{const t=G.join(e,".codeyam","editor-step.json"),r=Q.readFileSync(t,"utf8");return JSON.parse(r).featureStartedAt||null}catch{return null}}function Ia(e){try{const t=G.join(e,".codeyam","editor-step.json"),r=Q.readFileSync(t,"utf8");return JSON.parse(r).feature||null}catch{return null}}function Li(e){try{const t=G.join(e,".codeyam","editor-step.json"),r=Q.readFileSync(t,"utf8"),s=JSON.parse(r);return typeof s.step=="number"&&s.label?{step:s.step,label:s.label}:null}catch{return null}}function Bi(e){try{const t=G.join(e,".codeyam","editor-step.json"),r=Q.readFileSync(t,"utf8"),s=JSON.parse(r);return Array.isArray(s.appFormats)?s.appFormats:null}catch{return null}}function op(e){try{const t=G.join(e,".codeyam","claude-session-id.txt");return Q.readFileSync(t,"utf8").trim()||null}catch{return null}}function zi(e){try{const t=G.join(e,".codeyam","editor-user-prompt.txt");return Q.readFileSync(t,"utf8").trim()||null}catch{return null}}function ip(e){const t=G.join(e,".codeyam","active-scenario.json");try{return Q.existsSync(t)&&JSON.parse(Q.readFileSync(t,"utf-8")).scenarioId||null}catch{return null}}const Pb=Object.freeze(Object.defineProperty({__proto__:null,detectFirstFeature:sp,readEditorAppFormats:Bi,readEditorFeature:Ia,readEditorSessionId:op,readEditorStep:Li,readEditorUserPrompt:zi,readFeatureStartedAt:ap,readSavedActiveScenarioId:ip,scanPageFilePaths:Oi},Symbol.toStringTag,{value:"Module"}));async function br(e){const{projectRoot:t,scenarioInputs:r,glossaryInputs:s}=e,o=(e.precomputedPageFilePaths??Oi(t)).map,i=new Set(Object.keys(o)),l=e.precomputedGitFiles??xr();if(l.length===0)return{entityChangeStatus:{},pageEntityNames:i};const d=sp(t),u=_u(l,d);let p=[];if(e.precomputedEntities)p=e.precomputedEntities;else try{await We(),p=await et({})||[]}catch{}const h=Eu(r,o,p);let m=h;if(s&&s.length>0){const y=new Set(h.map(x=>x.name)),g=Py(s,y);m=[...h,...g]}return{entityChangeStatus:Pu(u,m),pageEntityNames:i}}function Ab(e,t,r,s){const a=s?s.replace("T"," ").replace(/\.\d{3}Z$/,""):null,o=[],i=[],l=new Set;for(const p of e){const h=rn({componentName:p.component_name,pageFilePath:p.page_file_path,url:p.url});if(!h)continue;const m=t[h];if(!m||p.component_name)continue;const f=p.created_at||"",y=p.updated_at||"";(a?f>=a||y>=a:!0)?(i.push({name:p.name,url:p.url,entityName:h}),l.add(h)):o.push({name:p.name,url:p.url,entityName:h,changeStatus:m.status,lastCaptured:f})}const d=[];for(const[p,h]of Object.entries(t)){if(!r.has(p)||l.has(p))continue;o.some(f=>f.entityName===p)||d.push({entityName:p,changeStatus:h.status})}const u=o.length===0&&d.length===0;return{staleScenarios:o,freshScenarios:i,uncoveredPages:d,pass:u}}async function Tb(){const e=Ce()||process.cwd(),t=await ze();if(!t)return Response.json({error:"No project configured"},{status:400});const r=G.join(e,".codeyam","editor-step.json");let s=null;try{const f=Q.readFileSync(r,"utf8");s=JSON.parse(f).featureStartedAt||null}catch{}const{project:a}=await Ie(t),i=await $e().selectFrom("editor_scenarios").select(["id","name","component_name","component_path","page_file_path","url","type","created_at","updated_at","display_name"]).where("project_id","=",a.id).orderBy("created_at","asc").execute(),l=Mt(i,f=>`${f.name}::${f.url||"/"}`),d=l.map(f=>({componentName:f.component_name||null,componentPath:f.component_path||null,pageFilePath:f.page_file_path??null,url:f.url??null,displayName:f.display_name??null}));let u={},p=new Set;try{const f=await br({projectRoot:e,scenarioInputs:d});u=f.entityChangeStatus,p=f.pageEntityNames}catch{}if(Object.keys(u).length===0)return Response.json({staleScenarios:[],uncoveredPages:[],freshScenarios:[],pass:!0,note:"No entity change data available — cannot determine coverage."});const h=l.map(f=>({name:f.name,component_name:f.component_name,page_file_path:f.page_file_path??null,url:f.url??null,created_at:f.created_at||"",updated_at:f.updated_at||null})),m=Ab(h,u,p,s);return Response.json(m)}const Mb=Object.freeze(Object.defineProperty({__proto__:null,loader:Tb},Symbol.toStringTag,{value:"Module"}));function $b({executionFlows:e,selections:t,onChange:r,disabled:s=!1}){const a=le(i=>t.some(l=>l.flowId===i),[t]),o=le(i=>{a(i.id)?r(t.filter(l=>l.flowId!==i.id)):r([...t,{flowId:i.id,flowName:i.name}])},[t,r,a]);return e.length===0?n("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):n("div",{className:"space-y-3",children:e.map(i=>{const l=a(i.id),d=i.usedInScenarios.length>0;return c("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[c("label",{className:"flex items-start gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:l,onChange:()=>o(i),disabled:s,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!d&&n("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&n("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&n("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&n("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),l&&i.requiredValues.length>0&&c("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[n("span",{className:"text-gray-700 font-medium",children:"Required values:"}),n("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((u,p)=>c("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:u.attributePath})," ",n("span",{className:"text-gray-400",children:u.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:u.value})]},p))})]})]},i.id)})})}function Yi(e,t){const r=(e||[]).map(d=>({...d,usedInScenarios:[]})),s=new Map;r.forEach(d=>{s.set(d.id,d)});const a=[];t.forEach(d=>{var p;const u=((p=d.metadata)==null?void 0:p.coveredFlows)||[];u.forEach(h=>{const m=s.get(h);m&&m.usedInScenarios.push({id:d.id||"",name:d.name})}),a.push({scenario:d,coveredFlowIds:u})});const o=r.length,i=r.filter(d=>d.usedInScenarios.length>0).length,l=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:l,scenariosWithFlows:a}}function Fb(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const Db=({data:e})=>[{title:e!=null&&e.entity?`Create Scenario - ${e.entity.name} - CodeYam`:"Create Scenario - CodeYam"},{name:"description",content:"Create a new scenario"}];async function Rb({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await xa(t,!0),s=r&&r.length>0?r[0]:null;if(!s)throw new Response("Analysis not found",{status:404});const a=(i=s.scenarios)==null?void 0:i.find(l=>l.name===ya);if(!a)throw new Response("Default scenario not found",{status:404});const o=await ze();return ue({analysis:s,defaultScenario:a,entity:s.entity,entitySha:t,projectSlug:o})}function Ib(){var Y;const{analysis:e,defaultScenario:t,entity:r,entitySha:s,projectSlug:a}=lt(),o=Yt(),{iframeRef:i}=Ti(),[l,d]=E(""),[u,p]=E(400),[h,m]=E(!1),[f,y]=E(!1),[g,x]=E(!1),[b,v]=E(null),[N,w]=E(null),[C,k]=E([]),j=fe(()=>{var O;return!((O=e==null?void 0:e.metadata)!=null&&O.executionFlows)||!(e!=null&&e.scenarios)?[]:Yi(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:A,isStarting:_,isLoading:M,showIframe:T,iframeKey:D,onIframeLoad:R}=Un({analysisId:e==null?void 0:e.id,scenarioId:t==null?void 0:t.id,scenarioName:t==null?void 0:t.name,projectSlug:a,enabled:!0}),L=le(async()=>{var P,O,S,$;if(!l.trim()&&C.length===0){v("Please describe how you want to change the scenario or select execution flows");return}y(!0),v(null),w("Generating scenario with AI...");try{const I=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:(P=e.metadata)==null?void 0:P.scenariosDataStructure,flowSelections:C.length>0?C:void 0})}),K=await I.json();if(!I.ok||!K.success)throw new Error(K.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",K.data);const q=K.data;if(!q.name||!q.data)throw new Error("AI response missing required fields (name or data)");w("Saving new scenario..."),x(!0);const J={name:q.name,description:q.description||l,metadata:{data:q.data,interactiveExamplePath:(O=t.metadata)==null?void 0:O.interactiveExamplePath}},z=[...e.scenarios||[],J],B=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:z})}),H=await B.json();if(!B.ok||!H.success)throw new Error(H.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",H);const re=($=(S=H.analysis)==null?void 0:S.scenarios)==null?void 0:$.find(ae=>ae.name===q.name);if(!(re!=null&&re.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),w("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${s}`),1e3);return}if(A){w("Capturing screenshot...");const ae=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:A,scenarioId:re.id,projectId:e.projectId,viewportWidth:1440})}),X=await ae.json();!ae.ok||!X.success?(console.error("[CreateScenario] Capture failed:",X),w("Scenario created! (Screenshot capture failed)")):w("Scenario created and captured!")}else w("Scenario created!");setTimeout(()=>{o(`/entity/${s}/scenarios/${re.id}`)},1e3)}catch(I){console.error("[CreateScenario] Error:",I),v(I instanceof Error?I.message:String(I)),w(null)}finally{y(!1),x(!1)}},[l,C,e,t,s,A,o]),U=f||g,W=le(()=>{m(!0)},[]),V=le(P=>{if(!h)return;const O=P.clientX;O>=250&&O<=600&&p(O)},[h]),F=le(()=>{m(!1)},[]);return se(()=>(h?(document.addEventListener("mousemove",V),document.addEventListener("mouseup",F)):(document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",F)),()=>{document.removeEventListener("mousemove",V),document.removeEventListener("mouseup",F)}),[h,V,F]),c("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-end h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:()=>void o(`/entity/${s}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:r==null?void 0:r.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:r==null?void 0:r.filePath,children:r==null?void 0:r.filePath})]}),c("div",{className:"flex items-end gap-8 shrink-0",children:[n(Ee,{to:`/entity/${s}/scenarios`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-medium border-b-2",style:{color:"#005C75",borderColor:"#005C75"},children:c("span",{className:"flex items-center gap-2",children:["Scenarios",n("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((Y=e==null?void 0:e.scenarios)==null?void 0:Y.length)||0})]})}),n(Ee,{to:`/entity/${s}/related`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Related Entities"}),n(Ee,{to:`/entity/${s}/code`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Code"}),n(Ee,{to:`/entity/${s}/data`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"Data Structure"}),n(Ee,{to:`/entity/${s}/history`,className:"relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline font-normal hover:text-gray-700",style:{color:"#9ca3af"},children:"History"})]})]})}),c("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[c("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${u}px`},children:[c("div",{className:"mb-6",children:[n("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),n("p",{className:"text-sm text-gray-600 leading-relaxed",children:"The preview on the right shows the Default Scenario. Select execution flows and/or describe how you'd like to change it."})]}),j.length>0&&c("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[c("summary",{className:"px-3 py-2 text-sm font-medium text-gray-700 cursor-pointer hover:bg-gray-50 rounded-lg",children:["Select Execution Flows"," ",C.length>0&&c("span",{className:"text-blue-600",children:["(",C.length," selected)"]})]}),n("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:n($b,{executionFlows:j,selections:C,onChange:k,disabled:U})})]}),c("div",{className:"mb-4",children:[n("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),n("textarea",{id:"prompt",value:l,onChange:P=>d(P.target.value),placeholder:"e.g., Show an empty state with no items...",className:"w-full h-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 text-sm resize-none",disabled:U})]}),c("div",{className:"space-y-2",children:[n("button",{onClick:()=>void L(),disabled:U||!l.trim()&&C.length===0,className:"w-full px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium cursor-pointer transition-colors hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed",children:U?"Creating...":"Create Scenario"}),N&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:N}),b&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:b})]})]}),c("div",{onMouseDown:W,style:{width:"20px",position:"absolute",top:0,left:`${u-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[n("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:h?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),n("div",{style:{position:"absolute",top:"50%",left:"10px",transform:"translate(-50%, -50%)",width:"8px",height:"40px",background:"#fff",border:"1px solid rgba(0,0,0,0.15)",borderRadius:"4px",cursor:"col-resize"}})]}),n("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
334
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
335
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
336
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
337
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
338
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(Ra,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:A,isStarting:_,isLoading:M,showIframe:T,iframeKey:D,onIframeLoad:R,projectSlug:a,defaultWidth:1440,defaultHeight:900})})]})]})}const Ob=tt(function(){return n(Da,{children:n(Ib,{})})}),Lb=Object.freeze(Object.defineProperty({__proto__:null,default:Ob,loader:Rb,meta:Db},Symbol.toStringTag,{value:"Module"})),Bb=Ei;async function zb({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioId:r,url:s,viewportWidth:a,viewportHeight:o}=t;if(!r)return new Response(JSON.stringify({error:"scenarioId is required"}),{status:400,headers:{"Content-Type":"application/json"}});const i=await ze();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:l}=await Ie(i),d=$e(),u=await d.selectFrom("editor_scenarios").selectAll().where("id","=",r).where("project_id","=",l.id).executeTakeFirst();if(!u)return new Response(JSON.stringify({error:"Scenario not found"}),{status:404,headers:{"Content-Type":"application/json"}});const p=s??u.url??null,h=p&&p.startsWith("/"),m=!p||h?await Ai():null,f=Bb(),y=ki(p,m,f);if(console.log(`[editor-capture-scenario] URL resolution: explicit=${s||"none"}, db=${u.url||"none"}, proxy=${m||"none"}, devServer=${f||"none"} → captureUrl=${y||"none"}`),!y)return new Response(JSON.stringify({error:"Cannot determine capture URL — no proxy or dev server running"}),{status:400,headers:{"Content-Type":"application/json"}});console.log(`[editor-capture-scenario] Starting capture for scenario "${u.name}" (id: ${r}), url: ${y}`);const g=process.env.CODEYAM_ROOT_PATH||process.cwd(),x=It(u.name);await Aa({scenarioId:r,scenarioSlug:x,scenarioType:u.type||void 0,projectRoot:g}),Bn(),console.log(`[editor-capture-scenario] Active scenario set to "${x}", cache invalidated`),await new Promise(T=>setTimeout(T,300));const b=G.join(g,".codeyam","editor-scenarios","screenshots");await Ae.mkdir(b,{recursive:!0});const v=Mi(import.meta.url),N=await $i(v,g);console.log(`[editor-capture-scenario] Capture script: ${N}`);let w;const C=u;if(t.dimensions&&t.dimensions.length>0)w=t.dimensions;else if(C.dimensions)try{const T=typeof C.dimensions=="string"?JSON.parse(C.dimensions):C.dimensions;w=Array.isArray(T)&&T.length>0?T:[null]}catch{w=[null]}else w=[null];const k=ji(g);let j=null;const A={};let _=[],M=null;for(let T=0;T<w.length;T++){const D=w[T];let R;D&&k[D]?R=k[D]:R=Pa({bodyWidth:a||C.viewport_width||void 0,bodyHeight:o||C.viewport_height||void 0,dimension:D||void 0,codeyamRoot:g});const L=D?Au(D):null,U=L&&w.length>1?`${r}--${L}.png`:`${r}.png`,W=G.join(b,U),V=`screenshots/${U}`,F=JSON.stringify({url:y,outputPath:W,viewportWidth:R.width,viewportHeight:R.height,...u.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-capture-scenario] Capture ${D||"default"}: ${R.width}×${R.height} → ${U}`);const Y=Date.now(),P=await Fi(N,F,g),O=Date.now()-Y;if(console.log(`[editor-capture-scenario] Capture ${D||"default"} ${P.success?"succeeded":"FAILED"} in ${O}ms`),!P.success){console.warn(`[editor-capture-scenario] Capture stdout: ${P.output.slice(0,500)}`),console.warn(`[editor-capture-scenario] Capture stderr: ${(P.error||"").slice(0,500)}`),T===0&&(M=P.error||"Unknown capture error");continue}if(T===0){j=V;const S=Zu(P.output);_=S,await Xu(g,r,u.name,S)}D&&(A[D]=V)}if(!j&&M)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:M}),{status:500,headers:{"Content-Type":"application/json"}});if(j){try{await d.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}const T={screenshot_path:j,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};Object.keys(A).length>0&&(T.screenshot_paths=JSON.stringify(A)),await d.updateTable("editor_scenarios").set(T).where("id","=",r).execute()}return _.length>0&&console.warn(`[editor-capture-scenario] ${_.length} client-side error(s) detected:`,_),Nt.notifyChange("scenario"),new Response(JSON.stringify({success:!0,screenshotPath:j,screenshotPaths:Object.keys(A).length>0?A:null,clientErrors:_}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-capture-scenario] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Yb=Object.freeze(Object.defineProperty({__proto__:null,action:zb},Symbol.toStringTag,{value:"Module"}));async function Ub({request:e,params:t}){const r=t["*"];if(!r)return new Response("Image path is required",{status:400});const s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=ee.join(s,".codeyam","editor-scenarios","screenshots",r),o=ee.resolve(a),i=ee.resolve(ee.join(s,".codeyam","editor-scenarios","screenshots"));if(!o.startsWith(i))return new Response("Invalid path",{status:403});try{const l=await Te.stat(a),d=`"${l.mtimeMs}-${l.size}"`;if(e.headers.get("If-None-Match")===d)return new Response(null,{status:304,headers:{ETag:d,"Cache-Control":"public, max-age=300"}});const p=await Te.readFile(a),h=ee.extname(a).toLowerCase(),m=h===".png"?"image/png":h===".jpg"||h===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(p,{status:200,headers:{"Content-Type":m,"Cache-Control":"public, max-age=300",ETag:d}})}catch{return new Response("Image not found",{status:404})}}const Wb=Object.freeze(Object.defineProperty({__proto__:null,loader:Ub},Symbol.toStringTag,{value:"Module"}));function _t(e,t){for(const r of[".env.local",".env",".env.development.local",".env.development"])try{const s=ee.join(e,r);if(!ce.existsSync(s))continue;const a=ce.readFileSync(s,"utf-8");for(const o of a.split(`
339
+ `)){const i=o.trim();if(!i||i.startsWith("#"))continue;const l=i.indexOf("=");if(l===-1)continue;const d=i.slice(0,l).trim();let u=i.slice(l+1).trim();if((u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),d===t&&u)return u}}catch{}return null}function Uo(e,t,r){const s=ee.join(e,".env.local");let a=[];try{a=ce.readFileSync(s,"utf-8").split(`
340
+ `)}catch{}const o=a.findIndex(l=>{const d=l.trim();if(d.startsWith("#"))return!1;const u=d.indexOf("=");return u===-1?!1:d.slice(0,u).trim()===t}),i=`${t}=${r}`;o>=0?a[o]=i:(a.length>0&&a[a.length-1].trim()!==""&&a.push(""),a.push(i)),ce.writeFileSync(s,a.join(`
341
+ `))}function Jb(e){const t=e.match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(t)return{owner:t[1],repo:t[2]};const r=e.match(/github\.com\/([^/]+)\/([^/.]+)/);return r?{owner:r[1],repo:r[2]}:null}function Kr(e,t,r){(!e.techStack||typeof e.techStack!="object")&&(e.techStack={}),Array.isArray(e.techStack[t])||(e.techStack[t]=[]),e.techStack[t].some(a=>a.name.toLowerCase()===r.name.toLowerCase())||e.techStack[t].push(r)}const fc={name:"GitHub",url:"https://github.com",description:"Source code hosting and version control"},gc={name:"Vercel",url:"https://vercel.com",description:"Frontend deployment and hosting platform"},Hb={name:"Supabase",url:"https://supabase.com",description:"Open-source Firebase alternative with PostgreSQL database",envKeys:["NEXT_PUBLIC_SUPABASE_URL","NEXT_PUBLIC_SUPABASE_ANON_KEY","DATABASE_URL"]},Vb="https://api.supabase.com";async function Dr(e,t,r){try{const s=await fetch(`${Vb}${e}`,{method:(r==null?void 0:r.method)||"GET",headers:{Authorization:`Bearer ${t}`,...r!=null&&r.body?{"Content-Type":"application/json"}:{}},...r!=null&&r.body?{body:JSON.stringify(r.body)}:{},signal:AbortSignal.timeout(15e3)}),a=await s.json();return{ok:s.ok,status:s.status,data:a}}catch(s){return{ok:!1,status:0,data:{error:s instanceof Error?s.message:String(s)}}}}function Kb(e){const t=ee.join(e,"prisma","schema.prisma");try{const r=ce.readFileSync(t,"utf8");return/provider\s*=\s*"postgresql"/.test(r)?"postgresql":/provider\s*=\s*"sqlite"/.test(r)?"sqlite":null}catch{return null}}async function Gb({request:e}){var t,r,s,a,o;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const i=Ce()||process.cwd(),l=await e.json(),d=l.action;if(d==="check-token"){const u=_t(i,"SUPABASE_ACCESS_TOKEN");if(!u)return Response.json({ok:!1,hasToken:!1,error:"SUPABASE_ACCESS_TOKEN not found in .env.local"});const p=await Dr("/v1/projects",u);return p.ok?Response.json({ok:!0,hasToken:!0,tokenVerified:!0}):Response.json({ok:!1,hasToken:!0,error:`Token invalid (${p.status}): ${((t=p.data)==null?void 0:t.message)||"unknown error"}`})}if(d==="save-token"){const u=l.token;if(!u||typeof u!="string")return Response.json({ok:!1,error:"Token is required"});Uo(i,"SUPABASE_ACCESS_TOKEN",u);const p=await Dr("/v1/projects",u);return p.ok?Response.json({ok:!0,saved:!0,tokenVerified:!0}):Response.json({ok:!1,saved:!0,error:`Token saved but verification failed (${p.status})`})}if(d==="list-projects"){const u=_t(i,"SUPABASE_ACCESS_TOKEN");if(!u)return Response.json({ok:!1,error:"SUPABASE_ACCESS_TOKEN not found"});const p=await Dr("/v1/projects",u);if(!p.ok)return Response.json({ok:!1,error:"Failed to list projects"});const h=(Array.isArray(p.data)?p.data:[]).map(x=>({id:x.id,name:x.name,region:x.region,status:x.status}));let m=null;const f=ee.join(i,".codeyam","config.json");let y=null,g=null;try{y=JSON.parse(ce.readFileSync(f,"utf8")).projectTitle||null}catch{}try{const b=Me("git remote get-url origin",{cwd:i,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim().match(/\/([^/]+?)(?:\.git)?$/);b&&(g=b[1])}catch{}for(const x of h){const b=x.name.toLowerCase();if(g&&b===g.toLowerCase()){m=x.id;break}if(y&&b===y.toLowerCase().replace(/\s+/g,"-")){m=x.id;break}}return Response.json({ok:!0,projects:h,suggestedProjectId:m})}if(d==="link-project"){const{projectId:u,projectName:p}=l;if(!u)return Response.json({ok:!1,error:"projectId is required"});const h=_t(i,"SUPABASE_ACCESS_TOKEN");if(!h)return Response.json({ok:!1,error:"SUPABASE_ACCESS_TOKEN not found"});const m=await Dr(`/v1/projects/${u}/api-keys`,h);let f=null;if(m.ok&&Array.isArray(m.data)){const N=m.data.find(w=>w.name==="anon");N&&(f=N.api_key)}const y=`https://${u}.supabase.co`,g=ee.join(i,".codeyam","config.json"),x=JSON.parse(ce.readFileSync(g,"utf8"));x.database={...x.database,provider:"supabase",supabaseProjectRef:u,supabaseProjectName:p||null},Kr(x,"databases",Hb);const b=x.environmentVariables||[],v=(N,w)=>{const C=b.findIndex(k=>(k.key||k.name)===N);C>=0?b[C]={key:N,value:w}:b.push({key:N,value:w}),Uo(i,N,w)};return v("NEXT_PUBLIC_SUPABASE_URL",y),f&&v("NEXT_PUBLIC_SUPABASE_ANON_KEY",f),x.environmentVariables=b,ce.writeFileSync(g,JSON.stringify(x,null,2)),Response.json({ok:!0,supabaseUrl:y,anonKeyAutoFilled:!!f,databaseUrlNeeded:!0})}if(d==="full-status"){const u=_t(i,"SUPABASE_ACCESS_TOKEN"),p=ee.join(i,".codeyam","config.json");let h={};try{h=JSON.parse(ce.readFileSync(p,"utf8"))}catch{}const m=Kb(i),f={hasToken:!!u,tokenVerified:!1,projectLinked:!!((r=h.database)!=null&&r.supabaseProjectRef),projectName:((s=h.database)==null?void 0:s.supabaseProjectName)||null,projectRef:((a=h.database)==null?void 0:a.supabaseProjectRef)||null,dashboardUrl:(o=h.database)!=null&&o.supabaseProjectRef?`https://supabase.com/dashboard/project/${h.database.supabaseProjectRef}`:null,envVarsConfigured:!1,envVars:[{key:"NEXT_PUBLIC_SUPABASE_URL",configured:!1,autoFilled:!1},{key:"NEXT_PUBLIC_SUPABASE_ANON_KEY",configured:!1,autoFilled:!1},{key:"DATABASE_URL",configured:!1,autoFilled:!1}],currentDbProvider:m,migrationNeeded:m==="sqlite"};u&&(await Dr("/v1/projects",u)).ok&&(f.tokenVerified=!0);const y=h.environmentVariables||[],g=new Set;for(const x of y){const b=x.key||x.name;b&&x.value&&g.add(b)}return f.envVars=f.envVars.map(x=>({...x,configured:g.has(x.key)})),f.envVarsConfigured=f.envVars.every(x=>x.configured),Response.json({ok:!0,...f})}if(d==="verify-connection"){const u=ee.join(i,".codeyam","config.json");let p={};try{p=JSON.parse(ce.readFileSync(u,"utf8"))}catch{return Response.json({ok:!1,error:"No config.json found"})}const h=p.environmentVariables||[];let m=null,f=null;for(const y of h){const g=y.key||y.name;g==="NEXT_PUBLIC_SUPABASE_URL"&&y.value&&(m=y.value),g==="NEXT_PUBLIC_SUPABASE_ANON_KEY"&&y.value&&(f=y.value)}if(!m||!f)return Response.json({ok:!1,error:"Supabase URL or anon key not configured"});try{const y=await fetch(`${m}/rest/v1/`,{headers:{apikey:f,Authorization:`Bearer ${f}`},signal:AbortSignal.timeout(1e4)});return y.ok||y.status===200?Response.json({ok:!0,connected:!0}):Response.json({ok:!1,error:`Supabase responded with status ${y.status}`})}catch(y){return Response.json({ok:!1,error:`Connection failed: ${y instanceof Error?y.message:String(y)}`})}}return Response.json({ok:!1,error:`Unknown action: ${d}`})}catch(i){const l=i instanceof Error?i.message:String(i);return Response.json({ok:!1,error:l},{status:500})}}const qb=Object.freeze(Object.defineProperty({__proto__:null,action:Gb},Symbol.toStringTag,{value:"Module"}));async function Qb({params:e}){const t=e["*"];if(!t)return new Response("Image path is required",{status:400});const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","journal","screenshots",t),a=ee.resolve(s),o=ee.resolve(ee.join(r,".codeyam","journal","screenshots"));if(!a.startsWith(o))return new Response("Invalid path",{status:403});try{const i=await Te.readFile(s),l=ee.extname(s).toLowerCase(),d=l===".png"?"image/png":l===".jpg"||l===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"no-store"}})}catch{return new Response("Image not found",{status:404})}}const Zb=Object.freeze(Object.defineProperty({__proto__:null,loader:Qb},Symbol.toStringTag,{value:"Module"})),Xb=["JSX","React","Element","ReactNode"],ev=new Set(["page.tsx","page.ts","index.tsx","index.ts"]);function tv(e){if(e.returnType&&Xb.some(t=>e.returnType.includes(t)))return!0;if(e.filePath){const t=e.filePath.split("/").pop()||"";if(ev.has(t))return!0}return!1}function nv(e){const t=[],r=[];for(const s of e)tv(s)?t.push(s):r.push(s);return{components:t,functions:r}}function go({components:e,functions:t,scenarioCounts:r,testFileExistence:s,testResults:a,clientErrors:o,totalScenarioCounts:i,entityChangeStatus:l,analysisFailedEntities:d,testCaseCounts:u}){const p=e.map(j=>{const A=r[j.name]||0,_=(i==null?void 0:i[j.name])||0,M=l==null?void 0:l[j.name],T=o==null?void 0:o[j.name],D=A>0&&T&&T.length>0;let R;d!=null&&d.has(j.name)?R="analysis_failed":A===0?M&&_>0?R="needs_recapture":R="missing":D?R="has_errors":R="ok";let L;if(R==="missing"){const U=j.filePath.split("/").pop()||"";U==="layout.tsx"||U==="layout.ts"?L=`This is a layout file — register an app-level scenario with pageFilePath instead of componentName: codeyam editor register '{"name":"${j.name} - Default","pageFilePath":"${j.filePath}","url":"/<route>","dimensions":["Desktop"]}'`:U==="page.tsx"||U==="page.ts"?L=`This is a page file — register an app-level scenario with pageFilePath: codeyam editor register '{"name":"${j.name} - Default","pageFilePath":"${j.filePath}","url":"/<route>","dimensions":["Desktop"]}'`:L=`Register a component scenario via an isolation route: codeyam editor isolate ${j.name} then codeyam editor register '{"name":"${j.name} - Default","componentName":"${j.name}","url":"/isolated-components/${j.name}?s=Default","dimensions":["Desktop"]}'`}else R==="needs_recapture"?L=`This component's code or dependencies changed — recapture existing scenarios to update screenshots: codeyam editor recapture ${j.name}`:R==="analysis_failed"&&(L="Analysis failed for this component (likely timed out due to complex dependencies). The component has partial data but may be missing some dependency schemas. Try re-analyzing: codeyam editor analyze-imports");return{name:j.name,filePath:j.filePath,scenarioCount:R==="needs_recapture"?_:A,status:R,...D?{clientErrors:T}:{},...L?{hint:L}:{}}}),h=t.map(j=>{if(!(j.testFile?s[j.testFile]??!1:!1)){const D=j.testFile?void 0:j.filePath.replace(/\.tsx?$/,".test.ts");return{name:j.name,filePath:j.filePath,testFile:j.testFile,testFileExists:!1,status:"missing",...D?{suggestedTestFile:D}:{}}}const _=j.testFile&&a?a[j.testFile]:void 0;if(!_)return{name:j.name,filePath:j.filePath,testFile:j.testFile,testFileExists:!0,status:"ok"};let M;!_.passing&&_.errorMessage?M="runner_error":_.passing?_.hasEntityNameDescribe?M="ok":M="name_mismatch":M="failing";let T;return M==="name_mismatch"?T=`Tests pass but won't show in the CodeYam UI. Add a top-level describe("${j.name}", ...) block in ${j.testFile}`:M==="runner_error"&&_.errorMessage&&(T=`Test runner crashed (not a test failure): ${_.errorMessage}`),{name:j.name,filePath:j.filePath,testFile:j.testFile,testFileExists:!0,testsPassing:_.passing,testsVisibleInUi:_.hasEntityNameDescribe,status:M,..._.errorMessage?{errorMessage:_.errorMessage}:{},...T?{hint:T}:{},...(u==null?void 0:u[j.name])!==void 0?{testCaseCount:u[j.name]}:{}}}),m=p.filter(j=>j.status==="ok").length,f=p.filter(j=>j.status==="has_errors").length,y=p.filter(j=>j.status==="missing").length,g=p.filter(j=>j.status==="needs_recapture").length,x=p.filter(j=>j.status==="analysis_failed").length,b=h.filter(j=>j.status==="ok").length,v=h.filter(j=>j.status==="failing").length,N=h.filter(j=>j.status==="runner_error").length,w=h.filter(j=>j.status==="name_mismatch").length,C=h.filter(j=>j.status==="missing").length,k=h.filter(j=>j.status==="ok"&&j.testCaseCount!==void 0&&j.testCaseCount<3).length;return{components:p,functions:h,summary:{totalComponents:p.length,componentsOk:m,componentsMissing:y,componentsWithErrors:f,componentsNeedingRecapture:g,componentsAnalysisFailed:x,totalFunctions:h.length,functionsOk:b,functionsMissing:C,functionsFailing:v,functionsRunnerError:N,functionsNameMismatch:w,functionsThinCoverage:k,allPassing:y===0&&f===0&&x===0&&v===0&&N===0&&w===0&&C===0}}}function rv({featureStartedAt:e,entityChangeStatus:t}){return t&&Object.keys(t).length>0?{featureStartedAt:e,entityChangeStatus:t}:{featureStartedAt:null,entityChangeStatus:t}}function sv(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>!!(t[r.name]||t[r.filePath]))}async function av(e,t,r){const a=await e.selectFrom("editor_scenarios").select(["entity_sha"]).select(e.fn.count("id").as("count")).where("project_id","=",t).where("entity_sha","is not",null).groupBy("entity_sha").execute();if(a.length===0)return[];const o=a.map(w=>w.entity_sha),i=await e.selectFrom("analyses").select("entity_sha").where("entity_sha","in",o).groupBy("entity_sha").execute(),l=new Set(i.map(w=>w.entity_sha)),d=a.filter(w=>!l.has(w.entity_sha));if(d.length===0)return[];const u=d.map(w=>w.entity_sha),p=await e.selectFrom("entities").select(["sha","name","file_path"]).where("sha","in",u).execute(),h=new Map(p.map(w=>[w.sha,w.name])),m=new Map(p.map(w=>[w.sha,w.file_path])),f=[...new Set(p.map(w=>`${w.name}::${w.file_path}`).filter(w=>!w.startsWith("::")&&!w.endsWith("::")))];let y=new Set;if(f.length>0){const w=[...new Set(p.map(k=>k.name).filter(Boolean))],C=await e.selectFrom("entities").innerJoin("analyses","analyses.entity_sha","entities.sha").select(["entities.name","entities.file_path"]).where("entities.name","in",w).groupBy(["entities.name","entities.file_path"]).execute();y=new Set(C.map(k=>`${k.name}::${k.file_path}`))}const g=d.filter(w=>{const C=w.entity_sha,k=h.get(C),j=m.get(C);if(!k)return!1;const A=`${k}::${j}`;return!y.has(A)});if(g.length===0)return[];const x=g.map(w=>w.entity_sha),b=await e.selectFrom("editor_scenarios").select(["entity_sha","component_name"]).where("project_id","=",t).where("entity_sha","in",x).where("component_name","is not",null).groupBy("entity_sha").execute(),v=new Map(b.map(w=>[w.entity_sha,w.component_name]));let N=new Set;if(r){const w=r.replace("T"," ").replace(/\.\d{3}Z$/,""),C=await e.selectFrom("editor_scenarios").select("entity_sha").where("project_id","=",t).where("entity_sha","in",x).where(k=>k.or([k("created_at",">=",w),k("updated_at",">=",w)])).groupBy("entity_sha").execute();N=new Set(C.map(k=>k.entity_sha))}return g.map(w=>{const C=w.entity_sha;return{entitySha:C,name:h.get(C)||v.get(C)||"Unknown",scenarioCount:Number(w.count),preExisting:r?!N.has(C):!1}})}async function ov(e,t,r){let s=e.selectFrom("editor_scenarios").select(["component_name","name","url"]).where("project_id","=",t).where("component_name","is not",null).where("url","is not",null);if(r){const l=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(d=>d.or([d("created_at",">=",l),d("updated_at",">=",l)]))}const o=(await s.execute()).filter(l=>l.url&&!_a(l.url));if(o.length===0)return[];const i=new Map;for(const l of o){const d=`${l.component_name}::${l.url}`,u=i.get(d);u?u.scenarioNames.push(l.name):i.set(d,{componentName:l.component_name,scenarioNames:[l.name],url:l.url})}return[...i.values()]}async function yc(e,t,r){let s=e.selectFrom("editor_scenarios").select(["component_name"]).select(e.fn.count("id").as("count")).where("project_id","=",t).where("component_name","is not",null).groupBy("component_name");if(r){const i=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(l=>l.or([l("created_at",">=",i),l("updated_at",">=",i)]))}const a=await s.execute(),o={};for(const i of a)i.component_name&&(o[i.component_name]=Number(i.count));return o}async function xc(e,t,r){let s=e.selectFrom("editor_scenarios").select(["page_file_path"]).select(e.fn.count("id").as("count")).where("project_id","=",t).where("component_name","is",null).where("page_file_path","is not",null).groupBy("page_file_path");if(r){const i=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(l=>l.or([l("created_at",">=",i),l("updated_at",">=",i)]))}const a=await s.execute(),o={};for(const i of a)i.page_file_path&&(o[i.page_file_path]=Number(i.count));return o}async function iv(e,t,r){var i;let s=e.selectFrom("editor_scenarios").select(["component_name","component_path","page_file_path","name"]).where("project_id","=",t).where("entity_sha","is",null).where(l=>l.or([l("component_path","is not",null),l("page_file_path","is not",null)]));if(r){const l=r.replace("T"," ").replace(/\.\d{3}Z$/,"");s=s.where(d=>d.or([d("created_at",">=",l),d("updated_at",">=",l)]))}const a=await s.execute();if(a.length===0)return[];const o=new Map;for(const l of a){const d=l,u=d.component_path||d.page_file_path,p=o.get(u);if(p)p.scenarioNames.push(d.name);else{const h=d.component_name||((i=u.split("/").pop())==null?void 0:i.replace(/\.\w+$/,""))||u;o.set(u,{name:h,filePath:u,scenarioNames:[d.name]})}}return[...o.values()].map(l=>({name:l.name,filePath:l.filePath,scenarioCount:l.scenarioNames.length,scenarioNames:l.scenarioNames}))}function lv(e){const t=new Map;for(const r of e){const s=t.get(r.name);s?s.push(r):t.set(r.name,[r])}for(const[r,s]of t)s.length<=1&&t.delete(r);return t}function lp(e){const{scenarios:t,entityChangeStatus:r}=e;if(!r||Object.keys(r).length===0)return[];const s=[];for(const a of t){if(a.updatedInSession||!a.entityName)continue;const o=r[a.entityName];o&&o.status!=="new"&&s.push({scenarioName:a.name,entityName:a.entityName,status:o})}return s}function cv(e,t){const r={},s=new Map;for(const a of t){const o=rn({componentName:a.componentName,pageFilePath:a.pageFilePath,url:a.url});o&&s.set(a.name,o)}for(const[,a]of Object.entries(e)){if(a.errors.length===0)continue;let o=s.get(a.scenarioName);if(!o){const i=a.scenarioName.indexOf(" - ");o=i>=0?a.scenarioName.slice(0,i):a.scenarioName}o&&(r[o]||(r[o]=[]),r[o].push(...a.errors))}return r}async function cp(e){const{scenarios:t,codeyamRoot:r,proxyUrl:s,devUrl:a,db:o,importMetaUrl:i,onProgress:l}=e,d={recaptured:[],failed:[]};if(t.length===0)return d;const u=Mi(i),p=await $i(u,r),h=G.join(r,".codeyam","editor-scenarios","screenshots");for(const m of t)try{const f=It(m.name);await Aa({scenarioId:m.id,scenarioSlug:f,projectRoot:r}),Bn(),await new Promise(w=>setTimeout(w,300));const y=ki(m.url||null,s,a);if(!y){d.failed.push({name:m.name,error:"No capture URL available"});continue}const g=G.join(h,`${m.id}.png`);let x;try{const w=m.dimensions?JSON.parse(m.dimensions):null;Array.isArray(w)&&w.length>0&&(x=w[0])}catch{}const b=Pa({bodyWidth:m.viewport_width||void 0,bodyHeight:m.viewport_height||void 0,dimension:x,codeyamRoot:r}),v=JSON.stringify({url:y,outputPath:g,viewportWidth:b.width,viewportHeight:b.height,...m.component_name?{selector:"#codeyam-capture"}:{}});l==null||l(`Capturing "${m.name}"...`),console.log(`[recapture] Capturing "${m.name}" at ${b.width}x${b.height}`);const N=await Fi(p,v,r);if(N.success)await o.updateTable("editor_scenarios").set({screenshot_path:`screenshots/${m.id}.png`,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")}).where("id","=",m.id).execute(),d.recaptured.push(m.name),l==null||l(`Recaptured "${m.name}"`),console.log(`[recapture] Succeeded: "${m.name}"`);else{const w=N.error||"Unknown capture error";d.failed.push({name:m.name,error:w}),l==null||l(`Failed: "${m.name}" — ${w}`),console.warn(`[recapture] Failed: "${m.name}": ${w}`)}}catch(f){const y=f instanceof Error?f.message:String(f);d.failed.push({name:m.name,error:y}),console.warn(`[recapture] Error for "${m.name}": ${y}`)}return d}const dv=Object.freeze(Object.defineProperty({__proto__:null,recaptureScenarios:cp},Symbol.toStringTag,{value:"Module"}));async function uv({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ce()||process.cwd(),r=await ze();if(!r)return Response.json({error:"No project configured"},{status:400});const{project:s}=await Ie(r),a=$e(),o=process.env.CODEYAM_ROOT_PATH||process.cwd(),i=G.join(t,".codeyam","editor-step.json");let l=null;try{const C=Q.readFileSync(i,"utf8");l=JSON.parse(C).featureStartedAt||null}catch{}try{await We();const C=await et({})||[];await Tu(a,C.map(k=>{var j,A;return{sha:k.sha,name:k.name,filePath:k.filePath||"",isDefaultExport:((j=k.metadata)==null?void 0:j.notExported)===!1&&((A=k.metadata)==null?void 0:A.namedExport)===!1}}))}catch{}const d=await a.selectFrom("editor_scenarios").select(["id","name","component_name","component_path","page_file_path","url","display_name","dimensions","viewport_width","viewport_height","created_at","updated_at"]).where("project_id","=",s.id).orderBy("created_at","asc").execute(),u=Mt(d,C=>`${C.name}::${C.url||"/"}`),p=u.map(C=>({componentName:C.component_name||null,componentPath:C.component_path||null,pageFilePath:C.page_file_path??null,url:C.url??null,displayName:C.display_name??null})),{entityChangeStatus:h}=await br({projectRoot:t,scenarioInputs:p});if(Object.keys(h).length===0)return Response.json({type:"done",recaptured:[],failed:[],total:0,note:"No entity changes detected."});const m=l?rs(l):null,f=u.map(C=>({name:C.name,entityName:rn({componentName:C.component_name,pageFilePath:C.page_file_path,url:C.url}),updatedInSession:m?Ci({created_at:C.created_at,updated_at:C.updated_at},m):!1})),y=lp({scenarios:f,entityChangeStatus:h});if(y.length===0)return Response.json({type:"done",recaptured:[],failed:[],total:0,note:"All scenarios are up to date."});const g=new Set(y.map(C=>C.scenarioName)),x=u.filter(C=>g.has(C.name)).map(C=>({id:C.id,name:C.name,url:C.url,component_name:C.component_name,dimensions:C.dimensions,viewport_width:C.viewport_width,viewport_height:C.viewport_height})),b=await Ai(),v=Ei(),N=new Map(u.map(C=>[C.name,C])),w=new ReadableStream({async start(C){const k=A=>{C.enqueue(new TextEncoder().encode(JSON.stringify(A)+`
342
+ `))};k({type:"start",total:y.length});const j=await cp({scenarios:x,codeyamRoot:o,proxyUrl:b,devUrl:v,db:a,importMetaUrl:import.meta.url,onProgress:A=>{if(A.startsWith('Recaptured "')){const _=A.slice(12,-1);k({type:"success",name:_});const M=N.get(_);if(M)try{cb(o,M.id,`screenshots/${M.id}.png`)}catch{}}else if(A.startsWith('Failed: "')){const _=A.match(/^Failed: "(.+?)" — (.+)$/);_&&k({type:"failure",name:_[1],error:_[2]})}else if(A.startsWith('Capturing "')){const _=A.slice(11,A.indexOf('"',11));k({type:"capturing",name:_})}}});k({type:"done",recaptured:j.recaptured,failed:j.failed,total:y.length}),C.close()}});return new Response(w,{headers:{"Content-Type":"application/x-ndjson","Transfer-Encoding":"chunked"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-recapture-stale] Error:",t),Response.json({error:r},{status:500})}}const pv=Object.freeze(Object.defineProperty({__proto__:null,action:uv},Symbol.toStringTag,{value:"Module"}));async function hv({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,name:s}=t;if(!r||!(s!=null&&s.trim()))return Response.json({error:"Missing required fields: scenarioId, name"},{status:400});const a=s.trim();await $e().updateTable("editor_scenarios").set({name:a,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")}).where("id","=",r).execute();const l=Ce()||process.cwd(),u=lb(l).find(p=>p.id===r);return u&&tp(l,r,{...u.metadata,name:a,updatedAt:new Date().toISOString()}),Response.json({success:!0,name:a})}catch(t){return console.error("[API] Error renaming scenario:",t),Response.json({error:"Failed to rename scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const mv=Object.freeze(Object.defineProperty({__proto__:null,action:hv},Symbol.toStringTag,{value:"Module"}));async function fv({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=t.mode||"overwrite",s=t.localStorage,a=Ce()||process.cwd(),o=ee.join(a,".codeyam"),i=ee.join(o,"active-scenario.json");if(!ce.existsSync(i))return new Response(JSON.stringify({error:"No active scenario"}),{status:400,headers:{"Content-Type":"application/json"}});const d=JSON.parse(ce.readFileSync(i,"utf-8")).scenarioId;if(!d)return new Response(JSON.stringify({error:"No active scenario ID"}),{status:400,headers:{"Content-Type":"application/json"}});const u=ee.join(o,"editor-scenarios"),p=Vr(a);let h=null;if(p){const f=ee.join(o,"tmp",`export-${Date.now()}.json`);ce.mkdirSync(ee.dirname(f),{recursive:!0});const y=await nx(p,f);if(!y.success)return new Response(JSON.stringify({error:`Export failed: ${y.error}`}),{status:500,headers:{"Content-Type":"application/json"}});try{h=JSON.parse(ce.readFileSync(f,"utf-8"))}finally{try{ce.unlinkSync(f)}catch{}}}if(!h&&!s)return new Response(JSON.stringify({error:"No data to save: no seed adapter found and no localStorage provided"}),{status:400,headers:{"Content-Type":"application/json"}});let m=d;if(r==="new"){m=pr.randomUUID();const f=ee.join(u,`${d}.json`);let y={_metadata:{type:"application"}};ce.existsSync(f)&&(y=JSON.parse(ce.readFileSync(f,"utf-8"))),h&&(y.seed=h),s&&(y.localStorage=s),ce.writeFileSync(ee.join(u,`${m}.json`),JSON.stringify(y,null,2)),h&&ce.writeFileSync(ee.join(u,`${m}.seed.json`),JSON.stringify(h,null,2))}else{const f=ee.join(u,`${d}.json`);if(ce.existsSync(f)){const y=JSON.parse(ce.readFileSync(f,"utf-8"));h&&(y.seed=h),s&&(y.localStorage=s),ce.writeFileSync(f,JSON.stringify(y,null,2))}h&&ce.writeFileSync(ee.join(u,`${d}.seed.json`),JSON.stringify(h,null,2))}return Bn(),new Response(JSON.stringify({success:!0,mode:r,scenarioId:m}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const gv=Object.freeze(Object.defineProperty({__proto__:null,action:fv},Symbol.toStringTag,{value:"Module"}));async function yv({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});const t=await e.json(),{prompt:r}=t;if(!r)return Response.json({error:"Missing prompt"},{status:400});const s=Ce()||process.cwd(),a=G.join(s,".codeyam","tmp");Q.mkdirSync(a,{recursive:!0});const o=si.randomUUID().slice(0,8),i=G.join(a,`scenario-prompt-${o}.md`);return Q.writeFileSync(i,r,"utf8"),Response.json({promptFile:i})}const xv=Object.freeze(Object.defineProperty({__proto__:null,action:yv},Symbol.toStringTag,{value:"Module"}));let An=null;async function bv({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{scenarioSlug:r,scenarioId:s,scenarioName:a,scenarioType:o,skipBroadcast:i}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({error:"scenarioSlug is required"}),{status:400,headers:{"Content-Type":"application/json"}});const l=Ce()||process.cwd(),d=ee.join(l,".codeyam"),u=ee.join(d,"active-scenario.json");let p=o||null;if(!p&&s){const x=ee.join(d,"editor-scenarios",`${s}.json`);try{ce.existsSync(x)&&(p=JSON.parse(ce.readFileSync(x,"utf-8")).type||null)}catch{}}let h=null;try{ce.existsSync(u)&&(h=JSON.parse(ce.readFileSync(u,"utf-8")).scenarioId||null)}catch{}const m=h===s&&s!==null;ce.mkdirSync(d,{recursive:!0}),ce.writeFileSync(u,JSON.stringify({scenarioSlug:r,scenarioName:a||null,scenarioId:s||null,type:p,dataFile:s?`.codeyam/editor-scenarios/${s}.json`:null,switchedAt:new Date().toISOString()},null,2));let f=null;const y=p==="application"||p==="user";if(y&&s&&m)console.log(`[editor-switch-scenario] Same scenario "${r}" already active — skipping seed`),f={success:!0};else if(y&&s)if(An&&An.scenarioId===s)console.log(`[editor-switch-scenario] Seed already in progress for "${s}" — reusing`),f=await An.promise;else{const x=Vr(l),b=ee.join(d,"editor-scenarios",`${s}.seed.json`);if(x&&ce.existsSync(b)){console.log(`[editor-switch-scenario] Running seed adapter for ${p} scenario "${a||r}"`);const v=_i(x,b).then(N=>{const w={success:N.success,error:N.error};if(N.success){console.log(`[editor-switch-scenario] Seed adapter completed in ${N.durationMs}ms`);const C=N.sessionCookies&&N.sessionCookies.length>0,k=N.externalApis&&Object.keys(N.externalApis).length>0;if(C||k)try{const j=ee.join(d,"editor-scenarios",`${s}.json`);if(ce.existsSync(j)){const A=JSON.parse(ce.readFileSync(j,"utf-8"));C&&(A.sessionCookies=N.sessionCookies),k&&(A.externalApis={...A.externalApis,...N.externalApis}),ce.writeFileSync(j,JSON.stringify(A,null,2))}}catch{}}else console.warn(`[editor-switch-scenario] Seed adapter failed: ${N.error}`);return w});An={scenarioId:s,promise:v};try{f=await v}finally{An&&An.scenarioId===s&&(An=null)}}else x||(console.warn("[editor-switch-scenario] No seed adapter found — skipping database seeding"),f={success:!1,error:"No seed adapter found"})}Bn();const g=i?0:Ri();return new Response(JSON.stringify({success:!0,scenarioSlug:r,refreshedClients:g,seeded:y,...f?{seedResult:f}:{}}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const vv=Object.freeze(Object.defineProperty({__proto__:null,action:bv},Symbol.toStringTag,{value:"Module"}));var Pe;(e=>{(t=>{t.OPENAI_GPT5_1="openai/gpt-5.1",t.OPENAI_GPT5="openai/gpt-5",t.OPENAI_GPT5_MINI="openai/gpt-5-mini",t.OPENAI_GPT5_NANO="openai/gpt-5-nano",t.OPENAI_GPT4_1="openai/gpt-4.1",t.OPENAI_GPT4_1_MINI="openai/gpt-4.1-mini",t.OPENAI_GPT4_O="openai/gpt-4o",t.OPENAI_GPT4_O_MINI="openai/gpt-4o-mini",t.OPENAI_GPT_OSS_120B_GROQ="openai/gpt-oss-120b-groq",t.OPENAI_GPT_OSS_120B_DEEPINFRA="openai/gpt-oss-120b-deepinfra",t.QWEN3_235B_INSTRUCT_DEEPINFRA="qwen/qwen3-235b-instruct-deepinfra",t.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA="qwen/qwen3-coder-480b-instruct-deepinfra",t.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA="google/gemini-2.5-pro-deepinfra",t.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA="google/gemini-2.5-flash-deepinfra",t.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER="google/gemini-2.5-flash-lite-openrouter",t.META_LLAMA_4_MAVERICK_OPENROUTER="meta-llama/llama-4-maverick-openrouter",t.DEEPSEEK_V3_1_TERMINUS_OPENROUTER="deepseek/v3.1-terminus-openrouter",t.ANTHROPIC_CLAUDE_4_5_HAIKU="anthropic/claude-4.5-haiku",t.ANTHROPIC_CLAUDE_4_5_SONNET="anthropic/claude-4.5-sonnet",t.ANTHROPIC_CLAUDE_4_5_OPUS="anthropic/claude-4.5-opus",t.PHIND_CODELLAMA="phind/codellama",t.GOOGLE_GEMINI_PRO="google/gemini-pro",t.GOOGLE_PALM_2_CODE_CHAT_32K="google/palm-2-code-chat-32k",t.META_CODELLAMA_34B_INSTRUCT="meta-llama/codellama-34b-instruct",t.OPENAI_GPT4_PREVIEW="openai/gpt-4-preview"})(e.Model||(e.Model={}))})(Pe||(Pe={}));function dp(e,t){return e?Object.values(Pe.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const up=dp(process.env.DEFAULT_SMALLER_MODEL,Pe.Model.OPENAI_GPT4_1_MINI),wv=dp(process.env.DEFAULT_LARGER_MODEL,Pe.Model.OPENAI_GPT4_1),Rt={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},yo={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},Nv={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},xo={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},un={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},Sv={[Pe.Model.OPENAI_GPT5_1]:{id:Pe.Model.OPENAI_GPT5_1,provider:Rt,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[Pe.Model.OPENAI_GPT5]:{id:Pe.Model.OPENAI_GPT5,provider:Rt,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[Pe.Model.OPENAI_GPT5_MINI]:{id:Pe.Model.OPENAI_GPT5_MINI,provider:Rt,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[Pe.Model.OPENAI_GPT5_NANO]:{id:Pe.Model.OPENAI_GPT5_NANO,provider:Rt,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[Pe.Model.OPENAI_GPT4_1]:{id:Pe.Model.OPENAI_GPT4_1,provider:Rt,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[Pe.Model.OPENAI_GPT4_1_MINI]:{id:Pe.Model.OPENAI_GPT4_1_MINI,provider:Rt,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[Pe.Model.OPENAI_GPT4_O]:{id:Pe.Model.OPENAI_GPT4_O,provider:Rt,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[Pe.Model.OPENAI_GPT4_O_MINI]:{id:Pe.Model.OPENAI_GPT4_O_MINI,provider:Rt,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[Pe.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:Pe.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:yo,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[Pe.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:Pe.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:yo,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[Pe.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:Pe.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:yo,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[Pe.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:Pe.Model.OPENAI_GPT_OSS_120B_GROQ,provider:Nv,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[Pe.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:Pe.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:un,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[Pe.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:Pe.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:un,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[Pe.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:Pe.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:un,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[Pe.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:Pe.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:un,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[Pe.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:Pe.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:un,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[Pe.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:Pe.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:xo,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[Pe.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:Pe.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:xo,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[Pe.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:Pe.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:xo,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[Pe.Model.PHIND_CODELLAMA]:{id:Pe.Model.PHIND_CODELLAMA,provider:Rt,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[Pe.Model.GOOGLE_GEMINI_PRO]:{id:Pe.Model.GOOGLE_GEMINI_PRO,provider:un,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[Pe.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:Pe.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:un,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[Pe.Model.META_CODELLAMA_34B_INSTRUCT]:{id:Pe.Model.META_CODELLAMA_34B_INSTRUCT,provider:un,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[Pe.Model.OPENAI_GPT4_PREVIEW]:{id:Pe.Model.OPENAI_GPT4_PREVIEW,provider:Rt,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function Oa(e){const t=Sv[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function Cv(e){return Oa(e).maxCompletionTokens}function kv(e){return Oa(e).pricing}const bc=1e6;function jv({model:e,usage:t}){const r=kv(e);return r?t.prompt_tokens*(r.input/bc)+t.completion_tokens*(r.output/bc):null}function _v({chatRequest:e,chatCompletion:t,model:r}){if("error"in t&&t.error)return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),error:JSON.stringify(t.error)};const s=t.usage||{prompt_tokens:0,completion_tokens:0},a=jv({model:r,usage:s});return{model:r,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(t,null,2),input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,cost:a?Math.round(a*1e5)/1e5:void 0}}function Ev({messages:{system:e,prompt:t},model:r,responseType:s,jsonSchema:a}){const o=r??up,i=Oa(o);Cv(o);const l=[];return e&&l.push({role:"system",content:e}),l.push({role:"user",content:[{type:"text",text:t}]}),{messages:l,model:i.apiModelName,response_format:s==="json_schema"&&a?{type:"json_schema",json_schema:{name:a.name,schema:a.schema,strict:a.strict!==!1}}:{type:s&&s=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}let Yr=null;function Pv(e){if(typeof process>"u"||!process.versions||!process.versions.node)return!1;try{const t=Jr(e,".codeyam","secrets.json");if(At(t)){const s=JSON.parse(Yl(t,"utf-8"));if(s.anthropicApiKey||s.ANTHROPIC_API_KEY||s.openAiApiKey||s.OPENAI_API_KEY||s.groqApiKey||s.GROQ_API_KEY)return!0}const r=Jr(Dm(),".codeyam","secrets.json");if(At(r)){const s=JSON.parse(Yl(r,"utf-8"));if(s.anthropicApiKey||s.ANTHROPIC_API_KEY||s.openAiApiKey||s.OPENAI_API_KEY||s.groqApiKey||s.GROQ_API_KEY)return!0}return!!(process.env.OPENAI_API_KEY||process.env.ANTHROPIC_API_KEY||process.env.GROQ_API_KEY)}catch{return!1}}function Av(e){if(typeof process>"u"||!process.versions||!process.versions.node)return!1;const t=Jr(e,".claude");return At(t)}function Zj(e){if(Pv(e))return Yr={mode:"direct-api",projectRoot:e},"direct-api";if(Av(e))return Yr={mode:"claude-cli",projectRoot:e},"claude-cli";throw new Error(`No AI service configured. Please either:
343
+ 1. Add an API key to ~/.codeyam/secrets.json (shared across projects) or .codeyam/secrets.json (project-specific), or
344
+ 2. Use Claude Code CLI (detected by .claude folder)`)}function Tv(){return(Yr==null?void 0:Yr.mode)==="claude-cli"}const Wo="/tmp/codeyam-e2e-tracking";let bo,vo;function Mv(){return bo===void 0&&(bo=process.env.CODEYAM_E2E_TRACK_DATA==="true"),bo}function $v(){return vo===void 0&&(vo=!process.env.CODEYAM_LLM_FIXTURES_DIR),vo}function Fv(){Q.existsSync(Wo)||Q.mkdirSync(Wo,{recursive:!0})}function Dv(e){const t=JSON.stringify(e,null,0);return si.createHash("md5").update(t).digest("hex")}function Rv(e,t,r){return[e].join("_")+".json"}function pp(e,t,r,s){if(!Mv())return;Fv();const a=Rv(e),o=G.join(Wo,a),i=Dv(t);if($v()){const l={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:s,dataHash:i,data:t};Q.writeFileSync(o,JSON.stringify(l,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(Q.existsSync(o)){const l=JSON.parse(Q.readFileSync(o,"utf-8")),d={matches:i===l.dataHash,firstRunHash:l.dataHash};if(d.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{d.differences=Jo(l.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${l.dataHash}`),console.log(` Second run hash: ${i}`);const u=o.replace(".json","_DIFF.json");Q.writeFileSync(u,JSON.stringify({checkpoint:e,entityName:r,scenarioName:s,firstRun:l.data,secondRun:t,differences:d.differences},null,2)),console.log(` Diff saved to: ${u}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function Jo(e,t,r=""){const s=[];if(typeof e!=typeof t)return s.push(`${r||"root"}: type mismatch (${typeof e} vs ${typeof t})`),s;if(e===null||t===null)return e!==t&&s.push(`${r||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(t)}`),s;if(Array.isArray(e)&&Array.isArray(t)){e.length!==t.length&&s.push(`${r||"root"}: array length ${e.length} vs ${t.length}`);const a=Math.max(e.length,t.length);for(let o=0;o<a;o++)s.push(...Jo(e[o],t[o],`${r}[${o}]`));return s}if(typeof e=="object"&&typeof t=="object"){const a=Object.keys(e),o=Object.keys(t),i=Array.from(new Set([...a,...o]));for(const l of i){const d=e[l],u=t[l];l in e?l in t?s.push(...Jo(d,u,`${r?r+".":""}${l}`)):s.push(`${r?r+".":""}${l}: missing in second run`):s.push(`${r?r+".":""}${l}: missing in first run`)}return s}if(e!==t){const a=JSON.stringify(e),o=JSON.stringify(t);a.length<100&&o.length<100?s.push(`${r||"root"}: ${a} vs ${o}`):s.push(`${r||"root"}: values differ (${a.length} chars vs ${o.length} chars)`)}return s}const vc=ii(oi),wc=2;function Iv(e){try{return JSON.parse(e),{valid:!0}}catch(t){return{valid:!1,error:t.message}}}function Ov(e){const t=e.trim(),r=(t.match(/\{/g)||[]).length,s=(t.match(/\}/g)||[]).length,a=(t.match(/\[/g)||[]).length,o=(t.match(/\]/g)||[]).length,i=(t.match(new RegExp('(?<!\\\\)"',"g"))||[]).length;return r>s||a>o||i%2!==0||!t.endsWith("}")&&!t.endsWith("]")}async function hp(e,t,r,s=0){try{const a=`${e}
345
+
346
+ ${t}${r?`
347
+
348
+ Respond with valid JSON only.`:""}`;let o="claude";try{const{stdout:d}=await vc("which claude",{timeout:1e3});o=d.trim()}catch{const d=["/usr/local/bin/claude",`${process.env.HOME}/.nvm/versions/node/v20.16.0/bin/claude`,`${process.env.HOME}/.npm-global/bin/claude`];for(const u of d)try{await vc(`test -x "${u}"`,{timeout:1e3}),o=u;break}catch{}}const{stdout:i,stderr:l}=await new Promise((d,u)=>{var g,x,b;const h=kt(o,["-p",a,"--output-format","json","--max-turns","1"],{env:{...process.env}});(g=h.stdin)==null||g.end();let m="",f="";(x=h.stdout)==null||x.on("data",v=>{const N=v.toString();m+=N}),(b=h.stderr)==null||b.on("data",v=>{f+=v.toString()}),h.on("error",v=>{u(v)}),h.on("close",(v,N)=>{if(v===0)d({stdout:m,stderr:f});else{const w=new Error(`Command failed with exit code ${v}. stderr: ${f.substring(0,500)}`);w.code=v,w.stdout=m,w.stderr=f,u(w)}});const y=setTimeout(()=>{h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},5e3),u(new Error("Claude CLI command timed out after 60 seconds"))},6e4);h.on("close",()=>clearTimeout(y))});try{const d=JSON.parse(i);let u=d.result||d.response||d.text||d.content;if(!u)throw new Error("No response content from Claude CLI");const p=u.match(/^```(?:json)?\s*\n([\s\S]*?)\n```\s*$/);if(p&&(u=p[1]),r){const h=Iv(u);if(h.valid)console.log("✅ Claude CLI: JSON validation passed");else{console.log(`⚠️ Claude CLI: Invalid JSON response (attempt ${s+1}/${wc+1})`),console.log(`⚠️ Claude CLI: JSON error: ${h.error}`),console.log(`⚠️ Claude CLI: Response length: ${u.length} bytes`);const m=Ov(u);if(console.log(`⚠️ Claude CLI: Appears truncated: ${m}`),m&&s<wc){console.log(`🔄 Claude CLI: Attempting to recover truncated JSON (retry ${s+1})`);const f=`The previous response was truncated and incomplete. Here's what was received:
349
+
350
+ \`\`\`json
351
+ ${u}
352
+ \`\`\`
353
+
354
+ Please complete this JSON response. Make sure it's valid, complete JSON that properly closes all braces, brackets, and quotes. Return ONLY the complete, valid JSON.`;try{return await hp(e,f,r,s+1)}catch(y){console.log(`⚠️ Claude CLI: Recovery attempt failed: ${y}`)}}console.log(`⚠️ Claude CLI: Returning invalid JSON response after ${s+1} attempts`),console.log(`⚠️ Claude CLI: Downstream parsing will likely fail. First 500 chars: ${u.substring(0,500)}`)}}return u}catch(d){if(i.trim())return i.trim();throw new Error(`Failed to parse Claude CLI response: ${d}`)}}catch(a){const o=a.message;throw o.includes("command not found")||o.includes("ENOENT")?new Error("Claude Code CLI not found. Please ensure Claude Code is installed."):o.includes("not authenticated")||o.includes("subscription")?new Error("Claude Code CLI not authenticated. Please run `claude` to authenticate."):a}}const _s=new Ym({concurrency:100,timeout:1200*1e3,autoStart:!0}),Nc={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},pn={};async function Ho({type:e,systemMessage:t,prompt:r,jsonResponse:s=!0,jsonSchema:a,model:o=up,attempts:i=0}){var j,A,_,M,T,D,R;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await Lv(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${_s.size}, running=${_s.pending}]`);const l=Date.now();let d,u=0;if(Tv()){console.log("Using Claude CLI mode for AI request");const L=await hp(t,r,s);return{finishReason:"stop",completion:L,stats:{model:"claude-sonnet-4-5",prompt_type:e,system_message:t,prompt_text:r,response:L,input_tokens:0,output_tokens:0,cost:0}}}const p=Oa(o),h=process.env[p.provider.apiKeyEnvVar];if(!h)throw new Error(`API key not found for provider ${p.provider.name}. Please set ${p.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${p.provider.name} for AI request`);const m=new zm({apiKey:h,baseURL:p.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:a?"json_schema":s?"json_object":"text",jsonSchema:a},y=Ev(f),g=await _s.add(()=>(d=Date.now(),Ul(async()=>{const L=Date.now(),U=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],W=setInterval(()=>{const V=Math.floor((Date.now()-L)/1e3),F=Math.floor(V/10)%U.length;Jl(1,`${U[F]} [type=${e}, model=${o}, elapsed=${V}s]`)},1e4);try{return await m.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(W)}},{...Nc,onFailedAttempt:L=>{u++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:L,prompt:r,systemMessage:t,attempts:i,retryCount:u})}})));if(!g)throw new Error("Completion call returned no result");const x=g,b=Date.now(),v=_v({chatRequest:f,chatCompletion:x,model:o});if(!v)throw new Error("Failed to get LLM call stats");v.retries=u,v.wait_ms=d-l,v.duration_ms=b-l;const N=(j=x.choices)==null?void 0:j[0];let w=null;if(N){if(!N.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:x,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");w=(A=N.message)==null?void 0:A.content}let C=w;w&&(C=w.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const k=s?C&&(((_=C.match(/\{[\s\S]*\}/))==null?void 0:_[0])??C):C;if(!k){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:k,rawCompletion:w,chatCompletion:x,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await Ho({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(k.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:w,prompt:r,systemMessage:t}),new Error("Empty completion");if(s)try{JSON.parse(k)}catch(L){if(console.log("CodeYam Error: Invalid JSON in completion",{error:L.message,model:o,completion:k.substring(0,500),rawCompletion:w==null?void 0:w.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:L.message});const U=`Your previous response contained invalid JSON with the following error:
355
+
356
+ ${L.message}
357
+
358
+ Here was your previous response:
359
+ \`\`\`
360
+ ${k}
361
+ \`\`\`
362
+
363
+ Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,W=await _s.add(()=>Ul(async()=>{const O=Date.now(),S=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],$=setInterval(()=>{const I=Math.floor((Date.now()-O)/1e3),K=Math.floor(I/10)%S.length;Jl(1,`${S[K]} [type=${e}, model=${o}, elapsed=${I}s]`)},1e4);try{return await m.chat.completions.create({...y,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:k},{role:"user",content:U}]},{timeout:300*1e3})}finally{clearInterval($)}},{...Nc,onFailedAttempt:O=>{console.log("CodeYam Error: Correction call failed",{error:O,attempts:i})}}));if(!W)throw new Error("Correction call returned no result");const V=W,F=(D=(T=(M=V.choices)==null?void 0:M[0])==null?void 0:T.message)==null?void 0:D.content;let Y=F;F&&(Y=F.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const P=Y&&(((R=Y.match(/\{[\s\S]*\}/))==null?void 0:R[0])??Y);if(!P)throw new Error("Correction attempt returned empty completion");try{JSON.parse(P),console.log("CodeYam: JSON correction successful");const O=Date.now();return v.duration_ms=O-l,{finishReason:V.choices[0].finish_reason,completion:P,stats:v}}catch(O){return console.log("CodeYam Error: Corrected JSON still invalid",{error:O.message,correctedCompletion:P.substring(0,500)}),await Ho({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${L.message}`)}return pp(`completionCall_${e}`,{completion:k,finishReason:x.choices[0].finish_reason}),{finishReason:x.choices[0].finish_reason,completion:k,stats:v}}async function Lv(e,t,r){var o,i,l,d,u;const s=await import("fs"),a=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${t}`);try{if(!s.existsSync(t))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${t}`),new Error(`No LLM fixture files found - directory does not exist: ${t}`);const p=s.readdirSync(t).filter(v=>v.endsWith(".json"));if(p.length===0)throw new Error(`No LLM fixture files found in ${t}`);const h={};for(const v of p)try{const N=s.readFileSync(a.join(t,v),"utf-8"),w=JSON.parse(N);h[w.prompt_type]||(h[w.prompt_type]=[]),h[w.prompt_type].push(w)}catch(N){console.warn(`Failed to parse LLM fixture file ${v}:`,N)}for(const v of Object.keys(h))h[v].sort((N,w)=>{const C=N.created_at??0,k=w.created_at??0;return C-k});const m=h[e];if(!m||m.length===0){const v=Object.keys(h).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${v}`),{finishReason:"stop",completion:"{}",stats:{model:"fixture-fallback",prompt_type:e,system_message:"",prompt_text:"",response:"{}",input_tokens:0,output_tokens:0,cost:0}}}let f;if(["generateEntityScenarioData","generateChunkMockData","generateMissingMockData"].includes(e)&&r){const v=r.match(/Scenario name must match exactly: "([^"]+)"/),N=v==null?void 0:v[1];if(N){const w={};for(const k of m)try{const A=((o=JSON.parse(k.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";w[A]||(w[A]=[]),w[A].push(k)}catch{}const C=w[N];if(C&&C.length>0){const k=`${t}::${e}::${N}`;pn[k]===void 0&&(pn[k]=0);const j=pn[k];pn[k]=(j+1)%C.length,f=C[j],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${N}' [${j+1}/${C.length}]`)}else{const k=Object.keys(w).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${N}'. Available: [${k}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const v=`${t}::${e}`;pn[v]===void 0&&(pn[v]=0);const N=pn[v];pn[v]=(N+1)%m.length,f=m[N],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${N+1}/${m.length}]`)}let g;try{g=((d=(l=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:l.message)==null?void 0:d.content)||f.response}catch{g=f.response}let x=g;g&&(x=g.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const b=x&&(((u=x.match(/\{[\s\S]*\}/))==null?void 0:u[0])??x);return pp(`completionCall_${e}`,{completion:b||"",finishReason:"stop"}),{finishReason:"stop",completion:b||"",stats:{model:f.model??"fixture",prompt_type:e,system_message:f.system_message??"",prompt_text:f.prompt_text??"",response:f.response??"",input_tokens:f.input_tokens??0,output_tokens:f.output_tokens??0,cost:f.cost??0,retries:0,wait_ms:0,duration_ms:1}}}catch(p){throw console.error("CodeYam Test Error: Failed to replay LLM call:",p),p}}function Sc(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function Bv(e){const{propsJson:t,...r}=e,s=JSON.stringify(t,null,2),a=ai(),o=Date.now(),i={...r,id:a,created_at:o,props:s};let l;const d=`${i.object_id}_${a}.json`;if(process.env.DYNAMODB_PATH?l=G.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=G.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),l)try{const p=G.dirname(l);return await Ae.mkdir(p,{recursive:!0}),await Ae.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:a}}catch(p){return console.log("CodeYam Error: Failed to save LLM call to local file",p),{id:"-1"}}const u=Sc();if(!u)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[p,h]of Object.entries(i))typeof h>"u"&&console.log(`CodeYam Warning: LLM call ${a} property ${p} with explicit value 'undefined'`);try{return await new ma().send(new Um({TableName:Sc(),Item:Jm(i,{removeUndefinedValues:!0})})),{id:a}}catch(p){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${u}`,p),{id:"-1"}}}new ma({});new ma({});new ma({});const zv=3,Yv=2,Ui=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+zv*String(t).length*(1+Yv)});new di(Ui());new di(Ui());new di(Ui());class Uv{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(t,r,s){this.byMethodName.has(t)||this.byMethodName.set(t,[]),this.byMethodName.get(t).push(r),s&&(this.byClassAndMethod.has(s)||this.byClassAndMethod.set(s,new Map),this.byClassAndMethod.get(s).set(t,r))}getByMethodName(t){return this.byMethodName.get(t)}getByClassAndMethod(t,r){var s;return(s=this.byClassAndMethod.get(t))==null?void 0:s.get(r)}}class Wv{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Jv{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Hv{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"boolean");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Vv{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class Kv{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];if(s.addType(o,"function"),s.addEquivalence(o.withParameter(1),r.withElement("*")),a.args.length>1){const i=a.args[1];s.addEquivalence(o.withParameter(0),i)}}}isComplete(){return!0}}class Gv{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.getLastFunctionCallSegment();a&&a.args.forEach(o=>{s.addEquivalence(t,o)}),s.addEquivalence(t,r.withElement("*"))}isComplete(){return!0}}class qv{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.withReturnValues();s.addType(a,"unknown")}isComplete(){return!0}}class Qv{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array"),s.addType(t,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>2)for(let o=2;o<a.args.length;o++){const i=a.args[o];s.addEquivalence(r.withElement("*"),i)}}isComplete(){return!0}}class Zv{getReturnType(){return"number"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0)for(let o=0;o<a.args.length;o++)s.addEquivalence(r.withElement("*"),t.withParameter(o))}isComplete(){return!0}}class Xv{getReturnType(){return"string"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class ew{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class tw{getReturnType(){return"array"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class nw{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown"),s.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class rw{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"array");const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r.withElement("*"))}}isComplete(){return!0}}class sw{getReturnType(){return"object"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"array")}}isComplete(){return!0}}class aw{getReturnType(){return"string[]"}addEquivalences(t,r,s){s.addType(r,"string"),s.addType(t,"string[]"),s.addEquivalence(t.withReturnValues().withElement("*"),r)}isComplete(){return!0}}class ow{getReturnType(){return"unknown"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(a&&a.args.length>0){const o=a.args[0];s.addType(o,"function"),s.addEquivalence(o.withParameter(0),r),s.addEquivalence(t.withProperty("functionCallReturnValue"),o.withProperty("returnValue"))}}isComplete(){return!0}}class iw{getReturnType(){return"unknown"}addEquivalences(t,r,s){t.getLastFunctionCallSegment()}isComplete(){return!0}}class lw{getReturnType(){return"array"}addEquivalences(t,r,s){const a=t.getLastFunctionCallSegment();if(s.addType(t.withParameter(1),"function"),a&&a.args.length>0){const o=a.args[0];s.addEquivalence(t.withParameter(0),o)}}isComplete(){return!0}}class cw{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(t,"boolean")}isComplete(){return!0}}class dw{getReturnType(){return"boolean"}addEquivalences(t,r,s){s.addType(t,"boolean")}isComplete(){return!0}}function uw(){const e=new Uv;return e.register("filter",new Wv,"Array"),e.register("map",new ew,"Array"),e.register("flatMap",new tw,"Array"),e.register("join",new Xv,"Array"),e.register("find",new Vv,"Array"),e.register("findLast",new rw,"Array"),e.register("at",new nw,"Array"),e.register("reduce",new Kv,"Array"),e.register("concat",new Gv,"Array"),e.register("slice",new qv,"Array"),e.register("splice",new Qv,"Array"),e.register("push",new Zv,"Array"),e.register("some",new Jv,"Array"),e.register("every",new Hv,"Array"),e.register("fromEntries",new sw,"Object"),e.register("split",new aw,"String"),e.register("then",new ow,"Promise"),e.register("useState",new lw,"React"),e.register("useMemo",new iw,"React"),e.register("has",new cw),e.register("delete",new dw),e}uw();new Set(Object.getOwnPropertyNames(Array.prototype).filter(e=>typeof Array.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(String.prototype).filter(e=>typeof String.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Number.prototype).filter(e=>typeof Number.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Boolean.prototype).filter(e=>typeof Boolean.prototype[e]=="function")),new Set(Object.getOwnPropertyNames(Date.prototype).filter(e=>typeof Date.prototype[e]=="function"));const pw=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),hw=new Set(["find","findLast","at","pop","shift"]),mw=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),fw=new Set([...pw,...hw,...mw]),gw=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),yw=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),xw=new Set([...gw,...yw]);[...fw,...xw];class bw{constructor(t){this.depth=0,this.traceCount=0,this.defaultOutput=(r,s)=>{const a=" ".repeat(this.depth),o=this.timestamps?`[${Date.now()}] `:"";s?console.info(`${o}${a}${r}`,JSON.stringify(s)):console.info(`${o}${a}${r}`)},this.enabled=t.enabled,this.pathPatterns=t.pathPatterns??[],this.scopePatterns=t.scopePatterns??[],this.maxDepth=t.maxDepth??50,this.output=t.output??this.defaultOutput,this.timestamps=t.timestamps??!1}shouldTrace(t){return!this.enabled||this.depth>=this.maxDepth?!1:!!(this.pathPatterns.length===0&&this.scopePatterns.length===0||t.path&&this.pathPatterns.length>0&&this.pathPatterns.some(r=>r.test(t.path))||t.scope&&this.scopePatterns.length>0&&this.scopePatterns.some(r=>r.test(t.scope)))}trace(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[TRACE] ${t}`,r))}traceEnter(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[ENTER] ${t}`,r),this.depth++)}traceExit(t,r={}){this.depth>0&&this.depth--,this.shouldTrace(r)&&this.output(`[EXIT] ${t}`,r)}traceWarn(t,r={}){this.shouldTrace(r)&&(this.traceCount++,this.output(`[WARN] ${t}`,r))}enable(){this.enabled=!0}disable(){this.enabled=!1}resetDepth(){this.depth=0}getStats(){return{traceCount:this.traceCount,currentDepth:this.depth,enabled:this.enabled}}reset(){this.depth=0,this.traceCount=0}}new bw({enabled:!1});function Tn(e,t){const r={added:{},removed:{},changed:{}},s=new Set(Object.keys(e??{})),a=new Set(Object.keys(t??{}));for(const o of a)s.has(o)||(r.added[o]=t[o]);for(const o of s)a.has(o)||(r.removed[o]=e[o]);for(const o of s)a.has(o)&&e[o]!==t[o]&&(r.changed[o]={from:e[o],to:t[o]});return r}function vw(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function Es(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let ww=0;class Wi{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++ww,this.enabled=(t==null?void 0:t.enabled)??!1,this.outputPath=(t==null?void 0:t.outputPath)??"/tmp/codeyam/transform-trace.json",this.enabled&&console.log(`[Tracer] Initialized (id=${this.tracerId}, output=${this.outputPath})`)}log(t){this.isEnabled()&&console.log(`[Tracer] ${t}`)}isEnabled(){const t=process.env.CODEYAM_TRACE_TRANSFORMS;return t==="1"||t==="true"?!0:this.enabled}enable(){this.enabled=!0}disable(){this.enabled=!1}setOutputPath(t){this.outputPath=t}setProjectSlug(t){this.projectSlug=t}startEntity(t){if(!this.isEnabled())return;this.currentEntity=t.name;const r=this.traces.get(t.name);if(r){this.log(`startEntity: ${t.name} already exists, preserving ${r.stages.length} stages`);return}this.log(`startEntity: ${t.name}`),this.traces.set(t.name,{entityName:t.name,entityType:t.entityType,filePath:t.filePath,stages:[],operations:[]})}snapshot(t,r,s){var d,u,p,h;if(!this.isEnabled())return;const a=this.traces.get(t);if(!a)return this.log(`snapshot: no trace for ${t}, creating one`),this.startEntity({name:t,entityType:"unknown",filePath:"unknown"}),this.snapshot(t,r,s);this.log(`snapshot: ${t} → ${r}`),this.currentStage=r;const o=JSON.parse(JSON.stringify(s)),i={stage:r,timestamp:Date.now(),data:o},l=a.stages[a.stages.length-1];if(l&&(i.diffFromPrevious={signatureSchema:Tn(l.data.signatureSchema,o.signatureSchema),returnValueSchema:Tn(l.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||l.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const m=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(l.data.dependencySchemas??{})]);for(const f of m){const y=(d=l.data.dependencySchemas)==null?void 0:d[f],g=(u=o.dependencySchemas)==null?void 0:u[f];for(const x of new Set([...Object.keys(y??{}),...Object.keys(g??{})])){const b=`${f}::${x}`,v=(p=y==null?void 0:y[x])==null?void 0:p.returnValueSchema,N=(h=g==null?void 0:g[x])==null?void 0:h.returnValueSchema,w=Tn(v,N);vw(w)&&(i.diffFromPrevious.dependencySchemas[b]=w)}}}a.stages.push(i)}operation(t,r){if(!this.isEnabled())return;const s=this.traces.get(t);s&&s.operations.push({...r,stage:r.stage??this.currentStage??void 0,timestamp:Date.now()})}computeFlushSummary(){var a;const t={},r=new Map;for(const[o,i]of this.traces){let l=0;for(const d of i.stages){if(!d.diffFromPrevious)continue;const p=`${((a=i.stages[i.stages.indexOf(d)-1])==null?void 0:a.stage)??"start"}→${d.stage}`;if(t[p]||(t[p]={added:0,removed:0,changed:0}),d.diffFromPrevious.signatureSchema){const h=d.diffFromPrevious.signatureSchema;t[p].added+=Object.keys(h.added).length,t[p].removed+=Object.keys(h.removed).length,t[p].changed+=Object.keys(h.changed).length,l+=Es(h)}if(d.diffFromPrevious.returnValueSchema){const h=d.diffFromPrevious.returnValueSchema;t[p].added+=Object.keys(h.added).length,t[p].removed+=Object.keys(h.removed).length,t[p].changed+=Object.keys(h.changed).length,l+=Es(h)}}r.set(o,l)}const s=[...r.entries()].sort((o,i)=>i[1]-o[1]).slice(0,10).map(([o])=>o);return{stageChangeCounts:t,entitiesWithMostChanges:s}}flush(){if(!this.isEnabled())return;if(this.traces.size===0){this.log("flush: no traces to write");return}const t=Array.from(this.traces.keys()),r=t.map(u=>`${u}(${this.traces.get(u).stages.length})`).join(", ");this.log(`flush: writing ${t.length} entities: ${r}`);const{stageChangeCounts:s,entitiesWithMostChanges:a}=this.computeFlushSummary(),o={timestamp:new Date().toISOString(),projectSlug:this.projectSlug,entityCount:this.traces.size},i={stageChangeCounts:s,entitiesWithMostChanges:a},l=G.dirname(this.outputPath);Q.existsSync(l)||Q.mkdirSync(l,{recursive:!0});const d=Q.openSync(this.outputPath,"w");try{Q.writeSync(d,`{
364
+ "meta": `),Q.writeSync(d,JSON.stringify(o,null,2)),Q.writeSync(d,`,
365
+ "summary": `),Q.writeSync(d,JSON.stringify(i,null,2)),Q.writeSync(d,`,
366
+ "entities": {`);let u=!0;for(const[p,h]of this.traces)u||Q.writeSync(d,","),Q.writeSync(d,`
367
+ ${JSON.stringify(p)}: `),Q.writeSync(d,JSON.stringify(h,null,2)),u=!1;Q.writeSync(d,`
368
+ }
369
+ }
370
+ `),this.log(`flush: wrote trace to ${this.outputPath}`)}finally{Q.closeSync(d)}}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=Q.readFileSync(t,"utf-8"),s=JSON.parse(r),a=new Wi({enabled:!1});a.projectSlug=s.meta.projectSlug;for(const[o,i]of Object.entries(s.entities))a.traces.set(o,i);return a}getSummary(){var a,o,i;const t={},r=new Map;for(const[l,d]of this.traces){let u=0;for(let p=1;p<d.stages.length;p++){const h=d.stages[p],f=`${((a=d.stages[p-1])==null?void 0:a.stage)??"start"}→${h.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=h.diffFromPrevious)!=null&&o.signatureSchema){const y=h.diffFromPrevious.signatureSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,u+=Es(y)}if((i=h.diffFromPrevious)!=null&&i.returnValueSchema){const y=h.diffFromPrevious.returnValueSchema;t[f].added+=Object.keys(y.added).length,t[f].removed+=Object.keys(y.removed).length,t[f].changed+=Object.keys(y.changed).length,u+=Es(y)}}r.set(l,u)}const s=[...r.entries()].sort((l,d)=>d[1]-l[1]).slice(0,10).map(([l,d])=>({name:l,totalChanges:d}));return{entityCount:this.traces.size,stageChangeCounts:t,entitiesWithMostChanges:s}}getEntitySummary(t){const r=this.traces.get(t);return r?{entityName:t,stages:r.stages.map(s=>({stage:s.stage,diffFromPrevious:s.diffFromPrevious?{signatureSchema:s.diffFromPrevious.signatureSchema,returnValueSchema:s.diffFromPrevious.returnValueSchema}:void 0}))}:null}getOperations(t,r){const s=this.traces.get(t);return s?r?s.operations.filter(a=>a.path&&r.test(a.path)):s.operations:[]}tracePath(t,r){var o,i;const s=this.traces.get(t),a=[];if(!s)return{entityName:t,path:r,history:a};for(const l of s.stages){const d=(o=l.data.signatureSchema)==null?void 0:o[r],u=(i=l.data.returnValueSchema)==null?void 0:i[r],p=d??u;p!==void 0&&a.push({stage:l.stage,value:p})}for(const l of s.operations)l.path===r&&a.push({operation:l.operation,stage:l.stage,value:l.after??l.before,context:l.context});return{entityName:t,path:r,history:a}}getEntityTrace(t){return this.traces.get(t)}getEntityNames(){return[...this.traces.keys()]}findProperty(t,r){const s=this.traces.get(t);if(!s)return[];const a=[],o=new RegExp(`(^|\\.)${r}(\\.|\\[|$)`);for(const i of s.stages){for(const[l,d]of Object.entries(i.data.signatureSchema??{}))o.test(l)&&a.push({stage:i.stage,path:l,type:d,schemaType:"signature"});for(const[l,d]of Object.entries(i.data.returnValueSchema??{}))o.test(l)&&a.push({stage:i.stage,path:l,type:d,schemaType:"returnValue"});for(const[l,d]of Object.entries(i.data.dependencySchemas??{}))for(const[u,p]of Object.entries(d))for(const[h,m]of Object.entries(p.returnValueSchema??{}))o.test(h)&&a.push({stage:i.stage,path:`${l}/${u}::${h}`,type:m,schemaType:"dependency"})}return a}findTypeInconsistencies(t){const r=this.traces.get(t);if(!r)return[];let s=r.stages[r.stages.length-1];for(let d=r.stages.length-1;d>=0;d--)if(Object.keys(r.stages[d].data.dependencySchemas??{}).length>0){s=r.stages[d];break}if(!s)return[];const a=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(d,u)=>{const p=d.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!p)return;const h=p[1],m=p[2]==="[]";if(a.has(h))return;const f=h+(m?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:d,type:u})};for(const[,d]of Object.entries(s.data.dependencySchemas??{}))for(const[,u]of Object.entries(d))for(const[p,h]of Object.entries(u.returnValueSchema??{}))i(p,h);const l=[];for(const[d,u]of o)new Set(u.map(h=>h.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&l.push({propertyName:d,paths:u.map(h=>({...h,stage:s.stage}))});return l.sort((d,u)=>{const p=new Set(d.paths.map(m=>m.type)).size;return new Set(u.paths.map(m=>m.type)).size-p}),l}getStageDiffSummary(t,r,s){const a=this.traces.get(t);if(!a)return null;const o=a.stages.find(m=>m.stage===r),i=a.stages.find(m=>m.stage===s);if(!o||!i)return null;const l={added:[],removed:[],typeChanged:[]},d=o.data.returnValueSchema??{},u=i.data.returnValueSchema??{},p=new Set(Object.keys(d)),h=new Set(Object.keys(u));for(const m of h)p.has(m)?d[m]!==u[m]&&l.typeChanged.push({path:m,from:d[m],to:u[m]}):l.added.push(`${m}: ${u[m]}`);for(const m of p)h.has(m)||l.removed.push(`${m}: ${d[m]}`);return l}traceSchemaTransform(t,r,s,a,o){if(!this.enabled)return a(s),s;const i={...s};a(s);const l=Tn(i,s);for(const[d,u]of Object.entries(l.added))this.operation(t,{operation:r,path:d,before:void 0,after:u,context:{...o,changeType:"added"}});for(const[d,u]of Object.entries(l.removed))this.operation(t,{operation:r,path:d,before:u,after:void 0,context:{...o,changeType:"removed"}});for(const[d,{from:u,to:p}]of Object.entries(l.changed))this.operation(t,{operation:r,path:d,before:u,after:p,context:{...o,changeType:"changed"}});return s}traceSchemaTransformResult(t,r,s,a,o){if(!this.enabled)return;const i=Tn(s,a);for(const[l,d]of Object.entries(i.added))this.operation(t,{operation:r,path:l,before:void 0,after:d,context:{...o,changeType:"added"}});for(const[l,d]of Object.entries(i.removed))this.operation(t,{operation:r,path:l,before:d,after:void 0,context:{...o,changeType:"removed"}});for(const[l,{from:d,to:u}]of Object.entries(i.changed))this.operation(t,{operation:r,path:l,before:d,after:u,context:{...o,changeType:"changed"}})}traceDependencySchemaTransform(t,r,s,a,o="both"){if(!this.enabled){for(const i in s)for(const l in s[i]){const d=s[i][l];(o==="signature"||o==="both")&&d.signatureSchema&&a(d.signatureSchema),(o==="returnValue"||o==="both")&&d.returnValueSchema&&a(d.returnValueSchema)}return}for(const i in s)for(const l in s[i]){const d=s[i][l],u={filePath:i,dependencyName:l};(o==="signature"||o==="both")&&d.signatureSchema&&this.traceSchemaTransform(t,r,d.signatureSchema,a,{...u,schemaType:"signature"}),(o==="returnValue"||o==="both")&&d.returnValueSchema&&this.traceSchemaTransform(t,r,d.returnValueSchema,a,{...u,schemaType:"returnValue"})}}traceDependencySchemaChanges(t,r,s,a){var i;if(!this.enabled){a();return}const o={};for(const l in s){o[l]={};for(const d in s[l]){const u=s[l][d];o[l][d]={sig:{...u.signatureSchema||{}},rv:{...u.returnValueSchema||{}}}}}a();for(const l in s)for(const d in s[l]){const u=s[l][d],p=(i=o[l])==null?void 0:i[d],h={filePath:l,dependencyName:d};if(u.signatureSchema){const m=(p==null?void 0:p.sig)||{},f=Tn(m,u.signatureSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...h,schemaType:"signature",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...h,schemaType:"signature",changeType:"changed"}})}if(u.returnValueSchema){const m=(p==null?void 0:p.rv)||{},f=Tn(m,u.returnValueSchema);for(const[y,g]of Object.entries(f.added))this.operation(t,{operation:r,path:y,before:void 0,after:g,context:{...h,schemaType:"returnValue",changeType:"added"}});for(const[y,{from:g,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:y,before:g,after:x,context:{...h,schemaType:"returnValue",changeType:"changed"}})}}}}function Nw(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const Cc=new Wi({enabled:Nw(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{Cc.isEnabled()&&Cc.flush()});function mp(e){if(e==null)return null;const t=e.match(/```json\s*([\s\S]*?)\s*```/);t&&(e=t[1]),e=e.replace(/"[^"]+"\s*:\s*undefined\s*,?\s*/g,""),e=e.replace(/,(\s*[}\]])/g,"$1");try{return Wm.parse(e)}catch(r){const a=r.message.match(/invalid character .* at (\d+):(\d+)/);if(a){const o=parseInt(a[2],10);if(e.substring(o-2,o-1)==='"')return e=e.substring(0,o-2)+"\\"+e.substring(o-2),mp(e)}return null}}function Sw({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:s}){let a="";return s&&s.length>0&&(a=`
371
+ User-selected Execution Flow Values:
372
+ The user has specifically requested these values be used in the scenario:
373
+ ${s.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
374
+ `)}
375
+
376
+ IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
377
+ `),`Mock Scenario Data Structure:
378
+ \`\`\`
379
+ ${JSON.stringify(r,null,2)}
380
+ \`\`\`
381
+ Existing Mock Scenario Data:
382
+ \`\`\`
383
+ ${JSON.stringify(t,null,2)}
384
+ \`\`\`
385
+ ${a}
386
+ New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
387
+ `}function Cw({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}){const o=s.find(i=>i.name===ya);return`Mock Scenario Data Structure:
388
+ \`\`\`
389
+ ${JSON.stringify({props:a.arguments,dataVariables:a.dataForMocks},null,2)}
390
+ \`\`\`
391
+
392
+ Existing Mock Scenario Data:
393
+ \`\`\`
394
+ ${JSON.stringify(s.map(i=>({name:i.name,data:Lr(o.metadata.data,i.metadata.data)})),null,2)}
395
+ \`\`\`
396
+
397
+ Mock Scenario that should be edited: "${t}"
398
+ ${r?`The portion of the data that should be edited:
399
+ \`\`\`
400
+ ${JSON.stringify(r,null,2)}
401
+ \`\`\``:""}
402
+
403
+ How this data should be changed: "${e}"
404
+ `}async function kw({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,flowSelections:o,model:i}){const l=t?Cw({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}):Sw({description:e,existingScenarios:s,scenariosDataStructure:a,flowSelections:o}),d=await Ho({type:"guessScenarioDataFromDescription",systemMessage:t?_w(r):jw,prompt:l,model:i??wv});await Bv({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,model:i},...d.stats});const{completion:u}=d;return u?mp(u):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const jw=`
405
+ You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
406
+
407
+ Your goal is to add one scenario to the list of existing scenarios by generating an english name, proper description, and a JSON data structure that describes the data that would be used in a scenario for the code.
408
+
409
+ The data for the scenario will be merged with the "Default Scenario" data, so you don't need to replicate any data in the default scenario but must overwrite any data that should be different.
410
+
411
+ You must respond with valid JSON following this format of this TS type definition:
412
+ \`\`\`
413
+ export type ScenarioData = {
414
+ name: string;
415
+ description: string;
416
+ data: {
417
+ mockData: { [key: string]: unknown };
418
+ argumentsData: { [key: string]: unknown };
419
+ };
420
+ };
421
+
422
+ \`\`\`
423
+ `,_w=e=>`
424
+ You will be provided with a list of data secnarios for a component and the overall structure for the data. Additionally you'll receive a description for a new scenario written by the user.
425
+
426
+ Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
427
+ ${e?`
428
+ We only want to edit a specific portion of the data, which is provided in the "The portion of the data that should be edited" section. You should only change the data that is provided in this section.`:""}
429
+
430
+ Always return the complete data structure for the scenario, with both mockData and argumentsData, even if you only changed a small portion of the data.
431
+
432
+ You must respond with valid JSON following this type definition:
433
+ \`\`\`
434
+ {
435
+ data: {
436
+ mockData: { [key: string]: unknown };
437
+ argumentsData: { [key: string]: unknown };
438
+ }
439
+ }
440
+ \`\`\`
441
+ `;async function Ew({request:e}){if(e.method!=="POST")return ue({error:"Method not allowed"},{status:405});try{const t=await e.json(),{description:r,existingScenarios:s,scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:l}=t;if(!r&&(!l||l.length===0))return ue({error:"Missing required field: description or flowSelections"},{status:400});const d=await kw({description:r||"",existingScenarios:s??[],scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:l}),u=(d==null?void 0:d.data)||d;return ue({success:!0,data:u})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),ue({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const Pw=Object.freeze(Object.defineProperty({__proto__:null,action:Ew},Symbol.toStringTag,{value:"Module"})),Aw="https://api.vercel.com";async function it(e,t,r){try{const s=await fetch(`${Aw}${e}`,{method:(r==null?void 0:r.method)||"GET",headers:{Authorization:`Bearer ${t}`,...r!=null&&r.body?{"Content-Type":"application/json"}:{}},...r!=null&&r.body?{body:JSON.stringify(r.body)}:{},signal:AbortSignal.timeout(15e3)}),a=await s.json();return{ok:s.ok,status:s.status,data:a}}catch(s){return{ok:!1,status:0,data:{error:s instanceof Error?s.message:String(s)}}}}function kc(e){try{const t=Me("git remote get-url origin",{cwd:e,encoding:"utf8"}).trim();return Jb(t)}catch{return null}}async function Tw({request:e}){var t,r,s,a,o,i,l,d,u,p,h,m,f,y,g,x,b,v,N,w,C,k,j,A,_,M,T,D,R,L,U,W,V,F;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const Y=Ce()||process.cwd(),P=await e.json(),O=P.action;if(O==="check-token"){const S=_t(Y,"VERCEL_TOKEN");if(!S)return Response.json({ok:!1,hasToken:!1,error:"VERCEL_TOKEN not found in .env.local"});const $=await it("/v2/user",S);return $.ok?Response.json({ok:!0,hasToken:!0,user:{username:((s=$.data.user)==null?void 0:s.username)||((a=$.data.user)==null?void 0:a.name),email:(o=$.data.user)==null?void 0:o.email}}):Response.json({ok:!1,hasToken:!0,error:`Token invalid (${$.status}): ${((r=(t=$.data)==null?void 0:t.error)==null?void 0:r.message)||"unknown error"}`})}if(O==="save-token"){const S=P.token;if(!S||typeof S!="string")return Response.json({ok:!1,error:"Token is required"});Uo(Y,"VERCEL_TOKEN",S);const $=await it("/v2/user",S);return $.ok?Response.json({ok:!0,saved:!0,user:{username:((i=$.data.user)==null?void 0:i.username)||((l=$.data.user)==null?void 0:l.name),email:(d=$.data.user)==null?void 0:d.email}}):Response.json({ok:!1,saved:!0,error:`Token saved but verification failed (${$.status})`})}if(O==="list-projects"){const S=_t(Y,"VERCEL_TOKEN");if(!S)return Response.json({ok:!1,error:"VERCEL_TOKEN not found"});const $=await it("/v9/projects?limit=20",S);if(!$.ok)return Response.json({ok:!1,error:"Failed to list projects"});const I=($.data.projects||[]).map(J=>({id:J.id,name:J.name,framework:J.framework}));let K=null;const q=kc(Y);if(q){const J=I.find(z=>z.name.toLowerCase()===q.repo.toLowerCase());J&&(K=J.id)}return Response.json({ok:!0,projects:I,suggestedProjectId:K,gitHubRepo:q?`${q.owner}/${q.repo}`:null})}if(O==="create-project"){const S=_t(Y,"VERCEL_TOKEN");if(!S)return Response.json({ok:!1,error:"VERCEL_TOKEN not found"});const $=kc(Y);if(!$)return Response.json({ok:!1,error:"Could not detect a GitHub remote. Push your code to GitHub first, then try again."});const I=ee.join(Y,".codeyam","config.json"),K=$.repo;let q=null;try{((p=(u=JSON.parse(ce.readFileSync(I,"utf8")).webapps)==null?void 0:u[0])==null?void 0:p.framework)==="Next"&&(q="nextjs")}catch{}const J={name:P.projectName||K,framework:q,gitRepository:{type:"github",repo:`${$.owner}/${$.repo}`}},z=await it("/v10/projects",S,{method:"POST",body:J});if(!z.ok){const H=((m=(h=z.data)==null?void 0:h.error)==null?void 0:m.message)||((y=(f=z.data)==null?void 0:f.error)==null?void 0:y.code)||"Failed to create project";return Response.json({ok:!1,error:H})}const B=z.data;try{const H=JSON.parse(ce.readFileSync(I,"utf8"));H.hosting={...H.hosting,provider:"vercel",vercelProjectId:B.id,vercelProjectName:B.name},Kr(H,"infrastructure",gc),ce.writeFileSync(I,JSON.stringify(H,null,2))}catch{}return Response.json({ok:!0,project:{id:B.id,name:B.name,framework:B.framework}})}if(O==="link-project"){const{projectId:S,projectName:$}=P;if(!S)return Response.json({ok:!1,error:"projectId is required"});const I=ee.join(Y,".codeyam","config.json"),K=JSON.parse(ce.readFileSync(I,"utf8"));return K.hosting={...K.hosting,provider:"vercel",vercelProjectId:S,vercelProjectName:$||null},Kr(K,"infrastructure",gc),ce.writeFileSync(I,JSON.stringify(K,null,2)),Response.json({ok:!0})}if(O==="check-env-vars"){const S=_t(Y,"VERCEL_TOKEN");if(!S)return Response.json({ok:!1,error:"VERCEL_TOKEN not found"});const $=ee.join(Y,".codeyam","config.json"),I=JSON.parse(ce.readFileSync($,"utf8")),K=(g=I.hosting)==null?void 0:g.vercelProjectId;if(!K)return Response.json({ok:!1,error:"No Vercel project linked"});const q=await it(`/v9/projects/${K}/env`,S);if(!q.ok)return Response.json({ok:!1,error:"Failed to fetch Vercel env vars"});const J=new Set((q.data.envs||[]).map(ae=>ae.key)),z=I.techStack||{},B=[];for(const ae of["databases","services","infrastructure"]){const X=z[ae];if(Array.isArray(X)){for(const oe of X)if(oe.envKeys&&Array.isArray(oe.envKeys))for(const me of oe.envKeys)B.push({key:me,service:oe.name})}}const H=B.map(({key:ae,service:X})=>({key:ae,service:X,configuredOnVercel:J.has(ae)})),re=B.length===0||H.every(ae=>ae.configuredOnVercel);return Response.json({ok:!0,allConfigured:re,envVars:H,vercelEnvCount:J.size})}if(O==="full-status"){const S=_t(Y,"VERCEL_TOKEN"),$=ee.join(Y,".codeyam","config.json");let I={};try{I=JSON.parse(ce.readFileSync($,"utf8"))}catch{}const K={hasToken:!!S,tokenVerified:!1,user:null,projectLinked:!!((x=I.hosting)!=null&&x.vercelProjectId),projectName:((b=I.hosting)==null?void 0:b.vercelProjectName)||null,dashboardUrl:null,productionUrl:null,envVarsChecked:!1,envVars:[]};if(S){const q=await it("/v2/user",S);if(q.ok&&(K.tokenVerified=!0,K.user={username:((v=q.data.user)==null?void 0:v.username)||((N=q.data.user)==null?void 0:N.name),email:(w=q.data.user)==null?void 0:w.email}),K.projectLinked){const J=await it(`/v9/projects/${I.hosting.vercelProjectId}`,S);if(J.ok){const H=J.data;let re=null;if(H.accountId){const X=await it(`/v2/teams/${H.accountId}`,S);X.ok&&(re=X.data.slug)}K.dashboardUrl=re?`https://vercel.com/${re}/${H.name}`:`https://vercel.com/~/project/${H.name}`;const ae=((k=(C=H.targets)==null?void 0:C.production)==null?void 0:k.alias)||H.alias||[];if(ae.length>0){const X=ae.find(oe=>!oe.endsWith(".vercel.app"));K.productionUrl=`https://${X||ae[0]}`}else H.name&&(K.productionUrl=`https://${H.name}.vercel.app`)}const z=await it(`/v6/deployments?projectId=${I.hosting.vercelProjectId}&limit=1&target=production`,S);if(z.ok){const H=z.data.deployments||[];if(H.length>0){const re=H[0],ae=((j=re.meta)==null?void 0:j.githubCommitSha)||((A=re.meta)==null?void 0:A.gitlabCommitSha)||((_=re.gitSource)==null?void 0:_.sha)||null;let X=0;if(ae)try{const oe=Me(`git rev-list --count ${ae}..HEAD`,{cwd:Y,encoding:"utf8"}).trim();X=parseInt(oe,10)||0}catch{}K.lastDeployment={state:re.state||re.readyState,url:re.url?`https://${re.url}`:null,createdAt:re.createdAt,commitsSince:X}}else K.lastDeployment=null}const B=await it(`/v9/projects/${I.hosting.vercelProjectId}/env`,S);if(B.ok){const H=new Set((B.data.envs||[]).map(X=>X.key)),re=I.techStack||{},ae=[];for(const X of["databases","services","infrastructure"]){const oe=re[X];if(Array.isArray(oe)){for(const me of oe)if(me.envKeys&&Array.isArray(me.envKeys))for(const ve of me.envKeys)ae.push({key:ve,service:me.name})}}K.envVarsChecked=!0,K.envVars=ae.map(({key:X,service:oe})=>({key:X,service:oe,configuredOnVercel:H.has(X)}))}}}return Response.json({ok:!0,...K})}if(O==="deploy"){const S=_t(Y,"VERCEL_TOKEN");if(!S)return Response.json({ok:!1,error:"VERCEL_TOKEN not found"});const $=ee.join(Y,".codeyam","config.json"),I=JSON.parse(ce.readFileSync($,"utf8")),K=(M=I.hosting)==null?void 0:M.vercelProjectName;if(!K)return Response.json({ok:!1,error:"No Vercel project linked"});const q=(T=I.hosting)==null?void 0:T.vercelProjectId,J=await it(`/v9/projects/${q}`,S);if(!J.ok)return Response.json({ok:!1,error:"Failed to fetch project details"});const z=J.data,B=(D=z.link)==null?void 0:D.repoId;if(!B)return Response.json({ok:!1,error:"Project is not linked to a GitHub repository on Vercel"});let H="main";try{H=Me("git rev-parse --abbrev-ref HEAD",{cwd:Y,encoding:"utf8"}).trim()}catch{}let re;try{re=Me("git rev-parse HEAD",{cwd:Y,encoding:"utf8"}).trim()}catch{}const ae=await it("/v13/deployments",S,{method:"POST",body:{name:K,target:"production",gitSource:{type:z.link.type||"github",repoId:B,ref:H,...re?{sha:re}:{}}}});if(!ae.ok){const X=((L=(R=ae.data)==null?void 0:R.error)==null?void 0:L.message)||((W=(U=ae.data)==null?void 0:U.error)==null?void 0:W.code)||"Failed to trigger deployment";return Response.json({ok:!1,error:X})}return Response.json({ok:!0,deployment:{id:ae.data.id,url:ae.data.url?`https://${ae.data.url}`:null,state:ae.data.readyState||ae.data.state}})}if(O==="check-deployment"){const S=_t(Y,"VERCEL_TOKEN");if(!S)return Response.json({ok:!1,error:"VERCEL_TOKEN not found"});const $=P.deploymentId;if(!$)return Response.json({ok:!1,error:"deploymentId is required"});const I=await it(`/v13/deployments/${$}`,S);if(!I.ok)return Response.json({ok:!1,error:"Failed to check deployment status"});const K=I.data,q=K.readyState||K.state||"UNKNOWN";let J=null;if(q==="ERROR"||q==="CANCELED"){const H=await it(`/v2/deployments/${$}/events?limit=20&direction=backward`,S);if(H.ok){const ae=(H.data||[]).filter(X=>X.type==="error"||X.type==="stderr");ae.length>0&&(J=ae.map(X=>{var oe;return((oe=X.payload)==null?void 0:oe.text)||X.text||""}).filter(Boolean).slice(0,5).join(`
442
+ `))}J||(J=K.errorMessage||((V=K.error)==null?void 0:V.message)||"Build failed")}const z=ee.join(Y,".codeyam","config.json");let B=null;try{const H=JSON.parse(ce.readFileSync(z,"utf8"));if((F=H.hosting)!=null&&F.vercelProjectId){const re=await it(`/v9/projects/${H.hosting.vercelProjectId}`,S);if(re.ok&&re.data.accountId){const ae=await it(`/v2/teams/${re.data.accountId}`,S);ae.ok&&(B=`https://vercel.com/${ae.data.slug}/${H.hosting.vercelProjectName}/${$.replace("dpl_","")}`)}}}catch{}return Response.json({ok:!0,state:q,url:K.url?`https://${K.url}`:null,errorMessage:J,logsUrl:B})}return Response.json({ok:!1,error:`Unknown action: ${O}`})}catch(Y){const P=Y instanceof Error?Y.message:String(Y);return Response.json({ok:!1,error:P},{status:500})}}const Mw=Object.freeze(Object.defineProperty({__proto__:null,action:Tw},Symbol.toStringTag,{value:"Module"}));function $w(e,t,r=new Date){const s={"1d":1,"3d":3,"7d":7,"30d":30}[t],a=new Date(r);a.setDate(a.getDate()-s);const o=a.toISOString().split("T")[0],i=e.filter(h=>h.date>=o),l=new Set(i.map(h=>h.commitSha).filter(Boolean)),d=new Map;for(const h of i)if(h.scenarioScreenshots)for(const m of h.scenarioScreenshots){d.has(m.name)||d.set(m.name,[]);const f=d.get(m.name);f.some(y=>y.path===m.path)||f.push({path:m.path,time:h.time})}for(const h of d.values())h.sort((m,f)=>m.time.localeCompare(f.time));const u=[],p=new Map;for(const[h,m]of d){const f=h.indexOf(" - ");if(f!==-1){const y=h.slice(0,f);p.has(y)||p.set(y,[]),p.get(y).push({name:h,screenshots:m})}else u.push({name:h,screenshots:m})}return{commitCount:l.size,entryCount:i.length,appScenarios:u,componentGroups:p,totalScenarios:d.size}}function Fw(e){const t=new Map;for(const r of[...e].reverse()){const s=t.get(r.date)||[];s.push(r),t.set(r.date,s)}return t}function Dw(e){const t=new Map;for(const r of e){let s;if("componentName"in r&&r.componentName)s=r.componentName;else if("componentName"in r&&r.componentName===null)s="App";else{const o=r.name.indexOf(" - ");s=o!==-1?r.name.slice(0,o):"App"}const a=t.get(s)||[];a.push(r),t.set(s,a)}return[...t.entries()].sort(([r],[s])=>r==="App"?-1:s==="App"?1:r.localeCompare(s))}function Rw(e,t){const r=e.replace(/[^a-zA-Z0-9_\-]/g,"_");return`${t.toISOString().replace(/:/g,"-").replace(/\.\d+Z$/,"")}_${r}.png`}function Iw(e){const{title:t,timeStr:r,type:s,description:a,allScenarioNames:o,screenshot:i,scenarioScreenshots:l,commitSha:d,commitMessage:u,featureName:p,userPrompt:h}=e,m=["","---","",`### ${t}`,`**Time:** ${r}`,`**Type:** ${s}`];if(p&&m.push(`**Feature:** ${p}`),h&&m.push(`**Prompt:** ${h}`),o.length>0&&m.push(`**Scenarios:** ${o.join(", ")}`),m.push(""),m.push(a),i&&(m.push(""),m.push(`![${t}](${i})`)),l.length>0){m.push(""),m.push("**Scenario Screenshots:**");for(const f of l)m.push(""),m.push(`![${f.name}](${f.path})`)}return d&&u&&(m.push(""),m.push(`**Commit:** \`${d}\` — ${u}`)),m.push(""),m.join(`
443
+ `)}function Ow(e,t){return e.findIndex(r=>r.time===t)}function Lw(e){return!!e.commitSha}function Bw(e,t){return t.commitSha!==void 0&&(e.commitSha=t.commitSha),t.commitMessage!==void 0&&(e.commitMessage=t.commitMessage),t.description!==void 0&&(e.description=t.description),t.scenarios!==void 0&&(e.scenarios=t.scenarios),t.scenarioScreenshots!==void 0&&(e.scenarioScreenshots=t.scenarioScreenshots),e}function zw(e,t,r,s){const a=`
444
+ **Commit:** \`${r}\` — ${s||"no message"}
445
+ `,o=`### ${t}`,i=e.lastIndexOf(o);if(i===-1)return null;const l=e.indexOf(`
446
+ ---
447
+ `,i+1),d=l!==-1?l:e.length;return e.slice(0,d)+a+e.slice(d)}async function Yw(e){console.log(`[editorScenarioLookup] Looking up screenshots for ${e.length} scenarios: ${e.join(", ")}`);try{const t=await ze();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up scenarios"),[];const{project:r}=await Ie(t),a=await $e().selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).where("name","in",e).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] DB query returned ${a.length} matching scenarios:`,a.map(d=>({name:d.name,screenshot_path:d.screenshot_path,id:d.id})));const o=a.filter(d=>!d.screenshot_path);o.length>0&&console.warn(`[editorScenarioLookup] ${o.length} scenarios have no screenshot_path:`,o.map(d=>d.name));const i=a.filter(d=>d.screenshot_path),l=Mt(i,d=>d.name).map(d=>({name:d.name,screenshotPath:d.screenshot_path,scenarioId:d.id,componentName:d.component_name||null,pageFilePath:d.page_file_path||null,url:d.url||null}));return console.log(`[editorScenarioLookup] Found ${l.length} scenarios with screenshots`),l}catch(t){return console.error("[editorScenarioLookup] Failed to look up scenario screenshots:",t),[]}}async function Uw(e){console.log(`[editorScenarioLookup] Looking up screenshots by entity names: ${e.join(", ")}`);try{const t=await ze();if(!t)return[];const{project:r}=await Ie(t),a=await $e().selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).orderBy("created_at","asc").execute(),o=new Set(e),l=a.filter(u=>{const p=rn({componentName:u.component_name,pageFilePath:u.page_file_path,url:u.url});return o.has(p)}).filter(u=>u.screenshot_path),d=Mt(l,u=>u.name).map(u=>({name:u.name,screenshotPath:u.screenshot_path,scenarioId:u.id,componentName:u.component_name||null,pageFilePath:u.page_file_path||null,url:u.url||null}));return console.log(`[editorScenarioLookup] Found ${d.length} scenarios for ${e.length} entities`),d}catch(t){return console.error("[editorScenarioLookup] Failed to look up entity screenshots:",t),[]}}async function fp(e){console.log("[editorScenarioLookup] Looking up session scenario screenshots",e?`(after ${e})`:"(all session)");try{const t=await ze();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up session scenarios"),[];const{project:r}=await Ie(t),s=$e(),a=Ce()||process.cwd();let o=null;const i=G.join(a,".codeyam","editor-step.json");try{const m=Q.readFileSync(i,"utf8");o=JSON.parse(m).featureStartedAt||null}catch{return console.warn("[editorScenarioLookup] No editor-step.json found — cannot determine session start"),[]}if(!o)return console.warn("[editorScenarioLookup] No featureStartedAt found in editor-step.json"),[];const l=e&&e>o?e:o,d=rs(l),u=await s.selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).where("created_at",">=",d).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] Query returned ${u.length} scenarios since ${l}`);const p=u.filter(m=>m.screenshot_path),h=Mt(p,m=>m.name).map(m=>({name:m.name,screenshotPath:m.screenshot_path,scenarioId:m.id,componentName:m.component_name||null,pageFilePath:m.page_file_path||null,url:m.url||null}));return console.log(`[editorScenarioLookup] Found ${h.length} session scenarios with screenshots`),h}catch(t){return console.error("[editorScenarioLookup] Failed to look up session scenario screenshots:",t),[]}}async function Vo(e,t,r){const s=G.join(t,".codeyam","journal","screenshots");await Ae.mkdir(s,{recursive:!0});const a=[];for(const o of e){const i=G.join(t,".codeyam","editor-scenarios",o.screenshotPath),l=Rw(o.name,r),d=G.join(s,l);console.log(`[editorScenarioLookup] Copying scenario screenshot: "${o.name}" from ${i} → ${d}`);try{await Ae.access(i),await Ae.copyFile(i,d),a.push({name:o.name,path:`screenshots/${l}`,componentName:o.componentName,url:o.url}),console.log(`[editorScenarioLookup] Successfully copied screenshot for "${o.name}"`)}catch(u){console.warn(`[editorScenarioLookup] Scenario screenshot not found: ${i}`,u instanceof Error?u.message:u)}}return console.log(`[editorScenarioLookup] Scenario screenshot summary: ${a.length} scenarios have screenshots embedded`),a}async function Ww({request:e}){if(e.method!=="PATCH")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{time:r,commitSha:s,commitMessage:a,description:o,includeSessionScenarios:i}=t;if(!r)return new Response(JSON.stringify({error:"time is required to identify the entry"}),{status:400,headers:{"Content-Type":"application/json"}});const l=process.env.CODEYAM_ROOT_PATH||process.cwd(),d=G.join(l,".codeyam","journal"),u=G.join(d,"index.json");console.log(`[editor-journal-update] Updating entry with time="${r}"`);let p={entries:[]};try{const g=await Ae.readFile(u,"utf8");p=JSON.parse(g)}catch{return new Response(JSON.stringify({error:"No journal index found"}),{status:404,headers:{"Content-Type":"application/json"}})}const h=Ow(p.entries,r);if(h===-1)return new Response(JSON.stringify({error:`No journal entry found with time "${r}"`}),{status:404,headers:{"Content-Type":"application/json"}});const m=p.entries[h];if(Lw(m))return console.log(`[editor-journal-update] Rejected: entry "${m.title}" already committed (${m.commitSha}). Create a new entry instead.`),new Response(JSON.stringify({error:`Journal entry already committed (${m.commitSha}). Create a new entry via POST /api/editor-journal-entry instead of updating.`}),{status:409,headers:{"Content-Type":"application/json"}});let f,y;if(i){const g=await fp();g.length>0&&(f=g.map(x=>x.name),y=await Vo(g,l,new Date))}if(Bw(m,{commitSha:s,commitMessage:a,description:o,scenarios:f,scenarioScreenshots:y}),p.entries[h]=m,await Ae.writeFile(u,JSON.stringify(p,null,2),"utf8"),console.log("[editor-journal-update] Updated index.json"),s)try{const g=m.date,x=G.join(d,`${g}.md`);let b="";try{b=await Ae.readFile(x,"utf8")}catch{}if(b){const v=zw(b,m.title,s,a||null);v&&(await Ae.writeFile(x,v,"utf8"),console.log(`[editor-journal-update] Appended commit line to ${x}`))}}catch(g){console.warn("[editor-journal-update] Failed to update markdown:",g)}return Nt.notifyChange("journal"),console.log(`[editor-journal-update] Done: updated entry "${m.title}"`),new Response(JSON.stringify({success:!0,entry:m}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-update] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Jw=Object.freeze(Object.defineProperty({__proto__:null,action:Ww},Symbol.toStringTag,{value:"Module"}));async function Hw({request:e}){var t;try{const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=await ep(r);let a=0;const o={};for(const[d,u]of Object.entries(s))u.errors.length>0&&(o[d]=u,a+=u.errors.length);let i=ic();if(!i)for(let d=0;d<20&&(await new Promise(u=>setTimeout(u,500)),i=ic(),!i);d++);const l=((t=i==null?void 0:i.errors)==null?void 0:t.length)??0;return new Response(JSON.stringify({hasErrors:a>0||l>0,totalErrors:a+l,scenarios:o,livePreview:i?{loaded:i.loaded,hasContent:i.hasContent,errors:i.errors,url:i.url,lastUpdated:i.lastUpdated}:null}),{headers:{"Content-Type":"application/json"}})}catch(r){const s=r instanceof Error?r.message:String(r);return console.error("[editor-client-errors] Error:",r),new Response(JSON.stringify({error:s}),{status:500,headers:{"Content-Type":"application/json"}})}}const Vw=Object.freeze(Object.defineProperty({__proto__:null,loader:Hw},Symbol.toStringTag,{value:"Module"}));async function Kw({request:e}){try{const r=(await Yn()||[]).filter(i=>i.analyses&&i.analyses.length>0).map(i=>{var y;const l=i.analyses[0],d=l.scenarios||[],u=!((y=l.status)!=null&&y.finishedAt),p=i.entityType||"visual",m=p==="library"||p==="functionCall"?d.some(g=>{var x;return!!((x=g.metadata)!=null&&x.executionResult)}):d.some(g=>{var x,b,v,N;return((b=(x=g.metadata)==null?void 0:x.screenshotPaths)==null?void 0:b[0])&&!((v=g.metadata)!=null&&v.noScreenshotSaved)&&!((N=g.metadata)!=null&&N.sameAsDefault)}),f=d.length;return{name:i.name,entityType:p,filePath:i.filePath||"",hasScreenshot:m,isAnalyzing:u,scenarioCount:f}}),s=r.filter(i=>i.hasScreenshot),a=r.filter(i=>!i.hasScreenshot&&!i.isAnalyzing).map(i=>i.name),o=r.filter(i=>i.isAnalyzing).length;return new Response(JSON.stringify({entities:r,summary:{total:r.length,withScreenshots:s.length,missingScreenshots:a,analyzing:o}}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-entity-status] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const Gw=Object.freeze(Object.defineProperty({__proto__:null,loader:Kw},Symbol.toStringTag,{value:"Module"})),qw="https://api.github.com";function gp(e,t){for(const r of[".env.local",".env",".env.development.local",".env.development"])try{const s=ee.join(e,r);if(!ce.existsSync(s))continue;const a=ce.readFileSync(s,"utf-8");for(const o of a.split(`
448
+ `)){const i=o.trim();if(!i||i.startsWith("#"))continue;const l=i.indexOf("=");if(l===-1)continue;const d=i.slice(0,l).trim();let u=i.slice(l+1).trim();if((u.startsWith('"')&&u.endsWith('"')||u.startsWith("'")&&u.endsWith("'"))&&(u=u.slice(1,-1)),d===t&&u)return u}}catch{}return null}function Qw(e,t,r){const s=ee.join(e,".env.local");let a=[];try{a=ce.readFileSync(s,"utf-8").split(`
449
+ `)}catch{}const o=a.findIndex(l=>{const d=l.trim();if(d.startsWith("#"))return!1;const u=d.indexOf("=");return u===-1?!1:d.slice(0,u).trim()===t}),i=`${t}=${r}`;o>=0?a[o]=i:(a.length>0&&a[a.length-1].trim()!==""&&a.push(""),a.push(i)),ce.writeFileSync(s,a.join(`
450
+ `))}function Ze(e,t){try{return{ok:!0,stdout:Me(e,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim(),stderr:""}}catch(r){return{ok:!1,stdout:(r.stdout||"").trim(),stderr:(r.stderr||"").trim()}}}async function Ps(e,t,r){try{const s=await fetch(`${qw}${e}`,{method:(r==null?void 0:r.method)||"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github+json",...r!=null&&r.body?{"Content-Type":"application/json"}:{}},...r!=null&&r.body?{body:JSON.stringify(r.body)}:{},signal:AbortSignal.timeout(15e3)}),a=await s.json();return{ok:s.ok,status:s.status,data:a}}catch(s){return{ok:!1,status:0,data:{error:s instanceof Error?s.message:String(s)}}}}function Zw(e){const t=Ze("git remote get-url origin",e);if(!t.ok)return null;const r=t.stdout,s=r.match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(s)return{owner:s[1],repo:s[2]};const a=r.match(/github\.com\/([^/]+)\/([^/.]+)/);return a?{owner:a[1],repo:a[2]}:null}function wo(e){const t=Ze("gh auth token",e);return t.ok&&t.stdout?t.stdout:gp(e,"GITHUB_TOKEN")}async function Xw({request:e}){var t,r,s,a,o,i;if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const l=Ce()||process.cwd(),d=await e.json(),u=d.action;if(u==="full-status"){const p=ce.existsSync(ee.join(l,".git")),h=ce.existsSync(ee.join(l,".gitignore"));let m=!1,f=null,y=!1;if(p){const M=Ze("git remote get-url origin",l);M.ok&&(m=!0,f=M.stdout,y=f.includes("github.com"))}const x=Ze("gh --version",l).ok;let b=!1;x&&(b=Ze("gh auth status",l).ok);const N=!!gp(l,"GITHUB_TOKEN");let w=!1,C=null;const k=wo(l);if(k){const M=await Ps("/user",k);M.ok&&(w=!0,C={username:M.data.login,email:M.data.email||""})}const j=Zw(l);let A=!1,_=!1;if(p&&(A=Ze("git rev-parse HEAD",l).ok,A&&m)){const T=Ze("git branch --show-current",l),D=T.ok&&T.stdout?T.stdout:"main";_=Ze(`git rev-parse origin/${D}`,l).ok}return Response.json({ok:!0,gitInitialized:p,hasGitignore:h,hasRemote:m,remoteUrl:f,isGitHub:y,ghCliInstalled:x,ghCliAuthenticated:b,hasToken:N,tokenVerified:w||b,user:C,githubRepo:j,hasCommits:A,pushed:_})}if(u==="init-git"){if(!ce.existsSync(ee.join(l,".git"))){const p=Ze("git init",l);if(!p.ok)return Response.json({ok:!1,error:`Failed to initialize git: ${p.stderr}`})}if(!ce.existsSync(ee.join(l,".gitignore"))){const p=["node_modules/",".env",".env.local",".env.*.local",".DS_Store","dist/",".next/","*.log",""].join(`
451
+ `);ce.writeFileSync(ee.join(l,".gitignore"),p)}return Response.json({ok:!0})}if(u==="save-token"){const p=d.token;if(!p||typeof p!="string")return Response.json({ok:!1,error:"Token is required"});Qw(l,"GITHUB_TOKEN",p);const h=await Ps("/user",p);return h.ok?Response.json({ok:!0,saved:!0,user:{username:h.data.login,email:h.data.email||""}}):Response.json({ok:!1,saved:!0,error:`Token saved but verification failed (${h.status})`})}if(u==="list-repos"){const p=wo(l);if(!p)return Response.json({ok:!1,error:"No GitHub authentication found"});const h=await Ps("/user/repos?sort=updated&per_page=20&affiliation=owner",p);if(!h.ok)return Response.json({ok:!1,error:"Failed to list repositories"});const m=(h.data||[]).map(g=>({name:g.name,fullName:g.full_name,url:g.html_url,private:g.private,cloneUrl:g.clone_url,sshUrl:g.ssh_url})),f=ee.basename(l).toLowerCase(),y=m.find(g=>g.name.toLowerCase()===f)||null;return Response.json({ok:!0,repos:m,suggestedRepoName:(y==null?void 0:y.name)||null})}if(u==="create-repo"){const p=wo(l);if(!p)return Response.json({ok:!1,error:"No GitHub authentication found"});const h=d.repoName||ee.basename(l),m=d.private!==!1,f=await Ps("/user/repos",p,{method:"POST",body:{name:h,private:m,auto_init:!1}});if(!f.ok){const N=((t=f.data)==null?void 0:t.message)||((a=(s=(r=f.data)==null?void 0:r.errors)==null?void 0:s[0])==null?void 0:a.message)||"Failed to create repository";return Response.json({ok:!1,error:N})}const y=f.data;Ze("git remote get-url origin",l).ok?Ze(`git remote set-url origin ${y.clone_url}`,l):Ze(`git remote add origin ${y.clone_url}`,l);try{const N=ee.join(l,".codeyam","config.json"),w=JSON.parse(ce.readFileSync(N,"utf8"));w.github={owner:(o=y.owner)==null?void 0:o.login,repo:y.name,repoUrl:y.html_url},Kr(w,"infrastructure",fc),ce.writeFileSync(N,JSON.stringify(w,null,2))}catch{}const x=Ze("git branch --show-current",l),b=x.ok&&x.stdout?x.stdout:"main",v=Ze(`git push -u origin ${b}`,l);return Response.json({ok:!0,repo:{owner:(i=y.owner)==null?void 0:i.login,name:y.name,url:y.html_url,private:y.private},pushed:v.ok,pushError:v.ok?null:v.stderr})}if(u==="link-repo"){const{repoUrl:p,owner:h,repo:m}=d;if(!p)return Response.json({ok:!1,error:"repoUrl is required"});if(Ze("git remote get-url origin",l).ok){const y=Ze(`git remote set-url origin ${p}`,l);if(!y.ok)return Response.json({ok:!1,error:`Failed to set remote: ${y.stderr}`})}else{const y=Ze(`git remote add origin ${p}`,l);if(!y.ok)return Response.json({ok:!1,error:`Failed to add remote: ${y.stderr}`})}try{const y=ee.join(l,".codeyam","config.json"),g=JSON.parse(ce.readFileSync(y,"utf8"));g.github={owner:h||null,repo:m||null,repoUrl:p},Kr(g,"infrastructure",fc),ce.writeFileSync(y,JSON.stringify(g,null,2))}catch{}return Response.json({ok:!0})}if(u==="push"){const p=Ze("git branch --show-current",l),h=p.ok&&p.stdout?p.stdout:"main",m=Ze(`git push -u origin ${h}`,l);return m.ok?Response.json({ok:!0,branch:h}):Response.json({ok:!1,error:m.stderr||"Push failed"})}return Response.json({ok:!1,error:`Unknown action: ${u}`})}catch(l){const d=l instanceof Error?l.message:String(l);return Response.json({ok:!1,error:d},{status:500})}}const eN=Object.freeze(Object.defineProperty({__proto__:null,action:Xw},Symbol.toStringTag,{value:"Module"}));async function tN({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{title:r,type:s,description:a,scenarios:o,includeSessionScenarios:i,screenshot:l,commitSha:d,commitMessage:u}=t;if(console.log(`[editor-journal-entry] Creating journal entry: title="${r}", type="${s}", scenarios=${JSON.stringify(o||[])}, includeSessionScenarios=${!!i}, screenshot=${l||"none"}`),!r||!s||!a)return console.warn("[editor-journal-entry] Missing required fields:",{title:!!r,type:!!s,description:!!a}),new Response(JSON.stringify({error:"title, type, and description are required"}),{status:400,headers:{"Content-Type":"application/json"}});const p=process.env.CODEYAM_ROOT_PATH||process.cwd(),h=G.join(p,".codeyam","journal");await Ae.mkdir(h,{recursive:!0});const m=new Date,f=m.toISOString().split("T")[0],y=m.toISOString();let g=o||[];const x=G.join(h,"index.json");let b={entries:[]};try{const U=await Ae.readFile(x,"utf8");b=JSON.parse(U)}catch{}let v;i&&b.entries.length>0&&(v=b.entries[b.entries.length-1].time);const N=i?await fp(v):o&&o.length>0?await Yw(o):[];i&&N.length>0&&(g=N.map(U=>U.name));const w=await Vo(N,p,m);let C;try{const U=Ce()||process.cwd(),W=await ze();if(W){const{project:V}=await Ie(W),Y=await $e().selectFrom("editor_scenarios").select(["name","component_name","component_path","page_file_path","url","display_name"]).where("project_id","=",V.id).orderBy("created_at","asc").execute(),O=Mt(Y,$=>`${$.name}::${$.url||"/"}`).map($=>({componentName:$.component_name||null,componentPath:$.component_path||null,pageFilePath:$.page_file_path??null,url:$.url??null,displayName:$.display_name??null})),S=await br({projectRoot:U,scenarioInputs:O});Object.keys(S.entityChangeStatus).length>0&&(C=S.entityChangeStatus)}}catch{}if(C&&Object.keys(C).length>0){const U=new Set(N.map(V=>V.name)),W=Object.entries(C).filter(([,V])=>V.status==="impacted").map(([V])=>V);if(W.length>0){const V=[],F=new Set(N.map(Y=>rn(Y)));for(const Y of W)F.has(Y)||V.push(Y);if(V.length>0)try{const Y=await Uw(V);if(Y.length>0){const P=await Vo(Y.filter(O=>!U.has(O.name)),p,m);w.push(...P),g.push(...P.map(O=>O.name))}}catch{}}}let k=w,j=g;if(!i&&C&&Object.keys(C).length>0){k=Ty(w,C);const U=new Set(k.map(W=>W.name));j=g.filter(W=>U.has(W))}const A=Ia(p),_=zi(p);let M;try{const U=xr();U.length>0&&(M=U.filter(W=>W.status!=="deleted").map(W=>({path:W.path,status:W.status})))}catch{}const T=G.join(h,`${f}.md`);let D="";try{D=await Ae.readFile(T,"utf8")}catch{D=`# Development Journal — ${f}
452
+ `}const R=Iw({title:r,timeStr:y,type:s,description:a,allScenarioNames:j,screenshot:l||null,scenarioScreenshots:k,commitSha:d||null,commitMessage:u||null,featureName:A,userPrompt:_});await Ae.writeFile(T,D+R,"utf8"),console.log(`[editor-journal-entry] Written daily markdown: ${T}`);const L={date:f,time:y,title:r,type:s,description:a,scenarios:j,screenshot:l||null,scenarioScreenshots:k,commitSha:d||null,commitMessage:u||null,entityChangeStatus:C,featureName:A,userPrompt:_,modifiedFiles:M};b.entries.push(L),await Ae.writeFile(x,JSON.stringify(b,null,2),"utf8"),console.log(`[editor-journal-entry] Updated index.json (now ${b.entries.length} entries)`);try{await Ae.unlink(G.join(p,"editor-user-prompt.txt"))}catch{}return Nt.notifyChange("journal"),console.log(`[editor-journal-entry] Done: title="${r}", scenarioScreenshotsEmbedded=${k.length}`),new Response(JSON.stringify({success:!0,entry:L,scenarioScreenshotsFound:k.length}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal-entry] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const nN=Object.freeze(Object.defineProperty({__proto__:null,action:tN},Symbol.toStringTag,{value:"Module"}));function rN({request:e}){const t={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const r=Ce()||process.cwd();let o=new URL(e.url).searchParams.get("scenarioId");if(!o){const d=G.join(r,".codeyam","active-scenario.json");if(!Q.existsSync(d))return new Response(JSON.stringify({}),{headers:t});o=JSON.parse(Q.readFileSync(d,"utf-8")).scenarioId||null}if(!o)return new Response(JSON.stringify({}),{headers:t});const i=G.join(r,".codeyam","editor-scenarios",`${o}.json`);if(!Q.existsSync(i))return new Response(JSON.stringify({}),{headers:t});const l=Q.readFileSync(i,"utf-8");return new Response(l,{headers:t})}catch{return new Response(JSON.stringify({}),{headers:t})}}const sN=Object.freeze(Object.defineProperty({__proto__:null,loader:rN},Symbol.toStringTag,{value:"Module"}));async function aN({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=Array.isArray(t.paths)?t.paths:[],s=Array.isArray(t.apiRoutes)?t.apiRoutes:[];if(r.length===0&&s.length===0)return new Response(JSON.stringify({error:'At least one entry in "paths" or "apiRoutes" is required.'}),{status:400,headers:{"Content-Type":"application/json"}});const a=globalThis.__codeyam_editor_dev_server__;if(!a||!a.url||a.status!=="running")return new Response(JSON.stringify({error:`Dev server is not running. Start it with: codeyam editor dev-server '{"action":"start"}'`}),{status:503,headers:{"Content-Type":"application/json"}});const o=a.url,i=1e4,l={},d={};let u=!0;for(const f of r)try{const y=await fetch(`${o}${f}`,{signal:AbortSignal.timeout(i)}),g=y.ok;g||(u=!1),l[f]={status:y.status,ok:g}}catch(y){u=!1,l[f]={status:0,ok:!1,error:y.message}}for(const f of s)try{const y=await fetch(`${o}${f}`,{signal:AbortSignal.timeout(i)}),g=y.ok;g||(u=!1);let x=!1,b;try{const v=await y.text();JSON.parse(v),x=!0,b=v.length>200?v.slice(0,200)+"…":v}catch{}d[f]={status:y.status,ok:g,isJSON:x,preview:b}}catch(y){u=!1,d[f]={status:0,ok:!1,isJSON:!1,error:y.message}}const p=r.length+s.length,h=Object.values(l).filter(f=>f.ok).length+Object.values(d).filter(f=>f.ok).length,m=u?`All ${p} routes OK`:`${h}/${p} routes passed`;return new Response(JSON.stringify({ok:u,routes:l,apiRoutes:d,summary:m}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-verify-routes] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const oN=Object.freeze(Object.defineProperty({__proto__:null,action:aN},Symbol.toStringTag,{value:"Module"}));async function iN(e,t){const r=Ce();if(!r)return{entityCalls:[],analysisCalls:[]};const s=G.join(r,".codeyam","llm-calls");try{await Ae.access(s)}catch{return{entityCalls:[],analysisCalls:[]}}const a=[],o=[];try{const l=(await Ae.readdir(s)).filter(b=>b.endsWith(".json")),d=`${e}_`,u=t?`${t}_`:null,p=[],h=[];for(const b of l)b.startsWith(d)||u&&b.startsWith(u)?p.push(b):h.push(b);const m=p.map(async b=>{try{const v=G.join(s,b),N=await Ae.readFile(v,"utf-8");return JSON.parse(N)}catch{return null}}),f=h.map(async b=>{try{const v=G.join(s,b),N=await Ae.readFile(v,"utf-8"),w=JSON.parse(N);return w.object_id===e||t&&w.object_id===t?w:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(m),Promise.all(f)]),x=[...y,...g].filter(b=>b!==null);for(const b of x)b.object_id===e?a.push(b):t&&b.object_id===t&&o.push(b);a.sort((b,v)=>v.created_at-b.created_at),o.sort((b,v)=>v.created_at-b.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:a,analysisCalls:o}}async function lN({params:e,request:t}){const{entitySha:r}=e;if(!r)return ue({error:"Entity SHA is required"},{status:400});const a=new URL(t.url).searchParams.get("analysisId")||void 0,o=await iN(r,a);return ue(o)}const cN=Object.freeze(Object.defineProperty({__proto__:null,loader:lN},Symbol.toStringTag,{value:"Module"}));function dN(){try{const e=Ce()||process.cwd(),t=ee.join(e,".codeyam","config.json");if(!ce.existsSync(t))return Response.json({projectTitle:null,projectDescription:null,defaultScreenSize:null,screenSizes:null,projectScreenSizes:null,appFormats:null,hosting:null,database:null,github:null});const r=JSON.parse(ce.readFileSync(t,"utf8"));return Response.json({projectTitle:r.projectTitle||null,projectDescription:r.projectDescription||null,defaultScreenSize:r.defaultScreenSize||null,screenSizes:r.screenSizes||null,projectScreenSizes:r.projectScreenSizes||null,appFormats:r.appFormats||null,techStack:r.techStack||null,hosting:r.hosting||null,database:r.database||null,github:r.github||null,environmentVariables:r.environmentVariables||[]})}catch{return Response.json({projectTitle:null,projectDescription:null,defaultScreenSize:null,screenSizes:null,appFormats:null,techStack:null,hosting:null,database:null,github:null,environmentVariables:[]})}}async function uN({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ce()||process.cwd(),r=ee.join(t,".codeyam","config.json");if(!ce.existsSync(r))return new Response(JSON.stringify({error:"No config.json found"}),{status:404,headers:{"Content-Type":"application/json"}});const s=await e.json(),a=JSON.parse(ce.readFileSync(r,"utf8"));if(s.projectTitle!==void 0&&(a.projectTitle=s.projectTitle),s.projectDescription!==void 0&&(a.projectDescription=s.projectDescription),s.defaultScreenSize!==void 0&&(a.defaultScreenSize=s.defaultScreenSize),s.screenSizes!==void 0&&(a.screenSizes=s.screenSizes),s.appFormats!==void 0&&(a.appFormats=s.appFormats),s.techStack!==void 0&&(a.techStack=s.techStack),s.projectScreenSizes!==void 0&&(a.projectScreenSizes=s.projectScreenSizes),s.hosting!==void 0&&(a.hosting=s.hosting),s.database!==void 0&&(a.database=s.database),s.github!==void 0&&(a.github=s.github),s.addEnvironmentVariable){const o=a.environmentVariables||[],{key:i,value:l}=s.addEnvironmentVariable,d=o.findIndex(u=>(u.key||u.name)===i);d>=0?o[d]={key:i,value:l}:o.push({key:i,value:l}),a.environmentVariables=o}if(s.screenSizes&&!s.defaultScreenSize)for(const[o,i]of Object.entries(s.screenSizes)){const l=i;if(l.default){a.defaultScreenSize={name:o,width:l.width,height:l.height},s.defaultScreenSize=a.defaultScreenSize;break}}return ce.writeFileSync(r,JSON.stringify(a,null,2)),s.defaultScreenSize&&!s.skipBroadcast&&Ii(s.defaultScreenSize),Nt.notifyChange("unknown"),new Response(JSON.stringify({success:!0,projectTitle:a.projectTitle||null,projectDescription:a.projectDescription||null,defaultScreenSize:a.defaultScreenSize||null,screenSizes:a.screenSizes||null,projectScreenSizes:a.projectScreenSizes||null,appFormats:a.appFormats||null,techStack:a.techStack||null,hosting:a.hosting||null,database:a.database||null,github:a.github||null,environmentVariables:a.environmentVariables||[]}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const pN=Object.freeze(Object.defineProperty({__proto__:null,action:uN,loader:dN},Symbol.toStringTag,{value:"Module"}));function yp(e){try{const t=G.join(e,"package.json"),r=JSON.parse(Q.readFileSync(t,"utf8")),s={...r.dependencies,...r.devDependencies};return s.vitest?"vitest":s.jest?"jest":null}catch{return null}}function hN(e,t){var i;const s=JSON.parse(t).testResults||[],a=[];for(const l of s)for(const d of l.assertionResults||[]){const u=d.ancestorTitles||[],p=d.title||d.fullName||"unknown",h=u.length>0?`${u.join(" > ")} > ${p}`:p;a.push({title:p,fullName:h,status:d.status==="passed"?"passed":d.status==="failed"?"failed":"skipped",duration:d.duration,failureMessages:(i=d.failureMessages)!=null&&i.length?d.failureMessages:void 0})}const o=a.some(l=>l.status==="failed");return{testFilePath:e,status:o?"failed":"passed",testCases:a}}function mN(e,t,r){var l;const a=JSON.parse(r).testResults||[],o=new Map;for(const d of a){const u=d.name||"",p=o.get(u);p?p.push(d):o.set(u,[d])}const i={};e.endsWith("/")||e+"";for(const d of t){const u=G.isAbsolute(d)?d:G.join(e,d),p=o.get(u);if(!p||p.length===0){i[d]={testFilePath:d,status:"error",testCases:[],errorMessage:`File not found in test output: ${d}`};continue}const h=[];for(const f of p)for(const y of f.assertionResults||[]){const g=y.ancestorTitles||[],x=y.title||y.fullName||"unknown",b=g.length>0?`${g.join(" > ")} > ${x}`:x;h.push({title:x,fullName:b,status:y.status==="passed"?"passed":y.status==="failed"?"failed":"skipped",duration:y.duration,failureMessages:(l=y.failureMessages)!=null&&l.length?y.failureMessages:void 0})}const m=h.some(f=>f.status==="failed");i[d]={testFilePath:d,status:m?"failed":"passed",testCases:h}}return i}function fN(e,t,r){return e==="vitest"?{cmd:"node",args:["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",t,...r]}:{cmd:"./node_modules/.bin/jest",args:["--json","--outputFile",t,...r]}}async function gN(e,t){if(t.length===0)return{};const r=yp(e);if(!r){const d={};for(const u of t)d[u]={testFilePath:u,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};return d}const s=[],a={};for(const d of t){const u=G.isAbsolute(d)?d:G.join(e,d);Q.existsSync(u)?s.push(d):a[d]={testFilePath:d,status:"error",testCases:[],errorMessage:"Test file not found"}}if(s.length===0)return a;const o=G.join(pa.tmpdir(),`codeyam-test-result-${Date.now()}.json`),{cmd:i,args:l}=fN(r,o,s);return new Promise(d=>{var m;const u=kt(i,l,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let p="";(m=u.stderr)==null||m.on("data",f=>{p+=f.toString()});const h=setTimeout(()=>{u.kill("SIGTERM");for(const f of s)a[f]={testFilePath:f,status:"error",testCases:[],errorMessage:"Test timed out after 60 seconds"};d(a)},6e4);u.on("close",()=>{clearTimeout(h);try{const f=Q.readFileSync(o,"utf8");Q.unlinkSync(o);const y=mN(e,s,f);Object.assign(a,y)}catch{for(const f of s)a[f]={testFilePath:f,status:"error",testCases:[],errorMessage:p.trim().slice(0,500)||"Test runner failed to produce output"}}d(a)}),u.on("error",f=>{clearTimeout(h);for(const y of s)a[y]={testFilePath:y,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${f.message}`};d(a)})})}async function yN(e,t){const r=yp(e);if(!r)return{testFilePath:t,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};const s=G.isAbsolute(t)?t:G.join(e,t);if(!Q.existsSync(s))return{testFilePath:t,status:"error",testCases:[],errorMessage:"Test file not found"};const a=G.join(pa.tmpdir(),`codeyam-test-result-${Date.now()}.json`);return new Promise(o=>{var h;let i,l;r==="vitest"?(l="node",i=["./node_modules/.bin/vitest","run","--reporter=json","--outputFile",a,t]):(l="./node_modules/.bin/jest",i=["--json","--outputFile",a,"--testPathPatterns",t]);const d=kt(l,i,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let u="";(h=d.stderr)==null||h.on("data",m=>{u+=m.toString()});const p=setTimeout(()=>{d.kill("SIGTERM"),o({testFilePath:t,status:"error",testCases:[],errorMessage:"Test timed out after 30 seconds"})},3e4);d.on("close",()=>{clearTimeout(p);try{const m=Q.readFileSync(a,"utf8");Q.unlinkSync(a),o(hN(t,m))}catch{o({testFilePath:t,status:"error",testCases:[],errorMessage:u.trim().slice(0,500)||"Test runner failed to produce output"})}}),d.on("error",m=>{clearTimeout(p),o({testFilePath:t,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${m.message}`})})})}function jc(){return{version:1,results:{}}}function xp(e,t,r){return e.sourceHash!==t||e.testHash!==r}function xN(e,t,r){return{testFilePath:e.testFilePath,status:e.status,testCases:e.testCases,...e.errorMessage?{errorMessage:e.errorMessage}:{},sourceHash:t,testHash:r,timestamp:new Date().toISOString()}}function bN(e,t){return{version:1,results:{...e.results,...t}}}const bp="test-results.json";function Ji(e){const t=G.join(e,".codeyam",bp);try{const r=Q.readFileSync(t,"utf8"),s=JSON.parse(r);return s&&s.version===1&&s.results?s:jc()}catch{return jc()}}function vN(e,t){const r=G.join(e,".codeyam");Q.mkdirSync(r,{recursive:!0});const s=G.join(r,bp);Q.writeFileSync(s,JSON.stringify(t,null,2)+`
453
+ `)}function _c(e){try{const t=Q.readFileSync(e);return si.createHash("sha256").update(t).digest("hex")}catch{return""}}function Hi(e,t){const r={};for(const s of t){const a=G.join(e,s.filePath),o=G.join(e,s.testFile);r[s.testFile]={sourceHash:_c(a),testHash:_c(o)}}return r}function vp(e,t,r){const s=Ji(e),a=Hi(e,r),o={};for(const[l,d]of Object.entries(t)){const u=a[l];u&&(o[l]=xN(d,u.sourceHash,u.testHash))}const i=bN(s,o);vN(e,i)}async function wN({request:e}){const r=new URL(e.url).searchParams.get("testFile");if(!r)return new Response(JSON.stringify({status:"error",errorMessage:"Missing testFile parameter",testCases:[],testFilePath:""}),{headers:{"Content-Type":"application/json"}});const s=Ce()||process.cwd();try{const a=await yN(s,r);try{const o=G.join(s,".codeyam","glossary.json"),i=Q.readFileSync(o,"utf8"),d=Ea(JSON.parse(i)).find(u=>u.testFile===r);d&&vp(s,{[r]:a},[{filePath:d.filePath,testFile:r}])}catch{}return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}catch(a){const o=a instanceof Error?a.message:"Unknown error";return new Response(JSON.stringify({testFilePath:r,status:"error",testCases:[],errorMessage:o}),{status:500,headers:{"Content-Type":"application/json"}})}}const NN=Object.freeze(Object.defineProperty({__proto__:null,loader:wN},Symbol.toStringTag,{value:"Module"}));function Ec(e,t){var r,s;try{return((s=(r=Me(`git rev-parse ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:r.toString())==null?void 0:s.trim())??null}catch(a){return console.error(`Failed to get commit SHA for ${e}:`,a),""}}function SN(e,t,r,s){const a=pr.createHash("sha256");return a.update(`${e}:${t}:${r}:${s}`),a.digest("hex").substring(0,16)}function wp(){const e=Ce();if(!e)throw new Error("No project root found");const t=ee.join(e,".codeyam","cache","branch-entity-diff");return ce.existsSync(t)||ce.mkdirSync(t,{recursive:!0}),t}function CN(e){try{const t=wp(),r=ee.join(t,`${e}.json`);if(!ce.existsSync(r))return null;const s=ce.readFileSync(r,"utf8");return JSON.parse(s)}catch(t){return console.error("Failed to read cache:",t),null}}function kN(e,t){try{const r=wp(),s=ee.join(r,`${e}.json`);ce.writeFileSync(s,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function jN(e,t,r){const s=ea(t,e),a=ea(r,e),o=new Map(s.map(p=>[p.name,p])),i=new Map(a.map(p=>[p.name,p])),l=[],d=[],u=[];for(const[p,h]of i){const m=o.get(p);m?m.sha!==h.sha&&d.push({name:p,baseSha:m.sha,compareSha:h.sha,entityType:h.entityType}):l.push(h)}for(const[p,h]of o)i.has(p)||u.push(h);return{filePath:e,newEntities:l,modifiedEntities:d,deletedEntities:u}}function _N(e,t){const r=Ce();if(!r)throw new Error("No project root found");const s=Ec(e,r),a=Ec(t,r);if(!s||!a)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=SN(e,t,s,a),i=CN(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const l=np(e,t),d=[];for(const p of l)if(p.path.match(/\.(tsx?|jsx?)$/))if(p.status==="deleted"){const h=Ys(p.path,e,t),m=ea(h.oldContent,p.path);d.push({filePath:p.path,newEntities:[],modifiedEntities:[],deletedEntities:m})}else if(p.status==="added"){const h=Ys(p.path,e,t),m=ea(h.newContent,p.path);d.push({filePath:p.path,newEntities:m,modifiedEntities:[],deletedEntities:[]})}else{const h=Ys(p.path,e,t),m=jN(p.path,h.oldContent,h.newContent);(m.newEntities.length>0||m.modifiedEntities.length>0||m.deletedEntities.length>0)&&d.push(m)}const u={baseBranch:e,compareBranch:t,baseCommitSha:s,compareCommitSha:a,fileComparisons:d,cacheKey:o,computedAt:new Date().toISOString()};return kN(o,u),u}function EN({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),s=t.searchParams.get("compare");if(!r||!s)return ue({error:"Missing required parameters: base and compare"},{status:400});const a=_N(r,s);return ue(a)}catch(t){return console.error("Failed to compute branch entity diff:",t),ue({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const PN=Object.freeze(Object.defineProperty({__proto__:null,loader:EN},Symbol.toStringTag,{value:"Module"}));async function AN({request:e}){if(e.method!=="POST")return ue({error:"Method not allowed"},{status:405});try{const t=await e.json(),{serverUrl:r,scenarioId:s,projectId:a,viewportWidth:o=1440}=t;if(!r||!s||!a)return ue({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${r}`),console.log(`[Capture] Scenario ID from request: ${s}`);const i=Ce();if(!i)return ue({error:"Project root not found"},{status:500});const l=G.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:r,scenarioId:s,projectId:a,projectRoot:i,viewportWidth:o}),u=await new Promise(m=>{const f=G.join(i,".codeyam","db.sqlite3"),y=kt("npx",["tsx",l,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let g="",x="";y.stdout.on("data",b=>{const v=b.toString();g+=v;const N=v.trim().split(`
454
+ `);for(const w of N)w.includes("[Capture]")&&console.log(w)}),y.stderr.on("data",b=>{const v=b.toString();x+=v,console.error("[Capture:Error]",v.trim())}),y.on("close",b=>{m(b===0?{success:!0,output:g}:{success:!1,output:g,error:x||`Process exited with code ${b}`})}),y.on("error",b=>{console.error("[Capture] Failed to spawn child process:",b),m({success:!1,output:"",error:b.message})})});if(!u.success)return ue({error:"Failed to capture screenshot",details:u.error},{status:500});const p=u.output.match(/\[Capture\] RESULT:(.+)/);if(!p)return ue({error:"Failed to parse capture result"},{status:500});const h=JSON.parse(p[1]);return ue(h)}catch(t){return console.error("[Capture] Error:",t),ue({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const TN=Object.freeze(Object.defineProperty({__proto__:null,action:AN},Symbol.toStringTag,{value:"Module"}));function MN(e){const t=e||process.cwd();try{return Me("git rev-parse HEAD",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch(r){throw new Error(`Failed to get HEAD SHA: ${r}`)}}function $N(e){const t=e||process.cwd();try{return Me("git rev-parse --git-dir",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),!0}catch{return!1}}function FN(e){if($N(e))return!1;Me("git init",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]});try{Me('git config user.email "codeyam@local"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Me('git config user.name "CodeYam"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}catch{}return!0}function DN(e){Me("git add -A",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}function RN(e,t){return Me(`git commit -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),MN(e)}function IN(e){return/^[0-9a-f]{7,40}$/i.test(e)}function ON(e,t){try{return Me(`git cat-file -t ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"}),!0}catch{return!1}}function LN(e,t){try{return{stashed:!Me(`git stash push -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:"pipe"}).includes("No local changes")}}catch{return{stashed:!1}}}function BN(e,t){Me(`git checkout ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"})}async function zN({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{commitSha:r}=t;if(!r||typeof r!="string")return new Response(JSON.stringify({success:!1,error:"commitSha is required"}),{status:400,headers:{"Content-Type":"application/json"}});if(!IN(r))return new Response(JSON.stringify({success:!1,error:"Invalid commit SHA format"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();if(console.log(`[editor-load-commit] Loading commit ${r} in ${s}`),!ON(s,r))return new Response(JSON.stringify({success:!1,error:`Commit ${r} not found`}),{status:400,headers:{"Content-Type":"application/json"}});const{stashed:a}=LN(s,"codeyam: auto-stash before time travel");a&&console.log("[editor-load-commit] Stashed uncommitted changes");try{BN(s,r),console.log(`[editor-load-commit] Checked out ${r}`)}catch(o){const i=o instanceof Error?o.message:String(o);return console.error("[editor-load-commit] Checkout failed:",i),new Response(JSON.stringify({success:!1,error:`Checkout failed: ${i}`}),{status:500,headers:{"Content-Type":"application/json"}})}try{const i=await(await fetch(`http://localhost:${process.env.CODEYAM_PORT||"3111"}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})})).json();console.log("[editor-load-commit] Dev server restart:",i)}catch(o){console.warn("[editor-load-commit] Dev server restart warning:",o)}return new Response(JSON.stringify({success:!0,stashed:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-load-commit] Error:",t),new Response(JSON.stringify({success:!1,error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const YN=Object.freeze(Object.defineProperty({__proto__:null,action:zN},Symbol.toStringTag,{value:"Module"}));async function UN(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await We();const s=await tn({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const a=$e(),o=s.entitySha,i=await a.selectFrom("entities").select(["metadata"]).where("sha","=",o).executeTakeFirst();let l={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?l=JSON.parse(i.metadata):l=i.metadata),l.defaultWidth=t,await a.updateTable("entities").set({metadata:JSON.stringify(l)}).where("sha","=",o).execute(),console.log(`[recapture] Updated defaultWidth for entity ${o} to ${t}`),!s.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=s.scenarios)==null?void 0:f.length)||0} scenarios`),await mr(e,y=>{if(y){if(y.readyToBeCaptured=!0,y.scenarios)for(const g of y.scenarios)delete g.finishedAt,delete g.startedAt,delete g.screenshotStartedAt,delete g.screenshotFinishedAt,delete g.interactiveStartedAt,delete g.interactiveFinishedAt,delete g.error,delete g.errorStack;delete y.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const d=Ce();if(!d)throw new Error("Project root not found");const u=G.join(d,".codeyam","config.json"),p=JSON.parse(Q.readFileSync(u,"utf8")),{projectSlug:h}=p;if(!h)throw new Error("Project slug not found in config");const{jobId:m}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:h,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${m}`),{jobId:m}}async function WN(e,t,r){var p;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await We();const s=await tn({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const a=(p=s.scenarios)==null?void 0:p.find(h=>h.id===t);if(!a)throw console.log(`[recapture] Scenario ${t} not found in analysis ${e}`),new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${a.name}`),await mr(e,h=>{if(h&&(h.readyToBeCaptured=!0,delete h.finishedAt,h.scenarios)){const m=h.scenarios.find(f=>f.name===a.name);m&&(delete m.finishedAt,delete m.startedAt,delete m.error,delete m.errorStack,delete m.screenshotStartedAt,delete m.screenshotFinishedAt,delete m.interactiveStartedAt,delete m.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${a.name} for recapture`);const o=Ce();if(!o)throw new Error("Project root not found");const i=G.join(o,".codeyam","config.json"),l=JSON.parse(Q.readFileSync(i,"utf8")),{projectSlug:d}=l;if(!d)throw new Error("Project slug not found in config");const{jobId:u}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:d,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${u}`),{jobId:u}}async function JN({request:e,context:t}){if(e.method!=="POST")return ue({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await nn()),!r)return ue({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a||!o)return ue({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${a}, scenario ${o}`);const i=await WN(a,o,r);return console.log("[API] Scenario recapture queued",i),ue({success:!0,message:"Scenario recapture queued",...i})}catch(s){return console.log("[API] Error during scenario recapture:",s),ue({error:"Failed to recapture scenario",details:s instanceof Error?s.message:String(s)},{status:500})}}const HN=Object.freeze(Object.defineProperty({__proto__:null,action:JN},Symbol.toStringTag,{value:"Module"}));async function Ko(e){try{return await Te.stat(e),!0}catch{return!1}}async function Np(){try{const e=Ce();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await Te.readFile(t,"utf-8")).projectSlug||null}catch{return null}}function VN(){return`/private/tmp/claude-501/-${(Ce()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const Us="/tmp/claude-rule-markers",KN=/<system-reminder>[\s\S]*?<\/system-reminder>/g,Pc=2e3;function GN(e,t){if(e==="Read"||e==="Write"||e==="Edit")return String(t.file_path||"");if(e==="Glob")return String(t.pattern||"");if(e==="Grep"){const r=String(t.pattern||""),s=String(t.path||"");return s?`"${r}" in ${s}`:`"${r}"`}if(e==="Bash"){const r=String(t.command||"");return r.length>100?r.slice(0,100)+"...":r}if(e==="Task")return String(t.description||String(t.prompt||"").slice(0,80));for(const r of Object.values(t))if(typeof r=="string"&&r)return r.slice(0,80);return""}const qN=["no,","no ","that's not","thats not","that is not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","dont do","shouldn't","should not","try again","let me clarify","to clarify","that broke","that failed","error","bug"];function QN(e){const t=[],r=new Set;for(const s of e)if(!(s.type!=="tool_call"||!s.name||!s.input)){if(s.name==="Write"||s.name==="Edit"){const a=String(s.input.file_path||"");if(a.includes(".claude/rules/")){const o=a.replace(/^.*?(\.claude\/rules\/)/,"$1"),i=`${s.name}:${o}`;r.has(i)||(r.add(i),s.name==="Write"?t.push({action:"created",filePath:o,content:String(s.input.content||"")}):t.push({action:"modified",filePath:o,oldString:String(s.input.old_string||""),newString:String(s.input.new_string||"")}))}}else if(s.name==="Bash"){const a=String(s.input.command||"");if(a.includes("codeyam memory touch")){const o=`touch:${a}`;r.has(o)||(r.add(o),t.push({action:"touched",filePath:a}))}}}return t}function ZN(e){if(!e)return;const t="### Session transcript",r=e.indexOf(t);if(r===-1)return;let s=e.slice(r+t.length).trim();const a=s.indexOf(`
455
+ ###`);return a!==-1&&(s=s.slice(0,a).trim()),s||void 0}function XN(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const s of qN)if(r.includes(s))return!0}return!1}function e1(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type==="assistant"){const a=(s.message||{}).model;if(typeof a=="string"&&a)return a}}catch{continue}}}function t1(e){for(const t of e){const r=t.trim();if(r)try{const s=JSON.parse(r);if(s.type!=="result")continue;const a={subtype:String(s.subtype||"unknown"),is_error:!!s.is_error};if(typeof s.duration_ms=="number"&&(a.duration_ms=s.duration_ms),typeof s.duration_api_ms=="number"&&(a.duration_api_ms=s.duration_api_ms),typeof s.num_turns=="number"&&(a.num_turns=s.num_turns),typeof s.total_cost_usd=="number"&&(a.total_cost_usd=s.total_cost_usd),s.usage&&typeof s.usage=="object"){a.usage={};for(const o of["input_tokens","output_tokens","cache_read_input_tokens","cache_creation_input_tokens"])typeof s.usage[o]=="number"&&(a.usage[o]=s.usage[o])}return Array.isArray(s.errors)&&s.errors.length>0&&(a.errors=s.errors.map(String)),a}catch{continue}}}function n1(e){const t=[],r={};for(const s of e){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}const i=o.type;if(i==="progress"||i==="system"||i==="result")continue;const d=(o.message||{}).content,u=o.timestamp||"";if(i==="user"){if(typeof d=="string")t.push({type:"user_prompt",text:d,timestamp:u,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(d)){for(const p of d)if(typeof p=="object"&&p!==null&&p.type==="tool_result"){const h=p,m=String(h.tool_use_id||"");let f=h.content;const y=!!h.is_error;typeof f=="string"&&(f=f.replace(KN,"").trim()),t.push({type:"tool_result",tool_use_id:m,tool_name:r[m]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:y,timestamp:u})}}}else if(i==="assistant"&&Array.isArray(d))for(const p of d){if(typeof p!="object"||p===null)continue;const h=p;if(h.type==="text"){const m=String(h.text||"").trim();m&&t.push({type:"assistant_text",text:m,timestamp:u})}else if(h.type==="tool_use"){const m=String(h.id||""),f=String(h.name||"unknown"),y=h.input||{};r[m]=f,t.push({type:"tool_call",tool_use_id:m,name:f,input:y,timestamp:u})}}}return t}function r1(e,t){return e.type==="user_prompt"||e.type==="assistant_text"?(e.text||"").toLowerCase().includes(t):e.type==="tool_call"?(e.name||"").toLowerCase().includes(t)?!0:JSON.stringify(e.input||{}).toLowerCase().includes(t):e.type==="tool_result"?(e.content||"").toLowerCase().includes(t):!1}const tr=20;async function Ac(e){const r=(await Te.readFile(e.filePath,"utf-8")).split(`
456
+ `),s=n1(r);if(s.length===0)return null;const a=s.find(N=>N.type==="user_prompt"),o=e.stem,i=e1(r);let l=(a==null?void 0:a.slug)||"",d=(a==null?void 0:a.timestamp)||"";d||(d=new Date(e.mtime).toISOString());let u;if(e.filePath.endsWith(".log")){e.stem.endsWith("-stale")?l=l||"rule-reflection/stale":e.stem.endsWith("-conversation")?l=l||"rule-reflection/conversation":e.stem.endsWith("-interruption")?l=l||"rule-reflection/interruption":l=l||"rule-reflection";const N=e.filePath.replace(/\.log$/,".context");if(await Ko(N))try{u=await Te.readFile(N,"utf-8")}catch{}}const p=s.filter(N=>N.type==="tool_call").length,h=s.filter(N=>N.type==="assistant_text").length,m=s.filter(N=>N.type==="tool_result"&&N.is_error&&N.content!=="Sibling tool call errored"),f=m.length,y=m.map(N=>{const w=N.content||"Unknown error";return w.length>150?w.slice(0,150)+"...":w});for(const N of s)N.type==="tool_call"&&N.name&&N.input&&(N.summary=GN(N.name,N.input));for(const N of s)N.type==="tool_result"&&N.content&&N.content.length>Pc&&(N.truncated=!0,N.fullLength=N.content.length,N.content=N.content.slice(0,Pc));const g=QN(s),x=XN(s),b=ZN(u),v=t1(r);return{id:o,slug:l,timestamp:d,model:i,sourceFile:e.filePath,stats:{toolCalls:p,textBlocks:h,errors:f,errorMessages:y},entries:s,context:u,conversationSnippet:b,ruleChanges:g,hasConfusion:x,sessionResult:v}}async function s1(){const e=VN(),t=Us,r=[];if(await Ko(e)){const i=await Te.readdir(e);for(const l of i)if(l.endsWith(".output")){const d=ee.join(e,l),u=await Te.stat(d);r.push({filePath:d,stem:l.replace(".output",""),mtime:u.mtimeMs})}}const s=new Set,a=await Np(),o=[];a&&o.push(ee.join(t,a)),o.push(t);for(const i of o){if(!await Ko(i))continue;const l=await Te.readdir(i);for(const d of l){if(!d.endsWith(".log")||s.has(d))continue;s.add(d);const u=ee.join(i,d),p=await Te.stat(u);r.push({filePath:u,stem:d.replace(".log",""),mtime:p.mtimeMs})}}return r.sort((i,l)=>l.mtime-i.mtime),r}async function a1({request:e}){var t;try{const r=new URL(e.url),s=((t=r.searchParams.get("search"))==null?void 0:t.toLowerCase())||"",a=Math.max(1,parseInt(r.searchParams.get("page")||"1",10)),o=await s1();if(!s){const p=o.length,h=(a-1)*tr,m=o.slice(h,h+tr),f=[];for(const y of m){const g=await Ac(y);g&&f.push(g)}return Response.json({agents:f,total:p,page:a,pageSize:tr})}const i=[];for(const p of o){const h=await Ac(p);if(!h)continue;(h.id.toLowerCase().includes(s)||h.slug.toLowerCase().includes(s)||h.entries.some(f=>r1(f,s)))&&i.push(h)}const l=i.length,d=(a-1)*tr,u=i.slice(d,d+tr);return Response.json({agents:u,total:l,page:a,pageSize:tr})}catch(r){return console.error("[api.agent-transcripts] Error:",r),Response.json({error:"Failed to load agent transcripts",details:r instanceof Error?r.message:String(r)},{status:500})}}const o1=Object.freeze(Object.defineProperty({__proto__:null,loader:a1},Symbol.toStringTag,{value:"Module"})),Sp="__codeyam_editor_dev_server__",Tc=30;function Vi(){return globalThis[Sp]??null}function Cp(e){globalThis[Sp]=e}function As(e,t){const r=[ee.join(e,".next","dev","lock"),ee.join(e,"node_modules",".vite","deps","_lock")];for(const s of r)try{ce.existsSync(s)&&(ce.unlinkSync(s),console.log(`[editor-dev-server] Removed stale lock file: ${s}`))}catch(a){console.warn(`[editor-dev-server] Failed to remove lock file ${s}:`,a)}if(t)try{const s=Me(`lsof -ti:${t}`,{encoding:"utf8"}).trim();if(s){const a=process.pid,o=s.split(`
457
+ `).filter(i=>i&&parseInt(i,10)!==a);if(o.length>0){for(const i of o)try{Me(`kill ${i}`)}catch{}console.log(`[editor-dev-server] Killed orphaned process(es) on port ${t}: ${o.join(", ")}`)}}}catch{}}function i1({request:e}){const t=Vi();return t?new Response(JSON.stringify({status:t.status,url:t.url,proxyUrl:Wu(),pid:t.pid,errorMessage:t.status==="error"?t.errorMessage:null}),{headers:{"Content-Type":"application/json"}}):new Response(JSON.stringify({status:"stopped",url:null,proxyUrl:null}),{headers:{"Content-Type":"application/json"}})}async function l1({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{action:r}=t;return r==="start"?Go():r==="stop"?Mc():r==="restart"?(Mc(),await new Promise(s=>setTimeout(s,1e3)),Go()):new Response(JSON.stringify({error:'Invalid action. Use "start", "stop", or "restart".'}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}function c1(){let t=ee.dirname(new URL(import.meta.url).pathname);for(let s=0;s<5;s++){const a=ee.dirname(t);if(ee.basename(a)==="webserver"||ee.basename(t)==="webserver"){t=ee.basename(t)==="webserver"?t:a;break}t=a}const r=[ee.join(t,"scripts","codeyam-preload.mjs"),ee.join(t,"scripts","codeyam-preload.mjs")];for(const s of r)if(ce.existsSync(s))return s;return console.warn("[editor-dev-server] codeyam-preload.mjs not found, SSR fetch interception disabled"),null}function Go(e=!1){var j,A;const t=Vi();if(t&&t.status!=="stopped"&&t.status!=="error")return new Response(JSON.stringify({status:t.status,url:t.url,message:"Dev server is already running"}),{headers:{"Content-Type":"application/json"}});const r=Ce()||process.cwd(),s=parseInt(process.env.CODEYAM_PORT||"3111",10),{proxyPort:a,devServerPort:o}=Ru(s),i=dx(r,o);if("error"in i)return new Response(JSON.stringify({error:i.error}),{status:400,headers:{"Content-Type":"application/json"}});const{command:l,args:d,env:u}=i;As(r,o),As(r,3e3),As(r,3001),As(r,5173),console.log(`[editor-dev-server] Starting: ${l} ${d.join(" ")} in ${r}`);const p=c1(),h=p?`--import ${p}`:"",{NODE_OPTIONS:m,PORT:f,CODEYAM_PORT:y,...g}=process.env,x={};for(const _ of[".env",".env.local",".env.development",".env.development.local"])try{const M=ee.join(r,_);if(!ce.existsSync(M))continue;const T=ce.readFileSync(M,"utf-8");for(const D of T.split(`
458
+ `)){const R=D.trim();if(!R||R.startsWith("#"))continue;const L=R.indexOf("=");if(L===-1)continue;const U=R.slice(0,L).trim();let W=R.slice(L+1).trim();(W.startsWith('"')&&W.endsWith('"')||W.startsWith("'")&&W.endsWith("'"))&&(W=W.slice(1,-1)),U&&(x[U]=W)}}catch{}const b={};try{const _=ee.join(r,".codeyam","config.json"),M=JSON.parse(ce.readFileSync(_,"utf-8"));for(const T of M.environmentVariables||[])T.key&&T.value!==void 0&&(b[T.key]=T.value)}catch{}const v=kt(l,d,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...g,...x,...b,FORCE_COLOR:"1",BROWSER:"none",...h?{NODE_OPTIONS:h}:{},CODEYAM_PROXY_URL:`http://localhost:${a}`,...u},detached:!0});v.unref();const N=e?((t==null?void 0:t.retryCount)??0)+1:0,w={process:v,url:null,status:"starting",errorMessage:null,stderrBuffer:[],pid:v.pid||0,startedAt:Date.now(),retryCount:N};Cp(w);const C=(_,M)=>{const T=_.toString(),D=T.split(`
459
+ `).filter(R=>R.trim());if(D.length>0&&(w.stderrBuffer.push(...D),w.stderrBuffer.length>Tc&&(w.stderrBuffer=w.stderrBuffer.slice(-Tc))),w.status==="starting"){const R=px(T);R&&(w.url=R,w.status="running",console.log(`[editor-dev-server] URL detected: ${w.url}`),zo({port:a,targetUrl:w.url}).then(()=>dc()))}};(j=v.stdout)==null||j.on("data",_=>C(_)),(A=v.stderr)==null||A.on("data",_=>C(_));const k=parseInt(u.PORT||"0",10);return k>0&&(async()=>{if(await new Promise(M=>setTimeout(M,1e4)),w.status!=="starting")return;console.log(`[editor-dev-server] Stdout detection timed out, polling port ${k}...`);const _=await mx(k,{intervalMs:2e3,maxAttempts:15});_&&w.status==="starting"&&(w.url=_,w.status="running",console.log(`[editor-dev-server] URL detected via polling: ${w.url}`),zo({port:a,targetUrl:w.url}).then(()=>dc()))})(),v.on("exit",_=>{console.log(`[editor-dev-server] Process exited with code ${_}`);const M=Date.now()-w.startedAt,T=w.status==="running",D=fx({exitCode:_??null,uptime:M,retryCount:w.retryCount,wasRunning:T});if(D.action==="retry")console.log(`[editor-dev-server] Quick failure (${M}ms), auto-retrying...`),w.status="stopped",Go(!0);else if(D.action==="error"){w.status="error";const R=w.stderrBuffer.length>0?w.stderrBuffer.join(`
460
+ `):"",L=T?`Dev server exited with code ${_}`:`Dev server exited (code ${_}) before it started serving`;w.errorMessage=R?`${L}
461
+
462
+ ${R}`:L,console.error(`[editor-dev-server] Server failed: ${w.errorMessage}`)}else w.status="stopped"}),v.on("error",_=>{console.error("[editor-dev-server] Process error:",_),w.status="error",w.errorMessage=_.message}),new Response(JSON.stringify({status:"starting",pid:v.pid,message:`Starting ${l} ${d.join(" ")}`}),{headers:{"Content-Type":"application/json"}})}function Mc(){const e=Vi();if(!e||e.status==="stopped")return new Response(JSON.stringify({status:"stopped",message:"No server to stop"}),{headers:{"Content-Type":"application/json"}});Gu();try{e.process.pid&&process.kill(-e.process.pid,"SIGTERM")}catch{try{e.process.kill("SIGTERM")}catch{}}return e.status="stopped",Cp(null),new Response(JSON.stringify({status:"stopped",message:"Dev server stopped"}),{headers:{"Content-Type":"application/json"}})}const d1=Object.freeze(Object.defineProperty({__proto__:null,action:l1,loader:i1},Symbol.toStringTag,{value:"Module"}));async function u1({params:e,request:t}){const{projectSlug:r}=e;if(!r)return new Response("Project slug is required",{status:400});if(t.method!=="DELETE")return new Response("Method not allowed",{status:405});const s=ts(r);try{return await Or(s,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(a){console.error("[api.logs] Error clearing log file:",a);const o=a instanceof Error?a.message:String(a);return new Response(`Error clearing log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function p1({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=ts(t);try{if(!At(r))return new Response("No logs available yet. Analysis may not have started.",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});const s=await $o(r,"utf-8");return!s||s.trim().length===0?new Response("Log file is empty. Waiting for analysis to start...",{headers:{"Content-Type":"text/plain; charset=utf-8"}}):new Response(s,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(s){console.error("[api.logs] Error reading log file:",s);const a=s instanceof Error?s.message:String(s);return new Response(`Error reading log file: ${a}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const h1=Object.freeze(Object.defineProperty({__proto__:null,action:u1,loader:p1},Symbol.toStringTag,{value:"Module"}));function m1({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return Response.json({error:"Missing path parameter"},{status:400});const s=Ce()||process.cwd(),a=G.resolve(s,r);if(!a.startsWith(s+G.sep)&&a!==s)return Response.json({error:"Path outside project root"},{status:403});const o=rp(r,s);return Response.json(o)}const f1=Object.freeze(Object.defineProperty({__proto__:null,loader:m1},Symbol.toStringTag,{value:"Module"}));async function g1(){const e=await ze();if(!e)return Response.json({error:"No project configured"},{status:400});const{project:t}=await Ie(e),r=$e(),s=process.env.CODEYAM_PORT||"3111",a=Ce()||process.cwd(),o=await r.selectFrom("editor_scenarios").select(["id","name","component_name","component_path","url","type","screenshot_path","page_file_path","display_name"]).where("project_id","=",t.id).orderBy("created_at","asc").execute(),i=Mt(o,u=>`${u.name}::${u.url||"/"}`);let l={};try{const u=i.map(h=>({componentName:h.component_name||null,componentPath:h.component_path||null,pageFilePath:h.page_file_path??null,url:h.url??null,displayName:h.display_name??null}));l=(await br({projectRoot:a,scenarioInputs:u})).entityChangeStatus}catch{}const d=i.map(u=>{const p=u,h=rn({componentName:u.component_name,pageFilePath:p.page_file_path,url:p.url}),m=h?l[h]:void 0;return{id:u.id,name:u.name,componentName:u.component_name||null,type:u.type||null,changeStatus:(m==null?void 0:m.status)||null,screenshotPath:u.screenshot_path||null,link:`http://localhost:${s}/editor?scenario=${u.id}&ref=link`}});return Response.json({scenarios:d})}const y1=Object.freeze(Object.defineProperty({__proto__:null,loader:g1},Symbol.toStringTag,{value:"Module"}));async function x1(e,t){var o,i,l,d,u,p;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await We();const r=await tn({id:e,includeScenarios:!0,includeFile:!0});if(!r)throw new Error(`Analysis ${e} not found`);const s=(o=r.scenarios)==null?void 0:o.find(h=>h.id===t);if(!s)throw new Error(`Scenario ${t} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${r.entityName} with scenario ${s.name}`);const a={returnValue:{status:"success",data:((d=(l=(i=s.metadata)==null?void 0:i.data)==null?void 0:l.argumentsData)==null?void 0:d[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((p=(u=s.metadata)==null?void 0:u.data)==null?void 0:p.argumentsData)]},{level:"log",args:["Execution completed successfully"]}],fileWrites:[],apiCalls:[]},timing:{duration:Math.floor(Math.random()*100)+10,timestamp:new Date().toISOString()}};return console.log(`[executeLibraryFunction] Execution completed for ${r.entityName}`),a}async function b1({request:e}){if(e.method!=="POST")return ue({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),s=t.get("scenarioId");if(!r||!s)return ue({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${s}`);const a=await x1(r,s);return console.log("[API] Function execution completed successfully"),ue({success:!0,result:a})}catch(t){return console.log("[API] Error during function execution:",t),ue({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const v1=Object.freeze(Object.defineProperty({__proto__:null,action:b1},Symbol.toStringTag,{value:"Module"}));function w1({request:e}){return ue({status:"ok"})}async function N1({request:e,context:t}){if(e.method!=="POST")return ue({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await nn()),!r)return console.error("[Interactive Mode API] Queue not initialized"),ue({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("action"),o=s.get("analysisId"),i=s.get("scenarioId");if(!a||!o)return ue({error:"Missing required fields: action and analysisId"},{status:400});if(a!=="start"&&a!=="stop")return ue({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await ze();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return ue({error:"Project not initialized"},{status:500});if(a==="start"){const d=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:l});return ue({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:l});return ue({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:d})}}catch(s){console.error("[Interactive Mode API] Error:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Interactive Mode API] Error stack:",o),ue({error:"Failed to control interactive mode",details:a},{status:500})}}const S1=Object.freeze(Object.defineProperty({__proto__:null,action:N1,loader:w1},Symbol.toStringTag,{value:"Module"}));async function C1({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{scenarioId:r,screenshotPaths:s}=t;if(!r)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${r}`),s&&s.length>0){const a=Ce();if(a)for(const o of s){const i=ee.join(a,".codeyam","captures","screenshots",o);try{await Te.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(l){console.log(`[API] Could not delete screenshot ${i}:`,l instanceof Error?l.message:l)}}}await vg({ids:[r]});try{await $e().deleteFrom("editor_scenarios").where("id","=",r).execute()}catch{}try{const a=Ce()||process.cwd();ub(a,r)}catch{}return console.log(`[API] Scenario ${r} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(t){return console.error("[API] Error deleting scenario:",t),Response.json({error:"Failed to delete scenario",details:t instanceof Error?t.message:String(t)},{status:500})}}const k1=Object.freeze(Object.defineProperty({__proto__:null,action:C1},Symbol.toStringTag,{value:"Module"}));class j1 extends Xr{emitFileSynced(t,r){this.emit("event",{type:"file-synced",fileName:t,filePath:r,timestamp:Date.now()})}emitError(t,r){this.emit("event",{type:"sync-error",fileName:t,filePath:r,timestamp:Date.now()})}emitRefreshPreview(){this.emit("event",{type:"refresh-preview",timestamp:Date.now()})}}const qo="__codeyam_dev_mode_event_emitter__";if(!globalThis[qo]){const e=new j1;e.setMaxListeners(20),globalThis[qo]=e}const $c=globalThis[qo];function _1({request:e}){const t=new ReadableStream({start(r){const s=new TextEncoder;r.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
463
+
464
+ `));let a=!1;const o=()=>{if(!a){a=!0,$c.off("event",i),clearInterval(l);try{r.close()}catch{}}},i=d=>{try{r.enqueue(s.encode(`data: ${JSON.stringify(d)}
465
+
466
+ `))}catch{o()}};$c.on("event",i);const l=setInterval(()=>{try{r.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
467
+
468
+ `))}catch{o()}},3e4);e.signal.addEventListener("abort",o)}});return new Response(t,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const E1=Object.freeze(Object.defineProperty({__proto__:null,loader:_1},Symbol.toStringTag,{value:"Module"})),Gr="/tmp/codeyam",Qo=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",kp=500,P1=kp*1024*1024;function $n(e,t){try{return Me(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function Ws(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function jp(e){return $n("config user.email",e)}function A1(e){const t=G.join(e,".codeyam","debug-report.md");if(!Q.existsSync(t))return null;try{return Q.readFileSync(t,"utf8")}catch{return null}}function T1(e,t=20){const r=G.join(Gr,"local-dev",e,"codeyam","log.txt");if(!Q.existsSync(r))return[];try{return Q.readFileSync(r,"utf8").split(`
469
+ `).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function M1(e){try{const t=await fetch(`${Qo}/api/reports/check-base`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseSha:e})});if(!t.ok)return!1;const{hasBase:r}=await t.json();return r}catch{return!1}}function $1(e,t){try{Me(`git archive HEAD | gzip > "${t}"`,{cwd:e,stdio:"pipe",shell:"/bin/bash"})}catch(r){throw new Error(`Failed to create base archive: ${r.message}`)}}function F1(e){const{projectRoot:t,projectSlug:r,outputPath:s,metadata:a,screenshot:o,onProgress:i}=e,l=i||(()=>{}),d=Date.now(),u=G.join(Gr,`delta-staging-${d}`),p=G.join(u,"delta");Q.mkdirSync(p,{recursive:!0});try{const h=$n("diff --binary HEAD",t)||"";Q.writeFileSync(G.join(p,"tracked.patch"),h?h+`
470
+ `:"");const m=$n("ls-files --others --exclude-standard",t);if(m){const x=G.join(p,"untracked");Q.mkdirSync(x,{recursive:!0});for(const b of m.split(`
471
+ `).filter(Boolean)){const v=G.join(t,b),N=G.join(x,b);if(Q.existsSync(v)){const w=G.dirname(N);Q.mkdirSync(w,{recursive:!0}),Q.statSync(v).isFile()&&Q.copyFileSync(v,N)}}}const f=G.join(t,".codeyam");if(Q.existsSync(f)){const x=G.join(p,"codeyam");Q.cpSync(f,x,{recursive:!0})}Q.writeFileSync(G.join(p,"meta.json"),JSON.stringify(a,null,2));const y=G.join(Gr,"local-dev",r,"codeyam","log.txt");Q.existsSync(y)?Q.copyFileSync(y,G.join(p,"codeyam-log.txt")):Q.writeFileSync(G.join(p,"codeyam-log.txt"),`# Log file not found
472
+ `);const g=G.join(t,".codeyam","debug-report.md");Q.existsSync(g)&&(Q.copyFileSync(g,G.join(p,"debug-report.md")),l("Debug report included")),o&&o.length>0&&(Q.writeFileSync(G.join(p,"screenshot.jpg"),o),l(`Screenshot included (${Ws(o.length)})`));try{Me(`tar -czf "${s}" -C "${u}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{Q.rmSync(u,{recursive:!0,force:!0})}}async function D1(e){const{projectRoot:t,projectSlug:r,feedback:s,screenshot:a,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const l=$n("rev-parse HEAD",t);if(!l)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=$n("rev-parse --abbrev-ref HEAD",t)||"unknown",u=$n("status --porcelain",t),p=$n("remote get-url origin",t),h=u!==null&&u.length>0,m=bu(r),f=A1(t);let y=s;f&&(y={...s||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam-diagnose workflow"));const g={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:l,branch:d,isDirty:h,remoteUrl:p},versions:{cli:m.cliVersion,webserver:m.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},x=Date.now(),b=G.join(Gr,`base-${l}-${x}.tar.gz`),v=G.join(Gr,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const N=await M1(l);let w=null;N?i("Server already has base, skipping..."):(i("Generating base archive..."),$1(t,b),w=Q.statSync(b).size,i(`Base archive: ${Ws(w)}`)),i("Generating delta archive..."),F1({projectRoot:t,projectSlug:r,outputPath:v,metadata:g,screenshot:a,onProgress:o});const k=Q.statSync(v).size;i(`Delta archive: ${Ws(k)}`);const j=(w||0)+k;if(j>P1)throw Q.existsSync(b)&&Q.unlinkSync(b),Q.unlinkSync(v),new Error(`Bundle too large: ${Ws(j)} (max: ${kp} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:N?null:b,deltaPath:v,metadata:g,baseSha:l,baseSize:w,deltaSize:k}}async function R1(e){const{basePath:t,deltaPath:r,projectSlug:s,metadata:a,baseSha:o,deltaSize:i,onProgress:l}=e,d=l||(()=>{}),u=Q.statSync(r),p=t?Q.statSync(t):null,h=u.size+((p==null?void 0:p.size)||0);d("Requesting upload URLs...");const m=await fetch(`${Qo}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:s,fileSizeBytes:h,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:a.timestamp,git:a.git,versions:a.versions,system:a.system,feedback:a.feedback}})});if(!m.ok){const N=await m.json();throw new Error(N.error||`Server returned ${m.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await m.json(),x=[];if(t&&g){d("Uploading base...");const N=Q.readFileSync(t);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:N}).then(w=>{if(!w.ok)throw new Error(`Base upload failed: ${w.status}`)}))}d("Uploading delta...");const b=Q.readFileSync(r);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:b}).then(N=>{if(!N.ok)throw new Error(`Delta upload failed: ${N.status}`)})),await Promise.all(x),d("Confirming upload...");const v=await fetch(`${Qo}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!v.ok){const N=await v.json();throw new Error(N.error||`Confirm failed: ${v.status}`)}return t&&Q.existsSync(t)&&Q.unlinkSync(t),Q.unlinkSync(r),{bundleId:f}}async function I1({request:e}){if(e.method!=="POST")return ue({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("issueType"),s=t.get("description"),a=t.get("email"),o=t.get("source"),i=t.get("entitySha"),l=t.get("scenarioId"),d=t.get("analysisId"),u=t.get("currentUrl"),p=t.get("entityName"),h=t.get("entityType"),m=t.get("scenarioName"),f=t.get("errorMessage"),y=t.get("screenshot");let g=s||void 0;!g&&p&&(m?g=`Issue on ${p} scenario "${m}"`:g=`Issue on ${p}`);let x;if(y&&y.size>0){const j=await y.arrayBuffer();x=Buffer.from(j),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const b=Ce();if(!b)return ue({error:"Project root not found"},{status:500});const v=await ze();if(!v)return ue({error:"Project slug not found"},{status:500});const N={issueType:r||"other",description:g,email:a||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:d||void 0,currentUrl:u||void 0,recentActivity:T1(v,20),entityName:p||void 0,entityType:h||void 0,scenarioName:m||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${v}...`),console.log(`[Bundle] Context: ${N.source}, issue: ${N.issueType}`);const w=await D1({projectRoot:b,projectSlug:v,feedback:N,screenshot:x,onProgress:j=>{console.log(`[Bundle] ${j}`)}}),C=(w.baseSize||0)+w.deltaSize;console.log(`[Bundle] Archives created: delta=${w.deltaSize} bytes${w.basePath?`, base=${w.baseSize} bytes`:" (base reused)"}`);const k=await R1({basePath:w.basePath,deltaPath:w.deltaPath,projectSlug:v,metadata:w.metadata,baseSha:w.baseSha,deltaSize:w.deltaSize,onProgress:j=>{console.log(`[Bundle] ${j}`)}});return console.log(`[Bundle] Upload complete: ${k.bundleId}`),ue({success:!0,reportId:k.bundleId,size:C})}catch(t){return console.error("[Bundle] Error:",t),ue({error:t.message||"Failed to generate bundle"},{status:500})}}function O1(){const e=Ce(),t=e?jp(e):null;return ue({defaultEmail:t})}const L1=Object.freeze(Object.defineProperty({__proto__:null,action:I1,loader:O1},Symbol.toStringTag,{value:"Module"})),B1={1:"Plan",2:"Prepare",3:"Prototype",4:"Verify Prototype",5:"Confirm",6:"Deconstruct",7:"Extract",8:"Glossary",9:"Analyze",10:"App Scenarios",11:"User Scenarios",12:"Verify",13:"Journal",14:"Review",15:"Present",16:"Commit",17:"Finalize",18:"Push"};function z1(e){var r;return e.length<4?null:((r=e.slice(3).split(" -> ").pop())==null?void 0:r.trim())||""||null}function Y1(e){const t=e.slice(0,2);return t==="??"?"untracked":t.includes("D")?"deleted":t.includes("A")?"added":t.includes("R")?"renamed":(t.includes("M"),"modified")}function Fc(e){const{projectRoot:t,previousProvider:r,newProvider:s,handoff:a}=e,o=[];try{const d=Me("git status --porcelain",{cwd:t,encoding:"utf8"}).split(`
473
+ `).filter(Boolean);for(const u of d){const p=z1(u);p&&!p.startsWith(".codeyam/")&&o.push({path:p,status:Y1(u)})}}catch{}const i=(a==null?void 0:a.lastStep)??null;return{previousProvider:r,newProvider:s,lastStep:i,lastStepLabel:i?B1[i]||"Unknown":null,handoffSummary:(a==null?void 0:a.summary)??null,stepHistory:(a==null?void 0:a.stepHistory)??[],uncommittedChanges:{summary:`${o.length} files changed`,files:o},generatedAt:new Date().toISOString()}}const No=30;function So(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Dc(e){const t=[];t.push("## Provider Handoff"),t.push("");const r=e.lastStep?` reached **Step ${e.lastStep} (${e.lastStepLabel})**`:"";if(t.push(`You are continuing work started by **${So(e.previousProvider)}** (now using **${So(e.newProvider)}**).`),r&&t.push(`The previous provider${r}.`),t.push(""),e.stepHistory.length>0){t.push("### Progress Timeline"),t.push("| Step | Label | Scenarios | Components | Functions | Files Changed |"),t.push("|------|-------|-----------|------------|-----------|---------------|");for(const a of e.stepHistory)t.push(`| ${a.step} | ${a.label} | ${a.scenarioCount} | ${a.glossaryComponentCount} | ${a.glossaryFunctionCount} | ${a.uncommittedFileCount} |`);t.push("")}e.handoffSummary&&(t.push("### Previous Provider's Notes"),t.push(`> ${e.handoffSummary}`),t.push(""));const{files:s}=e.uncommittedChanges;if(s.length>0){t.push(`### Uncommitted Changes (${s.length} files)`);const a=s.slice(0,No);for(const o of a)t.push(`- \`${o.path}\` (${o.status})`);s.length>No&&t.push(`- ... and ${s.length-No} more`),t.push("")}return t.push("### Instructions"),t.push("1. Review the uncommitted changes and the progress above"),t.push("2. Run `codeyam editor steps` to see the full step workflow"),e.lastStep&&e.lastStepLabel?t.push(`3. Continue from Step ${e.lastStep} (${e.lastStepLabel}), picking up where ${So(e.previousProvider)} left off`):t.push("3. Continue where the previous provider left off"),t.push("4. If anything looks wrong, fix it before proceeding"),t.push(""),t.join(`
474
+ `)}async function U1({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=Ce()||process.cwd(),s=G.join(r,".codeyam","config.json");if(!Q.existsSync(s))return new Response(JSON.stringify({error:"No config.json found"}),{status:404,headers:{"Content-Type":"application/json"}});const a=JSON.parse(Q.readFileSync(s,"utf8")),o=a.provider||"claude",i=a.handoff||null;if(t.action==="generate"){const l=Fc({projectRoot:r,previousProvider:(i==null?void 0:i.lastProvider)||"unknown",newProvider:o,handoff:i}),d=Dc(l);return new Response(JSON.stringify({context:l,markdown:d}),{headers:{"Content-Type":"application/json"}})}if(t.action==="accept"){const l=Fc({projectRoot:r,previousProvider:(i==null?void 0:i.lastProvider)||"unknown",newProvider:o,handoff:i}),d=Dc(l);Q.writeFileSync(G.join(r,".codeyam","handoff-context.md"),d,"utf8"),a.handoff={...a.handoff,lastProvider:o,lastUpdated:new Date().toISOString()},Q.writeFileSync(s,JSON.stringify(a,null,2),"utf8");try{Q.unlinkSync(G.join(r,".codeyam","claude-session-id.txt"))}catch{}return new Response(JSON.stringify({success:!0,context:l}),{headers:{"Content-Type":"application/json"}})}return t.action==="dismiss"?(a.handoff={...a.handoff,lastProvider:o,lastUpdated:new Date().toISOString(),stepHistory:[]},Q.writeFileSync(s,JSON.stringify(a,null,2),"utf8"),new Response(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})):new Response(JSON.stringify({error:"Unknown action"}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const W1=Object.freeze(Object.defineProperty({__proto__:null,action:U1},Symbol.toStringTag,{value:"Module"}));async function J1({request:e}){try{const r=new URL(e.url).searchParams.get("date"),s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=G.join(s,".codeyam","journal","index.json");let o={entries:[]};try{const l=await Ae.readFile(a,"utf8");o=JSON.parse(l)}catch{}let i=o.entries;return r&&(i=i.filter(l=>l.date===r)),new Response(JSON.stringify({entries:i}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-journal] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const H1=Object.freeze(Object.defineProperty({__proto__:null,loader:J1},Symbol.toStringTag,{value:"Module"}));function _p(e){if(!Q.existsSync(e))return rt.Unknown;try{const t=JSON.parse(Q.readFileSync(e,"utf8")),r={...t.dependencies,...t.devDependencies};return r.next?rt.Next:r["@remix-run/node"]||r["@remix-run/react"]||r["react-router"]?rt.Remix:r["react-scripts"]?rt.CRA:r.expo?rt.Expo:r.vite?rt.Vite:rt.Unknown}catch{return rt.Unknown}}function V1(e,t){let r=e;const s=G.resolve(t);for(;;){const a=G.resolve(r);if(Q.existsSync(G.join(a,"pnpm-lock.yaml")))return"pnpm";if(Q.existsSync(G.join(a,"yarn.lock")))return"yarn";if(Q.existsSync(G.join(a,"package-lock.json")))return"npm";if(a===s)break;const o=G.dirname(a);if(o===a)break;r=o}throw new Error(`Could not detect package manager in ${e} or any parent directory up to ${t}`)}function K1(e){const t=/cd\s+([^\s;&|]+)\s*(?:&&|;)/,r=e.match(t);return r?r[1]:null}function G1(e){const t=G.join(e,"package.json");if(!Q.existsSync(t))return{isWebApp:!1};if(_p(t)===rt.Unknown)return{isWebApp:!1};try{const a=JSON.parse(Q.readFileSync(t,"utf8")).scripts||{},o=["remix","react-router","next dev","vite","react-scripts","webpack-dev-server","parcel","expo"],l=Object.keys(a).filter(d=>["dev","start","serve","build"].some(u=>d.includes(u))).filter(d=>o.some(u=>a[d].includes(u)));if(l.length===0)return{isWebApp:!1};for(const d of l){const u=a[d],p=K1(u);if(p){const h=G.join(e,p);if(Q.existsSync(h)&&Q.statSync(h).isDirectory())return{isWebApp:!0,actualPath:h}}}return{isWebApp:!0}}catch{return{isWebApp:!1}}}function Ep(e,t=e,r=0,s=3){if(r>s)return[];const a=[],o=G1(t);if(o.isWebApp){const l=o.actualPath||t,d=G.relative(e,l);return a.push(d||"."),a}const i=["node_modules",".git",".next","dist","build",".cache","coverage",".codeyam"];try{const l=Q.readdirSync(t,{withFileTypes:!0});for(const d of l)if(d.isDirectory()&&!i.includes(d.name)){const u=G.join(t,d.name);a.push(...Ep(e,u,r+1,s))}}catch{}return a}function q1(e){const t=Ep(e);return t.length===0?[]:t.map(s=>{const a=G.join(e,s),o=G.join(a,"package.json"),i=_p(o),l=V1(a,e);let d;if(i===rt.Remix||i===rt.Next||i===rt.Expo){const m=G.join(a,"app");Q.existsSync(m)&&Q.statSync(m).isDirectory()&&(d="app")}const u=Q1(s,e),h=u?{command:"sh",args:["-c",`${l} run ${u} -- --port $PORT`]}:void 0;return{path:s,framework:i,packageManager:l,appDirectory:d,startCommand:h}})}function Q1(e,t){const r=G.join(t,e),s=G.join(r,"package.json");if(!Q.existsSync(s))return null;try{const o=JSON.parse(Q.readFileSync(s,"utf8")).scripts||{},i=["dev","start","serve"];for(const l of i)if(o[l])return l;return null}catch{return null}}function Z1(e,t){const r=new Set(e.map(a=>a.path)),s=[...e];for(const a of t)r.has(a.path)||s.push(a);return s}async function X1({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ce()||process.cwd(),r=ee.join(t,".codeyam","config.json");let s=[];try{s=q1(t)}catch{}if(ce.existsSync(r)){const i=JSON.parse(ce.readFileSync(r,"utf8")),l=i.webapps||[];i.webapps=Z1(s,l),s=i.webapps,ce.writeFileSync(r,JSON.stringify(i,null,2))}const a=await ze();if(a)try{await ir({projectSlug:a,metadataUpdate:{webapps:s}})}catch{}let o=!1;if(s.length>0)try{const i=process.env.CODEYAM_PORT||"3111",d=await(await fetch(`http://localhost:${i}/api/editor-dev-server`)).json();(d.status==="stopped"||d.status===void 0)&&(await fetch(`http://localhost:${i}/api/editor-dev-server`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}),o=!0)}catch{}return new Response(JSON.stringify({success:!0,webapps:s,devServerStarted:o,message:`Detected ${s.length} webapp(s)`}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const eS=Object.freeze(Object.defineProperty({__proto__:null,action:X1},Symbol.toStringTag,{value:"Module"})),tS=[{id:"plan-project-name",label:"Define project name and description",completed:!1,autoDetect:"project-title-exists"},{id:"plan-tech-stack",label:"Review tech stack",completed:!1,autoDetect:"tech-stack-configured"},{id:"plan-design-system",label:"Create design system",completed:!1,autoDetect:"design-system-exists"},{id:"plan-screen-sizes",label:"Configure screen sizes",completed:!1,autoDetect:"screen-sizes-configured"},{id:"plan-github",label:"Setup GitHub repository",completed:!1,autoDetect:"github-configured"}],nS=[{id:"deploy-hosting",label:"Set up hosting provider",completed:!1,autoDetect:"hosting-configured"},{id:"deploy-database",label:"Set up hosted database",completed:!1,autoDetect:"database-configured"},{id:"deploy-env-vars",label:"Configure environment variables",completed:!1,autoDetect:"env-vars-configured"},{id:"deploy-cicd",label:"Set up CI/CD pipeline",completed:!1},{id:"deploy-domain",label:"Configure custom domain",completed:!1},{id:"deploy-production",label:"Deploy to production",completed:!1}];function Pp(){return{plan:tS.map(e=>({...e})),deploy:nS.map(e=>({...e}))}}const Ki=["databases","services","infrastructure"];function Ap(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function rS(e){try{const t=ee.join(e,".codeyam","config.json"),s=JSON.parse(ce.readFileSync(t,"utf8")).techStack;if(!s||typeof s!="object")return[];const a=new Set(["supabase"]),o=[];for(const i of Ki){const l=s[i];if(Array.isArray(l))for(const d of l){if(!d.envKeys||!Array.isArray(d.envKeys)||d.envKeys.length===0)continue;const u=Ap(d.name);a.has(u)||o.push({id:`deploy-svc-${u}`,label:`Set up ${d.name}`,completed:!1,autoDetect:`svc-envkeys-${u}`,serviceRef:{name:d.name,category:i}})}}return o}catch{return[]}}function Tp(e){return ee.join(e,".codeyam","roadmap.json")}function Mp(e){let t;try{const s=ce.readFileSync(Tp(e),"utf8");t=oS(JSON.parse(s))}catch{t=Pp()}const r=rS(e);return r.length>0&&(t.deploy=sS(t.deploy,r)),t}function sS(e,t){const r=new Set(t.map(p=>p.id)),s=new Set(e.map(p=>p.id)),a=e.filter(p=>!p.id.startsWith("deploy-svc-")||r.has(p.id)),o=a.findIndex(p=>p.id==="deploy-database"),i=a.findIndex(p=>p.id==="deploy-hosting"),l=o>=0?o+1:i>=0?i+1:0,d=t.filter(p=>!s.has(p.id));d.length>0&&a.splice(l,0,...d);const u=new Map(t.map(p=>[p.id,p]));return a.map(p=>{const h=u.get(p.id);return h&&!p.serviceRef?{...p,serviceRef:h.serviceRef,autoDetect:h.autoDetect}:p})}function aS(e,t){const r=Tp(e),s=ee.dirname(r);ce.existsSync(s)||ce.mkdirSync(s,{recursive:!0}),ce.writeFileSync(r,JSON.stringify(t,null,2))}function Rc(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.id!="string"||typeof t.label!="string"?null:{id:t.id,label:t.label,completed:t.completed===!0,...typeof t.completedAt=="string"?{completedAt:t.completedAt}:{},...typeof t.autoDetect=="string"?{autoDetect:t.autoDetect}:{},...t.userCreated===!0?{userCreated:!0}:{},...t.serviceRef&&typeof t.serviceRef=="object"&&typeof t.serviceRef.name=="string"&&typeof t.serviceRef.category=="string"?{serviceRef:{name:t.serviceRef.name,category:t.serviceRef.category}}:{}}}function Ic(e,t){const r=new Set(e.map(o=>o.id)),s=t.filter(o=>!r.has(o.id));if(s.length===0)return e;const a=[...e];for(const o of s){const i=t.indexOf(o),l=t[i-1];if(l){const d=a.findIndex(u=>u.id===l.id);a.splice(d+1,0,{...o})}else a.unshift({...o})}return a}function Oc(e,t){const r=new Map(t.map(s=>[s.id,s]));return e.map(s=>{const a=r.get(s.id);return a!=null&&a.autoDetect&&!s.autoDetect?{...s,autoDetect:a.autoDetect}:s})}function oS(e){const t=Pp();if(typeof e!="object"||e===null)return t;const r=e,s=Oc(Array.isArray(r.plan)?Ic(r.plan.map(Rc).filter(Boolean),t.plan):t.plan,t.plan),a=Oc(Array.isArray(r.deploy)?Ic(r.deploy.map(Rc).filter(Boolean),t.deploy):t.deploy,t.deploy);return{plan:s,deploy:a}}const iS={"project-title-exists":e=>{try{const t=ee.join(e,".codeyam","config.json");return!!JSON.parse(ce.readFileSync(t,"utf8")).projectTitle}catch{return!1}},"tech-stack-configured":e=>{try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(ce.readFileSync(t,"utf8"));return r.techStack&&typeof r.techStack=="object"&&Object.values(r.techStack).some(a=>Array.isArray(a)&&a.length>0)?!0:Array.isArray(r.webapps)&&r.webapps.length>0}catch{return!1}},"webapps-configured":e=>{try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(ce.readFileSync(t,"utf8"));return Array.isArray(r.webapps)&&r.webapps.length>0}catch{return!1}},"design-system-exists":e=>ce.existsSync(ee.join(e,".codeyam","design-system.md")),"screen-sizes-configured":e=>{try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(ce.readFileSync(t,"utf8"));return r.screenSizes!=null&&Object.keys(r.screenSizes).length>0}catch{return!1}},"github-configured":e=>{try{return ce.existsSync(ee.join(e,".git"))?Me("git remote get-url origin",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim().includes("github.com"):!1}catch{return!1}},"database-configured":e=>{var t;try{const r=ee.join(e,".codeyam","config.json"),s=JSON.parse(ce.readFileSync(r,"utf8"));if(!((t=s.database)!=null&&t.provider))return!1;if(s.database.provider==="supabase"){if(!s.database.supabaseProjectRef)return!1;const a=s.environmentVariables||[],o=new Set;for(const i of a){const l=i.key||i.name;l&&i.value&&o.add(l)}return o.has("NEXT_PUBLIC_SUPABASE_URL")&&o.has("NEXT_PUBLIC_SUPABASE_ANON_KEY")&&o.has("DATABASE_URL")}return!0}catch{return!1}},"hosting-configured":e=>{var t;try{const r=ee.join(e,".codeyam","config.json"),s=JSON.parse(ce.readFileSync(r,"utf8"));return(t=s.hosting)!=null&&t.provider?s.hosting.provider==="vercel"?!!s.hosting.vercelProjectId:!0:!1}catch{return!1}},"scenarios-exist":e=>{const t=ee.join(e,".codeyam","editor-scenarios");try{return ce.readdirSync(t).some(s=>s.endsWith(".json"))}catch{return!1}},"env-vars-configured":e=>{try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(ce.readFileSync(t,"utf8")),s=lS(r.techStack);if(s.length===0)return!0;const a=$p(r.environmentVariables);return s.every(o=>a.has(o))}catch{return!1}}};function lS(e){if(!e||typeof e!="object")return[];const t=[];for(const r of Ki){const s=e[r];if(Array.isArray(s))for(const a of s)a.envKeys&&Array.isArray(a.envKeys)&&t.push(...a.envKeys)}return t}function $p(e){const t=new Set;if(!Array.isArray(e))return t;for(const r of e){const s=r.key||r.name;s&&r.value&&t.add(s)}return t}function cS(e,t){try{const r=t.replace("svc-envkeys-",""),s=ee.join(e,".codeyam","config.json"),a=JSON.parse(ce.readFileSync(s,"utf8")),o=a.techStack;if(!o)return!1;for(const i of Ki){const l=o[i];if(Array.isArray(l)){for(const d of l)if(Ap(d.name)===r){if(!d.envKeys||!Array.isArray(d.envKeys)||d.envKeys.length===0)return!1;const u=$p(a.environmentVariables);return d.envKeys.every(p=>u.has(p))}}}return!1}catch{return!1}}function Lc(e,t){return t.map(r=>{if(!r.autoDetect)return r;let s;const a=iS[r.autoDetect];if(a)s=a(e);else if(r.autoDetect.startsWith("svc-envkeys-"))s=cS(e,r.autoDetect);else return r;if(s&&!r.completed)return{...r,completed:!0,completedAt:new Date().toISOString()};if(!s&&r.completed&&!r.userCreated){const{completedAt:o,...i}=r;return{...i,completed:!1}}return r})}function dS(e){try{const t=ee.join(e,".codeyam","journal","index.json"),r=ce.readFileSync(t,"utf8"),s=JSON.parse(r);return Array.isArray(s.entries)?s.entries.length:0}catch{return 0}}function uS(e,t=3){try{const r=ee.join(e,".codeyam","journal","index.json"),s=ce.readFileSync(r,"utf8"),a=JSON.parse(s);return Array.isArray(a.entries)?a.entries.slice().reverse().slice(0,t).map(o=>({title:o.title,time:o.time,type:o.type||"feature",description:o.description||void 0,userPrompt:o.userPrompt||void 0,scenarioScreenshots:o.scenarioScreenshots||void 0,modifiedFiles:o.modifiedFiles||void 0,entityChangeStatus:o.entityChangeStatus||void 0,commitSha:o.commitSha||null,commitMessage:o.commitMessage||null})):[]}catch{return[]}}function pS(){try{const e=Ce()||process.cwd(),t=Mp(e),r=Lc(e,t.plan),s=Lc(e,t.deploy),a=dS(e),o=uS(e,3),i=Ia(e),l=Li(e);let d=null,u=null,p=[],h=null,m=null,f=null,y=null,g=null,x=null,b=null,v=null,N=[];try{const w=ee.join(e,".codeyam","config.json"),C=JSON.parse(ce.readFileSync(w,"utf8"));d=C.projectTitle||null,u=C.projectDescription||null,Array.isArray(C.webapps)&&(p=C.webapps.map(k=>({path:k.path||".",framework:k.framework||"Unknown"}))),C.techStack&&typeof C.techStack=="object"&&(h=C.techStack),C.screenSizes&&typeof C.screenSizes=="object"&&(m=C.screenSizes),C.projectScreenSizes&&typeof C.projectScreenSizes=="object"&&(f=C.projectScreenSizes),y=C.defaultScreenSize||null,C.hosting&&typeof C.hosting=="object"&&(g=C.hosting),C.database&&typeof C.database=="object"&&(x=C.database),C.github&&typeof C.github=="object"&&(b=C.github),Array.isArray(C.appFormats)&&(v=C.appFormats),Array.isArray(C.environmentVariables)&&(N=C.environmentVariables)}catch{}return v||(v=Bi(e)),Response.json({plan:r,deploy:s,buildSessionCount:a,recentEntries:o,featureName:i,editorStep:(l==null?void 0:l.step)??null,editorStepLabel:(l==null?void 0:l.label)??null,projectTitle:d,projectDescription:u,webapps:p,techStack:h,screenSizes:m,projectScreenSizes:f,defaultScreenSize:y,appFormats:v,hosting:g,database:x,github:b,environmentVariables:N})}catch{return Response.json({plan:[],deploy:[],buildSessionCount:0,recentEntries:[],featureName:null,editorStep:null,editorStepLabel:null,projectTitle:null,projectDescription:null,webapps:[],techStack:null,screenSizes:null,projectScreenSizes:null,defaultScreenSize:null,appFormats:null,hosting:null,database:null,github:null,environmentVariables:[]})}}async function hS({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ce()||process.cwd(),r=await e.json(),s=Mp(t);return Array.isArray(r.plan)&&(s.plan=r.plan),Array.isArray(r.deploy)&&(s.deploy=r.deploy),aS(t,s),Nt.notifyChange("unknown"),Response.json({success:!0,...s})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const mS=Object.freeze(Object.defineProperty({__proto__:null,action:hS,loader:pS},Symbol.toStringTag,{value:"Module"}));async function fS({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=Ce()||process.cwd();if(t.action==="clear"){By(r);try{Q.unlinkSync(G.join(r,".codeyam","claude-session-id.txt"))}catch{}try{Q.unlinkSync(G.join(r,".codeyam","handoff-context.md"))}catch{}return new Response(JSON.stringify({success:!0,message:"Editor state cleared"}),{headers:{"Content-Type":"application/json"}})}if(t.action==="clear-session-id"){try{Q.unlinkSync(G.join(r,".codeyam","claude-session-id.txt"))}catch{}return new Response(JSON.stringify({success:!0,message:"Session ID cleared"}),{headers:{"Content-Type":"application/json"}})}return new Response(JSON.stringify({error:"Unknown action"}),{status:400,headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const gS=Object.freeze(Object.defineProperty({__proto__:null,action:fS},Symbol.toStringTag,{value:"Module"}));function Dn(){const e=process.memoryUsage(),t=Hm.getHeapStatistics();return{process:{rss:Math.round(e.rss/1024/1024),heapTotal:Math.round(e.heapTotal/1024/1024),heapUsed:Math.round(e.heapUsed/1024/1024),external:Math.round(e.external/1024/1024),arrayBuffers:Math.round(e.arrayBuffers/1024/1024)},heap:{totalHeapSize:Math.round(t.total_heap_size/1024/1024),totalHeapSizeExecutable:Math.round(t.total_heap_size_executable/1024/1024),totalPhysicalSize:Math.round(t.total_physical_size/1024/1024),totalAvailableSize:Math.round(t.total_available_size/1024/1024),usedHeapSize:Math.round(t.used_heap_size/1024/1024),heapSizeLimit:Math.round(t.heap_size_limit/1024/1024),mallocedMemory:Math.round(t.malloced_memory/1024/1024),peakMallocedMemory:Math.round(t.peak_malloced_memory/1024/1024)},system:{totalMemory:Math.round(Fo.totalmem()/1024/1024),freeMemory:Math.round(Fo.freemem()/1024/1024)}}}function yS(){const e=Dn();console.log(`
475
+ [Memory Profiler] Detailed Statistics:`),console.log(" Process Memory:"),console.log(` RSS: ${e.process.rss} MB (total memory used by process)`),console.log(` Heap Used: ${e.process.heapUsed} MB / ${e.process.heapTotal} MB`),console.log(` External: ${e.process.external} MB (C++ objects)`),console.log(` ArrayBuffers: ${e.process.arrayBuffers} MB`),console.log(" V8 Heap:"),console.log(` Used: ${e.heap.usedHeapSize} MB / ${e.heap.totalHeapSize} MB`),console.log(` Physical: ${e.heap.totalPhysicalSize} MB`),console.log(` Limit: ${e.heap.heapSizeLimit} MB`),console.log(` Malloced: ${e.heap.mallocedMemory} MB (peak: ${e.heap.peakMallocedMemory} MB)`),console.log(" System:"),console.log(` Total: ${e.system.totalMemory} MB`),console.log(` Free: ${e.system.freeMemory} MB`);const t=(e.heap.usedHeapSize/e.heap.heapSizeLimit*100).toFixed(1);return console.log(` Heap Usage: ${t}% of limit`),e}function xS(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Dn();global.gc();const t=Dn(),r=e.process.heapUsed-t.process.heapUsed;return console.log(`[Memory Profiler] GC freed ${r} MB`),console.log(`[Memory Profiler] Heap: ${t.process.heapUsed} MB (was ${e.process.heapUsed} MB)`),!0}else return console.log("[Memory Profiler] GC not available. Start Node with --expose-gc to enable."),!1}function bS(){const e=Dn(),t=e.heap.usedHeapSize/e.heap.heapSizeLimit*100,r={highHeapUsage:t>80,highExternalMemory:e.process.external>200,highArrayBuffers:e.process.arrayBuffers>100,nearHeapLimit:e.heap.totalAvailableSize<100},s=[];return r.highHeapUsage&&s.push(`High heap usage: ${t.toFixed(1)}% of limit`),r.highExternalMemory&&s.push(`High external memory: ${e.process.external} MB`),r.highArrayBuffers&&s.push(`High ArrayBuffer usage: ${e.process.arrayBuffers} MB`),r.nearHeapLimit&&s.push(`Near heap limit: only ${e.heap.totalAvailableSize} MB available`),{indicators:r,warnings:s,hasIssues:s.length>0}}function vS({request:e}){const r=new URL(e.url).searchParams.get("action");try{switch(r){case"snapshot":return Response.json({success:!1,error:"Heap snapshots are disabled because they block the server for several minutes. Use action=leaks instead."},{status:400});case"gc":{const s=xS(),a=Dn();return Response.json({success:s,message:s?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:a})}case"detailed":{const s=yS();return Response.json({success:!0,stats:s})}case"leaks":{const s=bS(),a=Dn();return Response.json({success:!0,leakCheck:s,stats:a})}default:{const s=Dn();return Response.json({success:!0,stats:s,actions:{gc:"/api/memory-profile?action=gc - Force garbage collection (requires --expose-gc)",detailed:"/api/memory-profile?action=detailed - Log detailed stats to console",leaks:"/api/memory-profile?action=leaks - Check for memory leak indicators"}})}}}catch(s){return console.error("[Memory API] Error:",s),Response.json({success:!1,error:s.message},{status:500})}}const wS=Object.freeze(Object.defineProperty({__proto__:null,loader:vS},Symbol.toStringTag,{value:"Module"})),Ts=ii(oi);async function NS({request:e}){const r=new URL(e.url).searchParams.get("pids");if(!r)return Response.json({error:"Missing pids parameter"},{status:400});const s=r.split(",").map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o));if(s.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const a=await Promise.all(s.map(async o=>{const i=SS(o),l=i?await CS(o):null;return{pid:o,isRunning:i,processName:l}}));return Response.json({processes:a})}function SS(e){try{return process.kill(e,0),!0}catch{return!1}}async function CS(e){if(process.platform==="win32")try{const{stdout:r}=await Ts(`tasklist /FI "PID eq ${e}" /FO CSV /NH`),s=r.match(/"([^"]+)"/);if(!s)return null;const a=s[1];if(a.toLowerCase()==="node.exe")try{const{stdout:o}=await Ts(`wmic process where "ProcessId=${e}" get CommandLine /FORMAT:LIST`),i=o.match(/codeyam-(\w+)/);if(i)return`codeyam-${i[1]}`}catch{}return a}catch{return null}try{const{stdout:r}=await Ts(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:s}=await Ts(`ps -p ${e} -o args=`),a=s.trim(),o=a.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:a.split(" ")[0]||null}catch{return null}}}const kS=Object.freeze(Object.defineProperty({__proto__:null,loader:NS},Symbol.toStringTag,{value:"Module"})),jS=ha(import.meta.url),_S=G.dirname(jS);function ES({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=ka(),r=Ce()||(t==null?void 0:t.projectRoot);if(!r)throw new Error("Could not determine project root");const s=(t==null?void 0:t.port)||3111,a=G.join(_S,"..","..","..","..","webserver","bootstrap.js"),o=G.join(r,".codeyam","logs");Q.existsSync(o)||Q.mkdirSync(o,{recursive:!0});const i=Q.openSync(G.join(o,"background-server.log"),"a"),l=Q.openSync(G.join(o,"background-server-error.log"),"a"),d=new Date().toISOString();Q.appendFileSync(G.join(o,"background-server.log"),`
476
+ [${d}] Server restart requested via dashboard
477
+ `),wi();const u=kt("node",[a],{detached:!0,stdio:["ignore",i,l],env:{...process.env,CODEYAM_PORT:s.toString(),CODEYAM_ROOT_PATH:r,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});u.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${u.pid})`);const p=new Response(JSON.stringify({success:!0}),{status:200,headers:{"Content-Type":"application/json"}});return setTimeout(()=>{console.log("[api.restart-server] Exiting old server process"),process.exit(0)},100),p}catch(t){return console.error("[api.restart-server] Error restarting server:",t),new Response(JSON.stringify({success:!1,error:t instanceof Error?t.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const PS=Object.freeze(Object.defineProperty({__proto__:null,action:ES},Symbol.toStringTag,{value:"Module"}));async function AS({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{analysis:r,scenarios:s}=t;if(!r||!s)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${r.id}`),console.log(`[API] Received ${s.length} scenarios to save`),s.forEach((l,d)=>{var h,m,f,y,g;const u=(m=(h=l.metadata)==null?void 0:h.data)==null?void 0:m.argumentsData,p=Array.isArray(u)&&u.length>0?JSON.stringify(u[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!((f=l.metadata)!=null&&f.data),mockDataKeys:(g=(y=l.metadata)==null?void 0:y.data)!=null&&g.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(u)?u.length:"not-array",argumentsDataPreview:p})});const a=s.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),o=await Rg(a);if(!o||o.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${r.id}`),console.log(`[API] Saved ${o.length} scenarios to database`),o.forEach((l,d)=>{var p,h;const u=(h=(p=l.metadata)==null?void 0:p.data)==null?void 0:h.argumentsData;console.log(`[API] Saved scenario ${d}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(u)?u.length:"not-array"})});const i={...r,scenarios:o};return Response.json({success:!0,analysis:i})}catch(t){return console.error("[API] Error saving scenarios:",t),Response.json({error:"Failed to save scenarios",details:t instanceof Error?t.message:String(t)},{status:500})}}const TS=Object.freeze(Object.defineProperty({__proto__:null,action:AS},Symbol.toStringTag,{value:"Module"})),MS=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function $S({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("search")||"",s=t.searchParams.get("page")||"1",a=new URLSearchParams;r&&a.set("search",r),s!=="1"&&a.set("page",s);const o=a.toString(),i=new URL(`/api/agent-transcripts${o?`?${o}`:""}`,e.url),d=await(await fetch(i.toString())).json();if(d.error)return ue({agents:[],error:d.error,search:r,page:1,totalPages:1});const u=d.total??(d.agents||[]).length,p=d.pageSize??20;return ue({agents:d.agents||[],error:null,search:r,page:d.page??parseInt(s,10),totalPages:Math.max(1,Math.ceil(u/p))})}catch(t){return console.error("Failed to load agent transcripts:",t),ue({agents:[],error:"Failed to load agent transcripts",search:"",page:1,totalPages:1})}}function FS(e){if(!e)return"";try{return new Date(e).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return e}}function DS(e){if(!e)return"";try{return new Date(e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}catch{return e}}function RS(e){return e.includes("opus")?"Opus":e.includes("sonnet")?"Sonnet":e.includes("haiku")?"Haiku":e}function Js({type:e,toolName:t}){const r={user_prompt:"bg-[#00b4d8] text-black",assistant_text:"bg-[#a8dadc] text-black",tool_call:"bg-[#f4a261] text-black",tool_result:"bg-[#2a9d8f] text-black",context:"bg-[#7c3aed] text-white"},s={user_prompt:"USER",assistant_text:"ASSISTANT",tool_call:t||"TOOL",tool_result:"RESULT",context:"CONTEXT"};return n("span",{className:`inline-block px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wide ${r[e]||"bg-gray-300 text-black"}`,children:s[e]||e})}function IS({input:e}){return n("div",{className:"text-xs font-mono space-y-1",children:Object.entries(e).map(([t,r])=>{let s=typeof r=="string"?r:JSON.stringify(r);return s.length>500&&(s=s.slice(0,500)+"..."),c("div",{children:[c("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:s})]},t)})})}function OS({content:e,truncated:t,fullLength:r}){const[s,a]=E(!1);return c("div",{children:[c("pre",{className:"whitespace-pre-wrap break-words text-xs max-h-96 overflow-y-auto text-gray-700",children:[e,t&&!s&&"..."]}),t&&n("button",{onClick:()=>a(!s),className:"text-[11px] text-gray-500 hover:text-gray-700 mt-1 font-mono cursor-pointer",children:s?"Show less":`Show more (${(r||0)-e.length} more chars)`})]})}function LS({entry:e,pairedResult:t}){const[r,s]=E(!1),a=FS(e.timestamp||"");return e.type==="user_prompt"?c("div",{className:"my-2",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(Js,{type:"user_prompt"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("pre",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#00b4d8] max-h-72 overflow-y-auto text-gray-800",children:e.text})]}):e.type==="assistant_text"?c("div",{className:"my-2",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(Js,{type:"assistant_text"}),n("span",{className:"text-[11px] text-gray-400 font-mono",children:a})]}),n("div",{className:"bg-white border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-sm border-l-[3px] border-l-[#a8dadc] text-gray-800",children:e.text})]}):e.type==="tool_call"?c("div",{className:"my-2",children:[c("button",{onClick:()=>s(!r),className:"flex items-center gap-2 w-full text-left bg-white border border-gray-200 rounded-md px-3 py-2 hover:bg-gray-50 cursor-pointer",children:[r?n(Tt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(xn,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(Js,{type:"tool_call",toolName:e.name}),n("span",{className:"text-xs text-gray-500 font-mono truncate flex-1",children:e.summary||""}),n("span",{className:"text-[11px] text-gray-400 font-mono flex-shrink-0",children:a})]}),r&&c("div",{className:"bg-white border border-t-0 border-gray-200 rounded-b-md px-3 py-2 border-l-[3px] border-l-[#f4a261]",children:[n(IS,{input:e.input||{}}),t&&c("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[c("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(OS,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function BS({context:e}){const[t,r]=E(!1);return c("div",{className:"my-2",children:[c("button",{onClick:()=>r(!t),className:"flex items-center gap-2 mb-1 cursor-pointer hover:opacity-80",children:[t?n(Tt,{className:"w-3 h-3 text-gray-400"}):n(xn,{className:"w-3 h-3 text-gray-400"}),n(Js,{type:"context"}),n("span",{className:"text-xs text-gray-500",children:"Full prompt context"})]}),t&&n("pre",{className:"bg-gray-50 border border-gray-200 rounded-md p-3 whitespace-pre-wrap break-words text-xs font-mono border-l-[3px] border-l-[#7c3aed] max-h-96 overflow-y-auto text-gray-700",children:e})]})}function zS({snippet:e}){const[t,r]=E(!1),s=e.split(`
478
+ `).filter(l=>l.trim()),a=s.slice(0,4),o=s.length>4,i=t?s:a;return c("div",{className:"my-2 bg-blue-50 border border-blue-200 rounded-md p-3",children:[c("div",{className:"flex items-center gap-2 mb-2",children:[n(pm,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),c("span",{className:"text-[10px] text-blue-500",children:[s.length," message",s.length!==1?"s":""]})]}),n("div",{className:"space-y-1",children:i.map((l,d)=>{const u=l.match(/^\[(\w+)\]:\s*(.*)/);if(!u)return null;const[,p,h]=u,m=p==="user";return c("div",{className:"text-xs",children:[c("span",{className:`font-bold ${m?"text-blue-700":"text-gray-500"}`,children:[m?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:h.length>200?h.slice(0,200)+"...":h})]},d)})}),o&&n("button",{onClick:()=>r(!t),className:"text-[11px] text-blue-600 hover:text-blue-800 mt-2 font-mono cursor-pointer",children:t?"Show less":`Show all ${s.length} messages`})]})}function YS({change:e}){const[t,r]=E(!1),s=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return c("li",{children:[n("button",{onClick:()=>s&&r(!t),className:`text-left w-full ${s?"hover:text-green-900 cursor-pointer":""}`,children:c("span",{className:"inline-flex items-center gap-1",children:[s&&(t?n(Tt,{className:"w-3 h-3 inline flex-shrink-0"}):n(xn,{className:"w-3 h-3 inline flex-shrink-0"})),e.action==="created"?"Created":"Modified"," ",e.filePath]})}),t&&e.action==="created"&&e.content&&n("pre",{className:"mt-1 mb-2 ml-4 p-2 bg-white border border-green-200 rounded text-[11px] text-gray-700 whitespace-pre-wrap break-words max-h-64 overflow-y-auto",children:e.content}),t&&e.action==="modified"&&c("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&c("pre",{className:"p-2 bg-red-50 border border-red-200 rounded text-[11px] text-red-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["- ",e.oldString]}),e.newString&&c("pre",{className:"p-2 bg-green-50 border border-green-300 rounded text-[11px] text-green-800 whitespace-pre-wrap break-words max-h-32 overflow-y-auto",children:["+ ",e.newString]})]})]})}function US({changes:e}){const t=e.filter(i=>i.action==="touched"),r=e.filter(i=>i.action!=="touched"),s=r.some(i=>i.action==="created"),a=r.some(i=>i.action==="modified");return c("div",{className:`my-2 border rounded-md p-3 ${s?"bg-green-50 border-green-200 text-green-800 [&_ul]:text-green-700":a?"bg-amber-50 border-amber-200 text-amber-800 [&_ul]:text-amber-700":"bg-gray-50 border-gray-200 text-gray-600 [&_ul]:text-gray-500"}`,children:[n("div",{className:"text-xs font-bold mb-1",children:"Rule Changes:"}),c("ul",{className:"text-xs space-y-0.5 font-mono",children:[r.map((i,l)=>n(YS,{change:i},l)),t.length>0&&c("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function WS({result:e}){const t=e.is_error,r=t?"bg-red-50 border-red-200":"bg-green-50 border-green-200",s=t?"text-red-800":"text-green-800",a=t?"text-red-700":"text-green-700",o=e.subtype.replace(/^error_/,"").replace(/_/g," "),i=d=>d>=6e4?`${(d/6e4).toFixed(1)}m`:`${(d/1e3).toFixed(1)}s`,l=d=>d>=1e3?`${(d/1e3).toFixed(1)}k`:String(d);return c("div",{className:`my-2 border rounded-md p-3 ${r}`,children:[c("div",{className:`text-xs font-bold mb-1 ${s}`,children:["Session Result: ",o]}),c("div",{className:`text-xs ${a} font-mono space-y-0.5`,children:[c("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5",children:[e.duration_ms!=null&&c("span",{children:["Duration: ",i(e.duration_ms)]}),e.duration_api_ms!=null&&c("span",{children:["API time: ",i(e.duration_api_ms)]}),e.num_turns!=null&&c("span",{children:["Turns: ",e.num_turns]}),e.total_cost_usd!=null&&c("span",{children:["Cost: $",e.total_cost_usd.toFixed(4)]})]}),e.usage&&c("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1",children:[e.usage.input_tokens!=null&&c("span",{children:["Input: ",l(e.usage.input_tokens)]}),e.usage.output_tokens!=null&&c("span",{children:["Output: ",l(e.usage.output_tokens)]}),e.usage.cache_read_input_tokens!=null&&c("span",{children:["Cache read: ",l(e.usage.cache_read_input_tokens)]}),e.usage.cache_creation_input_tokens!=null&&c("span",{children:["Cache write:"," ",l(e.usage.cache_creation_input_tokens)]})]}),e.errors&&e.errors.length>0&&n("div",{className:"mt-1",children:e.errors.map((d,u)=>n("div",{className:"text-red-700 break-words",children:d},u))})]})]})}function JS({agent:e,defaultOpen:t,isAdmin:r}){var C,k,j;const[s,a]=E(t),[o,i]=E(!1),[l,d]=E(null),[u,p]=E(!1),h=fe(()=>{const A={};for(const _ of e.entries)_.type==="tool_result"&&_.tool_use_id&&(A[_.tool_use_id]=_);return A},[e.entries]),m=fe(()=>{const A=new Set;for(const _ of e.entries)_.type==="tool_call"&&_.tool_use_id&&h[_.tool_use_id]&&A.add(_.tool_use_id);return A},[e.entries,h]),f=A=>{A.stopPropagation(),i(!0),d(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(_=>_.json()).then(_=>{_.success?d(`Saved to ${_.fixturePath}`):d(`Error: ${_.error}`)}).catch(_=>{d(`Error: ${_ instanceof Error?_.message:String(_)}`)}).finally(()=>{i(!1)})},y=(e.ruleChanges||[]).filter(A=>A.action!=="touched"),g=y.filter(A=>A.action==="created"),x=y.filter(A=>A.action==="modified"),b=(e.ruleChanges||[]).filter(A=>A.action==="touched"),v=y.length>0,N=b.length>0,w=v||N;return c("div",{className:`bg-white border rounded-lg overflow-hidden mb-4 ${e.stats.errors>0?"border-red-300":g.length>0?"border-green-300":x.length>0?"border-amber-300":"border-gray-200"}`,children:[c("button",{onClick:()=>a(!s),className:"w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:[s?n(Tt,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(xn,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm font-bold text-[#005C75] font-mono",children:e.id.slice(0,8)}),e.slug&&n("span",{className:"text-xs text-gray-500",children:e.slug}),e.model&&n("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold bg-purple-100 text-purple-700",title:e.model,children:RS(e.model)}),g.length>0&&c("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-green-100 text-green-800",children:[n(Gs,{className:"w-3 h-3"}),g.length," rule",g.length!==1?"s":""," ","created"]}),x.length>0&&c("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-100 text-amber-800",children:[n(Gs,{className:"w-3 h-3"}),x.length," rule",x.length!==1?"s":""," ","modified"]}),!v&&N&&c("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-gray-100 text-gray-500",children:[b.length," timestamp",b.length!==1?"s":""," ","touched"]}),e.stats.errors>0&&c("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold bg-red-100 text-red-800",children:[n(Ks,{className:"w-3 h-3 flex-shrink-0"}),e.stats.errors," ",e.stats.errors===1?"Error":"Errors"]}),c("span",{className:"text-[11px] text-gray-400 font-mono",children:[e.stats.toolCalls," tool calls, ",e.stats.textBlocks," text blocks",((C=e.sessionResult)==null?void 0:C.duration_ms)!=null&&c(we,{children:[" · ",e.sessionResult.duration_ms>=6e4?`${(e.sessionResult.duration_ms/6e4).toFixed(1)}m`:`${(e.sessionResult.duration_ms/1e3).toFixed(1)}s`]}),((k=e.sessionResult)==null?void 0:k.total_cost_usd)!=null&&c(we,{children:[" · ","$",e.sessionResult.total_cost_usd.toFixed(2)]})]}),c("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[DS(e.timestamp),r&&v&&c("button",{onClick:f,disabled:o,className:"inline-flex items-center gap-1 px-2 py-1 rounded text-[10px] font-bold bg-gray-100 text-gray-600 hover:bg-gray-200 disabled:opacity-50 cursor-pointer",title:"Save as test fixture",children:[n(um,{className:"w-3 h-3"}),o?"Saving...":"Save Fixture"]})]})]}),l&&n("div",{className:`px-4 py-2 text-xs font-mono ${l.startsWith("Error")?"bg-red-50 text-red-700":"bg-green-50 text-green-700"}`,children:l}),s&&c("div",{className:"px-4 pb-4 border-t border-gray-100",children:[e.sourceFile&&c("div",{className:"flex items-center gap-2 py-2 text-xs text-gray-500 font-mono",children:[n("span",{className:"text-gray-400",children:"FILE:"}),n("span",{className:"truncate",children:e.sourceFile}),n("button",{onClick:A=>{A.stopPropagation(),navigator.clipboard.writeText(e.sourceFile),p(!0),setTimeout(()=>p(!1),2e3)},className:"p-0.5 rounded text-gray-400 hover:text-gray-600 cursor-pointer transition-colors flex-shrink-0",title:"Copy file path",children:u?n($t,{className:"w-3.5 h-3.5 text-green-500"}):n(Bt,{className:"w-3.5 h-3.5"})})]}),e.sessionResult&&n(WS,{result:e.sessionResult}),e.stats.errors>0&&((j=e.stats.errorMessages)==null?void 0:j.length)>0&&c("div",{className:"my-2 bg-red-50 border border-red-200 rounded-md p-3",children:[c("div",{className:"text-xs font-bold text-red-800 mb-1",children:[e.stats.errors," Error",e.stats.errors!==1?"s":"",":"]}),n("ul",{className:"text-xs text-red-700 space-y-1 font-mono",children:e.stats.errorMessages.map((A,_)=>n("li",{className:"break-words",children:A},_))})]}),e.conversationSnippet&&n(zS,{snippet:e.conversationSnippet}),w&&n(US,{changes:e.ruleChanges}),e.context&&n(BS,{context:e.context}),e.entries.map((A,_)=>{if(A.type==="tool_result"&&A.tool_use_id&&m.has(A.tool_use_id))return null;const M=A.type==="tool_call"&&A.tool_use_id?h[A.tool_use_id]:void 0;return n(LS,{entry:A,pairedResult:M},`${e.id}-${_}`)})]})]})}function Co(e,t){const r=new URLSearchParams;t&&r.set("search",t),e>1&&r.set("page",String(e));const s=r.toString();return`/agent-transcripts${s?`?${s}`:""}`}const HS=tt(function(){const{agents:t,error:r,search:s,page:a,totalPages:o}=lt(),i=Yt(),l=Fd("root"),d=(l==null?void 0:l.isAdmin)??!1,[u,p]=E(s),[h,m]=E(!1),[f,y]=E(0);Wt({source:"agent-transcripts-page"});const g=b=>{b.preventDefault(),window.location.href=Co(1,u)},x=()=>{m(!h),y(b=>b+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:r})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8",children:[c("div",{className:"flex items-center gap-3 mb-1",children:[n("button",{onClick:()=>{i("/memory")},className:"text-gray-600 hover:text-[#005C75] transition-colors cursor-pointer",title:"Back to Memory","aria-label":"Back to Memory",children:n(cm,{className:"w-5 h-5"})}),n(qs,{className:"w-6 h-6 text-[#232323]"}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Agent Transcripts"})]}),n("p",{className:"text-[15px] text-gray-500 ml-14",children:"View background agent transcripts and tool call history"})]}),c("div",{className:"flex items-center gap-4 mb-6",children:[c("form",{onSubmit:g,className:"relative flex-1 max-w-md",children:[n(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:u,onChange:b=>p(b.target.value),placeholder:"Search transcripts...",className:"w-full pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),n("button",{onClick:x,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:h?"Collapse All":"Expand All"})]}),c("div",{className:"text-sm text-gray-500 mb-4",children:["Page ",a," of ",o,s&&c("span",{children:[" ","matching “",s,"”",n(Ee,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?c("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(qs,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Agent Transcripts Found"}),n("p",{className:"text-gray-500",children:"Background agent output files will appear here when available."})]}):n("div",{children:t.map(b=>n(JS,{agent:b,defaultOpen:h,isAdmin:d},b.id))},f),o>1&&c("div",{className:"flex items-center justify-center gap-3 mt-8",children:[c("a",{href:a>1?Co(a-1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${a>1?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:[n(dm,{className:"w-4 h-4"}),"Prev"]}),c("span",{className:"text-sm text-gray-500 font-mono",children:[a," / ",o]}),c("a",{href:a<o?Co(a+1,s):void 0,className:`inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-sm font-medium ${a<o?"bg-white border border-gray-200 text-gray-700 hover:bg-gray-50 cursor-pointer":"bg-gray-100 text-gray-400 pointer-events-none"}`,children:["Next",n(xn,{className:"w-4 h-4"})]})]})]})})}),VS=Object.freeze(Object.defineProperty({__proto__:null,default:HS,loader:$S,meta:MS},Symbol.toStringTag,{value:"Module"}));async function KS({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),{message:r}=t;if(!r)return new Response(JSON.stringify({error:"message is required"}),{status:400,headers:{"Content-Type":"application/json"}});const s=process.env.CODEYAM_ROOT_PATH||process.cwd();console.log(`[editor-commit] Committing with message: "${r}" in ${s}`);const a=FN(s);a&&console.log("[editor-commit] Initialized new git repository"),DN(s),console.log("[editor-commit] Staged all changes");const o=RN(s,r);console.log(`[editor-commit] Created commit: ${o}`);try{const{broadcastHideResults:i}=await Promise.resolve().then(()=>hb);i()}catch{}return new Response(JSON.stringify({success:!0,commitSha:o,initialized:a}),{headers:{"Content-Type":"application/json"}})}catch(t){const r=t instanceof Error?t.message:String(t);return console.error("[editor-commit] Error:",t),new Response(JSON.stringify({error:r}),{status:500,headers:{"Content-Type":"application/json"}})}}const GS=Object.freeze(Object.defineProperty({__proto__:null,action:KS},Symbol.toStringTag,{value:"Module"}));function qS(){const e={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const t=Ce()||process.cwd(),r=G.join(t,".codeyam","data-structure.json");if(Q.existsSync(r))try{const o=JSON.parse(Q.readFileSync(r,"utf-8")),i=Array.isArray(o)?o:[];return i.sort((l,d)=>(l.order??99)-(d.order??99)),new Response(JSON.stringify({dataStructures:i,source:"explicit"}),{headers:e})}catch{}const s=G.join(t,"prisma","schema.prisma");if(Q.existsSync(s)){const o=Q.readFileSync(s,"utf-8"),i=QS(o);return new Response(JSON.stringify({models:i,source:"prisma"}),{headers:e})}const a=ZS(t);return a.length>0?new Response(JSON.stringify({models:a,source:"typescript"}),{headers:e}):new Response(JSON.stringify({models:[],source:null}),{headers:e})}catch{return new Response(JSON.stringify({models:[],source:null}),{headers:e})}}function QS(e){const t=[],r=/model\s+(\w+)\s*\{([^}]+)\}/g,s=new Set;let a;const o=/model\s+(\w+)\s*\{/g;for(;(a=o.exec(e))!==null;)s.add(a[1]);let i;for(;(i=r.exec(e))!==null;){const l=i[1],d=i[2],u=[];for(const p of d.split(`
479
+ `)){const h=p.trim();if(!h||h.startsWith("//")||h.startsWith("@@"))continue;const m=h.match(/^(\w+)\s+([\w[\]?]+)\??(\s+.*)?$/);if(!m)continue;const f=m[1];let y=m[2];const g=m[3]||"",x=y.endsWith("[]"),b=y.endsWith("?")||h.includes("?");y=y.replace(/[[\]?]/g,"");const v=s.has(y),N=g.includes("@id");u.push({name:f,type:y,isRelation:v,isOptional:b,isList:x,isId:N,...v?{relatedModel:y}:{}})}t.push({name:l,fields:u})}return t}function ZS(e){const t=G.join(e,"src");if(!Q.existsSync(t))return[];const r=[],s=new Set,a=[],o=["src","src/lib","src/types","src/utils","src/models"];for(const i of o){const l=G.join(e,i);if(Q.existsSync(l))try{for(const d of Q.readdirSync(l))d.endsWith(".ts")&&!d.endsWith(".test.ts")&&!d.endsWith(".spec.ts")&&a.push(G.join(l,d))}catch{}}for(const i of a){const l=Q.readFileSync(i,"utf-8"),d=/export\s+interface\s+(\w+)/g;let u;for(;(u=d.exec(l))!==null;)s.add(u[1])}for(const i of a){const l=Q.readFileSync(i,"utf-8"),d=/export\s+interface\s+(\w+)\s*\{([^}]+)\}/g;let u;for(;(u=d.exec(l))!==null;){const p=u[1],h=u[2],m=[];for(const f of h.split(`
480
+ `)){const y=f.trim();if(!y||y.startsWith("//"))continue;const g=y.match(/^(\w+)(\?)?:\s*([^;/]+)/);if(!g)continue;const x=g[1],b=!!g[2];let v=g[3].trim();const N=v.endsWith("[]");v=v.replace(/\[\]$/,"");const w=s.has(v);m.push({name:x,type:v,isRelation:w,isOptional:b,isList:N,isId:x==="id",...w?{relatedModel:v}:{}})}r.push({name:p,fields:m})}}return r}const XS=Object.freeze(Object.defineProperty({__proto__:null,loader:qS},Symbol.toStringTag,{value:"Module"}));async function eC({request:e}){const r=new URL(e.url).searchParams.get("skipTests")==="true",s=Ce()||process.cwd(),a=G.join(s,".codeyam","glossary.json");let o;try{const L=Q.readFileSync(a,"utf8");o=Ea(JSON.parse(L))}catch{return Response.json(go({components:[],functions:[],scenarioCounts:{},testFileExistence:{}}))}if(o.length===0)return Response.json(go({components:[],functions:[],scenarioCounts:{},testFileExistence:{}}));const i=G.join(s,".codeyam","editor-step.json");let l=null;try{const L=Q.readFileSync(i,"utf8");l=JSON.parse(L).featureStartedAt||null}catch{}let d,u=[];const p=await ze();if(p)try{const{project:L}=await Ie(p),W=await $e().selectFrom("editor_scenarios").select(["name","component_name","component_path","page_file_path","url","display_name"]).where("project_id","=",L.id).orderBy("created_at","asc").execute(),V=Mt(W,P=>`${P.name}::${P.url||"/"}`),F=V.map(P=>({componentName:P.component_name||null,componentPath:P.component_path||null,pageFilePath:P.page_file_path??null,url:P.url??null,displayName:P.display_name??null}));u=V.map(P=>({name:P.name,componentName:P.component_name||null,pageFilePath:P.page_file_path??null,url:P.url??null}));const Y=await br({projectRoot:s,scenarioInputs:F});Object.keys(Y.entityChangeStatus).length>0&&(d=Y.entityChangeStatus)}catch{}const h=rv({featureStartedAt:l,entityChangeStatus:d});l=h.featureStartedAt,d=h.entityChangeStatus;const m=sv(o,d),{components:f,functions:y}=nv(m);let g={},x={};if(p)try{const{project:L}=await Ie(p),U=$e();g=await yc(U,L.id,l);const W=await xc(U,L.id,l);for(const[V,F]of Object.entries(W)){const Y=m.find(P=>P.filePath===V);Y&&(g[Y.name]=(g[Y.name]||0)+F)}if(l&&d){const V=await yc(U,L.id,null),F=await xc(U,L.id,null);x={...V};for(const[Y,P]of Object.entries(F)){const O=m.find(S=>S.filePath===Y);O&&(x[O.name]=(x[O.name]||0)+P)}}}catch{}let b={};try{const L=process.env.CODEYAM_ROOT_PATH||process.cwd(),U=await ep(L);b=cv(U,u)}catch{}const v={};for(const L of y)L.testFile&&(v[L.testFile]=Q.existsSync(G.join(s,L.testFile)));const N={},w={};if(!r){const L=y.filter(W=>W.testFile&&v[W.testFile]).map(W=>W.testFile),U=[...new Set(L)];if(U.length>0){const W=Ji(s),V=y.filter(S=>!!S.testFile&&v[S.testFile]).map(S=>({filePath:S.filePath,testFile:S.testFile})),F=Hi(s,V),Y=new Set(d?Object.entries(d).filter(([,S])=>S.status==="impacted").map(([S])=>S):[]),P=[],O={};for(const S of U){const $=W.results[S],I=F[S],K=y.some(q=>q.testFile===S&&Y.has(q.name));$&&I&&!xp($,I.sourceHash,I.testHash)&&!K?O[S]={testFilePath:$.testFilePath,status:$.status,testCases:$.testCases,...$.errorMessage?{errorMessage:$.errorMessage}:{}}:P.push(S)}try{const S=P.length>0?await gN(s,P):{},$={...O,...S};try{vp(s,S,V)}catch{}for(const I of y){if(!I.testFile||!v[I.testFile])continue;const K=$[I.testFile];if(!K)continue;const q=K.status==="passed",J=K.testCases.some(z=>z.fullName.startsWith(I.name));w[I.name]=K.testCases.filter(z=>z.fullName.startsWith(I.name)&&z.status!=="skipped").length,N[I.testFile]={passing:q,hasEntityNameDescribe:J,...K.status==="error"&&K.errorMessage?{errorMessage:K.errorMessage}:{}}}}catch(S){for(const $ of U)N[$]={passing:!1,hasEntityNameDescribe:!1,errorMessage:S.message||"Unknown test runner error"}}}}const C=new Set(o.map(L=>L.filePath)),k=[];if(p)try{const{project:L}=await Ie(p),W=await $e().selectFrom("editor_scenarios").select(["component_name","component_path","page_file_path"]).where("project_id","=",L.id).execute(),V=new Map;for(const F of W){const Y=F,P=Y.component_path||Y.page_file_path;if(!P)continue;const O=V.get(P);O?O.count++:V.set(P,{name:Y.component_name||G.basename(P,G.extname(P)),count:1})}for(const[F,Y]of V)C.has(F)||k.push({name:Y.name,filePath:F,scenarioCount:Y.count})}catch{}const j=go({components:f,functions:y,scenarioCounts:g,testFileExistence:v,testResults:N,clientErrors:b,totalScenarioCounts:x,entityChangeStatus:d,testCaseCounts:w});j.missingFromGlossary=k,k.length>0&&(j.summary.allPassing=!1,j.summary.missingFromGlossary=k.length);let A=[];if(p)try{const{project:L}=await Ie(p),U=$e();A=await av(U,L.id,l)}catch{}if(j.incompleteEntities=A,A.length>0){j.summary.allPassing=!1,j.summary.incompleteEntities=A.length;const L=A.filter(U=>U.preExisting).length;L>0&&(j.summary.preExistingIncompleteEntities=L)}let _=[];if(p)try{const{project:L}=await Ie(p),U=$e();_=await ov(U,L.id,l)}catch{}j.miscategorizedScenarios=_,_.length>0&&(j.summary.allPassing=!1,j.summary.miscategorizedScenarios=_.length);let M=[];if(p)try{const{project:L}=await Ie(p),U=$e();M=await iv(U,L.id,l)}catch{}j.unassociatedScenarios=M,M.length>0&&(j.summary.allPassing=!1,j.summary.unassociatedScenarios=M.length);let T=[];if(p&&d&&Object.keys(d).length>0)try{const{project:L}=await Ie(p),W=await $e().selectFrom("editor_scenarios").select(["editor_scenarios.name","editor_scenarios.component_name","editor_scenarios.page_file_path","editor_scenarios.url","editor_scenarios.created_at","editor_scenarios.updated_at"]).where("editor_scenarios.project_id","=",L.id).execute(),V=l?rs(l):null,F=W.map(Y=>({name:Y.name,entityName:rn({componentName:Y.component_name,pageFilePath:Y.page_file_path,url:Y.url}),updatedInSession:V?Ci({created_at:Y.created_at,updated_at:Y.updated_at},V):!1}));T=lp({scenarios:F,entityChangeStatus:d})}catch{}j.scenariosNeedingRecapture=T,T.length>0&&(j.summary.allPassing=!1,j.summary.scenariosNeedingRecapture=T.length);const D=[],R=lv(o);for(const[L,U]of R)D.push({name:L,filePaths:U.map(W=>W.filePath)});return j.duplicateNames=D,Response.json(j)}const tC=Object.freeze(Object.defineProperty({__proto__:null,loader:eC},Symbol.toStringTag,{value:"Module"}));async function nC({request:e}){try{const t=await e.json(),{pid:r,signal:s="SIGTERM",commitSha:a}=t;if(!r||typeof r!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!Bc(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,s)}catch(p){return Response.json({error:"Failed to kill process",pid:r,details:p instanceof Error?p.message:String(p)},{status:500})}const i=3e4,l=500,d=Date.now();let u=!0;for(;u&&Date.now()-d<i;)await new Promise(p=>setTimeout(p,l)),u=Bc(r);if(u){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(p=>setTimeout(p,2e3))}catch(p){console.error(`Failed to SIGKILL process ${r}:`,p)}}if(a)try{await hn({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(p){console.error("Failed to update database after killing process:",p)}return Response.json({success:!0,pid:r,signal:s,message:`Process ${r} killed successfully`,waitedMs:Date.now()-d})}catch(t){return console.error("Error in kill-process API:",t),Response.json({error:"Internal server error",details:t instanceof Error?t.message:String(t)},{status:500})}}function Bc(e){try{return process.kill(e,0),!0}catch{return!1}}const rC=Object.freeze(Object.defineProperty({__proto__:null,action:nC},Symbol.toStringTag,{value:"Module"})),sC=ha(import.meta.url),aC=ee.dirname(sC),oC=ee.resolve(aC,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function iC(e){const t=[],r=new Set;for(const s of e.split(`
481
+ `)){const a=s.trim();if(!a)continue;let o;try{o=JSON.parse(a)}catch{continue}if(o.type!=="assistant")continue;const i=o.message;if(!(!i||!Array.isArray(i.content)))for(const l of i.content){if(typeof l!="object"||l===null)continue;const d=l;if(d.type!=="tool_use")continue;const u=String(d.name||""),p=d.input||{};if(u==="Write"||u==="Edit"){const h=String(p.file_path||"");if(h.includes(".claude/rules/")){const m=h.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${u}:${m}`;r.has(f)||(r.add(f),t.push({action:u==="Write"?"created":"modified",filePath:m}))}}else if(u==="Bash"){const h=String(p.command||"");if(h.includes("codeyam memory touch")){const m=`touch:${h}`;r.has(m)||(r.add(m),t.push({action:"touched",filePath:h}))}}}}return t}async function lC({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const t=await e.json(),{sessionId:r}=t;if(!r)return Response.json({error:"Missing required field: sessionId"},{status:400});const s=await Np(),a=s?ee.join(Us,s):null;let o=a?ee.join(a,`${r}.log`):"";if((!o||!At(o))&&(o=ee.join(Us,`${r}.log`)),!At(o))return Response.json({error:`Log file not found: ${r}.log`},{status:404});const i=await $o(o,"utf-8");let l=a?ee.join(a,`${r}.context`):"";(!l||!At(l))&&(l=ee.join(Us,`${r}.context`));let d=null;if(At(l))try{d=await $o(l,"utf-8")}catch{}const u=iC(i),h=d?["no,","no ","that's not","wrong","incorrect","actually,","actually ","i meant","i mean","not what i","stop","wait","don't do","shouldn't","try again","that broke","that failed","error","bug"].some(x=>d.toLowerCase().includes(x)):!1,m=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",f=r.slice(0,8)+m,y=ee.join(oC,f);await Fm(y,{recursive:!0}),await Or(ee.join(y,"agent-log.jsonl"),i),d&&await Or(ee.join(y,"context.md"),d),await Or(ee.join(y,"rule-changes.json"),JSON.stringify(u,null,2)),await Or(ee.join(y,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:h,ruleChangeCount:u.length},null,2));const g=ee.relative(process.cwd(),y);return console.log(`[api.save-fixture] Saved fixture to ${g}`),Response.json({success:!0,fixturePath:g})}catch(t){return console.error("[api.save-fixture] Error:",t),Response.json({error:"Failed to save fixture",details:t instanceof Error?t.message:String(t)},{status:500})}}const cC=Object.freeze(Object.defineProperty({__proto__:null,action:lC},Symbol.toStringTag,{value:"Module"}));async function dC({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=Ce();if(!r)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const s=ee.join(r,".codeyam","captures","screenshots",t);try{await Te.access(s);const a=await Te.readFile(s),o=ee.extname(s).toLowerCase(),i=o===".png"?"image/png":o===".jpg"||o===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(a,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const uC=Object.freeze(Object.defineProperty({__proto__:null,loader:dC},Symbol.toStringTag,{value:"Module"})),zc={visual:{label:"VISUAL",bgColor:"#f9f9f9",textColor:"#9040f5"},library:{label:"LIBRARY",bgColor:"#f9f9f9",textColor:"#06b6d5"},type:{label:"TYPE",bgColor:"#ffe1e1",textColor:"#db2627"},other:{label:"OTHER",bgColor:"#f9f9f9",textColor:"#646464"}};function Gi({type:e,className:t=""}){const r=zc[e]||zc.other;return n("div",{className:`inline-flex items-center justify-center px-[4px] rounded-[4px] ${t}`,style:{backgroundColor:r.bgColor,color:r.textColor,height:"15px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-semibold leading-[15px] uppercase",children:r.label})})}const pC={analyzer:{bgColor:"#e1e1e1",textColor:"#3e3e3e",borderColor:"#e1e1e1"},capture:{bgColor:"#e1e1e1",textColor:"#3e3e3e",borderColor:"#e1e1e1"},running:{bgColor:"#e8ffe6",textColor:"#00925d",borderColor:"#c3f3bf"},error:{bgColor:"#fee2e2",textColor:"#991b1b",borderColor:"#fecaca"}};function Ms({variant:e,pid:t,label:r,className:s=""}){const a=pC[e],o=r||(e==="analyzer"&&t?`Analyzer: ${t}`:e==="capture"&&t?`Capture: ${t}`:e==="running"?"Running":e==="error"?"Error":"");return n("div",{className:`inline-flex items-center justify-center px-[8px] rounded-[4px] ${s}`,style:{backgroundColor:a.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:a.borderColor,height:"20px"},children:n("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:a.textColor},children:o})})}let Yc=!1;function hC(){if(Yc)return;const e=document.createElement("style");e.textContent=`
482
+ @keyframes strongPulse {
483
+ 0%, 100% { opacity: 0.2; }
484
+ 50% { opacity: 1; }
485
+ }
486
+ `,document.head.appendChild(e),Yc=!0}function qi({size:e="medium",className:t=""}){typeof document<"u"&&hC();const r={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:s,centerDotSize:a,gap:o}=r[e];return c("div",{className:`flex items-center justify-center ${t}`,style:{gap:`${o}px`},role:"status","aria-label":"Loading",children:[n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),n("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),n("div",{className:"rounded-full",style:{width:`${s}px`,height:`${s}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}const mC=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function fC({request:e,context:t,params:r}){var Y,P,O,S,$,I,K,q;let s=t.analysisQueue;s||(s=await nn());const a=new URL(e.url),o=parseInt(a.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!s)return ue({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:o,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:l,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=s.getState(),u=await ze();let p=null;if(u&&((Y=d==null?void 0:d.currentlyExecuting)!=null&&Y.commitSha)){const{project:J,branch:z}=await Ie(u),B=await ta({projectId:J.id,branchId:z.id,shas:[d.currentlyExecuting.commitSha]});p=B&&B.length>0?B[0]:null}else p=await fr();const h=async J=>{const z=await Ln(J);if(!z)return null;const{getAnalysesForEntity:B}=await Promise.resolve().then(()=>s0),H=await B(J,!1);return{...z,analyses:H||[]}},m=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async J=>{const z=[];if(J.entityShas&&J.entityShas.length>0){const B=J.entityShas.map(re=>h(re)),H=await Promise.all(B);z.push(...H.filter(re=>re!==null))}return{...J,entities:z}}));let f=null;if(d!=null&&d.currentlyExecuting){const J=d.currentlyExecuting,z=[];if(J.entityShas&&J.entityShas.length>0){const B=J.entityShas.map(re=>h(re)),H=await Promise.all(B);z.push(...H.filter(re=>re!==null))}f={...J,entities:z}}const y=f?m.filter(J=>J.id!==f.id):m,g=((O=(P=p==null?void 0:p.metadata)==null?void 0:P.currentRun)==null?void 0:O.currentEntityShas)||[],b=(await Promise.all(g.map(J=>h(J)))).filter(J=>J!==null),v=[];if(u)try{const{project:J,branch:z}=await Ie(u),B=await ta({projectId:J.id,branchId:z.id,limit:100});for(const H of B){const re=((S=H.metadata)==null?void 0:S.historicalRuns)||[];v.push(...re)}}catch(J){console.error("[activity.tsx] Failed to load historical runs from commits:",J)}const N=[...v].sort((J,z)=>{const B=J.lastCaptureAt||J.analysisCompletedAt||J.archivedAt||J.createdAt||"";return(z.lastCaptureAt||z.analysisCompletedAt||z.archivedAt||z.createdAt||"").localeCompare(B)}),w=(o-1)*i,C=w+i,k=N.slice(w,C),j=Math.ceil(N.length/i),A=await Promise.all(k.map(async J=>{const z=J.currentEntityShas||[];if(z.length===0)return{...J,entities:[]};const B=await Promise.all(z.map(H=>h(H)));return{...J,entities:B.filter(H=>H!==null)}})),_=!!f,M=y.length,T=N.filter(J=>{const z=!!J.failedAt,B=J.readyToBeCaptured,H=J.capturesCompleted??0,re=B===void 0?!0:B===0||H>=B;return!z&&!!J.analysisCompletedAt&&re}),D=new Set((($=f==null?void 0:f.entities)==null?void 0:$.map(J=>J.sha))||[]),R=T.filter(J=>!(J.currentEntityShas||[]).some(B=>D.has(B))),U=(await Promise.all(R.slice(0,3).map(async J=>{const z=J.currentEntityShas||[];if(z.length===0)return{run:J,entities:[]};const B=await Promise.all(z.map(H=>h(H)));return{run:J,entities:B.filter(H=>H!==null)}}))).flatMap(({run:J,entities:z})=>z.map(B=>({...B,runId:J.id,completedAt:J.lastCaptureAt||J.analysisCompletedAt||J.archivedAt||J.createdAt})));let W=[],V=null,F=null;if((K=(I=p==null?void 0:p.metadata)==null?void 0:I.currentRun)!=null&&K.analysisCompletedAt&&b.length>0){const J=b[0].sha;V=b[0];const z=await xa(J);z&&z.length>0&&z[0].scenarios&&(W=z[0].scenarios,F=z[0].status)}return ue({state:{...d,jobs:y,currentlyExecuting:f},currentRun:(q=p==null?void 0:p.metadata)==null?void 0:q.currentRun,historicalRuns:A,totalHistoricalRuns:N.length,currentPage:o,totalPages:j,projectSlug:u,commitSha:p==null?void 0:p.sha,queueJobs:y,currentlyExecuting:f,currentEntities:b,tab:l,hasCurrentActivity:_,queuedCount:M,recentCompletedEntities:U,hasMoreCompletedRuns:R.length>3,currentEntityScenarios:W,currentEntityForScenarios:V,currentAnalysisStatus:F})}function gC({activeTab:e,hasCurrentActivity:t,queuedCount:r,historicCount:s}){const a=[{id:"current",label:"Current Activity",hasContent:t,count:t?1:null},{id:"queued",label:"Queued Activity",hasContent:r>0,count:r},{id:"historic",label:"Historic Activity",hasContent:s>0,count:s}];return n("div",{className:"border-b border-gray-200 mb-6",children:n("nav",{className:"flex gap-8",children:a.map(o=>{const i=e===o.id;return n(Ee,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
487
+ relative pb-4 px-2 text-sm transition-colors cursor-pointer
488
+ ${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
489
+ `,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:c("span",{className:"flex items-center gap-2",children:[o.label,o.count!==null&&o.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${i?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:o.count}),o.count===null&&o.hasContent&&n("span",{className:`
490
+ inline-block w-2 h-2 rounded-full
491
+ ${i?"":"bg-gray-400"}
492
+ `,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function yC({currentlyExecuting:e,currentRun:t,state:r,projectSlug:s,commitSha:a,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:d,currentEntityForScenarios:u,currentAnalysisStatus:p}){var L,U,W,V;const[h,m]=E({}),[f,y]=E({isKilling:!1,current:0,total:0}),g=Ut(),x=!!e,b=(e==null?void 0:e.entities)||[],v=!!(t!=null&&t.analysisCompletedAt),N=v&&!!(t!=null&&t.capturePid),w=!v,C=x,k=d||[],{lastLine:j}=Xt(s,C);se(()=>{if(!t)return;const F=[t.analyzerPid,t.capturePid].filter(S=>!!S);if(F.length===0)return;let Y=!0;const P=async()=>{try{const $=await(await fetch(`/api/process-status?pids=${F.join(",")}`)).json();if($.processes&&Y){const I={};$.processes.forEach(K=>{I[K.pid]={isRunning:K.isRunning,processName:K.processName}}),m(I)}}catch(S){Y&&console.error("Failed to fetch process statuses:",S)}};P();const O=setInterval(()=>void P(),5e3);return()=>{Y=!1,clearInterval(O)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[A,_]=E(!1),[M,T]=E(!1);se(()=>{b.length<=3&&A&&_(!1)},[b.length,A]),se(()=>{i.length<=3&&M&&T(!1)},[i.length,M]);const D=A?b:b.slice(0,3),R=b.length>3;return c("div",{className:"flex flex-col gap-[45px]",children:[C?c("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[c("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(Ot,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:N?"Capturing...":"Analyzing..."})]}),D.map(F=>c("div",{className:"bg-white border border-[#e1e1e1] rounded-[4px] mb-[15px]",style:{height:"60px",padding:"0 15px",display:"flex",alignItems:"center",justifyContent:"space-between",boxShadow:"0 1px 3px 0 rgb(0 0 0 / 0.1)"},children:[c("div",{className:"flex items-center gap-3",children:[n("div",{children:n(St,{type:F.entityType||"other",size:"large"})}),c("div",{className:"flex flex-col gap-[1px]",children:[c("div",{className:"flex items-center gap-[14px]",children:[n(Ee,{to:`/entity/${F.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:F.name}),F.entityType&&n(Gi,{type:F.entityType})]}),n("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:F.filePath,children:F.filePath})]})]}),n("button",{onClick:o,className:"px-[10px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},children:"View Logs"})]},F.sha)),R&&!A&&c("button",{onClick:()=>_(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",b.length-3," more"," ",b.length-3===1?"entity":"entities"]}),A&&R&&n("button",{onClick:()=>_(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"}),N&&k&&k.length>0&&u&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:k.map(F=>{var K,q,J,z;if(!F.id)return null;const Y=(q=(K=F.metadata)==null?void 0:K.screenshotPaths)==null?void 0:q[0],P=(J=F.metadata)==null?void 0:J.noScreenshotSaved,O=Y&&!P,S=(z=p==null?void 0:p.scenarios)==null?void 0:z.find(B=>B.name===F.name),I=S&&S.screenshotStartedAt&&!S.screenshotFinishedAt||!O&&!P;return n(Ee,{to:`/entity/${u.sha}/scenarios/${F.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:I?"#f9f9f9":void 0,borderColor:I?"#efefef":"#ccc"},children:O?n(ut,{screenshotPath:Y,alt:F.name,className:"w-full h-full object-contain bg-gray-100"}):I?n("div",{className:"w-full h-full flex items-center justify-center",children:n(qi,{size:"medium"})}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},F.id)})}),j&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:j}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-2",children:[c("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(Ms,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(w||((L=h[t.analyzerPid])==null?void 0:L.isRunning))&&n(Ms,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(Ms,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(N||((U=h[t.capturePid])==null?void 0:U.isRunning))&&n(Ms,{variant:"running"})]}),(((W=h[t==null?void 0:t.analyzerPid])==null?void 0:W.isRunning)||((V=h[t==null?void 0:t.capturePid])==null?void 0:V.isRunning))&&n("button",{onClick:()=>{const F=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(O=>{var S;return!!O&&((S=h[O])==null?void 0:S.isRunning)});if(F.length===0)return;const Y=F.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${Y})?`))return;y({isKilling:!0,current:1,total:F.length}),(async()=>{for(let O=0;O<F.length;O++){const S=F[O];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:S,commitSha:a||""})})}catch($){console.error(`Failed to kill process ${S}:`,$)}O<F.length-1&&y({isKilling:!0,current:O+2,total:F.length})}y({isKilling:!1,current:0,total:0}),g.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):c("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[c("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(Od,{size:24,style:{color:"#005C75"}})}),c("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),c("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",n(Ee,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(Ee,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),c(Ee,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]}),i&&i.length>0&&c("div",{children:[n("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),c("div",{className:"flex flex-col gap-4",children:[(M?i:i.slice(0,3)).map(F=>{var O;const Y=(O=F.analyses)==null?void 0:O[0],P=(Y==null?void 0:Y.scenarios)||[];return Y==null||Y.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:c("div",{className:"flex flex-col gap-[15px]",children:[c("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(St,{type:F.entityType||"other",size:"large"})}),c("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[c("div",{className:"flex items-center gap-[5px]",children:[n(Ee,{to:`/entity/${F.sha}`,className:"hover:underline cursor-pointer",title:F.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:F.name}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:"#e8ffe6",color:"#00925d",fontSize:"12px",lineHeight:"16px",fontWeight:400},children:F.isUncommitted?"Modified":"Up to date"})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:F.filePath,children:F.filePath})]}),n("div",{className:"flex-1"}),n("div",{className:"flex-shrink-0",children:n("button",{onClick:o,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:S=>{S.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:S=>{S.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),P.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:P.map(S=>{var q,J,z;if(!S.id)return null;const $=(J=(q=S.metadata)==null?void 0:q.screenshotPaths)==null?void 0:J[0],I=(z=S.metadata)==null?void 0:z.noScreenshotSaved,K=$&&!I;return c("div",{className:"shrink-0 flex flex-col gap-2",children:[n(Ee,{to:`/entity/${F.sha}/scenarios/${S.id}`,className:"block cursor-pointer",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:K?"#f3f4f6":"#FAFAFA",borderColor:K?"#d1d5db":"#BCCDD3",borderStyle:K?"solid":"dashed"},onMouseEnter:B=>{K&&(B.currentTarget.style.borderColor="#005C75",B.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:B=>{B.currentTarget.style.borderColor=K?"#d1d5db":"#BCCDD3",B.currentTarget.style.boxShadow="none"},children:K?n(ut,{screenshotPath:$,alt:S.name,className:"max-w-full max-h-full object-contain"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})})}),n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.name})]},S.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},F.sha)}),i.length>3&&!M&&c("button",{onClick:()=>T(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",i.length-3," more"," ",i.length-3===1?"entity":"entities"]}),M&&i.length>3&&n("button",{onClick:()=>T(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})]})}function xC({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return c("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[c("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(hm,{size:24,style:{color:"#005C75"}})}),c("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),c(Ee,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[s,a]=E(null),[o,i]=E(null),[l,d]=E(null),[u,p]=E(!1),[h,m]=E(!1),[f,y]=E(new Set),g=Ut();se(()=>{e.length<=3&&h&&m(!1)},[e.length,h]);const x=k=>{a(k)},b=(k,j)=>{k.preventDefault(),i(j)},v=async(k,j)=>{if(k.preventDefault(),!s){i(null);return}const A=e.findIndex(T=>T.id===s);if(A===-1){a(null),i(null);return}if(A===j){a(null),i(null);return}const _=A<j?"down":"up",M=Math.abs(j-A);p(!0);try{for(let T=0;T<M;T++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:s,direction:_})});g.revalidate()}catch(T){console.error("Failed to reorder job:",T)}finally{p(!1),a(null),i(null)}},N=()=>{u||(a(null),i(null))},w=async k=>{if(confirm("Are you sure you want to cancel this job?"))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"remove",jobId:k})}),window.location.reload()}catch(j){console.error("Failed to cancel job:",j)}},C=async()=>{if(confirm(`Are you sure you want to cancel all ${e.length} queued jobs?`))try{await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}),window.location.reload()}catch(k){console.error("Failed to cancel jobs:",k)}};return c("div",{children:[c("div",{className:"flex items-center justify-between mb-4",children:[c("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&n("button",{onClick:()=>void C(),className:"px-[10px] py-0 rounded transition-colors cursor-pointer hover:bg-red-300",style:{backgroundColor:"#ffdcd9",color:"#ef4444",fontSize:"12px",fontWeight:500,height:"29px"},children:"Cancel All"})]}),c("div",{className:"flex flex-col gap-3",children:[(h?e:e.slice(0,3)).map(k=>{var R,L,U,W;const j=e.findIndex(V=>V.id===k.id),A=l===j,_=s===k.id,M=o===j,T=f.has(k.id),D=((R=k.entities)==null?void 0:R.length)>0?T?k.entities:k.entities.slice(0,3):[];return c("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:_||u?.5:1,transform:M&&s!==null&&!_?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:u?"not-allowed":_?"grabbing":"grab"},onMouseEnter:()=>d(j),onMouseLeave:()=>d(null),draggable:!u,onDragStart:V=>{x(k.id),V.dataTransfer.effectAllowed="move"},onDragOver:V=>b(V,j),onDrop:V=>void v(V,j),onDragEnd:N,children:[c("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(mm,{size:16,style:{color:"#005C75"}}),c("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",j+1]})]}),c("div",{className:"flex flex-col gap-2 mt-8",children:[D.length>0?c(we,{children:[D.map(V=>n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(St,{type:V.entityType||"other",size:"large"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(Ee,{to:`/entity/${V.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:V.name}),V.entityType&&n(Gi,{type:V.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:V.filePath})]})]})})},V.sha)),((L=k.entities)==null?void 0:L.length)>3&&n("button",{onClick:()=>{y(V=>{const F=new Set(V);return F.has(k.id)?F.delete(k.id):F.add(k.id),F})},className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"40px",fontSize:"12px",color:"#646464",fontWeight:500},children:T?"Show less":`+${k.entities.length-3} more ${k.entities.length-3===1?"entity":"entities"}`})]}):n("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:n("div",{className:"flex items-center justify-between h-full px-[15px]",children:c("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(Qs,{size:18,style:{color:"#8e8e8e"}})}),c("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((U=k.entityNames)==null?void 0:U[0])||(k.type==="analysis"?"Analysis Job":k.type==="recapture"?"Recapture Job":k.type==="debug-setup"?"Debug Setup":k.type.charAt(0).toUpperCase()+k.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((W=k.filePaths)==null?void 0:W[0])||(k.filePaths&&k.filePaths.length>1?`${k.filePaths.length} files`:k.entityShas&&k.entityShas.length>0?`${k.entityShas.length} ${k.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),c("div",{className:"flex items-center justify-end gap-2 mt-1",children:[A&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(fm,{size:20})}),n("button",{onClick:()=>void w(k.id),className:"transition-colors cursor-pointer hover:bg-red-100 rounded flex items-center justify-center",style:{fontSize:"10px",fontWeight:600,lineHeight:"22px",color:"#ef4444",backgroundColor:"#fef6f6",padding:"0 10px",height:"22px"},children:"Cancel"})]})]})]},k.id)}),e.length>3&&!h&&c("button",{onClick:()=>m(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",e.length-3," more"," ",e.length-3===1?"job":"jobs"]}),h&&e.length>3&&n("button",{onClick:()=>m(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})]})}function bC({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:s,tab:a,onShowLogs:o}){if(t===0)return c("div",{className:"border border-dashed border-[#BCCDD3] rounded-xl p-6 flex items-center justify-between",style:{backgroundColor:"#EDEFF0",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.03) 1px, transparent 1px)",backgroundSize:"20px 20px",borderWidth:"1px",borderStyle:"dashed"},children:[c("div",{className:"flex items-center gap-4",children:[n("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:n(gm,{size:24,style:{color:"#005C75"}})}),c("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),n("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),c(Ee,{to:"/files",className:"px-4 py-2 bg-[#005C75] text-white rounded-lg text-sm font-medium hover:bg-[#004a5e] transition-colors flex items-center gap-2 whitespace-nowrap no-underline",children:[n("span",{children:"+"}),n("span",{children:"New Analysis"})]})]});const[i,l]=E(!1),d=[];e.forEach(p=>{p.entities&&p.entities.length>0&&p.entities.forEach(h=>{d.push({...h,runCreatedAt:p.createdAt})})});const u=i?d:d.slice(0,3);return c("div",{className:"flex flex-col gap-4",children:[u.map(p=>{var y;const h=(y=p.analyses)==null?void 0:y[0],m=(h==null?void 0:h.scenarios)||[],f=!p.isUncommitted;return c("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[c("div",{className:"flex items-start justify-between mb-3",children:[c("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(St,{type:p.entityType||"other",size:"large"})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(Ee,{to:`/entity/${p.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:p.name}),n("div",{className:"px-2 py-0.5 rounded",style:{backgroundColor:f?"#e8ffe6":"#fef3cd",color:f?"#00925d":"#a16207",fontSize:"12px",fontWeight:400},children:f?"Up to date":"Out of date"})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:p.filePath,children:p.filePath})]})]}),n("button",{onClick:o,className:"px-3 py-1 rounded transition-colors whitespace-nowrap cursor-pointer",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",fontWeight:600},children:"View Logs"})]}),m.length>0&&c("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[m.slice(0,8).map(g=>{var N,w,C;if(!g.id)return null;const x=(w=(N=g.metadata)==null?void 0:N.screenshotPaths)==null?void 0:w[0],b=(C=g.metadata)==null?void 0:C.noScreenshotSaved,v=x&&!b;return n(Ee,{to:`/entity/${p.sha}/scenarios/${g.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:v?"#ccc":"#BCCDD3",borderStyle:v?"solid":"dashed"},children:v?n(ut,{screenshotPath:x,alt:g.name,className:"w-full h-full object-cover bg-gray-100"}):n("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},g.id)}),m.length>8&&c("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",m.length-8," more"]})]})]},`${p.sha}-${p.runCreatedAt}`)}),d.length>3&&!i&&c("button",{onClick:()=>l(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",d.length-3," more"," ",d.length-3===1?"entity":"entities"]}),i&&d.length>3&&n("button",{onClick:()=>l(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"})]})}const vC=tt(function(){const t=lt(),r=Dd(),[s,a]=E(!1);Wt({source:"activity-page"});const o=r.tab||"current";return t?c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),n("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),n(gC,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(yC,{currentlyExecuting:t.currentlyExecuting,currentRun:t.currentRun,state:t.state,projectSlug:t.projectSlug,commitSha:t.commitSha,onShowLogs:()=>a(!0),recentCompletedEntities:t.recentCompletedEntities||[],hasMoreCompletedRuns:t.hasMoreCompletedRuns||!1,currentEntityScenarios:t.currentEntityScenarios||[],currentEntityForScenarios:t.currentEntityForScenarios,currentAnalysisStatus:t.currentAnalysisStatus}),o==="queued"&&n(xC,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(bC,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>a(!0)}),s&&t.projectSlug&&n(mn,{projectSlug:t.projectSlug,onClose:()=>a(!1)})]}):n("div",{className:"px-20 py-12",children:n("div",{className:"text-center",children:n("p",{className:"text-gray-600",children:"Loading..."})})})}),wC=Object.freeze(Object.defineProperty({__proto__:null,default:vC,loader:fC,meta:mC},Symbol.toStringTag,{value:"Module"}));async function Fp(e,t,r){var w,C;await We();const s=await tn({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${e} not found`);if(!s.commit)throw new Error(`Commit not found for analysis ${e}`);const a=Ce();if(!a)throw new Error("Project root not found");const o=G.join(a,".codeyam","config.json"),i=JSON.parse(Q.readFileSync(o,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const d=ts(l);try{Q.writeFileSync(d,"","utf8")}catch{}const{project:u}=await Ie(l),p=((w=u.metadata)==null?void 0:w.packageManager)||"npm",h=3112,m=zt(l),f=((C=u.metadata)==null?void 0:C.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const y=i.environmentVariables||[],g=yg({filePath:s.filePath,webapps:f,environmentVariables:y,port:h,packageManager:p});await mr(e,k=>{if(k&&(k.readyToBeCaptured=!0,k.scenarios))for(const j of k.scenarios)(!t||j.name===t)&&(delete j.screenshotStartedAt,delete j.screenshotFinishedAt,delete j.interactiveStartedAt,delete j.interactiveFinishedAt,delete j.error,delete j.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:s.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),b=g.startCommand,v={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:m}]},{heading:"What's Happening",items:[{content:"1. Preparing analyzer and dependencies"},{content:"2. Syncing project files"},{content:"3. Setting up mock environment"}]},{heading:"Next Steps (Once Complete)",items:[{label:"1. Open the project directory",content:`code ${m}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:b,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${h}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:m,projectSlug:l,port:h,packageManager:p,framework:g.framework,instructions:v}}async function NC({request:e,context:t}){const r=new URL(e.url),s=r.searchParams.get("analysisId"),a=r.searchParams.get("scenarioId")||void 0;if(!s)return ue({error:"Missing analysisId parameter",usage:"GET /api/debug-setup?analysisId=<uuid>&scenarioId=<uuid>",example:'curl "http://localhost:3111/api/debug-setup?analysisId=f35509cb-b8f1-4d86-998e-fc24201ae2c7"'},{status:400});let o=t.analysisQueue;if(o||(o=await nn()),!o)return ue({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:s,scenarioId:a});try{const i=await Fp(s,a,o);return ue({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),ue({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function SC({request:e,context:t}){if(e.method!=="POST")return ue({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await nn()),!r)return ue({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a)return ue({error:"Missing required field: analysisId"},{status:400});const i=await Fp(a,o,r);return ue({...i,success:!0,message:"Debug setup queued"})}catch(s){console.error("[Debug Setup API] Error during debug setup:",s);const a=s instanceof Error?s.message:String(s),o=s instanceof Error?s.stack:void 0;return console.error("[Debug Setup API] Error stack:",o),ue({error:"Failed to setup debug environment",details:a},{status:500})}}const CC=Object.freeze(Object.defineProperty({__proto__:null,action:SC,loader:NC},Symbol.toStringTag,{value:"Module"}));function kC({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return new Response("Missing path parameter",{status:400});const s=Ce()||process.cwd(),a=G.resolve(s,r);if(!a.startsWith(s+G.sep)&&a!==s)return new Response("Path outside project root",{status:403});try{const o=Q.readFileSync(a,"utf8");return new Response(o,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch{return new Response("File not found",{status:404})}}const jC=Object.freeze(Object.defineProperty({__proto__:null,loader:kC},Symbol.toStringTag,{value:"Module"})),_C=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function Dp(e){const t=Im("sha256",_C);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function EC(e,t){return t===Dp(e)}async function PC({request:e}){if(e.method!=="POST")return ue({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return ue({success:!1,error:"Unlock code is required"},{status:400});const s=await ze();return s?EC(s,r)?(await ir({projectSlug:s,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),ue({success:!0})):ue({success:!1,error:"Invalid unlock code"},{status:400}):ue({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),ue({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const AC=Object.freeze(Object.defineProperty({__proto__:null,action:PC},Symbol.toStringTag,{value:"Module"}));async function TC({request:e,context:t}){if(e.method!=="POST")return ue({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await nn()),!r)return ue({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("defaultWidth");if(!a||!o)return ue({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return ue({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${a} with width ${i}`);const l=await UN(a,i,r);return console.log("[API] Recapture queued",l),ue({success:!0,message:"Recapture queued",...l})}catch(s){return console.log("[API] Error during recapture:",s),ue({error:"Failed to recapture screenshots",details:s instanceof Error?s.message:String(s)},{status:500})}}const MC=Object.freeze(Object.defineProperty({__proto__:null,action:TC},Symbol.toStringTag,{value:"Module"}));function $C(e){if(e.length===0)throw new Error("paths array must not be empty");return e.map(FC).map(a=>a===""?[]:a.split("/")).reduce((a,o)=>{const i=[];for(let l=0;l<Math.min(a.length,o.length)&&a[l]===o[l];l++)i.push(a[l]);return i}).join("/")}function FC(e){const r=e.replace(/\/+$/,"").split("/");for(;r.length>0;){const s=r[r.length-1];if(DC(s))r.pop();else break}return r.join("/")}function DC(e){return!!(e.includes("*")||/\.\w+$/.test(e))}function RC({request:e}){const r=new URL(e.url).searchParams.getAll("paths");if(r.length===0)return Response.json({error:"Missing required query parameter: paths"},{status:400});const s=$C(r),a=s?`.claude/rules/${s}/`:".claude/rules/";return Response.json({result:a})}const IC=Object.freeze(Object.defineProperty({__proto__:null,loader:RC},Symbol.toStringTag,{value:"Module"}));function OC(e,t){var i,l,d,u,p;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,s=e.analyses&&e.analyses.length>0&&e.analyses.some(h=>h.scenarios&&h.scenarios.length>0);if(!r){const h=!!((l=e.metadata)!=null&&l.previousVersionWithAnalyses),m=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return h||m?s?{state:"committed_no_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Committed - Simulations Outdated",color:"text-orange-700",bgColor:"bg-orange-50",borderColor:"border-orange-300",icon:"⚠"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Yet Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}:s?{state:"committed_with_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up to date",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"✓"}}:{state:"committed_no_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}const a=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((u=e.metadata)!=null&&u.previousVersionWithAnalyses)||a){const h=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((p=e.metadata)==null?void 0:p.previousVersionWithAnalyses);return s&&!h?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:s?{state:"uncommitted_outdated_simulations",hasSimulations:!0,hasOutdatedSimulations:!0,canGenerateSimulations:!0,badge:{label:"Edited - Simulations Outdated",color:"text-amber-700",bgColor:"bg-amber-50",borderColor:"border-amber-300",icon:"⚠"}}:{state:"uncommitted_outdated_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"Not Analyzed",color:"text-gray-600",bgColor:"bg-gray-50",borderColor:"border-gray-200",icon:"○"}}}else return s?{state:"uncommitted_with_new_simulations",hasSimulations:!0,hasOutdatedSimulations:!1,canGenerateSimulations:!1,badge:{label:"Up-to-date Simulations",color:"text-green-700",bgColor:"bg-green-50",borderColor:"border-green-200",icon:"●"}}:{state:"uncommitted_no_previous_simulations",hasSimulations:!1,hasOutdatedSimulations:!1,canGenerateSimulations:!0,badge:{label:"New",color:"text-purple-700",bgColor:"bg-purple-50",borderColor:"border-purple-200",icon:"+"}}}function LC(e){return OC(e).hasOutdatedSimulations}function La(e,t,r,s,a){var V,F,Y,P,O,S,$,I;const o=(V=t==null?void 0:t.scenarios)==null?void 0:V.find(K=>K.name===e.name),i=!!(o!=null&&o.startedAt),l=!!(o!=null&&o.screenshotStartedAt),d=!!(o!=null&&o.screenshotFinishedAt),u=!!(o!=null&&o.finishedAt),p=1800*1e3,h=l&&!d&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>p,m=!!((Y=(F=e.metadata)==null?void 0:F.screenshotPaths)!=null&&Y[0])||!!((P=e.metadata)!=null&&P.executionResult),f=l&&!d,y=o==null?void 0:o.error,g=(S=(O=e.metadata)==null?void 0:O.executionResult)==null?void 0:S.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const K of t.errors)x.push({source:`${K.phase} phase`,message:K.message});if(t!=null&&t.steps)for(const K of t.steps)K.error&&x.push({source:K.name,message:K.error});const b=!m&&!y&&!g&&x.length>0,v=!!(y||g||h||b),N=h?"Capture timed out after 30 minutes":(typeof y=="string"?y:null)||(g==null?void 0:g.message)||(b?`Analysis error: ${x[0].message}`:null),w=h?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(o==null?void 0:o.errorStack)||(g==null?void 0:g.stack)||null,k=(s&&a?a.jobs.some(K=>{var q;return((q=K.entityShas)==null?void 0:q.includes(s))||K.type==="analysis"&&K.entityShas&&K.entityShas.length===0})||((I=($=a.currentlyExecuting)==null?void 0:$.entityShas)==null?void 0:I.includes(s)):!1)&&!i&&!v||!!(o!=null&&o.analyzing)&&!i&&!v,j=i&&!l&&!u&&!v,A=(k||j||f)&&!v,_=(k||j)&&r===!1&&!m;let M;_?M="crashed":v?M="error":m||u?M="completed":f?M="capturing":j?M="starting":k?M="queued":M="pending";let T="📷",D="pending",R=!1,L=`Not captured: ${e.name}`;const U="border-gray-300",W=v||_?"bg-red-50":"bg-white";return v||_?(T="⚠️",D="error",L=`Error: ${_?"Analysis process crashed":N||"Unknown error"}`):k?(T="⋯",D="queued",L=`Queued: ${e.name}`):j?(T="⋯",D="starting",R=!0,L=`Starting server for ${e.name}...`):f&&!v?(T="⋯",D="capturing",R=!0,L=`Capturing ${e.name}...`):m&&(T="✓",D="completed",L=e.name),{hasError:v||_,errorMessage:_?"Analysis process crashed":N,errorStack:_?"Process terminated unexpectedly before completing analysis":w,isCapturing:f,isCaptured:m,hasCrashed:_,isAnalyzing:A,isQueued:k,isServerStarting:j,status:M,icon:T,iconType:D,shouldSpin:R,title:L,borderColor:U,bgColor:W}}function Rp({scenario:e,entitySha:t,size:r="medium",showBorder:s=!0,isOutdated:a=!1}){var w,C,k,j,A,_;const o=La(e,void 0,void 0,t,void 0),i=(w=e.metadata)==null?void 0:w.executionResult,l=!!i,u=(((k=(C=e.metadata)==null?void 0:C.data)==null?void 0:k.argumentsData)||[]).length,p=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,h=((A=(j=i==null?void 0:i.sideEffects)==null?void 0:j.consoleOutput)==null?void 0:A.length)||0,m=((_=i==null?void 0:i.timing)==null?void 0:_.duration)||0;let f=0;u>0&&f++,u>2&&f++,p&&f++,h>0&&f++,f=Math.min(3,f);const y=r==="small"?{width:"w-[50px]",height:"h-[38px]",iconSize:"text-base",textSize:"text-[8px]"}:{width:"w-20",height:"h-15",iconSize:"text-xl",textSize:"text-[10px]"},x=o.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:l?a?{border:"border-amber-500",bg:"bg-amber-50",icon:"text-amber-700",badge:"bg-amber-100 text-amber-700"}:{border:"border-blue-400",bg:"bg-blue-50",icon:"text-blue-600",badge:"bg-blue-100 text-blue-700"}:{border:"border-gray-300 border-dashed",bg:"bg-gray-50",icon:"text-gray-400",badge:"bg-gray-100 text-gray-600"},b=s?`border-2 ${x.border}`:"",v=Array.from({length:3},(M,T)=>n("div",{className:`w-1 h-1 rounded-full ${T<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},T)),N=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:l?`${e.name}
493
+ ${u} args → ${p?"value":"void"}${h>0?` (${h} logs)`:""}
494
+ ${m}ms`:`Not executed: ${e.name}`;return c(Ee,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${y.width} ${y.height} ${b} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:N,onClick:M=>M.stopPropagation(),children:[n("div",{className:`${x.icon} ${y.iconSize} font-mono font-bold`,children:o.hasError?"⚠":l?"ƒ":"○"}),l&&!o.hasError&&c("div",{className:`flex items-center gap-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:u}),n("span",{children:"→"}),n("span",{children:p?"✓":"∅"})]}),l&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:v}),l&&!o.hasError&&m>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${x.badge} px-1 rounded`,children:m>1e3?`${Math.round(m/1e3)}s`:`${m}ms`}),l&&!o.hasError&&h>0&&r==="medium"&&c("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",h]})]})}function Zo({size:e=24,className:t=""}){return c("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:[n("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z",fill:"#ef4444",stroke:"none"}),n("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),n("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function Uc({scenario:e,entity:t,analysisStatus:r,queueState:s,processIsRunning:a,size:o="medium",cacheBuster:i,className:l="",viewMode:d}){var g,x;if(t.entityType==="library")return n(Rp,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const p=La(e,r,a,t.sha,s),h=o==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:o==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},m=`relative ${h.containerClass} ${l}`,f=()=>{const b=`/entity/${t.sha}/scenarios/${e.id}`;return d?`${b}/${d}`:b};if(p.isCaptured){const b=(x=(g=e.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return n(Ee,{to:f(),className:`${m} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(ut,{screenshotPath:b,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const y=()=>{const b={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},v=n(qi,{size:o});if(p.shouldSpin||p.iconType==="queued"||p.iconType==="pending")return v;switch(p.iconType){case"starting":case"capturing":return v;case"error":return c("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(Zo,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(ym,{...b});default:return v}};return n(Ee,{to:f(),className:`${m} ${p.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:p.title,children:n("div",{className:h.iconSize,children:y()})})}const nr=70;function BC({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:s,entitySha:a,cacheBuster:o,activeTab:i,entityType:l,entity:d,queueState:u,processIsRunning:p,isEntityAnalyzing:h,areScenariosStale:m,viewMode:f,setViewMode:y,isBreakdownView:g,onCreateScenario:x}){var L,U,W,V,F,Y;const b=be(null),[v,N]=E(new Set),[w,C]=E(!1);se(()=>{b.current&&i==="scenarios"&&b.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[s==null?void 0:s.id,i]);const k=P=>`/entity/${a}/scenarios/${P}`,j=P=>{N(O=>{const S=new Set(O);return S.has(P)?S.delete(P):S.add(P),S})},A=(P,O=2)=>{const $=P.split(`
495
+ `).slice(0,O).join(" ").trim();return $.length>nr?$.substring(0,nr-3):(P.split(`
496
+ `).length>O||P.length>$.length,$)},_=fe(()=>{var O;if(!((O=r==null?void 0:r.metadata)!=null&&O.executionFlows)||!(r!=null&&r.scenarios))return null;const P=r.scenarios.filter(S=>{var $;return!(($=S.metadata)!=null&&$.sameAsDefault)});return Yi(r.metadata.executionFlows,P)},[r]),M=(_==null?void 0:_.totalFlows)||0,T=(_==null?void 0:_.coveredFlows)||0,D=(_==null?void 0:_.coveragePercentage)||0;(L=d==null?void 0:d.metadata)!=null&&L.defaultWidth||(U=r==null?void 0:r.metadata)!=null&&U.defaultWidth;const R=(W=r==null?void 0:r.status)!=null&&W.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return c("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[r&&e.length>0&&c("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),c("div",{className:"grid grid-cols-2 gap-2",children:[c(Ee,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((V=e[0])==null?void 0:V.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[c("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(D),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),c(Ee,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((F=e[0])==null?void 0:F.id)}`:`/entity/${a}/scenarios/breakdown`,className:"bg-[#F6F9FC] border border-[#E0E9EC] rounded px-3 py-3 text-center no-underline cursor-pointer hover:bg-[#EDF4F8] transition-colors",children:[c("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[T,"/",M]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),c(Ee,{to:g?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((Y=e[0])==null?void 0:Y.id)}`:`/entity/${a}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${g?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[n("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),g?n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),d&&d.filePath&&n("div",{children:n("button",{onClick:x,className:"w-full px-3 py-2 bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[11px] font-medium font-mono cursor-pointer transition-colors hover:bg-[#004a5e] flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&c("div",{className:"py-3 flex items-center justify-between",children:[c("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),R&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:R})]}),h&&(m||e.length===0)?c("div",{className:"",children:[c("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[c("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}),n("p",{className:"text-[#8e8e8e] text-xs font-normal m-0 mt-2 text-left leading-5",children:"Scenarios will appear here once analysis completes"})]}):e.length===0?n("div",{className:"",children:n("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"flex flex-col gap-[11.6px]",children:e.map((P,O)=>{const S=!g&&(s==null?void 0:s.id)===P.id,$=v.has(P.id||"");return P.id?c(Ee,{to:k(P.id),ref:S?b:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${S?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n(Uc,{scenario:P,entity:{sha:a,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:u,processIsRunning:p,size:"large",cacheBuster:o,viewMode:f})}),c("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${$?"":"line-clamp-1"}`,children:P.name}),P.description&&n("div",{className:"mt-2",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[$?P.description:A(P.description),!$&&P.description.length>nr&&c(we,{children:["...",n("button",{onClick:I=>{I.preventDefault(),I.stopPropagation(),j(P.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),$&&P.description.length>nr&&n("button",{onClick:I=>{I.preventDefault(),I.stopPropagation(),j(P.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},O):null})})}),t.length>0&&!(h&&m)&&c("div",{className:"border-t border-[#e1e1e1] pt-3",children:[c("button",{onClick:()=>C(!w),className:"flex items-center gap-1 text-[10px] text-[#626262] font-medium cursor-pointer bg-transparent border-none p-0 hover:text-[#005c75] transition-colors w-full",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform ${w?"rotate-90":""}`,children:n("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"Hidden Scenarios (",t.length,")"]}),w&&c("div",{className:"mt-2",children:[n("p",{className:"text-[10px] text-[#8e8e8e] leading-[14px] mb-3",children:"These scenarios were hidden because the screenshots did not differ from the Default Scenario."}),n("div",{className:"flex flex-col gap-[11.6px]",children:t.map((P,O)=>{const S=!g&&(s==null?void 0:s.id)===P.id,$=v.has(P.id||"");return P.id?c(Ee,{to:`/entity/${a}/scenarios/${P.id}`,ref:S?b:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${S?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[n("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:n(Uc,{scenario:P,entity:{sha:a,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:u,processIsRunning:p,size:"large",cacheBuster:o,viewMode:f})}),c("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${$?"":"line-clamp-1"}`,children:P.name}),P.description&&n("div",{className:"mt-2",children:c("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[$?P.description:A(P.description),!$&&P.description.length>nr&&c(we,{children:["...",n("button",{onClick:I=>{I.preventDefault(),I.stopPropagation(),j(P.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),$&&P.description.length>nr&&n("button",{onClick:I=>{I.preventDefault(),I.stopPropagation(),j(P.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},O):null})})]})]})]})}function zC({scenario:e,entitySha:t,onApply:r,onSave:s,onEditMockData:a,onDelete:o,isApplying:i=!1,isSaving:l=!1,saveMessage:d=null,showDeleteConfirm:u=!1,onShowDeleteConfirm:p,isDeleting:h=!1,deleteError:m=null}){const[f,y]=E(""),g=async()=>{await r(f)},x=async b=>{await s(f,b),b||y("")};return c("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[c("div",{className:"border-b border-[#e1e1e1] pb-3",children:[c("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(Ee,{to:`/entity/${t}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),n("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),c("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[c("div",{className:"pt-1",children:[n("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),n("textarea",{id:"ai-description",value:f,onChange:b=>y(b.target.value),placeholder:"e.g. change amount of data to zero",className:"w-full px-[7px] py-[6px] border border-[#c7c7c7] rounded-[4px] text-xs focus:outline-none focus:ring-1 focus:ring-[#005c75] focus:border-[#005c75] resize-none",rows:4}),c("button",{onClick:()=>void g(),disabled:i||!f.trim(),className:"w-full mt-1 h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1",children:[i&&c("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[n("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),n("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),i?"Applying...":"Apply"]})]}),n("div",{className:"border-t border-[#e1e1e1] my-1"}),c("div",{className:"pt-1",children:[n("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),n("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),n("button",{onClick:a,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),d&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&n("div",{children:n(Ee,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),c("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[n("button",{onClick:()=>void x(!1),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center",children:l?"Saving...":"Save Scenario Data"}),n("button",{onClick:()=>void x(!0),disabled:l||!f.trim(),className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa] disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center",children:"Save As New"}),o&&c(we,{children:[u?c("div",{className:"flex flex-col gap-1",children:[c("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),c("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void o(),disabled:h,className:"flex-1 h-[22px] bg-red-600 text-white rounded text-[10px] font-normal hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors flex items-center justify-center cursor-pointer",children:h?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>p==null?void 0:p(!1),disabled:h,className:"flex-1 h-[22px] bg-gray-100 text-gray-700 border border-gray-300 rounded text-[10px] font-normal hover:bg-gray-200 disabled:opacity-50 transition-colors flex items-center justify-center cursor-pointer",children:"Cancel"})]})]}):n("button",{onClick:()=>p==null?void 0:p(!0),className:"w-full h-[22px] bg-red-50 text-red-600 border border-red-200 rounded text-[10px] font-normal hover:bg-red-100 transition-colors flex items-center justify-center cursor-pointer",children:"Delete Scenario"}),m&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:m})]})]})]})}function YC({scenario:e,analysis:t,entity:r}){var i,l,d;const s=((i=e.metadata)==null?void 0:i.executionResult)||null,a=((d=(l=e.metadata)==null?void 0:l.data)==null?void 0:d.argumentsData)||[],o=u=>{var y,g,x;if(!u)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const p=[],h=((y=u.sideEffects)==null?void 0:y.consoleOutput)||[];h.length>0&&(p.push(`Console Output: ${h.length} log ${h.length===1?"entry":"entries"} captured`),h.forEach(b=>{p.push(` [${b.level.toUpperCase()}] ${b.args.join(" ")}`)}));const m=((g=u.sideEffects)==null?void 0:g.fileWrites)||[];m.length>0&&(p.push(`
497
+ File System Operations: ${m.length} ${m.length===1?"operation":"operations"} detected`),m.forEach(b=>{p.push(` ${b.operation}: ${b.path}${b.size?` (${b.size} bytes)`:""}`)}));const f=((x=u.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(p.push(`
498
+ API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(b=>{p.push(` ${b.method} ${b.url}${b.status?` → ${b.status}`:""}${b.duration?` (${b.duration}ms)`:""}`)})),u.error&&p.push(`
499
+ Error: ${u.error.name||"Error"}: ${u.error.message}`),p.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":p.join(`
500
+ `)};return c("div",{className:"flex w-full h-full gap-0",children:[c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(a,null,2)})})]}),c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-0",children:s?n("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:s.returnValue!==void 0?JSON.stringify(s.returnValue,null,2):"undefined"}):n("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),c("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[n("div",{className:"px-4 pt-3.5 pb-2.5",children:n("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),n("div",{className:"flex-1 overflow-auto px-4 pb-4",children:n("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:o(s)})})]})]})}const Mn={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function $s({scenarioId:e,analysisId:t}){const[r,s]=E(!1),[a,o]=E(!1),[i,l]=E(null),[d,u]=E(!1),p=e||t;if(!p)return null;const h=`/codeyam-diagnose ${p}`,m=async()=>{o(!0);try{const{default:y}=await import("html2canvas-pro"),x=(await y(document.body,{scale:.5})).toDataURL("image/jpeg",.8);l(x),s(!0)}catch(y){console.error("Screenshot capture failed:",y),s(!0)}finally{o(!1)}},f=()=>{s(!1),l(null)};return c(we,{children:[c("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[n("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:Mn.heading},children:"Claude can help debug this error."}),n("p",{className:"m-0 mb-4 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"18px",color:Mn.subtext},children:"Simply run this command in Claude Code:"}),c("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:Mn.commandBoxBg,borderColor:Mn.commandBoxBorder,maxWidth:"505px",height:"35px",paddingLeft:"13px",paddingRight:"13px",paddingTop:"6px",paddingBottom:"6px"},children:[n("code",{className:"font-mono font-['IBM_Plex_Mono'] flex-1 text-left",style:{fontSize:"12px",lineHeight:"20px",color:Mn.commandBoxText},children:h}),n("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(h),u(!0),setTimeout(()=>u(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:d?"#22c55e":Mn.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?n($t,{size:14}):n(Bt,{size:14})})]}),c("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:"#005c75"},children:["If Claude is unable to address this issue or suggests reporting it,"," ",n("button",{onClick:()=>void m(),disabled:a,className:"underline cursor-pointer bg-transparent border-none p-0 font-normal hover:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed font-['IBM_Plex_Sans']",style:{fontSize:"12px",lineHeight:"15px",color:Mn.link},children:a?"capturing...":"please do so here"}),"."]})]}),n(Jd,{isOpen:r,onClose:f,context:{source:e?"scenario-page":"entity-page",entitySha:void 0,scenarioId:e,analysisId:t,currentUrl:typeof window<"u"?window.location.pathname:"/"},screenshotDataUrl:i??void 0})]})}const Wc=1440,Fs=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Gt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function Ip({selectedScenario:e,analysis:t,entity:r,viewMode:s,cacheBuster:a,hasScenarios:o,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:d=!0,processIsRunning:u,queueState:p}){var H,re,ae,X,oe,me,ve,je,te,ke,Z;const h=Ke(),[m,f]=E(!1),[y,g]=E(!1),[x,b]=E({name:"Desktop",width:Wc,height:900}),[v,N]=E(Wc),[w,C]=E(1),{customSizes:k,addCustomSize:j,removeCustomSize:A}=ja(l),_=fe(()=>[...Fs,...k],[k]),M=(pe,ie)=>{N(pe);const de=_.find(he=>he.width===pe&&he.height===ie);b({name:(de==null?void 0:de.name)||"Custom",width:pe,height:ie})},T=pe=>{N(pe.width),b({name:pe.name,width:pe.width,height:pe.height})},D=pe=>{j(pe,x.width,x.height??900),g(!1),b(ie=>({...ie,name:pe}))},R=(pe,ie)=>{N(pe);const de=_.find(he=>he.width===pe&&he.height===ie);b(he=>({name:(de==null?void 0:de.name)||"Custom",width:pe,height:he.height}))},L=(re=(H=e==null?void 0:e.metadata)==null?void 0:H.screenshotPaths)==null?void 0:re[0],U=fe(()=>e?La(e,t==null?void 0:t.status,u,r==null?void 0:r.sha,p):null,[e,t==null?void 0:t.status,u,r==null?void 0:r.sha,p]),W=fe(()=>{var ie,de;const pe=[];if((ie=t==null?void 0:t.status)!=null&&ie.errors&&t.status.errors.length>0)for(const he of t.status.errors)pe.push({source:`${he.phase} phase`,message:he.message,stack:he.stack});if((de=t==null?void 0:t.status)!=null&&de.steps)for(const he of t.status.steps)he.error&&pe.push({source:he.name,message:he.error,stack:he.errorStack});return pe},[(ae=t==null?void 0:t.status)==null?void 0:ae.errors,(X=t==null?void 0:t.status)==null?void 0:X.steps]),V=(U==null?void 0:U.errorMessage)||null,F=(U==null?void 0:U.errorStack)||null,{interactiveServerUrl:Y,isStarting:P,isLoading:O,showIframe:S,iframeKey:$,onIframeLoad:I}=Un({analysisId:t==null?void 0:t.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:l,enabled:s==="interactive"}),K=fe(()=>Y||null,[Y]),q=!i&&o&&e&&!((me=(oe=e.metadata)==null?void 0:oe.screenshotPaths)!=null&&me[0])&&((je=(ve=t==null?void 0:t.status)==null?void 0:ve.scenarios)==null?void 0:je.some(pe=>pe.name===e.name&&pe.screenshotStartedAt&&!pe.screenshotFinishedAt)),{lastLine:J}=Xt(l,i||s==="interactive"||q||!1);if(!e){if(i&&r)return c(we,{children:[n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:c("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[n("div",{className:"w-12 h-12 mb-2",children:n("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:n("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),n("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:q?"Capturing screenshots...":"Analyzing..."}),n("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:"This may take a few minutes."}),J&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:J}),l&&n("button",{onClick:()=>f(!0),className:"w-[148px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-sm text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] font-['IBM_Plex_Sans']",children:"View full logs"})]})}),m&&l&&n(mn,{projectSlug:l,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(W.length>0){const pe=W.length===1?((te=W[0])==null?void 0:te.message)||"An error occurred during analysis.":`${W.length} errors occurred during analysis.`;return c(we,{children:[n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:c("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:Gt.background,border:`2px solid ${Gt.border}`},role:"alert",children:c("div",{className:"flex items-center gap-3",children:[n(Zo,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:c("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:Gt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",pe," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:Gt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n($s,{analysisId:t==null?void 0:t.id})})]})}),m&&l&&n(mn,{projectSlug:l,onClose:()=>f(!1)})]})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:c("div",{className:"max-w-[600px]",children:[n("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),n("p",{className:"text-base font-normal text-[#3e3e3e] mb-8 leading-6 m-0",children:"Analyze the code to create simulations and create test scenarios automatically."}),r.filePath&&n("button",{onClick:()=>{h.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:h.state!=="idle",className:"h-[54px] w-[183px] px-2.5 py-[5px] bg-[#005c75] text-white border-none rounded-lg text-base font-medium cursor-pointer transition-all hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed",children:h.state!=="idle"?"Analyzing...":"Analyze"})]})})}return n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:n("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return c(we,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
501
+ linear-gradient(45deg, #ebebeb 25%, transparent 25%),
502
+ linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
503
+ linear-gradient(45deg, transparent 75%, #ebebeb 75%),
504
+ linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
505
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||q&&!L)&&!V&&s==="screenshot"?n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-linear-to-br from-blue-50 to-indigo-50",children:c("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[c("div",{className:"mb-8",children:[n("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:n("span",{className:"text-5xl animate-spin",children:"⚙️"})}),n("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:q?`Capturing ${r==null?void 0:r.name}`:`Analyzing ${r==null?void 0:r.name}`}),n("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:q?`Taking screenshots for ${((ke=t==null?void 0:t.scenarios)==null?void 0:ke.length)||0} scenario${((Z=t==null?void 0:t.scenarios)==null?void 0:Z.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&c("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),J&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:c("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),n("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:J,children:J})]})]})}),l&&n("button",{onClick:()=>f(!0),className:"px-6 py-3 bg-[#005c75] text-white border-none rounded-lg text-base font-semibold cursor-pointer transition-all hover:bg-[#004a5e] hover:shadow-lg",children:"📋 View Full Logs"}),n("p",{className:"text-xs text-gray-500 mt-8 m-0",children:"Screenshots will appear here as they are captured. This may take a few minutes."})]})}):s==="screenshot"&&(L||V)||s==="interactive"&&(K||P)||s==="data"?c(we,{children:[V&&!L&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:c("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:Gt.background,border:`2px solid ${Gt.border}`,maxHeight:"50vh"},role:"alert",children:c("div",{className:"flex flex-col gap-3",children:[c("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:Gt.text},children:[n(Zo,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),c("div",{className:"text-center",children:[n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:Gt.link},children:"See logs"})," ","for details."]}),n("div",{className:"flex-1 min-w-0",children:n("div",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:Gt.text},children:V})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n($s,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),s==="interactive"?c("div",{className:"flex-1 flex flex-col min-h-0",children:[K&&c("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[n(Ux,{presets:[...Fs],customSizes:k,currentWidth:x.width,currentHeight:x.height??900,scale:w,onSizeChange:M,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:A}),e&&r&&c(Ee,{to:`/entity/${r.sha}/scenarios/${e.id}/fullscreen?from=${encodeURIComponent(`/entity/${r.sha}/scenarios/${e.id}/interactive`)}`,className:"flex items-center gap-2 px-4 py-2 bg-[#005c75] text-white rounded hover:bg-[#004a5c] transition-colors text-sm font-medium no-underline",title:"Open in fullscreen",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:n("path",{d:"M2 5V2H5M11 2H14V5M14 11V14H11M5 14H2V11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Fullscreen"]})]}),K&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${Fs[Fs.length-1].width}px`,width:"100%"},children:n(Ni,{currentViewportWidth:v,currentPresetName:x.name,onDevicePresetClick:T,devicePresets:_})})}),n(Ra,{scenarioId:e.id,scenarioName:e.name,iframeUrl:K,isStarting:P,isLoading:O,showIframe:S,iframeKey:$,onIframeLoad:I,onScaleChange:C,onDimensionChange:R,projectSlug:l,defaultWidth:x.width,defaultHeight:x.height})]}):s==="data"?n("div",{className:"flex-1 min-h-0",children:n(YC,{scenario:e,analysis:t,entity:r})}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 p-6 flex items-center justify-center",children:n("div",{className:"transition-all duration-300",style:{maxWidth:`${v}px`},children:(L||!V)&&n(ut,{screenshotPath:L,cacheBuster:a,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):n("div",{className:"flex-1 flex flex-col",children:n("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!L?n("div",{className:"w-full h-full flex items-center justify-center",children:n("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),c("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),c("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",n("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),J&&c("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[n("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),n("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:J})]}),l&&n("button",{onClick:()=>f(!0),className:"mt-4 px-4 py-2 bg-[#005c75] text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-[#004a5e]",children:"📋 View Full Logs"})]})]})})}):V?c("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:c("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[c("div",{className:"flex items-start gap-4",children:[n("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),c("div",{className:"bg-white border border-blue-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-blue-900 m-0 mb-2 uppercase tracking-wide",children:"CodeYam requires an AI API key for reliable analysis."}),c("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[n("li",{children:"You can use API keys for a variety of models"}),n("li",{children:"Faster analysis processing"}),n("li",{children:"Better handling of complex code structures"}),n("li",{children:"Improved scenario generation quality"})]})]}),n(Ee,{to:"/settings",className:"inline-block px-4 py-2 bg-blue-600 text-white border-none rounded-md text-sm font-semibold cursor-pointer transition-colors hover:bg-blue-700",children:"🔐 Configure API Keys"})]})}),n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),n("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),c("div",{className:"bg-white border border-red-200 rounded p-4",children:[n("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),n("div",{className:"max-h-[300px] overflow-auto",children:n("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:V})})]}),F&&c("details",{className:"mt-4",children:[n("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),n("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:n("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:F})})]}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n($s,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):W.length>0?n("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:n("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:c("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),c("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:W,title:"Analysis Error",description:W.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${W.length} errors occurred during analysis. Screenshot capture was not completed.`}),n("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n($s,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):c("div",{className:"flex flex-col items-center gap-4 text-center",children:[n("span",{className:"text-6xl text-gray-300",children:"📷"}),n("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),n("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),m&&l&&n(mn,{projectSlug:l,onClose:()=>f(!1)}),y&&n(Si,{width:x.width,height:x.height??900,onSave:D,onCancel:()=>g(!1)})]})}function UC({analysis:e,entitySha:t,onCreateScenario:r}){Ut();const[s,a]=E(e);se(()=>{a(e)},[e]);const[o,i]=E(null),l=fe(()=>{var m;if(!((m=s==null?void 0:s.metadata)!=null&&m.executionFlows)||!(s!=null&&s.scenarios))return null;const h=s.scenarios.filter(f=>{var y;return!((y=f.metadata)!=null&&y.sameAsDefault)});return Yi(s.metadata.executionFlows,h)},[s]),d=fe(()=>l?Fb(l):[],[l]),u=fe(()=>s!=null&&s.scenarios?s.scenarios.filter(h=>{var m;return!((m=h.metadata)!=null&&m.sameAsDefault)}):[],[s]),p=h=>{var f;const m=((f=h.metadata)==null?void 0:f.coveredFlows)||[];return l?l.executionFlows.filter(y=>m.includes(y.id)):[]};return s?!l||l.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:c("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),n("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):n("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:c("div",{className:"p-6 space-y-6",children:[c("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),c("div",{className:"grid grid-cols-4 gap-4 text-center",children:[c("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:u.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:l.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[c("div",{className:"text-2xl font-bold text-gray-900",children:[l.coveredFlows,"/",l.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),c("div",{className:"bg-gray-50 rounded-lg p-3",children:[c("div",{className:`text-2xl font-bold ${l.coveragePercentage===100?"text-green-600":l.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[l.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),c("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:c("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",u.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:u.length===0?c("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n("button",{onClick:r,className:"text-blue-600 hover:underline bg-transparent border-none cursor-pointer p-0 text-sm",children:"Create one"})]}):u.map(h=>{var y,g,x;const m=(g=(y=h.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0],f=p(h);return c("div",{className:"p-4 flex gap-4",children:[n("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:n(ut,{screenshotPath:m,alt:h.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),c("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:c("div",{children:[n(Ee,{to:`/entity/${t}/scenarios/${h.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:h.name}),((x=h.metadata)==null?void 0:x.error)&&n("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),n("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:h.description}),f.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:f.map(b=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${b.isError?"bg-red-50 text-red-700":b.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:b.name},b.id))})]})]},h.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:c("button",{onClick:r,className:"w-full px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 flex items-center justify-center gap-2 border-none cursor-pointer",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),d.length>0&&c("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[c("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[d.length," uncovered execution flow",d.length>1?"s":""," — consider adding scenarios to cover these"]}),c("div",{className:"flex flex-wrap gap-1",children:[d.slice(0,10).map(h=>c("span",{className:`text-xs px-2 py-0.5 rounded ${h.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[h.name,h.impact==="high"&&" (high impact)"]},h.id)),d.length>10&&c("span",{className:"text-xs text-amber-600",children:["+",d.length-10," more"]})]})]}),c("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[n("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:c("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",l.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:l.executionFlows.map(h=>{const m=o===h.id,f=h.usedInScenarios.length>0;return c("div",{children:[n("button",{onClick:()=>i(m?null:h.id),className:"w-full px-4 py-3 flex items-start justify-between text-left bg-transparent border-none cursor-pointer hover:bg-gray-50",children:c("div",{className:"flex items-start gap-3 flex-1",children:[n("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:m?"▼":"▶"}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:h.name}),f?n("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):n("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),h.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),h.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),h.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),h.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:h.description})]})]})}),m&&c("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[h.requiredValues.length>0&&c("div",{className:"mb-4",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),n("div",{className:"space-y-1",children:h.requiredValues.map((y,g)=>c("div",{className:"flex items-center gap-2 text-xs",children:[n("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:y.attributePath}),n("span",{className:"text-gray-400",children:y.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:y.value})]},g))})]}),f&&c("div",{children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),n("div",{className:"flex flex-wrap gap-1",children:h.usedInScenarios.map(y=>n("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:y.name},y.id))})]}),h.codeSnippet&&c("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[n("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),n("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:n("code",{children:h.codeSnippet})})]})]})]},h.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:c("div",{className:"text-center text-gray-500",children:[n("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),n("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function Jc({hasIndirectBadge:e,onAnalyze:t}){return c(we,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-end gap-2",children:[e&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:"0 scenarios"})]})}),c("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[n("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),n("button",{className:"px-[15px] py-0 h-[23px] bg-[#005c75] text-white rounded text-xs font-medium leading-5 border-none cursor-pointer hover:bg-[#004a5e] transition-colors flex items-center justify-center",onClick:t,children:"Analyze"})]})]})}function WC({entity:e,history:t}){const[r,s]=E("entity"),[a,o]=E(new Set),i=t.filter(p=>p.analyses.length>0).length,l=fe(()=>{const p=new Map;return t.forEach(h=>{h.analyses.forEach(m=>{(m.scenarios??[]).filter(y=>{var g;return!((g=y.metadata)!=null&&g.sameAsDefault)}).forEach(y=>{p.has(y.name)||p.set(y.name,[]),p.get(y.name).push({version:h,analysis:m,scenario:y})})})}),Array.from(p.entries()).map(([h,m])=>{var f;return{name:h,description:((f=m[0])==null?void 0:f.scenario.description)||"",versions:m.sort((y,g)=>{const x=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-x})}})},[t]),d=l.length,u=p=>{o(h=>{const m=new Set(h);return m.has(p)?m.delete(p):m.add(p),m})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:c("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:c("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[c("button",{onClick:()=>s("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),c("button",{onClick:()=>s("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${r==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[n("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),n("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${r==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:d})]})]})}),t.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):r==="entity"?c("div",{className:"relative pl-12",children:[t.length>1&&n("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),t.map((p,h)=>c("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3",children:[p.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),c(Ee,{to:`/entity/${p.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:p.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:p.createdAt&&new Date(p.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),p.analyses.length>0?n("div",{children:p.analyses.map((m,f)=>{var g;const y=(m.scenarios??[]).filter(x=>{var b;return!((b=x.metadata)!=null&&b.sameAsDefault)});return n("div",{children:y.length===0?n(Jc,{hasIndirectBadge:m.indirect,onAnalyze:()=>{console.log("Analyze version:",p.sha)}}):c(we,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:c("div",{className:"flex items-center justify-end gap-2",children:[m.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),c("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[y.length," scenario",y.length!==1?"s":""]})]})}),((g=m.metadata)==null?void 0:g.scenarioChangesOverview)&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:c("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[c("span",{className:"font-medium",children:["What Changed:"," "]}),m.metadata.scenarioChangesOverview]})}),y.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:y.map((x,b)=>{var w,C;const v=(C=(w=x.metadata)==null?void 0:w.screenshotPaths)==null?void 0:C[0],N=`${x.name}-${b}`;return c(Ee,{to:`/entity/${p.sha}/scenarios/${x.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[n("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:v?n(ut,{screenshotPath:v,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),n("div",{className:"p-[5.6px]",children:n("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:x.name})})]},N)})})})]})},m.id||f)})}):n(Jc,{onAnalyze:()=>{console.log("Analyze version:",p.sha)}})]})]},p.sha))]}):n("div",{className:"relative pl-12",children:l.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:n("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):l.map((p,h)=>{const m=a.has(p.name),f=m?p.versions:p.versions.slice(0,1),y=p.versions.length-1,g=p.versions[0];return g==null||g.version.sha,e==null||e.sha,c("div",{className:"relative mb-12 last:mb-0",children:[n("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[n("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:p.name}),p.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:p.description})]}),c("div",{className:"p-5 bg-white",children:[f.map((x,b)=>{var j,A;const{version:v,analysis:N,scenario:w}=x,C=(A=(j=w.metadata)==null?void 0:j.screenshotPaths)==null?void 0:A[0],k=b===0;return c("div",{className:`flex gap-5 items-start ${k?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(Ee,{to:`/entity/${v.sha}/scenarios/${w.id}`,className:"w-[175px] h-[110px] border border-[#e1e1e1] rounded bg-gray-50 flex items-center justify-center shrink-0 hover:border-[#005c75] hover:shadow-sm transition-all",children:C?n(ut,{screenshotPath:C,alt:w.name,className:"max-w-full max-h-full object-contain rounded-sm"}):c("div",{className:"flex flex-col items-center gap-1",children:[n("span",{className:"text-gray-400 text-xl",children:"📷"}),n("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),c("div",{className:"flex-1 flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-2 flex-wrap",children:[v.sha===(e==null?void 0:e.sha)&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-xs font-medium leading-5",children:"Current Version"}),k&&p.versions.length>1&&c("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[p.versions.length," versions"]})]}),c(Ee,{to:`/entity/${v.sha}/scenarios`,className:"text-xs font-mono text-[#646464] m-0 leading-5 hover:text-[#005c75] transition-colors w-fit",children:["SHA:"," ",n("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:v.sha.substring(0,8)})]}),N.createdAt&&c("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(N.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),N.indirect&&n("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5 self-start",children:"Indirect"})]})]},`${v.sha}-${b}`)}),y>0&&c("button",{onClick:()=>u(p.name),className:"mt-5 flex items-center gap-2 text-sm text-[#005c75] bg-transparent border-none cursor-pointer p-0 hover:underline",children:[n("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${m?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),m?"Hide":`${y} previous version${y!==1?"s":""}`]})]})]})]},p.name)})})]})})}function Hc({entity:e,analysisInfo:t,from:r}){const s=Ke(),a=s.state!=="idle",o=e.entityType==="visual"||e.entityType==="library",i=l=>{l.preventDefault(),l.stopPropagation(),o&&s.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return n(Ee,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:c("div",{className:"flex gap-0 border border-gray-200 rounded-lg overflow-hidden transition-all hover:border-[#005c75] hover:shadow-md bg-white h-[100px]",children:[e.screenshotPath?n("div",{className:"w-[125px] h-full bg-gray-50 flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n(ut,{screenshotPath:e.screenshotPath,alt:e.name,className:"max-w-full max-h-full object-contain"})}):n("div",{className:"w-[125px] h-full bg-[#efefef] flex items-center justify-center shrink-0 rounded-bl-[8px] rounded-tl-[8px] border-r border-gray-200",children:n("span",{className:"text-[40px]",children:n(St,{type:e.entityType})})}),c("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n(St,{type:e.entityType}),n("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),n("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),t.hasScenarios&&c("div",{className:"flex items-center gap-2 mt-2",children:[c("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[t.scenarioCount," scenarios"]}),n("span",{className:"text-xs text-[#8e8e8e]",children:t.timestamp})]})]}),n("div",{className:"shrink-0 ml-4",children:t.status==="not_analyzed"?c(we,{children:[c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),n("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]}):t.status==="up_to_date"?c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),n("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):c(we,{children:[c("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),n("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),o&&n("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${a?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:a,children:a?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Vc=e=>{var a,o,i;const t=((a=e.analysisStatus)==null?void 0:a.status)||"not_analyzed",r=((o=e.analysisStatus)==null?void 0:o.scenarioCount)||0,s=(i=e.analysisStatus)==null?void 0:i.timestamp;return t==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:t==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:r>0,scenarioCount:r,timestamp:s}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:r>0,scenarioCount:r,timestamp:s}};function JC({importedEntities:e,importingEntities:t}){const[r]=dr(),s=r.get("from"),a=Ke(),o=a.state!=="idle",i=e.length>0,l=t.length>0,d=m=>m.filter(f=>f.entityType==="visual"||f.entityType==="library"),u=m=>{const f=d(m);f.length!==0&&a.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},p=d(e).length>0,h=d(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:c("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#deeafc] text-[#2f80ed] rounded-[9.095px] text-xs font-semibold leading-5",children:e.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),p&&n("button",{onClick:()=>u(e),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),i?n("div",{className:"p-6 space-y-4",children:e.map(m=>n(Hc,{entity:m,analysisInfo:Vc(m),from:s},m.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[c("div",{className:"px-6 py-4 flex items-start justify-between",children:[c("div",{children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),n("span",{className:"px-2 h-[20.464px] flex items-center justify-center bg-[#f3eefe] text-[#9b51e0] rounded-[9.095px] text-xs font-semibold leading-5",children:t.length})]}),n("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),h&&n("button",{onClick:()=>u(t),disabled:o,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:o?"Analyzing...":"Analyze All"})]}),l?n("div",{className:"p-6 space-y-4",children:t.map(m=>n(Hc,{entity:m,analysisInfo:Vc(m),from:s},m.sha))}):n("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:n("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function HC({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(JC,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function VC({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(qr,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function qr({data:e,depth:t,defaultExpanded:r,maxDepth:s,objectKey:a,showInlineToggle:o=!1}){const[i,l]=E(r||t<2);if(se(()=>{l(r||t<2)},[r,t]),e===null)return n("span",{className:"text-gray-500",children:"null"});if(e===void 0)return n("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return c("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return n("span",{className:"text-blue-600",children:e});if(d==="boolean")return n("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?n("span",{className:"text-gray-600",children:"[]"}):c("span",{children:[c("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[c("span",{children:[i?"▼":"▶"," ","["]}),!i&&c("span",{children:[e.length,"]"]})]}),i?c(we,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((u,p)=>n("div",{className:"py-0.5",children:n(qr,{data:u,depth:t+1,defaultExpanded:r,maxDepth:s})},p))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const u=Object.keys(e);if(u.length===0)return n("span",{className:"text-gray-600",children:"{}"});const p=m=>m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,h=m=>Array.isArray(m)&&m.length>0;return c("span",{children:[c("button",{className:"text-gray-600 hover:text-gray-900 cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded",onClick:()=>l(!i),children:[c("span",{children:[i?"▼":"▶"," ","{"]}),!i&&c("span",{children:[u.length,"}"]})]}),i?c(we,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:u.map(m=>{const f=e[m],y=p(f),g=h(f);return n("div",{className:"py-0.5",children:y?n(Qi,{propertyKey:m,value:f,depth:t,defaultExpanded:r,maxDepth:s}):g?n(Zi,{propertyKey:m,value:f,depth:t,defaultExpanded:r,maxDepth:s}):c(we,{children:[c("span",{className:"text-orange-600",children:[m,": "]}),n(qr,{data:f,depth:t+1,defaultExpanded:r,maxDepth:s})]})},m)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function Qi({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=E(s||r<2),l=Object.keys(t);return se(()=>{i(s||r<2)},[s,r]),c(we,{children:[c("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&c("span",{className:"text-gray-600",children:[l.length,"}"]})]}),o&&c(we,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(d=>{const u=t[d],p=u!==null&&typeof u=="object"&&!Array.isArray(u)&&Object.keys(u).length>0,h=Array.isArray(u)&&u.length>0;return n("div",{className:"py-0.5",children:p?n(Qi,{propertyKey:d,value:u,depth:r+1,defaultExpanded:s,maxDepth:a}):h?n(Zi,{propertyKey:d,value:u,depth:r+1,defaultExpanded:s,maxDepth:a}):c(we,{children:[c("span",{className:"text-orange-600",children:[d,": "]}),n(qr,{data:u,depth:r+2,defaultExpanded:s,maxDepth:a})]})},d)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function Zi({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=E(s||r<2);return se(()=>{i(s||r<2)},[s,r]),c(we,{children:[c("button",{className:"cursor-pointer bg-transparent border-none p-0 font-mono hover:bg-gray-100 rounded inline-flex items-baseline",style:{marginLeft:"-14px"},onClick:()=>i(!o),children:[n("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:o?"▼":"▶"}),c("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&c("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&c(we,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,d)=>{const u=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,p=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:u?n(Qi,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:a}):p?n(Zi,{propertyKey:d.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:a}):n(qr,{data:l,depth:r+2,defaultExpanded:s,maxDepth:a})},d)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function ko({label:e,count:t,isActive:r,onClick:s,badgeColorActive:a,badgeTextActive:o}){return c("button",{onClick:s,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${r?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,t!==void 0&&n("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${r?`${a} ${o}`:"bg-gray-200 text-gray-700"}`,children:t}),r&&n("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function Kc({label:e,isActive:t,onClick:r,disabled:s=!1}){return n("button",{onClick:r,className:`w-full text-left px-3 py-2.5 rounded-md transition-all text-sm cursor-pointer ${t?"bg-[#f6f9fc] text-[#005c75] font-medium border-l-2 border-[#005c75] pl-[10px]":"text-[#3e3e3e] hover:bg-gray-50"}`,disabled:s,children:e})}function Gc({call:e,scenarioName:t}){const[r,s]=E(!1),[a,o]=E("system"),i=m=>new Date(m).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=m=>m?`$${m.toFixed(4)}`:null,d=(m,f)=>{if(!m&&!f)return null;const y=[];return m&&y.push(`${m.toLocaleString()} in`),f&&y.push(`${f.toLocaleString()} out`),y.join(" / ")},u=fe(()=>{var m,f,y,g,x;try{const b=JSON.parse(e.response);return(y=(f=(m=b.choices)==null?void 0:m[0])==null?void 0:f.message)!=null&&y.content?b.choices[0].message.content:(x=(g=b.content)==null?void 0:g[0])!=null&&x.text?b.content[0].text:e.response}catch{return e.response}},[e.response]),p=fe(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),h=fe(()=>{var m;if(t)return t;try{const f=JSON.parse(e.props);return((m=f==null?void 0:f.scenario)==null?void 0:m.name)||null}catch{return null}},[e.props,t]);return c("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[n("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>s(!r),children:c("div",{className:"flex items-start justify-between gap-4",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#005c75] text-white rounded text-[11px] font-medium",children:e.prompt_type}),n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),h&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:h}),e.error&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),c("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&n("span",{children:d(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),c("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),n("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${r?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),r&&c("div",{className:"border-t border-[#e1e1e1]",children:[c("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[n("button",{onClick:()=>o("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),n("button",{onClick:()=>o("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),n("button",{onClick:()=>o("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),n("button",{onClick:()=>o("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${a==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),a&&c("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[a==="system"&&n("div",{children:e.system_message?n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.system_message}):n("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),a==="prompt"&&n("div",{children:n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:e.prompt_text})}),a==="response"&&c("div",{children:[e.error&&c("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[n("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),n("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:u})]}),a==="props"&&n("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:p})]}),e.error&&!a&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:c("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const qc=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function KC({entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a}){var N,w,C,k,j,A,_,M,T;const[o,i]=E("entity"),[l,d]=E("analysis"),[u,p]=E(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[h,m]=E("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=fe(()=>{if(!a)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const D=[...a.entityCalls,...a.analysisCalls],R=D.filter(U=>U.object_type==="entity"||qc.includes(U.prompt_type)),L=D.filter(U=>U.object_type!=="entity"&&!qc.includes(U.prompt_type));return R.sort((U,W)=>W.created_at-U.created_at),L.sort((U,W)=>W.created_at-U.created_at),{entityLlmCalls:R,scenarioLlmCalls:L,totalLlmCalls:D.length}},[a]),x=[{id:"analysis",title:"Analysis",data:t?{id:t.id,status:t.status}:void 0,description:"Analysis metadata including ID and processing status"},{id:"isolatedDataStructure",title:"Isolated Data Structure",data:(N=e==null?void 0:e.metadata)==null?void 0:N.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(w=t==null?void 0:t.metadata)==null?void 0:w.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(k=(C=e==null?void 0:e.metadata)==null?void 0:C.isolatedDataStructure)==null?void 0:k.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(j=t==null?void 0:t.metadata)==null?void 0:j.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(A=e==null?void 0:e.metadata)==null?void 0:A.importedExports,"External Dependencies":(_=e==null?void 0:e.metadata)==null?void 0:_.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(M=t==null?void 0:t.metadata)==null?void 0:M.scenariosDataStructure,description:"Structure template used across all scenarios"}],b=x.filter(D=>D.data!==void 0&&D.data!==null).length;let v=null;if(o==="entity"){const D=x.find(R=>R.id===l);D&&D.data!==void 0&&D.data!==null&&(v={title:D.title,description:D.description,data:D.data})}else if(o==="scenarios"&&u){const D=r.find(R=>(R.id||R.name)===u.scenarioId);D&&(v={title:D.name,description:D.description||"Scenario data and configuration",data:D.metadata})}return c("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:c("div",{className:"flex border-b border-gray-200 relative",children:[n(ko,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(ko,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(ko,{label:"LLM Calls",count:g,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((T=t==null?void 0:t.metadata)==null?void 0:T.analyzerVersion)&&c("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[n("span",{className:"font-medium",children:"Analyzer:"}),n("span",{className:"ml-1 font-mono",children:t.metadata.analyzerVersion})]})]})}),o==="llm-calls"?c("div",{className:"flex-1 min-h-0",children:[c("div",{className:"flex gap-4 mb-4",children:[c("button",{onClick:()=>m("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${h==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),c("button",{onClick:()=>m("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${h==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",y.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:h==="entity"?f.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(D=>n(Gc,{call:D},D.id)):y.length===0?n("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:n("p",{className:"text-gray-500 text-sm m-0",children:"No scenario-level LLM calls found"})}):y.map(D=>n(Gc,{call:D},D.id))})]}):c("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:o==="entity"?c(we,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),b===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(D=>{const R=D.data!==void 0&&D.data!==null;return n(Kc,{label:D.title,isActive:l===D.id,onClick:()=>d(D.id),disabled:!R},D.id)})})]}):c(we,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"SCENARIOS"}),r.length===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No scenarios available."}):n("nav",{className:"space-y-1",children:r.map(D=>{const R=D.id||D.name,L=(u==null?void 0:u.scenarioId)===R;return n(Kc,{label:D.name,isActive:L,onClick:()=>p({scenarioId:R})},R)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:v?n(GC,{title:v.title,description:v.description,data:v.data}):o==="scenarios"&&r.length===0?n(Qc,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:s}):o==="entity"?n(Qc,{title:"No Entity Data Yet",description:"Entity data structures will appear here after analysis is complete.",onAnalyze:s}):n("div",{className:"p-6 text-center py-12 text-gray-500",children:"Select a section to view data"})})]})]})}function Qc({title:e,description:t,onAnalyze:r}){return c("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[n("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),n("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:t}),r&&n("button",{onClick:r,className:"h-[54px] w-[183px] bg-[#005c75] text-white text-base font-medium rounded-lg border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]})}function GC({title:e,description:t,data:r}){const[s,a]=E(!0);return c(we,{children:[c("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[n("h3",{className:"text-base font-semibold text-black m-0",children:e}),n("p",{className:"text-sm text-[#646464] mt-1 m-0",children:t})]}),c("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[c("div",{className:"flex gap-2",children:[n("button",{onClick:()=>a(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),n("button",{onClick:()=>a(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${s?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),n(xt,{content:JSON.stringify(r,null,2),label:"Copy JSON",copiedLabel:"Copied!",className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none transition-colors whitespace-nowrap"})]}),n("div",{className:"overflow-y-auto flex-1",children:n("div",{className:"p-6",children:r?n("div",{className:"bg-gray-50 rounded-lg p-3 overflow-x-auto",children:n(VC,{data:r,defaultExpanded:s,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function qC({entity:e,analysis:t,scenarios:r,onAnalyze:s}){const a=Ke();return se(()=>{if(e!=null&&e.sha&&a.state==="idle"&&!a.data){const o=t!=null&&t.id?`/api/llm-calls/${e.sha}?analysisId=${t.id}`:`/api/llm-calls/${e.sha}`;a.load(o)}},[e==null?void 0:e.sha,t==null?void 0:t.id,a.state,a.data]),n("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:n(KC,{entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a.data})})}const QC={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},ZC={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},XC=2e3,e2=e=>{var r;if(!e)return"typescript";switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"ts":case"tsx":return"typescript";case"js":case"jsx":return"javascript";case"json":return"json";case"css":return"css";default:return"typescript"}};function t2({entity:e,entityCode:t}){const r=Qr(),s=be(null);return se(()=>{const a=r.hash;if(!a||!s.current)return;const o=a.match(/^#L(\d+)$/);if(!o)return;const i=parseInt(o[1],10);setTimeout(()=>{if(!s.current)return;const l=s.current.querySelector(`[data-line-number="${i}"]`);if(l&&l instanceof HTMLElement){l.scrollIntoView({behavior:"smooth",block:"center"});const d=l.style.backgroundColor;l.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{l.style.backgroundColor=d},2e3)}},300)},[r.hash,t]),n("div",{ref:s,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:c("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[c("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),n("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),t&&n(xt,{content:t,label:"Copy Code",duration:XC,className:"px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium cursor-pointer transition-colors hover:bg-[#004a5c] disabled:opacity-75 disabled:cursor-not-allowed"})]}),n("div",{className:"p-0",children:t?n("div",{className:"relative",children:n(Vm,{language:e2(e==null?void 0:e.filePath),style:Km,showLineNumbers:!0,customStyle:QC,lineNumberStyle:ZC,wrapLines:!0,lineProps:a=>({"data-line-number":a,style:{display:"block"}}),children:t})}):n("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}function Zt({prompt:e,height:t=300,onClose:r,hideHeader:s}){const a=be(null),o=be(null),i=be(null),l=be(!1),d=be(e);se(()=>{const p=a.current;if(!p)return;let h=!1,m=null;async function f(){const[y,g]=await Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit")]);if(h)return;{let _=document.getElementById("xterm-css");_||(_=document.createElement("style"),_.id="xterm-css",document.head.appendChild(_)),_.textContent=`
506
+ .xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
507
+ .xterm.focus, .xterm:focus { outline: none; }
508
+ .xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
509
+ .xterm .xterm-helper-textarea { padding: 0; border: 0; margin: 0; position: absolute; opacity: 0; left: -9999em; top: 0; width: 0; height: 0; z-index: -5; white-space: nowrap; overflow: hidden; resize: none; caret-color: transparent !important; clip-path: inset(100%) !important; }
510
+ .xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
511
+ .xterm .composition-view.active { display: block; }
512
+ .xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
513
+ .xterm .xterm-screen { position: relative; }
514
+ .xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
515
+ .xterm .xterm-scroll-area { visibility: hidden; }
516
+ .xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
517
+ .xterm.enable-mouse-events { cursor: default; }
518
+ .xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
519
+ .xterm.column-select.focus { cursor: crosshair; }
520
+ .xterm .xterm-accessibility:not(.debug), .xterm .xterm-message { position: absolute; left: 0; top: 0; bottom: 0; right: 0; z-index: 10; color: transparent; pointer-events: none; }
521
+ .xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
522
+ .xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
523
+ .xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
524
+ .xterm-dim { opacity: 1 !important; }
525
+ .xterm-underline-1 { text-decoration: underline; }
526
+ .xterm-underline-2 { text-decoration: double underline; }
527
+ .xterm-underline-3 { text-decoration: wavy underline; }
528
+ .xterm-underline-4 { text-decoration: dotted underline; }
529
+ .xterm-underline-5 { text-decoration: dashed underline; }
530
+ .xterm-overline { text-decoration: overline; }
531
+ .xterm-strikethrough { text-decoration: line-through; }
532
+ .xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
533
+ .xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
534
+ .xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
535
+ .xterm-decoration-top { z-index: 2; position: relative; }
536
+ `}const x=new y.Terminal({theme:{background:"#1a1a1a",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},fontSize:12,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",cursorBlink:!0,scrollback:5e3,allowProposedApi:!0}),b=new g.FitAddon;x.loadAddon(b),x.open(p),requestAnimationFrame(()=>{try{b.fit()}catch{}}),i.current=x;let v=null;try{const _=await fetch("/api/editor-scenario-prompt",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:d.current})});_.ok&&(v=(await _.json()).promptFile)}catch{}if(h)return;const N=window.location.protocol==="https:"?"wss:":"ws:",w=window.location.host,C=new URLSearchParams;C.set("entityName","inline-claude");const k=`${N}//${w}/ws/terminal?${C.toString()}`,j=new WebSocket(k);o.current=j,j.onopen=()=>{j.send(JSON.stringify({type:"resize",cols:x.cols,rows:x.rows}))};let A=!1;j.onmessage=_=>{try{const M=JSON.parse(_.data);if(M.type==="session-id"&&!A){A=!0,setTimeout(()=>{const T=v?`claude "Read the file at '${v.replace(/'/g,"'\\''")}' for your instructions."`:"claude";j.send(JSON.stringify({type:"input",data:T+"\r"}))},300);return}if(M.type==="output"&&M.data){x.write(M.data);return}}catch{x.write(_.data)}},j.onclose=()=>{l.current||x.write(`\r
537
+ \x1B[90m--- Session ended ---\x1B[0m\r
538
+ `)},j.onerror=()=>{x.write(`\r
539
+ \x1B[31mConnection error\x1B[0m\r
540
+ `)},x.onData(_=>{j.readyState===WebSocket.OPEN&&j.send(JSON.stringify({type:"input",data:_}))}),m=new ResizeObserver(()=>{try{b.fit(),j.readyState===WebSocket.OPEN&&j.send(JSON.stringify({type:"resize",cols:x.cols,rows:x.rows}))}catch{}}),m.observe(p)}return f(),()=>{var y,g;h=!0,l.current=!0,m==null||m.disconnect(),((y=o.current)==null?void 0:y.readyState)===WebSocket.OPEN&&o.current.close(),(g=i.current)==null||g.dispose()}},[]);const u=t==="100%";return c("div",{className:s?"":"border-t border-[#2d2d2d]",style:u?{height:"100%",display:"flex",flexDirection:"column"}:void 0,children:[!s&&c("div",{className:"flex items-center justify-between px-3 py-1.5 bg-[#1e1e1e]",children:[n("span",{className:"text-[10px] font-medium text-[#00a0c4]",children:"Claude"}),r&&n("button",{onClick:r,className:"text-gray-500 hover:text-gray-300 text-[10px] bg-transparent border-none cursor-pointer",children:"Close"})]}),n("div",{ref:a,style:{height:u?void 0:t,flex:u?1:void 0,background:"#1a1a1a",padding:"4px 0",position:"relative",overflow:"hidden"}})]})}const n2=Object.freeze(Object.defineProperty({__proto__:null,MiniClaudeChat:Zt},Symbol.toStringTag,{value:"Module"})),r2=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function s2({currentParams:e,nextParams:t,currentUrl:r,nextUrl:s,formMethod:a,defaultShouldRevalidate:o}){return r.pathname===s.pathname&&r.search===s.search?o:!!(e.sha!==t.sha||a)}async function a2({params:e,request:t,context:r}){const{sha:s}=e;if(!s)throw new Response("Entity SHA is required",{status:400});const o=new URL(t.url).searchParams.get("from"),l=(e["*"]||"").split("/").filter(Boolean),d=l[0]||"scenarios",u=l[1]||null,p=l[2]||null,h=r.analysisQueue,m=h?h.getState():{paused:!1,jobs:[]},[f,y,g,x]=await Promise.all([Ln(s),ze(),fr(),o0(Ce()||process.cwd())]),b=f?await ba(f):null,v=f?await ou(f.sha):null;let N={importedEntities:[],importingEntities:[]},w=null,C=[];f&&(N=await iu(f),w=await lu(f),C=await du(f));const k=!!(f&&C.length>0&&C[0].sha!==f.sha),j=C.length>0?C[0].sha:null,A=!!(C.length>0&&C[0].analyses&&C[0].analyses.length>0),_=f?await cu(f):!1;return ue({entity:f??void 0,analysis:b??void 0,currentEntityAnalysis:v??void 0,projectSlug:y,from:o,relatedEntities:N,entityCode:w??void 0,hasNewerVersion:k,newestEntitySha:j,newestVersionHasAnalysis:A,fileModifiedSinceEntity:_,history:C,tab:d,scenarioId:u,viewModeFromUrl:p,currentCommit:g,hasAnApiKey:x,queueState:m})}const o2=tt(function(){var an,on,Kt,Sn,Er,Pr,cs,ds,us,ps,hs,Jn,ms,fs,gs;const t=lt(),a=(Dd()["*"]||"").split("/").filter(Boolean),o=a[0]||"scenarios",i=a[1]||null,l=a[2]||null,d=t.entity,u=t.analysis,p=t.currentEntityAnalysis,h=p||u,m=t.projectSlug;t.from;const f=t.relatedEntities,y=t.entityCode,g=t.hasNewerVersion,x=t.newestEntitySha,b=t.newestVersionHasAnalysis,v=t.fileModifiedSinceEntity,N=t.history,w=t.currentCommit,C=t.hasAnApiKey,k=t.queueState;(an=h==null?void 0:h.status)==null||an.errors;const j=(h==null?void 0:h.scenarios)||[],A=j.filter(xe=>{var Fe;return!((Fe=xe.metadata)!=null&&Fe.sameAsDefault)}),_=j.filter(xe=>{var Fe;return(Fe=xe.metadata)==null?void 0:Fe.sameAsDefault}),M=Yt(),T=be(null);se(()=>{T.current===null&&(T.current=window.history.length)},[]);const D=()=>{if(typeof window>"u")return;const xe=window.history.state;if(xe===null||(xe==null?void 0:xe.idx)===void 0||(xe==null?void 0:xe.idx)===0)M("/");else{const Fe=window.history.length,st=T.current;if(st!==null&&Fe>st){const Ye=Fe-st+1;M(-Ye)}else M(-1)}},R=!!k.currentlyExecuting,L=o,U=(on=w==null?void 0:w.metadata)==null?void 0:on.currentRun,W=!!(U!=null&&U.createdAt)&&!(U!=null&&U.analysisCompletedAt),V=!!(d!=null&&d.sha&&((Kt=U==null?void 0:U.currentEntityShas)!=null&&Kt.includes(d.sha))),F=!!(d!=null&&d.sha&&((Er=(Sn=k.currentlyExecuting)==null?void 0:Sn.entityShas)!=null&&Er.includes(d.sha))),Y=!!(d!=null&&d.sha&&((Pr=k.jobs)!=null&&Pr.some(xe=>{var Fe;return(Fe=xe.entityShas)==null?void 0:Fe.includes(d.sha)}))),P=V||F||Y,O=P&&((cs=h==null?void 0:h.status)==null?void 0:cs.finishedAt)!=null&&A.length>0&&h.entitySha!==(d==null?void 0:d.sha),S=fe(()=>{if(L!=="scenarios")return null;if(i){const xe=A.find(Fe=>Fe.id===i);if(xe)return xe}return A.length>0&&!P?A[0]:null},[L,i,A,P]),$=((ps=(us=(ds=S==null?void 0:S.metadata)==null?void 0:ds.executionResult)==null?void 0:us.error)==null?void 0:ps.message)||((ms=(Jn=(hs=h==null?void 0:h.status)==null?void 0:hs.errors)==null?void 0:Jn[0])==null?void 0:ms.message);Wt({source:S?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:S==null?void 0:S.id,analysisId:h==null?void 0:h.id,entityName:d==null?void 0:d.name,entityType:d==null?void 0:d.entityType,scenarioName:S==null?void 0:S.name,errorMessage:$});const[I,K]=E(()=>l&&l!=="edit"?l:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");se(()=>{l&&l!==I&&l!=="edit"&&K(l)},[l]);const q=l==="edit",[J,z]=E(!1),[B,H]=E(!1),[re,ae]=E(null),[X,oe]=E(!1),[me,ve]=E(!1),[je,te]=E(null),[ke,Z]=E(null),[pe,ie]=E(0),{interactiveServerUrl:de,isStarting:he,isLoading:_e,showIframe:ye,iframeKey:Re,onIframeLoad:Je}=Un({analysisId:h==null?void 0:h.id,scenarioId:S==null?void 0:S.id,scenarioName:S==null?void 0:S.name,projectSlug:m,enabled:q&&!!S,refreshTrigger:pe}),[bt,Ge]=E(!1),[vr,pt]=E(""),[qe,Ht]=E(!1),[wr,sn]=E(Date.now()),[Nr,Wn]=E(!1),[wn,Dt]=E(!1),ht=Ke(),mt=Ke(),ft=Ke(),ct=Ut(),Sr=k.jobs.some(xe=>{var Fe;return(d==null?void 0:d.sha)&&((Fe=xe.entityShas)==null?void 0:Fe.includes(d.sha))||xe.type==="analysis"&&xe.commitSha===(w==null?void 0:w.sha)&&xe.entityShas&&xe.entityShas.length===0}),Le=P,Vt=((fs=d==null?void 0:d.metadata)==null?void 0:fs.defaultWidth)||((gs=h==null?void 0:h.metadata)==null?void 0:gs.defaultWidth)||1440,as=Math.round(Vt*(900/1440));ht.state==="submitting"||ht.state,fe(()=>{var xe;return!!((xe=S==null?void 0:S.metadata)!=null&&xe.interactiveExamplePath)},[S]);const{isCompleted:Cr}=Xt(m,qe);se(()=>{ht.state==="idle"&&ht.data&&(ht.data.success?setTimeout(()=>{sn(Date.now()),ct.revalidate(),Ht(!1)},1500):ht.data.error&&(Ht(!1),alert(`Recapture failed: ${ht.data.error}`)))},[ht.state,ht.data,ct]),se(()=>{qe&&Cr&&setTimeout(()=>{sn(Date.now()),ct.revalidate(),Ht(!1)},1500)},[qe,Cr,ct]),se(()=>{mt.state==="idle"&&mt.data&&(mt.data.success?setTimeout(()=>{sn(Date.now()),ct.revalidate(),Ht(!1)},1500):mt.data.error&&(Ht(!1),alert(`Recapture failed: ${mt.data.error}`)))},[mt.state,mt.data,ct]);const dt=fe(()=>{var st;if(!d)return"";const xe=[];if(xe.push(`# Create a New Scenario for "${d.name}"`),xe.push(""),xe.push(`**Entity**: ${d.name}`),xe.push(`**Type**: ${d.entityType}`),d.filePath&&xe.push(`**File**: ${d.filePath}`),xe.push(""),A.length>0){xe.push("## Existing Scenarios");for(const Ye of A)xe.push(`- **${Ye.name}**${Ye.description?`: ${Ye.description}`:""}`);xe.push("")}const Fe=(st=h==null?void 0:h.metadata)==null?void 0:st.executionFlows;if(Fe&&Fe.length>0){xe.push("## Execution Flows");const Ye=new Set(A.flatMap(Ve=>{var ot;return((ot=Ve.metadata)==null?void 0:ot.coveredFlows)||[]})),at=Fe.filter(Ve=>!Ye.has(Ve.id)),yt=Fe.filter(Ve=>Ye.has(Ve.id));if(yt.length>0){xe.push(`### Covered (${yt.length})`);for(const Ve of yt)xe.push(`- ${Ve.name}${Ve.description?`: ${Ve.description}`:""}`);xe.push("")}if(at.length>0){xe.push(`### Uncovered (${at.length}) — gaps to consider`);for(const Ve of at)xe.push(`- ${Ve.name}${Ve.description?`: ${Ve.description}`:""}${Ve.impact==="high"?" **(high impact)**":""}`);xe.push("")}}return xe.push("## Your Task"),xe.push("Ask the user what scenario they would like to create. Offer two options:"),xe.push("1. **Describe a scenario** — the user tells you what they want and you create it"),xe.push("2. **Analyze gaps** — you review the existing scenarios and execution flows to suggest scenarios that would improve coverage"),xe.push(""),xe.push("Once you know what scenario to create, use the `codeyam editor register` CLI command to register it. Write the scenario JSON to `.codeyam/tmp/scenario.json` first, then run `codeyam editor register @.codeyam/tmp/scenario.json`."),xe.join(`
541
+ `)},[d,A,h]),kr=()=>{Dt(!0)},os=()=>{d&&(g&&x&&x!==d.sha?(M(`/entity/${x}/scenarios`),setTimeout(()=>{ft.submit({entitySha:x,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):ft.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};se(()=>{ft.state==="idle"&&ft.data&&(ft.data.success?ct.revalidate():ft.data.error&&alert(`Analysis failed: ${ft.data.error}`))},[ft.state,ft.data,d==null?void 0:d.sha,ct]),se(()=>{const xe=setTimeout(()=>{ct.revalidate()},500);return()=>clearTimeout(xe)},[]),se(()=>{if(W||Le){const xe=setInterval(()=>{ct.revalidate()},3e3);return()=>clearInterval(xe)}},[W,Le,ct]);const is=(xe,Fe)=>xe==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${xe}`,ls=(xe,Fe)=>`/entity/${d==null?void 0:d.sha}/scenarios/${xe}/${Fe}`,nt=xe=>{K(xe),S!=null&&S.id&&(xe==="interactive"?M(`/entity/${d==null?void 0:d.sha}/scenarios/${S.id}/fullscreen`,{replace:!0}):M(ls(S.id,xe),{replace:!0}))},gt=async xe=>{var Fe,st;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:xe,hasSelectedScenario:!!S,hasAnalysis:!!h}),!S||!h){const Ye="Error: No scenario or analysis available";console.error("[EntityDetail]",Ye),ae(Ye);return}z(!0),ae(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:xe,scenarioId:S.id,scenarioName:S.name,currentData:S.data});try{const Ye=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:xe,existingScenarios:h.scenarios,scenariosDataStructure:(Fe=h.metadata)==null?void 0:Fe.scenariosDataStructure,editingMockName:S.name,editingMockData:ke||((st=S.metadata)==null?void 0:st.data)})}),at=await Ye.json();if(!Ye.ok||!at.success)throw new Error(at.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",at.data),Z(at.data);const yt=(h.scenarios||[]).map(He=>He.id===S.id?{...He,metadata:{...He.metadata,data:at.data}}:He),Ve=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:yt})}),ot=await Ve.json();if(!Ve.ok||!ot.success)throw console.error("[EntityDetail] Temp save failed:",ot),new Error(ot.error||"Failed to apply preview");if(ae("Generating preview. Capturing screenshot..."),de){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:de});const He=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:de,scenarioId:S.id,projectId:h.projectId,viewportWidth:1440})}),Cn=await He.json();!He.ok||!Cn.success?(console.error("[EntityDetail] Direct capture failed:",Cn),ae("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),ae('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const He=new FormData;He.append("analysisId",h.id||""),He.append("scenarioId",S.id||"");const Cn=await fetch("/api/recapture-scenario",{method:"POST",body:He}),kn=await Cn.json();!Cn.ok||!kn.success?(console.warn("[EntityDetail] Recapture failed:",kn.error),ae("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",kn.jobId),ae('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}ie(He=>He+1),ct.revalidate()}catch(Ye){console.error("Error applying changes:",Ye),ae(`Error: ${Ye instanceof Error?Ye.message:String(Ye)}`)}finally{z(!1)}},jr=async(xe,Fe)=>{var st;if(!S||!h){ae("Error: No scenario or analysis available");return}H(!0),ae(null),console.log("[EntityDetail] Saving scenario to database",{description:xe,saveAsNew:Fe});try{const Ye=ke||((st=S.metadata)==null?void 0:st.data);let at;if(Fe){const ot={...S,id:`${S.name}-${Date.now()}`,name:`${S.name} (Copy)`,metadata:{...S.metadata,data:Ye},description:xe||S.description};at=[...h.scenarios||[],ot]}else at=(h.scenarios||[]).map(ot=>ot.id===S.id?{...ot,metadata:{...ot.metadata,data:Ye},description:xe||ot.description}:ot);const yt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:h,scenarios:at})}),Ve=await yt.json();if(!yt.ok||!Ve.success)throw new Error(Ve.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),ae(Fe?"New scenario created successfully":"Scenario saved successfully"),Z(null),ct.revalidate()}catch(Ye){console.error("Error saving scenario:",Ye),ae(`Error: ${Ye instanceof Error?Ye.message:String(Ye)}`)}finally{H(!1)}},Ya=()=>{S!=null&&S.id&&(d!=null&&d.sha)&&M(`/entity/${d.sha}/scenarios/${S.id}/dev`)},Ua=async()=>{var xe;if(!(S!=null&&S.id)){te("Cannot delete scenario without ID");return}oe(!0),te(null);try{const Fe=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:S.id,screenshotPaths:((xe=S.metadata)==null?void 0:xe.screenshotPaths)||[]})}),st=await Fe.json();if(!Fe.ok||!st.success)throw new Error(st.error||"Failed to delete scenario");M(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(Fe){console.error("[EntityDetail] Error deleting scenario:",Fe),te(Fe instanceof Error?Fe.message:"Failed to delete scenario"),ve(!1)}finally{oe(!1)}},_r=h&&d&&h.entitySha!==d.sha,Nn=d?LC(d):!1;return n(Da,{children:c("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-end h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:D,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),n("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d==null?void 0:d.filePath,children:d==null?void 0:d.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:A.length},{id:"related",label:"Related Entities",count:f.importedEntities.length+f.importingEntities.length},{id:"code",label:"Code"},{id:"data",label:"Data Structure"},{id:"history",label:"History"}].map(xe=>n(Ee,{to:is(xe.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${L===xe.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:L===xe.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:c("span",{className:"flex items-center gap-2",children:[xe.label,xe.count!==void 0&&xe.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${L===xe.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:xe.count})]})},xe.id))})]})}),(g||_r&&!p||v&&Nn)&&!P&&!Sr&&n("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:c("div",{className:"flex items-center gap-3",children:[n("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),n("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:_r&&!g?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),n("span",{className:"text-sm",style:{color:"#714A25"},children:g?"You are viewing an older version. A newer version is available.":_r?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),g&&x&&b?n(Ee,{to:`/entity/${x}/scenarios`,className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono cursor-pointer transition-colors no-underline",style:{backgroundColor:"#C69538"},onMouseEnter:xe=>{xe.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:xe=>{xe.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:os,disabled:ft.state!=="idle",className:"px-3 py-1.5 text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#C69538"},onMouseEnter:xe=>{ft.state==="idle"&&(xe.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:xe=>{ft.state==="idle"&&(xe.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),c("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[L==="scenarios"&&c(we,{children:[q&&S?n(zC,{scenario:S,entitySha:(d==null?void 0:d.sha)||"",onApply:gt,onSave:jr,onEditMockData:Ya,onDelete:Ua,isApplying:J,isSaving:B,saveMessage:re,showDeleteConfirm:me,onShowDeleteConfirm:ve,isDeleting:X,deleteError:je}):n(BC,{scenarios:A,hiddenScenarios:_,analysis:h,selectedScenario:S,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:wr,activeTab:L,entityType:d==null?void 0:d.entityType,entity:d,queueState:k,processIsRunning:R,isEntityAnalyzing:P,areScenariosStale:O,viewMode:I,setViewMode:nt,isBreakdownView:i==="breakdown",onCreateScenario:kr}),wn?c("div",{className:"flex flex-col flex-1 min-h-0",children:[c("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:"Create New Scenario"}),n("button",{onClick:()=>Dt(!1),className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors",children:"Close"})]}),n("div",{className:"flex-1 min-h-0",children:n(Zt,{prompt:dt,height:"100%",hideHeader:!0})})]}):i==="breakdown"?n(UC,{analysis:h??null,entitySha:(d==null?void 0:d.sha)||"",onCreateScenario:kr}):q&&S?n(Ra,{scenarioId:S.id||S.name,scenarioName:S.name,iframeUrl:de,isStarting:he,isLoading:_e,showIframe:ye,iframeKey:Re,onIframeLoad:Je,projectSlug:m,defaultWidth:1440,defaultHeight:900}):c("div",{className:"flex flex-col flex-1 min-h-0",children:[S&&c("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:S.name}),c("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[Vt," × ",as]})]}),c("div",{className:"flex items-center gap-2",children:[n(Ee,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${S.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),c("button",{className:"px-3 py-1.5 bg-[#022A35] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#011a21] transition-colors flex items-center gap-1.5",onClick:()=>{alert("Download functionality coming soon")},title:"Download",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:n("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),c(Ee,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${S.id}/dev`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Dev Mode - Live preview with data editor and code sync",children:[c("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[n("polyline",{points:"16 18 22 12 16 6"}),n("polyline",{points:"8 6 2 12 8 18"})]}),"Dev Mode"]}),c(Ee,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${S.id}/fullscreen`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Interactive Mode",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:n("path",{d:"M8 5v14l11-7z"})}),"Interactive Mode"]})]})]}),n(Ip,{selectedScenario:S,analysis:h,entity:d,viewMode:I,cacheBuster:wr,hasScenarios:A.length>0,isAnalyzing:Le,projectSlug:m,hasAnApiKey:C,processIsRunning:R,queueState:k})]})]}),L==="related"&&n(HC,{relatedEntities:f}),L==="data"&&n(qC,{entity:d,analysis:h,scenarios:A,onAnalyze:os}),L==="code"&&n(t2,{entity:d,entityCode:y}),L==="history"&&n(WC,{entity:d,history:N})]}),Nr&&m&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>Wn(!1),children:c("div",{className:"bg-white rounded-xl max-w-[1200px] w-full max-h-[90vh] flex flex-col shadow-[0_20px_60px_rgba(0,0,0,0.3)]",onClick:xe=>xe.stopPropagation(),children:[c("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[n("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),n("button",{className:"bg-transparent border-none text-[28px] text-gray-500 cursor-pointer p-0 w-8 h-8 flex items-center justify-center rounded transition-colors hover:bg-gray-100",onClick:()=>Wn(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(mn,{projectSlug:m,onClose:()=>Wn(!1)})})]})})]})})}),i2=Object.freeze(Object.defineProperty({__proto__:null,default:o2,loader:a2,meta:r2,shouldRevalidate:s2},Symbol.toStringTag,{value:"Module"}));async function l2(e){const{entityShas:t,filePaths:r,context:s,scenarioCount:a,queue:o}=e;console.log(`[analyzeEntities] Starting analysis for ${t.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await We();const i=Ce();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=ee.join(i,".codeyam","config.json"),d=JSON.parse(await Te.readFile(l,"utf8")),{projectSlug:u,branchId:p}=d;if(!u||!p)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${u}, Branch: ${p}`);const h=ts(u);try{await Te.writeFile(h,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:m,branch:f}=await Ie(u);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await et({shas:t});if(!y||y.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);let g=r;if((!g||g.length===0)&&(g=[...new Set(y.map(v=>v.filePath).filter(v=>!!v))],console.log(`[analyzeEntities] Found ${g.length} unique files`)),!g||g.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${g.length} files...`);const x=await t0(m,f,g);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await hn({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:v=>{if(!v)return;const N=v.currentRun;if(N&&N.id&&N.archivedAt)return;N&&(N.analysesCompleted&&N.analysesCompleted>0||N.capturesCompleted&&N.capturesCompleted>0)&&m0(v)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:b}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:u,filePaths:g,entityShas:t,entityNames:y.map(v=>v.name),...s?{context:s}:{},...a?{scenarioCount:a}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${b} for ${t.length} entities`),{jobId:b}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function c2({request:e,context:t}){if(e.method!=="POST")return ue({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await nn()),!r)return ue({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("entitySha"),o=s.get("entityShas"),i=s.get("filePath"),l=s.get("context"),d=s.get("scenarioCount");let u;if(o)u=o.split(",").filter(Boolean);else if(a)u=[a];else return ue({error:"Missing required field: entitySha or entityShas"},{status:400});if(u.length===0)return ue({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${u.length} entity(ies)`);const p=await et({shas:u}),m=[...new Set(p.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await l2({entityShas:u,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),ue({success:!0,message:`Analysis queued for ${u.length} entity(ies)`,entityCount:u.length,fileCount:m,jobId:f})}catch(s){return console.error("[API] Error starting analysis:",s),ue({error:"Failed to start analysis",details:s.message},{status:500})}}const d2=Object.freeze(Object.defineProperty({__proto__:null,action:c2},Symbol.toStringTag,{value:"Module"}));function u2(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]})};case"up-to-date":return{text:"Up to date",bgColor:"#e8ffe6",textColor:"#00925d",icon:null};case"incomplete":return{text:"Incomplete",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"out-of-date":return{text:"Out of date",bgColor:"#fdf9c9",textColor:"#c69538",icon:null};case"not-analyzed":return{text:"Not analyzed",bgColor:"#f9f9f9",textColor:"#646464",icon:null}}}function Op(e){if(!e)return"Never";const t=new Date(e),r=new Date;if(t.getDate()===r.getDate()&&t.getMonth()===r.getMonth()&&t.getFullYear()===r.getFullYear()){const a=t.getHours(),o=t.getMinutes(),i=a>=12?"pm":"am",l=a%12||12,d=o.toString().padStart(2,"0");return`Today, ${l}:${d} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function Et(e,t=[],r=!1){var p,h;if(t.some(m=>{var f,y;return!!((f=m.entityShas)!=null&&f.includes(e.sha)||(y=m.entities)!=null&&y.some(g=>g.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const a=e.analyses[0];if(!(((p=a.status)==null?void 0:p.scenarios)&&a.status.scenarios.length>0&&a.status.scenarios.some(m=>m.screenshotFinishedAt||m.finishedAt))||a.entitySha!==e.sha)return"not-analyzed";const i=a.createdAt?new Date(a.createdAt).getTime():0,l=(h=e.metadata)!=null&&h.editedAt?new Date(e.metadata.editedAt).getTime():0,d=a.scenarios||[],u=d.some(m=>{var f,y,g;return((y=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||((g=m.metadata)==null?void 0:g.executionResult)});return i>=l?d.length>0&&u?d.every(f=>{var y,g,x;return((g=(y=f.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const p2=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function h2({request:e,context:t}){try{const r=t.analysisQueue,s=r?r.getState():{paused:!1,jobs:[]},a=await Yn();return ue({entities:a||[],queueState:s})}catch(r){return console.error("Failed to load simulations:",r),ue({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const m2=tt(function(){const t=lt(),r=t.entities,s=t.queueState;Wt({source:"simulations-page"});const[a,o]=E(""),[i,l]=E("visual"),d=fe(()=>{const g=[];return r.forEach(x=>{var v;const b=(v=x.analyses)==null?void 0:v[0];if(b!=null&&b.scenarios){const N=b.scenarios.filter(w=>{var C;return!((C=w.metadata)!=null&&C.sameAsDefault)}).map(w=>{var T,D,R,L,U;const C=(D=(T=w.metadata)==null?void 0:T.screenshotPaths)==null?void 0:D[0],k=(R=w.metadata)==null?void 0:R.noScreenshotSaved,j=C&&!k,A=(U=(L=b.status)==null?void 0:L.scenarios)==null?void 0:U.find(W=>W.name===w.name),_=A&&A.screenshotStartedAt&&!A.screenshotFinishedAt;let M;return j?M="completed":_?M="capturing":M="error",{scenarioName:w.name,scenarioDescription:w.description||"",screenshotPath:C||"",scenarioId:w.id,state:M}}).filter(w=>w.state==="completed"||w.state==="capturing");N.length>0&&g.push({entity:x,screenshots:N,createdAt:b.createdAt||""})}}),g.sort((x,b)=>new Date(b.createdAt).getTime()-new Date(x.createdAt).getTime()),g},[r]),u=fe(()=>r.filter(g=>{var v,N;const x=(v=g.analyses)==null?void 0:v[0];return!((N=x==null?void 0:x.scenarios)==null?void 0:N.some(w=>{var C,k;return(k=(C=w.metadata)==null?void 0:C.screenshotPaths)==null?void 0:k[0]}))}),[r]),p=fe(()=>d.filter(({entity:g})=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),b=i==="all"||g.entityType===i;return x&&b}),[d,a,i]),h=fe(()=>u.filter(g=>{const x=!a||g.name.toLowerCase().includes(a.toLowerCase()),b=i==="all"||g.entityType===i;return x&&b}),[u,a,i]),m=le(g=>{o(g.target.value)},[]),f=le(g=>{l(g.target.value)},[]),y=d.length>0;return n("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),n("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!y&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:c("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",n("strong",{children:"Start by analyzing your first component below."})]})}),c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative",children:[c("select",{className:"appearance-none bg-gray-50 border border-gray-200 rounded px-3 pr-8 text-[13px] h-[39px] cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",value:i,onChange:f,children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(Tt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-3 text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors",value:a,onChange:m})]})]})]}),y&&p.length>0&&n("div",{className:"mb-2",children:c("div",{className:"flex items-center py-3",children:[c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:p.length})," ",p.length===1?"entity":"entities"]}),c("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:p.reduce((g,{screenshots:x})=>g+x.length,0)})," ","scenarios"]})]})}),c("div",{className:"flex flex-col gap-3",children:[y&&(p.length===0?n("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):n(we,{children:p.map(({entity:g,screenshots:x})=>n(f2,{entity:g,screenshots:x,queueJobs:(s==null?void 0:s.jobs)||[]},g.sha))})),!y&&(h.length===0?n("div",{className:"bg-white border border-gray-200 rounded-b-lg p-8 text-center text-gray-500",children:"No components found matching your filters."}):h.map(g=>n(g2,{entity:g},g.sha)))]})]})})});function f2({entity:e,screenshots:t,queueJobs:r}){var f,y,g;const s=Yt(),a=Ke(),[o,i]=E(!1),l=t.length||(((g=(y=(f=e.analyses)==null?void 0:f[0])==null?void 0:y.scenarios)==null?void 0:g.length)??0),d=x=>{s(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},u=()=>{i(!0),a.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};se(()=>{a.state==="idle"&&o&&i(!1)},[a.state,o]);const p=Et(e,r),h=u2(p),m=p==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:c("div",{className:"flex flex-col",children:[c("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(St,{type:e.entityType||"other",size:"large"})}),c("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[c("div",{className:"flex items-center gap-[5px]",children:[c(Ee,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",l,")"]}),n("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:h.bgColor,color:h.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:h.text})]}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),n("div",{className:"flex-1"}),c("div",{className:"flex-shrink-0 flex items-center gap-2",children:[m&&n(we,{children:o||a.state!=="idle"?c("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(Ot,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:u,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),n("button",{onClick:()=>void s(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),n("div",{className:"border-t border-gray-200"}),n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:t.length>0?t.map(x=>c("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>d(x.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:n("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:x.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:x.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:b=>{x.state==="completed"&&(b.currentTarget.style.borderColor="#005C75",b.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:b=>{b.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",b.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(ut,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(qi,{size:"medium"}):null})}),c("div",{className:"relative group",children:[n("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:x.scenarioName}),n("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children:c("div",{className:"bg-gray-100 text-gray-800 text-xs rounded-lg px-3 py-2 shadow-lg max-w-xs border border-gray-200",children:[x.scenarioName,x.scenarioDescription&&c(we,{children:[": ",x.scenarioDescription]}),n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-100 border-l border-t border-gray-200 transform rotate-45"})]})})]})]},x.scenarioId)):n("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function g2({entity:e}){const t=Ke(),[r,s]=E(!1),a=()=>{s(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return se(()=>{t.state==="idle"&&r&&s(!1)},[t.state,r]),n("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:a,children:c("div",{className:"px-5 py-4 flex items-center",children:[c("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(St,{type:e.entityType}),c("div",{className:"min-w-0",children:[c("div",{className:"flex items-center gap-3 mb-0.5",children:[n(Ee,{to:`/entity/${e.sha}`,className:"text-sm font-medium text-gray-900 no-underline",children:e.name}),n("span",{className:"text-[10px] font-semibold px-1 py-0.5 rounded",style:{color:e.entityType==="visual"?"#7c3aed":e.entityType==="library"?"#0DBFE9":e.entityType==="type"?"#dc2626":e.entityType==="data"?"#2563eb":e.entityType==="index"?"#ea580c":e.entityType==="functionCall"?"#7c3aed":e.entityType==="class"?"#059669":e.entityType==="method"?"#0891b2":"#6b7280",backgroundColor:e.entityType==="visual"?"#f3e8ff":e.entityType==="library"?"#cffafe":e.entityType==="type"?"#fee2e2":e.entityType==="data"?"#dbeafe":e.entityType==="index"?"#ffedd5":e.entityType==="functionCall"?"#f3e8ff":e.entityType==="class"?"#d1fae5":e.entityType==="method"?"#cffafe":"#f3f4f6"},children:e.entityType?e.entityType.toUpperCase():"UNKNOWN"})]}),n("div",{className:"text-xs text-gray-400 truncate",children:e.filePath})]})]}),n("div",{className:"w-32 flex justify-center",children:n("span",{className:"text-[10px] text-gray-500 bg-gray-100 px-2 py-1 rounded",children:"Not analyzed"})}),n("div",{className:"w-32 text-center text-[10px] text-gray-500",children:Op(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(Ot,{size:14,className:"animate-spin"}),"Analyzing..."]}):n("button",{onClick:a,className:"bg-[#e0e9ec] text-[#005c75] px-4 py-1.5 rounded text-xs font-medium hover:bg-[#d0dde1] transition-colors cursor-pointer",children:"Analyze"})})]})})}const y2=Object.freeze(Object.defineProperty({__proto__:null,default:m2,loader:h2,meta:p2},Symbol.toStringTag,{value:"Module"}));function x2({request:e,context:t}){const r=t.dbNotifier||Nt;if(!r)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});r.start().catch(()=>{});const s=new ReadableStream({start(a){const o=new TextEncoder;a.enqueue(o.encode(`data: ${JSON.stringify({type:"connected"})}
542
+
543
+ `)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",d),clearInterval(u);try{a.close()}catch{}}},d=p=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:p.type,timestamp:p.timestamp})}
544
+
545
+ `))}catch{l()}};r.on("change",d);const u=setInterval(()=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
546
+
547
+ `))}catch{l()}},3e4);e.signal.addEventListener("abort",l)}});return new Response(s,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const b2=Object.freeze(Object.defineProperty({__proto__:null,loader:x2},Symbol.toStringTag,{value:"Module"}));function v2(){return new Response(JSON.stringify({status:"ok",version:xi,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const w2=Object.freeze(Object.defineProperty({__proto__:null,loader:v2},Symbol.toStringTag,{value:"Module"}));function Xi(e){const t=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,r=e.match(t);if(!r)return{frontmatter:{},body:e};const s=r[1],a=r[2],o={},i=s.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/),l=s.match(/paths:\s*\[([^\]]*)\]/);i&&i[1].trim()?o.paths=i[1].split(`
548
+ `).filter(u=>u.trim().startsWith("-")).map(u=>u.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean):l&&(o.paths=l[1].split(",").map(u=>u.replace(/['"]/g,"").trim()).filter(Boolean));const d=s.match(/^category:\s*(.+)$/m);return d&&(o.category=d[1].replace(/['"]/g,"").trim()),{frontmatter:o,body:a}}async function Ba(e,t=""){const r=[];try{const s=await Te.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){const i=await Ba(ee.join(e,a.name),o);r.push(...i)}else a.isFile()&&a.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function ss(e){const t=await Ba(e),r=[];for(const s of t){const a=ee.join(e,s);try{const o=await Te.readFile(a,"utf-8"),{frontmatter:i,body:l}=Xi(o);r.push({filePath:s,absolutePath:a,frontmatter:i,body:l})}catch{}}return r}function Lp(e){const t=ee.posix.dirname(e.filePath);return!t||t==="."?null:`${t}/**`}function Bp(e,t){if(t.frontmatter.paths&&t.frontmatter.paths.length>0)return t.frontmatter.paths.some(s=>Do(e,s,{matchBase:!0}));const r=Lp(t);return r?Do(e,r,{matchBase:!0}):!1}function N2(e,t){return(!e.frontmatter.paths||e.frontmatter.paths.length===0)&&!Lp(e)?[]:t.filter(r=>Bp(r,e))}const S2=new Set(["node_modules",".git","dist",".codeyam",".claude","build","coverage"]);async function el(e){const t=[];async function r(s,a){try{const o=await Ae.readdir(s,{withFileTypes:!0});for(const i of o){const l=G.join(s,i.name),d=a?`${a}/${i.name}`:i.name;i.isDirectory()&&S2.has(i.name)||(i.isDirectory()?await r(l,d):i.isFile()&&t.push(d))}}catch{}}return await r(e,""),t}const C2="codeyam-rule-state.json",jo=1;function zp(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return pr.createHash("sha256").update(t).digest("hex")}function Yp(e){return ee.join(e,".claude",C2)}async function Up(e){const t=Yp(e);try{const r=await Te.readFile(t,"utf-8"),s=JSON.parse(r);return s.version!==jo?(console.warn(`[ruleState] Unknown version ${s.version}, using empty state`),{version:jo,rules:{}}):s}catch{return{version:jo,rules:{}}}}async function Wp(e,t){const r=Yp(e),s=ee.dirname(r);await Te.mkdir(s,{recursive:!0}),await Te.writeFile(r,JSON.stringify(t,null,2)+`
549
+ `,"utf-8")}async function tl(e,t){const r=await Up(e),s=new Set(t.map(a=>a.filePath));for(const a of Object.keys(r.rules))s.has(a)||delete r.rules[a];for(const a of t){const o=await Te.readFile(a.absolutePath,"utf-8"),i=zp(o),l=r.rules[a.filePath];l?l.contentHash!==i&&(r.rules[a.filePath]={...l,contentHash:i,reviewed:!1}):r.rules[a.filePath]={contentHash:i,reviewed:!1}}return await Wp(e,r),r}async function Zc(e,t,r,s){const a=await Up(e);if(r){const o=ee.join(e,".claude","rules"),i=ee.join(o,t),l=await Te.readFile(i,"utf-8"),d=zp(l);a.rules[t]?(a.rules[t].reviewed=!0,a.rules[t].contentHash=d):a.rules[t]={contentHash:d,reviewed:!0}}else a.rules[t]&&(a.rules[t].reviewed=!1);await Wp(e,a)}function nl(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function Jp(e,t=""){const r=[],s=await Te.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;a.isDirectory()?r.push(...await Jp(ee.join(e,a.name),o)):a.name.endsWith(".md")&&r.push(o)}return r}function oa(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
550
+ `).filter(s=>!(!s.startsWith("+")&&!s.startsWith("-")||s.startsWith("+++")||s.startsWith("---"))).map(s=>s.substring(1).trim());if(t.length===0)return!1;const r=/^(category:\s*\w+)$/;return t.every(s=>r.test(s))}async function k2({request:e}){const t=Ce();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=new URL(e.url),s=r.searchParams.get("action"),a=ee.join(t,".claude","rules");if(s==="recent-changes")return _2(t,a);if(s==="reviewed-status")return P2(t,a);if(s==="audit")return A2(t,a);if(s==="source-files")return T2(t);if(s==="rule-coverage")return M2(t,a);if(s==="rule-diff"){const o=r.searchParams.get("filePath");return o?E2(t,o):Response.json({error:"Missing required parameter: filePath"},{status:400})}if(s==="rules-for-path"){const o=r.searchParams.get("path");return o?$2(a,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await Ba(a),i=[];for(const p of o){const h=ee.join(a,p);try{const m=await Te.readFile(h,"utf-8"),f=await Te.stat(h),{frontmatter:y,body:g}=Xi(m);i.push({filePath:p,content:m,frontmatter:y,body:g,lastModified:f.mtime.toISOString()})}catch{}}i.sort((p,h)=>new Date(h.lastModified).getTime()-new Date(p.lastModified).getTime());let l=i.length>0;if(!l)try{await Te.access(ee.join(t,".claude","codeyam-rule-state.json")),l=!0}catch{}const d=await ss(a),u={};if(d.length>0){const p=await tl(t,d);for(const h of d)u[h.filePath]=nl(p,h.filePath)}return Response.json({memories:i,memoryInitialized:l,reviewedStatus:u})}catch(o){return console.error("[API] Error loading memories:",o),Response.json({error:"Failed to load memories",details:o instanceof Error?o.message:String(o),memoryInitialized:!1},{status:500})}}async function j2(e,t){const r=[];try{const s=t("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const a of s.split(`
551
+ `).filter(Boolean)){const o=a.substring(0,2);let i=a.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const l=o[0],d=o[1];let u=[i];if(i.endsWith("/")&&l==="?"){const p=ee.join(e,i);try{u=(await Jp(p)).map(m=>i+m)}catch{continue}}for(const p of u){if(p.endsWith("/"))continue;const h=p.replace(".claude/rules/","");let m="modified";l==="A"||l==="?"?m="added":l==="D"||d==="D"?m="deleted":(l==="M"||d==="M")&&(m="modified");let f="";try{if(m==="deleted")f=t(`git diff HEAD -- "${p}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(m==="added"&&l==="?"){const y=`${e}/${p}`;try{const g=await Te.readFile(y,"utf-8");f=`diff --git a/${p} b/${p}
552
+ new file mode 100644
553
+ --- /dev/null
554
+ +++ b/${p}
555
+ @@ -0,0 +1,${g.split(`
556
+ `).length} @@
557
+ ${g.split(`
558
+ `).map(x=>"+"+x).join(`
559
+ `)}`}catch{f="(content not available)"}}else f=t(`git diff HEAD -- "${p}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});f.length>5e3&&(f=f.substring(0,5e3)+`
560
+ ... (truncated)`)}catch{f="(diff not available)"}m==="modified"&&oa(f)||r.push({filePath:h,changeType:m,diff:f})}}}catch{}return r}async function _2(e,t){try{const{execSync:r}=await import("child_process"),s=[],a=await ss(t),o={};if(a.length>0){const p=await tl(e,a);for(const h of a)o[h.filePath]=nl(p,h.filePath)}const l=(await j2(e,r)).filter(p=>!o[p.filePath]);l.length>0&&s.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:l});const u=r('git log --format="%H|%aI|%s" --since="60 days ago" -- .claude/rules/ 2>/dev/null || true',{cwd:e,encoding:"utf-8",maxBuffer:10*1024*1024}).split(`
561
+ `).filter(Boolean).slice(0,20);for(const p of u){const[h,m,...f]=p.split("|"),y=f.join("|");if(!h||!m)continue;const g=r(`git diff-tree --no-commit-id --name-status -r ${h} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),x=[];for(const b of g.split(`
562
+ `).filter(Boolean)){const[v,N]=b.split(" ");if(!N||!N.startsWith(".claude/rules/"))continue;const w=N.replace(".claude/rules/","");let C="modified";if(v==="A"?C="added":v==="D"&&(C="deleted"),o[w])continue;let k="";try{k=r(`git show ${h} --format="" -- "${N}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),k.length>5e3&&(k=k.substring(0,5e3)+`
563
+ ... (truncated)`)}catch{k="(diff not available)"}C==="modified"&&oa(k)||x.push({filePath:w,changeType:C,diff:k})}x.length>0&&s.push({commitHash:h.substring(0,8),date:m,message:y,files:x})}return Response.json({changes:s,reviewedStatus:o})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[],reviewedStatus:{}})}}async function E2(e,t){try{const{execSync:r}=await import("child_process"),s=`.claude/rules/${t}`,a=r(`git rev-list --count HEAD -- "${s}" 2>/dev/null || echo 0`,{cwd:e,encoding:"utf-8"}),o=parseInt(a.trim(),10)||0,i=r(`git diff HEAD -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});if(i.trim()){if(oa(i))return Response.json({diff:null});const g=i.length>5e3?i.substring(0,5e3)+`
564
+ ... (truncated)`:i;return Response.json({diff:{diff:g,commitMessage:"Uncommitted changes",date:new Date().toISOString(),isUncommitted:!0,commitCount:o}})}if(r(`git status --porcelain -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim().startsWith("?")){const g=ee.join(e,s);try{const x=await Te.readFile(g,"utf-8"),b=`diff --git a/${s} b/${s}
565
+ new file mode 100644
566
+ --- /dev/null
567
+ +++ b/${s}
568
+ @@ -0,0 +1,${x.split(`
569
+ `).length} @@
570
+ ${x.split(`
571
+ `).map(v=>"+"+v).join(`
572
+ `)}`;return Response.json({diff:{diff:b.length>5e3?b.substring(0,5e3)+`
573
+ ... (truncated)`:b,commitMessage:"New file (untracked)",date:new Date().toISOString(),isUncommitted:!0,commitCount:0}})}catch{}}const u=r(`git log -1 --format="%H|%aI|%s" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim();if(!u)return Response.json({diff:null});const[p,h,...m]=u.split("|"),f=m.join("|");if(!p||!h)return Response.json({diff:null});let y=r(`git show ${p} --format="" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});return y.trim()?oa(y)?Response.json({diff:null}):(y.length>5e3&&(y=y.substring(0,5e3)+`
574
+ ... (truncated)`),Response.json({diff:{diff:y,commitMessage:f,date:h,isUncommitted:!1,commitCount:o}})):Response.json({diff:null})}catch(r){return console.error("[API] Error getting rule diff:",r),Response.json({diff:null})}}async function P2(e,t){try{const r=await ss(t),s={};if(r.length>0){const a=await tl(e,r);for(const o of r)s[o.filePath]=nl(a,o.filePath)}return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function A2(e,t){try{const r=await ss(t),s=await el(e),a=[];for(const o of s){const i=r.filter(l=>Bp(o,l));if(i.length>0){const l=i.reduce((d,u)=>d+u.body.length,0);a.push({filePath:o,matchingRules:i.map(d=>({filePath:d.filePath,patterns:d.frontmatter.paths||[],bodyLength:d.body.length})),totalTextLength:l})}}return a.sort((o,i)=>i.totalTextLength-o.totalTextLength),Response.json({topPaths:a,totalFilesWithCoverage:a.length,allSourceFiles:s})}catch(r){return console.error("[API] Error getting audit data:",r),Response.json({error:"Failed to get audit data",details:r instanceof Error?r.message:String(r)},{status:500})}}async function T2(e){try{const t=await el(e);return Response.json({files:t})}catch(t){return console.error("[API] Error getting source files:",t),Response.json({error:"Failed to get source files",details:t instanceof Error?t.message:String(t)},{status:500})}}async function M2(e,t){try{const[r,s]=await Promise.all([ss(t),el(e)]),a={};for(const o of r)a[o.filePath]=N2(o,s).length;return Response.json({coverage:a})}catch(r){return console.error("[API] Error getting rule coverage:",r),Response.json({error:"Failed to get rule coverage",details:r instanceof Error?r.message:String(r)},{status:500})}}async function $2(e,t){try{const r=await Ba(e),s=[];for(const o of r){const i=ee.join(e,o);try{const l=await Te.readFile(i,"utf-8"),d=await Te.stat(i),{frontmatter:u,body:p}=Xi(l);u.paths&&u.paths.some(h=>Do(t,h,{matchBase:!0}))&&s.push({filePath:o,content:l,frontmatter:u,body:p,lastModified:d.mtime.toISOString()})}catch{}}const a=s.reduce((o,i)=>o+i.body.length,0);return Response.json({rules:s,totalTextLength:a})}catch(r){return console.error("[API] Error getting rules for path:",r),Response.json({error:"Failed to get rules for path",details:r instanceof Error?r.message:String(r)},{status:500})}}async function F2({request:e}){const t=Ce();if(!t)return Response.json({error:"Project root not found"},{status:500});const r=ee.join(t,".claude","rules");try{const s=await e.json(),{action:a,filePath:o,content:i,lastModified:l}=s;if(!o)return Response.json({error:"Missing required field: filePath"},{status:400});if(a==="mark-reviewed")return await Zc(t,o,!0),console.log(`[API] Rule marked as reviewed: ${o}`),Response.json({success:!0,message:"Rule marked as reviewed",filePath:o});if(a==="mark-unreviewed")return await Zc(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const d=ee.normalize(o);if(d.includes("..")||ee.isAbsolute(d))return Response.json({error:"Invalid file path"},{status:400});const u=ee.join(r,d);switch(a){case"create":case"update":return i?(await Te.mkdir(ee.dirname(u),{recursive:!0}),await Te.writeFile(u,i,"utf-8"),console.log(`[API] Memory ${a}d: ${o}`),Response.json({success:!0,message:`Memory ${a}d successfully`,filePath:o})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await Te.unlink(u),console.log(`[API] Memory deleted: ${o}`);const p=ee.dirname(u);try{(await Te.readdir(p)).length===0&&p!==r&&await Te.rmdir(p)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(p){if(p.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw p}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(s){return console.error("[API] Error managing memory:",s),Response.json({error:"Failed to manage memory",details:s instanceof Error?s.message:String(s)},{status:500})}}const D2=Object.freeze(Object.defineProperty({__proto__:null,action:F2,loader:k2},Symbol.toStringTag,{value:"Module"}));async function R2({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await nn()),!r)return ue({error:"Queue not initialized"},{status:500});const s=new URL(e.url),a=s.searchParams.get("queryType");if(!a)return ue({error:"Missing queryType parameter for GET request"},{status:400});if(a==="job"){const i=s.searchParams.get("jobId");if(!i)return ue({error:"Missing jobId parameter for job query"},{status:400});const l=r.getState();if(((o=l.currentlyExecuting)==null?void 0:o.id)===i)return ue({jobId:i,status:"running",job:l.currentlyExecuting});const d=l.jobs.find(p=>p.id===i);if(d){const p=l.jobs.indexOf(d);return ue({jobId:i,status:"queued",position:p,job:d})}const u=r.getJobResult(i);return u?ue({jobId:i,status:u.status==="error"?"failed":"completed",error:u.error}):ue({jobId:i,status:"completed"})}if(a==="full"){const i=r.getState(),l=await Promise.all(i.jobs.map(async u=>{const p=[];if(u.entityShas&&u.entityShas.length>0){const h=u.entityShas.map(f=>Ln(f)),m=await Promise.all(h);p.push(...m.filter(f=>f!==null))}return{id:u.id,type:u.type,commitSha:u.commitSha,projectSlug:u.projectSlug,queuedAt:u.queuedAt,entities:p,filePaths:u.filePaths}}));let d;if(i.currentlyExecuting){const u=i.currentlyExecuting,p=[];if(u.entityShas&&u.entityShas.length>0){const h=u.entityShas.map(f=>Ln(f)),m=await Promise.all(h);p.push(...m.filter(f=>f!==null))}d={id:u.id,type:u.type,commitSha:u.commitSha,projectSlug:u.projectSlug,queuedAt:u.queuedAt,entities:p,filePaths:u.filePaths}}return ue({state:{...i,jobsWithEntities:l,currentlyExecutingWithEntities:d}})}return ue({error:"Unknown queryType"},{status:400})}async function I2({request:e,context:t}){console.log("[Queue API] Received request"),console.log("[Queue API] Context keys:",Object.keys(t||{})),console.log("[Queue API] analysisQueue exists:",!!(t!=null&&t.analysisQueue));let r=t.analysisQueue;if(r||(r=await nn(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),ue({error:"Queue not initialized"},{status:500});const s=await e.json(),{action:a,...o}=s;if(console.log("[Queue API] Action:",a,"Params:",Object.keys(o)),a==="enqueue"){const{jobId:i,completion:l}=r.enqueue(o);return l.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),ue({jobId:i,status:"queued"})}if(a==="resume")return r.resume(),ue({status:"resumed"});if(a==="pause")return r.pause(),ue({status:"paused"});if(a==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?ue({status:"removed",jobId:i}):ue({error:"Job not found in queue"},{status:404}):ue({error:"Missing jobId parameter"},{status:400})}if(a==="clear"){const i=r.clearQueue();return ue({status:"cleared",count:i})}if(a==="reorder"){const{jobId:i,direction:l}=o;return!i||!l?ue({error:"Missing jobId or direction parameter"},{status:400}):l!=="up"&&l!=="down"?ue({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,l)?ue({status:"reordered",jobId:i,direction:l}):ue({error:"Could not reorder job (not found or at boundary)"},{status:400})}return ue({error:"Unknown action"},{status:400})}const O2=Object.freeze(Object.defineProperty({__proto__:null,action:I2,loader:R2},Symbol.toStringTag,{value:"Module"})),L2=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],B2=tt(function(){return Ke(),n(Da,{children:c("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[n("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:c("div",{className:"flex items-center h-full px-6 gap-6",children:[c("div",{className:"flex items-center gap-3 min-w-0",children:[n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),n("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),n("span",{className:"text-xs text-[#626262] font-mono whitespace-nowrap overflow-hidden text-ellipsis min-w-0",children:"codeyam-cli/src/webserver/app/routes/_index.tsx"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[c("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[n("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),n("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),n("button",{className:"px-[15px] py-0 h-[26px] bg-[#005c75] text-white rounded text-xs font-semibold border-none cursor-pointer hover:bg-[#004a5e] transition-colors",children:"Analyze"})]}),c("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[n("span",{className:"leading-[22px]",children:"Next Entity"}),n("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:n("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),n("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:c("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[c("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded bg-[#343434] text-[#efefef] font-semibold h-8",children:["Scenarios",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),c("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",n("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),n("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),c("div",{className:"flex flex-1 gap-0 min-h-0",children:[n("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),n(Ip,{selectedScenario:null,analysis:void 0,entity:{sha:"mock-sha",name:"Dashboard",filePath:"codeyam-cli/src/webserver/app/routes/_index.tsx",entityType:"visual"},viewMode:"screenshot",cacheBuster:Date.now(),hasScenarios:!1,isAnalyzing:!1,projectSlug:null,hasAnApiKey:!0})]})]})})}),z2=Object.freeze(Object.defineProperty({__proto__:null,default:B2,meta:L2},Symbol.toStringTag,{value:"Module"})),Y2=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function U2({request:e}){var t,r;try{const s=await va();if(!s)return ue({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let a=!1;try{const d=await ze();if(d){const{project:u}=await Ie(d);a=((r=(t=u.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const o=Ce()||process.cwd(),i=await wa(o),l=bu(s.projectSlug);return ue({config:s,secrets:{GROQ_API_KEY:i.GROQ_API_KEY||"",ANTHROPIC_API_KEY:i.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:i.OPENAI_API_KEY||""},versionInfo:l,simulationsEnabled:a,error:null})}catch(s){return console.error("Failed to load config:",s),ue({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function W2(e){if(!e||!e.trim())return;const t=e.trim().split(/\s+/);if(t.length===0)return;const r=t[0],s=t.length>1?t.slice(1):void 0;return{command:r,args:s}}async function J2({request:e}){try{const t=await e.formData(),r=t.get("universalMocks"),s=t.get("startCommands"),a=t.get("groqApiKey"),o=t.get("anthropicApiKey"),i=t.get("openAiApiKey"),l=t.get("pathsToIgnore"),d=t.get("memorySettings");let u;if(r)try{u=JSON.parse(r)}catch{return ue({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let p;if(s)try{p=JSON.parse(s)}catch{return ue({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let h;l&&(h=l.split(",").map(x=>x.trim()).map(x=>x.startsWith('"')&&x.endsWith('"')||x.startsWith("'")&&x.endsWith("'")?x.slice(1,-1):x).filter(x=>x.length>0));let m;if(d)try{m=JSON.parse(d)}catch{return ue({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(p){const x=await va();x!=null&&x.webapps&&(f=x.webapps.map((b,v)=>{if(p[v]!==void 0){const N=W2(p[v]);return{...b,startCommand:N}}return b}))}if(!await uu({universalMocks:u,pathsToIgnore:h,webapps:f,memory:m}))return ue({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let g=!1;if(a!==void 0||o!==void 0||i!==void 0){const x=Ce()||process.cwd(),b=await wa(x);g=a!==void 0&&a!==(b.GROQ_API_KEY||"")||o!==void 0&&o!==(b.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(b.OPENAI_API_KEY||""),await a0(x,{...b,GROQ_API_KEY:a||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return ue({success:!0,error:null,requiresRestart:g})}catch(t){return console.log("[Settings Action] Failed to save config:",t),ue({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function Xc(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function ed({mock:e,onSave:t,onCancel:r}){const[s,a]=E(e.entityName),[o,i]=E(e.filePath),[l,d]=E(e.content);return c("div",{className:"space-y-3",children:[c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),n("input",{type:"text",value:s,onChange:p=>a(p.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., determineDatabaseType"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),n("input",{type:"text",value:o,onChange:p=>i(p.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., packages/database/src/lib/kysely/db.ts"})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:l,onChange:p=>d(p.target.value),rows:6,className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]",placeholder:"e.g., function determineDatabaseType() { return 'postgresql' }"})]}),c("div",{className:"flex gap-2 justify-end",children:[n("button",{type:"button",onClick:r,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),n("button",{type:"button",onClick:()=>{if(!s.trim()||!o.trim()||!l.trim()){alert("All fields are required");return}t({entityName:s,filePath:o,content:l})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function H2(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const V2=tt(function(){var je,te,ke,Z,pe;const{config:t,secrets:r,versionInfo:s,simulationsEnabled:a,error:o}=lt(),i=Uh(),l=Ke(),d=Ut(),[u,p]=E(a?"project-metadata":"memory");Wt({source:"settings-page"});const[h,m]=E((t==null?void 0:t.universalMocks)||[]),[f,y]=E(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[g,x]=E(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[b,v]=E((r==null?void 0:r.GROQ_API_KEY)||""),[N,w]=E((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[C,k]=E((r==null?void 0:r.OPENAI_API_KEY)||""),[j,A]=E(!1),[_,M]=E(!1),[T,D]=E(!1),[R,L]=E(!1),[U,W]=E(!1),[V,F]=E(!1),[Y,P]=E(null),[O,S]=E(!1),[$,I]=E({}),[K,q]=E(((je=t==null?void 0:t.memory)==null?void 0:je.conversationReflection)??!0),[J,z]=E(((te=t==null?void 0:t.memory)==null?void 0:te.ruleMaintenance)??!0),[B,H]=E(((ke=t==null?void 0:t.memory)==null?void 0:ke.promptModel)??"haiku");se(()=>{var ie,de,he,_e;if(t){m(t.universalMocks||[]);const ye=(t.pathsToIgnore||[]).join(", ");y(ye),x(ye);const Re={};(ie=t.webapps)==null||ie.forEach((Je,bt)=>{Je.startCommand&&(Re[bt]=Xc(Je.startCommand))}),I(Re),q(((de=t.memory)==null?void 0:de.conversationReflection)??!0),z(((he=t.memory)==null?void 0:he.ruleMaintenance)??!0),H(((_e=t.memory)==null?void 0:_e.promptModel)??"haiku")}r&&(v(r.GROQ_API_KEY||""),w(r.ANTHROPIC_API_KEY||""),k(r.OPENAI_API_KEY||""))},[t,r]),se(()=>{if(i!=null&&i.success){L(!0);const ie=setTimeout(()=>L(!1),3e3);return()=>clearTimeout(ie)}},[i]),se(()=>{if(l.state==="idle"&&l.data&&!V){console.log("[Settings] Fetcher data:",l.data);const ie=l.data;if(ie.success){console.log("[Settings] Save successful, revalidating..."),L(!0),F(!0),(f!==g||ie.requiresRestart)&&W(!0),d.revalidate();const de=setTimeout(()=>{L(!1),F(!1)},3e3);return()=>clearTimeout(de)}}},[l.state,l.data,V,d,f,g]);const re=ie=>{ie.preventDefault();const de=new FormData(ie.currentTarget);de.set("universalMocks",JSON.stringify(h)),de.set("startCommands",JSON.stringify($)),de.set("memorySettings",JSON.stringify({conversationReflection:K,ruleMaintenance:J,promptModel:B})),console.log("[Settings] Submitting form data:",{universalMocks:de.get("universalMocks"),startCommands:de.get("startCommands"),openAiApiKey:de.get("openAiApiKey")?"***":"(empty)"}),l.submit(de,{method:"post"})},ae=ie=>{m([...h,ie]),S(!1)},X=(ie,de)=>{const he=[...h];he[ie]=de,m(he),P(null)},oe=ie=>{m(h.filter((de,he)=>he!==ie))};if(o)return c("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[n("header",{className:"mb-6 pb-4 border-b border-gray-200",children:n("div",{className:"flex justify-between items-center",children:n("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:n("p",{className:"text-red-700",children:o})})]});const me=[{id:"project-metadata",label:"Project Metadata"},{id:"ai-provider",label:"AI Provider Configuration"},{id:"commands",label:"Commands"},{id:"paths-to-ignore",label:"Paths To Ignore"},{id:"universal-mocks",label:"Universal Mocks"},{id:"memory",label:"Memory"},{id:"current-configuration",label:"Current Configuration"}],ve=a?me:me.filter(ie=>ie.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[c("div",{className:"mb-8 flex justify-between items-start",children:[c("div",{children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),n("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),n("button",{type:"submit",form:"settings-form",disabled:l.state==="submitting",className:"px-6 py-2 bg-[#005C75] text-white border-none rounded text-sm font-medium cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 hover:bg-[#004a5d] whitespace-nowrap",children:l.state==="submitting"?"Saving...":"Save Settings"})]}),(R||U||(i==null?void 0:i.error)||l.data&&typeof l.data=="object"&&"error"in l.data)&&c("div",{className:"mb-4 space-y-3",children:[R&&n("div",{className:"text-emerald-600 text-sm font-medium bg-emerald-50 border border-emerald-200 rounded px-4 py-2",children:"Settings saved successfully!"}),U&&c("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[n("div",{children:"Settings changed. Please restart CodeYam for changes to take effect:"}),c("div",{className:"flex items-center gap-2 mt-1",children:[n("code",{className:"bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"}),n(xt,{content:"codeyam stop && codeyam",className:"px-2 py-1 text-xs bg-amber-200 hover:bg-amber-300 text-amber-800 rounded border-none transition-colors"})]})]}),(i==null?void 0:i.error)&&n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:i.error}),(()=>{if(l.data&&typeof l.data=="object"&&"error"in l.data){const ie=l.data;return typeof ie.error=="string"?n("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:ie.error}):null}return null})()]}),c("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8 items-start",children:[n("nav",{className:"w-full lg:w-64 flex-shrink-0",children:n("ul",{className:"flex lg:flex-col overflow-x-auto gap-1",children:ve.map(ie=>n("li",{children:n("button",{type:"button",onClick:()=>p(ie.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${u===ie.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:ie.label})},ie.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:c("form",{id:"settings-form",onSubmit:re,className:"space-y-6",children:[u==="project-metadata"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),c("div",{className:"mb-6",children:[n("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-3",children:t.webapps.map((ie,de)=>{var he;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:ie.path==="."?"Root":ie.path})]}),ie.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:ie.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:ie.framework})]}),ie.startCommand&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",c("span",{className:"text-gray-900 font-mono text-xs",children:[ie.startCommand.command," ",(he=ie.startCommand.args)==null?void 0:he.join(" ")]})]})]})},de)})}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"}),n("p",{className:"mt-2 text-sm text-gray-600",children:"Web applications are detected during initialization. To modify, edit `.codeyam/config.json` or re-run `codeyam init`."})]})]}),u==="ai-provider"&&c("div",{children:[n("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure API keys for AI-powered analysis. Choose the provider that best fits your needs."}),c("div",{className:"space-y-6",children:[c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Lightning-fast inference with industry-leading speed. Groq's LPU architecture delivers exceptional performance for real-time AI applications with competitive pricing."}),c("div",{className:"flex flex-wrap gap-2 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:j?"text":"password",id:"groqApiKey",name:"groqApiKey",value:b,onChange:ie=>v(ie.target.value),placeholder:"gsk_...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>A(!j),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:j?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Advanced reasoning and coding capabilities with superior context understanding. Claude excels at complex analysis tasks and provides highly accurate results with detailed explanations."}),c("div",{className:"flex flex-wrap gap-2 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:_?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:N,onChange:ie=>w(ie.target.value),placeholder:"sk-ant-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>M(!_),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:_?"Hide":"Show"})]})]})]}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:c("div",{children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),n("p",{className:"text-sm text-gray-600 mb-3",children:"Industry-standard AI with broad capabilities and extensive ecosystem. GPT models offer reliable performance across diverse tasks with good balance of speed and quality."}),c("div",{className:"flex flex-wrap gap-2 text-xs",children:[c("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[n("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),c("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),c("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[n("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),c("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),c("div",{className:"relative",children:[n("input",{type:T?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:C,onChange:ie=>k(ie.target.value),placeholder:"sk-...",className:"w-full px-3 py-2 pr-24 border border-gray-300 rounded text-sm focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("button",{type:"button",onClick:()=>D(!T),className:"absolute right-2 top-1/2 -translate-y-1/2 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 focus:outline-none cursor-pointer",children:T?"Hide":"Show"})]})]})]})]})]}),u==="commands"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),t!=null&&t.webapps&&t.webapps.length>0?n("div",{className:"space-y-4",children:t.webapps.map((ie,de)=>c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[c("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:ie.path==="."?"Root":ie.path}),n("div",{className:"text-sm text-gray-600",children:ie.framework})]}),c("div",{children:[n("label",{htmlFor:`startCommand-${de}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${de}`,name:`startCommand-${de}`,value:$[de]||"",onChange:he=>I({...$,[de]:he.target.value}),placeholder:"e.g., pnpm dev --port $PORT",className:"w-full px-3 py-2 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-1 focus:ring-[#005C75]"}),n("p",{className:"mt-2 text-xs text-gray-500",children:"Use $PORT as a placeholder for the dynamic port number"})]})]},de))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),u==="paths-to-ignore"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),n("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:f,onChange:ie=>y(ie.target.value),placeholder:"e.g., __tests__, \\.test\\.ts$, ^background (no quotes needed)",className:"w-full px-3 py-3 border border-gray-300 rounded text-sm font-mono focus:outline-none focus:border-[#005C75] focus:ring-2 focus:ring-[#005C75]/10"}),c("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",n("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),n("br",{}),n("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),u==="universal-mocks"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),n("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),h.length===0?c("div",{className:"mb-4",children:[n("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),n("button",{type:"button",onClick:()=>S(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):n("div",{className:"space-y-3",children:h.map((ie,de)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:Y===de?n(ed,{mock:ie,onSave:he=>X(de,he),onCancel:()=>P(null)}):n(we,{children:c("div",{className:"flex justify-between items-start mb-2",children:[c("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:ie.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:ie.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:ie.content})]}),c("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>P(de),className:"px-3 py-1 bg-teal-600 text-white border-none rounded text-sm cursor-pointer hover:bg-teal-700",children:"Edit"}),n("button",{type:"button",onClick:()=>oe(de),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},de))}),h.length>0&&n("button",{type:"button",onClick:()=>S(!0),className:"mt-4 px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}),u==="memory"&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Memory"}),n("p",{className:"text-sm text-gray-600 mb-6",children:"Configure how CodeYam reflects on conversations and maintains rules between sessions."}),c("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:c("div",{className:"flex items-start justify-between",children:[c("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Conversation Reflection"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent reviews the session for architectural decisions, tribal knowledge, confusion, or corrections that future sessions would benefit from knowing. It creates or updates Claude Rules based on what it learns."})]}),n("button",{type:"button",role:"switch","aria-checked":K,onClick:()=>q(!K),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${K?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${K?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:c("div",{className:"flex items-start justify-between",children:[c("div",{className:"flex-1 mr-4",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Rule Maintenance"}),n("p",{className:"text-sm text-gray-600",children:"After each conversation, an agent checks if any existing Claude Rules have become stale based on recent code changes. It reviews the rule content against file diffs and updates rules that are out of date."})]}),n("button",{type:"button",role:"switch","aria-checked":J,onClick:()=>z(!J),className:`relative inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${J?"bg-[#005C75]":"bg-gray-200"}`,children:n("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${J?"translate-x-5":"translate-x-0"}`})})]})}),c("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Memory Prompt Model"}),n("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the Claude model used for conversation reflection and rule maintenance tasks."}),n("div",{className:"space-y-3",children:[{value:"haiku",label:"Haiku",badge:"Default, Recommended",description:"Fastest and cheapest. Good for routine reflection tasks."},{value:"sonnet",label:"Sonnet",badge:null,description:"Balanced speed and quality. Better at nuanced rule writing."},{value:"opus",label:"Opus",badge:null,description:"Highest quality. Best for complex architectural decisions. Costs significantly more."}].map(ie=>c("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${B===ie.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:ie.value,checked:B===ie.value,onChange:()=>H(ie.value),className:"mt-1 accent-[#005C75]"}),c("div",{children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:ie.label}),ie.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:ie.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:ie.description})]})]},ie.value))})]})]})]}),u==="current-configuration"&&c("div",{className:"space-y-6",children:[t&&c("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:c("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",n("span",{className:"text-gray-900",children:t.packageManager})]})]})}),t.webapps&&t.webapps.length>0&&c("div",{children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),n("div",{className:"space-y-3",children:t.webapps.map((ie,de)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:ie.path==="."?"Root":ie.path})]}),ie.appDirectory&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:ie.appDirectory})]}),c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:ie.framework})]}),ie.startCommand&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:Xc(ie.startCommand)})]})]})},de))})]})]}),s&&c("div",{className:"mt-6",children:[n("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:c("div",{className:"space-y-2 text-sm",children:[s.webserverVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",n("span",{className:"text-gray-900 font-mono",children:s.webserverVersion.version||"unknown"})]}),s.templateVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",n("span",{className:"font-mono text-gray-900",children:s.templateVersion.version||((Z=s.templateVersion.gitCommit)==null?void 0:Z.slice(0,7))||"unknown"}),s.templateVersion.buildTimestamp&&c("span",{className:"text-gray-500 ml-2",children:["(built"," ",H2(s.templateVersion.buildTimestamp),")"]})]}),s.cachedAnalyzerVersion&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"font-mono text-gray-900",children:s.cachedAnalyzerVersion.version||((pe=s.cachedAnalyzerVersion.gitCommit)==null?void 0:pe.slice(0,7))||"unknown"}),s.isCacheStale?n("span",{className:"ml-2 px-2 py-0.5 bg-amber-100 text-amber-800 rounded text-xs",children:"Stale - will update on next analysis"}):n("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!s.cachedAnalyzerVersion&&(t==null?void 0:t.projectSlug)&&c("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",n("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),O&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:c("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[n("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),n(ed,{mock:{entityName:"",filePath:"",content:""},onSave:ae,onCancel:()=>S(!1)})]})})]})})}),K2=Object.freeze(Object.defineProperty({__proto__:null,action:J2,default:V2,loader:U2,meta:Y2},Symbol.toStringTag,{value:"Module"}));async function G2({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=Ce();if(!r)return new Response("Project root not found",{status:500});const a=ee.extname(t)!==""?t:`${t}.html`,o=ee.join(r,".codeyam","captures","static",a);try{await Te.access(o);let i=await Te.readFile(o);const l=ee.extname(o).toLowerCase();let d="application/octet-stream";if(l===".html"){d="text/html";let u=i.toString("utf-8");const p=u.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(p)try{const m=p[1].match(/=\s*(\{[\s\S]*\})/);if(m){const f=JSON.parse(m[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const y=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;u=u.replace(p[0],y)}}catch(h){console.error("[Static] Failed to parse Remix context:",h)}i=Buffer.from(u,"utf-8")}else l===".js"||l===".mjs"?d="application/javascript":l===".css"?d="text/css":l===".json"?d="application/json":l===".png"?d="image/png":l===".jpg"||l===".jpeg"?d="image/jpeg":l===".svg"?d="image/svg+xml":l===".woff"?d="font/woff":l===".woff2"?d="font/woff2":l===".ttf"&&(d="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const q2=Object.freeze(Object.defineProperty({__proto__:null,loader:G2},Symbol.toStringTag,{value:"Module"}));function Q2(e,t,r=10){var d;const s=new Map,a=u=>u.entityType==="visual"||u.entityType==="library";for(const u of e)a(u)&&s.set(u.sha,{entity:u,depth:0});const o=new Map;for(const u of t){const p=(d=u.metadata)==null?void 0:d.importedBy;if(p)for(const h of Object.keys(p))for(const m of Object.keys(p[h])){const{shas:f}=p[h][m];for(const y of f)o.has(u.sha)||o.set(u.sha,new Set),o.get(u.sha).add(y)}}const i=[],l=new Set;for(const u of e)i.push({sha:u.sha,depth:0}),l.add(u.sha);for(;i.length>0;){const{sha:u,depth:p}=i.shift();if(p>=r)continue;const h=o.get(u);if(h)for(const m of h){if(l.has(m))continue;l.add(m);const f=t.find(y=>y.sha===m);if(f){if(a(f)){const y=p+1,g=s.get(m);(!g||y<g.depth)&&s.set(m,{entity:f,depth:y})}i.push({sha:m,depth:p+1})}}}return Array.from(s.values()).sort((u,p)=>u.depth!==p.depth?u.depth-p.depth:u.entity.name.localeCompare(p.entity.name))}function ia(e){const t=new Map;for(const s of e)t.has(s.name)||t.set(s.name,[]),t.get(s.name).push(s);const r=[];for(const s of t.values())if(s.length===1)r.push(s[0]);else{const a=s.sort((o,i)=>{var u,p;const l=((u=o.metadata)==null?void 0:u.editedAt)||o.createdAt||"";return(((p=i.metadata)==null?void 0:p.editedAt)||i.createdAt||"").localeCompare(l)});r.push(a[0])}return r}function Hp(e,t){const r=new Map,s=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&s.add(a.oldPath);for(const a of e){const o=t.filter(d=>d.filePath===a.path||a.status==="renamed"&&a.oldPath&&d.filePath===a.oldPath),i=o.filter(d=>{var u,p;return s.has(d.filePath)&&((u=d.metadata)==null?void 0:u.isUncommitted)&&!((p=d.metadata)!=null&&p.isSuperseded)}),l=ia(i);r.set(a.path,{status:a,entities:o,editedEntities:l})}return r}function Z2(e,t,r){const s=new Map;if(!r){for(const o of e)if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const i=t.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),l=ia(i);s.set(o.path,{status:o,entities:l})}return s}const a=new Map;for(const o of r.fileComparisons){const i=new Set;for(const l of o.newEntities)i.add(l.name);for(const l of o.modifiedEntities)i.add(l.name);for(const l of o.deletedEntities)i.add(l.name);i.size>0&&a.set(o.filePath,i)}for(const o of e){const i=a.get(o.path);if(o.status==="deleted")s.set(o.path,{status:o,entities:[]});else{const l=i?t.filter(u=>(u.filePath===o.path||o.status==="renamed"&&o.oldPath&&u.filePath===o.oldPath)&&i.has(u.name)):[],d=ia(l);s.set(o.path,{status:o,entities:d})}}return s}function X2(e,t){const r=new Map,s=Vp(e,t);for(const a of s){const i=Q2([a],t).filter(({depth:l})=>l>0);r.set(a.sha,i)}return r}function Vp(e,t){const r=new Set(e.map(a=>a.path));for(const a of e)a.status==="renamed"&&a.oldPath&&r.add(a.oldPath);const s=t.filter(a=>{var o,i;return r.has(a.filePath)&&((o=a.metadata)==null?void 0:o.isUncommitted)&&!((i=a.metadata)!=null&&i.isSuperseded)});return ia(s)}function ek({recentSimulations:e}){const t=fe(()=>{const r=new Map;return e.forEach(s=>{const a=s.entitySha,o=r.get(a);o?o.push(s):r.set(a,[s])}),Array.from(r.entries()).map(([s,a])=>({entitySha:s,entityName:a[0].entityName,scenarios:a}))},[e]);return c("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:e.length>0?`Latest ${e.length} captured screenshot${e.length!==1?"s":""}`:"No simulations captured yet"})]})}),e.length>0?c(we,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>c("div",{children:[c("div",{className:"mb-3 flex items-center gap-2",children:[n("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:n(Wr,{size:16,style:{color:"#8B5CF6"}})}),n(Ee,{to:`/entity/${r.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:r.entityName})]}),n("div",{className:"grid grid-cols-4 gap-3",children:r.scenarios.map((s,a)=>n(Ee,{to:s.scenarioId?`/entity/${s.entitySha}/scenarios/${s.scenarioId}`:`/entity/${s.entitySha}`,className:"aspect-4/3 border border-gray-200 rounded-lg overflow-hidden bg-gray-50 transition-all flex items-center justify-center hover:scale-105",onMouseEnter:o=>{o.currentTarget.style.borderColor="#005C75",o.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:o=>{o.currentTarget.style.borderColor="#E5E7EB",o.currentTarget.style.boxShadow="none"},title:s.scenarioName,children:n(ut,{screenshotPath:s.screenshotPath,alt:s.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},s.scenarioId||`${s.entitySha}-${a}`))})]},r.entitySha))}),n(Ee,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:r=>r.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:r=>r.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):c("div",{className:"py-12 px-6 text-center rounded-lg w-full flex flex-col items-center justify-center min-h-50 border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:n(Wr,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),c("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(Ee,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(Ee,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const tk="/assets/codeyam-name-logo-CvKwUgHo.svg",nk=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function rk({request:e,context:t}){var r,s,a,o,i;try{const l=await ze();if(l){const{project:R}=await Ie(l),L=((r=R.metadata)==null?void 0:r.editorMode)??!1;if(!(((a=(s=R.metadata)==null?void 0:s.labs)==null?void 0:a.simulations)??!1)||L)return Wh("/memory")}const d=t.analysisQueue,u=d?d.getState():{paused:!1,jobs:[]},[p,h]=await Promise.all([Yn(),fr()]),m=xr(),f=p?Hp(m,p):new Map,y=Array.from(f.entries()).sort((R,L)=>R[0].localeCompare(L[0])),g=(p==null?void 0:p.length)||0,x=(p==null?void 0:p.filter(R=>R.entityType==="visual").length)||0,b=(p==null?void 0:p.filter(R=>R.entityType==="library").length)||0,v=p?Vp(m,p):[],N=v.length,w=(p==null?void 0:p.filter(R=>(R.analyses??[]).filter(L=>L.scenarios&&L.scenarios.length>0).length>0).length)||0,C=(p==null?void 0:p.reduce((R,L)=>{var W,V,F;const U=((F=(V=(W=L.analyses)==null?void 0:W[0])==null?void 0:V.scenarios)==null?void 0:F.length)||0;return R+U},0))||0,k=(p==null?void 0:p.reduce((R,L)=>{var V,F;const W=(((F=(V=L.analyses)==null?void 0:V[0])==null?void 0:F.scenarios)||[]).filter(Y=>{var P,O;return(O=(P=Y.metadata)==null?void 0:P.screenshotPaths)==null?void 0:O[0]}).length;return R+W},0))||0,j=[];p==null||p.forEach(R=>{var U;const L=(U=R.analyses)==null?void 0:U[0];L!=null&&L.scenarios&&L.scenarios.filter(V=>{var F;return!((F=V.metadata)!=null&&F.sameAsDefault)}).forEach(V=>{var Y,P;const F=(P=(Y=V.metadata)==null?void 0:Y.screenshotPaths)==null?void 0:P[0];F&&j.push({entitySha:R.sha,entityName:R.name,scenarioId:V.id,scenarioName:V.name,screenshotPath:F,createdAt:L.createdAt||""})})}),j.sort((R,L)=>new Date(L.createdAt).getTime()-new Date(R.createdAt).getTime());const A=j.slice(0,16),_=(p==null?void 0:p.filter(R=>R.entityType==="visual").filter(R=>{var W,V;const L=(W=R.analyses)==null?void 0:W[0];return!((V=L==null?void 0:L.scenarios)==null?void 0:V.some(F=>{var Y,P;return(P=(Y=F.metadata)==null?void 0:Y.screenshotPaths)==null?void 0:P[0]}))}).slice(0,8))||[],M=(o=h==null?void 0:h.metadata)==null?void 0:o.currentRun,T=((i=M==null?void 0:M.currentEntityShas)==null?void 0:i.length)||0,D=u.jobs.length||0;return ue({stats:{totalEntities:g,visualEntities:x,libraryEntities:b,uncommittedEntities:N,entitiesWithAnalyses:w,totalScenarios:C,capturedScreenshots:k,currentlyAnalyzing:T,filesOnQueue:D},uncommittedFiles:y,uncommittedEntitiesList:v,recentSimulations:A,visualEntitiesForSimulation:_,projectSlug:l,queueState:u,currentCommit:h})}catch(l){return console.error("Failed to load dashboard data:",l),ue({stats:{totalEntities:0,visualEntities:0,libraryEntities:0,uncommittedEntities:0,entitiesWithAnalyses:0,totalScenarios:0,capturedScreenshots:0,currentlyAnalyzing:0,filesOnQueue:0},uncommittedFiles:[],uncommittedEntitiesList:[],recentSimulations:[],visualEntitiesForSimulation:[],projectSlug:null,queueState:{paused:!1,jobs:[]},currentCommit:null,error:"Failed to load dashboard data"})}}const sk=tt(function(){var Y,P;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:s,recentSimulations:a,visualEntitiesForSimulation:o,projectSlug:i,queueState:l,currentCommit:d}=lt(),u=Ke(),p=Ut(),{showToast:h}=pi();Wt({source:"dashboard"});const[m,f]=E(new Set),[y,g]=E(null),[x,b]=E(!1),[v,N]=E(!1),{lastLine:w,isCompleted:C}=Xt(i,!!y),{simulatingEntity:k,scenarios:j,scenarioStatuses:A,allScenariosCaptured:_}=fe(()=>{var z,B;const O={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return O;const S=o==null?void 0:o.find(H=>H.sha===y);if(!S)return O;const $=(z=S.analyses)==null?void 0:z[0],I=($==null?void 0:$.scenarios)||[],K=((B=$==null?void 0:$.status)==null?void 0:B.scenarios)||[],q=K.filter(H=>H.screenshotFinishedAt).length,J=I.length>0&&q===I.length;return{simulatingEntity:S,scenarios:I,scenarioStatuses:K,allScenariosCaptured:J}},[y,o]);se(()=>{(C||_)&&g(null)},[C,_]);const M=(Y=d==null?void 0:d.metadata)==null?void 0:Y.currentRun,T=new Set((M==null?void 0:M.currentEntityShas)||[]),D=new Set(l.jobs.flatMap(O=>O.entityShas||[])),R=new Set(((P=l.currentlyExecuting)==null?void 0:P.entityShas)||[]),L=s.filter(O=>O.entityType==="visual"||O.entityType==="library"),U=L.filter(O=>!T.has(O.sha)&&!D.has(O.sha)&&!R.has(O.sha)),W=()=>{if(U.length===0){h("All entities are already queued or analyzing","info",3e3);return}const O=U.map(S=>S.sha);N(!0),h(`Starting analysis for ${U.length} entities...`,"info",3e3),u.submit({entityShas:O.join(",")},{method:"post",action:"/api/analyze"})};se(()=>{if(u.state==="idle"&&u.data){const O=u.data;O.success?(console.log("[Analyze All] Success:",O.message),h(`Analysis started for ${O.entityCount} entities in ${O.fileCount} files. Watch the logs for progress.`,"success",6e3),N(!1)):O.error&&(console.error("[Analyze All] Error:",O.error),h(`Error: ${O.error}`,"error",8e3),N(!1))}},[u.state,u.data,h]);const V=O=>{f(S=>{const $=new Set(S);return $.has(O)?$.delete(O):$.add(O),$})},F=[{label:"Total Entities",value:t.totalEntities,iconType:"folder",link:"/files",color:"#005C75",tooltip:"In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested."},{label:"Analyzed Entities",value:t.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:t.visualEntities,iconType:"image",link:"/files?entityType=visual",color:"#8B5CF6",tooltip:"React components and visual elements that can be rendered and captured as screenshots."},{label:"Library Functions",value:t.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return n("div",{className:"bg-cygray-10 min-h-screen",children:c("div",{className:"px-20 pt-8 pb-12",children:[c("header",{className:"mb-8 flex justify-between items-center",children:[c("div",{className:"flex items-center gap-4",children:[n("img",{src:tk,alt:"CodeYam",className:"h-3.5"}),n("span",{className:"text-gray-400 text-sm",children:"|"}),n("h1",{className:"text-sm font-mono font-normal text-gray-400 m-0",children:i?i.replace(/-/g," ").replace(/\b\w/g,O=>O.toUpperCase()):"Project"})]}),p.state==="loading"&&n("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),n("div",{className:"flex items-center justify-between gap-3",children:F.map((O,S)=>n(Ee,{to:O.link,className:"flex-1 bg-white rounded-xl border border-gray-200 overflow-hidden flex transition-all hover:shadow-lg no-underline cursor-pointer",style:{borderLeft:`4px solid ${O.color}`},children:c("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[c("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[c("div",{className:"flex items-center gap-1.5 group relative",children:[n("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:O.label}),c("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[n("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[O.tooltip,n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:O.color},children:"View All →"})]}),c("div",{className:"flex flex-col gap-2",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${O.color}15`},children:[O.iconType==="folder"&&n(xm,{size:20,style:{color:O.color}}),O.iconType==="check"&&n(ni,{size:20,style:{color:O.color}}),O.iconType==="image"&&n(Wr,{size:20,style:{color:O.color}}),O.iconType==="code-xml"&&n(bm,{size:20,style:{color:O.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:O.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:O.color},children:"View All →"})]})]})},S))}),c("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[c("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[c("div",{className:"flex justify-between items-start mb-5",children:[c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),n("p",{className:"text-sm text-gray-500 m-0",children:r.length>0?`${r.length} file${r.length!==1?"s":""} with ${s.length} uncommitted entit${s.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),L.length>0&&n("button",{onClick:W,disabled:u.state!=="idle"||v||U.length===0,className:"px-5 py-2.5 text-white border-none rounded-lg text-sm font-semibold cursor-pointer transition-all hover:-translate-y-px disabled:bg-gray-400 disabled:cursor-not-allowed disabled:translate-y-0",style:{backgroundColor:"#005C75"},onMouseEnter:O=>O.currentTarget.style.backgroundColor="#004560",onMouseLeave:O=>O.currentTarget.style.backgroundColor="#005C75",children:u.state!=="idle"||v?"Starting analysis...":U.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([O,S])=>{const $=m.has(O),I=S.editedEntities||[];return c("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[n("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>V(O),role:"button",tabIndex:0,children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:$?"▼":"▶"}),c("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[c("g",{clipPath:"url(#clip0_784_10666)",children:[n("path",{d:"M0 2.55857C0 1.14551 1.14551 0 2.55857 0H8.73194L12 3.3616V13.4414C12 14.8545 10.8545 16 9.44143 16H2.55857C1.14551 16 0 14.8545 0 13.4414V2.55857Z",fill:"#DDDDFE"}),n("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),n("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),n("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),n("defs",{children:n("clipPath",{id:"clip0_784_10666",children:n("rect",{width:"12",height:"16",fill:"white"})})})]}),c("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:O}),c("span",{className:"text-xs text-gray-500",children:[I.length," entit",I.length!==1?"ies":"y"]})]})]})}),$&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:I.length>0?I.map(K=>{const q=T.has(K.sha),J=D.has(K.sha)||R.has(K.sha);return c(Ee,{to:`/entity/${K.sha}`,className:"flex items-center gap-4 p-4 bg-white border border-gray-200 rounded-lg no-underline transition-all hover:shadow-md hover:-translate-y-0.5",style:{borderColor:"inherit"},onMouseEnter:z=>z.currentTarget.style.borderColor="#005C75",onMouseLeave:z=>z.currentTarget.style.borderColor="inherit",children:[c("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:K.entityType==="visual"?"#8B5CF615":K.entityType==="library"?"#6366F1":"#EC4899"},children:[K.entityType==="visual"&&n(Wr,{size:16,style:{color:"#8B5CF6"}}),K.entityType==="library"&&n(Id,{size:16,className:"text-white"}),K.entityType==="other"&&n(vm,{size:16,className:"text-white"})]}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:K.name}),K.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),K.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),K.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),K.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:K.description})]}),c("div",{className:"flex items-center gap-2 shrink-0",children:[q&&c("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[n(Ot,{size:14,className:"animate-spin"}),"Analyzing..."]}),!q&&J&&n("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!q&&!J&&n("button",{onClick:z=>{z.preventDefault(),z.stopPropagation(),h(`Starting analysis for ${K.name}...`,"info",3e3),u.submit({entityShas:K.sha},{method:"post",action:"/api/analyze"})},disabled:u.state!=="idle",className:"px-3 py-1.5 text-white border-none rounded text-xs font-medium cursor-pointer transition-all disabled:bg-gray-400 disabled:cursor-not-allowed",style:{backgroundColor:"#005C75"},onMouseEnter:z=>z.currentTarget.style.backgroundColor="#004560",onMouseLeave:z=>z.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},K.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},O)})}):c("div",{className:"py-12 px-6 text-center flex flex-col items-center rounded-lg min-h-50 justify-center border border-dashed",style:{backgroundColor:"#F2F7F8",borderColor:"#BBCCD3"},children:[n("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:c("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),n("polyline",{points:"14 2 14 8 20 8"}),n("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),n("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),n("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!y&&n(ek,{recentSimulations:a}),y&&c("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:c("div",{children:[n("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),n("p",{className:"text-sm text-gray-500 m-0",children:a.length>0?`Latest ${a.length} captured screenshot${a.length!==1?"s":""}`:"No simulations captured yet"})]})}),y&&c("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[k&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:c("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(St,{type:"visual"})}),c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",k.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:k.filePath})]})]})}),_?c("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[n("span",{className:"text-lg",children:"✅"}),c("span",{children:["Complete (",j.length," scenario",j.length!==1?"s":"",")"]})]}):w?c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Ot,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:w,children:w}),i&&n("button",{onClick:()=>b(!0),className:"px-2 py-1.5 bg-gray-500 text-white border-none rounded-md text-[13px] font-medium cursor-pointer transition-all whitespace-nowrap self-start hover:bg-gray-600 hover:-translate-y-px",title:"View analysis logs",children:"📋 Logs"})]}):u.state!=="idle"?c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Ot,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):c("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(Ot,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),j.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:j.slice(0,8).map((O,S)=>{var B,H,re;const $=(B=k==null?void 0:k.analyses)==null?void 0:B[0],I=La(O,$==null?void 0:$.status,void 0,y||void 0,void 0),K=(re=(H=O.metadata)==null?void 0:H.screenshotPaths)==null?void 0:re[0],q=I.isCaptured,J=I.status==="capturing"||I.status==="starting",z=I.hasError;return q?n(Ee,{to:`/entity/${y}`,className:"w-20 h-15 border-2 border-gray-200 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center no-underline hover:border-blue-600 hover:scale-105 hover:shadow-md",children:n(ut,{screenshotPath:K,alt:O.name,title:O.name,className:"max-w-full max-h-full object-contain object-center"})},S):z?n("div",{className:"w-20 h-15 border-2 border-solid border-red-300 rounded bg-red-50 flex flex-col items-center justify-center text-lg",title:I.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},S):n("div",{className:"w-20 h-15 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex items-center justify-center text-2xl",title:`${J?"Capturing":"Pending"} ${O.name}...`,children:n("span",{className:J?"animate-pulse":"text-gray-400",children:J?"⋯":"⏹️"})},S)})})]})]})]}),x&&i&&n(mn,{projectSlug:i,onClose:()=>b(!1)})]})})}),ak=Object.freeze(Object.defineProperty({__proto__:null,default:sk,loader:rk,meta:nk},Symbol.toStringTag,{value:"Module"}));function Kp({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(qm,{remarkPlugins:[Qm],components:{h1:({children:s})=>n("h1",{className:"text-lg font-bold text-gray-900 mb-3 mt-6 first:mt-0 pb-1 border-b border-gray-200",children:s}),h2:({children:s})=>n("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:s}),h3:({children:s})=>n("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:s}),p:({children:s})=>n("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:s}),ul:({children:s})=>n("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),ol:({children:s})=>n("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:s}),li:({children:s})=>n("li",{className:"leading-relaxed",children:s}),code:({children:s,className:a})=>(a==null?void 0:a.includes("language-"))?n("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:n("code",{children:s})}):n("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:s}),pre:({children:s})=>n(we,{children:s}),strong:({children:s})=>n("strong",{className:"font-semibold text-gray-900",children:s}),blockquote:({children:s})=>n("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:s}),table:({children:s})=>n("div",{className:"overflow-x-auto mb-3",children:n("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:s})}),thead:({children:s})=>n("thead",{className:"bg-gray-50",children:s}),th:({children:s})=>n("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:s}),td:({children:s})=>n("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:s}),a:({children:s,href:a})=>n("a",{href:a,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:s})},children:r})}function Gp(e){const t={name:"root",path:"",memories:[],children:new Map};for(const r of e){const s=r.filePath.split("/");s.pop();let a=t,o="";for(const i of s)o=o?`${o}/${i}`:i,a.children.has(i)||a.children.set(i,{name:i,path:o,memories:[],children:new Map}),a=a.children.get(i);s.length===0?t.memories.push(r):a.memories.push(r)}return t}function qp(e){let t=e.memories.length;for(const r of e.children.values())t+=qp(r);return t}function za(e,t){var s;const r=e.match(/^#+ (.+)$/m);return r?r[1]:((s=t.split("/").pop())==null?void 0:s.replace(".md",""))||t}function Ur(e){return Math.round(e/3.5)}function ar(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const d=r.getTime()-t.getTime(),u=Math.floor(d/(1e3*60)),p=Math.floor(d/(1e3*60*60));return u<3?"Just now":u<60?`${u}min ago`:p===1?"1h ago":`${p}h ago`}const a=t.toLocaleDateString("en-US",{month:"short"}),o=t.getDate(),i=t.getFullYear(),l=r.getFullYear();return i===l?`${a} ${o}`:`${a} ${o}, ${i}`}function ok({rule:e,onEdit:t,onDelete:r,onView:s,isReviewed:a,onToggleReviewed:o,changeType:i,isUncommitted:l,changeDate:d,diff:u,isFadingOut:p,showLeftBorder:h}){const[m,f]=E(!1),[y,g]=E(!1),x=fe(()=>za(e.body,e.filePath),[e.body,e.filePath]),b=Ur(e.body.length),v=m?"#3e3e3e":l?"#d97706":"#c7c7c7",N=`rounded-lg border overflow-hidden transition-all ease-in-out ${l?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,w={...p&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return c("div",{className:N,style:w,children:[n("div",{className:`p-4 cursor-pointer ${l?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>s?s(e):f(!m),children:c("div",{className:"flex items-start justify-between",children:[c("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:m?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:v})})}),c("div",{className:"flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1",children:[n("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:l?"#78350f":"#000"},children:x}),i&&n("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${i==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...i==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...i==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:i}),l&&n("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"}),c("span",{className:"text-xs text-gray-400",children:["~",b.toLocaleString()," tokens"]})]}),n("div",{className:"flex items-center gap-2 text-xs text-gray-500 flex-wrap",children:e.frontmatter.paths&&e.frontmatter.paths.length>0&&c(we,{children:[e.frontmatter.paths.slice(0,2).map((C,k)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:C},k)),e.frontmatter.paths.length>2&&c("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),c("div",{className:"flex items-center gap-3 flex-shrink-0",children:[d&&n("span",{className:"text-xs text-gray-400",children:ar(d)}),o&&n("button",{onClick:C=>{C.stopPropagation(),o(e.filePath,e.lastModified,a??!1)},className:`w-5 h-5 rounded-full border-2 flex items-center justify-center cursor-pointer transition-colors ${a?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,title:a?"Mark as unreviewed":"Mark as reviewed",children:a&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}),m&&c("div",{className:`border-t ${l?"border-amber-200":"border-gray-100"}`,children:[c("div",{className:`px-4 py-3 flex items-center justify-between ${l?"bg-amber-50":"bg-white"}`,children:[n("div",{className:"flex items-center gap-2",children:i==="modified"&&u&&c("button",{onClick:C=>{C.stopPropagation(),g(!y)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${y?l?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":l?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(qs,{className:"w-3 h-3"}),y?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&c("div",{className:"flex items-center gap-2",children:[c("button",{onClick:C=>{C.stopPropagation(),t(e)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${l?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[n(wm,{className:"w-3 h-3"}),"Edit"]}),c("button",{onClick:C=>{C.stopPropagation(),r(e)},className:"flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer text-red-600 hover:text-red-800 hover:bg-red-100",children:[n(Nm,{className:"w-3 h-3"}),"Delete"]})]})]}),y&&u&&n("pre",{className:"mx-4 mb-4 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:u.split(`
575
+ `).map((C,k)=>{let j="";return C.startsWith("+")&&!C.startsWith("+++")?j="text-green-400":C.startsWith("-")&&!C.startsWith("---")?j="text-red-400":C.startsWith("@@")&&(j="text-cyan-400"),n("div",{className:j,children:C},k)})}),c("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),c("div",{className:"flex items-center gap-2",children:[c("span",{className:"px-2 py-1 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:["Claude, can you help me edit this rule: `",e.filePath,"`"]}),n(xt,{content:`Claude, can you help me edit this rule: \`${e.filePath}\``,icon:!0,iconSize:14,className:"p-1 text-gray-400 hover:text-gray-600 rounded transition-colors"})]})]}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&c("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Applies to paths:"}),n("div",{className:"flex flex-wrap gap-1.5",children:e.frontmatter.paths.map((C,k)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:C},k))})]}),!y&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n(Kp,{content:e.body})})]})]})}function ik(){return new Date().toISOString().split(".")[0]+"",`---
576
+ paths:
577
+ - '**/*.ts'
578
+ ---
579
+
580
+ ## Title
581
+
582
+ Description here.
583
+ `}function lk({rule:e,onSave:t,onCancel:r}){const[s,a]=E(e?`.claude/rules/${e.filePath}`:""),[o,i]=E((e==null?void 0:e.content)||ik()),[l,d]=E(!!e),[u,p]=E(!1),h=!e;return c("div",{className:"p-6",children:[c("div",{className:"flex items-center justify-between mb-4",children:[n("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),n("button",{onClick:r,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:n(ur,{className:"w-5 h-5"})})]}),h&&c("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:c("div",{className:"flex items-start gap-3",children:[n(qs,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),c("div",{children:[n("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),n("p",{className:"text-sm text-[#0369a1] mb-2",children:"Run this command in Claude Code to create a properly formatted rule with the right file location and paths:"}),c("div",{className:"relative",children:[n("code",{className:"block bg-white px-3 py-2 pr-9 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam-new-rule"}),n("button",{onClick:()=>{navigator.clipboard.writeText("/codeyam-new-rule"),p(!0),setTimeout(()=>p(!1),2e3)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[#0284c7] hover:text-[#0c4a6e] cursor-pointer transition-colors",title:"Copy command",children:u?n($t,{className:"w-4 h-4 text-green-500"}):n(Bt,{className:"w-4 h-4"})})]})]})]})}),c("button",{onClick:()=>d(!l),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:l?"rotate(90deg)":"none",transition:"transform 0.2s"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:l?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(l||!h)&&c("div",{className:"space-y-4",children:[c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),c("div",{className:"relative",children:[n("input",{type:"text",value:s,onChange:m=>a(m.target.value),placeholder:"e.g., src/webserver/architecture.md",className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm",disabled:!!e}),n("button",{onClick:()=>{navigator.clipboard.writeText(s)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy path",children:n(Bt,{className:"w-4 h-4"})})]})]}),e&&c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),c("div",{className:"relative",children:[n("input",{type:"text",value:`Claude, can you help me edit the rule: \`${s}\``,readOnly:!0,className:"w-full px-3 py-2 pr-10 border border-gray-300 rounded-md bg-gray-50 font-mono text-sm text-gray-600"}),n("button",{onClick:()=>{navigator.clipboard.writeText(`Claude, can you help me edit the rule: \`${s}\``)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 cursor-pointer",title:"Copy prompt",children:n(Bt,{className:"w-4 h-4"})})]})]}),c("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:m=>i(m.target.value),rows:20,className:"w-full px-3 py-2 border border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-sm bg-gray-900 text-gray-100 [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-800 [&::-webkit-scrollbar-thumb]:bg-gray-600 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:hover:bg-gray-500 [&::-webkit-resizer]:bg-gray-700"})]}),c("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),n("button",{onClick:()=>t(s.replace(/^\.claude\/rules\//,""),o),disabled:!s.trim()||!o.trim(),className:"px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer font-mono uppercase text-xs font-semibold",children:"Save"})]})]})]})}function ck({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:s,onToggleFolder:a}){const o=fe(()=>Gp(e),[e]),i=(u,p,h)=>{if(u.target.closest(".chevron-toggle")){h&&a(p||"root");return}const f=p||null;r(t===f?null:f),h&&!s.has(p||"root")&&a(p||"root")},l=u=>{r(t===u?null:u)},d=(u,p=0)=>{const h=s.has(u.path||"root"),m=qp(u),f=u.children.size>0,y=u.name==="root"?"(root)":u.name,g=u.memories.length>0||f,x=u.path||"",b=t===x||t===null&&x==="";return c("div",{children:[c("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${b?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${p*12+8}px`},onClick:v=>i(v,u.path,g),children:[g&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:v=>{v.stopPropagation(),a(u.path||"root")},children:n(xn,{className:`w-3 h-3 text-gray-500 transition-transform ${h?"rotate-90":""}`})}),!g&&n("div",{className:"w-3"}),n(Ld,{className:"w-3.5 h-3.5 text-[#005C75]"}),n("span",{className:`text-xs font-mono font-semibold ${b?"text-[#005C75]":""}`,style:{color:"#005C75"},children:y}),c("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[m," rules"]})]}),h&&c("div",{className:"relative",children:[(u.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${p*12+8+6}px`}}),u.memories.length>0&&n("div",{style:{paddingLeft:`${(p+1)*12+8}px`},children:u.memories.map(v=>{var w;const N=t===v.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${N?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>l(v.filePath),children:n("span",{className:"text-xs",children:(w=v.filePath.split("/").pop())==null?void 0:w.replace(".md","")})},v.filePath)})}),f&&n("div",{children:Array.from(u.children.values()).sort((v,N)=>v.name.localeCompare(N.name)).map(v=>d(v,p+1))})]})]},u.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:d(o)})}function dk({memories:e,onEdit:t,onDelete:r,expandedFolders:s,onToggleFolder:a,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:l,onViewRule:d}){const[u,p]=E({});se(()=>{p({})},[o]);const h=fe(()=>({...o,...u}),[o,u]),m=fe(()=>Gp(e),[e]),f=(g,x,b)=>{p(v=>({...v,[g]:!b})),b?l(g):i(g,x)},y=(g,x=0)=>{const b=s.has(g.path||"root"),v=g.children.size>0,N=g.name==="root"?"root":g.name,w=g.memories.length>0||v;return c("div",{children:[c("div",{className:"flex items-center gap-2 py-2 cursor-pointer hover:bg-gray-50 rounded px-2 mb-2",style:{backgroundColor:"rgba(224, 233, 236, 0.5)"},onClick:()=>w&&a(g.path||"root"),children:[w&&n(xn,{className:`w-4 h-4 text-gray-500 transition-transform ${b?"rotate-90":""}`}),!w&&n("div",{className:"w-4"}),n(Ld,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:N})]}),b&&c("div",{className:"ml-10 space-y-4 relative",children:[(g.memories.length>0||v)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),g.memories.length>0&&n("div",{className:"space-y-2",children:g.memories.map(C=>n(ok,{rule:C,onEdit:t,onDelete:r,onView:d,isReviewed:h[C.filePath]??!1,onToggleReviewed:f},C.filePath))}),v&&n("div",{className:"space-y-4",children:Array.from(g.children.values()).sort((C,k)=>C.name.localeCompare(k.name)).map(C=>y(C,x+1))})]})]},g.path||"root")};return n("div",{children:y(m)})}function uk({memories:e,reviewedStatus:t,onViewRule:r,refreshKey:s}){const[a,o]=E("unreviewed"),[i,l]=E("by-date"),[d,u]=E(null),[p,h]=E(!0),[m,f]=E(new Map),y=be(t),g=be([]);se(()=>()=>{g.current.forEach(clearTimeout)},[]),se(()=>{(async()=>{h(!0);try{const k=await(await fetch("/api/memory?action=rule-coverage")).json();u(k.coverage??null)}catch{u(null)}finally{h(!1)}})()},[s]),se(()=>{const w=y.current,C=[];for(const[k,j]of Object.entries(t))j&&!w[k]&&C.push(k);y.current=t,C.length!==0&&(f(k=>{const j=new Map(k);return C.forEach(A=>j.set(A,"approved")),j}),g.current.push(setTimeout(()=>{f(k=>{const j=new Map(k);return C.forEach(A=>j.set(A,"fading")),j})},1500)),g.current.push(setTimeout(()=>{f(k=>{const j=new Map(k);return C.forEach(A=>j.delete(A)),j})},2500)))},[t]);const x=fe(()=>{const w=[...e];return i==="by-impact"&&d!==null?w.sort((C,k)=>{const j=d[C.filePath]??0,A=d[k.filePath]??0;return A!==j?A-j:new Date(k.lastModified).getTime()-new Date(C.lastModified).getTime()}):w.sort((C,k)=>new Date(k.lastModified).getTime()-new Date(C.lastModified).getTime()),w},[e,i,d]),b=fe(()=>x.filter(w=>!t[w.filePath]).length,[x,t]),v=fe(()=>a==="unreviewed"?x.filter(w=>!t[w.filePath]||m.has(w.filePath)):x,[x,a,t,m]),N=!p&&d!==null;return c("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[c("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Recently Changed Rules"})}),n("div",{className:"flex-1"}),c("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),c("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",b,")"]})]}),c("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),c("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:["All (",x.length,")"]})]})]}),c("div",{className:"grid grid-cols-[1fr_90px_80px_100px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Rule"}),c("button",{onClick:()=>N&&l("by-impact"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none p-0 ${N?"cursor-pointer hover:text-gray-600":"cursor-default"} ${i==="by-impact"?"text-[#005C75]":"text-gray-400"}`,children:["Src Files",i==="by-impact"&&n(Tt,{className:"w-3 h-3"})]}),c("button",{onClick:()=>l("by-date"),className:`text-[11px] uppercase tracking-wider font-medium text-center flex items-center justify-center gap-0.5 whitespace-nowrap bg-transparent border-none cursor-pointer p-0 hover:text-gray-600 ${i==="by-date"?"text-[#005C75]":"text-gray-400"}`,children:["Changed At",i==="by-date"&&n(Tt,{className:"w-3 h-3"})]}),c("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium text-center flex items-center justify-center gap-1 whitespace-nowrap",children:["✓ Reviewed",c("span",{className:"relative group",children:[n(Mo,{className:"w-3 h-3 text-gray-300 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Showing which rules have been reviewed and approved. Click a rule to view it and approve it"})]})]})]}),n("div",{className:"flex-1 overflow-y-auto max-h-[400px]",children:v.map(w=>{const C=t[w.filePath]??!1,k=m.get(w.filePath),j=za(w.body,w.filePath),A=(d==null?void 0:d[w.filePath])??0;return n("div",{className:`border-b border-gray-50 transition-all ${k==="fading"?"duration-1000":"duration-300"}`,style:{opacity:k==="fading"?0:1},children:c("div",{className:`grid grid-cols-[1fr_90px_80px_100px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${k==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(w),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:j})}),n("span",{className:"text-xs text-center",children:p?n("span",{className:"inline-block w-6 h-3 bg-gray-100 rounded animate-pulse"}):d!==null?n("span",{className:A>0?"text-gray-700 font-medium":"text-gray-300",children:A}):n("span",{className:"text-gray-300",children:"—"})}),n("span",{className:"text-xs text-gray-500 text-center",children:ar(w.lastModified)}),n("div",{className:"flex justify-center",children:n("div",{className:`w-5 h-5 rounded-full border-2 flex items-center justify-center transition-colors duration-300 ${C?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:C&&n("svg",{width:"10",height:"8",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})},w.filePath)})}),v.length===0&&a==="unreviewed"&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:"All rules have been reviewed"})]})}function pk(e,t){const r=t.map(s=>`- \`${s}\``).join(`
584
+ `);return`Please audit the following Claude Rules that apply to the file \`${e}\`:
585
+
586
+ ${r}
587
+
588
+ Please review these rules in conjunction with one another as they all apply to this file.
589
+
590
+ Review each rule with the other rules in mind:
591
+ - Necessary: Is this rule really necessary to avoid confusion in future work sessions?
592
+ - Efficiency: Are the rules concise and well-structured?
593
+ - Effectiveness: Does the rules provide clear, actionable guidance?
594
+ - Context window impact: Can the rules be shortened without losing important information?
595
+ - Overlap: Is there any redundant information across the rules that can be consolidated?
596
+ - Duplication: Are there any rules that are nearly identical that can be merged or removed?
597
+
598
+ Remember that documenting past confusion isn't helpul unless that confusion will likely happen again.
599
+
600
+ Note: Each rule may apply to multiple files, not just the file listed above. Consider this when suggesting changes — modifications should not negatively impact the rule's usefulness for other files it covers.`}function hk({filePath:e,rulePaths:t,onClose:r}){const[s,a]=E(!1),o=pk(e,t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:c("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:l=>l.stopPropagation(),children:[n("button",{onClick:r,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(ur,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-1",children:"Audit Rules For File"}),n("p",{className:"font-mono text-sm text-gray-500 mb-4 truncate",title:e,children:e}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can audit these rules to try and make them as efficient and effective as possible, reducing the impact on the context window."}),n("textarea",{readOnly:!0,value:o,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-4",children:n("button",{onClick:()=>{navigator.clipboard.writeText(o),a(!0),setTimeout(()=>a(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:s?c(we,{children:[n($t,{className:"w-4 h-4"}),"Copied!"]}):c(we,{children:[n(Bt,{className:"w-4 h-4"}),"Copy Prompt"]})})})]})})}function mk({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:s}){const[a,o]=E("unreviewed"),[i,l]=E(null),[d,u]=E(""),[p,h]=E(0),[m,f]=E(!1),[y,g]=E(null),[x,b]=E(null),v=be(null),N=be(null),[w,C]=E({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[k,j]=E(!0);se(()=>{(async()=>{j(!0);try{const V=await(await fetch("/api/memory?action=audit")).json();C({topPaths:V.topPaths||[],totalFilesWithCoverage:V.totalFilesWithCoverage||0,allSourceFiles:V.allSourceFiles||[]})}catch(W){console.error("Failed to load audit data:",W)}finally{j(!1)}})()},[e]);const A=fe(()=>a==="all"?w.topPaths:w.topPaths.filter(U=>U.matchingRules.some(W=>!t[W.filePath])),[w.topPaths,a,t]);fe(()=>w.topPaths.filter(U=>U.matchingRules.some(W=>!t[W.filePath])).length,[w.topPaths,t]);const _=U=>U.split("/").pop()||U,M=fe(()=>{const U=new Map;for(const W of w.topPaths)U.set(W.filePath,W);return U},[w.topPaths]),T=fe(()=>{if(!d.trim())return[];const U=d.toLowerCase(),W=[],V=[];for(const F of w.allSourceFiles){const Y=F.toLowerCase();if(!Y.includes(U))continue;const P=M.get(F)||{filePath:F,matchingRules:[],totalTextLength:0};Y.startsWith(U)?W.push(P):V.push(P)}return W.sort((F,Y)=>F.filePath.localeCompare(Y.filePath)),V.sort((F,Y)=>F.filePath.localeCompare(Y.filePath)),[...W,...V].slice(0,8)},[d,w.allSourceFiles,M]),D=le(U=>{var W;g(U),l(U.filePath),u(U.filePath),f(!1),(W=v.current)==null||W.blur()},[]),R=le(()=>{var U;u(""),g(null),l(null),(U=v.current)==null||U.focus()},[]),L=le(U=>{var W;!m||T.length===0||(U.key==="ArrowDown"?(U.preventDefault(),h(V=>Math.min(V+1,T.length-1))):U.key==="ArrowUp"?(U.preventDefault(),h(V=>Math.max(V-1,0))):U.key==="Enter"?(U.preventDefault(),D(T[p])):U.key==="Escape"&&(f(!1),(W=v.current)==null||W.blur()))},[m,T,p,D]);return se(()=>{h(0)},[T]),c("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[c("div",{className:"flex items-center gap-4 border-b border-[#e1e1e1] px-5",children:[n("button",{className:"py-3 border-b-2 border-[#232323] text-[#232323] bg-transparent cursor-pointer",children:n("span",{className:"text-[14px] leading-6",style:{fontFamily:"Sora",fontWeight:600},children:"Rule Audit"})}),c("div",{className:"relative flex-1 max-w-[300px]",children:[n(Zr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:v,type:"text",value:d,onChange:U=>{u(U.target.value),f(!0)},onFocus:()=>{d.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:L,placeholder:"Search files...",className:`w-full pl-8 ${d?"pr-7":"pr-3"} py-1 text-xs border border-gray-200 rounded-md focus:outline-none focus:ring-1 focus:ring-[#005C75] focus:border-[#005C75] bg-gray-50`}),d&&n("button",{type:"button",onMouseDown:U=>{U.preventDefault(),R()},className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center text-gray-400 hover:text-gray-600 cursor-pointer",children:n("svg",{viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"w-3 h-3",children:n("path",{d:"M1 1l12 12M13 1L1 13"})})}),m&&T.length>0&&n("div",{ref:N,className:"absolute left-0 top-full mt-0.5 bg-white border border-gray-200 rounded-md shadow-lg z-10 max-h-75 overflow-y-auto min-w-75 max-w-120",children:T.map((U,W)=>c("div",{onMouseDown:V=>{V.preventDefault(),D(U)},onMouseEnter:()=>h(W),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${W===p?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(Qs,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:U.filePath,children:(()=>{const V=U.filePath.toLowerCase().indexOf(d.toLowerCase());if(V===-1)return U.filePath;const F=U.filePath.slice(0,V),Y=U.filePath.slice(V,V+d.length),P=U.filePath.slice(V+d.length);return c(we,{children:[F,n("span",{className:"font-semibold text-[#005C75]",children:Y}),P]})})()}),c("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[U.matchingRules.length," rule",U.matchingRules.length!==1?"s":""]})]},U.filePath))})]}),n("div",{className:"flex-1"}),c("button",{onClick:()=>o("unreviewed"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="unreviewed"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:"Unreviewed Rules"})]}),c("button",{onClick:()=>o("all"),className:"flex items-center gap-1.5 bg-transparent cursor-pointer py-3",children:[n("span",{className:"w-2 h-2 rounded-full flex-shrink-0",style:{backgroundColor:a==="all"?"#005C75":"#d1d5db"}}),n("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:"All"})]})]}),c("div",{className:"grid grid-cols-[1fr_140px_150px] px-5 py-2 border-b border-gray-100",children:[n("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium",children:"Source file"}),c("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",c("span",{className:"relative group",children:[n(Mo,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full left-1/2 -translate-x-1/2 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-48 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Number of rules not yet reviewed for this file / Total number of rules that apply to this file"})]})]}),c("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",c("span",{className:"relative group",children:[n(Mo,{className:"w-3 h-3 text-gray-300 flex-shrink-0 cursor-help"}),n("span",{className:"absolute top-full right-0 mt-1.5 px-3 py-2 bg-gray-800 text-white text-[10px] leading-relaxed rounded shadow-lg w-52 text-center whitespace-normal opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity z-20",children:"Estimated tokens from unreviewed rules / Total number of tokens from all rules that apply to this file"})]})]})]}),k&&n("div",{className:"px-5 py-6",children:c("div",{className:"animate-pulse space-y-3",children:[n("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),n("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),n("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"})]})}),!k&&(A.length>0||y)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(y?[y,...A.filter(W=>W.filePath!==y.filePath)].slice(0,8):A.slice(0,8)).map((U,W)=>{const V=U.matchingRules.length,F=U.matchingRules.filter(I=>!t[I.filePath]),Y=F.length,P=F.reduce((I,K)=>I+K.bodyLength,0),O=Y>0,S=i===U.filePath,$=(y==null?void 0:y.filePath)===U.filePath;return c("div",{children:[c("div",{onClick:()=>l(S?null:U.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${$?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[c("div",{className:"flex items-center gap-2 min-w-0",children:[S?n(Tt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(xn,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(Qs,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:U.filePath,children:$?U.filePath:_(U.filePath)})]}),c("span",{className:"text-sm text-center",children:[n("span",{className:O?"font-semibold text-[#1A5276]":"text-gray-400",children:Y}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:V})]}),c("span",{className:"text-sm text-center",children:[n("span",{className:O?"font-semibold text-[#1A5276]":"text-gray-400",children:Ur(P).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:Ur(U.totalTextLength).toLocaleString()})]})]}),S&&c("div",{className:"bg-gray-50 border-b border-gray-100",children:[U.matchingRules.map(I=>{const K=r.find(J=>J.filePath===I.filePath),q=t[I.filePath]??!1;return c("div",{onClick:J=>{J.stopPropagation(),K&&s(K)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(Gs,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-700 truncate flex-1",children:K?za(K.body,K.filePath):I.filePath}),c("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[Ur(I.bodyLength).toLocaleString()," ","tokens"]}),n("div",{className:`w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${q?"bg-[#005C75] border-[#005C75]":"bg-white border-gray-300"}`,children:q&&n("svg",{width:"8",height:"6",viewBox:"0 0 10 8",fill:"none",children:n("path",{d:"M1 4L3.5 6.5L9 1",stroke:"white",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})]},I.filePath)}),c("div",{className:"flex items-center justify-center gap-3 px-5 py-2 border-t border-gray-200",children:[n("span",{className:"text-xs text-gray-400",children:"Have Claude audit these rules"}),n("button",{onClick:I=>{I.stopPropagation(),b({filePath:U.filePath,rulePaths:U.matchingRules.map(K=>K.filePath)})},className:"px-3 py-1 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer",children:"Prompt"})]})]})]},U.filePath)})}),!k&&A.length===0&&n("div",{className:"px-5 py-8 text-center text-sm text-gray-500",children:a==="unreviewed"?"No files have unreviewed rules":"No files have rule coverage yet"}),x&&n(hk,{filePath:x.filePath,rulePaths:x.rulePaths,onClose:()=>b(null)})]})}function fk({rule:e,changeInfo:t,isReviewed:r,onApprove:s,onEdit:a,onDelete:o,onClose:i}){const l=za(e.body,e.filePath),d=Ur(e.body.length),u=e.frontmatter.category,p=`.claude/rules/${e.filePath}`,[h,m]=E(null),f=(t==null?void 0:t.changeType)==="added"||h!=null&&h.commitCount!=null&&h.commitCount<=1&&!(h.commitCount===1&&h.isUncommitted);return se(()=>{m(null),fetch(`/api/memory?action=rule-diff&filePath=${encodeURIComponent(e.filePath)}`).then(y=>y.json()).then(y=>{y.diff&&m(y.diff)}).catch(()=>{})},[e.filePath]),se(()=>{const y=g=>{g.key==="Escape"&&i()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[i]),n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:i,children:c("div",{className:"rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",style:{backgroundColor:"#F8F7F6"},onClick:y=>y.stopPropagation(),children:[n("div",{className:"px-6 pt-5 pb-4",children:c("div",{className:"flex items-start justify-between",children:[c("div",{className:"min-w-0 flex-1",children:[c("div",{className:"flex items-center gap-2 mb-1.5 flex-wrap",children:[n("h2",{className:"text-[16px] font-bold text-gray-900",children:l}),t&&c(we,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:ar(t.date)}),n("span",{className:`flex-shrink-0 text-[11px] uppercase font-semibold tracking-wider ${t.changeType==="added"?"text-green-600":t.changeType==="modified"?"text-orange-600":"text-red-600"}`,children:t.changeType})]})]}),u&&c("div",{className:"flex items-center gap-2 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"TYPE:"}),n("span",{className:"px-2 py-0.5 rounded text-[10px] uppercase font-semibold tracking-wider bg-[#E0F2F1] text-[#00796B]",children:u})]}),c("div",{className:"flex items-center gap-1.5 mb-1.5",children:[n("span",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:"FILE:"}),n("code",{className:"text-[11px] text-gray-600 font-mono",children:p}),n(xt,{content:p,icon:!0,iconSize:12,className:"p-0.5 rounded text-gray-400 hover:text-gray-600 transition-colors",ariaLabel:"Copy file path"})]}),c("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",d.toLocaleString()]})]}),c("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[c("button",{onClick:s,className:`flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer transition-colors ${r?"bg-green-600 text-white":"border border-green-600 text-green-700 hover:bg-green-50"}`,children:[n($t,{className:"w-3.5 h-3.5"}),r?"Approved":"Approve"]}),n("button",{onClick:a,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-gray-300 text-gray-600 hover:bg-gray-50 transition-colors",children:"Edit"}),n("button",{onClick:o,className:"px-3 py-1.5 rounded text-xs font-medium uppercase tracking-wider cursor-pointer border border-red-300 text-red-600 hover:bg-red-50 transition-colors",children:"Delete"}),n("button",{onClick:i,className:"p-1.5 rounded text-gray-400 hover:text-gray-600 hover:bg-gray-200 cursor-pointer transition-colors ml-1",children:n(ur,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&c("div",{className:"px-6 pb-4",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Applies to paths:"}),n("div",{className:"bg-white rounded-lg p-4 space-y-2.5",style:{border:"1px solid #E6E6E6"},children:e.frontmatter.paths.map((y,g)=>{const x=y.split("/"),b=x.pop()||y,v=x.length>0?x.join("/")+"/":"";return c("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(Qs,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),c("span",{children:[v&&n("span",{className:"text-gray-500",children:v}),n("span",{className:"font-bold text-gray-900",children:b})]})]},g)})})]}),f?n("div",{className:"px-6 pb-4",children:c("div",{className:"text-[13px] text-gray-500",children:["Created"," ",t!=null&&t.date?ar(t.date):h!=null&&h.date?ar(h.date):"recently"]})}):h&&n("div",{className:"px-6 pb-4",children:c("details",{children:[c("summary",{className:"text-[13px] text-gray-700 font-semibold cursor-pointer",children:["Recent change: ",h.commitMessage," —"," ",ar(h.date)]}),n("pre",{className:"mt-2 p-4 text-xs font-mono overflow-x-auto bg-gray-900 text-gray-100 max-h-64 overflow-y-auto rounded-md",children:h.diff.split(`
601
+ `).map((y,g)=>{let x="";return y.startsWith("+")&&!y.startsWith("+++")?x="text-green-400":y.startsWith("-")&&!y.startsWith("---")?x="text-red-400":y.startsWith("@@")&&(x="text-cyan-400"),n("div",{className:x,children:y},g)})})]})}),c("div",{className:"px-6 pb-6",children:[n("div",{className:"text-[13px] text-gray-700 font-semibold mb-2",children:"Rule Text:"}),n("div",{className:"bg-white rounded-lg p-6",style:{border:"1px solid #E6E6E6"},children:n(Kp,{content:e.body})})]})]})})}function gk(){return c("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]})}function yk(){return c("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),n("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),n("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),n("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),n("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),n("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),n("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),n("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),n("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),n("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),n("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),n("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),n("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),n("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),n("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),n("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),n("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),n("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),n("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),n("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),n("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),n("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),n("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),n("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),n("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),n("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),n("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),n("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}function xk(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[c("div",{className:"text-center mb-10",children:[n("h1",{className:"text-[22px] font-semibold mb-4",style:{fontFamily:"Sora",color:"#232323"},children:"Get Started with CodeYam Memory"}),n("p",{className:"text-[15px] text-gray-500 leading-relaxed max-w-2xl mx-auto",children:"CodeYam Memory generates path-scoped Claude Rules that load automatically when Claude works on matching files. These rules capture any confusion, architectural decisions, and tribal knowledge from your as you work with Claude, ensuring sessions become more efficient and aligned with your codebase over time."})]}),c("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"Setup Steps"}),c("ol",{className:"space-y-5",children:[c("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"1"}),n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Open Claude Code in your project terminal"})]}),c("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"2"}),c("div",{children:[c("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(td,{value:"/codeyam-memory"}),n("span",{className:"text-[14px] font-medium text-gray-900",children:"in the Claude Code session"})]}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"This kicks off analysis of your git history to find confusion patterns."})]})]}),c("li",{className:"flex gap-3 items-start",children:[n("span",{className:"flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center text-sm font-semibold",style:{backgroundColor:"#005C75",color:"#fff"},children:"3"}),c("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900 pt-0.5",children:"Return to this dashboard page to review the new rules"}),n("p",{className:"text-[13px] text-gray-600 mt-1",children:"You can review, edit, and approve the rules Claude creates."})]})]})]})]}),c("div",{className:"rounded-lg p-8 mb-6",style:{backgroundColor:"#EDF8FA",border:"1px solid #C8E6EC"},children:[n("h2",{className:"text-[18px] font-semibold mb-6",style:{fontFamily:"Sora",color:"#232323"},children:"What Gets Created"}),c("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),c("div",{className:"space-y-6",children:[c("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),c("div",{children:[c("p",{className:"text-[14px] font-medium text-gray-900",children:[n("code",{className:"bg-gray-200/60 px-1.5 py-0.5 rounded text-[13px]",children:".claude/rules/*.md"}),n("span",{className:"text-gray-400 mx-1.5",children:"—"}),"path-scoped guidance files"]}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"Markdown files with frontmatter specifying which file paths they apply to."})]})]}),c("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),c("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Rules load automatically when Claude works on matching files"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"No manual steps needed — Claude picks up relevant rules based on the files it touches."})]})]}),c("div",{className:"flex items-start gap-4 relative",children:[n("div",{className:"flex-shrink-0 w-8 h-8 rounded flex items-center justify-center",style:{backgroundColor:"#2C3E50"},children:n("div",{className:"w-3 h-3 rounded-sm bg-white/30"})}),c("div",{children:[n("p",{className:"text-[14px] font-medium text-gray-900",children:"Pre-commit hook to keep rules fresh and capture new patterns"}),n("p",{className:"text-[13px] text-gray-500 mt-1",children:"A git hook runs automatically to update rules when related code changes and looks for any new patterns of confusion in work sessions."})]})]})]})]})]}),c("div",{className:"rounded-lg px-8 py-5 flex items-center justify-center gap-3",style:{backgroundColor:"#1A2332"},children:[n("span",{className:"text-white text-[15px] font-medium",children:"Run"}),n(td,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in Claude Code to get started"})]})]})})}function td({value:e}){const[t,r]=E(!1);return c("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded text-[13px] font-mono cursor-pointer border-0",style:{backgroundColor:"#2C3E50",color:"#E0E0E0"},title:"Copy to clipboard",children:[e,t?n($t,{className:"w-3.5 h-3.5 text-green-400"}):c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-400",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]})}function Ds({label:e,count:t,icon:r,bgColor:s,iconBgColor:a,textColor:o}){return n("div",{className:"rounded-lg p-4",style:{backgroundColor:s,border:"1px solid #EFEFEF"},children:c("div",{className:"flex items-start gap-3",children:[n("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:a},children:r}),c("div",{className:"flex-1",children:[n("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:o},children:t}),n("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:o},children:e})]})]})})}function bk({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:s,reviewCounts:a}){return c("div",{className:"mb-8",children:[c("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[c("div",{children:[c("div",{className:"flex items-center gap-3 mb-2",children:[n(gk,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),c("p",{className:"text-[15px] text-gray-500",children:["Rules help Claude understand your codebase patterns and conventions."," ",n("button",{onClick:s,className:"text-[#005C75] underline cursor-pointer",children:"Learn more about rules."})]})]}),c("div",{className:"flex items-center gap-3",children:[c("div",{className:"relative",children:[n(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:e,onChange:o=>t(o.target.value),placeholder:"Search rules...",className:"w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent text-sm"})]}),c("button",{onClick:r,className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(ri,{className:"w-4 h-4"}),"New Rule"]})]})]}),c("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(Ds,{label:"Total Rules",count:a.total,icon:n(yk,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(Ds,{label:"Unreviewed",count:a.unreviewed,icon:n(Sm,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(Ds,{label:"Reviewed",count:a.reviewed,icon:n($t,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(Ds,{label:"Stale",count:a.stale,icon:n(Od,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function vk({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:c("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative",onClick:r=>r.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(ur,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-4",children:"What are Claude Rules?"}),n("h3",{className:"mb-4 font-semibold",children:"And how does CodeYam Memory work with Claude Rules?"}),c("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[c("p",{children:["Claude Rules are a component of"," ",n("a",{href:"https://code.claude.com/docs/en/memory#modular-rules-with-claude%2Frules%2F",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 underline",children:"Memory Management in Claude Code"}),'. The text of each rule is passed into the context window when working on the specific files described in the "paths" frontmatter field of the rule.']}),n("p",{children:"This allows you to provide context that is surgically specific to certain files in your codebase. They are a powerful tool but are harder to write and maintain than CLAUDE.md files."}),n("p",{children:"CodeYam Memory helps write and maintain Claude Rules. Hooks ensure that rules are reviewed and added during Claude Code working sessions. The CodeYam CLI Dashboard provides a page dedicated to Memory where you can view, edit, create, delete, and review Claude Rules."})]}),n("div",{className:"flex justify-center",children:c("button",{onClick:t,className:"flex items-center gap-2 px-5 py-2.5 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:[n(ri,{className:"w-4 h-4"}),"New Rule"]})})]})})}function wk({rule:e,onConfirm:t,onCancel:r}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:c("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[n("h3",{className:"text-lg font-semibold mb-2",children:"Delete Memory?"}),c("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",n("span",{className:"font-mono text-sm",children:e.filePath}),"? This cannot be undone."]}),c("div",{className:"flex justify-end gap-2",children:[n("button",{onClick:r,className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),n("button",{onClick:()=>t(e),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})}const nd="Can you help me perform an interactive rules audit? Please look at all of the rules in `.claude/rules`. Are they organized properly? Ideally they should be in a folder that is the best representation of the files they impact (e.g. if the rule impacts `folder1/folder2/file1` and `folder1/folder2/folder3/file2` then the rule should be in `.claude/rules/folder1/folder2`). Do they make sense? Are they oriented toward avoiding future confusion (vs documenting bug fixes or temporary workarounds, etc)? Please literally read each one to ensure you understand what it is saying and learn something useful from it. Are they concise and efficient in their communication? We want to be respectful of the context window so any information in a rule that does not make sense, is not particularly helpful, or is repetitive should be removed. All other information should be presented as directly as possible. Bullets and tables can help with this as opposed to paragraphs. Take into consideration how rules interact as any one file may have multiple rules applied to it. Please look at the impacted files as well to ensure that it is an appropriate rule for them and to ensure the rule is not just repeating information that can be ascertained from the code. We don't want Claude to have to read a large number of files (or a single very large file) to figure out how everything works, so architectural guidance can be quite valuable, but information that is specific to one file and can be ascertained by the code and comments in that file is unnecessary. Too often rules reflect past confusion that has been resolved and is unlikely to happen again. Content and rules like this should be removed. If you have any questions please ask!",rd="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function sd({text:e}){const[t,r]=E(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?c(we,{children:[n($t,{className:"w-4 h-4"}),"Copied!"]}):c(we,{children:[n(Bt,{className:"w-4 h-4"}),"Copy Prompt"]})})}function Nk({onClose:e}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:c("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:t=>t.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(ur,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-2",children:"Audit All Rules"}),n("p",{className:"text-gray-600 text-sm mb-4",children:"Claude can review all rules to look for information that is inconsistent, inappropriate, duplicative, inefficient, etc."}),n("textarea",{readOnly:!0,value:nd,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(sd,{text:nd})}),c("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:rd,className:"w-full h-16 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(sd,{text:rd})})]})]})})}function Sk(){const[e,t]=E(!1);return c(we,{children:[c("div",{className:"border border-gray-200 rounded-lg px-5 py-4 flex items-center gap-3",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit All Rules"}),n("p",{className:"text-sm text-gray-500",children:"Ask Claude to review, audit, and improve all rules."}),n("button",{onClick:()=>t(!0),className:"px-4 py-2 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer flex-shrink-0",children:"Get Prompt"})]}),e&&n(Nk,{onClose:()=>t(!1)})]})}function Ck(e){return`Can you help me review my unreviewed rules? The following rules in \`.claude/rules\` have not been reviewed yet:
602
+
603
+ ${e.map(r=>`- \`.claude/rules/${r}\``).join(`
604
+ `)}
605
+
606
+ Are they organized properly? Ideally they should be in a folder that is the best representation of the files they impact (e.g. if the rule impacts \`folder1/folder2/file1\` and \`folder1/folder2/folder3/file2\` then the rule should be in \`.claude/rules/folder1/folder2\`). Do they make sense? Are they oriented toward avoiding future confusion (vs documenting bug fixes or temporary workarounds, etc)? Please literally read each one to ensure you understand what it is saying and learn something useful from it. Are they concise and efficient in their communication? We want to be respectful of the context window so any information in a rule that does not make sense, is not particularly helpful, or is repetitive should be removed. All other information should be presented as directly as possible. Bullets and tables can help with this as opposed to paragraphs. Take into consideration how rules interact as any one file may have multiple rules applied to it. Please look at the impacted files as well to ensure that it is an appropriate rule for them and to ensure the rule is not just repeating information that can be ascertained from the code. We don't want Claude to have to read a large number of files (or a single very large file) to figure out how everything works, so architectural guidance can be quite valuable, but information that is specific to one file and can be ascertained by the code and comments in that file is unnecessary. Too often rules reflect past confusion that has been resolved and is unlikely to happen again. Content and rules like this should be removed. If you have any questions please ask!`}const ad="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function od({text:e}){const[t,r]=E(!1);return n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"flex items-center gap-2 px-4 py-2 rounded-md hover:opacity-90 cursor-pointer font-mono uppercase text-xs font-semibold text-white",style:{backgroundColor:"#1A2332"},children:t?c(we,{children:[n($t,{className:"w-4 h-4"}),"Copied!"]}):c(we,{children:[n(Bt,{className:"w-4 h-4"}),"Copy Prompt"]})})}function kk({onClose:e,unreviewedRulePaths:t}){const r=Ck(t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:c("div",{className:"bg-white rounded-lg p-8 max-w-xl w-full mx-4 relative max-h-[90vh] overflow-y-auto",onClick:s=>s.stopPropagation(),children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 cursor-pointer",children:n(ur,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-2",children:"Audit Unreviewed Rules"}),c("p",{className:"text-gray-600 text-sm mb-4",children:["Claude will review only the ",t.length," unreviewed"," ",t.length===1?"rule":"rules"," for quality, relevance, and organization."]}),n("textarea",{readOnly:!0,value:r,className:"w-full h-48 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(od,{text:r})}),c("div",{className:"border-t border-gray-200 mt-6 pt-5",children:[n("p",{className:"text-gray-500 text-sm mb-3",children:"If you would like to avoid reviewing all of the changes Claude makes you can ask Claude to mark all rules as reviewed."}),n("textarea",{readOnly:!0,value:ad,className:"w-full h-16 p-3 text-sm font-mono bg-gray-50 border border-gray-200 rounded-md resize-none focus:outline-none"}),n("div",{className:"flex justify-end mt-3",children:n(od,{text:ad})})]})]})})}function jk({unreviewedRulePaths:e}){const[t,r]=E(!1);return e.length===0?c("div",{className:"border border-gray-200 rounded-lg px-5 py-4 flex items-center gap-3 opacity-50",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit Unreviewed Rules"}),n("p",{className:"text-sm text-gray-500",children:"All rules have been reviewed."})]}):c(we,{children:[c("div",{className:"border border-gray-200 rounded-lg px-5 py-4 flex items-center gap-3",children:[n("h3",{className:"text-[14px] leading-6 text-[#232323] flex-shrink-0",style:{fontFamily:"Sora",fontWeight:600},children:"Audit Unreviewed Rules"}),c("p",{className:"text-sm text-gray-500",children:["Ask Claude to review the ",e.length," unreviewed"," ",e.length===1?"rule":"rules","."]}),n("button",{onClick:()=>r(!0),className:"px-4 py-2 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer flex-shrink-0",children:"Get Prompt"})]}),t&&n(kk,{onClose:()=>r(!1),unreviewedRulePaths:e})]})}const _k=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function Ek({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?ue({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?ue({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):ue({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),ue({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const Pk=tt(function(){const{memories:t,reviewedStatus:r,memoryInitialized:s,error:a}=lt(),o=Ke(),i=Ut(),[l,d]=E(""),[u,p]=E(null),[h,m]=E(new Set(["root"])),[f,y]=E(null),[g,x]=E(!1),[b,v]=E(null),[N,w]=E(0),[C,k]=E(!1),[j,A]=E(null),[_,M]=E(null),[T,D]=E({}),R=J=>{m(z=>{const B=new Set(z);return B.has(J)?B.delete(J):B.add(J),B})};Wt({source:"memory-page"});const L=fe(()=>({...r,...T}),[r,T]),U=be(o.state);se(()=>{const J=U.current==="loading"||U.current==="submitting",z=o.state==="idle";J&&z&&o.data&&(i.revalidate(),y(null),x(!1),w(B=>B+1)),U.current=o.state},[o.state,o.data,i]),se(()=>{D(J=>{const z={};for(const[B,H]of Object.entries(J))r[B]!==H&&(z[B]=H);return Object.keys(z).length===Object.keys(J).length?J:z})},[r]);const W=(J,z)=>{D(B=>({...B,[J]:!0})),o.submit({action:"mark-reviewed",filePath:J,lastModified:z},{method:"POST",action:"/api/memory",encType:"application/json"})},V=J=>{D(z=>({...z,[J]:!1})),o.submit({action:"mark-unreviewed",filePath:J},{method:"POST",action:"/api/memory",encType:"application/json"})},F=(J,z)=>{A(J),M(z??null)},Y=fe(()=>{let J=t;if(l.trim()){const z=l.toLowerCase();J=J.filter(B=>{var re;return(((re=B.filePath.split("/").pop())==null?void 0:re.replace(".md",""))||"").toLowerCase().includes(z)||B.body.toLowerCase().includes(z)})}return J},[t,l]),P=fe(()=>u?Y.some(z=>z.filePath===u)?Y.filter(z=>z.filePath===u):Y.filter(z=>z.filePath.startsWith(u+"/")||z.filePath===u):Y,[Y,u]),O=(J,z)=>{const B=f?"update":"create";o.submit({action:B,filePath:J,content:z},{method:"POST",action:"/api/memory",encType:"application/json"})},S=J=>{o.submit({action:"delete",filePath:J.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),v(null)},$=fe(()=>{const J=t.filter(z=>L[z.filePath]).length;return{total:t.length,reviewed:J,unreviewed:t.length-J,stale:0}},[t,L]),I=fe(()=>{const J=new Set(["root"]);for(const z of Y){const B=z.filePath.split("/");B.pop();let H="";for(const re of B)H=H?`${H}/${re}`:re,J.add(H)}return J},[Y]),K=I.size===h.size&&[...I].every(J=>h.has(J)),q=()=>{m(K?new Set(["root"]):new Set(I))};return a?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:a})]})}):s?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(bk,{searchFilter:l,onSearchChange:d,onCreateNew:()=>x(!0),onLearnMore:()=>k(!0),reviewCounts:$}),(g||f)&&n("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>{x(!1),y(null)},children:n("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:J=>J.stopPropagation(),children:n(lk,{rule:f,onSave:O,onCancel:()=>{x(!1),y(null)}})})}),c("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(uk,{memories:Y,reviewedStatus:L,onViewRule:F,refreshKey:N}),n(mk,{onEditRule:y,onDeleteRule:v,refreshKey:N,reviewedStatus:L,onMarkReviewed:W,onMarkUnreviewed:V,memories:t,onViewRule:F})]}),c("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(jk,{unreviewedRulePaths:t.filter(J=>!L[J.filePath]).map(J=>J.filePath)}),n(Sk,{})]}),c("div",{className:"flex items-center justify-between mb-4",children:[n("h2",{className:"text-xl leading-6 text-[#232323]",style:{fontFamily:"Sora",fontWeight:600},children:"All Rules"}),n("div",{className:"flex items-center gap-4",children:I.size>1&&n("button",{onClick:q,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:K?"Collapse All":"Expand All"})})]}),c("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(ck,{memories:Y,selectedPath:u,onSelectPath:p,expandedFolders:h,onToggleFolder:R})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?c("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(Cm,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),n("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),c("p",{className:"text-gray-500 mb-4",children:["Run"," ",n("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam-memory"})," ","to generate initial memories for your codebase."]}),c("button",{onClick:()=>x(!0),className:"inline-flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer",children:[n(ri,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):c("div",{children:[u&&c("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:["Showing rules in"," ",n("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:u||"(root)"}),n("button",{onClick:()=>p(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(dk,{memories:P,onEdit:y,onDelete:v,expandedFolders:h,onToggleFolder:R,reviewedStatus:L,onMarkReviewed:W,onMarkUnreviewed:V,onViewRule:F})]})})]}),n("div",{className:"mt-8 mb-8",children:n(Ee,{to:"/agent-transcripts",className:"block bg-white border border-gray-200 rounded-lg p-5 hover:border-[#005C75] hover:shadow-sm transition-all group",children:c("div",{className:"flex items-center gap-3",children:[n("div",{className:"w-10 h-10 rounded-lg bg-[#EDF1F3] flex items-center justify-center",children:c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#005C75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("polyline",{points:"4 17 10 11 4 5"}),n("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}),c("div",{children:[n("h3",{className:"text-sm font-semibold text-[#232323] group-hover:text-[#005C75]",style:{fontFamily:"Sora"},children:"Agent Transcripts"}),n("p",{className:"text-xs text-gray-500",children:"View background agent transcripts and tool call history"})]})]})})}),j&&!f&&(()=>{const J=t.find(z=>z.filePath===j.filePath)??j;return n(fk,{rule:J,changeInfo:_??void 0,isReviewed:L[J.filePath]??!1,onApprove:()=>{L[J.filePath]??!1?V(J.filePath):W(J.filePath,J.lastModified),A(null)},onEdit:()=>{y(J)},onDelete:()=>{v(J),A(null)},onClose:()=>A(null)})})(),C&&n(vk,{onClose:()=>k(!1),onCreateNew:()=>{k(!1),x(!0)}}),b&&n(wk,{rule:b,onConfirm:S,onCancel:()=>v(null)})]})}):n(xk,{})}),Ak=Object.freeze(Object.defineProperty({__proto__:null,default:Pk,loader:Ek,meta:_k},Symbol.toStringTag,{value:"Module"}));function _o(e){return`${e.filePath||""}::${e.name}`}function Qp(e,t){const r=Ke(),{showToast:s}=pi(),[a,o]=E(new Map);se(()=>{if(r.state==="idle"&&r.data){const m=r.data;m!=null&&m.error&&s(`Error: ${m.error}`,"error",6e3)}},[r.state,r.data,s]),se(()=>{var f;if(a.size===0)return;const m=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(y=>{var g;(g=y.entityShas)==null||g.forEach(x=>{a.forEach((b,v)=>{b===x&&m.add(v)})})}),e==null||e.forEach(y=>{a.forEach((g,x)=>{g===y&&m.add(x)})}),m.size>0&&o(y=>{const g=new Map(y);return m.forEach(x=>g.delete(x)),g})},[t,e,a]);const i=le(m=>{console.log("Generate analysis clicked for entity:",m.sha,m.name);const f=_o(m);o(g=>new Map(g).set(f,m.sha));const y=new FormData;y.append("entitySha",m.sha),y.append("filePath",m.filePath||""),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),l=le(m=>{const f=m.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const b=new Map(x);return f.forEach(v=>b.set(_o(v),v.sha)),b});const y=f.map(x=>x.sha).join(","),g=new FormData;g.append("entityShas",y),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),d=le(m=>(e==null?void 0:e.includes(m))??!1,[e]),u=le(m=>{const f=_o(m);return a.has(f)},[a]),p=le(m=>{var f;return((f=t==null?void 0:t.jobs)==null?void 0:f.some(y=>{var g;return(g=y.entityShas)==null?void 0:g.includes(m)}))??!1},[t]),h=fe(()=>Array.from(a.keys()),[a]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:l,isEntityBeingAnalyzed:d,isEntityPending:u,isEntityInQueue:p,pendingEntityKeys:h}}function rl({showActions:e=!1,sortOrder:t="desc",onSortChange:r,onAnalyzeAll:s,analyzeAllDisabled:a=!1,analyzeAllText:o="Analyze All"}){return n("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:c("div",{className:"flex justify-between items-center px-3 py-2",children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:n("span",{children:"STATE"})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:n("span",{children:"SIMULATIONS"})}),c("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),c("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:r,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r==null||r())},children:[n("span",{children:"MODIFIED"}),n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:t==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:n("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&n("div",{className:"text-center",style:{width:"127px"},children:s&&n("button",{onClick:s,disabled:a,className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer disabled:bg-gray-400 disabled:cursor-not-allowed whitespace-nowrap px-3 py-1.5 normal-case",title:a?o:"Analyze all entities",children:o})})]})]})]})})}function Tk({status:e,variant:t="compact"}){const r={modified:{label:"M",bgColor:"bg-[#f59e0c]"},added:{label:"A",bgColor:"bg-emerald-500"},deleted:{label:"D",bgColor:"bg-red-500",showWarning:!0},renamed:{label:"R",bgColor:"bg-indigo-500"},untracked:{label:"U",bgColor:"bg-purple-500"}},s={modified:{label:"MODIFIED",textColor:"#BB6BD9"},added:{label:"ADDED",textColor:"#F2994A"},deleted:{label:"DELETED",textColor:"#EF4444"},renamed:{label:"RENAMED",textColor:"#3B82F6"},untracked:{label:"UNTRACKED",textColor:"#6B7280"}};if(t==="full"){const o=s[e]||{label:"UNKNOWN",textColor:"#6B7280"};return n("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:n("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:o.textColor},children:o.label})})}const a=r[e]||{label:"?",bgColor:"bg-gray-500"};return c("div",{className:"inline-flex items-center gap-1",children:[n("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${a.bgColor}`,title:e,children:a.label}),a.showWarning&&n("span",{className:"inline-flex items-center justify-center w-3 h-3 text-[10px] text-amber-600",title:"Warning: File will be deleted",children:"⚠"})]})}function sl({filePath:e,isExpanded:t,onToggle:r,fileStatus:s,simulationPreviews:a,entityCount:o,state:i,lastModified:l,actionButton:d,uncommittedCount:u,children:p,isNotAnalyzable:h=!1,isUncommitted:m=!1}){return c("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[c("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${h?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:r,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),r())},children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:t?"rotate(90deg)":"none"},children:n("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:n("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:t?"#3e3e3e":"#c7c7c7"})})}),n("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),n(Vd,{filePath:e}),s&&n(Tk,{status:typeof s=="string"?s:s.status,variant:"full"}),m&&i==="out-of-date"&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(m||i==="out-of-date")&&c("div",{className:"flex gap-1.5 items-center",children:[m&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fff3cd",color:"#856404",height:"22px"},children:"Uncommitted"}),i==="out-of-date"&&!m&&n("span",{className:"text-[11px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#fdf9c9",color:"#c69538",height:"22px"},children:"Out of date"})]})}),n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:a}),c("div",{className:"flex gap-4 items-center",children:[n("div",{className:"flex items-center justify-center",style:{width:"70px"},children:n("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:c("span",{className:"text-[13px] text-[#3e3e3e]",children:[o," ",o===1?"entity":"entities"]})})}),n("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:Op(l)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:d})]})]})]}),t&&p&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:p})]})}function al({entities:e,maxPreviews:t=3}){var s,a,o,i,l;const r=[];for(const d of e){if(r.length>=t)break;const u=((a=(s=d.analyses)==null?void 0:s[0])==null?void 0:a.scenarios)||[];if(d.entityType==="library"){const p=u.find(h=>{var m,f;return((m=h.metadata)==null?void 0:m.executionResult)||((f=h.metadata)==null?void 0:f.error)});p&&r.push({type:"library",scenario:p,entitySha:d.sha})}else if(d.entityType==="visual"){const p=u.find(h=>{var m,f;return(f=(m=h.metadata)==null?void 0:m.screenshotPaths)==null?void 0:f[0]});if(p){const h=(i=(o=p.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],m=!!((l=p.metadata)!=null&&l.error);h&&r.push({type:"screenshot",screenshot:h,hasError:m,scenario:p,entitySha:d.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(we,{children:r.map((d,u)=>{if(d.type==="screenshot"&&d.screenshot){const p=d.hasError?"border-red-400":"border-gray-200";return c(Ee,{to:d.scenario?`/entity/${d.entitySha}/scenarios/${d.scenario.id}`:`/entity/${d.entitySha}`,className:`relative w-[50px] h-[38px] border ${p} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:h=>h.stopPropagation(),children:[n(ut,{screenshotPath:d.screenshot,alt:`Preview ${u+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&n("div",{className:"absolute top-0 right-0 w-4 h-4 bg-red-500 text-white flex items-center justify-center text-[10px] rounded-bl",title:"Error during capture",children:n(Ks,{size:12,color:"white"})})]},`screenshot-${u}`)}return d.type==="library"&&d.scenario&&d.entitySha?n(Rp,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${u}`):null})})}function ol({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:s}){var p,h;const a=t||r?[{entityShas:[e.sha]}]:[],o=Et(e,a,t),i=e.entityType==="visual"||e.entityType==="library",l=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,u=(((h=(p=e.analyses)==null?void 0:p[0])==null?void 0:h.scenarios)||[]).filter(m=>{var f,y;return(y=(f=m.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0]});return c("div",{className:"bg-white rounded-lg",children:[c(Ee,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[c("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4 shrink-0"}),e.entityType==="type"?n("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:n("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:n(St,{type:"type"})})}):n(St,{type:e.entityType||"other"}),n("span",{className:`font-['IBM_Plex_Sans'] text-[14px] leading-[18px] text-black ${i?"font-medium":"font-normal"}`,children:e.name}),n(Gi,{type:e.entityType||"other"})]}),c("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),c("div",{className:"flex gap-4 items-center",children:[n("div",{style:{width:"70px"}}),n("div",{style:{width:"116px"}}),n("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?o==="queued"?c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):o==="analyzing"?c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):o==="up-to-date"?n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):o==="out-of-date"?n("button",{onClick:m=>{m.preventDefault(),m.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):l&&n("button",{onClick:m=>{m.preventDefault(),m.stopPropagation(),s(e)},className:"bg-[#e0e9ec] text-[#005c75] rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#d0dfe5] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:"Analyze"}):n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),u.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:u.map((m,f)=>{var g,x;const y=(x=(g=m.metadata)==null?void 0:g.screenshotPaths)==null?void 0:x[0];return y?n(Ee,{to:`/entity/${e.sha}?scenario=${m.id}`,className:"relative w-[120px] h-[90px] border border-gray-200 rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center hover:border-gray-400 transition-colors",onClick:b=>b.stopPropagation(),children:n(ut,{screenshotPath:y,alt:m.name,className:"max-w-full max-h-full object-contain object-center"})},m.id):null})})]})}function Mk({entities:e,page:t,itemsPerPage:r=50,currentRun:s,filter:a,entityType:o,queueState:i,isEntityPending:l,pendingEntityKeys:d,onGenerateSimulation:u,onGenerateAllSimulations:p,totalFilesCount:h,totalEntitiesCount:m,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[x,b]=dr(),[v,N]=E(new Set),[w,C]=E(""),[k,j]=E(!1),[A,_]=E("all"),[M,T]=E("desc"),D=o||"all",R=fe(()=>{let S=e;return D!=="all"&&(S=S.filter($=>$.entityType===D)),a==="analyzed"&&(S=S.filter($=>$.analyses&&$.analyses.length>0)),S},[e,D,a]),L=fe(()=>{const S=new Map,$=new Map,I=new Map;R.forEach(z=>{var re,ae;const B=`${z.filePath}::${z.name}`,H=$.get(B);if(!H)$.set(B,z),I.set(B,[]);else{const X=((re=H.metadata)==null?void 0:re.editedAt)||H.createdAt||"",oe=((ae=z.metadata)==null?void 0:ae.editedAt)||z.createdAt||"";let me=!1;if(oe>X)me=!0;else if(oe===X){const ve=H.createdAt||"";me=(z.createdAt||"")>ve}me?(I.get(B).push(H),$.set(B,z)):I.get(B).push(z)}}),$.forEach((z,B)=>{var re;if(!(z.analyses&&z.analyses.length>0)&&((re=z.metadata)!=null&&re.previousVersionWithAnalyses)){const X=(I.get(B)||[]).find(oe=>{var me;return oe.sha===((me=z.metadata)==null?void 0:me.previousVersionWithAnalyses)});X&&X.analyses&&X.analyses.length>0&&(z.analyses=X.analyses)}}),Array.from($.values()).sort((z,B)=>{var ae,X,oe,me;const H=!((ae=z.metadata)!=null&&ae.notExported)&&!((X=z.metadata)!=null&&X.namedExport),re=!((oe=B.metadata)!=null&&oe.notExported)&&!((me=B.metadata)!=null&&me.namedExport);return H&&!re?-1:!H&&re?1:0}).forEach(z=>{var X,oe,me,ve,je;const B=z.filePath??"No File Path";S.has(B)||S.set(B,{filePath:B,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const H=S.get(B);H.entities.push(z),H.totalCount++,(X=z.metadata)!=null&&X.isUncommitted&&H.uncommittedCount++;const re=((ve=(me=(oe=z.analyses)==null?void 0:oe[0])==null?void 0:me.scenarios)==null?void 0:ve.length)||0;H.simulationCount+=re;const ae=((je=z.metadata)==null?void 0:je.editedAt)||z.updatedAt;ae&&(!H.lastUpdated||new Date(ae)>new Date(H.lastUpdated))&&(H.lastUpdated=ae)});const K=(i==null?void 0:i.jobs)||[],q=z=>{const B=`${z.filePath||""}::${z.name}`;return(d==null?void 0:d.includes(B))||!1};S.forEach(z=>{const B=z.entities.map(H=>q(H)?"queued":Et(H,K));B.includes("analyzing")||B.includes("queued")?z.state="analyzing":B.includes("incomplete")?z.state="incomplete":B.includes("out-of-date")?z.state="out-of-date":B.includes("not-analyzed")?z.state="not-analyzed":z.state="up-to-date"}),S.forEach(z=>{var B,H,re,ae,X;for(const oe of z.entities){if(z.previewScreenshots.length+z.previewLibraryScenarios.length>=3)break;const ve=((H=(B=oe.analyses)==null?void 0:B[0])==null?void 0:H.scenarios)||[];if(oe.entityType==="library"){const je=ve.find(te=>{var ke,Z;return((ke=te.metadata)==null?void 0:ke.executionResult)||((Z=te.metadata)==null?void 0:Z.error)});je&&z.previewLibraryScenarios.push({scenario:je,entitySha:oe.sha})}else{const je=ve.find(te=>{var ke,Z;return(Z=(ke=te.metadata)==null?void 0:ke.screenshotPaths)==null?void 0:Z[0]});if(je){const te=(ae=(re=je.metadata)==null?void 0:re.screenshotPaths)==null?void 0:ae[0],ke=!!((X=je.metadata)!=null&&X.error);te&&!z.previewScreenshots.includes(te)&&(z.previewScreenshots.push(te),z.previewScreenshotErrors.push(ke))}}}});const J=Array.from(S.values());return J.sort((z,B)=>{if(a==="analyzed"){const ae=Math.max(...z.entities.filter(oe=>{var me,ve;return(ve=(me=oe.analyses)==null?void 0:me[0])==null?void 0:ve.createdAt}).map(oe=>new Date(oe.analyses[0].createdAt).getTime()),0),X=Math.max(...B.entities.filter(oe=>{var me,ve;return(ve=(me=oe.analyses)==null?void 0:me[0])==null?void 0:ve.createdAt}).map(oe=>new Date(oe.analyses[0].createdAt).getTime()),0);return M==="desc"?X-ae:ae-X}if(z.uncommittedCount>0&&B.uncommittedCount===0)return-1;if(z.uncommittedCount===0&&B.uncommittedCount>0)return 1;const H=z.lastUpdated?new Date(z.lastUpdated).getTime():0,re=B.lastUpdated?new Date(B.lastUpdated).getTime():0;return M==="desc"?re-H:H-re}),J},[R,a,M,i,d]),U=fe(()=>{let S=L;if(A!=="all"&&(S=S.filter($=>$.state===A)),w.trim()){const $=w.toLowerCase();S=S.filter(I=>I.filePath.toLowerCase().includes($))}return S},[L,w,A]),W=(t-1)*r,V=W+r,F=U.slice(W,V),Y=Math.ceil(U.length/r),P=S=>{N($=>{const I=new Set($);return I.has(S)?I.delete(S):I.add(S),I})},O=()=>{T(S=>S==="desc"?"asc":"desc")};return c("div",{children:[c("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),c("div",{className:"flex gap-3",children:[c("div",{className:"relative w-[130px]",children:[c("select",{value:D,onChange:S=>{const $=S.target.value,I=new URLSearchParams(x);$==="all"?I.delete("entityType"):I.set("entityType",$),I.set("page","1"),b(I)},className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All Types"}),n("option",{value:"visual",children:"Visual"}),n("option",{value:"library",children:"Library"})]}),n(Tt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"relative w-[130px]",children:[c("select",{value:A,onChange:S=>_(S.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[n("option",{value:"all",children:"All States"}),n("option",{value:"analyzing",children:"Analyzing..."}),n("option",{value:"up-to-date",children:"Up to date"}),n("option",{value:"incomplete",children:"Incomplete"}),n("option",{value:"out-of-date",children:"Out of date"}),n("option",{value:"not-analyzed",children:"Not analyzed"})]}),n(Tt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),c("div",{className:"flex-1 relative",children:[n(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",placeholder:"Search component",value:w,onChange:S=>C(S.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),h!==void 0&&m!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center",children:[c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:U.length})," ",U.length===1?"file":"files"]}),c("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:U.reduce((S,$)=>S+$.totalCount,0)})," ",U.reduce((S,$)=>S+$.totalCount,0)===1?"entity":"entities"]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),y?c("button",{onClick:g,className:"flex items-center gap-2 text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase cursor-pointer",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[U.filter(S=>S.uncommittedCount>0).length," ","uncommitted"," ",U.filter(S=>S.uncommittedCount>0).length===1?"file":"files",n("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):c("button",{onClick:g,className:"text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[f," uncommitted"," ",f===1?"file":"files"]})]}),F.length>0&&c("div",{className:"flex gap-6",children:[c("button",{onClick:()=>{N(new Set(F.map(S=>S.filePath))),j(!0)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Bd,{className:"w-3.5 h-3.5"}),"Expand All"]}),c("button",{onClick:()=>{N(new Set),j(!1)},className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(zd,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(rl,{showActions:!0,sortOrder:M,onSortChange:O}),n("div",{className:"flex flex-col gap-[3px]",children:F.map(S=>{const $=v.has(S.filePath),K=S.entities.filter(B=>(B.entityType==="visual"||B.entityType==="library")&&(Et(B,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Et(B,(i==null?void 0:i.jobs)||[])==="out-of-date"||Et(B,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,q=B=>{var H;return((H=s==null?void 0:s.currentEntityShas)==null?void 0:H.includes(B))||!1},J=B=>{var H;return l!=null&&l(B)?!0:((H=i==null?void 0:i.jobs)==null?void 0:H.some(re=>{var ae;return(ae=re.entityShas)==null?void 0:ae.includes(B.sha)}))||!1},z=B=>{u==null||u(B)};return n(sl,{filePath:S.filePath,isExpanded:$,onToggle:()=>P(S.filePath),simulationPreviews:n(al,{entities:S.entities,maxPreviews:1}),entityCount:S.totalCount,state:S.state,lastModified:S.lastUpdated,uncommittedCount:S.uncommittedCount,isUncommitted:S.uncommittedCount>0,actionButton:K?n("button",{onClick:B=>{B.stopPropagation();const H=S.entities.filter(re=>(re.entityType==="visual"||re.entityType==="library")&&(Et(re,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Et(re,(i==null?void 0:i.jobs)||[])==="out-of-date"||Et(re,(i==null?void 0:i.jobs)||[])==="incomplete"));p==null||p(H)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:S.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:S.entities.sort((B,H)=>{var me,ve,je,te;const re=!((me=B.metadata)!=null&&me.notExported)&&!((ve=B.metadata)!=null&&ve.namedExport),ae=!((je=H.metadata)!=null&&je.notExported)&&!((te=H.metadata)!=null&&te.namedExport);if(re&&!ae)return-1;if(!re&&ae)return 1;const X=B.entityType==="visual"||B.entityType==="library",oe=H.entityType==="visual"||H.entityType==="library";return X&&!oe?-1:!X&&oe?1:B.name.localeCompare(H.name)}).map(B=>n(ol,{entity:B,isActivelyAnalyzing:q(B.sha),isQueued:J(B),onGenerateSimulation:z},B.sha))},S.filePath)})}),Y>1&&c("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[t>1&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),c("span",{children:["Page ",t," of ",Y]}),t<Y&&n("a",{href:`?${new URLSearchParams({...Object.fromEntries(x),page:String(t+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const $k=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function Fk({request:e,context:t}){try{const r=new URL(e.url),s=parseInt(r.searchParams.get("page")||"1"),a=r.searchParams.get("filter")||null,o=r.searchParams.get("entityType"),i=t.analysisQueue,l=i?i.getState():{paused:!1,jobs:[]},[d,u]=await Promise.all([Yn(),fr()]);return ue({entities:d,currentCommit:u,page:s,filter:a,entityType:o,queueState:l})}catch(r){return console.error("Failed to load entities:",r),ue({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const Dk=tt(function(){var w,C,k;const{entities:t,currentCommit:r,page:s,filter:a,entityType:o,queueState:i,error:l}=lt();Ut();const[d,u]=dr(),[p,h]=E(!1);Wt({source:"files-page"});const{handleGenerateSimulation:m,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=Qp((C=(w=r==null?void 0:r.metadata)==null?void 0:w.currentRun)==null?void 0:C.currentEntityShas,i),x=t||[],b=fe(()=>{const j=new Set([]);for(const A of x)j.add(A.filePath??"No File Path");return Array.from(j)},[x]),v=fe(()=>{let j=x;return p&&(j=j.filter(A=>{var _;return(_=A.metadata)==null?void 0:_.isUncommitted})),j.sort((A,_)=>{var M,T,D,R,L,U;return(M=A.metadata)!=null&&M.isUncommitted&&!((T=_.metadata)!=null&&T.isUncommitted)?-1:!((D=A.metadata)!=null&&D.isUncommitted)&&((R=_.metadata)!=null&&R.isUncommitted)?1:new Date(((L=_.metadata)==null?void 0:L.editedAt)||0).getTime()-new Date(((U=A.metadata)==null?void 0:U.editedAt)||0).getTime()})},[x,p]),N=fe(()=>{var A;const j=new Set([]);for(const _ of x)(A=_.metadata)!=null&&A.isUncommitted&&j.add(_.filePath??"No File Path");return Array.from(j)},[x]);return l?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-12 py-6 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),n("p",{className:"text-base text-gray-500",children:l})]})}):x.length===0?n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:c("div",{className:"max-w-md mx-auto",children:[n("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),c("p",{className:"text-[15px] text-gray-600 mb-6",children:["Your project hasn't been analyzed yet. Run"," ",n("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),n("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):n("div",{className:"bg-[#f9f9f9] min-h-screen",children:c("div",{className:"px-20 py-12 font-sans",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),n("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),n(Mk,{entities:v,page:s,itemsPerPage:50,currentRun:(k=r==null?void 0:r.metadata)==null?void 0:k.currentRun,filter:a,entityType:o,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:m,onGenerateAllSimulations:f,totalFilesCount:b.length,totalEntitiesCount:x.length,uncommittedFilesCount:N.length,showOnlyUncommitted:p,onToggleUncommitted:()=>h(!p)})]})})}),Rk=Object.freeze(Object.defineProperty({__proto__:null,default:Dk,loader:Fk,meta:$k},Symbol.toStringTag,{value:"Module"})),Ik=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function Ok({request:e}){var t;try{const r=await ze();if(!r)return ue({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:s}=await Ie(r),a=Ce()||process.cwd(),o=jp(a)||"";let i="";try{const d=await va();if(d!=null&&d.webapps&&Array.isArray(d.webapps)){const u=d.webapps.map(p=>p.framework).filter(Boolean);u.length>0&&(i=u.join(", "))}}catch{}const l=Dp(r);return ue({labs:((t=s.metadata)==null?void 0:t.labs)??null,projectSlug:r,defaultEmail:o,detectedTechStack:i,unlockCode:l,error:null})}catch(r){return console.error("Failed to load labs config:",r),ue({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function Lk({request:e}){try{const t=await e.formData(),r=t.get("feature"),s=t.get("enabled")==="true";if(!r)return ue({success:!1,error:"Missing feature name"},{status:400});const a=await ze();return a?(r==="clearAccess"?await ir({projectSlug:a,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await ir({projectSlug:a,metadataUpdate:{labs:{[r]:s}}}),ue({success:!0,error:null})):ue({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),ue({success:!1,error:"Failed to save labs configuration"},{status:500})}}const Bk=[{id:"simulations",name:"Simulations",description:"Enable entity analysis, visual simulations, git impact analysis, file browsing, and activity monitoring. When disabled, only Memory, Labs, and Settings are accessible.",defaultEnabled:!0},{id:"enhancedClaudeTesting",name:"Enhanced Claude Testing",description:"Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!0},{id:"gitIntegration",name:"Git Integration Showing Impacted Files",description:"Lorem Ipsum Automatically generated mock data that covers the scenarios you actually care about: empty states, error states, auth flows, broken images, missing permissions.",defaultEnabled:!1}],id="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",zk=[{title:"CodeYam Simulations",status:"apply for early access",desc:"CodeYam Simulations are the core of the CodeYam development experience. They leverage static code analysis and AI to generate robust data scenarios that are used to hydrate code. This creates a whole new dimension to the software development experience"},{title:"The Full CodeYam Experience",status:"more to come",desc:"CodeYam is completely rethinking the software development experience in the AI era. Focused on navigating the challenges of iteration speed, complexity, and communication, CodeYam will provide a powerful software development experience."}];function Yk({onClose:e}){const t=be(null),r=be(0);return se(()=>{const s=t.current;if(!s)return;const a=100,o=2e3,i=500;let l=null,d=!1;const u=()=>{r.current=Date.now(),!l&&!d&&(l=setInterval(()=>{const p=Date.now()-r.current,h=s.scrollTop>a,m=p>o;h&&m&&(s.scrollTo({top:0,behavior:"smooth"}),d=!0,l&&(clearInterval(l),l=null))},i))};return s.addEventListener("scroll",u,{passive:!0}),()=>{s.removeEventListener("scroll",u),l&&clearInterval(l)}},[]),c("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:s=>{s.target===s.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),c("div",{className:"relative bg-white rounded-xl max-w-3xl w-full mx-4 max-h-[90vh] overflow-hidden",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none z-10",children:"×"}),c("div",{ref:t,className:"overflow-y-auto max-h-[90vh] p-4 md:p-6",children:[c("div",{className:"mb-4",children:[n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Request Early Access"}),n("p",{className:"text-sm text-gray-500",children:"Complete the form below to join the waitlist for CodeYam Labs."})]}),n("div",{className:"bg-white rounded-lg overflow-hidden",children:n("iframe",{src:`${id}?embedded=true`,width:"100%",height:"1400",style:{border:0,minHeight:"1400px"},title:"Labs Waitlist Form",loading:"eager",children:n("div",{className:"flex items-center justify-center p-8 text-gray-600",children:c("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),c("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:id,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})]})}function Uk({onClose:e,unlockCodeInput:t,setUnlockCodeInput:r,unlockFetcher:s}){var i,l;const a=(i=s.data)==null?void 0:i.error,o=(l=s.data)==null?void 0:l.success;return c("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:d=>{d.target===d.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),c("div",{className:"relative bg-white rounded-xl p-8 max-w-md w-full mx-4",children:[n("button",{onClick:e,className:"absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-2xl leading-none cursor-pointer bg-transparent border-none",children:"×"}),n("h3",{className:"font-serif italic text-2xl text-primary-200 mb-2",children:"Have an unlock code?"}),n("p",{className:"text-sm text-cygray-50 mb-6",children:"If you've received an unlock code, paste it below to enable Simulations immediately."}),c(s.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:d=>r(d.target.value),placeholder:"CY-...",className:"w-full px-4 py-2.5 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-primary-100 focus:border-transparent"}),n("button",{type:"submit",disabled:!t.trim()||s.state==="submitting",className:"w-full py-3 text-white border-none rounded-lg text-sm font-mono font-semibold uppercase tracking-wider cursor-pointer transition-all bg-primary-200 hover:bg-primary-100 disabled:bg-gray-400 disabled:cursor-not-allowed",children:s.state==="submitting"?"Validating...":"Unlock"}),a&&n("p",{className:"text-red-600 text-sm mt-2",children:a}),o&&n("p",{className:"text-emerald-600 text-sm mt-2",children:"Simulations enabled! Refresh the page to see all tabs."})]})]})]})}const Wk=tt(function(){const{labs:t,unlockCode:r,error:s}=lt(),a=Ke(),o=Ke(),i=Ke(),[l,d]=E(""),[u,p]=E(!1),[h,m]=E(!1);Wt({source:"labs-page"});const f=(t==null?void 0:t.accessGranted)===!0||(t==null?void 0:t.simulations)===!0;return s?n("div",{className:"bg-cygray-10 min-h-screen",children:c("div",{className:"px-20 pt-8 pb-12 font-sans",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Labs"}),n("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 mt-4",children:n("p",{className:"text-red-700",children:s})})]})}):f?c("div",{className:"bg-cygray-10 min-h-screen font-sans flex flex-col",children:[n("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"})}),c("div",{className:"px-6 sm:px-12 pt-8 pb-10",children:[n("h2",{className:"font-serif italic text-[32px] sm:text-[48px] text-primary-100 mb-3 font-normal leading-tight",children:"Congrats!"}),n("p",{className:"font-serif text-[18px] sm:text-[24px] text-cyblack-100 font-normal leading-snug max-w-2xl",children:"You were granted early access to software simulation and other experimental features."})]}),n("div",{className:"px-6 sm:px-12 space-y-6 flex-1",children:Bk.map(y=>{var b;const g=(t==null?void 0:t[y.id])??y.defaultEnabled,x=o.state==="submitting"&&((b=o.formData)==null?void 0:b.get("feature"))===y.id;return n("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:c("div",{className:"flex items-center justify-between gap-4",children:[c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children:y.name}),n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${g?"bg-primary-100/15 text-primary-100":"bg-cygray-20 text-cygray-50"}`,children:g?"Enabled":"Disabled"})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed m-0",children:y.description})]}),c(o.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:y.id}),n("input",{type:"hidden",name:"enabled",value:String(!g)}),n("button",{type:"submit",disabled:x,className:`relative inline-flex h-8 w-14 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none disabled:opacity-60 disabled:cursor-not-allowed ${g?"bg-primary-100":"bg-gray-300"}`,children:n("span",{className:`pointer-events-none inline-block h-7 w-7 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${g?"translate-x-6":"translate-x-0"}`})})]})]})},y.id)})}),r&&n("div",{className:"px-6 sm:px-12 pt-12",children:c("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:[n("h3",{className:"text-base font-semibold text-cyblack-100 mb-1",children:"Unlock Code"}),n("p",{className:"text-sm text-cygray-50 mb-3",children:"This code was used to enable Labs access. Clear it to revoke access and return to the landing page."}),c("div",{className:"flex flex-col sm:flex-row sm:items-center gap-3",children:[n("code",{className:"sm:flex-1 px-4 py-2.5 bg-cygray-10 border border-cygray-30 rounded-lg text-sm font-mono text-cyblack-100 overflow-x-auto",children:r}),c(i.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:"clearAccess"}),n("input",{type:"hidden",name:"enabled",value:"false"}),n("button",{type:"submit",disabled:i.state==="submitting",className:"px-4 py-2.5 bg-red-50 border border-red-200 rounded-lg text-sm font-medium text-red-700 cursor-pointer transition-colors hover:bg-red-100 disabled:opacity-60 disabled:cursor-not-allowed",children:i.state==="submitting"?"Clearing...":"Clear"})]})]})]})})]}):c("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[u&&n(Yk,{onClose:()=>p(!1)}),h&&n(Uk,{onClose:()=>m(!1),unlockCodeInput:l,setUnlockCodeInput:d,unlockFetcher:a}),c("div",{className:"flex flex-wrap justify-between items-center gap-3 px-6 sm:px-12 pt-8 pb-4",children:[n("h1",{className:"font-mono text-lg font-semibold tracking-widest text-cyblack-100 m-0",children:"LABS"}),c("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>m(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cygray-30 bg-transparent text-cygray-50 cursor-pointer transition-colors hover:border-cyblack-100 hover:text-cyblack-100",children:"Have a Code?"}),n("button",{onClick:()=>p(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-4 sm:px-5 py-2.5 rounded border border-cyblack-100 bg-transparent text-cyblack-100 cursor-pointer transition-colors hover:bg-cyblack-100 hover:text-white",children:"Apply for Early Access"})]})]}),c("div",{className:"px-6 sm:px-12 pt-12 pb-8",children:[n("h2",{className:"font-serif text-[24px] sm:text-[32px] leading-snug text-cyblack-100 max-w-xl mb-4 font-normal",children:"Powerful tools for the AI coding era."}),c("p",{className:"text-base sm:text-lg text-cygray-50 leading-relaxed max-w-xl mb-8",children:["We're opening early access to"," ",n("strong",{className:"text-cyblack-100",children:"experimental features"})," to a small group of developers and teams."]}),n("button",{onClick:()=>p(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded bg-primary-200 text-white border-none cursor-pointer transition-colors hover:bg-primary-100",children:"Apply for Early Access"})]}),n("div",{className:"px-6 sm:px-12 py-8",children:n("hr",{className:"border-t border-cygray-30 m-0"})}),c("div",{className:"px-6 sm:px-12 pt-8 pb-4",children:[n("h3",{className:"font-serif text-[22px] sm:text-[28px] text-cyblack-100 mb-10 font-normal text-center",children:"In The Works"}),n("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5 max-w-4xl mx-auto",children:zk.map(y=>c("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[c("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[y.title," ",c("span",{className:"font-normal text-primary-100 font-serif italic",children:["(",y.status,")"]})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed mt-3 mb-0",children:y.desc})]},y.title))})]}),n("div",{className:"px-6 sm:px-12 py-16",children:c("div",{className:"rounded-lg p-6 sm:p-12 bg-primary-200",children:[n("h3",{className:"font-serif text-[20px] sm:text-[24px] text-white mb-4 font-semibold",children:"Request Early Access"}),n("p",{className:"text-sm text-white/80 leading-relaxed max-w-lg mb-10 font-mono",children:"We're onboarding a limited number of developers and teams. Tell us about how you build and we'll let you know when you can try simulations and other Labs features."}),n("button",{onClick:()=>p(!0),className:"font-mono text-xs font-semibold uppercase tracking-widest px-6 py-3 rounded border border-white bg-white text-cyblack-100 cursor-pointer transition-colors hover:bg-white/90 mb-4",children:"Apply for Early Access"}),n("p",{className:"text-xs text-white/60 m-0",children:"Takes about 2 minutes. Your answers help us determine eligibility and prioritize access."})]})})]})}),Jk=Object.freeze(Object.defineProperty({__proto__:null,action:Lk,default:Wk,loader:Ok,meta:Ik},Symbol.toStringTag,{value:"Module"}));function Hk(e,t,r){const[s,a]=E(()=>new Set),[o,i]=E(()=>new Set),l=be([]),d=be([]);return se(()=>{(t.length!==l.current.length||t.some((g,x)=>g!==l.current[x]))&&(l.current=t,a(g=>{const x=new Set;return t.forEach(b=>{g.has(b)&&x.add(b)}),x}))},[t]),se(()=>{(r.length!==d.current.length||r.some((g,x)=>g!==d.current[x]))&&(d.current=r,i(g=>{const x=new Set;return r.forEach(b=>{g.has(b)&&x.add(b)}),x}))},[r]),{expandedUncommitted:s,expandedBranch:o,setExpandedUncommitted:a,setExpandedBranch:i,toggleFile:(y,g,x)=>{x(b=>{const v=new Set(b);return v.has(y)?v.delete(y):v.add(y),v})},expandAllUncommitted:()=>{a(new Set(t))},collapseAllUncommitted:()=>{a(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function Vk(e,t,r){const[s,a]=E(null),[o,i]=E(null),l=Ke();se(()=>{var h,m;((h=l.data)==null?void 0:h.oldContent)!==void 0&&((m=l.data)==null?void 0:m.newContent)!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const d=h=>{a({type:"file",path:h}),i(null);const m=new FormData;m.append("actionType","getDiff"),m.append("filePath",h),m.append("diffType","branch"),m.append("baseBranch",e),m.append("currentBranch",t||""),l.submit(m,{method:"post"})},u=(h,m)=>{a({type:"entity",path:h,entitySha:m}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",h),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",m),l.submit(f,{method:"post"})},p=()=>{a(null),i(null)};return{diffView:s,diffContent:o,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:u,handleCloseDiff:p}}function Kk({diffView:e,diffContent:t,isLoading:r,entities:s,onClose:a}){var u;const[o,i]=E(!1),[l,d]=E(!1);return se(()=>{d(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:c("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[c("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[c("div",{children:[n("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),n("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&c("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((u=s.find(p=>p.sha===e.entitySha))==null?void 0:u.name)||e.entitySha]})]}),c("div",{className:"flex items-center gap-3",children:[n("button",{onClick:()=>i(!o),className:"px-3 py-1.5 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] text-sm font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",title:o?"Show changes only":"Show full file",children:o?"Show Changes Only":"Show Full File"}),n("button",{onClick:a,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:n("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),n("div",{className:"flex-1 overflow-auto",children:r?n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):t?n("div",{className:"diff-viewer-wrapper",children:l&&n(Zm,{oldValue:t.oldContent,newValue:t.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!o,extraLinesSurroundingDiff:4,styles:{variables:{light:{diffViewerBackground:"#fff",diffViewerColor:"#212529",addedBackground:"#e6ffed",addedColor:"#24292e",removedBackground:"#ffeef0",removedColor:"#24292e",wordAddedBackground:"#acf2bd",wordRemovedBackground:"#fdb8c0",addedGutterBackground:"#cdffd8",removedGutterBackground:"#ffdce0",gutterBackground:"#f6f8fa",gutterBackgroundDark:"#f3f4f6",highlightBackground:"#fffbdd",highlightGutterBackground:"#fff5b1"}},contentText:{fontSize:"12px",lineHeight:"1.5"},line:{padding:"2px 10px",fontSize:"12px","&:hover":{background:"#f8f9fa"}},splitView:{display:"flex",width:"100%"},diffContainer:{width:"50%",overflowX:"auto"}}})}):n("div",{className:"p-6 text-center",children:n("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),n("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:n("button",{onClick:a,className:"px-4 py-2 bg-[#efefef] text-[#3e3e3e] rounded-lg font-['IBM_Plex_Sans'] font-semibold hover:bg-[#e1e1e1] transition-colors cursor-pointer",children:"Close"})})]})})}function Gk({files:e,currentBranch:t,defaultBranch:r,baseBranch:s,allBranches:a,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:d,onToggleFile:u,onBranchChange:p,onGenerateSimulation:h,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=e.flatMap(([N,{entities:w}])=>{const C=w.filter(k=>i(k.sha)||l(k)).map(k=>k.sha);return C.length>0?[{entityShas:C}]:[]}),b=N=>{const w=N.map(C=>Et(C,x));return w.includes("analyzing")||w.includes("queued")?"analyzing":w.includes("out-of-date")?"out-of-date":w.includes("not-analyzed")?"not-analyzed":"up-to-date"},v=fe(()=>[...e].sort((N,w)=>{const C=N[1].entities.reduce((_,M)=>{var D;const T=((D=M.metadata)==null?void 0:D.editedAt)||M.updatedAt;return T?_?new Date(T)>new Date(_)?T:_:T:_},null),k=w[1].entities.reduce((_,M)=>{var D;const T=((D=M.metadata)==null?void 0:D.editedAt)||M.updatedAt;return T?_?new Date(T)>new Date(_)?T:_:T:_},null);if(!C&&!k)return 0;if(!C)return 1;if(!k)return-1;const j=new Date(C).getTime(),A=new Date(k).getTime();return d==="desc"?A-j:j-A}),[e,d]);return n("div",{children:e.length>0?c("div",{children:[n(rl,{showActions:!0,sortOrder:d,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:v.map(([N,{status:w,entities:C,isUncommitted:k}])=>{const j=o.has(N),A=b(C),_=C.reduce((R,L)=>{var W;const U=((W=L.metadata)==null?void 0:W.editedAt)||L.updatedAt;return U?R?new Date(U)>new Date(R)?U:R:U:R},null),T=C.filter(R=>R.entityType==="visual"||R.entityType==="library").length===0;let D;return T?D=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):A==="analyzing"?D=c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):A==="up-to-date"?D=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):A==="out-of-date"?D=n("button",{onClick:R=>{R.stopPropagation(),C.filter(L=>(L.entityType==="visual"||L.entityType==="library")&&!i(L.sha)&&!l(L)).forEach(L=>h(L))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):A==="not-analyzed"&&(D=n("button",{onClick:R=>{R.stopPropagation(),C.filter(L=>(L.entityType==="visual"||L.entityType==="library")&&!i(L.sha)&&!l(L)).forEach(L=>h(L))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(sl,{filePath:N,isExpanded:j,onToggle:()=>u(N),fileStatus:w,isUncommitted:k,simulationPreviews:n(al,{entities:C,maxPreviews:1}),entityCount:C.length,state:A,lastModified:_,isNotAnalyzable:T,actionButton:D,children:C.sort((R,L)=>{const U=R.entityType==="visual"||R.entityType==="library",W=L.entityType==="visual"||L.entityType==="library";return U&&!W?-1:!U&&W?1:0}).map(R=>n(ol,{entity:R,isActivelyAnalyzing:i(R.sha),isQueued:l(R),onGenerateSimulation:h},R.sha))},N)})})]}):c("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function qk({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:s,isEntityQueued:a,projectSlug:o,baseBranch:i,currentBranch:l,sortOrder:d,onToggleFile:u,onShowFileDiff:p,onGenerateSimulation:h,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const x=fe(()=>{const N=[];return e.forEach(([w,{editedEntities:C}])=>{const k=C.filter(j=>s(j.sha)||a(j)).map(j=>j.sha);k.length>0&&N.push({entityShas:k})}),N},[e,s,a]),b=fe(()=>{const N=new Map;return e.forEach(([w,{editedEntities:C}])=>{const k=C.map(M=>Et(M,x));let j;k.includes("analyzing")||k.includes("queued")?j="analyzing":k.includes("out-of-date")?j="out-of-date":k.includes("not-analyzed")?j="not-analyzed":j="up-to-date";const A=C.reduce((M,T)=>{var R;const D=((R=T.metadata)==null?void 0:R.editedAt)||T.updatedAt;return D&&(!M||new Date(D)>new Date(M))?D:M},null),_=C.filter(M=>M.entityType==="visual"||M.entityType==="library").length;N.set(w,{state:j,lastModified:A,analyzableCount:_})}),N},[e,x]),v=fe(()=>[...e].sort((N,w)=>{const C=b.get(N[0]),k=b.get(w[0]),j=C==null?void 0:C.lastModified,A=k==null?void 0:k.lastModified;if(!j&&!A)return 0;if(!j)return 1;if(!A)return-1;const _=new Date(j).getTime(),M=new Date(A).getTime();return d==="desc"?M-_:_-M}),[e,b,d]);return e.length===0?c("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[n("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),n("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"If you edit a file in your project, it will show up here."})]}):c("div",{children:[n(rl,{showActions:!0,sortOrder:d,onSortChange:m,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),n("div",{className:"flex flex-col gap-[3px]",children:v.map(([N,{status:w,editedEntities:C}])=>{const k=r.has(N),j=b.get(N),{state:A,lastModified:_,analyzableCount:M}=j,T=M===0;let D;return T?D=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):A==="analyzing"?D=c("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[c("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[n("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),n("path",{d:"M4.5 1C2.57 1 1 2.57 1 4.5C1 5.6 1.5 6.58 2.28 7.23",stroke:"#FF2AB5",strokeWidth:"1",strokeLinecap:"round",fill:"none"})]}),"Analyzing..."]}):A==="up-to-date"?D=n("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#e8ffe6",color:"#00925d",height:"26px"},children:"Up to date"}):A==="out-of-date"?D=n("button",{onClick:R=>{R.stopPropagation(),C.filter(L=>(L.entityType==="visual"||L.entityType==="library")&&!s(L.sha)&&!a(L)).forEach(L=>h(L))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Re-Analyze"}):A==="not-analyzed"&&(D=n("button",{onClick:R=>{R.stopPropagation(),C.filter(L=>(L.entityType==="visual"||L.entityType==="library")&&!s(L.sha)&&!a(L)).forEach(L=>h(L))},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors px-[15px] py-0 h-[28px]",children:"Analyze File"})),n(sl,{filePath:N,isExpanded:k,onToggle:()=>u(N),fileStatus:w,simulationPreviews:n(al,{entities:C,maxPreviews:1}),entityCount:C.length,state:A,lastModified:_,isNotAnalyzable:T,isUncommitted:!0,actionButton:D,children:C.sort((R,L)=>{const U=R.entityType==="visual"||R.entityType==="library",W=L.entityType==="visual"||L.entityType==="library";return U&&!W?-1:!U&&W?1:0}).map(R=>n(ol,{entity:R,isActivelyAnalyzing:s(R.sha),isQueued:a(R),onGenerateSimulation:h},R.sha))},N)})})]})}function Qk({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:s}){return n("div",{className:"border-b border-gray-200",children:c("nav",{className:"flex gap-8 items-center",children:[c("button",{onClick:()=>t("branch"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="branch"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[c("span",{className:"flex items-center gap-2",children:["Branch Changes",s>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="branch"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:s})]}),e==="branch"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),c("button",{onClick:()=>t("uncommitted"),className:`relative pb-3 px-2 text-sm font-medium transition-colors cursor-pointer ${e==="uncommitted"?"text-primary-100":"text-gray-500 hover:text-gray-700"}`,children:[c("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",r>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${e==="uncommitted"?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:r})]}),e==="uncommitted"&&n("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const Zk=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function Xk({request:e}){const t=await e.formData();if(t.get("actionType")==="getDiff"){const s=t.get("filePath"),a=t.get("diffType"),o=t.get("baseBranch"),i=t.get("currentBranch"),l=t.get("entitySha");let d;return a==="branch"?d=Ys(s,o,i):d=Cb(s),ue({...d,entitySha:l})}return ue({error:"Unknown action"},{status:400})}async function e5({request:e,context:t}){try{const r=new URL(e.url),s=r.searchParams.get("compare"),a=r.searchParams.get("viewBranch"),o=t.analysisQueue,i=o?o.getState():{paused:!1,jobs:[]},[l,d,u]=await Promise.all([Yn(),fr(),ze()]),p=xr(),h=vb(),m=wb(),f=Nb(),y=a||h,g=s||m;let x=[];return y&&y!==g&&(x=np(g,y)),ue({entities:l||[],gitStatus:p,currentBranch:y,actualCurrentBranch:h,defaultBranch:m,allBranches:f,baseBranch:g,branchDiff:x,currentCommit:d,projectSlug:u,queueState:i})}catch(r){return console.error("Failed to load git data:",r),ue({entities:[],gitStatus:[],currentBranch:null,actualCurrentBranch:null,defaultBranch:"main",allBranches:[],baseBranch:"main",branchDiff:[],currentCommit:null,projectSlug:null,queueState:{paused:!1,jobs:[]},error:"Failed to load git data"})}}const t5=tt(function(){var he,_e;const{entities:t,gitStatus:r,currentBranch:s,actualCurrentBranch:a,defaultBranch:o,allBranches:i,baseBranch:l,branchDiff:d,currentCommit:u,projectSlug:p,queueState:h}=lt();Wt({source:"git-page"});const[m,f]=dr(),[y,g]=E(null),[x,b]=E("desc"),[v,N]=E("branch"),w=m.get("expanded")==="true",C=()=>{b(ye=>ye==="desc"?"asc":"desc")},k=Ke(),j=k.data;se(()=>{s&&l&&s!==l&&k.state==="idle"&&!j&&k.load(`/api/branch-entity-diff?base=${encodeURIComponent(l)}&compare=${encodeURIComponent(s)}`)},[s,l,k,j]);const A=fe(()=>{const ye=Hp(r,t);return Array.from(ye.entries()).sort((Re,Je)=>Re[0].localeCompare(Je[0]))},[r,t]),_=fe(()=>{const ye=Z2(d,t,j);return Array.from(ye.entries()).sort((Re,Je)=>Re[0].localeCompare(Je[0]))},[d,t,j]),M=fe(()=>X2(r,t),[r,t]),T=fe(()=>v==="uncommitted"?A:_,[v,A,_]),D=fe(()=>T.map(([ye])=>ye),[T]),{expandedUncommitted:R,setExpandedUncommitted:L,toggleFile:U,expandAllUncommitted:W,collapseAllUncommitted:V}=Hk(w,D,[]),{diffView:F,diffContent:Y,isLoading:P,handleShowFileDiff:O,handleCloseDiff:S}=Vk(l,s),$=(he=u==null?void 0:u.metadata)==null?void 0:he.currentRun,I=new Set(($==null?void 0:$.currentEntityShas)||[]),K=new Set(h.jobs.flatMap(ye=>ye.entityShas||[])),q=new Set(((_e=h.currentlyExecuting)==null?void 0:_e.entityShas)||[]),{isAnalyzing:J,handleGenerateSimulation:z,handleGenerateAllSimulations:B,isEntityBeingAnalyzed:H,isEntityPending:re}=Qp($==null?void 0:$.currentEntityShas,h),ae=ye=>re(ye)||K.has(ye.sha)||q.has(ye.sha),X=ye=>{ye===(a||s)?m.delete("viewBranch"):m.set("viewBranch",ye),f(m)},oe=ye=>{ye===o?m.delete("compare"):m.set("compare",ye),f(m)},me=()=>{const Re=T.flatMap(([Je,bt])=>bt.editedEntities||bt.entities||[]).filter(Je=>!I.has(Je.sha)&&!K.has(Je.sha)&&!q.has(Je.sha)&&!re(Je));B(Re)},ve=A.length,je=_.length,te=T.flatMap(([ye,Re])=>Re.editedEntities||Re.entities||[]),ke=te.filter(ye=>ye.entityType==="visual"||ye.entityType==="library"),Z=ke.length>0&&ke.every(ye=>I.has(ye.sha)),pe=ke.length>0&&!Z&&ke.every(ye=>K.has(ye.sha)||q.has(ye.sha)),ie=J||Z||pe,de=Z?"Analyzing...":pe?"Queued...":J?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:c("div",{className:"px-20 py-12",children:[c("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),c("p",{className:"text-[15px] text-gray-500",children:["This is a list of all the files that are affected by your local changes. ",n("strong",{children:"Analyze a file to get simulations."})]})]}),n("div",{className:"mb-6",children:n(Qk,{activeTab:v,onTabChange:N,uncommittedCount:ve,branchCount:je})}),s&&v==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:s===o?c("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):c("div",{className:"flex gap-6 items-center",children:[c("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?c("div",{className:"relative w-50",children:[n("select",{value:s,onChange:ye=>X(ye.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-2.5 pr-6 text-[13px] h-9.75 w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.map(ye=>n("option",{value:ye,children:ye},ye))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):n("span",{className:"text-gray-900 font-medium text-[12px]",children:s})]}),c("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),c("div",{className:"relative w-[200px]",children:[n("select",{value:l,onChange:ye=>oe(ye.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:i.filter(ye=>ye!==s).map(ye=>n("option",{value:ye,children:ye},ye))}),n("svg",{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),n("div",{className:"flex-1 mt-6",children:c("div",{className:"relative flex items-center",children:[n("svg",{className:"absolute left-3 w-4 h-4 text-gray-400 pointer-events-none",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),n("input",{type:"text",placeholder:"Search component",className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})})]})}),n("div",{className:"mb-3",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center",children:[c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:T.length})," ","modified ",T.length===1?"file":"files"]}),c("div",{className:"relative group inline-flex items-center ml-1.5",children:[n("svg",{className:"w-3 h-3 text-gray-400 cursor-help",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:n("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),n("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:c("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:["In CodeYam, an entity is a discrete, analyzable unit of code that can be independently simulated and tested.",n("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),c("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:te.length})," ",te.length===1?"entity":"entities"]})]}),T.length>0&&c("div",{className:"flex gap-6",children:[c("button",{onClick:W,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(Bd,{className:"w-3.5 h-3.5"}),"Expand All"]}),c("button",{onClick:V,className:"text-[#005c75] hover:bg-[#E6F5F8] hover:text-[#003d4f] font-mono uppercase transition-all cursor-pointer px-3 py-1 rounded flex items-center gap-1.5",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[n(zd,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),c("div",{className:"overflow-hidden",children:[v==="branch"&&s&&n(Gk,{files:_,currentBranch:s,defaultBranch:o,baseBranch:l,allBranches:i,expandedFiles:R,isEntityBeingAnalyzed:H,isEntityQueued:ae,sortOrder:x,onToggleFile:ye=>U(ye,R,L),onBranchChange:oe,onGenerateSimulation:z,onSortChange:C,onAnalyzeAll:me,analyzeAllDisabled:ie,analyzeAllText:de}),v==="uncommitted"&&n(qk,{files:A,entityImpactMap:M,expandedFiles:R,isEntityBeingAnalyzed:H,isEntityQueued:ae,projectSlug:p,baseBranch:l,currentBranch:s,sortOrder:x,onToggleFile:ye=>U(ye,R,L),onShowFileDiff:O,onGenerateSimulation:z,onSortChange:C,onAnalyzeAll:me,analyzeAllDisabled:ie,analyzeAllText:de})]}),F&&n(Kk,{diffView:F,diffContent:Y,isLoading:P,entities:t,onClose:S}),y&&p&&n(mn,{projectSlug:p,onClose:()=>g(null)})]})})}),n5=Object.freeze(Object.defineProperty({__proto__:null,action:Xk,default:t5,loader:e5,meta:Zk},Symbol.toStringTag,{value:"Module"}));function Hs(e){const t=e.name.toLowerCase();if(e.name==="Desktop"||e.name==="Full HD"||e.name==="HD")return"desktop";if(e.name==="Laptop"||e.name==="Small Laptop")return"laptop";if(e.name==="Tablet")return"tablet";if(e.name==="Mobile"||t.includes("iphone")||t.includes("pixel")||t.includes("galaxy")||t.includes("phone"))return"mobile";if(t.includes("ipad")||t.includes("tablet"))return"tablet";if(t.includes("laptop"))return"laptop";if(t.includes("desktop"))return"desktop";const r=e.height>e.width;return r&&e.width>=700?"tablet":r?"mobile":e.width>1200?"desktop":"laptop"}const r5=[{name:"Desktop",width:1440,height:900},{name:"Laptop",width:1024,height:768},{name:"Tablet",width:768,height:1024},{name:"Mobile",width:375,height:667}],s5=[{name:"iPhone 16",width:393,height:852},{name:"iPhone 16 Pro Max",width:430,height:932},{name:"iPhone SE",width:375,height:667},{name:"Pixel 8",width:412,height:915},{name:"iPad mini",width:744,height:1133}],Zp=[{category:"Desktop",presets:[{name:"Full HD",width:1920,height:1080},{name:"Desktop",width:1440,height:900},{name:"HD",width:1280,height:720}]},{category:"Laptop",presets:[{name:"Laptop",width:1366,height:768},{name:"Small Laptop",width:1024,height:768}]},{category:"Tablet",presets:[{name:'iPad Pro 12.9"',width:1024,height:1366},{name:"iPad Air",width:820,height:1180},{name:"Tablet",width:768,height:1024},{name:"iPad mini",width:744,height:1133}]},{category:"Mobile",presets:[{name:"iPhone 16 Pro Max",width:430,height:932},{name:"iPhone 16",width:393,height:852},{name:"iPhone 14",width:390,height:844},{name:"Mobile",width:375,height:667},{name:"Pixel 8",width:412,height:915},{name:"Galaxy S",width:360,height:800}]}];function Xp(e,t){if(e&&Object.keys(e).length>0&&Object.values(e).some(l=>"default"in l))return Object.entries(e).map(([l,d])=>({name:l,width:d.width,height:d.height}));const r=(t==null?void 0:t.includes("mobile-app"))??!1,s=r?s5:r5,a=s.map(l=>{const d=e==null?void 0:e[l.name];return d?{...l,width:d.width,height:d.height}:l});if(!e||r)return a;const o=new Set(s.map(l=>l.name)),i=Object.entries(e).filter(([l])=>!o.has(l)).map(([l,d])=>({name:l,width:d.width,height:d.height}));return[...a,...i]}const Rs={width:24,height:76};function a5({width:e,height:t,enabled:r=!0,children:s}){if(!r)return n(we,{children:s});const a=12,o=48,i=28,l=e+a*2,d=t+o+i;return c("div",{style:{width:`${l}px`,height:`${d}px`,background:"#1a1a1a",borderRadius:"44px",padding:`${o}px ${a}px ${i}px`,position:"relative",boxShadow:"0 0 0 1px rgba(255,255,255,0.08), 0 8px 32px rgba(0,0,0,0.4)"},children:[n("div",{style:{position:"absolute",top:"14px",left:"50%",transform:"translateX(-50%)",width:"100px",height:"24px",background:"#000",borderRadius:"12px"}}),n("div",{style:{width:`${e}px`,height:`${t}px`,borderRadius:"6px",overflow:"hidden",position:"relative"},children:s}),n("div",{style:{position:"absolute",bottom:"10px",left:"50%",transform:"translateX(-50%)",width:"120px",height:"4px",background:"rgba(255,255,255,0.25)",borderRadius:"2px"}})]})}function Is(e){return e.charAt(0).toUpperCase()+e.slice(1)}function o5({from:e,to:t,lastStep:r,lastStepLabel:s,handoffSummary:a,featureName:o,onContinue:i,onStartFresh:l}){const d=le(u=>{u.key==="Enter"&&(u.preventDefault(),i())},[i]);return se(()=>(window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)),[d]),n("div",{className:"flex items-center justify-center h-full bg-[#1e1e1e] text-[#d4d4d4]",children:c("div",{className:"max-w-md w-full mx-4 p-6 bg-[#252526] border border-[#3d3d3d] rounded-lg",children:[c("div",{className:"flex items-center gap-2 mb-3",children:[n("div",{className:"w-2 h-2 rounded-full bg-amber-400"}),n("h2",{className:"text-lg font-semibold text-white",children:"Provider Changed"})]}),c("p",{className:"text-sm text-amber-300 mb-4",children:[Is(e)," → ",Is(t)]}),c("div",{className:"bg-[#1e1e1e] rounded p-3 mb-4 text-sm space-y-1",children:[o&&c("div",{children:[n("span",{className:"text-[#999]",children:"Feature:"})," ",n("span",{className:"text-white",children:o})]}),r!=null&&s&&c("div",{children:[n("span",{className:"text-[#999]",children:"Last step:"})," ",c("span",{className:"text-white",children:[r," of 18 — ",s]})]})]}),a&&c("div",{className:"bg-[#1e1e1e] rounded p-3 mb-4 text-sm",children:[n("div",{className:"text-[#999] mb-1",children:"Previous provider's notes:"}),n("div",{className:"text-[#ccc] italic",children:a})]}),c("p",{className:"text-xs text-[#999] mb-4",children:["Continuing will generate a handoff context with uncommitted changes and progress history for ",Is(t)," to review."]}),c("button",{onClick:i,className:"w-full px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-amber-600 text-white font-medium hover:bg-amber-700 ring-2 ring-amber-400/50",children:["Continue with ",Is(t)]}),n("button",{onClick:l,className:"w-full mt-2 px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-transparent text-[#999] hover:text-white hover:bg-[#3d3d3d] border border-[#3d3d3d]",children:"Start Fresh"})]})})}function i5({featureName:e,editorStep:t,editorStepLabel:r,onContinue:s,onStartFresh:a}){const o=le(i=>{i.key==="Enter"&&(i.preventDefault(),s())},[s]);return se(()=>(window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)),[o]),n("div",{className:"flex items-center justify-center h-full bg-[#1e1e1e] text-[#d4d4d4]",children:c("div",{className:"flex flex-col items-center max-w-lg w-full mx-4",children:[n("h2",{className:"text-2xl font-bold mb-2 text-white",children:"Resume Previous Session?"}),n("p",{className:"text-sm text-[#999] mb-6",children:"An editor session is still in progress:"}),c("div",{className:"bg-[#2a2a1e] border border-[#D7FF63]/30 rounded-lg px-12 py-5 mb-6 text-center w-full max-w-sm",children:[e&&n("div",{className:"text-white font-medium text-base mb-1",children:e}),t!=null&&r&&c("div",{className:"font-['IBM_Plex_Mono'] text-sm",children:[c("span",{className:"text-[#D7FF63] font-bold",children:["STEP ",t]})," ",c("span",{className:"text-[#D7FF63]/70",children:["(",r.toUpperCase(),")"]})]})]}),n("button",{onClick:s,className:"px-12 py-2.5 text-sm rounded-md transition-colors cursor-pointer bg-[#D7FF63] text-black font-bold tracking-wider uppercase font-['IBM_Plex_Mono'] hover:bg-[#c5ee52]",children:"Continue Session"}),a&&n("button",{onClick:a,className:"mt-4 px-4 py-2 text-xs rounded transition-colors cursor-pointer bg-transparent text-[#666] hover:text-white tracking-wider uppercase font-['IBM_Plex_Mono']",children:"Start Over"})]})})}function l5({onStartNextFeature:e,onContinueInSession:t}){const r=le(s=>{s.key==="Enter"&&(s.preventDefault(),e())},[e]);return se(()=>(window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)),[r]),n("div",{className:"absolute inset-0 flex items-center justify-center bg-[#1e1e1e]/90 z-10",children:c("div",{className:"max-w-md w-full mx-4 p-6 bg-[#252526] border border-[#3d3d3d] rounded-lg",children:[n("h2",{className:"text-lg font-semibold mb-3 text-white",children:"Feature Complete!"}),n("p",{className:"text-sm text-[#999] mb-5",children:"Your feature has been pushed. What would you like to do next?"}),n("button",{onClick:e,className:"w-full px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-[#005c75] text-white font-medium hover:bg-[#004d63] ring-2 ring-white/50",children:"Start Next Feature"}),n("button",{onClick:t,className:"w-full mt-2 px-4 py-2 text-sm rounded transition-colors cursor-pointer bg-transparent text-[#999] hover:text-white hover:bg-[#3d3d3d] border border-[#3d3d3d]",children:"Continue in Current Session"}),n("p",{className:"text-xs text-[#666] mt-3 text-center",children:"Press Enter to start a new feature with a fresh context"})]})})}const c5={1:"Plan",2:"Prepare",3:"Prototype",4:"Verify Prototype",5:"Confirm",6:"Deconstruct",7:"Extract",8:"Glossary",9:"Analyze",10:"App Scenarios",11:"User Scenarios",12:"Verify",13:"Journal",14:"Review",15:"Present",16:"Commit",17:"Finalize",18:"Push"},d5={1:"Plan the feature and confirm the approach with the user before writing any code.",2:"Prepare the project environment and dependencies for prototyping.",3:"Build a working prototype quickly to validate the concept.",4:"Verify the prototype works correctly and fix any issues.",5:"Confirm the prototype looks right and get user approval to proceed.",6:"Read the code and plan all component and function extractions.",7:"Extract components and functions via TDD — components first, then functions.",8:"Record all extracted functions and components in the glossary.",9:"Analyze imports and verify all components are captured correctly.",10:"Create app-level scenarios that show full pages with realistic data.",11:"Create user-persona scenarios that exercise the app from different perspectives.",12:"Review all screenshots and check for visual errors or regressions.",13:"Create or update the journal entry documenting what was built.",14:"Final review of screenshots, audit for completeness.",15:"Present a summary of all work to the user for approval.",16:"Commit all changes to git.",17:"Update the journal with final details and amend the commit.",18:"Push the branch to the remote repository."},u5={1:"Survey",2:"App Scenarios",3:"Component Scenarios",4:"Preview",5:"Discuss",6:"Decompose",7:"Extract",8:"Recapture",9:"Journal",10:"Present"},p5={1:"Survey the existing codebase to understand pages, components, and dependencies.",2:"Create app-level scenarios showing full pages with realistic data.",3:"Create component-level scenarios for isolated component previews.",4:"Preview all captured scenarios and verify they look correct.",5:"Discuss the migration plan and prioritize which pages to decompose.",6:"Plan the decomposition of pages into clean, reusable components.",7:"Extract components and functions with tests via TDD.",8:"Recapture scenarios after extraction to verify nothing broke.",9:"Document the migration progress in a journal entry.",10:"Present the migration results for review and approval."},h5=18,m5=10;function f5({projectTitle:e,featureName:t,editorStep:r,editorStepLabel:s,migrationMode:a}){const[o,i]=E(!1),[l,d]=E(null),u=be(null);se(()=>{if(!o)return;const b=v=>{u.current&&!u.current.contains(v.target)&&i(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[o]);const p=t&&r!=null,h=a==="active",m=h?u5:c5,f=h?p5:d5,y=h?m5:h5,g=p?s||m[r]||"?":null;return c("div",{className:"h-8 shrink-0 flex items-center justify-between px-3 bg-[#2a2a2a] border-b border-[#333] text-xs select-none",children:[c("div",{className:"flex items-center gap-1.5 min-w-0",children:[n("span",{className:"text-[#888] truncate",children:e||"New Project"}),n("span",{className:"text-[#555]",children:">"}),n("span",{className:"text-[#ccc] font-medium truncate",children:t||"New Working Session"})]}),p&&c("div",{className:"relative",ref:u,children:[c("button",{onClick:()=>i(b=>!b),className:"flex items-center gap-1.5 text-[#ccc] hover:text-white transition-colors cursor-pointer",children:[n("span",{className:"text-[#555]",children:"::"}),c("span",{children:["Step ",r,c("span",{className:"text-[#888]",children:[" / ",y]}),":"," ",g]}),n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`transition-transform ${o?"rotate-180":""}`,children:n("path",{d:"M2 4l3 3 3-3"})})]}),o&&n("div",{className:"absolute right-0 top-full mt-1 w-48 bg-[#2d2d2d] border border-[#444] rounded-lg shadow-lg z-30 py-1",children:Array.from({length:y},(b,v)=>v+1).map(b=>{const v=b===r,N=b<r,w=l===b,C=f[b];return c("div",{onClick:()=>d(w?null:b),className:"cursor-pointer",children:[c("div",{className:`w-full px-3 py-1 flex items-center gap-2 text-left transition-colors hover:bg-[#383838] ${v?"text-cygreen font-medium":N?"text-[#ccc]":"text-[#999]"}`,children:[c("span",{className:"w-5 text-right tabular-nums shrink-0",children:[b,"."]}),n("span",{className:"flex-1",children:m[b]||`Step ${b}`}),C&&n("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`shrink-0 opacity-40 transition-transform ${w?"rotate-180":""}`,children:n("path",{d:"M2 4l3 3 3-3"})})]}),w&&C&&n("div",{className:"px-3 pb-1.5 pl-10",children:n("p",{className:"text-[10px] text-[#888] m-0 leading-relaxed",children:C})})]},b)})})]})]})}function il(e,t){const[r,s]=E(t??null),[a,o]=E(!1),[i,l]=E((t==null?void 0:t.stale)??!1),d=le(()=>{e&&(o(!0),fetch(`/api/editor-test-results?testFile=${encodeURIComponent(e)}`).then(u=>u.json()).then(u=>{s(u),l(!1),o(!1)}).catch(()=>{s({testFilePath:e,status:"error",testCases:[],errorMessage:"Failed to fetch test results"}),l(!1),o(!1)}))},[e]);return{results:r,isRunning:a,runTests:d,stale:i}}function cr({scenarioId:e,screenshotPath:t,updatedAt:r,alt:s,className:a="",imgClassName:o=""}){const[i,l]=E(!1),u=`/api/editor-scenario-image/${t?t.replace(/^screenshots\//,""):`${e}.png`}${r?`?v=${encodeURIComponent(r)}`:""}`;return se(()=>{l(!1)},[e,t]),i?n("div",{className:`flex items-center justify-center ${a}`,children:n("span",{className:"text-[8px] text-gray-500",children:"No img"})}):n("div",{className:a,children:n("img",{src:u,alt:s,className:o,loading:"lazy",onError:()=>l(!0)})})}function gn(e){return e.flatMap(t=>{const r=t.screenshotPaths;return r&&Object.keys(r).length>1?Object.entries(r).map(([s,a])=>({scenario:t,dimensionLabel:s,screenshotPath:a,key:`${t.id}--${s}`})):[{scenario:t,dimensionLabel:null,screenshotPath:t.screenshotPath,key:t.id}]})}function Rr({scenarioId:e,screenshotPath:t,updatedAt:r,hasScreenshot:s,imgSrc:a,name:o,dimensionLabel:i,isActive:l,onSelect:d}){const u=e&&s,p=!e&&a;return c("button",{onClick:d,className:"flex flex-col items-center gap-1 cursor-pointer group w-full",title:i?`${o} (${i})`:o,children:[c("div",{className:`w-full aspect-[16/10] rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] relative ${l?"border-[#D7FF63]/40 ring-1 ring-[#D7FF63]/20":"border-transparent hover:border-[#4d4d4d]"}`,children:[u?n(cr,{scenarioId:e,screenshotPath:t,updatedAt:r,alt:i?`${o} (${i})`:o,className:"w-full h-full",imgClassName:"w-full h-full object-contain"}):p?n("img",{src:a,alt:o,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})}),i&&n("span",{className:"absolute bottom-1 right-1 text-[8px] font-medium bg-black/60 text-white px-1 py-0.5 rounded",children:i})]}),n("span",{className:`text-[10px] leading-tight text-center truncate w-full ${l?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:i?`${o} (${i})`:o})]})}function Eo({testFile:e,entityName:t,cachedResult:r}){const{results:s,isRunning:a,runTests:o,stale:i}=il(e,r);if(a&&!s)return c("div",{className:"px-2 pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!s)return null;if(s.status==="error")return n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-red-400",children:s.errorMessage})});const l=t?s.testCases.filter(p=>p.fullName.startsWith(t)):s.testCases,d=l.length>0?l:s.testCases;if(d.length===0)return null;const u=t?`${t} > `:"";return c("div",{className:"px-2 pt-1 space-y-0.5",children:[d.map(p=>{var m;const h=u&&p.fullName.startsWith(u)?p.fullName.slice(u.length):p.fullName;return c("div",{children:[c("div",{className:"flex items-center gap-1.5",children:[p.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):p.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${p.status==="passed"?"text-green-400":p.status==="failed"?"text-red-400":"text-gray-500"}`,children:h})]}),p.status==="failed"&&((m=p.failureMessages)==null?void 0:m.map((f,y)=>n("div",{className:"pl-4 text-[9px] text-red-300/70 truncate max-w-full",title:f,children:f.split(`
607
+ `)[0]},y)))]},p.fullName)}),c("div",{className:"flex items-center gap-2 mt-1",children:[n("button",{onClick:o,disabled:a,className:"text-[10px] text-[#00a0c4] hover:text-[#00c4ee] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:a?"Running...":i?"Re-run (stale)":"Re-run"}),i&&!a&&n("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0",title:"Source or test file changed since last run"})]})]})}function Ir({filePath:e}){return e?c("div",{className:"flex items-center gap-1 px-2 mt-0.5",children:[c("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(xt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function g5({scenarios:e,projectRoot:t,activeScenarioId:r,onScenarioSelect:s,zoomComponent:a,focusedEntity:o,onZoomChange:i,analyzedEntities:l=[],glossaryFunctions:d=[],cachedTestResults:u={},activeAnalyzedScenarioId:p,onAnalyzedScenarioSelect:h,entityImports:m,pageFilePaths:f={},onSwitchToBuild:y,entityShaMap:g,structureTab:x="application",onStructureTabChange:b}){const[v,N]=E(""),[w,C]=E(x),k=b?x:w,j=b||C,{pageGroups:A,componentGroups:_}=fe(()=>{var O;const F=new Map,Y=new Map;for(const S of e)if(S.componentName){const $=Y.get(S.componentName)||[];$.push(S),Y.set(S.componentName,$)}else if(_a(S.url)){const $=(O=S.url)==null?void 0:O.match(/[?&]c=([^&]+)/),I=$?decodeURIComponent($[1]):"Isolated",K=Y.get(I)||[];K.push(S),Y.set(I,K)}else{const $=S.pageFilePath?Jt(Ft(S.pageFilePath)):Ct(S.url),I=F.get($)||[];I.push(S),F.set($,I)}const P=new Map([...Y.entries()].sort(([S],[$])=>S.localeCompare($)));return{pageGroups:F,componentGroups:P}},[e]),M=fe(()=>{const F=new Set((l||[]).filter(P=>P.entityType==="visual").map(P=>P.name)),Y=new Map;for(const[P,O]of _)F.has(P)||Y.set(P,O);return Y},[_,l]),{visualEntities:T,libraryEntities:D}=fe(()=>{const F=l.filter(P=>P.entityType==="visual").sort((P,O)=>P.name.localeCompare(O.name)),Y=l.filter(P=>P.entityType==="library"||P.entityType==="functionCall").sort((P,O)=>P.name.localeCompare(O.name));return{visualEntities:F,libraryEntities:Y}},[l]),R=fe(()=>{const F=new Set(D.map(Y=>Y.name));return d.filter(Y=>!F.has(Y.name)).sort((Y,P)=>Y.name.localeCompare(P.name))},[d,D]),L=l.some(F=>F.isAnalyzing),U=be(null),W=be(0),V=le(()=>{U.current&&(W.current=U.current.scrollTop)},[]);if(se(()=>{U.current&&W.current>0&&(U.current.scrollTop=W.current)}),e.length===0&&l.length===0&&R.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:c("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No scenarios yet"}),n("p",{className:"text-xs",children:"Scenarios will appear here as Claude creates them alongside your code. Each scenario represents a different state of your app's data."})]})});if(a&&o){const F=o.name,Y=o.filePath,P=o.sha,O=e.filter(q=>q.componentName===F||q.componentPath===Y||!q.componentName&&(q.pageFilePath===Y||P&&q.entitySha===P)),S=new Set((m==null?void 0:m[F])||[]),$=S.size>0,I=$?T.filter(q=>S.has(q.name)):[],K=$?D.filter(q=>S.has(q.name)):[];return n("div",{className:"flex-1 overflow-auto",children:c("div",{className:"p-3 space-y-1",children:[c("button",{onClick:()=>i(void 0),className:"w-full flex items-center gap-2 px-3 py-1.5 text-xs text-gray-400 hover:text-white transition-colors cursor-pointer",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:n("path",{d:"M7.5 9L4.5 6L7.5 3",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"All scenarios"]}),n("div",{className:"px-3 py-1.5",children:n("span",{className:"text-xs font-semibold text-white uppercase tracking-wider",children:o.displayName})}),n("div",{className:"flex flex-wrap gap-2 px-2",children:O.length===0?n("div",{className:"px-3 py-2 text-xs text-gray-500",children:"No scenarios for this component"}):gn(O).map(({scenario:q,dimensionLabel:J,screenshotPath:z,key:B})=>n(Rr,{scenarioId:q.id,screenshotPath:z,updatedAt:q.updatedAt,hasScreenshot:!!z,name:q.name,dimensionLabel:J,isActive:q.id===r,onSelect:()=>s(q,J??void 0)},B))}),I.length>0&&c("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),I.map(q=>c("div",{className:"mt-2",children:[n("div",{className:"flex items-center gap-2 px-2 py-1",children:n("button",{onClick:()=>i(q.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:q.name})}),n(Ir,{filePath:q.filePath,projectRoot:t}),(q.scenarios.length>0||q.pendingScenarios.length>0)&&n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:q.scenarios.map(J=>n(Rr,{imgSrc:J.screenshotPath?`/api/screenshot/${J.screenshotPath}`:null,name:J.name,isActive:J.id===p,onSelect:()=>h==null?void 0:h({analysisId:q.analysisId,scenarioId:J.id,scenarioName:J.name,entitySha:q.sha,entityName:q.name})},J.id))})]},q.sha))]}),K.length>0&&c("div",{className:"pt-2 mt-1",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),K.map(q=>c("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:q.name})}),n(Ir,{filePath:q.filePath,projectRoot:t}),q.testFile&&n(Eo,{testFile:q.testFile,entityName:q.name,cachedResult:u[q.testFile]})]},q.sha))]})]})})}return n("div",{ref:U,onScroll:V,className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:c("div",{className:"p-4 space-y-4",children:[c("div",{className:"flex items-center gap-3 font-['IBM_Plex_Mono']",children:[n("button",{onClick:()=>j("application"),className:`text-xs font-bold uppercase tracking-wider shrink-0 bg-transparent border-none cursor-pointer p-0 transition-colors ${k==="application"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:"Application"}),n("button",{onClick:()=>j("components"),className:`text-xs font-bold uppercase tracking-wider shrink-0 bg-transparent border-none cursor-pointer p-0 transition-colors ${k==="components"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:"Components"}),n("div",{className:"flex-1"}),c("div",{className:"relative",style:{width:170},children:[c("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"11",cy:"11",r:"8"}),n("path",{d:"M21 21l-4.35-4.35"})]}),n("input",{type:"text",placeholder:"SEARCH...",value:v,onChange:F=>N(F.target.value),className:"w-full pl-9 pr-3 py-2 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors tracking-wider"})]}),y&&c("button",{onClick:y,className:"flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer shrink-0 uppercase tracking-wider",children:[n("span",{children:"+"})," New Feature"]})]}),n("div",{className:"border-b border-[#2d2d2d]"}),k==="application"&&A.size>0&&n("div",{children:[...A.entries()].sort(([F],[Y])=>F==="Home"?-1:Y==="Home"?1:F.localeCompare(Y)).filter(([F])=>v.trim()?F.toLowerCase().includes(v.trim().toLowerCase()):!0).map(([F,Y])=>{const P=Y.some(O=>O.id===r&&!p);return c("div",{className:"mt-3",children:[c("div",{className:"flex items-center gap-1.5 py-1",children:[c("button",{onClick:()=>i(F,g==null?void 0:g.get(F)),className:`flex items-center gap-1.5 text-sm font-normal cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0 ${P?"text-[#D7FF63]":"text-gray-300"}`,children:[F,c("span",{className:`text-xs ${P?"text-[#D7FF63]/60":"text-gray-500"}`,children:["(",Y.length,")"]}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:P?"text-[#D7FF63]/60":"text-gray-500",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),P&&c("div",{className:"flex items-center gap-1 ml-auto",children:[n("button",{onClick:()=>i(F,g==null?void 0:g.get(F)),className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Edit scenarios",children:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),y&&n("button",{onClick:y,className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Add scenario",children:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]})]}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:gn(Y).map(({scenario:O,dimensionLabel:S,screenshotPath:$,key:I})=>n(Rr,{scenarioId:O.id,screenshotPath:$,updatedAt:O.updatedAt,hasScreenshot:!!$,name:O.name,dimensionLabel:S,isActive:O.id===r&&!p,onSelect:()=>s(O,S??void 0)},I))})]},F)})}),k==="components"&&M.size>0&&n("div",{children:[...M.entries()].filter(([F])=>v.trim()?F.toLowerCase().includes(v.trim().toLowerCase()):!0).map(([F,Y])=>{const P=Y.some(O=>O.id===r&&!p);return c("div",{className:"mt-3",children:[c("div",{className:"flex items-center gap-1.5 py-1",children:[c("button",{onClick:()=>i(F,g==null?void 0:g.get(F)),className:`flex items-center gap-1.5 text-sm font-normal cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0 ${P?"text-[#D7FF63]":"text-gray-300"}`,children:[F,c("span",{className:`text-xs ${P?"text-[#D7FF63]/60":"text-gray-500"}`,children:["(",Y.length,")"]}),n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:P?"text-[#D7FF63]/60":"text-gray-500",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),P&&c("div",{className:"flex items-center gap-1 ml-auto",children:[n("button",{onClick:()=>i(F,g==null?void 0:g.get(F)),className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Edit scenarios",children:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),y&&n("button",{onClick:y,className:"p-1.5 rounded-md bg-[#3d3d3d] hover:bg-[#4d4d4d] text-gray-300 hover:text-white transition-colors cursor-pointer border-none",title:"Add scenario",children:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]})]}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:gn(Y).map(({scenario:O,dimensionLabel:S,screenshotPath:$,key:I})=>n(Rr,{scenarioId:O.id,screenshotPath:$,updatedAt:O.updatedAt,hasScreenshot:!!$,name:O.name,dimensionLabel:S,isActive:O.id===r&&!p,onSelect:()=>s(O,S??void 0)},I))})]},F)})}),T.length>0&&c("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[c("div",{className:"px-2 py-1",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),L&&e.length===0&&l.every(F=>F.scenarioCount===0)&&n("span",{className:"ml-2 text-[10px] text-gray-500",children:"— Entities are being analyzed..."})]}),T.map(F=>c("div",{className:"mt-2",children:[c("div",{className:"flex items-center gap-2 px-2 py-1",children:[n("button",{onClick:()=>i(F.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:F.name}),F.isAnalyzing&&F.scenarioCount===0&&c("span",{className:"flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(Ir,{filePath:F.filePath,projectRoot:t}),(F.scenarios.length>0||F.pendingScenarios.length>0)&&c("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:[F.scenarios.map(Y=>n(Rr,{imgSrc:Y.screenshotPath?`/api/screenshot/${Y.screenshotPath}`:null,name:Y.name,isActive:Y.id===p,onSelect:()=>h==null?void 0:h({analysisId:F.analysisId,scenarioId:Y.id,scenarioName:Y.name,entitySha:F.sha,entityName:F.name})},Y.id)),F.pendingScenarios.map(Y=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:Y,children:Y},Y))]})]},F.sha))]}),(D.length>0||R.length>0)&&c("div",{className:`pt-2 mt-1 ${T.length>0?"":"border-t border-[#3d3d3d]"}`,children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),D.map(F=>c("div",{className:"mt-2",children:[c("div",{className:"px-2 py-1",children:[n("span",{className:"text-[11px] font-medium text-gray-300",children:F.name}),F.isAnalyzing&&F.scenarioCount===0&&c("span",{className:"ml-2 inline-flex items-center gap-1.5 text-[10px] text-gray-400",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#005c75] animate-pulse"}),"Analyzing..."]})]}),n(Ir,{filePath:F.filePath,projectRoot:t}),F.testFile?n(Eo,{testFile:F.testFile,entityName:F.name,cachedResult:u[F.testFile]}):n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},F.sha)),R.map(F=>c("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:F.name})}),n(Ir,{filePath:F.filePath,projectRoot:t}),n(Eo,{testFile:F.testFile,entityName:F.name,cachedResult:u[F.testFile]})]},F.name))]})]})})}function eh(e){const t={};for(const[r,s]of Object.entries(e))if(typeof s=="string")try{const a=JSON.parse(s);Array.isArray(a)?t[r]=a:typeof a=="object"&&a!==null&&(t[r]=[a])}catch{}else Array.isArray(s)&&(t[r]=s);return t}function th(e,t){return e.length===0||t.length===0?!1:e.filter(s=>t.includes(s)).length>=Math.min(e.length,t.length)*.5}function y5(e,t){const{_metadata:r,...s}=t,a=s.localStorage&&typeof s.localStorage=="object"&&!Array.isArray(s.localStorage)?eh(s.localStorage):{},o={};if(s.seed&&typeof s.seed=="object"&&!Array.isArray(s.seed))for(const[h,m]of Object.entries(s.seed))Array.isArray(m)&&(o[h]=m);const i={},l=[],d=new Set,u=new Set,p=new Set;for(const h of e){const m=h.fields.filter(b=>!b.isRelation),f=m.map(b=>b.name),y=h.name.charAt(0).toLowerCase()+h.name.slice(1);let g=null,x=[];for(const b of[h.name,y,`${y}s`])if(b in s&&Array.isArray(s[b])){g=b,x=s[b],u.add(b);break}if(!g){for(const b of[h.name,y,`${y}s`])if(b in o){g=b,x=o[b],p.add(b),b in a&&d.add(b);break}}if(!g){for(const b of[h.name,y,`${y}s`])if(b in a){g=y,x=a[b],d.add(b);break}}if(!g){for(const[b,v]of Object.entries(a))if(!d.has(b)&&v.length>0&&th(f,Object.keys(v[0]))){g=y,x=v,d.add(b);break}}g||(g=y),i[g]=x,l.push({label:h.name,dataKey:g,schemaFields:m.map(b=>({name:b.name,type:b.type,isId:b.isId}))})}for(const[h,m]of Object.entries(s))h==="_metadata"||h==="localStorage"||h==="seed"||h==="type"||u.has(h)||Array.isArray(m)&&(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(o))p.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(a))d.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));return{data:i,tabs:l}}function x5(e){return e==null?"null":typeof e=="number"?Number.isInteger(e)?"int4":"float":typeof e=="boolean"?"bool":typeof e=="object"?Array.isArray(e)?"array":"json":"text"}function b5(e,t){return e.length>0?Object.keys(e[0]):t?t.map(r=>r.name):[]}function v5(e,t,r){const s=new Map((r||[]).map(o=>[o.name,o.type])),a={};for(const o of e)a[o]=s.get(o)||(t.length>0?x5(t[0][o]):"text");return a}function w5(e,t){var r;return((r=t==null?void 0:t.find(s=>s.isId))==null?void 0:r.name)||e.find(s=>s==="id")||null}function N5(e,t){const{_metadata:r,...s}=t,a=s.localStorage&&typeof s.localStorage=="object"&&!Array.isArray(s.localStorage)?eh(s.localStorage):{},o={};if(s.seed&&typeof s.seed=="object"&&!Array.isArray(s.seed))for(const[h,m]of Object.entries(s.seed))Array.isArray(m)&&(o[h]=m);const i={},l=[],d=new Set,u=new Set,p=new Set;for(const h of e){const m=h.name.charAt(0).toLowerCase()+h.name.slice(1),f=h.fields.map(x=>x.name);let y=null,g=[];for(const x of[h.name,m,`${m}s`])if(x in s&&Array.isArray(s[x])){y=x,g=s[x],u.add(x);break}if(!y){for(const x of[h.name,m,`${m}s`])if(x in o){y=x,g=o[x],p.add(x),x in a&&d.add(x);break}}if(!y){for(const x of[h.name,m,`${m}s`])if(x in a){y=m,g=a[x],d.add(x);break}}if(!y){for(const[x,b]of Object.entries(a))if(!d.has(x)&&b.length>0&&th(f,Object.keys(b[0]))){y=m,g=b,d.add(x);break}}y||(y=m),i[y]=g,l.push({label:h.name,dataKey:y,category:h.category,description:h.description,schemaFields:h.fields.map(x=>({name:x.name,type:x.type,isId:x.isId??!1}))})}for(const[h,m]of Object.entries(s))h==="_metadata"||h==="localStorage"||h==="seed"||h==="type"||u.has(h)||Array.isArray(m)&&(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(o))p.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));for(const[h,m]of Object.entries(a))d.has(h)||(i[h]=m,l.push({label:h,dataKey:h}));return{data:i,tabs:l}}function ll(e){var a,o;const t=new Map,r=new Map;for(const i of e)if(i.componentName){const l=r.get(i.componentName)||[];l.push(i),r.set(i.componentName,l)}else if(_a(i.url)){const l=(a=i.url)==null?void 0:a.match(/[?&]c=([^&]+)/),d=l?decodeURIComponent(l[1]):"Isolated",u=r.get(d)||[];u.push(i),r.set(d,u)}else{const l=i.displayName||((o=i.pageFilePath)!=null&&o.startsWith("app/")?Jt(Ft(i.pageFilePath)):Ct(i.url)),d=t.get(l)||[];d.push(i),t.set(l,d)}const s=new Map([...r.entries()].sort(([i],[l])=>i.localeCompare(l)));return{pageGroups:t,componentGroups:s}}function nh(e,t){var s,a;const r=new Map;for(const[o,i]of e){const l=(s=i.find(d=>d.entitySha))==null?void 0:s.entitySha;l&&r.set(o,l)}for(const[o,i]of t){const l=(a=i.find(d=>d.entitySha))==null?void 0:a.entitySha;l&&r.set(o,l)}return r}function S5(e){const t=new Set;for(const[r,s]of Object.entries(e)){t.add(r);for(const a of s)t.add(a)}return t}function C5(e,t,r,s){if(t.has(e))return!0;const a=r.find(o=>o.sha===e);return a?s.has(a.name):!1}function k5(e,t,r,s){const a=[];for(const[o,i]of e){const l=r.get(o);l?s(l)||a.push({name:o,scenarios:i,reason:"incomplete"}):a.push({name:o,scenarios:i,reason:"missing"})}for(const[o,i]of t){const l=r.get(o);l?s(l)||a.push({name:o,scenarios:i,reason:"incomplete"}):a.push({name:o,scenarios:i,reason:"missing"})}return a}function ld(e,t,r){if(!e)return null;const s=t.find(a=>a.sha===e);return s?{sha:e,name:s.name,filePath:s.filePath,entityType:s.entityType,displayName:s.name}:null}const cd=120;function rh({text:e,theme:t}){const[r,s]=E(!1),a=e.length>cd,o=a&&!r?e.slice(0,cd)+"…":e,i=t==="light";return c("div",{className:`px-4 py-2 ${i?"border-b border-gray-200 bg-gray-50":"border-b border-[#3d3d3d] bg-[#252525]"}`,children:[n("span",{className:"text-[9px] font-semibold uppercase tracking-wider text-gray-500",children:"User Prompt"}),c("p",{className:`text-[11px] mt-0.5 mb-0 leading-relaxed ${i?"text-gray-600":"text-gray-400"}`,children:[o,a&&n("button",{onClick:()=>s(!r),className:`ml-1 text-[11px] font-medium bg-transparent border-none p-0 cursor-pointer ${i?"text-blue-500 hover:text-blue-700":"text-[#00a0c4] hover:text-[#00c0e8]"}`,children:r?"Show less":"Read more…"})]})]})}const dd={new:0,edited:1,impacted:2};function ud({status:e,onClick:t}){const r={new:{label:"New",bg:"bg-green-100",text:"text-green-700",border:"border-green-200"},edited:{label:"Edited",bg:"bg-blue-100",text:"text-blue-700",border:"border-blue-200"},impacted:{label:"Impacted",bg:"bg-amber-100",text:"text-amber-700",border:"border-amber-200"}}[e.status],s=t&&(e.status==="edited"||e.status==="impacted");return n("button",{onClick:s?t:void 0,className:`${r.bg} ${r.text} ${r.border} border text-[9px] font-bold px-1.5 py-0.5 rounded-full uppercase tracking-wider shrink-0 ${s?"cursor-pointer hover:opacity-80 transition-opacity":"cursor-default"}`,children:r.label})}function pd({filePath:e}){const[t,r]=E(null),[s,a]=E(!0),[o,i]=E(null);return se(()=>{import("react-diff-viewer-continued").then(l=>{i(()=>l.default)})},[]),se(()=>{a(!0),fetch(`/api/editor-file-diff?path=${encodeURIComponent(e)}`).then(l=>l.json()).then(l=>{r({oldContent:l.oldContent,newContent:l.newContent})}).catch(()=>{r(null)}).finally(()=>a(!1))},[e]),s?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Loading diff..."}):!t||!o?n("div",{className:"p-2 text-[10px] text-gray-400",children:"Could not load diff"}):n("div",{className:"mt-2 border border-gray-200 rounded-lg overflow-hidden max-h-[300px] overflow-auto text-xs",children:n(o,{oldValue:t.oldContent,newValue:t.newContent,splitView:!1,useDarkTheme:!1,showDiffOnly:!0,styles:{contentText:{fontSize:"11px",lineHeight:"1.4"},line:{padding:"1px 8px",fontSize:"11px"}}})})}function hd({impactedBy:e,changedEntities:t}){return n("div",{className:"mt-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5",children:e&&e.length>0?c(we,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Re-captured because these dependencies changed"}),n("ul",{className:"mt-1.5 space-y-1",children:e.map(r=>c("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.changeType==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.changeType==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name}),n("span",{className:"text-[9px] text-amber-500 truncate",children:r.filePath})]},r.filePath))})]}):t&&t.length>0?c(we,{children:[n("span",{className:"text-[10px] font-semibold text-amber-700 uppercase tracking-wider",children:"Unchanged — these entities were modified in this session"}),n("ul",{className:"mt-1.5 space-y-1",children:t.map(r=>c("li",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold px-1 py-0 rounded-full uppercase tracking-wider border ${r.status==="new"?"bg-green-100 text-green-700 border-green-200":"bg-blue-100 text-blue-700 border-blue-200"}`,children:r.status==="new"?"New":"Edited"}),n("span",{className:"text-[11px] font-medium text-amber-800",children:r.name})]},r.name))})]}):n("span",{className:"text-[10px] text-amber-600",children:"This component was re-captured because a dependency changed"})})}function md({scenarioId:e,screenshotPath:t,name:r,dimensionLabel:s,isActive:a,onSelect:o,updatedAt:i}){const l=be(null);return se(()=>{a&&l.current&&l.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[a]),c("button",{ref:l,onClick:o,className:"flex flex-col items-center gap-1.5 cursor-pointer group",title:s?`${r} (${s})`:r,children:[c("div",{className:`w-32 h-32 rounded-lg overflow-hidden border-2 transition-all relative ${a?"border-[#0ea5e9] ring-2 ring-[#0ea5e9]/40 shadow-lg shadow-[#0ea5e9]/20":"border-gray-200 hover:border-gray-400 shadow-sm"}`,children:[n(cr,{scenarioId:e,screenshotPath:t,updatedAt:i,alt:s?`${r} (${s})`:r,className:"w-full h-full bg-white",imgClassName:"w-full h-full object-contain bg-white"}),s&&n("span",{className:"absolute bottom-1 right-1 text-[9px] font-medium bg-black/60 text-white px-1.5 py-0.5 rounded",children:s})]}),n("span",{className:`text-[11px] leading-tight text-center truncate w-32 font-medium ${a?"text-gray-900":"text-gray-600 group-hover:text-gray-900"}`,children:s?`${r} (${s})`:r})]})}function j5({filePath:e}){return e?c("div",{className:"flex items-center gap-1 mt-0.5",children:[c("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1 text-gray-400 hover:text-gray-600 transition-colors min-w-0",children:[n("span",{className:"text-[9px] truncate",children:e}),n("svg",{className:"shrink-0",width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(xt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-400 hover:text-gray-600 transition-colors"})]}):null}function Xo({testFile:e,entityName:t,cachedResult:r}){const{results:s,isRunning:a,runTests:o,stale:i}=il(e,r);if(a&&!s)return c("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#0ea5e9] animate-pulse"}),n("span",{className:"text-[10px] text-gray-400",children:"Running tests..."})]});if(!s)return null;if(s.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-500",children:s.errorMessage})});const l=t?s.testCases.filter(p=>p.fullName.startsWith(t)):s.testCases,d=l.length>0?l:s.testCases;if(d.length===0)return null;const u=t?`${t} > `:"";return c("div",{className:"pt-1 space-y-0.5",children:[d.map(p=>{var m;const h=u&&p.fullName.startsWith(u)?p.fullName.slice(u.length):p.fullName;return c("div",{children:[c("div",{className:"flex items-center gap-1.5",children:[p.status==="passed"?n("span",{className:"text-green-600 text-[10px]",children:"✓"}):p.status==="failed"?n("span",{className:"text-red-500 text-[10px]",children:"✗"}):n("span",{className:"text-gray-400 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${p.status==="passed"?"text-green-600":p.status==="failed"?"text-red-500":"text-gray-400"}`,children:h})]}),p.status==="failed"&&((m=p.failureMessages)==null?void 0:m.map((f,y)=>n("div",{className:"pl-4 text-[9px] text-red-400 truncate max-w-full",title:f,children:f.split(`
608
+ `)[0]},y)))]},p.fullName)}),c("div",{className:"flex items-center gap-2 mt-1",children:[n("button",{onClick:o,disabled:a,className:"text-[10px] text-[#0ea5e9] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:a?"Running...":i?"Re-run (stale)":"Re-run"}),i&&!a&&n("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0",title:"Source or test file changed since last run"})]})]})}function fd(e){const t=e.indexOf(" - ");return t!==-1?e.slice(t+3):e}function gd(e,t){return!t||Object.keys(t).length===0?e:[...e].sort(([r],[s])=>{var l,d;const a=((l=t[r])==null?void 0:l.status)||"impacted",o=((d=t[s])==null?void 0:d.status)||"impacted",i=(dd[a]??2)-(dd[o]??2);return i!==0?i:r.localeCompare(s)})}function _5({scenarios:e,allScenarios:t=[],glossaryFunctions:r=[],cachedTestResults:s={},projectRoot:a,activeScenarioId:o,onScenarioSelect:i,onClose:l,entityChangeStatus:d={},modifiedFiles:u=[],featureName:p,userPrompt:h}){const m=fe(()=>{if(t.length===0||Object.keys(d).length===0)return e;const M=new Set(e.map(D=>D.id)),T=t.filter(D=>{var L,U;if(M.has(D.id))return!1;const R=D.componentName||D.displayName||((L=D.pageFilePath)!=null&&L.startsWith("app/")?Jt(Ft(D.pageFilePath)):Ct(D.url));return((U=d[R])==null?void 0:U.status)==="impacted"});return T.length===0?e:[...e,...T]},[e,t,d]),f=fe(()=>Object.entries(d).filter(([,M])=>M.status==="new"||M.status==="edited").map(([M,T])=>({name:M,status:T.status})),[d]),[y,g]=E(null),x=le(M=>{g(T=>T===M?null:M)},[]),{pageGroups:b,componentGroups:v}=fe(()=>ll(m),[m]),N=fe(()=>gd([...b.entries()],d),[b,d]),w=fe(()=>gd([...v.entries()],d),[v,d]),C=N,k=w,j=fe(()=>Ay(r,d),[r,d]),A=fe(()=>{const M=[];for(const[,T]of C)M.push(...T);for(const[,T]of k)M.push(...T);return M},[C,k]),_=be(!1);return se(()=>{_.current||A.length!==0&&(_.current=!0,console.log("[ResultsPanel] Auto-selecting first scenario: %s",A[0].name),i(A[0]))},[A,i]),se(()=>{if(A.length===0)return;const M=T=>{if(T.key!=="ArrowLeft"&&T.key!=="ArrowRight")return;const D=T.target,R=D==null?void 0:D.tagName;if(R==="INPUT"||R==="SELECT"||R==="TEXTAREA"&&!D.classList.contains("xterm-helper-textarea"))return;T.preventDefault();const L=A.findIndex(W=>W.id===o);let U;T.key==="ArrowLeft"?U=L<=0?A.length-1:L-1:U=L>=A.length-1?0:L+1,i(A[U])};return document.addEventListener("keydown",M),()=>document.removeEventListener("keydown",M)},[A,o,i]),m.length===0&&r.length===0?c("div",{className:"h-full bg-white flex items-center justify-center relative",children:[n("button",{onClick:l,className:"absolute top-2 right-3 text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none",title:"Close results",children:"×"}),n("span",{className:"text-sm text-gray-400",children:"No scenarios registered yet"})]}):c("div",{className:"h-full bg-white flex flex-col overflow-hidden",children:[c("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-gray-200 shrink-0",children:[c("div",{className:"min-w-0",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Working Session Results"}),p&&n("div",{className:"text-[11px] text-gray-400 truncate",title:p,children:p})]}),n("button",{onClick:l,className:"text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none shrink-0",title:"Close results",children:"×"})]}),h&&n(rh,{text:h,theme:"light"}),n("div",{className:"flex-1 overflow-auto p-4",children:c("div",{className:"space-y-5",children:[C.length>0&&c("div",{children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),n("div",{className:"space-y-3 pl-1",children:C.map(([M,T])=>{var U;const D=d[M],R=y===M,L=(U=T[0])==null?void 0:U.componentPath;return c("div",{children:[c("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:M}),D&&n(ud,{status:D,onClick:()=>x(M)})]}),R&&(D==null?void 0:D.status)==="edited"&&L&&n(pd,{filePath:L}),R&&(D==null?void 0:D.status)==="impacted"&&n(hd,{impactedBy:D.impactedBy,changedEntities:f}),n("div",{className:"flex flex-wrap gap-3",children:gn(T).map(({scenario:W,dimensionLabel:V,screenshotPath:F,key:Y})=>n(md,{scenarioId:W.id,screenshotPath:F,name:fd(W.name),dimensionLabel:V,isActive:W.id===o,onSelect:()=>i(W,V??void 0),updatedAt:W.updatedAt},Y))})]},M)})})]}),k.length>0&&c("div",{className:C.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"})}),n("div",{className:"space-y-3 pl-1",children:k.map(([M,T])=>{var U;const D=d[M],R=y===M,L=(U=T[0])==null?void 0:U.componentPath;return c("div",{children:[c("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:M}),D&&n(ud,{status:D,onClick:()=>x(M)})]}),R&&(D==null?void 0:D.status)==="edited"&&L&&n(pd,{filePath:L}),R&&(D==null?void 0:D.status)==="impacted"&&n(hd,{impactedBy:D.impactedBy,changedEntities:f}),n("div",{className:"flex flex-wrap gap-3",children:gn(T).map(({scenario:W,dimensionLabel:V,screenshotPath:F,key:Y})=>n(md,{scenarioId:W.id,screenshotPath:F,name:fd(W.name),dimensionLabel:V,isActive:W.id===o,onSelect:()=>i(W,V??void 0),updatedAt:W.updatedAt},Y))})]},M)})})]}),j.length>0&&c("div",{className:C.length>0||k.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"})}),n("div",{className:"space-y-2 pl-1",children:j.map(M=>c("div",{children:[n("div",{className:"flex items-center gap-2",children:n("span",{className:"text-[11px] font-medium text-gray-700",children:M.name})}),n(j5,{filePath:M.filePath,projectRoot:a}),M.testFile?n(Xo,{testFile:M.testFile,entityName:M.name,cachedResult:s[M.testFile]}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-400",children:"No test file"})})]},M.name))})]}),u.length>0&&c("div",{className:C.length>0||k.length>0||j.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:c("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:["Modified Files (",u.length,")"]})}),n("div",{className:"space-y-0.5 pl-1 max-h-[200px] overflow-auto",children:u.map(M=>c("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${M.status==="added"||M.status==="untracked"?"text-green-600":M.status==="modified"?"text-blue-600":M.status==="renamed"?"text-purple-600":"text-gray-400"}`,children:M.status==="added"||M.status==="untracked"?"A":M.status==="modified"?"M":M.status==="renamed"?"R":"?"}),n("span",{className:"text-[10px] text-gray-500 truncate font-mono",children:M.path})]},M.path))})]})]})})]})}function yd(e,t,r,s){var d;const a=s.length>0?s.map(u=>`- "${u.name}" (ID: ${u.id})${u.url?` — URL: ${u.url}`:""}`).join(`
609
+ `):"(no scenarios yet)",o=t.endsWith("/page.tsx")||t.endsWith("/page.js"),i=((d=s.find(u=>u.url))==null?void 0:d.url)||"/",l=[`You are helping edit scenarios for the "${e}" entity in a CodeYam project.`,"","## Entity",`- **Name:** ${e}`,`- **File:** ${t}`,`- **Type:** ${o?"Page (application scenario with seed data)":"Component (component scenario with mock props)"}`,"","## Existing Scenarios",a,""];return o?l.push("## How Seed Data Works","","Application scenarios use `seed` data to populate the database before the page is captured.","The seed is a JSON object where each key is a Prisma model name in camelCase singular (matching the Prisma client accessor name) and the value is an array of records.","","### Seed Key Naming Convention","The key must be the camelCase singular form of the Prisma model name:",'- `model User` → key `"user"`','- `model BlogPost` → key `"blogPost"`','- `model Feedback` → key `"feedback"`',"",'**WARNING:** Do NOT use plural forms like "users", "blogPosts", or "feedbacks" — the seed adapter will silently fail to match them.',"","To understand the data models, read the Prisma schema at `prisma/schema.prisma`.","To see examples of existing seed data, look at `.codeyam/editor-scenarios/*.seed.json` files.","",`Also read the source file at \`${t}\` to understand what data the page queries and renders.`,"","## Registering a Scenario","","For small seed data, pass it inline:","```",`codeyam editor register '{"name":"Scenario Name","type":"application","url":"${i}","dimensions":["Laptop"],"seed":{"user":[...],"feedback":[...]}}'`,"```","","For large seed data, write it to a temp file and use @file syntax:","```","# Write JSON to a temp file","cat > .codeyam/tmp/scenario.json << 'SCENARIO_EOF'",`{"name":"Scenario Name","type":"application","url":"${i}","dimensions":["Laptop"],"seed":{"user":[...],"feedback":[...]}}`,"SCENARIO_EOF","codeyam editor register @.codeyam/tmp/scenario.json","```"):l.push("## Registering a Scenario","",`Read the source file at \`${t}\` to understand what props the component expects.`,"","```",`codeyam editor register '{"name":"Scenario Name","type":"component","componentName":"${e}","componentPath":"${t}","dimensions":["Laptop"],"mockData":{"propName":"value"}}'`,"```"),l.push("","## Deleting a Scenario","","To delete a scenario, use its ID from the list above:","```","codeyam editor delete <scenarioId>","```","","## Validating Seed Data","","Before registering, you can validate seed data structure and check that keys match Prisma models:","```",`codeyam editor validate-seed '{"user":[...]}'`,"```"),l.push("","## Recapturing Scenarios After Code Changes","",`If the user asks you to modify the code for this ${o?"page":"component"} (CSS, layout, logic, etc.), you MUST re-register all existing scenarios after the code change so their screenshots are updated.`,"","Re-registering a scenario with the same name overwrites it and captures a fresh screenshot.","","To recapture, re-register each existing scenario using `codeyam editor register` with its current configuration. You can read the scenario JSON files in `.codeyam/editor-scenarios/` to get the exact registration data for each scenario."),l.push("","## Important","- DO NOT take any action until the user tells you what they want","- Start by briefly listing the existing scenarios",'- Then ask: "Would you like to modify an existing scenario or add a new one?"',"- Wait for the user's answer before proceeding",'- Keep scenario names descriptive: "Empty State", "With Comments", "Admin View", etc.',`- Each scenario should capture a distinct, meaningful state of the ${o?"page":"component"}`),l.join(`
610
+ `)}function sh(e,t){var a;const r=t.some(o=>!o.componentName),s=t.map(o=>`'${o.id}'`).join(", ");if(r){const o=((a=t.find(l=>l.url))==null?void 0:a.url)||null,i=t.map(l=>`.codeyam/editor-scenarios/${l.id}.json`).join(", ");return[`### Page: "${e}" (${t.length} scenario(s))`,...o?["",`Scenario URL: \`${o}\``]:[],"",...o?["Step A: Find the source file that renders this page. In Next.js App Router, URLs map to page.tsx files:"," - `/` → `app/page.tsx`"," - `/about` → `app/about/page.tsx`"," - `/c/my-slug` → `app/c/[slug]/page.tsx` (dynamic segment)","",`Based on the URL \`${o}\`, find the corresponding page.tsx file. Confirm it exists with \`cat <filepath> | head -5\`.`]:["Step A: Find the source file that renders this page by running:",' find src app -name "App.tsx" -o -name "App.jsx" -o -name "page.tsx" -o -name "page.jsx" -o -name "index.tsx" 2>/dev/null',"","Pick the file that is the main app entry point or the page component for this route. Confirm it exists with `cat <filepath> | head -5`."],"","Step B: Set page_file_path on all scenarios for this page (replace PAGE_FILE_PATH with the path from Step A):",` sqlite3 .codeyam/db.sqlite3 "UPDATE editor_scenarios SET page_file_path = 'PAGE_FILE_PATH' WHERE id IN (${s});"`,"","Step C: Get the entity SHA (after running analyze-imports in the shared step above):",` sqlite3 .codeyam/db.sqlite3 "SELECT sha FROM entities WHERE file_path = 'PAGE_FILE_PATH' ORDER BY created_at DESC LIMIT 1;"`,"","If no rows appear, the path was wrong — go back to Step A.","","Step D: Set entity_sha and display_name on all scenarios (replace ENTITY_SHA with the SHA from Step C):",` sqlite3 .codeyam/db.sqlite3 "UPDATE editor_scenarios SET entity_sha = 'ENTITY_SHA', display_name = '${e}' WHERE id IN (${s});"`,"","Step E: Add pageFilePath to the scenario JSON files so this fix persists across clones.",`For each file (${i}), read it and add \`"pageFilePath": "PAGE_FILE_PATH"\` to the \`_metadata\` object (after the \`"type"\` field). Then commit the updated JSON files.`].join(`
611
+ `)}else return[`### Component: "${e}" (${t.length} scenario(s))`,"","Step A: Get the entity SHA (after running analyze-imports in the shared step above):",` sqlite3 .codeyam/db.sqlite3 "SELECT sha FROM entities WHERE name = '${e}' ORDER BY created_at DESC LIMIT 1;"`,"","If no rows appear, check that .codeyam/glossary.json contains an entry for this component.","","Step B: Set entity_sha and display_name on all scenarios (replace ENTITY_SHA with the SHA from Step A):",` sqlite3 .codeyam/db.sqlite3 "UPDATE editor_scenarios SET entity_sha = 'ENTITY_SHA', display_name = '${e}' WHERE id IN (${s});"`].join(`
612
+ `)}function Vs({scenarioId:e,screenshotPath:t,updatedAt:r,hasScreenshot:s,imgSrc:a,name:o,dimensionLabel:i,isActive:l,onSelect:d}){const u=e&&s,p=!e&&a;return c("button",{onClick:d,className:"flex flex-col items-center gap-1 cursor-pointer group w-full",title:i?`${o} (${i})`:o,children:[c("div",{className:`w-full aspect-[16/10] rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] relative ${l?"border-[#D7FF63]/40 ring-1 ring-[#D7FF63]/20":"border-transparent hover:border-[#4d4d4d]"}`,children:[u?n(cr,{scenarioId:e,screenshotPath:t,updatedAt:r,alt:i?`${o} (${i})`:o,className:"w-full h-full",imgClassName:"w-full h-full object-contain"}):p?n("img",{src:a,alt:o,className:"w-full h-full object-contain",loading:"lazy"}):n("div",{className:"w-full h-full bg-[#1a1a1a] flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})}),i&&n("span",{className:"absolute bottom-1 right-1 text-[8px] font-medium bg-black/60 text-white px-1 py-0.5 rounded",children:i})]}),n("span",{className:`text-[10px] leading-tight text-center truncate w-full ${l?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:i?`${o} (${i})`:o})]})}function Os({filePath:e}){return e?c("div",{className:"flex items-center gap-1.5 mt-0.5",children:[c("a",{href:`/api/editor-file?path=${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",title:"Open file",className:"flex items-center gap-1.5 text-gray-500 hover:text-gray-300 transition-colors min-w-0",children:[n("span",{className:"text-sm truncate font-['IBM_Plex_Mono']",children:e}),n("svg",{className:"shrink-0",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:n("path",{d:"M4.5 1.5H2.5C1.95 1.5 1.5 1.95 1.5 2.5V9.5C1.5 10.05 1.95 10.5 2.5 10.5H9.5C10.05 10.5 10.5 10.05 10.5 9.5V7.5M7.5 1.5H10.5M10.5 1.5V4.5M10.5 1.5L5 7",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n(xt,{content:e,icon:!0,iconSize:12,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function ah({name:e,scenarios:t,reason:r="missing"}){var o,i;const s=((o=t[0])==null?void 0:o.componentPath)||((i=t[0])==null?void 0:i.pageFilePath)||null,a=r==="incomplete"?[`The "${e}" entity exists but has not been fully analyzed — its components and functions cannot be displayed.`,"","Follow these steps:","",`Step 1: Check if "${e}" is in the glossary:`,` cat .codeyam/glossary.json | grep "${e}"`,"","If not found, add an entry to .codeyam/glossary.json:",` { "name": "${e}", "filePath": "${s||"FILL_IN_PATH"}", "description": "...", "returnType": "JSX.Element" }`,"","Step 2: Run: codeyam editor analyze-imports","","Step 3: Reload the editor page and verify components/functions appear."].join(`
613
+ `):[`The "${e}" ${t.some(l=>!l.componentName)?"page":"component"} is missing entity data in the CodeYam database. Its scenarios are hidden until this is fixed.`,"","IMPORTANT: Do NOT re-register scenarios — that would overwrite their screenshots. Instead, update the database and scenario JSON files directly.","","Follow these steps EXACTLY:","","Step 1: Run: codeyam editor analyze-imports","","Step 2: Fix this entity:","",sh(e,t),"","Step 3: Reload the editor page in the browser and verify the scenarios appear."].join(`
614
+ `);return n(xt,{content:a,label:"Copy Fix Prompt",copiedLabel:"Copied!",className:"text-[10px] text-[#E0D400] hover:text-[#E0D400]/80 bg-transparent border border-[#E0D400]/30 rounded px-2 py-0.5 cursor-pointer transition-colors ml-2"})}function E5({brokenEntities:e}){const[t,r]=E(!1),s=le(d=>{navigator.clipboard.writeText(d).then(()=>{r(!0),setTimeout(()=>r(!1),2e3)})},[]);if(e.length===0)return null;const a=e.reduce((d,u)=>d+u.scenarios.length,0),o=e.filter(d=>d.reason==="incomplete"),i=e.filter(d=>d.reason==="missing"),l=[`${e.length} entities are missing data in the CodeYam database. ${a} total scenario(s) are hidden until this is fixed.`,"","IMPORTANT: Do NOT re-register scenarios — that would overwrite their screenshots. Instead, update the database and scenario JSON files directly.","","Follow these steps EXACTLY:","",...o.length>0?["## Step 1: Add missing entries to the glossary","","Read `.codeyam/glossary.json` and check if these entities have entries. For each one that is missing, add an entry:","",...o.map(d=>{var p,h;const u=((p=d.scenarios[0])==null?void 0:p.componentPath)||((h=d.scenarios[0])==null?void 0:h.pageFilePath)||"FILL_IN_PATH";return`- "${d.name}" (filePath: "${u}")`}),"",'Each glossary entry needs: name, filePath, description, returnType (use "JSX.Element" for components/pages).',""]:["## Step 1: No glossary changes needed",""],"## Step 2: Run import analysis"," codeyam editor analyze-imports","",...i.length>0?["## Step 3: Fix missing entity associations","",...i.map(d=>sh(d.name,d.scenarios)),""]:[],`## Step ${i.length>0?"4":"3"}: Reload the editor page in the browser and verify all scenarios appear. Then commit the updated scenario JSON files so the fix persists across clones.`].join(`
615
+ `);return n("div",{className:"p-4 rounded-lg border border-[#E0D400]/40 bg-[#E0D400]/8",children:c("div",{className:"flex items-center gap-3",children:[c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#E0D400",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),c("p",{className:"flex-1 min-w-0 text-sm text-[#E0D400]/90 m-0 leading-snug font-['IBM_Plex_Sans']",children:[e.length," ",e.length===1?"entity is":"entities are"," missing data, resulting in ",a," hidden scenario",a!==1?"s":"","."," ",n("button",{type:"button",className:"font-bold underline bg-transparent border-none text-[#E0D400] cursor-pointer p-0 text-sm inline hover:text-[#E0D400]/70 transition-colors",onClick:()=>s(l),children:t?c("span",{className:"inline-flex items-center gap-1",children:["Copied",n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:"inline",children:n("polyline",{points:"20 6 9 17 4 12"})})]}):"Copy this prompt"})," ","into Claude to fix them all at once."]}),n(xt,{content:l,label:c("span",{className:"flex items-center gap-2",children:["COPY PROMPT",c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),n("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})]}),copiedLabel:c("span",{className:"flex items-center gap-2",children:[n("span",{className:"invisible",children:"COPY PROMPT"}),n("span",{className:"absolute inset-0 flex items-center justify-center",children:"COPIED!"}),n("span",{className:"invisible",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",children:n("rect",{x:"9",y:"9",width:"13",height:"13"})})})]}),className:"relative text-xs font-semibold text-[#1e1e1e] bg-[#E0D400] hover:bg-[#E0D400]/80 border-none rounded px-4 py-2 cursor-pointer transition-colors shrink-0 tracking-wide font-['IBM_Plex_Mono']"})]})})}function oh({focusedEntity:e,breadcrumbItems:t,onZoomChange:r,projectRoot:s,scenarios:a,analyzedEntities:o,activeScenarioId:i,onScenarioSelect:l,onAnalyzedScenarioSelect:d,onSwitchToBuild:u,entityImports:p,glossaryFunctions:h,cachedTestResults:m={},glossaryEntries:f,entityShaMap:y,componentGroups:g,visualEntities:x,isEntityComplete:b,onReseedPreview:v}){var ke;const N=e.filePath,w=e.name,[C,k]=E("scenarios"),[j,A]=E(null),[_,M]=E(""),[T,D]=E(!1),[R,L]=E(null),[U,W]=E(!1),[V,F]=E(!1),[Y,P]=E(null);se(()=>{k("scenarios"),A(null),W(!1),F(!1),P(null)},[e.sha]);const O=fe(()=>{const Z=new Map;for(const pe of h)Z.set(pe.name,pe);return Z},[h]),S=o.some(Z=>Z.sha===e.sha||Z.filePath===N),$=!!((ke=p==null?void 0:p[w])!=null&&ke.length),I=le(async Z=>{if(!(!_.trim()||T)){D(!0);try{(await fetch("/api/editor-rename-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:Z,name:_.trim()})})).ok&&A(null)}catch{}finally{D(!1)}}},[_,T]),K=le(async Z=>{if(confirm(`Delete scenario "${Z.name}"?`)){L(Z.id);try{const pe=Z.screenshotPaths?Object.values(Z.screenshotPaths):Z.screenshotPath?[Z.screenshotPath]:[];await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:Z.id,screenshotPaths:pe})})}catch{}finally{L(null)}}},[]);if(!S&&!$){const Z=a.filter(ie=>ie.entitySha===e.sha),pe=[`The "${e.displayName}" entity (${N}) exists in the database but has not been fully analyzed. Its components and functions cannot be shown until it has import metadata.`,"","Follow these steps:","",`Step 1: Add "${w}" to the glossary if it's not already there:`,` Check: cat .codeyam/glossary.json | grep "${w}"`,"",` If not found, add an entry with name "${w}" and filePath "${N}" to .codeyam/glossary.json`,"","Step 2: Run import analysis:"," codeyam editor analyze-imports","","Step 3: Reload the editor page and verify components/functions appear."].join(`
616
+ `);return n("div",{className:"flex-1 overflow-auto",children:c("div",{className:"p-4 space-y-3",children:[c("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>{if(t.length>1){const ie=t[t.length-2];r(ie.componentName,ie.entitySha)}else r()},className:"text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0 shrink-0 text-lg",title:"Go back",children:"←"}),n("h2",{className:"text-lg font-medium text-white m-0 font-['IBM_Plex_Sans']",children:e.displayName})]}),N&&n(Os,{filePath:N,projectRoot:s}),c("div",{className:"py-2",children:[n("p",{className:"text-[11px] text-amber-400/80 m-0 leading-relaxed",children:"This entity has not been fully analyzed. Its components and functions cannot be displayed. Please copy and paste this prompt into Claude to fix the data."}),n("div",{className:"mt-2",children:n(xt,{content:pe,label:"Copy Fix Prompt",copiedLabel:"Copied!",className:"text-[10px] text-amber-400 hover:text-amber-300 bg-transparent border border-amber-400/30 rounded px-2 py-1 cursor-pointer transition-colors"})})]}),Z.length>0&&n("div",{className:"grid grid-cols-3 gap-2",children:gn(Z).map(({scenario:ie,dimensionLabel:de,screenshotPath:he,key:_e})=>n(Vs,{scenarioId:ie.id,screenshotPath:he,updatedAt:ie.updatedAt,hasScreenshot:!!he,name:ie.name,dimensionLabel:de,isActive:ie.id===i,onSelect:()=>l(ie,de??void 0)},_e))})]})})}const q=e.sha,J=a.filter(Z=>!Z.componentName&&(Z.pageFilePath===N||q&&Z.entitySha===q)),z=a.filter(Z=>Z.componentName===w||Z.componentPath===N),B=x.find(Z=>Z.filePath===N||Z.name===w),H=O.get(w)||h.find(Z=>Z.filePath===N),re=[...J,...z],ae=fe(()=>{const Z=[];if(Z.push(`# Create a New Scenario for "${e.displayName}"`),Z.push(""),Z.push(`**Entity**: ${e.displayName}`),Z.push(`**Type**: ${e.entityType}`),Z.push(`**File**: ${N}`),Z.push(""),re.length>0){Z.push("## Existing Scenarios");for(const pe of re)Z.push(`- **${pe.name}**${pe.url?` — URL: ${pe.url}`:""}`);Z.push("")}return Z.push("## Your Task"),Z.push("Ask the user what scenario they would like to create. Offer two options:"),Z.push("1. **Describe a scenario** — the user tells you what they want and you create it"),Z.push("2. **Analyze gaps** — you review the existing scenarios and source code to suggest scenarios that would improve coverage"),Z.push(""),Z.push("Once you know what scenario to create, use the `codeyam editor register` CLI command to register it. Write the scenario JSON to `.codeyam/tmp/scenario.json` first, then run `codeyam editor register @.codeyam/tmp/scenario.json`."),Z.join(`
617
+ `)},[e.displayName,e.entityType,N,re]),X=new Set((p==null?void 0:p[w])||[]),oe=$?[...g.entries()].filter(([Z])=>X.has(Z)):[],me=$?x.filter(Z=>X.has(Z.name)&&!oe.some(([pe])=>pe===Z.name)):[],ve=$?f.filter(Z=>X.has(Z.name)&&Z.returnType!=="JSX.Element"&&Z.returnType!=="React.ReactNode").map(Z=>({name:Z.name,filePath:Z.filePath,description:Z.description||"",testFile:Z.testFile,feature:Z.feature})):[],je=oe.length>0||me.length>0,te=ve.length>0;return n("div",{className:"flex-1 overflow-auto",children:c("div",{className:"p-5",children:[c("div",{className:"mb-5",children:[c("div",{className:"flex items-center gap-2.5",children:[n("button",{onClick:()=>{if(t.length>1){const Z=t[t.length-2];r(Z.componentName,Z.entitySha)}else r()},className:"text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0 shrink-0 text-xl",title:"Go back",children:"←"}),n("h2",{className:"text-xl font-medium text-white m-0 font-['IBM_Plex_Sans']",children:e.displayName})]}),e.filePath&&n("div",{className:"mt-1.5 ml-7",children:n(Os,{filePath:e.filePath,projectRoot:s})})]}),n("div",{className:"-mx-5 px-5 border-t border-b border-[#3d3d3d] flex items-center gap-6",children:[["scenarios","Scenarios"],["components","Components"],["functions","Functions"],["data-structure","Data Structure"]].map(([Z,pe])=>n("button",{onClick:()=>k(Z),className:`text-xs font-normal uppercase tracking-wider transition-colors bg-transparent border-none cursor-pointer px-0 font-['IBM_Plex_Mono'] border-b-2 leading-none ${C===Z?"text-[#D7FF63] border-b-[#D7FF63]":"text-gray-500 hover:text-gray-300 border-b-transparent"}`,style:{marginBottom:-1,paddingTop:16,paddingBottom:14},children:pe},Z))}),C==="scenarios"&&c("div",{className:"space-y-3 mt-5",children:[re.map(Z=>{const pe=Z.id===i,ie=j===Z.id;return c("div",{children:[c("div",{onClick:()=>{ie||l(Z)},className:`flex items-center gap-4 p-3 rounded-lg cursor-pointer transition-colors ${pe?"bg-[#1a2e1a] border border-[#D7FF63]/40":"bg-[#252525] hover:bg-[#2a2a2a] border border-transparent"}`,style:{opacity:R===Z.id?.4:1},children:[Z.screenshotPaths&&Object.keys(Z.screenshotPaths).length>1?n("div",{className:"flex gap-2 shrink-0",children:Object.entries(Z.screenshotPaths).map(([de,he])=>c("div",{className:"relative",children:[n(cr,{scenarioId:Z.id,screenshotPath:he,updatedAt:Z.updatedAt,alt:de,className:"rounded w-[120px] h-[75px] overflow-hidden border border-[#3d3d3d]",imgClassName:"w-full h-full object-cover"}),n("span",{className:"absolute bottom-1 right-1 text-[8px] font-medium bg-black/60 text-white px-1 py-0.5 rounded",children:de})]},de))}):Z.screenshotPath?n(cr,{scenarioId:Z.id,screenshotPath:Z.screenshotPath,updatedAt:Z.updatedAt,alt:"",className:"rounded w-[160px] h-[100px] shrink-0 overflow-hidden border border-[#3d3d3d]",imgClassName:"w-full h-full object-cover"}):n("div",{className:"rounded bg-[#1a1a1a] w-[160px] h-[100px] shrink-0 flex items-center justify-center border border-[#3d3d3d]",children:n("span",{className:"text-[10px] text-gray-600",children:"No image"})}),n("div",{className:"flex-1 min-w-0",children:ie?c("form",{className:"flex items-center gap-1.5",onSubmit:de=>{de.preventDefault(),I(Z.id)},onClick:de=>de.stopPropagation(),children:[n("input",{type:"text",value:_,onChange:de=>M(de.target.value),className:"flex-1 px-2 py-1 text-xs bg-[#1e1e1e] text-white border border-[#3d3d3d] rounded outline-none focus:border-[#005c75] min-w-0",autoFocus:!0,disabled:T}),n("button",{type:"submit",disabled:T||!_.trim(),className:"px-2 py-1 text-[10px] bg-[#005c75] text-white rounded hover:bg-[#004d63] disabled:opacity-40 cursor-pointer border-none",children:T?"...":"Save"}),n("button",{type:"button",onClick:()=>A(null),className:"px-2 py-1 text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none",children:"Cancel"})]}):c(we,{children:[n("span",{className:"text-xs text-gray-300 truncate block",children:Z.name}),pe&&c("div",{className:"flex items-center gap-3 mt-1.5",children:[n("button",{onClick:de=>{de.stopPropagation(),P(Y===Z.id?null:Z.id)},className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 cursor-pointer bg-transparent border-none p-0",children:"View Data"}),n("button",{onClick:de=>{de.stopPropagation(),F(!1),W(!0)},className:"text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none p-0",children:"Edit with Claude"}),n("button",{onClick:de=>{de.stopPropagation(),A(Z.id),M(Z.name)},className:"text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none p-0",children:"Rename"}),n("button",{onClick:de=>{de.stopPropagation(),K(Z)},disabled:R===Z.id,className:"text-[10px] text-red-400/60 hover:text-red-400 cursor-pointer bg-transparent border-none p-0",children:"Delete"})]})]})})]}),Y===Z.id&&n(P5,{scenarioId:Z.id,onClose:()=>P(null),editPrompt:yd(e.displayName,e.filePath,e.entityType,re),onReseedPreview:v})]},Z.id)}),B&&(B.scenarios.length>0||B.pendingScenarios.length>0)&&c("div",{className:"space-y-1 mt-2",children:[B.scenarios.map(Z=>c("div",{onClick:()=>d({analysisId:B.analysisId,scenarioId:Z.id,scenarioName:Z.name,entitySha:B.sha,entityName:B.name}),className:"flex items-center gap-3 p-2 rounded cursor-pointer transition-colors hover:bg-[#252525] border border-transparent",children:[Z.screenshotPath?n("img",{src:`/api/screenshot/${Z.screenshotPath}`,alt:Z.name,className:"rounded w-[48px] h-[48px] shrink-0 object-cover",loading:"lazy"}):n("div",{className:"rounded bg-[#1a1a1a] w-[48px] h-[48px] shrink-0 flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"No img"})}),n("span",{className:"text-xs text-gray-300 truncate",children:Z.name})]},Z.id)),B.pendingScenarios.map(Z=>c("div",{className:"flex items-center gap-3 p-2",children:[n("div",{className:"rounded bg-[#1a1a1a] w-[48px] h-[48px] shrink-0 flex items-center justify-center",children:n("span",{className:"text-[8px] text-gray-600",children:"..."})}),n("span",{className:"text-xs text-gray-500 truncate",children:Z})]},Z))]}),re.length===0&&!B&&!H&&n("div",{className:"text-xs text-gray-500 py-2",children:"No scenarios for this entity"}),c("button",{onClick:()=>{W(!1),F(!0)},className:"flex items-center gap-2.5 mt-4 text-xs text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none cursor-pointer p-0 font-normal uppercase tracking-wider font-['IBM_Plex_Mono'] transition-colors",children:[c("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("line",{x1:"12",y1:"8",x2:"12",y2:"16"}),n("line",{x1:"8",y1:"12",x2:"16",y2:"12"})]}),"Create New Scenario"]}),V&&n("div",{className:"mt-2 border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(Zt,{prompt:ae,height:500,onClose:()=>F(!1)})}),U&&re.length>0&&n("div",{className:"mt-2 border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(Zt,{prompt:yd(e.displayName,e.filePath,e.entityType,re),height:500,onClose:()=>W(!1)})})]}),C==="components"&&n("div",{className:"space-y-3",children:je?c(we,{children:[oe.map(([Z,pe])=>n("div",{children:y.has(Z)?c(we,{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>r(Z,y.get(Z)),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:Z})}),pe.length>0&&n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:gn(pe).map(({scenario:ie,dimensionLabel:de,screenshotPath:he,key:_e})=>n(Vs,{scenarioId:ie.id,screenshotPath:he,updatedAt:ie.updatedAt,hasScreenshot:!!he,name:ie.name,dimensionLabel:de,isActive:ie.id===i,onSelect:()=>l(ie,de??void 0)},_e))})]}):c("div",{className:"py-2",children:[n("span",{className:"text-[11px] font-medium text-gray-500",children:Z}),n("p",{className:"text-[10px] text-amber-400/80 m-0 mt-1.5 leading-relaxed",children:"There is data missing that is required to show the scenarios for this component. Please copy and paste this prompt into Claude to ask Claude to fix the data."}),n("div",{className:"mt-1.5",children:n(ah,{name:Z,scenarios:pe})})]})},Z)),me.map(Z=>c("div",{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>r(Z.name,Z.sha),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:Z.name})}),(Z.scenarios.length>0||Z.pendingScenarios.length>0)&&c("div",{className:"grid grid-cols-3 gap-2 pt-1",children:[Z.scenarios.map(pe=>n(Vs,{imgSrc:pe.screenshotPath?`/api/screenshot/${pe.screenshotPath}`:null,name:pe.name,isActive:!1,onSelect:()=>d({analysisId:Z.analysisId,scenarioId:pe.id,scenarioName:pe.name,entitySha:Z.sha,entityName:Z.name})},pe.id)),Z.pendingScenarios.map(pe=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:pe,children:pe},pe))]})]},Z.sha))]}):n("div",{className:"text-xs text-gray-500 py-2",children:"No component dependencies"})}),C==="functions"&&c("div",{className:"space-y-3",children:[H&&H.testFile&&c("div",{children:[c("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] text-gray-500",children:"Tests:"}),n(Os,{filePath:H.testFile,projectRoot:s})]}),n(Xo,{testFile:H.testFile,entityName:w,cachedResult:m[H.testFile]})]}),te?n("div",{children:ve.map(Z=>c("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>r(Z.name,y.get(Z.name)),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:Z.name})}),n(Os,{filePath:Z.filePath,projectRoot:s}),Z.testFile&&c("div",{className:"mt-0.5",children:[c("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[9px] text-gray-600",children:"test:"}),n("span",{className:"text-[9px] text-gray-500 truncate",children:Z.testFile})]}),n(Xo,{testFile:Z.testFile,entityName:Z.name,cachedResult:m[Z.testFile]})]})]},Z.name))}):H!=null&&H.testFile?null:n("div",{className:"text-xs text-gray-500 py-2",children:"No function dependencies"})]}),C==="data-structure"&&n(A5,{})]})})}function P5({scenarioId:e,onClose:t,editPrompt:r,onReseedPreview:s}){const[a,o]=E(null),[i,l]=E([]),[d,u]=E(!0),[p,h]=E(null),[m,f]=E(null),[y,g]=E(!1),[x,b]=E(null),[v,N]=E(""),[w,C]=E(""),[k,j]=E(0),[A,_]=E(!1),[M,T]=E(!1),D=be(null);if(se(()=>{u(!0),h(null),Promise.all([fetch("/api/editor-schema").then(P=>P.json()).catch(()=>({models:[]})),fetch(`/api/editor-scenario-data?scenarioId=${e}`).then(P=>P.json())]).then(([P,O])=>{const S=P.source==="explicit"?N5(P.dataStructures||[],O):y5(P.models||[],O);o(S.data),l(S.tabs),S.tabs.length>0&&!m&&f(S.tabs[0].dataKey)}).catch(()=>h("Failed to load scenario data")).finally(()=>u(!1))},[e,k]),d)return n("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg p-4 text-xs text-gray-400",children:"Loading mock data..."});if(p||!a)return n("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg p-4 text-xs text-red-400",children:p||"No data available"});if(i.length===0)return c("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg p-4 text-xs text-gray-500",children:["No mock data found for this scenario.",n("button",{onClick:t,className:"ml-2 text-gray-400 hover:text-white bg-transparent border-none cursor-pointer text-[10px]",children:"Dismiss"})]});const R=i.find(P=>P.dataKey===m)||i[0],L=m?a[m]||[]:[],U=b5(L,R.schemaFields),W=v5(U,L,R.schemaFields),V=w5(U,R.schemaFields);return c("div",{className:"mt-1 mb-1 border border-[#3d3d3d] rounded-lg overflow-hidden",children:[c("div",{className:"flex items-center gap-1.5 px-2 py-1.5 bg-[#252525] border-b border-[#3d3d3d] flex-wrap",children:[i.map(P=>{const O=m===P.dataKey,S=P.category==="datastore"?O?"text-[#D7FF63] bg-[#D7FF63]/15 border-[#D7FF63]/40":"text-[#D7FF63]/60 bg-transparent border-transparent hover:text-[#D7FF63]/80":P.category==="mock-api"?O?"text-blue-400 bg-blue-400/15 border-blue-400/40":"text-blue-400/60 bg-transparent border-transparent hover:text-blue-400/80":O?"text-white bg-[#3d3d3d] border-[#4d4d4d]":"text-gray-500 bg-transparent border-transparent hover:text-gray-300";return n("button",{onClick:()=>f(P.dataKey),className:`px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider rounded cursor-pointer border transition-colors ${S}`,children:P.label},P.dataKey)}),n("div",{className:"flex-1"}),n("button",{onClick:t,className:"w-5 h-5 flex items-center justify-center text-gray-500 hover:text-white bg-[#3d3d3d] hover:bg-[#4d4d4d] rounded-full border-none cursor-pointer text-xs transition-colors",title:"Close",children:"×"})]}),(R.description||R.category)&&c("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-[#1e1e1e] border-b border-[#2d2d2d]",children:[R.category&&n("span",{className:`text-[9px] rounded px-1.5 py-0 border ${R.category==="datastore"?"text-[#D7FF63]/80 bg-[#D7FF63]/10 border-[#D7FF63]/30":R.category==="mock-api"?"text-blue-400/80 bg-blue-400/10 border-blue-400/30":"text-gray-400 bg-gray-700/30 border-gray-600/30"}`,children:R.category==="mock-api"?"API Mock":R.category}),R.description&&n("span",{className:"text-[10px] text-gray-500",children:R.description})]}),U.length===0?n("div",{className:"px-3 py-4 text-[10px] text-gray-500 text-center",children:"No columns defined for this table"}):n("div",{className:"overflow-x-auto max-h-[300px] overflow-y-auto",children:c("table",{className:"w-full text-[10px] border-collapse table-fixed",children:[n("thead",{children:c("tr",{className:"bg-[#1e1e1e] sticky top-0 z-10",children:[n("th",{className:"text-right text-gray-600 font-normal px-2 py-1.5 border-b border-[#3d3d3d] w-8",children:"#"}),U.map(P=>c("th",{className:"text-left px-2 py-1.5 border-b border-[#3d3d3d] whitespace-nowrap overflow-hidden",children:[P===V&&n("span",{className:"inline-block text-[8px] font-bold text-white bg-[#D7FF63] rounded px-1 py-0 mr-1.5 align-middle",children:"PK"}),n("span",{className:"text-gray-300 font-medium",children:P}),n("span",{className:"text-gray-600 font-normal ml-1",children:W[P]})]},P))]})}),n("tbody",{children:L.map((P,O)=>c("tr",{className:"border-b border-[#2d2d2d] hover:bg-[#252525] group/row",children:[n("td",{className:"text-right text-gray-600 px-2 py-1.5 w-8 select-none",children:O+1}),U.map(S=>c("td",{className:`px-2 py-1.5 overflow-hidden relative group/cell ${S===V?"text-[#D7FF63] font-medium":"text-gray-300"}`,title:String(P[S]??""),children:[n("span",{className:"truncate block whitespace-nowrap",children:P[S]===null?n("span",{className:"text-gray-600 italic",children:"null"}):typeof P[S]=="object"?n("span",{className:"text-gray-500",children:JSON.stringify(P[S])}):typeof P[S]=="number"?n("span",{className:"text-amber-400",children:String(P[S])}):String(P[S])}),n("button",{onClick:$=>{$.stopPropagation(),b({row:O,col:S});const I=P[S]===null?"":typeof P[S]=="object"?JSON.stringify(P[S]):String(P[S]);N(I),C(I)},className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover/cell:opacity-100 text-gray-500 hover:text-white bg-[#252525] border border-[#4d4d4d] rounded cursor-pointer p-0.5 transition-opacity",title:"Edit",children:c("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]},S))]},O))})]})}),x&&c("div",{className:"border-t border-[#3d3d3d] bg-[#1e1e1e] px-3 py-2",children:[n("div",{className:"flex items-center gap-2 mb-1.5",children:c("span",{className:"text-[10px] text-gray-400",children:["Editing"," ",n("strong",{className:"text-gray-200",children:x.col})," in row ",x.row+1]})}),n("textarea",{value:v,onChange:P=>{const O=P.target.value;N(O),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{Y(R.dataKey,x.row,x.col,O)},600)},className:"w-full px-2 py-1.5 text-[11px] bg-[#252525] text-white border border-[#4d4d4d] rounded outline-none focus:border-[#D7FF63]/50 resize-y min-h-[60px] max-h-[200px] font-mono",autoFocus:!0,rows:v.length>100?4:2,onKeyDown:P=>{P.key==="Escape"&&F(),P.key==="Enter"&&(P.metaKey||P.ctrlKey)&&(D.current&&clearTimeout(D.current),Y(R.dataKey,x.row,x.col,v),b(null))}}),c("div",{className:"flex items-center gap-2 mt-1.5",children:[n("button",{onClick:()=>{D.current&&clearTimeout(D.current),Y(R.dataKey,x.row,x.col,v),b(null)},className:"px-3 py-1 text-[10px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded cursor-pointer border-none hover:bg-[#D7FF63]/80 transition-colors",children:"Save"}),n("button",{onClick:()=>F(),className:"px-3 py-1 text-[10px] text-gray-400 hover:text-white bg-transparent border-none cursor-pointer",children:"Cancel"}),c("span",{className:"text-[9px] text-gray-600 ml-auto",children:["⌘","+Enter to save, Esc to cancel"]})]})]}),A&&!x&&c("div",{className:"border-t border-[#3d3d3d] bg-amber-500/5 px-3 py-2 flex items-center gap-2",children:[n("span",{className:"text-[10px] text-amber-400/80",children:"Data modified — recapture to update the screenshot"}),n("div",{className:"flex-1"}),n("button",{onClick:()=>{T(!0),Promise.resolve().then(()=>(s&&s(),new Promise(P=>setTimeout(P,2e3)))).then(()=>fetch("/api/editor-capture-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e})})).then(()=>_(!1)).catch(()=>{}).finally(()=>T(!1))},disabled:M,className:"px-3 py-1 text-[10px] font-medium text-white bg-amber-600 rounded cursor-pointer border-none hover:bg-amber-500 disabled:opacity-50 transition-colors",children:M?"Recapturing...":"Recapture Screenshot"})]}),r&&c("div",{className:"border-t border-[#3d3d3d]",children:[n("div",{className:"flex justify-center py-2",children:n("button",{onClick:()=>g(!y),className:"px-3 py-1 text-[10px] font-medium text-[#D7FF63] border border-[#D7FF63]/40 rounded cursor-pointer transition-colors hover:bg-[#D7FF63]/10 bg-transparent",children:y?"Hide Claude":"Edit with Claude"})}),y&&n("div",{className:"border-t border-[#3d3d3d]",children:n(Zt,{prompt:r,height:400,onClose:()=>{g(!1),j(P=>P+1)}})})]})]});function F(){if(D.current&&clearTimeout(D.current),!!x){if(v!==w){if(a&&m){const P=a[m];if(P&&P[x.row]){let O=w;w===""?O="":w==="null"?O=null:w==="true"?O=!0:w==="false"?O=!1:isNaN(Number(w))||(O=Number(w));const S=[...P];S[x.row]={...S[x.row],[x.col]:O},o({...a,[m]:S})}}fetch("/api/editor-save-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e,table:R.dataKey,rowIndex:x.row,column:x.col,value:w})}).then(()=>{s&&s()}).catch(()=>{})}b(null),_(!1)}}async function Y(P,O,S,$){if(a&&m){const I=a[m];if(I&&I[O]){let K=$;$==="null"?K=null:$==="true"?K=!0:$==="false"?K=!1:$!==""&&!isNaN(Number($))&&(K=Number($));const q=[...I];q[O]={...q[O],[S]:K},o({...a,[m]:q})}}_(!0);try{await fetch("/api/editor-save-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:e,table:P,rowIndex:O,column:S,value:$})}),s&&s()}catch{}}}function A5(){const[e,t]=E([]),[r,s]=E([]),[a,o]=E(!0),[i,l]=E(null),[d,u]=E(!1),[p,h]=E(null);if(se(()=>{fetch("/api/editor-schema").then(g=>g.json()).then(g=>{var x,b;h(g.source||null),g.source==="explicit"?(s(g.dataStructures||[]),((x=g.dataStructures)==null?void 0:x.length)>0&&l(g.dataStructures[0].name)):(t(g.models||[]),((b=g.models)==null?void 0:b.length)>0&&l(g.models[0].name))}).catch(()=>{}).finally(()=>o(!1))},[]),a)return n("div",{className:"text-xs text-gray-400 py-4",children:"Loading schema..."});if(!(p==="explicit"?r.length>0:e.length>0))return n("div",{className:"text-xs text-gray-500 py-4",children:"No data structure found. Use the chat below to have Claude analyze your codebase and generate one."});const f=p==="explicit"?$5(r):M5(e,p);return p==="explicit"?c("div",{className:"space-y-2",children:[r.map(g=>{const x=i===g.name,b=g.category==="datastore"?"text-[#D7FF63]/80 bg-[#D7FF63]/10 border border-[#D7FF63]/30":g.category==="mock-api"?"text-blue-400/80 bg-blue-400/10 border border-blue-400/30":"text-gray-400 bg-gray-700/30 border border-gray-600/30";return c("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:[c("button",{onClick:()=>l(x?null:g.name),className:"w-full flex items-center gap-2 px-3 py-2 bg-[#252525] text-left cursor-pointer border-none transition-colors hover:bg-[#2a2a2a]",children:[n("svg",{className:`text-gray-500 transition-transform shrink-0 ${x?"rotate-90":""}`,width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M9 18l6-6-6-6"})}),n("span",{className:"text-xs font-semibold text-gray-200",children:g.name}),g.order===1&&n("span",{className:"text-[9px] text-amber-400/70",children:"Primary"}),n("span",{className:`text-[9px] rounded px-1.5 py-0 ${b}`,children:g.category==="mock-api"?"API Mock":g.category}),c("span",{className:"text-[10px] text-gray-500",children:[g.fields.length," fields"]})]}),x&&c("div",{className:"border-t border-[#3d3d3d]",children:[g.description&&n("div",{className:"px-3 py-1.5 text-[10px] text-gray-400 border-b border-[#2d2d2d]",children:g.description}),n("table",{className:"w-full text-[10px]",children:n("tbody",{children:g.fields.map(v=>c("tr",{className:"border-b border-[#2d2d2d] last:border-b-0",children:[c("td",{className:"px-3 py-1.5 text-gray-300 font-medium w-1/3",children:[v.isId&&n("span",{className:"text-amber-400 mr-1",title:"Primary key",children:"•"}),v.name]}),n("td",{className:"px-3 py-1.5 text-gray-500",children:v.type}),n("td",{className:"px-3 py-1.5 text-gray-600 w-16 text-right",children:v.required===!1?"optional":""})]},v.name))})})]})]},g.name)}),n("div",{className:"flex justify-center pt-2",children:n("button",{onClick:()=>u(!d),className:"px-4 py-1.5 text-[11px] font-medium text-[#D7FF63] border border-[#D7FF63]/40 rounded-lg cursor-pointer transition-colors hover:bg-[#D7FF63]/10 bg-transparent",children:d?"Hide Chat":"Chat with Claude about the Data Structure"})}),d&&n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(Zt,{prompt:f,height:500,onClose:()=>u(!1)})})]}):c("div",{className:"space-y-2",children:[n(T5,{prompt:`Analyze this codebase and generate a .codeyam/data-structure.json file that describes the app's data structures.
618
+
619
+ The file should be a JSON array where each entry has:
620
+ - "name": display name for the data structure
621
+ - "description": what this data represents and how it's used
622
+ - "category": either "datastore" (persisted data like DB tables, localStorage) or "mock-api" (mocked external API responses)
623
+ - "order": integer for display order (1 = primary/most important)
624
+ - "fields": array of { "name", "type", "isId" (boolean), "required" (boolean) }
625
+
626
+ Look at:
627
+ - Database schemas (prisma/schema.prisma, SQLite, etc.)
628
+ - TypeScript interfaces/types used for stored data
629
+ - localStorage usage patterns
630
+ - API response types that need mocking
631
+ - Do NOT include types that are only used as component props
632
+
633
+ Write the file to .codeyam/data-structure.json.`}),e.map(g=>{const x=i===g.name,b=g.fields.filter(N=>N.isRelation),v=g.fields.filter(N=>!N.isRelation);return c("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:[c("button",{onClick:()=>l(x?null:g.name),className:"w-full flex items-center gap-2 px-3 py-2 bg-[#252525] text-left cursor-pointer border-none transition-colors hover:bg-[#2a2a2a]",children:[n("svg",{className:`text-gray-500 transition-transform ${x?"rotate-90":""}`,width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M9 18l6-6-6-6"})}),n("span",{className:"text-xs font-semibold text-gray-200",children:g.name}),c("span",{className:"text-[10px] text-gray-500",children:[v.length," fields"]}),b.length>0&&c("span",{className:"text-[10px] text-[#D7FF63]/70",children:[b.length," relation",b.length>1?"s":""]})]}),x&&n("div",{className:"border-t border-[#3d3d3d]",children:n("table",{className:"w-full text-[10px]",children:c("tbody",{children:[v.map(N=>c("tr",{className:"border-b border-[#2d2d2d] last:border-b-0",children:[c("td",{className:"px-3 py-1.5 text-gray-300 font-medium w-1/3",children:[N.isId&&n("span",{className:"text-amber-400 mr-1",title:"Primary key",children:"•"}),N.name]}),c("td",{className:"px-3 py-1.5 text-gray-500",children:[N.type,N.isOptional&&"?",N.isList&&"[]"]})]},N.name)),b.length>0&&n("tr",{children:c("td",{colSpan:2,className:"px-3 py-1.5 border-t border-[#3d3d3d]",children:[n("span",{className:"text-[9px] text-gray-500 uppercase tracking-wider",children:"Relations"}),n("div",{className:"mt-1 flex flex-wrap gap-1.5",children:b.map(N=>n("button",{onClick:()=>l(N.relatedModel??null),className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/80 bg-[#D7FF63]/10 border border-[#D7FF63]/30 rounded px-1.5 py-0.5 cursor-pointer transition-colors",children:N.isList?`${N.relatedModel}[]`:N.relatedModel},N.name))})]})})]})})})]},g.name)}),n("div",{className:"flex justify-center pt-2",children:n("button",{onClick:()=>u(!d),className:"px-4 py-1.5 text-[11px] font-medium text-[#D7FF63] border border-[#D7FF63]/40 rounded-lg cursor-pointer transition-colors hover:bg-[#D7FF63]/10 bg-transparent",children:d?"Hide Chat":"Chat with Claude about the Data Structure"})}),d&&n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(Zt,{prompt:f,height:500,onClose:()=>u(!1)})})]})}function T5({prompt:e}){const[t,r]=E(!1),[s,a]=E(()=>typeof window>"u"?!1:localStorage.getItem("codeyam-ds-migration-dismissed")==="1");return s?null:c("div",{className:"relative border border-amber-500/30 bg-amber-500/5 rounded-lg p-3 pr-8",children:[n("button",{onClick:()=>{a(!0),localStorage.setItem("codeyam-ds-migration-dismissed","1")},className:"absolute top-2 right-2 text-gray-500 hover:text-white bg-transparent border-none cursor-pointer p-0.5",title:"Dismiss",children:n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})}),n("p",{className:"text-[11px] text-amber-400/90 m-0 font-['IBM_Plex_Sans'] leading-relaxed",children:"This data structure was auto-detected. For better results, ask Claude to generate an explicit data structure config."}),n("button",{onClick:()=>{navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},className:"mt-2 px-3 py-1 text-[10px] font-medium text-amber-400 border border-amber-500/40 rounded cursor-pointer transition-colors hover:bg-amber-500/10 bg-transparent",children:t?"Copied!":"Copy prompt for Claude"})]})}function M5(e,t){const r=e.map(a=>{const o=a.fields.map(i=>{let l=` ${i.name}: ${i.type}`;return i.isList&&(l+="[]"),i.isOptional&&(l+=" (optional)"),i.isId&&(l+=" [PK]"),i.isRelation&&(l+=` → ${i.relatedModel}`),l}).join(`
634
+ `);return`${a.name}:
635
+ ${o}`}).join(`
636
+
637
+ `);return`You are helping the user understand and modify the data structure of their application.
638
+
639
+ ${t==="prisma"?"The data structure is defined in `prisma/schema.prisma`.":t==="typescript"?"The data structure is defined via TypeScript interfaces in the `src/` directory.":"The data structure was inferred from the project."}
640
+
641
+ Here is the current data structure:
642
+
643
+ ${r}
644
+
645
+ Wait for the user to tell you what they want to do. They might want to:
646
+ - Add new models/tables
647
+ - Add or modify fields on existing models
648
+ - Understand relationships between models
649
+ - Get advice on data modeling
650
+ - Generate or modify seed data for scenarios
651
+
652
+ When making changes:
653
+ ${t==="prisma"?"- Edit `prisma/schema.prisma` directly":"- Edit the TypeScript interface files in `src/`"}
654
+ - After schema changes, update any affected scenario seed data
655
+ - Explain the impact of changes on existing data
656
+
657
+ Do NOT start making changes until the user tells you what they want.`}function $5(e){return`You are helping the user understand and modify the data structure of their application.
658
+
659
+ The data structure is explicitly defined in \`.codeyam/data-structure.json\`.
660
+
661
+ Here is the current data structure:
662
+
663
+ ${e.map(r=>{const s=r.category==="datastore"?"[datastore]":r.category==="mock-api"?"[mock-api]":`[${r.category}]`,a=r.fields.map(i=>{let l=` ${i.name}: ${i.type}`;return i.isId&&(l+=" [PK]"),i.required===!1&&(l+=" (optional)"),l}).join(`
664
+ `),o=r.description?` ${r.description}`:"";return`${r.name} ${s}${o?`
665
+ ${o}`:""}
666
+ ${a}`}).join(`
667
+
668
+ `)}
669
+
670
+ Each data structure has:
671
+ - **name**: display name
672
+ - **description**: what this data represents
673
+ - **category**: "datastore" (persisted data) or "mock-api" (mocked external API)
674
+ - **order**: display order (1 = primary)
675
+ - **fields**: array of { name, type, isId, required }
676
+
677
+ Wait for the user to tell you what they want to do. They might want to:
678
+ - Add new data structures (tables, API mocks)
679
+ - Add or modify fields
680
+ - Change categories or descriptions
681
+ - Understand how data flows through the app
682
+
683
+ When making changes:
684
+ - Edit \`.codeyam/data-structure.json\` directly
685
+ - Keep the file as a JSON array sorted by order
686
+ - Update descriptions to reflect changes
687
+ - After data structure changes, update affected scenario seed data
688
+
689
+ Do NOT start making changes until the user tells you what they want.`}function xd({status:e}){const t={new:{label:"New",bg:"bg-green-900/40",text:"text-green-400",border:"border-green-700/50"},edited:{label:"Edited",bg:"bg-blue-900/40",text:"text-blue-400",border:"border-blue-700/50"},impacted:{label:"Impacted",bg:"bg-amber-900/40",text:"text-amber-400",border:"border-amber-700/50"}}[e.status];return n("span",{className:`${t.bg} ${t.text} ${t.border} border text-[8px] font-bold px-1 py-0 rounded-full uppercase tracking-wider`,children:t.label})}function F5({testFile:e,entityName:t,cachedResult:r}){const{results:s,isRunning:a,runTests:o,stale:i}=il(e,r);if(a&&!s)return c("div",{className:"pt-1 flex items-center gap-1.5",children:[n("span",{className:"w-1.5 h-1.5 rounded-full bg-[#00a0c4] animate-pulse"}),n("span",{className:"text-[10px] text-gray-500",children:"Running tests..."})]});if(!s)return null;if(s.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-400",children:s.errorMessage})});const l=t?s.testCases.filter(p=>p.fullName.startsWith(t)):s.testCases,d=l.length>0?l:s.testCases;if(d.length===0)return null;const u=t?`${t} > `:"";return c("div",{className:"pt-1 space-y-0.5",children:[d.map(p=>{var m;const h=u&&p.fullName.startsWith(u)?p.fullName.slice(u.length):p.fullName;return c("div",{children:[c("div",{className:"flex items-center gap-1.5",children:[p.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):p.status==="failed"?n("span",{className:"text-red-400 text-[10px]",children:"✗"}):n("span",{className:"text-gray-500 text-[10px]",children:"—"}),n("span",{className:`text-[10px] ${p.status==="passed"?"text-green-400":p.status==="failed"?"text-red-400":"text-gray-500"}`,children:h})]}),p.status==="failed"&&((m=p.failureMessages)==null?void 0:m.map((f,y)=>n("div",{className:"pl-4 text-[9px] text-red-400/70 truncate max-w-full",title:f,children:f.split(`
690
+ `)[0]},y)))]},p.fullName)}),c("div",{className:"flex items-center gap-2 mt-1",children:[n("button",{onClick:o,disabled:a,className:"text-[10px] text-[#00a0c4] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:a?"Running...":i?"Re-run (stale)":"Re-run"}),i&&!a&&n("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0",title:"Source or test file changed since last run"})]})]})}const D5={added:"text-green-400",untracked:"text-green-400",modified:"text-blue-400",renamed:"text-purple-400"};function R5({files:e}){return c("div",{className:"border-t border-[#3d3d3d] pt-2 mt-1",children:[c("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:["Modified Files (",e.length,")"]}),n("div",{className:"mt-1 space-y-0.5 max-h-[150px] overflow-auto",children:e.map(t=>c("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${D5[t.status]||"text-gray-500"}`,children:t.status==="added"||t.status==="untracked"?"A":t.status==="modified"?"M":t.status==="renamed"?"R":"?"}),n("span",{className:"text-[10px] text-gray-400 truncate font-mono",children:t.path})]},t.path))})]})}const I5={feature:{label:"Feature",color:"bg-[#005c75]"},fix:{label:"Fix",color:"bg-amber-700"},refactor:{label:"Refactor",color:"bg-purple-700"},scaffold:{label:"Scaffold",color:"bg-green-700"},data:{label:"Data",color:"bg-blue-700"},milestone:{label:"Milestone",color:"bg-yellow-600"}};function O5(e){try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function L5(e){try{return new Date(e+"T00:00:00").toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"})}catch{return e}}const B5=[{value:"1d",label:"1 Day"},{value:"3d",label:"3 Days"},{value:"7d",label:"1 Week"},{value:"30d",label:"1 Month"}];function z5({entries:e,onScreenshotClick:t}){const[r,s]=E(!1),[a,o]=E("7d"),i=fe(()=>$w(e,a),[e,a]);return c("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[c("button",{onClick:()=>s(!r),className:"w-full flex items-center justify-between px-3 py-2.5 cursor-pointer bg-transparent border-none text-left hover:bg-[#333] transition-colors",children:[n("span",{className:"text-xs font-semibold text-gray-400 uppercase tracking-wider",children:"Timeframe Summary"}),n("span",{className:`text-gray-500 text-[10px] transition-transform ${r?"rotate-180":""}`,children:"▼"})]}),r&&c("div",{className:"px-3 pb-3 space-y-3 border-t border-[#3d3d3d]",children:[n("div",{className:"flex gap-1 pt-2.5",children:B5.map(l=>n("button",{onClick:()=>o(l.value),className:`px-2.5 py-1 text-[10px] font-medium rounded transition-colors cursor-pointer border ${a===l.value?"bg-[#005c75] text-white border-[#005c75]":"bg-transparent text-gray-400 border-[#4d4d4d] hover:text-white hover:border-[#005c75]"}`,children:l.label},l.value))}),c("div",{className:"flex items-center gap-3 text-[11px] text-gray-400",children:[c("span",{children:[n("span",{className:"text-white font-medium",children:i.commitCount})," ",i.commitCount===1?"commit":"commits"]}),n("span",{className:"text-[#3d3d3d]",children:"|"}),c("span",{children:[n("span",{className:"text-white font-medium",children:i.totalScenarios})," ",i.totalScenarios===1?"scenario changed":"scenarios changed"]}),n("span",{className:"text-[#3d3d3d]",children:"|"}),c("span",{children:[n("span",{className:"text-white font-medium",children:i.entryCount})," ",i.entryCount===1?"entry":"entries"]})]}),i.totalScenarios===0?n("p",{className:"text-[11px] text-gray-500 italic m-0",children:"No scenario changes in this period."}):c("div",{className:"space-y-3",children:[i.appScenarios.length>0&&c("div",{className:"space-y-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),i.appScenarios.map(l=>n(bd,{scenario:l,onScreenshotClick:t},l.name))]}),i.componentGroups.size>0&&c("div",{className:"space-y-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),[...i.componentGroups.entries()].sort(([l],[d])=>l.localeCompare(d)).map(([l,d])=>c("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:l}),d.map(u=>n(bd,{scenario:u,onScreenshotClick:t},u.name))]},l))]})]})]})]})}function bd({scenario:e,onScreenshotClick:t}){const r=e.name.indexOf(" - "),s=r!==-1?e.name.slice(r+3):e.name;return c("div",{className:"pl-2",children:[n("span",{className:"text-[10px] text-gray-500 block mb-1",children:s}),n("div",{className:"flex items-center gap-1 overflow-x-auto",children:e.screenshots.map((a,o)=>c("div",{className:"flex items-center shrink-0",children:[o>0&&n("span",{className:"text-[8px] text-gray-600 mx-0.5",children:"→"}),n("button",{type:"button",className:"w-16 h-16 rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors",title:`${e.name} (${new Date(a.time).toLocaleDateString()})`,onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${a.path.replace("screenshots/","")}`,commitSha:null,commitMessage:null,scenarioName:e.name}),children:n("img",{src:`/api/editor-journal-image/${a.path.replace("screenshots/","")}`,alt:e.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})})]},a.path))})]})}function Y5({isActive:e,onScreenshotClick:t,glossaryFunctions:r=[],cachedTestResults:s={}}){const[a,o]=E([]),[i,l]=E(!0),[d,u]=E(new Set),p=le(f=>{u(y=>{const g=new Set(y);return g.has(f)?g.delete(f):g.add(f),g})},[]),h=le(async()=>{try{const f=await fetch("/api/editor-journal");if(f.ok){const y=await f.json();o(y.entries||[])}}catch{}finally{l(!1)}},[]);if(se(()=>{h()},[h]),se(()=>{e&&h()},[e,h]),se(()=>{if(!e)return;const f=setInterval(()=>void h(),5e3);return()=>clearInterval(f)},[e,h]),i)return n("div",{className:"flex-1 flex items-center justify-center",children:n("span",{className:"text-gray-500 text-sm",children:"Loading journal..."})});if(a.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:c("div",{className:"text-center text-gray-500 px-8",children:[n("p",{className:"text-sm font-medium mb-2",children:"No journal entries yet"}),n("p",{className:"text-xs",children:"Journal entries will appear as you build. Claude records features, screenshots, and commits as the project evolves."})]})});const m=Fw(a);return n("div",{className:"flex-1 overflow-auto",children:c("div",{className:"p-3 space-y-4",children:[n(z5,{entries:a,onScreenshotClick:t}),[...m.entries()].map(([f,y])=>c("div",{children:[n("div",{className:"px-3 py-1.5 sticky top-0 bg-[#1e1e1e] z-10",children:n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:L5(f)})}),n("div",{className:"space-y-2",children:y.map((g,x)=>{const b=I5[g.type]||{label:g.type,color:"bg-gray-600"},v=`${g.time}-${x}`,N=d.has(v);return c("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[c("div",{className:`p-3 space-y-2 ${N?"":"max-h-[300px] overflow-y-auto"}`,children:[n("div",{className:"flex items-start gap-2 cursor-pointer",onClick:()=>p(v),children:c("div",{className:"flex-1 min-w-0",children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white truncate",children:g.title}),n("span",{className:`${b.color} text-white text-[9px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:b.label})]}),n("span",{className:"text-[10px] text-gray-500",children:O5(g.time)}),g.featureName&&n("span",{className:"text-[10px] text-gray-500 italic truncate",title:g.featureName,children:g.featureName})]})}),g.userPrompt&&n(rh,{text:g.userPrompt,theme:"dark"}),n("p",{className:"text-xs text-gray-400 leading-relaxed",children:g.description}),g.screenshot&&n("button",{type:"button",className:"rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] flex items-center justify-center p-1 cursor-pointer transition-colors w-full",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${g.screenshot.replace("screenshots/","")}`,commitSha:g.commitSha,commitMessage:g.commitMessage,scenarioName:g.title}),children:n("img",{src:`/api/editor-journal-image/${g.screenshot.replace("screenshots/","")}`,alt:g.title,className:"max-w-full max-h-full object-contain",loading:"lazy"})}),g.scenarioScreenshots&&g.scenarioScreenshots.length>0&&(()=>{const w=Dw(g.scenarioScreenshots),C=g.entityChangeStatus,k=w.filter(([T])=>T==="App").flatMap(([,T])=>T),j=w.filter(([T])=>T!=="App"),A=new Map;for(const T of k){const D=T,R=D.pageFilePath?Jt(Ft(D.pageFilePath)):Ct(D.url??null),L=A.get(R)||[];L.push(T),A.set(R,L)}const _=[...A.entries()],M=T=>n("button",{type:"button",className:"w-[4.5rem] h-[4.5rem] rounded overflow-hidden border border-[#3d3d3d] hover:border-[#00a0c4] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors",onClick:()=>t==null?void 0:t({screenshotUrl:`/api/editor-journal-image/${T.path.replace("screenshots/","")}`,commitSha:g.commitSha,commitMessage:g.commitMessage,scenarioName:T.name}),children:n("img",{src:`/api/editor-journal-image/${T.path.replace("screenshots/","")}`,alt:T.name,title:T.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})},T.path);return c("div",{className:"space-y-2",children:[_.length>0&&c("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),_.map(([T,D])=>c("div",{children:[c("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:T}),(C==null?void 0:C[T])&&n(xd,{status:C[T]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:D.map(M)})]},T))]}),j.length>0&&c("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),j.map(([T,D])=>c("div",{children:[c("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:T}),(C==null?void 0:C[T])&&n(xd,{status:C[T]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:D.map(M)})]},T))]})]})})(),r.length>0&&c("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"}),n("div",{className:"space-y-2",children:r.map(w=>c("div",{children:[n("span",{className:"text-[11px] font-medium text-gray-200",children:w.name}),n("span",{className:"text-[9px] text-gray-500 truncate block",children:w.filePath}),w.testFile?n(F5,{testFile:w.testFile,entityName:w.name,cachedResult:s[w.testFile]}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},w.name))})]}),g.commitSha&&c("div",{className:"flex items-center gap-1.5 text-[10px]",children:[n("span",{className:"font-mono text-[#00a0c4] bg-[#00a0c4]/10 px-1.5 py-0.5 rounded",children:g.commitSha.slice(0,7)}),n("span",{className:"text-gray-500 truncate",children:g.commitMessage})]}),N&&g.modifiedFiles&&g.modifiedFiles.length>0&&n(R5,{files:g.modifiedFiles})]}),c("button",{onClick:()=>p(v),className:"w-full py-1.5 text-[10px] text-gray-500 hover:text-gray-300 border-t border-[#3d3d3d] transition-colors cursor-pointer",children:["——— ",N?"Collapse":"Expand"," ———"]})]},v)})})]},f))]})})}function la({className:e="",color:t="currentColor",dotSize:r=3,interval:s=180}){const[a,o]=E(0);se(()=>{const d=setInterval(()=>{o(u=>(u+1)%6)},s);return()=>clearInterval(d)},[s]);const i=[0,1,2,3,4,5],l=Math.max(1,Math.round(r*.4));return n("span",{className:`inline-grid shrink-0 ${e}`,style:{gridTemplateColumns:`${r}px ${r}px`,gridTemplateRows:`${r}px ${r}px ${r}px`,gap:`${l}px`},children:i.map(d=>n("span",{style:{width:r,height:r,borderRadius:"50%",backgroundColor:t,opacity:d===a||d===(a+1)%6?1:.25,transition:"opacity 0.15s ease"}},d))})}function Po({title:e,completedCount:t,totalCount:r,subtitle:s,onClick:a,previewItems:o}){return c("button",{type:"button",onClick:a,className:"bg-[#1e1e1e] border border-[#3d3d3d] rounded-lg p-3 flex flex-col gap-2 cursor-pointer hover:border-[#555] transition-colors text-left",children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white",children:e}),n("div",{className:"flex-1"}),r!=null&&r>0?c("span",{className:"text-xs text-gray-500",children:[t,"/",r]}):null,s&&n("span",{className:"text-xs text-gray-500",children:s})]}),o&&o.length>0&&n("div",{className:"flex flex-col gap-1.5",children:o.map(i=>c("div",{className:"flex items-center gap-2 bg-[#2a2a2a] rounded-md px-2.5 py-1.5",children:[i.status==="active"&&i.buildIdle&&n("span",{className:"w-2 h-2 rounded-full bg-[#FF8B43] shrink-0"}),i.status==="active"&&!i.buildIdle&&n(la,{color:"#5ce0d2",dotSize:2}),n("span",{className:`text-[11px] truncate flex-1 ${i.status==="completed"?"text-gray-400":i.status==="active"?"text-white":"text-gray-300"}`,children:i.label}),i.status==="completed"&&n("span",{className:"shrink-0 w-3 h-3 rounded-full border border-gray-500 flex items-center justify-center",children:n("svg",{width:"6",height:"6",viewBox:"0 0 24 24",fill:"none",stroke:"#6b7280",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}),i.status==="pending"&&n("span",{className:"text-[8px] font-bold text-[#FFFF36] uppercase tracking-wider font-['IBM_Plex_Mono'] shrink-0",children:"Pending"}),i.status==="active"&&i.step&&n("span",{className:"text-[10px] text-[#5ce0d2] font-['IBM_Plex_Mono'] shrink-0",children:i.step})]},i.label))})]})}function U5({onNavigateToRoadmap:e,onSwitchToBuild:t,buildIdle:r=!1}){const[s,a]=E(null),o=le(()=>{fetch("/api/editor-roadmap").then(g=>g.json()).then(g=>a(g)).catch(()=>{})},[]);if(se(()=>{o();const g=setInterval(o,5e3);return()=>clearInterval(g)},[o]),!s)return null;const i=s.plan.filter(g=>g.completed).length,l=s.plan.length,d=s.deploy.filter(g=>g.completed).length,u=s.deploy.length,p=[],h=s.plan.find(g=>!g.completed);h&&p.push({label:h.label,status:"pending"});const m=s.plan.find(g=>g.completed);m&&p.push({label:m.label,status:"completed"});const f=[];s.editorStep!=null&&s.editorStep<18&&f.push({label:s.featureName||"New Feature",status:"active",step:`${s.editorStep}/18`,buildIdle:r}),s.recentEntries.length>0&&f.push({label:s.recentEntries[0].title,status:"completed"});const y=s.deploy.filter(g=>!g.completed).slice(0,2).map(g=>({label:g.label,status:"pending"}));return c("div",{children:[c("button",{type:"button",onClick:e,className:"flex items-center gap-1.5 bg-transparent border-none p-0 cursor-pointer group",children:[n("span",{className:"text-base font-medium text-gray-300 group-hover:text-white transition-colors",children:"Roadmap"}),n("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-500 group-hover:text-white transition-colors",children:n("path",{d:"M3 1l4 4-4 4"})})]}),c("div",{className:"grid grid-cols-3 gap-3 mt-2",children:[n(Po,{title:"Setup",completedCount:i,totalCount:l,onClick:e,previewItems:p}),n(Po,{title:"Build",subtitle:s.buildSessionCount>0?`${s.buildSessionCount} features completed.`:void 0,onClick:e,previewItems:f}),n(Po,{title:"Deploy",completedCount:d,totalCount:u,onClick:e,previewItems:y})]})]})}function ei(e){return{name:W5(e),description:J5(e),colors:H5(e),fonts:V5(e),typographyScale:K5(e),radiusTokens:G5(e)}}function W5(e){const t=e.match(/^# (.+)$/m);return t?t[1].trim():"Design System"}function J5(e){const t=e.match(/^> (.+)$/m);return t?t[1].trim():""}function H5(e){const t=[],r=cl(e,"Colors");if(!r)return t;const s=Z5(r);for(const{heading:a,content:o}of s){const i=ih(o);for(const l of i){const d=/--([a-zA-Z0-9_-]+):\s*([^;]+);(?:\s*\/\*\s*(.+?)\s*\*\/)?/g;let u;for(;(u=d.exec(l))!==null;){const p=u[2].trim();X5(p)&&t.push({name:u[1],value:p,group:a,...u[3]?{comment:u[3]}:{}})}}}return t}function V5(e){const t=e.match(/\*\*Font stack:\*\*\s*`([^`]+)`(?:\s*\([^)]*\))?(?:,\s*`([^`]+)`)?/);if(!t)return[];const r=[];if(t[1]){const a=Ao(t[1]);a&&r.push(a)}if(t[2]){const a=Ao(t[2]);a&&!r.includes(a)&&r.push(a)}const s=e.match(/\*\*Font stack:\*\*\s*`[^`]+`[^`]*`[^`]+`[^`]*`([^`]+)`/);if(s){const a=Ao(s[1]);a&&!r.includes(a)&&r.push(a)}return r}function Ao(e){return e.split(",")[0].trim().replace(/'/g,"")||null}function K5(e){const t=[],r=cl(e,"Typography");if(!r)return t;const s=r.split(`
691
+ `).filter(a=>a.startsWith("|"));if(s.length<3)return t;for(let a=2;a<s.length;a++){const o=s[a].split("|").map(i=>i.trim()).filter(Boolean);o.length>=3&&t.push({style:o[0],size:o[1],weight:o[2],notes:o.slice(3).join(" | ")})}return t}function G5(e){const t=[],r=cl(e,"Spacing");if(!r)return t;const s=ih(r);for(const a of s){const o=/--radius-([a-zA-Z0-9_-]+):\s*([^;]+);(?:\s*\/\*\s*(.+?)\s*\*\/)?/g;let i;for(;(i=o.exec(a))!==null;)t.push({name:`radius-${i[1]}`,value:i[2].trim(),...i[3]?{comment:i[3]}:{}})}return t}function q5(e,t,r){const s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`(--${s}:\\s*)([^;]+)(;.*)`,"g");return e.replace(a,`$1${r}$3`)}function Q5(e,t){return e.replace(/(\*\*Font stack:\*\*\s*`)([^`]+)(`)/,`$1${t}$3`)}function cl(e,t){const s=new RegExp(`^## .*${t}.*$`,"im").exec(e);if(!s)return null;const a=s.index+s[0].length,o=e.indexOf(`
692
+ ## `,a);return o===-1?e.slice(a):e.slice(a,o)}function Z5(e){const t=[],r=e.split(/^### /m);for(let s=0;s<r.length;s++){if(s===0){const o=r[s].trim();o&&t.push({heading:"General",content:o});continue}const a=r[s].indexOf(`
693
+ `);a===-1?t.push({heading:r[s].trim(),content:""}):t.push({heading:r[s].slice(0,a).trim(),content:r[s].slice(a+1)})}return t}function ih(e){const t=[],r=/```css\n([\s\S]*?)```/g;let s;for(;(s=r.exec(e))!==null;)t.push(s[1]);return t}function X5(e){return!!(e.startsWith("#")||e.startsWith("rgb")||e.startsWith("hsl")||e.startsWith("var(--"))}const vd=[{key:"languages",label:"Languages"},{key:"frameworks",label:"Frameworks"},{key:"databases",label:"Databases"},{key:"services",label:"External Services"},{key:"libraries",label:"Key Libraries"},{key:"infrastructure",label:"Infrastructure"}];function wd({todo:e,expanded:t,onToggle:r,onRemove:s,children:a}){return c("div",{className:"mx-3 mb-2",children:[c("div",{className:"flex items-center gap-2 py-3 px-4 group cursor-pointer bg-[#2a2a2a] rounded-lg hover:bg-[#303030] transition-colors",onClick:r,children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-gray-500 transition-transform ${t?"rotate-90":""}`,children:n("path",{d:"M3 1l4 4-4 4"})}),c("span",{className:`text-sm flex-1 ${e.completed?"text-gray-400":"text-white"}`,children:[e.label,e.autoDetect&&!e.userCreated&&n("span",{className:"text-[10px] text-gray-600 ml-1.5",children:"(auto)"})]}),e.completed?n("span",{className:"shrink-0 w-4 h-4 rounded-full border border-gray-500 flex items-center justify-center",children:n("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"#6b7280",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}):n("span",{className:"text-[9px] font-bold text-[#FFFF36] uppercase tracking-wider font-['IBM_Plex_Mono'] shrink-0",children:"Pending"}),e.userCreated&&s&&n("button",{type:"button",onClick:o=>{o.stopPropagation(),s()},className:"opacity-0 group-hover:opacity-100 text-gray-600 hover:text-red-400 bg-transparent border-none cursor-pointer p-0 transition-opacity",title:"Remove",children:n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})})]}),t&&n("div",{className:"px-4 pb-3 pt-1",children:a})]})}function Ls({title:e,completedCount:t,totalCount:r,subtitle:s,subtitleAccent:a=!1,subtitleLink:o,collapsed:i,onToggleCollapse:l,onAction:d,actionLabel:u="Select"}){return c("div",{className:`flex items-center gap-2 py-3 px-3 ${l?"cursor-pointer":""}`,onClick:l,children:[l&&n("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-gray-400 transition-transform ${i?"":"rotate-90"}`,children:n("path",{d:"M3 1l4 4-4 4"})}),n("h3",{className:"text-base font-medium text-white m-0",children:e}),r!=null&&r>0&&c(we,{children:[n("span",{className:"text-gray-500",children:"/"}),c("span",{className:"text-sm text-gray-400",children:[t,"/",r]})]}),s&&c(we,{children:[n("span",{className:"text-gray-500",children:"/"}),n("span",{className:`text-sm ${a?"text-[#5ce0d2]":"text-gray-400"}`,children:s})]}),o&&c(we,{children:[n("span",{className:"text-gray-500",children:"/"}),n("button",{type:"button",onClick:p=>{p.stopPropagation(),o.onClick()},className:"text-sm text-[#D7FF63] hover:text-[#D7FF63]/70 underline bg-transparent border-none p-0 cursor-pointer transition-colors",children:o.label})]}),n("div",{className:"flex-1"}),d&&n("button",{type:"button",onClick:p=>{p.stopPropagation(),d()},className:"text-[10px] font-bold text-gray-500 hover:text-white uppercase tracking-wider bg-transparent border-none p-0 cursor-pointer transition-colors font-['IBM_Plex_Mono']",children:u})]})}const e3={feature:"text-gray-300 border-gray-500/40 bg-gray-500/15",fix:"text-amber-400 border-amber-400/40 bg-amber-400/10",refactor:"text-purple-400 border-purple-400/40 bg-purple-400/10",scaffold:"text-emerald-400 border-emerald-400/40 bg-emerald-400/10",data:"text-blue-400 border-blue-400/40 bg-blue-400/10",milestone:"text-yellow-400 border-yellow-400/40 bg-yellow-400/10"},t3="text-gray-400 border-gray-400/40 bg-gray-400/10";function n3(e){const t=new Map;for(const s of e){const a=s.componentName||"App";t.has(a)||t.set(a,[]),t.get(a).push(s)}return[...t.entries()].sort(([s],[a])=>s==="App"?-1:a==="App"?1:s.localeCompare(a))}const r3={added:"text-green-400",untracked:"text-green-400",modified:"text-blue-400",renamed:"text-purple-400",deleted:"text-red-400"};function s3({entry:e,expandedSections:t,onToggleSection:r,onScreenshotClick:s}){var p;const a=e.scenarioScreenshots?n3(e.scenarioScreenshots):[],o=((p=a.find(([h])=>h==="App"))==null?void 0:p[1])||[],i=a.filter(([h])=>h!=="App"),l=(e.modifiedFiles||[]).filter(h=>!h.path.startsWith(".codeyam/")&&!h.path.includes("node_modules")&&!h.path.endsWith(".log")),d=h=>`${e.time}-${h}`,u=(o.length>0?o:e.scenarioScreenshots||[]).slice(0,3);return c("div",{className:"px-4 py-4 space-y-4",children:[e.description&&c("div",{children:[n("span",{className:"text-[10px] font-bold text-[#646464] uppercase tracking-wider font-['IBM_Plex_Mono']",children:"Description"}),n("p",{className:"text-sm text-white m-0 mt-1.5 leading-relaxed",children:e.description})]}),e.userPrompt&&c("div",{children:[n("span",{className:"text-[10px] font-bold text-[#646464] uppercase tracking-wider font-['IBM_Plex_Mono'] mr-2",children:"User Prompt"}),c("span",{className:"text-sm text-gray-400 leading-relaxed",children:[e.userPrompt.length>150?e.userPrompt.slice(0,150)+"... ":e.userPrompt,e.userPrompt.length>150&&n("span",{className:"text-[#5ce0d2] cursor-pointer hover:underline text-sm",children:"Read More"})]})]}),u.length>0&&c("div",{children:[n("span",{className:"text-[10px] font-bold text-[#646464] uppercase tracking-wider font-['IBM_Plex_Mono']",children:"Preview"}),n("div",{className:"flex gap-3 mt-2",children:u.map(h=>c("div",{className:"flex flex-col gap-1.5",children:[n("button",{type:"button",onClick:()=>s==null?void 0:s({screenshotUrl:`/api/editor-journal-image/${h.path.replace("screenshots/","")}`,commitSha:e.commitSha||null,commitMessage:e.commitMessage||null,scenarioName:h.name}),className:"w-[7rem] h-[5.5rem] rounded-lg overflow-hidden border border-[#3d3d3d] hover:border-[#5ce0d2] bg-[#1e1e1e] flex items-center justify-center cursor-pointer transition-colors p-0",children:n("img",{src:`/api/editor-journal-image/${h.path.replace("screenshots/","")}`,alt:h.name,title:h.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})}),n("span",{className:"text-[11px] text-gray-500 truncate w-[7rem]",children:h.name.includes(" - ")?h.name.split(" - ")[0]:h.name})]},h.path))})]}),l.length>0&&c("div",{children:[c("button",{type:"button",onClick:()=>r(d("files")),className:"flex items-center gap-2 text-[10px] font-bold text-[#646464] uppercase tracking-wider font-['IBM_Plex_Mono'] bg-transparent border-none p-0 cursor-pointer hover:text-gray-300 transition-colors",children:[n("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:`transition-transform ${t.has(d("files"))?"rotate-90":""}`,children:n("path",{d:"M3 1l4 4-4 4"})}),"Modified Files (",l.length,")"]}),t.has(d("files"))&&n("div",{className:"mt-1.5 max-h-[120px] overflow-auto space-y-0.5",children:l.map(h=>c("div",{className:"flex items-center gap-1.5 text-[11px]",children:[n("span",{className:`shrink-0 text-[9px] font-bold uppercase ${r3[h.status]||"text-gray-500"}`,children:h.status==="untracked"?"A":h.status.charAt(0).toUpperCase()}),n("span",{className:"text-gray-500 truncate",children:h.path})]},h.path))})]}),o.length>0&&c("div",{children:[c("button",{type:"button",onClick:()=>r(d("app")),className:"flex items-center gap-2 text-[10px] font-bold text-[#646464] uppercase tracking-wider font-['IBM_Plex_Mono'] bg-transparent border-none p-0 cursor-pointer hover:text-gray-300 transition-colors",children:[n("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:`transition-transform ${t.has(d("app"))?"":"rotate-90"}`,children:n("path",{d:"M3 1l4 4-4 4"})}),"App"]}),!t.has(d("app"))&&n("div",{className:"flex gap-2 mt-1.5 flex-wrap",children:o.map(h=>n("button",{type:"button",onClick:()=>s==null?void 0:s({screenshotUrl:`/api/editor-journal-image/${h.path.replace("screenshots/","")}`,commitSha:e.commitSha||null,commitMessage:e.commitMessage||null,scenarioName:h.name}),className:"w-[4.5rem] h-[4.5rem] rounded overflow-hidden border border-[#3d3d3d] hover:border-[#5ce0d2] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors p-0",children:n("img",{src:`/api/editor-journal-image/${h.path.replace("screenshots/","")}`,alt:h.name,title:h.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})},h.path))})]}),i.length>0&&c("div",{children:[c("button",{type:"button",onClick:()=>r(d("components")),className:"flex items-center gap-2 text-[10px] font-bold text-[#646464] uppercase tracking-wider font-['IBM_Plex_Mono'] bg-transparent border-none p-0 cursor-pointer hover:text-gray-300 transition-colors",children:[n("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:`transition-transform ${t.has(d("components"))?"rotate-90":""}`,children:n("path",{d:"M3 1l4 4-4 4"})}),"Components (",i.length,")"]}),t.has(d("components"))&&n("div",{className:"mt-1.5 space-y-2",children:i.map(([h,m])=>c("div",{children:[n("button",{type:"button",onClick:()=>onZoomChange==null?void 0:onZoomChange(h),className:"text-[11px] text-gray-400 hover:text-[#5ce0d2] font-medium bg-transparent border-none p-0 cursor-pointer transition-colors",children:h}),n("div",{className:"flex gap-1.5 mt-1 flex-wrap",children:m.map(f=>n("button",{type:"button",onClick:()=>s==null?void 0:s({screenshotUrl:`/api/editor-journal-image/${f.path.replace("screenshots/","")}`,commitSha:e.commitSha||null,commitMessage:e.commitMessage||null,scenarioName:f.name}),className:"w-14 h-14 rounded overflow-hidden border border-[#3d3d3d] hover:border-[#5ce0d2] bg-[#1e1e1e] shrink-0 flex items-center justify-center cursor-pointer transition-colors p-0",children:n("img",{src:`/api/editor-journal-image/${f.path.replace("screenshots/","")}`,alt:f.name,title:f.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})},f.path))})]},h))})]})]})}function a3(e){try{return new Date(e).toLocaleDateString([],{month:"short",day:"numeric"})}catch{return""}}function o3({designSystem:e,onEdit:t}){const r=e.colors.filter(s=>s.value.startsWith("#")).slice(0,10);return c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-xs font-medium text-gray-200 mb-2",children:e.name}),r.length>0&&n("div",{className:"flex gap-1.5 mb-2 flex-wrap",children:r.map(s=>n("div",{className:"w-5 h-5 rounded border border-[#444]",style:{backgroundColor:s.value},title:`--${s.name}: ${s.value}`},`${s.group}-${s.name}`))}),e.fonts.length>0&&c("div",{className:"text-[10px] text-gray-500 mb-2",children:["Font: ",e.fonts.join(", ")]}),t&&n("button",{type:"button",onClick:t,className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors font-medium",children:"View & Edit >"})]})}function Nd({projectTitle:e,projectDescription:t,onSave:r,onEditNavigate:s,defaultEditing:a=!1}){const[o,i]=E(a),[l,d]=E(e||""),[u,p]=E(t||""),[h,m]=E(!1);se(()=>{d(e||""),p(t||"")},[e,t]);const f=()=>{m(!0),r(l,u),m(!1),i(!1)},y=()=>{d(e||""),p(t||""),i(!1)};return o?n("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:c("div",{className:"space-y-2.5",children:[c("div",{children:[n("label",{className:"block text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1",children:"Project Name"}),n("input",{type:"text",value:l,onChange:g=>d(g.target.value),placeholder:"My App",className:"w-full px-2.5 py-1.5 text-sm bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"})]}),c("div",{children:[n("label",{className:"block text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1",children:"Description"}),n("textarea",{value:u,onChange:g=>p(g.target.value),placeholder:"A brief description of your project...",rows:2,className:"w-full px-2.5 py-1.5 text-sm bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors resize-none"})]}),c("div",{className:"flex gap-2 pt-0.5",children:[n("button",{type:"button",onClick:f,disabled:h,className:"px-3 py-1 text-[11px] text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium disabled:opacity-50",children:h?"Saving...":"Save"}),n("button",{type:"button",onClick:y,className:"px-3 py-1 text-[11px] text-gray-400 bg-transparent border border-[#3d3d3d] rounded-md hover:text-white hover:border-[#555] transition-colors cursor-pointer",children:"Cancel"})]})]})}):c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[e?n("div",{className:"text-xs font-medium text-gray-200 mb-0.5",children:e}):n("div",{className:"text-xs text-gray-500 italic mb-0.5",children:"No name set"}),t&&n("div",{className:"text-[11px] text-gray-400 leading-relaxed",children:t}),n("button",{type:"button",onClick:s??(()=>i(!0)),className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-1.5 cursor-pointer transition-colors font-medium",children:"Edit >"})]})}function i3({techStack:e,onNavigate:t}){if(!(e&&vd.some(({key:i})=>e[i]&&e[i].length>0)))return c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-xs text-gray-400 mb-2",children:"No tech stack configured yet"}),t&&n("button",{type:"button",onClick:t,className:"px-3 py-1.5 text-[11px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer",children:"Set up with Claude >"})]});const s=[];for(const{key:i}of vd){const l=e[i];if(l)for(const d of l)s.push(d)}const a=s.slice(0,5),o=s.length-5;return c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[c("div",{className:"flex flex-wrap gap-1.5",children:[a.map((i,l)=>c("span",{className:"inline-flex items-center gap-1 text-xs text-gray-300 bg-[#2a2a2a] px-2 py-0.5 rounded",children:[i.name,i.version&&c("span",{className:"text-[10px] text-gray-500",children:["v",i.version]})]},l)),o>0&&c("span",{className:"text-[10px] text-gray-500 self-center",children:["+",o," more"]})]}),t&&n("button",{type:"button",onClick:t,className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-2 cursor-pointer transition-colors font-medium",children:"View all >"})]})}function To({iconType:e,size:t=14,className:r=""}){const s={width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",className:r};switch(e){case"desktop":return c("svg",{...s,children:[n("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n("path",{d:"M8 21h8M12 17v4"})]});case"laptop":return c("svg",{...s,children:[n("path",{d:"M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8H4V6z"}),n("path",{d:"M2 18h20"})]});case"tablet":return c("svg",{...s,children:[n("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]});case"mobile":return c("svg",{...s,children:[n("rect",{x:"7",y:"2",width:"10",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]})}}function Sd({open:e,size:t=12}){return e?c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),n("circle",{cx:"12",cy:"12",r:"3"})]}):c("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"}),n("path",{d:"M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"}),n("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),n("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}const l3=new Set(Zp.flatMap(e=>e.presets.map(t=>t.name)));function Cd({screenSizes:e,projectScreenSizes:t,defaultScreenSize:r,appFormats:s,onSave:a,onEditNavigate:o,defaultEditing:i=!1}){const l=fe(()=>Xp(e,s),[e,s]),d=fe(()=>{if(e){for(const[W,V]of Object.entries(e))if(V.default)return W}return(r==null?void 0:r.name)||""},[e,r]),[u,p]=E(i),[h,m]=E({}),[f,y]=E(new Set),[g,x]=E(""),[b,v]=E(""),[N,w]=E(""),[C,k]=E(""),j=()=>{const W={};for(const Y of l)W[Y.name]={width:Y.width,height:Y.height};m(W);const V=new Set,F=t||e;if(F)for(const Y of Object.keys(F)){const P=F[Y];(t||!P||!("default"in P))&&V.add(Y)}y(V),x(d),v(""),w(""),k(""),p(!0)};se(()=>{i&&j()},[]);const A=(W,V,F)=>{m(Y=>{const P={...Y};if(P[W]){if(delete P[W],y(O=>{const S=new Set(O);return S.delete(W),S}),W===g){const O=Object.keys(P);x(O[0]||"")}}else P[W]={width:V,height:F},Object.keys(Y).length===0&&x(W);return P})},_=W=>{y(V=>{const F=new Set(V);return F.has(W)?F.delete(W):F.add(W),F})},M=W=>{h[W]&&x(W)},T=()=>{const W=b.trim(),V=parseInt(N,10),F=parseInt(C,10);!W||isNaN(V)||isNaN(F)||V<=0||F<=0||(m(Y=>(Object.keys(Y).length===0&&x(W),{...Y,[W]:{width:V,height:F}})),v(""),w(""),k(""))},D=W=>{m(V=>{const F={...V};return delete F[W],W===g&&x(Object.keys(F)[0]||""),F}),y(V=>{const F=new Set(V);return F.delete(W),F})},R=()=>{const W={};for(const[F,Y]of Object.entries(h))W[F]={width:Y.width,height:Y.height,...F===g?{default:!0}:{}};const V={};for(const F of f)h[F]&&(V[F]={...h[F]});a(W,V),p(!1)};if(u){const W=Object.entries(h).filter(([V])=>!l3.has(V));return c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[c("div",{className:"flex items-center gap-2 mb-2 px-0.5",children:[n("div",{className:"w-3.5"}),n("div",{className:"w-3.5"}),n("span",{className:"text-[9px] font-semibold text-gray-600 uppercase tracking-wider flex-1",children:"Size"}),n("span",{className:"text-[9px] font-semibold text-gray-600 uppercase tracking-wider w-[72px] text-right",children:"Dimensions"}),n("span",{className:"text-[9px] font-semibold text-gray-600 uppercase tracking-wider w-[50px] text-center",title:"Include in project screenshot sizes",children:"Project"}),n("span",{className:"text-[9px] font-semibold text-gray-600 uppercase tracking-wider w-[54px] text-center",children:"Default"})]}),c("div",{className:"space-y-3",children:[Zp.map(V=>c("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:V.category}),n("div",{className:"space-y-0.5",children:V.presets.map(F=>{const Y=!!h[F.name],P=g===F.name,O=f.has(F.name),S=Hs(F);return c("div",{className:"flex items-center gap-2 py-0.5",children:[n("button",{type:"button",onClick:()=>A(F.name,F.width,F.height),className:`w-3.5 h-3.5 rounded-sm border flex items-center justify-center shrink-0 cursor-pointer transition-colors ${Y?"bg-[#D7FF63] border-[#D7FF63]":"bg-transparent border-[#555] hover:border-[#888]"}`,children:Y&&n("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"#1e1e1e",strokeWidth:"3.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}),n(To,{iconType:S,size:14,className:Y?"text-gray-300":"text-gray-600"}),n("span",{className:`text-xs flex-1 ${Y?"text-gray-300":"text-gray-500"}`,children:F.name}),c("span",{className:"text-[10px] text-gray-500 tabular-nums w-[72px] text-right",children:[F.width," × ",F.height]}),n("div",{className:"w-[50px] flex justify-center",children:Y?n("button",{type:"button",onClick:()=>_(F.name),className:`p-1 rounded cursor-pointer transition-colors ${O?"text-[#D7FF63] hover:text-[#D7FF63]/70":"text-gray-600 hover:text-gray-400"}`,title:O?"In project screenshots":"Not in project screenshots",children:n(Sd,{open:O})}):n("span",{className:"w-3"})}),n("div",{className:"w-[54px] flex justify-center",children:Y?n("button",{type:"button",onClick:()=>M(F.name),className:`text-[10px] px-1.5 py-0.5 rounded border cursor-pointer transition-colors ${P?"text-[#1e1e1e] bg-[#D7FF63] border-[#D7FF63]":"text-gray-500 bg-transparent border-[#444] hover:border-[#666] hover:text-gray-300"}`,title:P?"Default size":"Set as default",children:P?"★":"☆"}):n("span",{className:"w-3"})})]},F.name)})})]},V.category)),W.length>0&&c("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:"Custom"}),n("div",{className:"space-y-0.5",children:W.map(([V,F])=>{const Y=g===V,P=f.has(V),O=Hs({name:V,width:F.width,height:F.height});return c("div",{className:"flex items-center gap-2 py-0.5",children:[n("div",{className:"w-3.5"}),n(To,{iconType:O,size:14,className:"text-gray-300"}),n("span",{className:"text-xs text-gray-300 flex-1",children:V}),c("span",{className:"text-[10px] text-gray-500 tabular-nums w-[72px] text-right",children:[F.width," × ",F.height]}),n("div",{className:"w-[50px] flex justify-center",children:n("button",{type:"button",onClick:()=>_(V),className:`p-1 rounded cursor-pointer transition-colors ${P?"text-[#D7FF63] hover:text-[#D7FF63]/70":"text-gray-600 hover:text-gray-400"}`,title:P?"In project screenshots":"Not in project screenshots",children:n(Sd,{open:P})})}),n("div",{className:"w-[54px] flex justify-center",children:n("button",{type:"button",onClick:()=>M(V),className:`text-[10px] px-1.5 py-0.5 rounded border cursor-pointer transition-colors ${Y?"text-[#1e1e1e] bg-[#D7FF63] border-[#D7FF63]":"text-gray-500 bg-transparent border-[#444] hover:border-[#666] hover:text-gray-300"}`,title:Y?"Default size":"Set as default",children:Y?"★":"☆"})}),n("button",{type:"button",onClick:()=>D(V),className:"text-gray-600 hover:text-red-400 bg-transparent border-none p-0.5 cursor-pointer transition-colors text-xs leading-none",children:"×"})]},V)})})]}),c("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:"Add Custom Size"}),c("div",{className:"flex items-center gap-1.5",children:[n("input",{type:"text",value:b,onChange:V=>v(V.target.value),placeholder:"Name",className:"flex-1 min-w-0 px-2 py-1 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("input",{type:"number",value:N,onChange:V=>w(V.target.value),placeholder:"W",className:"w-14 px-2 py-1 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("span",{className:"text-[10px] text-gray-500",children:"×"}),n("input",{type:"number",value:C,onChange:V=>k(V.target.value),placeholder:"H",className:"w-14 px-2 py-1 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("button",{type:"button",onClick:T,className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors font-medium",children:"+ Add"})]})]})]}),c("div",{className:"flex gap-2 pt-2.5",children:[n("button",{type:"button",onClick:R,className:"px-3 py-1 text-[11px] text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium",children:"Save"}),n("button",{type:"button",onClick:()=>p(!1),className:"px-3 py-1 text-[11px] text-gray-400 bg-transparent border border-[#3d3d3d] rounded-md hover:text-white hover:border-[#555] transition-colors cursor-pointer",children:"Cancel"})]})]})}if(l.length===0)return c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-xs text-gray-500 italic",children:"No screen sizes configured"}),n("button",{type:"button",onClick:o??j,className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-1.5 cursor-pointer transition-colors font-medium",children:"Edit >"})]});const L=W=>d===W,U=W=>{var V;return!!((V=t||e)!=null&&V[W])};return c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"flex flex-wrap gap-1.5",children:l.map(W=>{const V=Hs(W);return c("span",{className:"inline-flex items-center gap-1.5 text-xs bg-[#2a2a2a] px-2 py-1 rounded text-gray-300",children:[n(To,{iconType:V,size:12,className:"text-gray-400"}),W.name,c("span",{className:"text-[10px] text-gray-500",children:[W.width,"×",W.height]}),L(W.name)&&n("span",{className:"text-[10px] text-[#D7FF63]",children:"★"}),U(W.name)&&n("span",{className:"text-[10px] text-[#D7FF63]",title:"Project screenshot size",children:"P"})]},W.name)})}),n("button",{type:"button",onClick:o??j,className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-2 cursor-pointer transition-colors font-medium",children:"Edit >"})]})}const kd=[{id:"vercel",name:"Vercel",services:["Hosting"],description:"Frontend-optimized hosting"},{id:"railway",name:"Railway",services:["Hosting","Database","Storage"],description:"Full-stack infrastructure"},{id:"runloop",name:"Runloop",services:["Sandboxes","Hosting"],description:"Sandbox-first deployment"}];function Lt({step:e,done:t,active:r}){return n("span",{className:`shrink-0 w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold ${t?"bg-green-600 text-white":r?"bg-[#D7FF63] text-black":"bg-[#333] text-gray-500"}`,children:t?n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})}):e})}function c3({hosting:e,onSave:t}){var ae;const[r,s]=E(null),[a,o]=E(!0),[i,l]=E(""),[d,u]=E(!1),[p,h]=E([]),[m,f]=E(null),[y,g]=E(!1),[x,b]=E(!1),[v,N]=E(!1),[w,C]=E(!1),[k,j]=E(null),[A,_]=E(null),[M,T]=E(null),[D,R]=E(null),[L,U]=E(null),W=le(()=>{o(!0),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"full-status"})}).then(X=>X.json()).then(X=>{s(X),T(null)}).catch(()=>T("Failed to check status")).finally(()=>o(!1))},[]);se(()=>{W()},[W]);const V=()=>{i.trim()&&(u(!0),T(null),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"save-token",token:i.trim()})}).then(X=>X.json()).then(X=>{X.ok?(l(""),W()):T(X.error||"Token verification failed")}).catch(()=>T("Failed to save token")).finally(()=>u(!1)))},[F,Y]=E(!1),P=le(()=>{g(!0),T(null),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"list-projects"})}).then(X=>X.json()).then(X=>{X.ok?(h(X.projects||[]),f(X.suggestedProjectId||null),_(X.gitHubRepo||null)):T(X.error||"Failed to load projects"),Y(!0)}).catch(X=>{T(`Failed to load projects: ${X.message||"network error"}`),Y(!0)}).finally(()=>g(!1))},[]),O=()=>{N(!0),T(null),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"create-project"})}).then(X=>X.json()).then(X=>{X.ok?(t({provider:"vercel",vercelProjectId:X.project.id,vercelProjectName:X.project.name}),W()):T(X.error||"Failed to create project")}).catch(()=>T("Failed to create project")).finally(()=>N(!1))},S=(X,oe)=>{b(!0),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"link-project",projectId:X,projectName:oe})}).then(me=>me.json()).then(me=>{me.ok&&(t({provider:"vercel",vercelProjectId:X,vercelProjectName:oe}),W())}).catch(()=>{}).finally(()=>b(!1))},$=r||{hasToken:!1,tokenVerified:!1,user:null,projectLinked:!1,projectName:null,dashboardUrl:null,productionUrl:null,lastDeployment:null,envVarsChecked:!1,envVars:[]},I=$.tokenVerified,K=$.projectLinked,q=$.envVars.filter(X=>X.configuredOnVercel).length,J=$.envVars.length,z=$.envVarsChecked&&(J===0||q===J),B=I?K?3:2:1,H=le(X=>{var ve;const oe=[`Step 1 (Account & Token): ${$.tokenVerified?`Connected as ${(ve=$.user)==null?void 0:ve.username}`:$.hasToken?"Token found but verification failed":"Not started"}`,`Step 2 (Link Project): ${$.projectLinked?`Linked to "${$.projectName}"`:"Not linked"}`,`Step 3 (Environment Variables): ${$.envVarsChecked?$.envVars.length===0?"No env vars needed":`${$.envVars.filter(je=>je.configuredOnVercel).length}/${$.envVars.length} configured`:"Not checked yet"}`];$.lastDeployment&&oe.push(`Last deployment: ${$.lastDeployment.state} (${$.lastDeployment.commitsSince} commits since)`);const me=["# Vercel Setup Help","","The user is setting up Vercel hosting for their project and needs help.","","## Current Status",...oe.map(je=>`- ${je}`),M?`
694
+ ## Current Error
695
+ \`\`\`
696
+ ${M}
697
+ \`\`\``:"",X?`
698
+ ## Additional Context
699
+ ${X}`:"","","## What You Can Do","- Help the user understand what they need to do next","- If there is a deployment error, help them debug it","- You can read project files to understand the setup (package.json, next.config.ts, etc.)","- Guide them to the right Vercel documentation or settings pages","- If the issue is about GitHub permissions, guide them to vercel.com/account/login-connections","","Start by acknowledging what step they are on and ask what they need help with."].filter(Boolean).join(`
700
+ `);R(me),Promise.resolve().then(()=>n2).then(je=>{U(()=>je.MiniClaudeChat)})},[$,M]),re=be(!1);return se(()=>{B===2&&!re.current&&p.length===0&&!y&&(re.current=!0,P())},[B,p.length,y,P]),se(()=>{if(!k)return;const X=["READY","ERROR","CANCELED"];if(X.includes(k.state))return;const oe=setInterval(()=>{fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"check-deployment",deploymentId:k.id})}).then(me=>me.json()).then(me=>{me.ok&&(j(ve=>ve?{...ve,state:me.state,url:me.url||ve.url,errorMessage:me.errorMessage,logsUrl:me.logsUrl}:null),X.includes(me.state)&&W())}).catch(()=>{})},5e3);return()=>clearInterval(oe)},[k,W]),a&&!r?n("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:n("span",{className:"text-xs text-gray-500",children:"Checking Vercel setup..."})}):c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333] space-y-3",children:[c("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:"Vercel Setup"}),n("p",{className:"text-[11px] text-gray-400 m-0 leading-relaxed",children:"Vercel deploys your app to the web. Push your code and Vercel automatically builds and hosts it at a public URL — no server setup required. Free for personal projects."})]}),M&&c("div",{className:"text-[11px] bg-red-400/10 rounded px-2.5 py-2 space-y-1.5",children:[n("p",{className:"text-red-400 m-0",children:M}),M.toLowerCase().includes("login connection")&&c(we,{children:[n("p",{className:"text-gray-400 m-0 text-[10px] leading-relaxed",children:"Vercel needs permission to access your GitHub repositories. Connect your GitHub account, then come back and try again."}),c("div",{className:"flex items-center gap-2",children:[n("a",{href:"https://vercel.com/account/login-connections",target:"_blank",rel:"noopener noreferrer",className:"inline-block text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border border-[#D7FF63]/30 rounded px-2.5 py-1 no-underline transition-colors",children:"Connect GitHub →"}),n("button",{type:"button",onClick:()=>{T(null),O()},className:"text-[11px] text-gray-400 hover:text-white bg-transparent border border-[#3d3d3d] rounded px-2.5 py-1 cursor-pointer transition-colors",children:"Retry"})]})]})]}),c("div",{className:"space-y-1.5",children:[c("div",{className:"flex items-center gap-2",children:[n(Lt,{step:1,done:I,active:B===1}),n("span",{className:"text-xs font-medium text-white",children:"Create Account & Connect"}),I&&$.user&&n("span",{className:"text-[10px] text-gray-400 ml-auto",children:$.user.username})]}),B===1&&c("div",{className:"ml-7 space-y-2.5",children:[c("div",{className:"space-y-1",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"a) Create a free Vercel account"}),n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"Sign up with GitHub, GitLab, or email. The free Hobby plan includes unlimited deployments and custom domains."}),n("a",{href:"https://vercel.com/signup",target:"_blank",rel:"noopener noreferrer",className:"inline-block text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border border-[#D7FF63]/30 rounded px-2.5 py-1 no-underline transition-colors",children:"Sign up at vercel.com →"})]}),c("div",{className:"space-y-1",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"b) Create an API token"}),n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"This lets CodeYam verify your setup and check your project configuration. Go to Account Settings → Tokens → Create."}),n("a",{href:"https://vercel.com/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"inline-block text-[11px] text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline transition-colors",children:"Open token settings →"})]}),c("div",{className:"space-y-1",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"c) Paste your token here"}),$.hasToken&&!$.tokenVerified&&n("p",{className:"text-[11px] text-amber-400 m-0",children:"A token was found but it didn't work. Try creating a new one and pasting it below."}),c("div",{className:"flex items-center gap-1.5",children:[n("input",{type:"password",placeholder:"Paste your Vercel token",value:i,onChange:X=>l(X.target.value),onKeyDown:X=>{X.key==="Enter"&&V()},className:"bg-[#1a1a1a] border border-[#444] rounded px-2 py-1 text-xs text-white flex-1 outline-none focus:border-[#D7FF63]/50 font-mono"}),n("button",{type:"button",onClick:V,disabled:d||!i.trim(),className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:d?"Verifying...":"Connect"})]}),n("p",{className:"text-[10px] text-gray-600 m-0",children:"Stored in .env.local (gitignored — never committed)"})]})]})]}),c("div",{className:"space-y-1.5",children:[c("div",{className:"flex items-center gap-2",children:[n(Lt,{step:2,done:K,active:B===2}),n("span",{className:`text-xs font-medium ${B>=2?"text-white":"text-gray-600"}`,children:"Link Project"}),K&&$.projectName&&n("span",{className:"text-[10px] text-gray-400 ml-auto",children:$.projectName})]}),K&&c("div",{className:"ml-7 space-y-1.5",children:[c("div",{className:"flex items-center gap-3",children:[$.dashboardUrl&&n("a",{href:$.dashboardUrl,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline transition-colors",children:"Dashboard →"}),((ae=$.lastDeployment)==null?void 0:ae.url)&&c("a",{href:$.lastDeployment.url,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline transition-colors",children:[$.lastDeployment.url.replace("https://","")," →"]})]}),$.lastDeployment&&!k&&c("div",{className:"flex items-center gap-2 text-[10px] text-gray-500",children:[c("span",{children:["Deployed"," ",(()=>{const X=Date.now()-$.lastDeployment.createdAt,oe=Math.floor(X/6e4);if(oe<1)return"just now";if(oe<60)return`${oe}m ago`;const me=Math.floor(oe/60);return me<24?`${me}h ago`:`${Math.floor(me/24)}d ago`})()]}),n("span",{className:"text-gray-600",children:"·"}),c("span",{className:$.lastDeployment.commitsSince>0?"text-amber-400":"text-gray-500",children:[$.lastDeployment.commitsSince," commit",$.lastDeployment.commitsSince===1?"":"s"," since"]}),n("button",{type:"button",disabled:w,onClick:()=>{T(null),C(!0),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"deploy"})}).then(X=>X.json()).then(X=>{X.ok&&X.deployment?j({id:X.deployment.id,state:X.deployment.state||"QUEUED",url:X.deployment.url,errorMessage:null,logsUrl:null}):T(X.error||"Deployment failed")}).catch(()=>T("Failed to trigger deployment")).finally(()=>C(!1))},className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors underline",children:w?"Starting...":"Redeploy"})]}),k&&c("div",{className:`bg-[#2a2a2a] border rounded-md px-3 py-2 space-y-1.5 ${k.state==="ERROR"?"border-red-500/40":k.state==="READY"?"border-green-500/40":"border-[#D7FF63]/30"}`,children:[c("div",{className:"flex items-center gap-2",children:[k.state==="READY"?n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}):k.state==="ERROR"||k.state==="CANCELED"?n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-red-500 flex items-center justify-center",children:n("svg",{width:"8",height:"8",viewBox:"0 0 12 12",fill:"none",stroke:"white",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})}):n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-[#D7FF63]/30 flex items-center justify-center animate-pulse",children:n("span",{className:"w-2 h-2 rounded-full bg-[#D7FF63]"})}),n("span",{className:"text-[11px] text-white font-medium",children:k.state==="READY"?"Deployed successfully":k.state==="ERROR"?"Deployment failed":k.state==="CANCELED"?"Deployment canceled":k.state==="BUILDING"?"Building...":"Deploying..."})]}),k.state==="READY"&&k.url&&c("a",{href:k.url,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline transition-colors block",children:[k.url.replace("https://","")," →"]}),k.state==="ERROR"&&c("div",{className:"space-y-1",children:[k.errorMessage&&n("pre",{className:"text-[10px] text-red-300 bg-[#1a1a1a] rounded px-2 py-1.5 m-0 whitespace-pre-wrap font-mono overflow-x-auto max-h-24 overflow-y-auto",children:k.errorMessage}),c("div",{className:"flex items-center gap-2",children:[k.logsUrl&&n("a",{href:k.logsUrl,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline transition-colors",children:"View full logs →"}),n("button",{type:"button",onClick:()=>{j(null),T(null),C(!0),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"deploy"})}).then(X=>X.json()).then(X=>{X.ok&&X.deployment?j({id:X.deployment.id,state:X.deployment.state||"QUEUED",url:X.deployment.url,errorMessage:null,logsUrl:null}):T(X.error||"Deployment failed")}).catch(()=>T("Failed to trigger deployment")).finally(()=>C(!1))},className:"text-[10px] text-gray-400 hover:text-white bg-transparent border border-[#3d3d3d] rounded px-2 py-0.5 cursor-pointer transition-colors",children:"Retry"}),n("button",{type:"button",onClick:()=>H(`## Deployment Error
701
+ The deployment failed with this error:
702
+ \`\`\`
703
+ ${k.errorMessage||"Unknown error"}
704
+ \`\`\`
705
+ ${k.logsUrl?`Full logs: ${k.logsUrl}`:""}
706
+
707
+ Help the user understand what went wrong and how to fix it. Read their project config files (package.json, next.config.ts, prisma/schema.prisma) if needed to diagnose the issue.`),className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border border-[#D7FF63]/30 rounded px-2 py-0.5 cursor-pointer transition-colors",children:"Debug with AI"})]})]})]}),$.lastDeployment===null&&!k&&c("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-md px-3 py-2 space-y-1.5",children:[n("p",{className:"text-[11px] text-amber-400 m-0",children:"Not deployed yet"}),n("p",{className:"text-[10px] text-gray-500 m-0 leading-relaxed",children:"Your project is linked but hasn't been deployed. Push your code to GitHub to trigger an automatic deploy, or deploy now directly."}),n("button",{type:"button",disabled:w,onClick:()=>{T(null),C(!0),fetch("/api/editor-hosting-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"deploy"})}).then(X=>X.json()).then(X=>{X.ok&&X.deployment?j({id:X.deployment.id,state:X.deployment.state||"QUEUED",url:X.deployment.url,errorMessage:null,logsUrl:null}):T(X.error||"Deployment failed")}).catch(()=>T("Failed to trigger deployment")).finally(()=>C(!1))},className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:w?"Starting...":"Deploy now"})]})]}),B===2&&c("div",{className:"ml-7 space-y-2",children:[n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"A Vercel project is where your app lives once deployed. If you signed up with GitHub, Vercel can import the repo directly. Otherwise, create a new project and connect your repository."}),y?n("div",{children:n("span",{className:"text-[11px] text-gray-500",children:"Loading your Vercel projects..."})}):F&&p.length===0?n("div",{className:"space-y-2",children:A?c("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-md px-3 py-2.5 space-y-1.5",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"No Vercel projects found on your account."}),c("p",{className:"text-[10px] text-gray-500 m-0",children:["Create one linked to"," ",n("span",{className:"text-gray-300 font-mono",children:A}),"? Vercel will auto-deploy when you push."]}),n("button",{type:"button",onClick:O,disabled:v,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium mt-0.5",children:v?"Creating...":"Create Vercel project"})]}):c("div",{className:"space-y-1.5",children:[n("p",{className:"text-[11px] text-gray-400 m-0",children:"No Vercel projects found. Create one and import your repository:"}),n("a",{href:"https://vercel.com/new",target:"_blank",rel:"noopener noreferrer",className:"inline-block text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border border-[#D7FF63]/30 rounded px-2.5 py-1 no-underline transition-colors",children:"Create at vercel.com/new →"}),c("p",{className:"text-[10px] text-gray-600 m-0",children:["Then"," ",n("button",{type:"button",onClick:()=>{Y(!1),re.current=!1,P()},className:"text-[#D7FF63]/60 hover:text-[#D7FF63] bg-transparent border-none p-0 cursor-pointer text-[10px] underline",children:"re-check"})," ","to find it."]})]})}):p.length>0?c("div",{className:"space-y-2",children:[A&&!m&&c("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-md px-3 py-2.5 space-y-1.5",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"No existing project matches this repo."}),c("p",{className:"text-[10px] text-gray-500 m-0",children:["Create a new Vercel project linked to"," ",n("span",{className:"text-gray-300 font-mono",children:A}),"? Vercel will auto-deploy when you push."]}),n("button",{type:"button",onClick:O,disabled:v,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium mt-0.5",children:v?"Creating...":"Create Vercel project"})]}),p.length>0&&c("div",{className:"space-y-1.5",children:[n("p",{className:"text-[10px] text-gray-500 m-0",children:m?"Select the project for this app:":"Or select an existing project:"}),n("div",{className:"space-y-1",children:p.map(X=>c("button",{type:"button",onClick:()=>S(X.id,X.name),disabled:x,className:`w-full text-left rounded px-2.5 py-1.5 border transition-colors cursor-pointer flex items-center gap-2 ${X.id===m?"bg-[#2a2a2a] border-[#D7FF63]/40":"bg-[#2a2a2a] border-[#3d3d3d] hover:border-[#555]"}`,children:[n("span",{className:"text-xs text-white flex-1",children:X.name}),X.framework&&n("span",{className:"text-[10px] text-gray-500",children:X.framework}),X.id===m&&n("span",{className:"text-[9px] text-[#D7FF63] bg-[#D7FF63]/10 px-1 py-px rounded",children:"matches repo"})]},X.id))})]})]}):null]})]}),c("div",{className:"space-y-1.5",children:[c("div",{className:"flex items-center gap-2",children:[n(Lt,{step:3,done:z,active:B===3}),n("span",{className:`text-xs font-medium ${B>=3?"text-white":"text-gray-600"}`,children:"Environment Variables"}),B===3&&J>0&&c("span",{className:"text-[10px] text-gray-400 ml-auto",children:[q,"/",J," on Vercel"]})]}),B===3&&$.envVarsChecked&&n("div",{className:"ml-7 space-y-1.5",children:J===0?n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"Your app doesn't use any third-party services that need secrets yet. When you add services like a database or payment provider, their required keys will appear here."}):c(we,{children:[n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"These are the secrets your app needs to run in production. They must be added to your Vercel project so deployed builds can access them."}),n("div",{className:"space-y-1 mt-1",children:$.envVars.map(X=>c("div",{className:"flex items-center gap-2",children:[X.configuredOnVercel?n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}):n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-amber-500/30 flex items-center justify-center",children:n("span",{className:"w-2 h-2 rounded-full bg-amber-400"})}),n("span",{className:"text-xs text-gray-300 font-mono flex-1 truncate",children:X.key}),n("span",{className:"text-[10px] text-gray-500",children:X.service})]},X.key))}),q<J&&c("p",{className:"text-[10px] text-gray-500 m-0 mt-1.5 leading-relaxed",children:["Add missing variables in your"," ",n("a",{href:`https://vercel.com/~/project/${$.projectName||""}/settings/environment-variables`,target:"_blank",rel:"noopener noreferrer",className:"text-[#D7FF63]/60 hover:text-[#D7FF63] no-underline",children:"Vercel project settings"})," ","→ Environment Variables. Then"," ",n("button",{type:"button",onClick:W,className:"text-[#D7FF63]/60 hover:text-[#D7FF63] bg-transparent border-none p-0 cursor-pointer text-[10px] underline",children:"re-check"}),"."]})]})}),B===3&&!$.envVarsChecked&&c("div",{className:"ml-7 space-y-1",children:[n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"Check which secrets your app needs and whether they're configured on Vercel."}),n("button",{type:"button",onClick:W,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:"Check environment variables"})]})]}),L&&D?n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(L,{prompt:D,height:400,onClose:()=>{U(null),R(null),W()}})}):n("button",{type:"button",onClick:()=>H(),className:"text-[11px] text-gray-400 hover:text-white bg-transparent border border-[#3d3d3d] hover:border-[#555] rounded px-2.5 py-1.5 cursor-pointer transition-colors w-full mt-1",children:"I'm stuck — chat with AI"})]})}function jd({github:e,onSave:t,onShowChat:r}){const[s,a]=E(null),[o,i]=E(!0),[l,d]=E(""),[u,p]=E(!1),[h,m]=E(!1),[f,y]=E([]),[g,x]=E(!1),[b,v]=E(!1),[N,w]=E(!1),[C,k]=E(null),[j,A]=E(!1),[_,M]=E(null),T=le(()=>{i(!0),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"full-status"})}).then(I=>I.json()).then(I=>{a(I),M(null)}).catch(()=>M("Failed to check status")).finally(()=>i(!1))},[]);se(()=>{T()},[T]);const D=()=>{m(!0),M(null),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"init-git"})}).then(I=>I.json()).then(I=>{I.ok?T():M(I.error||"Failed to initialize git")}).catch(()=>M("Failed to initialize git")).finally(()=>m(!1))},R=()=>{l.trim()&&(p(!0),M(null),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"save-token",token:l.trim()})}).then(I=>I.json()).then(I=>{I.ok?(d(""),T()):M(I.error||"Token verification failed")}).catch(()=>M("Failed to save token")).finally(()=>p(!1)))},L=()=>{x(!0),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"list-repos"})}).then(I=>I.json()).then(I=>{I.ok&&(y(I.repos||[]),k(I.suggestedRepoName||null))}).catch(()=>{}).finally(()=>x(!1))},U=()=>{v(!0),M(null),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"create-repo"})}).then(I=>I.json()).then(I=>{I.ok?(t({owner:I.repo.owner,repo:I.repo.name,repoUrl:I.repo.url}),T()):M(I.error||"Failed to create repository")}).catch(()=>M("Failed to create repository")).finally(()=>v(!1))},W=I=>{w(!0),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"link-repo",repoUrl:I.cloneUrl,owner:I.fullName.split("/")[0],repo:I.name})}).then(K=>K.json()).then(K=>{K.ok&&(t({owner:I.fullName.split("/")[0],repo:I.name,repoUrl:I.url}),T())}).catch(()=>{}).finally(()=>w(!1))},V=()=>{A(!0),M(null),fetch("/api/editor-github-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"push"})}).then(I=>I.json()).then(I=>{I.ok?T():M(I.error||"Push failed")}).catch(()=>M("Push failed")).finally(()=>A(!1))},F=s||{gitInitialized:!1,hasGitignore:!1,hasRemote:!1,isGitHub:!1,ghCliInstalled:!1,ghCliAuthenticated:!1,hasToken:!1,tokenVerified:!1,user:null,githubRepo:null,hasCommits:!1,pushed:!1},Y=F.gitInitialized,P=F.ghCliAuthenticated||F.tokenVerified,O=F.hasRemote&&F.isGitHub,S=Y?P?3:2:1,$=be(!1);return se(()=>{S===3&&!O&&!$.current&&f.length===0&&!g&&($.current=!0,L())},[S,O]),o&&!s?n("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:n("span",{className:"text-xs text-gray-500",children:"Checking GitHub setup..."})}):c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333] space-y-3",children:[c("div",{children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-1.5",children:"GitHub Setup"}),n("p",{className:"text-[11px] text-gray-400 m-0 leading-relaxed",children:"GitHub stores your code and tracks changes. Push your code to a repository so it’s backed up, versioned, and ready for collaboration or deployment."})]}),_&&n("div",{className:"text-[11px] text-red-400 bg-red-400/10 rounded px-2 py-1.5",children:_}),c("div",{className:"space-y-1.5",children:[c("div",{className:"flex items-center gap-2",children:[n(Lt,{step:1,done:Y,active:S===1}),n("span",{className:"text-xs font-medium text-white",children:"Initialize Git"}),Y&&F.hasGitignore&&n("span",{className:"text-[10px] text-gray-400 ml-auto",children:"ready"})]}),S===1&&c("div",{className:"ml-7 space-y-2",children:[c("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:["Git tracks every change to your code so you can undo mistakes, see history, and collaborate. This initializes a local git repository and creates a ",n("code",{children:".gitignore"})," file to keep sensitive files out of version control."]}),n("button",{type:"button",onClick:D,disabled:h,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:h?"Initializing...":"Initialize Git"})]})]}),c("div",{className:"space-y-1.5",children:[c("div",{className:"flex items-center gap-2",children:[n(Lt,{step:2,done:P,active:S===2}),n("span",{className:`text-xs font-medium ${S>=2?"text-white":"text-gray-600"}`,children:"Connect to GitHub"}),P&&F.user&&n("span",{className:"text-[10px] text-gray-400 ml-auto",children:F.user.username})]}),S===2&&c("div",{className:"ml-7 space-y-2.5",children:[c("div",{className:"space-y-1",children:[c("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:["a) Install & authenticate with GitHub CLI",F.ghCliInstalled&&!F.ghCliAuthenticated&&n("span",{className:"text-[10px] text-green-400 ml-1.5",children:"(installed)"})]}),c("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:["The GitHub CLI (",n("code",{children:"gh"}),") is the easiest way to authenticate. Install it, then run ",n("code",{children:"gh auth login"})," in your terminal."]}),c("div",{className:"flex items-center gap-2",children:[!F.ghCliInstalled&&n("a",{href:"https://cli.github.com/",target:"_blank",rel:"noopener noreferrer",className:"inline-block text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border border-[#D7FF63]/30 rounded px-2.5 py-1 no-underline transition-colors",children:"Install GitHub CLI →"}),n("button",{type:"button",onClick:T,disabled:o,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:o?"Checking...":"Check Authentication"})]})]}),c("div",{className:"space-y-1",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"b) Or paste a Personal Access Token"}),c("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:["Create a token with ",n("strong",{children:"repo"})," scope. This is stored in .env.local (never committed)."]}),n("a",{href:"https://github.com/settings/tokens/new?scopes=repo&description=CodeYam",target:"_blank",rel:"noopener noreferrer",className:"inline-block text-[11px] text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline transition-colors",children:"Create token on GitHub →"}),F.hasToken&&!F.tokenVerified&&n("p",{className:"text-[11px] text-amber-400 m-0",children:"A token was found but it didn't work. Try creating a new one."}),c("div",{className:"flex items-center gap-1.5",children:[n("input",{type:"password",placeholder:"Paste your GitHub token",value:l,onChange:I=>d(I.target.value),onKeyDown:I=>{I.key==="Enter"&&R()},className:"bg-[#1a1a1a] border border-[#444] rounded px-2 py-1 text-xs text-white flex-1 outline-none focus:border-[#D7FF63]/50 font-mono"}),n("button",{type:"button",onClick:R,disabled:u||!l.trim(),className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:u?"Verifying...":"Connect"})]}),n("p",{className:"text-[10px] text-gray-600 m-0",children:"Stored in .env.local (gitignored — never committed)"})]})]})]}),c("div",{className:"space-y-1.5",children:[c("div",{className:"flex items-center gap-2",children:[n(Lt,{step:3,done:O,active:S===3}),n("span",{className:`text-xs font-medium ${S>=3?"text-white":"text-gray-600"}`,children:"Create or Link Repository"}),O&&F.githubRepo&&c("span",{className:"text-[10px] text-gray-400 ml-auto",children:[F.githubRepo.owner,"/",F.githubRepo.repo]})]}),S===3&&O&&F.githubRepo&&c("div",{className:"ml-7 space-y-2",children:[c("p",{className:"text-[11px] text-gray-400 m-0 leading-relaxed",children:["Connected to"," ",c("a",{href:`https://github.com/${F.githubRepo.owner}/${F.githubRepo.repo}`,target:"_blank",rel:"noopener noreferrer",className:"text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline",children:[F.githubRepo.owner,"/",F.githubRepo.repo]})]}),F.hasCommits&&!F.pushed&&c("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-md px-3 py-2.5 space-y-1.5",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"Push your code to GitHub"}),n("p",{className:"text-[10px] text-gray-500 m-0",children:"Your local commits haven't been pushed yet. Push now to back up your code and make it available on GitHub."}),n("button",{type:"button",onClick:V,disabled:j,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium mt-0.5",children:j?"Pushing...":"Push to GitHub"})]}),F.pushed&&n("p",{className:"text-[10px] text-green-400 m-0",children:"Code is pushed and up to date."})]}),S===3&&!O&&c("div",{className:"ml-7 space-y-2",children:[n("p",{className:"text-[11px] text-gray-500 m-0 leading-relaxed",children:"Create a new GitHub repository for this project or link to an existing one."}),c("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-md px-3 py-2.5 space-y-1.5",children:[n("p",{className:"text-[11px] text-gray-300 m-0 font-medium",children:"Create a new private repository"}),n("p",{className:"text-[10px] text-gray-500 m-0",children:"Creates a repository on GitHub and sets it as the remote for this project."}),n("button",{type:"button",onClick:U,disabled:b,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium mt-0.5",children:b?"Creating...":"Create repository"})]}),f.length===0&&g&&n("span",{className:"text-[11px] text-gray-500",children:"Loading your repositories..."}),f.length>0&&c("div",{className:"space-y-1.5",children:[n("p",{className:"text-[10px] text-gray-500 m-0",children:"Or link an existing repository:"}),n("div",{className:"space-y-1",children:f.map(I=>c("button",{type:"button",onClick:()=>W(I),disabled:N,className:`w-full text-left rounded px-2.5 py-1.5 border transition-colors cursor-pointer flex items-center gap-2 ${I.name===C?"bg-[#2a2a2a] border-[#D7FF63]/40":"bg-[#2a2a2a] border-[#3d3d3d] hover:border-[#555]"}`,children:[n("span",{className:"text-xs text-white flex-1",children:I.fullName}),I.private&&n("span",{className:"text-[10px] text-gray-500",children:"private"}),I.name===C&&n("span",{className:"text-[9px] text-[#D7FF63] bg-[#D7FF63]/10 px-1 py-px rounded",children:"matches project"})]},I.fullName))})]})]})]}),r&&n("button",{type:"button",onClick:r,className:"text-[11px] text-gray-400 hover:text-white bg-transparent border border-[#3d3d3d] hover:border-[#555] rounded px-2.5 py-1.5 cursor-pointer transition-colors w-full mt-1",children:"Need help? Ask Claude about GitHub setup"})]})}function _d({hosting:e,onSave:t,onEditNavigate:r,defaultEditing:s=!1,onShowChat:a}){const o=(e==null?void 0:e.provider)||null,[i,l]=E(s&&!o),d=u=>{t({provider:u}),l(!1)};if(o==="vercel")return n(c3,{hosting:e,onSave:t});if(!i&&o){const u=kd.find(p=>p.id===o);return c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-2",children:"Hosting"}),u?n("div",{className:"flex items-center gap-2 bg-[#2a2a2a] border border-[#D7FF63]/40 rounded-md px-3 py-2",children:c("div",{className:"flex-1",children:[n("div",{className:"text-sm font-medium text-white",children:u.name}),n("div",{className:"text-[11px] text-gray-400 mt-0.5",children:u.description})]})}):n("div",{className:"text-xs text-gray-400",children:o}),n("button",{type:"button",onClick:r??(()=>l(!0)),className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-2 cursor-pointer transition-colors font-medium",children:"Change >"})]})}return c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-2",children:"Choose a hosting provider"}),n("div",{className:"space-y-2",children:kd.map(u=>c("button",{type:"button",onClick:()=>d(u.id),className:`w-full text-left rounded-md px-3 py-2.5 border transition-colors cursor-pointer ${o===u.id?"bg-[#2a2a2a] border-[#D7FF63]/40":"bg-[#2a2a2a] border-[#3d3d3d] hover:border-[#555]"}`,children:[n("div",{className:"text-sm font-medium text-white",children:u.name}),n("div",{className:"text-[11px] text-gray-400 mt-0.5",children:u.description}),n("div",{className:"flex gap-1.5 mt-1.5",children:u.services.map(p=>n("span",{className:"text-[10px] text-gray-300 bg-[#333] px-1.5 py-0.5 rounded",children:p},p))})]},u.id))}),o&&n("button",{type:"button",onClick:()=>l(!1),className:"text-[11px] text-gray-400 hover:text-white bg-transparent border-none p-0 mt-2 cursor-pointer transition-colors",children:"Cancel"})]})}const Ed=[{id:"supabase",name:"Supabase",services:["PostgreSQL","Auth","Storage","Realtime"],description:"Open-source Firebase alternative"},{id:"neon",name:"Neon",services:["PostgreSQL"],description:"Serverless Postgres",disabled:!0},{id:"planetscale",name:"PlanetScale",services:["MySQL"],description:"Serverless MySQL",disabled:!0}];function d3({database:e,onSave:t}){const[r,s]=E(null),[a,o]=E(!0),[i,l]=E(""),[d,u]=E(!1),[p,h]=E([]),[m,f]=E(null),[y,g]=E(!1),[x,b]=E(!1),[v,N]=E(!1),[w,C]=E(""),[k,j]=E(!1),[A,_]=E(!1),[M,T]=E(null),[D,R]=E(null),L=le(()=>{o(!0),fetch("/api/editor-database-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"full-status"})}).then(S=>S.json()).then(S=>{s(S),R(null)}).catch(()=>R("Failed to check status")).finally(()=>o(!1))},[]);se(()=>{L()},[L]);const U=()=>{i.trim()&&(u(!0),R(null),fetch("/api/editor-database-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"save-token",token:i.trim()})}).then(S=>S.json()).then(S=>{S.ok?(l(""),L()):R(S.error||"Token verification failed")}).catch(()=>R("Failed to save token")).finally(()=>u(!1)))},W=le(()=>{g(!0),R(null),fetch("/api/editor-database-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"list-projects"})}).then(S=>S.json()).then(S=>{S.ok?(h(S.projects||[]),f(S.suggestedProjectId||null),b(!0)):R(S.error||"Failed to load projects")}).catch(()=>R("Failed to load projects")).finally(()=>g(!1))},[]);se(()=>{r!=null&&r.tokenVerified&&!(r!=null&&r.projectLinked)&&!x&&W()},[r==null?void 0:r.tokenVerified,r==null?void 0:r.projectLinked,x,W]);const V=S=>{const $=p.find(I=>I.id===S);N(!0),R(null),fetch("/api/editor-database-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"link-project",projectId:S,projectName:$==null?void 0:$.name})}).then(I=>I.json()).then(I=>{I.ok?L():R(I.error||"Failed to link project")}).catch(()=>R("Failed to link project")).finally(()=>N(!1))},F=()=>{w.trim()&&(j(!0),R(null),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({addEnvironmentVariable:{key:"DATABASE_URL",value:w.trim()}})}).then(S=>S.json()).then(S=>{S.success?(C(""),L()):R(S.error||"Failed to save DATABASE_URL")}).catch(()=>R("Failed to save DATABASE_URL")).finally(()=>j(!1)))},Y=()=>{_(!0),T(null),R(null),fetch("/api/editor-database-verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"verify-connection"})}).then(S=>S.json()).then(S=>{S.ok&&S.connected?T(!0):(T(!1),R(S.error||"Connection test failed"))}).catch(()=>{T(!1),R("Failed to test connection")}).finally(()=>_(!1))};if(a&&!r)return n("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:n("span",{className:"text-[11px] text-gray-500",children:"Checking Supabase status..."})});const P=r||{tokenVerified:!1,projectLinked:!1,projectName:null,projectRef:null,dashboardUrl:null,envVarsConfigured:!1,envVars:[],currentDbProvider:null,migrationNeeded:!1};let O=1;return P.tokenVerified&&P.projectLinked&&P.envVarsConfigured?O=(P.migrationNeeded,4):P.tokenVerified&&P.projectLinked?O=3:P.tokenVerified&&(O=2),c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333] space-y-3",children:[O===1&&!P.tokenVerified&&c("div",{className:"bg-[#1a1a1a] rounded-md px-3 py-2.5 border border-[#333]",children:[n("p",{className:"text-[11px] text-gray-300 m-0 leading-relaxed",children:"Supabase gives you a hosted PostgreSQL database with built-in auth, storage, and realtime. The free tier includes 2 projects with 500MB of database storage."}),c("p",{className:"text-[10px] text-gray-500 m-0 mt-1.5 leading-relaxed",children:["If you don't have an account yet, sign up at"," ",n("a",{href:"https://supabase.com/dashboard",target:"_blank",rel:"noopener noreferrer",className:"text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline",children:"supabase.com"})," ","(GitHub sign-in is fastest), then come back here to connect."]})]}),c("div",{className:"flex items-start gap-2",children:[n(Lt,{step:1,done:P.tokenVerified,active:O===1}),c("div",{className:"flex-1 min-w-0",children:[n("div",{className:"text-[11px] font-medium text-white",children:"Connect your Supabase account"}),P.tokenVerified?n("p",{className:"text-[10px] text-green-400 m-0 mt-0.5",children:"Connected"}):c("div",{className:"mt-1.5 space-y-1.5",children:[c("p",{className:"text-[10px] text-gray-500 m-0 leading-relaxed",children:["We need a"," ",n("span",{className:"text-gray-400",children:"personal access token"})," ","(not a project API key) to list your projects and fetch credentials automatically."]}),c("div",{className:"bg-[#1a1a1a] rounded px-2.5 py-2 border border-[#333] space-y-1",children:[c("p",{className:"text-[10px] text-gray-400 m-0",children:["1. Go to"," ",n("a",{href:"https://supabase.com/dashboard/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline",children:"Account → Access Tokens"})]}),c("p",{className:"text-[10px] text-gray-400 m-0",children:["2. Click"," ",n("span",{className:"text-gray-300",children:'"Generate new token"'}),', name it anything (e.g. "CodeYam")']}),c("p",{className:"text-[10px] text-gray-400 m-0",children:["3. Copy the token (starts with"," ",n("span",{className:"text-gray-300 font-mono",children:"sbp_"}),") and paste it below"]})]}),c("div",{className:"flex items-center gap-1.5",children:[n("input",{type:"password",placeholder:"sbp_...",value:i,onChange:S=>l(S.target.value),onKeyDown:S=>{S.key==="Enter"&&U()},className:"bg-[#1a1a1a] border border-[#444] rounded px-2 py-1 text-xs text-white flex-1 outline-none focus:border-[#D7FF63]/50 font-mono"}),n("button",{type:"button",disabled:d||!i.trim(),onClick:U,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:d?"Verifying...":"Connect"})]})]})]})]}),c("div",{className:"flex items-start gap-2",children:[n(Lt,{step:2,done:P.projectLinked,active:O===2}),c("div",{className:"flex-1 min-w-0",children:[n("div",{className:"text-[11px] font-medium text-white",children:"Select a Supabase project"}),P.projectLinked?n("div",{className:"mt-1",children:c("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-[11px] text-gray-300",children:P.projectName||P.projectRef}),P.dashboardUrl&&n("a",{href:P.dashboardUrl,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-[#D7FF63]/60 hover:text-[#D7FF63] no-underline",children:"dashboard →"})]})}):O>=2?c("div",{className:"mt-1.5 space-y-1.5",children:[n("p",{className:"text-[10px] text-gray-500 m-0 leading-relaxed",children:"Each Supabase project is an isolated PostgreSQL database. Select the project for this app, or create a new one first."}),y?n("span",{className:"text-[11px] text-gray-500",children:"Loading your Supabase projects..."}):p.length>0?c("div",{className:"space-y-1",children:[p.map(S=>n("button",{type:"button",disabled:v,onClick:()=>V(S.id),className:`w-full text-left rounded-md px-2.5 py-1.5 border transition-colors cursor-pointer ${S.id===m?"bg-[#2a2a2a] border-[#D7FF63]/40":"bg-[#2a2a2a] border-[#3d3d3d] hover:border-[#555]"}`,children:c("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs text-white font-medium",children:S.name}),n("span",{className:"text-[10px] text-gray-500",children:S.region}),S.id===m&&n("span",{className:"text-[10px] text-[#D7FF63] ml-auto",children:"suggested"})]})},S.id)),c("p",{className:"text-[10px] text-gray-600 m-0 mt-1",children:["Don't see the right project?"," ",n("a",{href:"https://supabase.com/dashboard/projects",target:"_blank",rel:"noopener noreferrer",className:"text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline",children:"Open your dashboard"})," ",`and click "New project" (you'll pick an organization first), then`," ",n("button",{type:"button",onClick:W,className:"text-[#D7FF63]/70 hover:text-[#D7FF63] bg-transparent border-none p-0 cursor-pointer transition-colors underline",children:"refresh this list"}),"."]})]}):x?c("div",{className:"space-y-1.5",children:[n("p",{className:"text-[10px] text-gray-500 m-0",children:"No projects found on your Supabase account."}),c("div",{className:"bg-[#1a1a1a] rounded px-2.5 py-2 border border-[#333] space-y-1",children:[c("p",{className:"text-[10px] text-gray-400 m-0",children:["1. Open your"," ",n("a",{href:"https://supabase.com/dashboard/projects",target:"_blank",rel:"noopener noreferrer",className:"text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline",children:"Supabase dashboard"})," ","and click"," ",n("span",{className:"text-gray-300",children:'"New project"'})]}),n("p",{className:"text-[10px] text-gray-400 m-0",children:"2. Select an organization (or create one — this is just a billing group for your projects)"}),c("p",{className:"text-[10px] text-gray-400 m-0",children:["3. Pick a name, set a"," ",n("span",{className:"text-gray-300",children:"database password"})," ","(save this — you'll need it for the connection string), and choose a region"]}),n("p",{className:"text-[10px] text-gray-400 m-0",children:"4. Wait for the project to finish provisioning (~2 min), then come back and refresh"})]}),n("button",{type:"button",onClick:W,className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors",children:"Refresh project list"})]}):null]}):n("p",{className:"text-[10px] text-gray-500 m-0 mt-0.5",children:"Connect your account first"})]})]}),c("div",{className:"flex items-start gap-2",children:[n(Lt,{step:3,done:P.envVarsConfigured,active:O===3}),c("div",{className:"flex-1 min-w-0",children:[n("div",{className:"text-[11px] font-medium text-white",children:"Configure database connection"}),P.envVarsConfigured?c("div",{className:"mt-1 space-y-1",children:[n("p",{className:"text-[10px] text-green-400 m-0",children:"All credentials configured"}),M===!0&&n("p",{className:"text-[10px] text-green-400 m-0",children:"Connection verified"}),M===!1&&n("p",{className:"text-[10px] text-red-300 m-0",children:"Connection test failed — check your credentials"}),n("button",{type:"button",disabled:A,onClick:Y,className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors underline",children:A?"Testing...":M===!0?"Test again":"Test connection"})]}):O>=3?c("div",{className:"mt-1.5 space-y-2",children:[n("p",{className:"text-[10px] text-gray-500 m-0 leading-relaxed",children:"Your Supabase URL and anon key were auto-filled when you linked the project. You still need to add the database connection string (which includes your database password)."}),n("div",{className:"space-y-1",children:P.envVars.map(S=>c("div",{className:"flex items-center gap-2",children:[S.configured?n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}):n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-amber-500/30 flex items-center justify-center",children:n("span",{className:"w-2 h-2 rounded-full bg-amber-400"})}),n("span",{className:"text-xs text-gray-300 font-mono truncate",children:S.key}),S.configured&&n("span",{className:"text-[10px] text-gray-500",children:"configured"})]},S.key))}),P.envVars.some(S=>S.key==="DATABASE_URL"&&!S.configured)&&c("div",{className:"space-y-1.5",children:[c("div",{className:"bg-[#1a1a1a] rounded px-2.5 py-2 border border-[#333] space-y-1",children:[c("p",{className:"text-[10px] text-gray-400 m-0",children:["1. Open"," ",P.projectRef?n("a",{href:`https://supabase.com/dashboard/project/${P.projectRef}/database/settings?showConnect=true`,target:"_blank",rel:"noopener noreferrer",className:"text-[#D7FF63]/70 hover:text-[#D7FF63] no-underline",children:"Database Settings → Connect"}):n("span",{className:"text-gray-300",children:"Database Settings → Connect"})]}),c("p",{className:"text-[10px] text-gray-400 m-0",children:["2. Select"," ",n("span",{className:"text-gray-300",children:'"Session pooler"'})," ","mode (port 5432) — this gives the best performance for CodeYam's scenario data seeding"]}),c("p",{className:"text-[10px] text-gray-400 m-0",children:["3. Copy the ",n("span",{className:"text-gray-300",children:"URI"})," ","connection string and replace"," ",n("span",{className:"text-gray-300 font-mono",children:"[YOUR-PASSWORD]"})," ","with the database password you set when creating the project"]})]}),c("p",{className:"text-[10px] text-gray-600 m-0",children:["Forgot your password? Reset it in"," ",P.projectRef?n("a",{href:`https://supabase.com/dashboard/project/${P.projectRef}/database/settings`,target:"_blank",rel:"noopener noreferrer",className:"text-gray-500 hover:text-gray-400 no-underline",children:"Database Settings"}):"Database Settings"," ",'under "Database password".']}),c("div",{className:"flex items-center gap-1.5",children:[n("input",{type:"password",placeholder:"postgresql://postgres.xxxxx:password@aws-0-region.pooler.supabase.com:5432/postgres",value:w,onChange:S=>C(S.target.value),onKeyDown:S=>{S.key==="Enter"&&F()},className:"bg-[#1a1a1a] border border-[#444] rounded px-2 py-1 text-xs text-white flex-1 outline-none focus:border-[#D7FF63]/50 font-mono"}),n("button",{type:"button",disabled:k||!w.trim(),onClick:F,className:"text-[11px] text-black bg-[#D7FF63] hover:bg-[#D7FF63]/80 disabled:opacity-40 rounded px-2.5 py-1 border-none cursor-pointer transition-colors font-medium",children:k?"Saving...":"Save"})]})]})]}):n("p",{className:"text-[10px] text-gray-500 m-0 mt-0.5",children:"Link a project first"})]})]}),c("div",{className:"flex items-start gap-2",children:[n(Lt,{step:4,done:!P.migrationNeeded,active:O===4&&P.migrationNeeded}),c("div",{className:"flex-1 min-w-0",children:[n("div",{className:"text-[11px] font-medium text-white",children:"Migrate to PostgreSQL"}),P.migrationNeeded?O===4?c("div",{className:"mt-1.5 space-y-1.5",children:[n("p",{className:"text-[10px] text-gray-500 m-0 leading-relaxed",children:"Your project currently uses SQLite for local development. To use your Supabase database, Claude needs to update several files:"}),c("div",{className:"bg-[#1a1a1a] rounded px-2.5 py-2 border border-[#333] space-y-0.5",children:[c("p",{className:"text-[10px] text-gray-400 m-0",children:[n("span",{className:"text-gray-300 font-mono",children:"prisma/schema.prisma"})," ","— switch provider from sqlite to postgresql"]}),c("p",{className:"text-[10px] text-gray-400 m-0",children:[n("span",{className:"text-gray-300 font-mono",children:"app/lib/prisma.ts"})," ","— swap the database adapter"]}),c("p",{className:"text-[10px] text-gray-400 m-0",children:[n("span",{className:"text-gray-300 font-mono",children:"package.json"})," ","— replace sqlite packages with pg + supabase-js"]}),c("p",{className:"text-[10px] text-gray-400 m-0",children:[n("span",{className:"text-gray-300 font-mono",children:".codeyam/seed-adapter.ts"})," ","— switch to Supabase seed adapter"]})]}),n("p",{className:"text-[10px] text-gray-500 m-0 leading-relaxed",children:"Your Prisma models and app code stay the same — only the database connection layer changes. After migration, use the Live Preview to verify everything loads correctly."}),c("div",{className:"bg-[#D7FF63]/5 border border-[#D7FF63]/20 rounded px-2.5 py-2",children:[c("p",{className:"text-[10px] text-[#D7FF63]/90 m-0 leading-relaxed",children:["Ask Claude in the chat:"," ",n("span",{className:"font-medium",children:'"Migrate my project from SQLite to Supabase"'})]}),n("p",{className:"text-[10px] text-[#D7FF63]/60 m-0 mt-0.5",children:"Claude will make the changes, run npm install, push the schema to Supabase, and help you verify it works."})]})]}):n("p",{className:"text-[10px] text-gray-500 m-0 mt-0.5",children:"Configure credentials first"}):n("p",{className:"text-[10px] text-green-400 m-0 mt-0.5",children:P.currentDbProvider==="postgresql"?"Already using PostgreSQL":"No migration needed"})]})]}),D&&n("div",{className:"bg-red-500/10 border border-red-500/30 rounded px-2.5 py-1.5",children:n("p",{className:"text-[10px] text-red-300 m-0",children:D})})]})}function Pd({database:e,onSave:t,onEditNavigate:r,defaultEditing:s=!1}){const a=(e==null?void 0:e.provider)||null,[o,i]=E(s&&!a),l=d=>{t({provider:d}),i(!1)};if(a==="supabase")return n(d3,{database:e,onSave:t});if(!o&&a){const d=Ed.find(u=>u.id===a);return c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-2",children:"Database"}),d?n("div",{className:"flex items-center gap-2 bg-[#2a2a2a] border border-[#D7FF63]/40 rounded-md px-3 py-2",children:c("div",{className:"flex-1",children:[n("div",{className:"text-sm font-medium text-white",children:d.name}),n("div",{className:"text-[11px] text-gray-400 mt-0.5",children:d.description})]})}):n("div",{className:"text-xs text-gray-400",children:a}),n("button",{type:"button",onClick:r??(()=>i(!0)),className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 mt-2 cursor-pointer transition-colors font-medium",children:"Change >"})]})}return c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[n("div",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider mb-2",children:"Choose a database provider"}),n("div",{className:"space-y-2",children:Ed.map(d=>c("button",{type:"button",disabled:d.disabled,onClick:()=>l(d.id),className:`w-full text-left rounded-md px-3 py-2.5 border transition-colors ${d.disabled?"bg-[#2a2a2a] border-[#333] opacity-40 cursor-not-allowed":"bg-[#2a2a2a] border-[#3d3d3d] hover:border-[#555] cursor-pointer"}`,children:[c("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white",children:d.name}),d.disabled&&n("span",{className:"text-[10px] text-gray-500",children:"coming soon"})]}),n("div",{className:"text-[11px] text-gray-400 mt-0.5",children:d.description}),n("div",{className:"flex gap-1.5 mt-1.5",children:d.services.map(u=>n("span",{className:"text-[10px] text-gray-300 bg-[#333] px-1.5 py-0.5 rounded",children:u},u))})]},d.id))}),a&&n("button",{type:"button",onClick:()=>i(!1),className:"text-[11px] text-gray-400 hover:text-white bg-transparent border-none p-0 mt-2 cursor-pointer transition-colors",children:"Cancel"})]})}function Ad({serviceName:e,serviceUrl:t,envKeys:r,environmentVariables:s,onSaveEnvVar:a,onEditNavigate:o,defaultEditing:i=!1}){const[l,d]=E(i),[u,p]=E({}),h=fe(()=>{const g=new Set;for(const x of s){const b=x.key||x.name;b&&x.value&&g.add(b)}return g},[s]),m=r.filter(g=>h.has(g)).length,f=m===r.length,y=g=>{const x=u[g];x!==void 0&&x!==""&&(a(g,x),p(b=>{const v={...b};return delete v[g],v}))};return c("div",{className:"mt-1 mb-2 bg-[#222] rounded-lg p-3 border border-[#333]",children:[c("div",{className:"flex items-center gap-2 mb-2",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Credentials"}),t&&n("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-[#D7FF63]/60 hover:text-[#D7FF63] no-underline",children:"docs →"})]}),n("div",{className:"space-y-1.5",children:r.map(g=>{const x=h.has(g),b=u[g]!==void 0;return c("div",{className:"flex items-center gap-2",children:[x?n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-green-600 flex items-center justify-center",children:n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})}):n("span",{className:"shrink-0 w-4 h-4 rounded-full bg-amber-500/30 flex items-center justify-center",children:n("span",{className:"w-2 h-2 rounded-full bg-amber-400"})}),n("span",{className:"text-xs text-gray-300 font-mono flex-1 truncate",children:g}),x&&!b?n("span",{className:"text-[10px] text-gray-500",children:"configured"}):l||b?c("div",{className:"flex items-center gap-1",children:[n("input",{type:"text",placeholder:"value",value:u[g]||"",onChange:v=>p(N=>({...N,[g]:v.target.value})),onKeyDown:v=>{v.key==="Enter"&&y(g)},className:"bg-[#1a1a1a] border border-[#444] rounded px-1.5 py-0.5 text-xs text-white w-32 outline-none focus:border-[#D7FF63]/50"}),n("button",{type:"button",onClick:()=>y(g),className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none cursor-pointer p-0 transition-colors",children:"Save"})]}):n("button",{type:"button",onClick:()=>p(v=>({...v,[g]:""})),className:"text-[10px] text-amber-400 hover:text-amber-300 bg-transparent border-none cursor-pointer p-0 transition-colors",children:"add"})]},g)})}),c("div",{className:"flex items-center justify-between mt-2",children:[n("span",{className:"text-[10px] text-gray-500",children:f?"All keys configured":`${m} of ${r.length} keys configured`}),!l&&!f&&n("button",{type:"button",onClick:o??(()=>d(!0)),className:"text-[10px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none cursor-pointer p-0 transition-colors",children:"Configure all >"})]})]})}function u3({onBack:e,onSwitchToBuild:t,onSwitchToHistory:r,onNavigateToDesignSystem:s,onNavigateToTechStack:a,expandedTasks:o,onExpandedTasksChange:i,buildIdle:l=!1,onScreenshotClick:d,onZoomChange:u}){const{revalidate:p}=Ut(),[h,m]=E(null),[f,y]=E(!1),[g,x]=E(null),b=le(()=>{fetch("/api/editor-roadmap").then(te=>te.json()).then(te=>m(te)).catch(()=>{})},[]);se(()=>{b()},[b]);const v=(h==null?void 0:h.plan.some(te=>te.id==="plan-design-system"&&te.completed))??!1;se(()=>{if(!v){x(null);return}fetch("/api/editor-design-system").then(te=>te.json()).then(te=>{te.exists&&te.content?x(ei(te.content)):x(null)}).catch(()=>x(null))},[v]);const N=le(te=>{y(!0),fetch("/api/editor-roadmap",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(te)}).then(ke=>ke.json()).then(()=>b()).catch(()=>{}).finally(()=>y(!1))},[b]),w=le((te,ke)=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectTitle:te,projectDescription:ke})}).then(()=>b()).catch(()=>{})},[b]),C=le((te,ke)=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenSizes:te,projectScreenSizes:ke})}).then(()=>{b(),p()}).catch(()=>{})},[b,p]),k=le(te=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hosting:te})}).then(()=>b()).catch(()=>{})},[b]),j=le(te=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({database:te})}).then(()=>b()).catch(()=>{})},[b]),A=le(te=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({github:te})}).then(()=>b()).catch(()=>{})},[b]),_=le((te,ke)=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({addEnvironmentVariable:{key:te,value:ke}})}).then(()=>b()).catch(()=>{})},[b]),M=le((te,ke)=>{if(!h)return;const Z=h[te].filter(pe=>pe.id!==ke);m({...h,[te]:Z}),N({[te]:Z})},[h,N]),[T,D]=E(null),[R,L]=E(()=>new Set),[U,W]=E(()=>new Set),[V,F]=E(()=>new Set),Y=le(te=>{F(ke=>{const Z=new Set(ke);return Z.has(te)?Z.delete(te):Z.add(te),Z})},[]),[P,O]=E(()=>new Set),[S,$]=E(!1),[I,K]=E(null),q=be(null),J=be(null),z=be(0),B=le(te=>{L(ke=>{const Z=new Set(ke);return Z.has(te)?Z.delete(te):Z.add(te),Z})},[]),H=le(te=>{O(ke=>{const Z=new Set(ke);return Z.has(te)?Z.delete(te):Z.add(te),Z})},[]);se(()=>{if(!S||typeof document>"u")return;const te=ke=>{q.current&&!q.current.contains(ke.target)&&($(!1),K(null))};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[S]);const re=[{key:"plan",label:"Setup"},{key:"build",label:"Build"},{key:"deploy",label:"Deploy"},{key:"gtm",label:"Go To Market"}],ae=le(te=>{const ke=new Set(o);ke.has(te)?ke.delete(te):ke.add(te),i(ke)},[o,i]),X=le(te=>{J.current&&(z.current=J.current.scrollTop),D(te)},[]),oe=le(()=>{D(null),requestAnimationFrame(()=>{J.current&&(J.current.scrollTop=z.current)})},[]);if(!h)return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:n("span",{className:"text-sm text-gray-500",children:"Loading roadmap..."})});const me=h.plan.filter(te=>te.completed).length,ve=h.deploy.filter(te=>te.completed).length,je=T&&([...h.plan,...h.deploy].find(te=>te.id===T)??null);if(je){const te=je.id==="plan-project-name"&&je.completed?n(Nd,{projectTitle:h.projectTitle,projectDescription:h.projectDescription,onSave:w,defaultEditing:!0}):je.id==="plan-screen-sizes"&&je.completed?n(Cd,{screenSizes:h.screenSizes,projectScreenSizes:h.projectScreenSizes,defaultScreenSize:h.defaultScreenSize,appFormats:h.appFormats,onSave:C,defaultEditing:!0}):je.id==="plan-github"?n(jd,{github:h.github,onSave:A}):je.id==="deploy-hosting"?n(_d,{hosting:h.hosting,onSave:k,defaultEditing:!0}):je.id==="deploy-database"?n(Pd,{database:h.database,onSave:j,defaultEditing:!0}):je.serviceRef&&h.techStack?(()=>{var pe;const ke=h.techStack[je.serviceRef.category],Z=ke==null?void 0:ke.find(ie=>ie.name===je.serviceRef.name);return(pe=Z==null?void 0:Z.envKeys)!=null&&pe.length?n(Ad,{serviceName:Z.name,serviceUrl:Z.url,envKeys:Z.envKeys,environmentVariables:h.environmentVariables,onSaveEnvVar:_,defaultEditing:!0}):null})():null;return n("div",{className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:c("div",{className:"p-4 space-y-4",children:[c("button",{type:"button",onClick:oe,className:"flex items-center gap-1.5 text-xs text-gray-500 hover:text-white bg-transparent border-none p-0 cursor-pointer transition-colors",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M15 18l-6-6 6-6"})}),"Back to Roadmap"]}),c("div",{className:"flex items-center gap-2.5",children:[n("h2",{className:"text-lg font-medium text-white mt-0 mb-0",children:je.label}),je.completed&&n("span",{className:"shrink-0 w-4 h-4 rounded-full border border-green-500 flex items-center justify-center",children:n("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"#22c55e",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})})]}),te?n("div",{children:te}):n("p",{className:"text-sm text-gray-500",children:je.completed?"This task has been completed.":"This task has not been started yet."}),f&&n("span",{className:"text-[10px] text-gray-600",children:"Saving..."})]})})}return n("div",{ref:J,className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:c("div",{className:"p-4 space-y-5",children:[n("div",{className:"flex items-center px-0 -mx-4 bg-[#161616] border-b border-[#2d2d2d]",style:{marginTop:"-1rem",paddingLeft:"1rem",paddingRight:"1rem",paddingTop:"0.5rem",paddingBottom:"0.5rem"},children:c("button",{type:"button",onClick:e,className:"flex items-center gap-1.5 text-xs text-gray-500 hover:text-white bg-transparent border-none p-0 cursor-pointer transition-colors",children:[n("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M15 18l-6-6 6-6"})}),"Home"]})}),c("div",{className:"flex items-center gap-3 mt-2",children:[n("h2",{className:"text-xl font-medium text-white m-0",children:"Roadmap"}),n("div",{className:"flex-1"}),c("div",{className:"relative",ref:q,children:[n("button",{type:"button",onClick:()=>{$(!S),K(null)},className:"p-1 text-gray-500 hover:text-white bg-transparent border-none cursor-pointer transition-colors",title:"Options",children:c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:[n("circle",{cx:"12",cy:"5",r:"2"}),n("circle",{cx:"12",cy:"12",r:"2"}),n("circle",{cx:"12",cy:"19",r:"2"})]})}),S&&c("div",{className:"absolute right-0 top-full mt-1 z-50 flex items-start gap-0",children:[I&&n("div",{className:"bg-[#2d2d2d] border border-[#3d3d3d] rounded-lg shadow-lg py-1 min-w-[150px]",children:(I==="hide"?re.filter(te=>!P.has(te.key)):re.filter(te=>P.has(te.key))).map(te=>n("button",{type:"button",onClick:()=>{H(te.key),$(!1),K(null)},className:"w-full text-left px-4 py-2 text-sm text-gray-300 hover:text-white hover:bg-[#3d3d3d] bg-transparent border-none cursor-pointer transition-colors",children:te.label},te.key))}),c("div",{className:"bg-[#2d2d2d] border border-[#3d3d3d] rounded-lg shadow-lg py-1 min-w-[130px]",children:[re.some(te=>!P.has(te.key))&&c("button",{type:"button",onMouseEnter:()=>K("hide"),className:"w-full flex items-center justify-between px-4 py-2 text-sm text-gray-300 hover:text-white hover:bg-[#3d3d3d] bg-transparent border-none cursor-pointer transition-colors",children:["Hide",n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-500",children:n("path",{d:"M3 1l4 4-4 4"})})]}),P.size>0&&c("button",{type:"button",onMouseEnter:()=>K("show"),className:"w-full flex items-center justify-between px-4 py-2 text-sm text-gray-300 hover:text-white hover:bg-[#3d3d3d] bg-transparent border-none cursor-pointer transition-colors",children:["Show",n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"text-gray-500",children:n("path",{d:"M3 1l4 4-4 4"})})]})]})]})]})]}),!P.has("plan")&&c("div",{className:"border border-[#2D2D2D] rounded-lg pb-1 bg-[#171717]",children:[n(Ls,{title:"Setup",completedCount:me,totalCount:h.plan.length,collapsed:R.has("plan"),onToggleCollapse:()=>B("plan")}),!R.has("plan")&&h.plan.map(te=>c(wd,{todo:te,expanded:o.has(te.id),onToggle:()=>ae(te.id),onRemove:te.userCreated?()=>M("plan",te.id):void 0,children:[te.id==="plan-project-name"&&te.completed&&n(Nd,{projectTitle:h.projectTitle,projectDescription:h.projectDescription,onSave:w,onEditNavigate:()=>X(te.id)}),te.id==="plan-tech-stack"&&n(i3,{techStack:h.techStack,onNavigate:a}),te.id==="plan-design-system"&&te.completed&&g&&n(o3,{designSystem:g,onEdit:s}),te.id==="plan-screen-sizes"&&te.completed&&n(Cd,{screenSizes:h.screenSizes,projectScreenSizes:h.projectScreenSizes,defaultScreenSize:h.defaultScreenSize,appFormats:h.appFormats,onSave:C,onEditNavigate:()=>X(te.id)}),te.id==="plan-github"&&n(jd,{github:h.github,onSave:A})]},te.id))]}),!P.has("build")&&c("div",{className:"border border-[#2D2D2D] rounded-lg pb-1 bg-[#171717]",children:[n(Ls,{title:"Build",subtitle:h.editorStep!=null&&h.editorStep<18?"Building...":void 0,subtitleAccent:h.editorStep!=null&&h.editorStep<18,collapsed:R.has("build"),onToggleCollapse:()=>B("build"),subtitleLink:h.editorStep==null||h.editorStep>=18?{label:"Start New Feature",onClick:t}:void 0}),!R.has("build")&&c(we,{children:[h.editorStep!=null&&h.editorStep>=18?n("div",{className:"mx-3 mb-2",children:c("button",{type:"button",onClick:t,className:"w-full flex items-center gap-2 py-3 px-4 bg-[#2a2a2a] rounded-lg border-none cursor-pointer text-left group hover:bg-[#303030] transition-colors",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0 text-gray-500",children:n("path",{d:"M3 1l4 4-4 4"})}),n("span",{className:"text-sm text-white group-hover:text-white transition-colors truncate flex-1 font-medium",children:h.featureName||"New Feature"}),n("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded uppercase tracking-wider shrink-0 font-['IBM_Plex_Mono'] bg-[#5ce0d2]/20 text-[#5ce0d2]",children:"New"}),n("span",{className:"text-[10px] text-gray-500 shrink-0 uppercase font-['IBM_Plex_Mono']",children:"Just now"}),n("span",{className:"shrink-0 w-4 h-4 rounded-full border border-green-500 flex items-center justify-center",children:n("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"#22c55e",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})})]})}):h.editorStep!=null?n("div",{className:"mx-3 mb-2",children:c("button",{type:"button",onClick:t,className:"w-full flex flex-col gap-2 py-3 px-4 bg-[#1a3a3a] border border-[#2a5a5a] rounded-lg cursor-pointer text-left hover:bg-[#1e4242] transition-colors",children:[c("div",{className:"flex items-center gap-3 w-full",children:[l?n("span",{className:"w-3 h-3 rounded-full bg-[#FF8B43] shrink-0"}):n(la,{color:"#5ce0d2",dotSize:3}),n("span",{className:"text-sm text-white font-medium",children:h.featureName||"New Feature"}),l&&n("span",{className:"text-xs text-[#FF8B43] underline cursor-pointer hover:text-[#FF8B43]/70",onClick:te=>{te.stopPropagation(),t()},children:"Go to build"}),n("span",{className:"flex-1"}),h.editorStep!=null&&h.editorStepLabel&&c("span",{className:"text-xs font-['IBM_Plex_Mono'] text-[#5ce0d2] tracking-wider shrink-0",children:[h.editorStepLabel.toUpperCase()," (",h.editorStep,"/18)"]})]}),h.editorStep!=null&&n("div",{className:"flex items-center gap-2 w-full",children:n("div",{className:"flex-1 h-[6px] bg-[#0d2626] rounded-full overflow-hidden",children:n("div",{className:"h-full bg-gradient-to-r from-[#5ce0d2] to-[#5ce0d2] rounded-full transition-all",style:{width:`${h.editorStep/18*100}%`}})})})]})}):null,h.recentEntries.map(te=>{const ke=U.has(te.time);return c("div",{className:"mx-3 mb-2",children:[c("div",{className:"flex items-center gap-2 py-3 px-4 bg-[#2a2a2a] rounded-lg cursor-pointer hover:bg-[#303030] transition-colors",onClick:()=>{W(Z=>{const pe=new Set(Z);return pe.has(te.time)?pe.delete(te.time):pe.add(te.time),pe})},children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-gray-500 transition-transform ${ke?"rotate-90":""}`,children:n("path",{d:"M3 1l4 4-4 4"})}),n("span",{className:"text-sm text-gray-300 truncate flex-1",children:te.title}),n("span",{className:`${e3[te.type]||t3} text-[10px] font-bold px-2.5 py-0.5 rounded-full border uppercase tracking-wider shrink-0 font-['IBM_Plex_Mono']`,children:te.type}),n("span",{className:"text-[10px] text-gray-500 shrink-0 uppercase font-['IBM_Plex_Mono']",children:a3(te.time)}),n("span",{className:"shrink-0 w-4 h-4 rounded-full border border-green-500 flex items-center justify-center",children:n("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"#22c55e",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M20 6L9 17l-5-5"})})})]}),ke&&n("div",{className:"mt-1 bg-[#222] rounded-lg",children:n(s3,{entry:te,expandedSections:V,onToggleSection:Y,onScreenshotClick:d,onZoomChange:u})})]},te.time)}),!h.featureName&&h.buildSessionCount===0&&n("div",{className:"mx-3 mb-2 py-3 px-4 bg-[#2a2a2a] rounded-lg",children:n("p",{className:"text-xs text-gray-500 m-0",children:"No sessions yet."})}),c("div",{className:"mx-3 mb-2 flex items-center gap-2 px-4 py-2.5 bg-[#2a2a2a] rounded-lg",children:[n("input",{type:"text",placeholder:"Plan next feature",className:"flex-1 text-sm bg-transparent border-none text-gray-300 placeholder-gray-600 outline-none",onKeyDown:te=>{te.key==="Enter"&&te.currentTarget.value.trim()&&t()}}),n("button",{type:"button",onClick:t,className:"text-[10px] font-bold text-black bg-[#D7FF63] hover:bg-[#c5ee52] px-2.5 py-1 rounded cursor-pointer transition-colors font-['IBM_Plex_Mono'] tracking-wider",children:"ADD"})]})]})]}),!P.has("deploy")&&c("div",{className:"border border-[#2D2D2D] rounded-lg pb-1 bg-[#171717]",children:[n(Ls,{title:"Deploy",completedCount:ve,totalCount:h.deploy.length>0?h.deploy.length:void 0,collapsed:R.has("deploy"),onToggleCollapse:()=>B("deploy")}),!R.has("deploy")&&(h.deploy.length>0?h.deploy.map(te=>n(wd,{todo:te,expanded:o.has(te.id),onToggle:()=>ae(te.id),onRemove:te.userCreated?()=>M("deploy",te.id):void 0,children:te.id==="deploy-hosting"?n(_d,{hosting:h.hosting,onSave:k,onEditNavigate:()=>X(te.id)}):te.id==="deploy-database"?n(Pd,{database:h.database,onSave:j,onEditNavigate:()=>X(te.id)}):te.serviceRef&&h.techStack?(()=>{var pe;const ke=h.techStack[te.serviceRef.category],Z=ke==null?void 0:ke.find(ie=>ie.name===te.serviceRef.name);return(pe=Z==null?void 0:Z.envKeys)!=null&&pe.length?n(Ad,{serviceName:Z.name,serviceUrl:Z.url,envKeys:Z.envKeys,environmentVariables:h.environmentVariables,onSaveEnvVar:_,onEditNavigate:()=>X(te.id)}):n("p",{className:"text-xs text-gray-500 m-0 mt-1 mb-2",children:te.completed?"Completed":"Not started yet"})})():n("p",{className:"text-xs text-gray-500 m-0 mt-1 mb-2",children:te.completed?"Completed":"Not started yet"})},te.id)):n("div",{className:"mx-3 mb-2 py-3 px-4 bg-[#2a2a2a] rounded-lg",children:n("span",{className:"text-sm text-gray-500",children:"-"})}))]}),!P.has("gtm")&&c("div",{className:"border border-[#2D2D2D] rounded-lg pb-1 bg-[#171717]",children:[n(Ls,{title:"Go To Market",collapsed:R.has("gtm"),onToggleCollapse:()=>B("gtm")}),!R.has("gtm")&&n(we,{children:["Blog Post","Demo","One Liner"].map(te=>n("div",{className:"mx-3 mb-2",children:c("div",{className:"flex items-center gap-2 py-3 px-4 bg-[#2a2a2a] rounded-lg",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0 text-gray-500",children:n("path",{d:"M3 1l4 4-4 4"})}),n("span",{className:"text-sm text-gray-500 flex-1",children:te})]})},te))})]}),f&&n("span",{className:"text-[10px] text-gray-600",children:"Saving..."})]})})}function p3({color:e,onColorChange:t}){const r=be(null),s=h3(e.value),a=e.value.startsWith("#");return c("div",{className:"flex flex-col gap-1",children:[n("button",{type:"button",className:"w-full h-10 rounded-md border border-[#444] cursor-pointer relative group",style:{backgroundColor:e.value},onClick:()=>{var o;return a&&((o=r.current)==null?void 0:o.click())},title:`--${e.name}: ${e.value}${e.comment?` (${e.comment})`:""}`,children:a&&n("div",{className:"absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/30 rounded-md",children:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})}),a&&n("input",{ref:r,type:"color",value:s,onChange:o=>t(e.name,o.target.value),className:"sr-only"}),c("div",{className:"text-[9px] font-mono text-gray-500 truncate",title:`--${e.name}`,children:["--",e.name]}),n("div",{className:"text-[9px] font-mono text-gray-600 truncate",children:e.value})]})}function h3(e){if(!e.startsWith("#"))return"#000000";const t=e.slice(1);return t.length===3?`#${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`:t.length===6||t.length===8?`#${t.slice(0,6)}`:"#000000"}function m3({group:e,colors:t,onColorChange:r}){const[s,a]=E(!1);return c("div",{className:"mb-4",children:[c("button",{type:"button",onClick:()=>a(!s),className:"flex items-center gap-1.5 text-[10px] font-semibold text-gray-400 uppercase tracking-wider mb-2 bg-transparent border-none p-0 cursor-pointer hover:text-gray-300 transition-colors",children:[n("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",className:`transition-transform ${s?"":"rotate-90"}`,children:n("path",{d:"M9 18l6-6-6-6"})}),e,c("span",{className:"text-gray-600 font-normal",children:["(",t.length,")"]})]}),!s&&n("div",{className:"grid grid-cols-5 gap-2",children:t.map(o=>n(p3,{color:o,onColorChange:r},`${o.group}-${o.name}`))})]})}function f3({designSystem:e,rawMarkdown:t,onSave:r}){const s=e.colors.reduce((d,u)=>(d[u.group]||(d[u.group]=[]),d[u.group].push(u),d),{}),a=le((d,u)=>{const p=q5(t,d,u);r(p)},[t,r]),[o,i]=E(e.fonts.length>0?e.fonts.join(", "):""),l=le(()=>{if(!o.trim())return;const d=Q5(t,`'${o.trim()}', sans-serif`);r(d)},[t,o,r]);return c("div",{className:"space-y-6",children:[Object.keys(s).length>0&&c("div",{children:[n("h4",{className:"text-xs font-medium text-white mb-3",children:"Colors"}),Object.entries(s).map(([d,u])=>n(m3,{group:d,colors:u,onColorChange:a},d))]}),e.fonts.length>0&&c("div",{children:[n("h4",{className:"text-xs font-medium text-white mb-3",children:"Typography"}),c("div",{className:"flex items-center gap-2 mb-3",children:[n("label",{className:"text-[10px] text-gray-500 uppercase tracking-wider shrink-0",children:"Font"}),n("input",{type:"text",value:o,onChange:d=>i(d.target.value),onBlur:l,onKeyDown:d=>d.key==="Enter"&&l(),className:"flex-1 px-2 py-1 text-xs bg-[#222] border border-[#3d3d3d] rounded text-gray-300 outline-none focus:border-[#D7FF63]/50"})]}),e.typographyScale.length>0&&n("div",{className:"bg-[#222] rounded border border-[#333] overflow-hidden",children:c("table",{className:"w-full",children:[n("thead",{children:c("tr",{className:"border-b border-[#333]",children:[n("th",{className:"text-left px-3 py-1.5 text-[9px] font-semibold text-gray-500 uppercase tracking-wider",children:"Style"}),n("th",{className:"text-left px-3 py-1.5 text-[9px] font-semibold text-gray-500 uppercase tracking-wider",children:"Size"}),n("th",{className:"text-left px-3 py-1.5 text-[9px] font-semibold text-gray-500 uppercase tracking-wider",children:"Weight"})]})}),n("tbody",{children:e.typographyScale.map(d=>c("tr",{className:"border-b border-[#333] last:border-b-0",children:[n("td",{className:"px-3 py-1.5 text-xs text-gray-300",children:d.style}),n("td",{className:"px-3 py-1.5 text-xs font-mono text-gray-400",children:d.size}),n("td",{className:"px-3 py-1.5 text-xs font-mono text-gray-400",children:d.weight})]},d.style))})]})})]}),e.radiusTokens.length>0&&c("div",{children:[n("h4",{className:"text-xs font-medium text-white mb-3",children:"Border Radius"}),n("div",{className:"flex gap-3 flex-wrap",children:e.radiusTokens.map(d=>c("div",{className:"flex flex-col items-center gap-1",children:[n("div",{className:"w-10 h-10 bg-[#D7FF63]/20 border border-[#D7FF63]/40",style:{borderRadius:d.value}}),c("div",{className:"text-[9px] font-mono text-gray-500",children:["--",d.name]}),n("div",{className:"text-[9px] font-mono text-gray-600",children:d.value})]},d.name))})]})]})}function g3({content:e,onSave:t}){const[r,s]=E(e),[a,o]=E(!1);se(()=>{s(e),o(!1)},[e]);const i=le(()=>{t(r),o(!1)},[r,t]);return c("div",{className:"flex flex-col gap-2 h-full",children:[n("textarea",{value:r,onChange:l=>{s(l.target.value),o(!0)},className:"flex-1 min-h-[400px] p-3 text-xs font-mono bg-[#1a1a1a] border border-[#3d3d3d] rounded-lg text-gray-300 outline-none focus:border-[#D7FF63]/50 resize-none leading-relaxed",spellCheck:!1}),c("div",{className:"flex items-center gap-2",children:[n("button",{type:"button",onClick:i,disabled:!a,className:`px-4 py-1.5 text-xs rounded-md font-medium transition-colors cursor-pointer ${a?"text-[#1e1e1e] bg-[#D7FF63] hover:bg-[#D7FF63]/80":"text-gray-500 bg-[#333] cursor-not-allowed"}`,children:"Save"}),a&&n("span",{className:"text-[10px] text-gray-500",children:"Unsaved changes"})]})]})}function y3({onClose:e}){return n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(Zt,{prompt:`# Edit Design System
708
+
709
+ You are helping the user edit their design system file at \`.codeyam/design-system.md\`.
710
+
711
+ Read the current design system file first, then ask the user what they'd like to change. Common changes include:
712
+ - Changing colors (background, text, accent colors)
713
+ - Switching fonts or typography scale
714
+ - Adjusting spacing, radius, or shadow values
715
+ - Adding or removing theme modes (light/dark)
716
+ - Changing the overall aesthetic (minimal, bold, editorial, etc.)
717
+
718
+ After making changes, briefly summarize what was updated.`,height:500,onClose:e})})}function x3({onBack:e,onPreviewShowcase:t}){const[r,s]=E("visual"),[a,o]=E(null),[i,l]=E(null),[d,u]=E(!1),[p,h]=E(!1),m=le(()=>{fetch("/api/editor-design-system").then(g=>g.json()).then(g=>{g.exists&&g.content&&(o(g.content),l(ei(g.content)))}).catch(()=>{})},[]);se(()=>{m()},[m]),se(()=>{if(r!=="claude"||!p)return;const g=setInterval(m,3e3);return()=>clearInterval(g)},[r,p,m]);const f=le(g=>{u(!0),o(g),l(ei(g)),fetch("/api/editor-design-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:g})}).then(()=>{t()}).catch(()=>{}).finally(()=>u(!1))},[t]);if(!a||!i)return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:n("span",{className:"text-sm text-gray-500",children:"Loading design system..."})});const y=[{id:"visual",label:"Visual"},{id:"markdown",label:"Markdown"},{id:"claude",label:"Claude"}];return n("div",{className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:c("div",{className:"p-4 space-y-4",children:[c("button",{type:"button",onClick:e,className:"flex items-center gap-1.5 text-xs text-gray-500 hover:text-white bg-transparent border-none p-0 cursor-pointer transition-colors",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M15 18l-6-6 6-6"})}),"Back to Roadmap"]}),c("div",{className:"flex items-center justify-between",children:[c("div",{children:[n("h2",{className:"text-lg font-medium text-white m-0",children:i.name}),i.description&&n("p",{className:"text-xs text-gray-500 m-0 mt-1 max-w-md",children:i.description})]}),c("button",{type:"button",onClick:t,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium",children:[c("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),n("circle",{cx:"12",cy:"12",r:"3"})]}),"Preview Components"]})]}),n("div",{className:"flex gap-1 bg-[#222] rounded-lg p-0.5 w-fit border border-[#333]",children:y.map(g=>n("button",{type:"button",onClick:()=>{s(g.id),g.id==="claude"&&h(!0)},className:`px-3 py-1 text-xs rounded-md transition-colors cursor-pointer border-none ${r===g.id?"bg-[#3a3a3a] text-white font-medium":"bg-transparent text-gray-500 hover:text-gray-300"}`,children:g.label},g.id))}),c("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-4",children:[r==="visual"&&n(f3,{designSystem:i,rawMarkdown:a,onSave:f}),r==="markdown"&&n(g3,{content:a,onSave:f}),r==="claude"&&p&&n(y3,{onClose:()=>{h(!1),m()}}),r==="claude"&&!p&&c("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[n("p",{className:"text-xs text-gray-500",children:"Use Claude to make design system changes with natural language."}),n("button",{type:"button",onClick:()=>h(!0),className:"px-4 py-2 text-xs text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium",children:"Start Claude Chat"})]})]}),d&&n("span",{className:"text-[10px] text-gray-600",children:"Saving..."})]})})}const Bs=[{key:"languages",label:"Languages"},{key:"frameworks",label:"Frameworks"},{key:"databases",label:"Databases"},{key:"services",label:"External Services"},{key:"libraries",label:"Key Libraries"},{key:"infrastructure",label:"Infrastructure"}];function b3({onBack:e}){const[t,r]=E(null),[s,a]=E(!1),[o,i]=E(!1),[l,d]=E({}),[u,p]=E(!1),h=typeof window<"u"?window.location.origin:"",m=le(()=>{fetch("/api/editor-project-info").then(k=>k.json()).then(k=>{r(k.techStack||null),a(!0)}).catch(()=>a(!0))},[]);se(()=>{m()},[m]);const f=le(k=>{fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({techStack:k})}).then(()=>m()).catch(()=>{})},[m]),y=()=>{d(t?JSON.parse(JSON.stringify(t)):{}),i(!0)},g=()=>{const k={};for(const{key:j}of Bs){const A=l[j];A&&A.length>0&&(k[j]=A.filter(_=>_.name.trim()!==""))}f(k),i(!1)},x=k=>{d(j=>({...j,[k]:[...j[k]||[],{name:"",url:"",description:""}]}))},b=(k,j)=>{d(A=>({...A,[k]:(A[k]||[]).filter((_,M)=>M!==j)}))},v=(k,j,A,_)=>{d(M=>({...M,[k]:(M[k]||[]).map((T,D)=>D===j?{...T,[A]:_}:T)}))},N=(k,j,A)=>{const _=A.split(",").map(M=>M.trim()).filter(Boolean);d(M=>({...M,[k]:(M[k]||[]).map((T,D)=>D===j?{...T,envKeys:_}:T)}))},w=fe(()=>`# Detect and Set Up Tech Stack
719
+
720
+ You are helping the user configure their project's tech stack in CodeYam.
721
+
722
+ ## Instructions
723
+
724
+ 1. Read \`package.json\` to find all dependencies and devDependencies
725
+ 2. Check for framework config files: \`next.config.js\`, \`next.config.ts\`, \`tailwind.config.js\`, \`prisma/schema.prisma\`, \`tsconfig.json\`, \`vite.config.ts\`, etc.
726
+ 3. Check \`.env\`, \`.env.example\`, \`.env.local\` for service references (e.g., STRIPE_SECRET_KEY, DATABASE_URL, OPENAI_API_KEY)
727
+ 4. Categorize everything into: languages, frameworks, databases, services, libraries, infrastructure
728
+
729
+ ## Tech Stack Categories
730
+
731
+ - **languages**: Programming languages (TypeScript, JavaScript, Python, etc.)
732
+ - **frameworks**: Application frameworks (Next.js, React, Express, etc.)
733
+ - **databases**: Database systems (PostgreSQL, SQLite, MongoDB, etc.)
734
+ - **services**: External services/APIs (Stripe, Auth0, SendGrid, AWS S3, etc.) — include \`url\` and \`envKeys\` for each
735
+ - **libraries**: Key libraries beyond the framework (Prisma, Tailwind CSS, Zod, etc.)
736
+ - **infrastructure**: Deployment/infrastructure tools (Vercel, Docker, etc.)
737
+
738
+ ## Output Format
739
+
740
+ After scanning, POST the tech stack:
741
+
742
+ \`\`\`bash
743
+ curl -s -X POST ${h}/api/editor-project-info \\
744
+ -H "Content-Type: application/json" \\
745
+ -d '{"techStack":{"languages":[{"name":"TypeScript","url":"https://typescriptlang.org","description":"Statically typed JavaScript superset","version":"5"}],"frameworks":[{"name":"Next.js","url":"https://nextjs.org","description":"Full-stack React framework with SSR and API routes","version":"15"}],"databases":[{"name":"SQLite","url":"https://sqlite.org","description":"Embedded relational database"}],"services":[{"name":"Stripe","url":"https://stripe.com","description":"Payment processing and billing","envKeys":["STRIPE_SECRET_KEY","STRIPE_PUBLISHABLE_KEY"]}],"libraries":[{"name":"Prisma","url":"https://prisma.io","description":"Type-safe database ORM and query builder","version":"7"}],"infrastructure":[]}}'
746
+ \`\`\`
747
+
748
+ Replace the example values with what you actually detect. For each item:
749
+ - \`name\` (required): Technology name
750
+ - \`url\` (required): Link to homepage or docs
751
+ - \`description\` (required): Brief description of what it does or how it's used in this project
752
+ - \`version\` (optional): Version number
753
+ - \`envKeys\` (optional): Array of environment variable names associated with this tech
754
+
755
+ Omit empty categories. After posting, briefly summarize what was detected.`,[h]),C=t&&Bs.some(({key:k})=>t[k]&&t[k].length>0);return n("div",{className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:c("div",{className:"p-4 space-y-4",children:[c("button",{type:"button",onClick:e,className:"flex items-center gap-1.5 text-xs text-gray-500 hover:text-white bg-transparent border-none p-0 cursor-pointer transition-colors",children:[n("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M15 18l-6-6 6-6"})}),"Back to Roadmap"]}),c("div",{className:"flex items-center justify-between",children:[n("h2",{className:"text-lg font-medium text-white m-0",children:"Tech Stack"}),n("div",{className:"flex items-center gap-2",children:s&&!o&&!u&&(C?n("button",{type:"button",onClick:y,className:"px-3 py-1.5 text-[11px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer",children:"Edit"}):n("button",{type:"button",onClick:()=>p(!0),className:"px-3 py-1.5 text-[11px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer",children:"Set up with Claude"}))})]}),u&&n("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:n(Zt,{prompt:w,height:400,onClose:()=>{p(!1),m()}})}),o&&c("div",{className:"space-y-4",children:[n("button",{type:"button",onClick:()=>{i(!1),p(!0)},className:"px-3 py-1.5 text-[11px] font-medium text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer",children:"Re-detect with Claude"}),Bs.map(({key:k,label:j})=>{const A=l[k]||[];return c("div",{children:[c("div",{className:"flex items-center justify-between mb-2",children:[n("label",{className:"text-[11px] font-semibold text-gray-500 uppercase tracking-wider",children:j}),n("button",{type:"button",onClick:()=>x(k),className:"text-[11px] text-[#D7FF63] hover:text-[#D7FF63]/70 bg-transparent border-none p-0 cursor-pointer transition-colors",children:"+ Add"})]}),A.map((_,M)=>c("div",{className:"bg-[#2a2a2a] border border-[#3d3d3d] rounded-lg p-2.5 mb-2 space-y-1.5",children:[c("div",{className:"flex items-center gap-1.5",children:[n("input",{type:"text",value:_.name,onChange:T=>v(k,M,"name",T.target.value),placeholder:"Name *",className:"flex-1 min-w-0 px-2 py-1 text-xs bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors font-medium"}),n("input",{type:"text",value:_.version||"",onChange:T=>v(k,M,"version",T.target.value),placeholder:"Version",className:"w-20 px-2 py-1 text-xs bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-200 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("button",{type:"button",onClick:()=>b(k,M),className:"text-gray-600 hover:text-red-400 bg-transparent border-none p-0.5 cursor-pointer transition-colors text-xs leading-none",children:"×"})]}),n("input",{type:"text",value:_.url||"",onChange:T=>v(k,M,"url",T.target.value),placeholder:"URL * (e.g. https://stripe.com)",className:"w-full px-2 py-1 text-[11px] bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("input",{type:"text",value:_.description||"",onChange:T=>v(k,M,"description",T.target.value),placeholder:"Description * (e.g. Payment processing and billing)",className:"w-full px-2 py-1 text-[11px] bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors"}),n("input",{type:"text",value:(_.envKeys||[]).join(", "),onChange:T=>N(k,M,T.target.value),placeholder:"ENV_KEYS (comma-separated, e.g. STRIPE_SECRET_KEY, STRIPE_PUBLISHABLE_KEY)",className:"w-full px-2 py-1 text-[10px] bg-[#1e1e1e] border border-[#3d3d3d] rounded text-gray-400 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors font-mono"})]},M)),A.length===0&&n("div",{className:"text-[11px] text-gray-600 italic py-1",children:"No items"})]},k)}),c("div",{className:"flex gap-2 pt-1",children:[n("button",{type:"button",onClick:g,className:"px-4 py-1.5 text-[11px] text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer font-medium",children:"Save"}),n("button",{type:"button",onClick:()=>i(!1),className:"px-4 py-1.5 text-[11px] text-gray-400 bg-transparent border border-[#3d3d3d] rounded-md hover:text-white hover:border-[#555] transition-colors cursor-pointer",children:"Cancel"})]})]}),!o&&!u&&n(we,{children:C?n("div",{className:"space-y-4",children:Bs.map(({key:k,label:j})=>{const A=t[k];return!A||A.length===0?null:c("div",{children:[n("div",{className:"text-[11px] font-semibold text-gray-500 uppercase tracking-wider mb-2",children:j}),n("div",{className:"space-y-2",children:A.map((_,M)=>c("div",{className:"bg-[#2a2a2a] rounded-lg px-3 py-2.5",children:[c("div",{className:"flex items-center gap-2",children:[_.url?n("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-gray-200 hover:text-[#D7FF63] transition-colors",children:_.name}):n("span",{className:"text-sm font-medium text-gray-200",children:_.name}),_.version&&c("span",{className:"text-[11px] text-gray-500",children:["v",_.version]}),_.url&&n("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",className:"text-[11px] text-gray-600 hover:text-gray-400 transition-colors truncate",children:_.url.replace(/^https?:\/\//,"")})]}),_.description&&n("div",{className:"text-xs text-gray-400 mt-1",children:_.description}),_.envKeys&&_.envKeys.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-1.5",children:_.envKeys.map((T,D)=>n("span",{className:"text-[10px] text-[#D7FF63]/60 bg-[#D7FF63]/10 px-1.5 py-0.5 rounded font-mono",children:T},D))})]},M))})]},k)})}):n("div",{className:"text-xs text-gray-500 italic py-4",children:"No tech stack configured yet. Use the buttons above to set up your project's tech stack."})})]})})}function v3({hasProject:e,scenarios:t,analyzedEntities:r,allEntities:s=[],glossaryFunctions:a=[],cachedTestResults:o={},glossaryEntries:i=[],projectRoot:l,activeScenarioId:d,onScenarioSelect:u,onAnalyzedScenarioSelect:p,onSwitchToBuild:h,onSwitchToHistory:m,zoomComponent:f,focusedEntity:y,onZoomChange:g,entityImports:x,pageFilePaths:b={},projectTitle:v,projectDescription:N,migrationMode:w="none",migrationState:C,onStartMigration:k,breadcrumbItems:j=[],onReseedPreview:A,isAdmin:_=!1,roadmapView:M=!1,onRoadmapViewChange:T,designSystemView:D=!1,onDesignSystemViewChange:R,onPreviewDesignSystem:L,techStackView:U=!1,onTechStackViewChange:W,buildIdle:V=!1,onScreenshotClick:F,onNavigateToComponent:Y}){const{pageGroups:P,componentGroups:O}=fe(()=>ll(t),[t]),S=fe(()=>nh(P,O),[P,O]),$=fe(()=>new Set(r.map(pe=>pe.sha)),[r]),I=fe(()=>S5(x||{}),[x]),K=le(pe=>C5(pe,$,s,I),[$,s,I]),q=fe(()=>{const pe=new Map;for(const ie of s)pe.set(ie.sha,ie.name);return pe},[s]),J=fe(()=>k5(P,O,S,K),[P,O,S,K]),z=fe(()=>r.filter(pe=>pe.entityType==="visual").sort((pe,ie)=>pe.name.localeCompare(ie.name)),[r]),[B,H]=E(()=>{try{return localStorage.getItem("codeyam-app-banner-dismissed")==="true"}catch{return!1}}),re=le(()=>{H(!0);try{localStorage.setItem("codeyam-app-banner-dismissed","true")}catch{}},[]),[ae,X]=E(""),[oe,me]=E(()=>new Set),ve=be(null),je=be(0),te=le(()=>{ve.current&&(je.current=ve.current.scrollTop)},[]);se(()=>{ve.current&&je.current>0&&(ve.current.scrollTop=je.current)});const ke=(y==null?void 0:y.sha)??"overview";if(!e)return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:c("div",{className:"flex flex-col items-center gap-4",children:[n("h2",{className:"text-lg font-medium text-white m-0",children:"Ready to build something?"}),n("button",{onClick:h,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})});if(w==="candidate")return n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:c("div",{className:"flex flex-col items-center gap-5 px-8 text-center max-w-[420px]",children:[n("h2",{className:"text-lg font-medium text-white m-0",children:"Migrate Your Project"}),n("p",{className:"text-sm text-gray-400 m-0 leading-relaxed",children:"It looks like you have an existing project. Claude can survey your codebase and systematically migrate it — deconstructing pages into clean components, extracting functions with tests, and creating scenarios. One page per session."}),n("button",{onClick:k,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Get Started"}),n("button",{onClick:h,className:"text-xs text-gray-500 hover:text-gray-300 bg-transparent border-none p-0 cursor-pointer underline",children:"Skip — build a new feature instead"})]})});if(w==="active"&&C){const pe=C.pages||[],ie=pe.filter(_e=>_e.status==="complete").length,de=pe.length,he=de>0?Math.round(ie/de*100):0;return c("div",{className:"flex-1 flex flex-col overflow-auto p-4 font-['IBM_Plex_Sans']",children:[n("h2",{className:"text-lg font-medium text-white m-0 mb-3",children:"Project Migration"}),c("div",{className:"mb-4",children:[n("div",{className:"flex items-center gap-2 mb-1",children:c("span",{className:"text-xs text-gray-400",children:[ie,"/",de," pages (",he,"%)"]})}),n("div",{className:"w-full h-1.5 bg-[#2d2d2d] rounded-full overflow-hidden",children:n("div",{className:"h-full bg-[#005c75] rounded-full transition-all",style:{width:`${he}%`}})})]}),n("div",{className:"space-y-1.5",children:pe.map((_e,ye)=>{const Re=_e.status==="complete"?"✓":_e.status==="in-progress"?"→":"○",Je=_e.status==="complete"?"text-green-400":_e.status==="in-progress"?"text-cyan-400":"text-gray-600";return c("div",{className:"flex items-center gap-2",children:[n("span",{className:`text-xs ${Je} w-3 text-center`,children:Re}),n("span",{className:`text-xs ${_e.status==="in-progress"?"text-white font-medium":_e.status==="complete"?"text-gray-400":"text-gray-600"}`,children:_e.name}),n("span",{className:"text-[10px] text-gray-600",children:_e.route}),_e.status==="complete"&&c("span",{className:"text-[10px] text-gray-600",children:[(_e.extractedComponents||[]).length,"c"," ",(_e.extractedFunctions||[]).length,"f"," ",_e.scenarioCount||0,"s"]})]},ye)})}),(C.sharedComponents||[]).length>0&&c("div",{className:"mt-4",children:[n("h3",{className:"text-xs font-medium text-gray-400 mb-1.5",children:"Shared Components"}),(C.sharedComponents||[]).map((_e,ye)=>c("div",{className:"text-[10px] text-gray-500 mb-0.5",children:[_e.name," ",c("span",{className:"text-gray-600",children:["— used in: ",(_e.usedInPages||[]).join(", ")]})]},ye))]}),n("div",{className:"mt-4",children:n("button",{onClick:h,className:"px-4 py-2 bg-[#005c75] text-white text-xs font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Continue in Chat"})})]})}return t.length>0||z.length>0?y?n(oh,{focusedEntity:y,breadcrumbItems:j,onZoomChange:g,projectRoot:l,scenarios:t,analyzedEntities:r,activeScenarioId:d,onScenarioSelect:u,onAnalyzedScenarioSelect:p,onSwitchToBuild:h,entityImports:x,glossaryFunctions:a,cachedTestResults:o,glossaryEntries:i,entityShaMap:S,componentGroups:O,visualEntities:z,isEntityComplete:K,onReseedPreview:A}):U?n(b3,{onBack:()=>{W==null||W(!1),T==null||T(!0)}}):D?n(x3,{onBack:()=>{R==null||R(!1),T==null||T(!0)},onPreviewShowcase:()=>L==null?void 0:L()}):_&&M?n(u3,{onBack:()=>T==null?void 0:T(!1),onSwitchToBuild:h,onSwitchToHistory:m,onNavigateToDesignSystem:()=>{T==null||T(!1),R==null||R(!0)},onNavigateToTechStack:()=>{T==null||T(!1),W==null||W(!0)},expandedTasks:oe,onExpandedTasksChange:me,buildIdle:V,onScreenshotClick:F,onZoomChange:Y}):c("div",{ref:ve,onScroll:te,className:"flex-1 overflow-auto font-['IBM_Plex_Sans']",children:[_&&n("div",{className:"px-4 py-4 bg-[#141414] border-b border-[#2D2D2D]",children:n(U5,{onNavigateToRoadmap:()=>T==null?void 0:T(!0),onSwitchToBuild:h,buildIdle:V})}),c("div",{className:"p-4 space-y-4 flex flex-col gap-12",children:[J.length>1&&n(E5,{brokenEntities:J}),!B&&c("div",{className:"relative border border-[#2e7d32]/40 bg-cybg rounded-lg p-4 pr-10",children:[n("button",{onClick:re,className:"absolute top-3 right-3 text-[#D7FF63] hover:text-white bg-transparent border-none cursor-pointer p-0.5",title:"Dismiss",children:n("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})}),n("p",{className:"text-sm text-white font-medium m-0 leading-snug",children:"These are all the pages in your project."}),c("p",{className:"text-sm text-gray-400 m-0 leading-snug mt-0.5",children:["(1) Select a scenario below and switch to"," ",n("button",{type:"button",onClick:h,className:"underline text-[#D7FF63] bg-transparent border-none cursor-pointer p-0 text-sm inline hover:text-[#D7FF63]/70 transition-colors",children:"build"})," ","to change or enhance an existing page."]}),n("p",{className:"text-sm text-gray-400 m-0 leading-snug mt-0.5",children:"(2) Select a page to see all of its sub-components and edit scenarios."})]}),P.size>0&&c("div",{children:[c("div",{className:"flex items-center gap-3 font-['IBM_Plex_Mono']",children:[n("span",{className:"text-xs font-bold text-gray-400 uppercase tracking-wider shrink-0",children:"Pages"}),n("div",{className:"flex-1"}),c("div",{className:"relative",style:{width:170},children:[c("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-500",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"11",cy:"11",r:"8"}),n("path",{d:"M21 21l-4.35-4.35"})]}),n("input",{type:"text",placeholder:"SEARCH...",value:ae,onChange:pe=>X(pe.target.value),className:"w-full pl-9 pr-3 py-2 text-xs bg-[#2a2a2a] border border-[#3d3d3d] rounded-md text-gray-300 placeholder-gray-600 outline-none focus:border-[#D7FF63]/50 transition-colors tracking-wider"})]}),c("button",{onClick:h,className:"flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-[#1e1e1e] bg-[#D7FF63] rounded-md hover:bg-[#D7FF63]/80 transition-colors cursor-pointer shrink-0 uppercase tracking-wider",children:[n("span",{children:"+"})," New Page"]})]}),n("div",{className:"border-b border-[#2d2d2d] mt-3"}),[...P.entries()].sort(([pe],[ie])=>pe==="Home"?-1:ie==="Home"?1:pe.localeCompare(ie)).filter(([pe])=>{if(!ae.trim())return!0;const ie=S.get(pe);return((ie?q.get(ie):void 0)||pe).toLowerCase().includes(ae.trim().toLowerCase())}).map(([pe,ie])=>{const de=ie.some(he=>he.id===d);return n("div",{className:"mt-2",children:S.has(pe)&&K(S.get(pe))?c(we,{children:[n("div",{className:"flex items-center gap-1.5 py-1",children:c("button",{onClick:()=>g(pe,S.get(pe)),className:`flex items-center gap-1.5 text-sm font-normal cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0 ${de?"text-[#D7FF63]":"text-gray-300"}`,children:[(()=>{const he=S.get(pe);return(he?q.get(he):void 0)||pe})(),c("span",{className:`font-normal text-sm ${de?"text-[#D7FF63]/60":"text-gray-500"}`,children:["(",ie.length,")"]}),n("svg",{className:de?"text-[#D7FF63]/60":"text-gray-500",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M9 18l6-6-6-6"})})]})}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:gn(ie).map(({scenario:he,dimensionLabel:_e,screenshotPath:ye,key:Re})=>n(Vs,{scenarioId:he.id,screenshotPath:ye,updatedAt:he.updatedAt,hasScreenshot:!!ye,name:he.name,dimensionLabel:_e,isActive:he.id===d,onSelect:()=>u(he,_e??void 0)},Re))})]}):c("div",{className:"py-2",children:[n("span",{className:"text-sm font-normal text-gray-500",children:(()=>{const he=S.get(pe);return he&&q.get(he)||pe})()}),c("div",{className:"flex items-center gap-2 mt-1.5",children:[c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#E0D400",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0",children:[n("circle",{cx:"12",cy:"12",r:"10"}),n("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),n("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})]}),n("p",{className:"text-xs text-[#E0D400]/80 m-0 leading-relaxed",children:"Data missing for this page."}),n(ah,{name:pe,scenarios:ie,reason:S.has(pe)?"incomplete":"missing"})]})]})},pe)})]})]})]},ke):n("div",{className:"flex-1 flex items-center justify-center font-['IBM_Plex_Sans']",children:c("div",{className:"flex flex-col items-center gap-4 px-8 text-center",children:[v?c(we,{children:[n("h2",{className:"text-lg font-medium text-white m-0",children:v}),N&&n("p",{className:"text-sm text-gray-400 m-0 leading-relaxed",children:N})]}):n("h2",{className:"text-lg font-medium text-white m-0",children:"Your project is ready"}),n("p",{className:"text-sm text-gray-400 m-0 leading-relaxed",children:"Describe what you want to build in the Chat and your pages and components will appear here."}),n("button",{onClick:h,className:"px-6 py-3 bg-[#005c75] text-white text-sm font-medium rounded-lg hover:bg-[#004d63] transition-colors cursor-pointer",children:"Start Building"})]})})}const Td=[{key:"app",label:"Home"},{key:"build",label:"Build"},{key:"data",label:"Structure"},{key:"history",label:"History"}],w3=()=>n("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"text-[#8E8E8E] shrink-0",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})});function N3({activeTab:e,onTabChange:t,buildIdle:r,claudeBuilding:s=!1,buildReady:a=!1,projectTitle:o,breadcrumbItems:i,onBreadcrumbNavigate:l}){const[d,u]=E(!1),p=be(null);se(()=>{if(!d)return;const m=f=>{p.current&&!p.current.contains(f.target)&&u(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[d]);const h=i&&i.length>0;return c("div",{className:"shrink-0 z-20 @container",children:[c("div",{className:"bg-black h-10 flex items-center px-4 gap-4",children:[c("div",{className:"flex items-center gap-3 min-w-0",children:[c("div",{className:"flex items-center gap-1.5 shrink-0",children:[n("img",{src:fa,alt:"CodeYam",className:"h-4 shrink-0"}),n("span",{className:"text-sm font-medium text-white whitespace-nowrap hidden @min-[500px]:inline",children:"CodeYam"})]}),n("span",{className:"text-[#8E8E8E] text-sm shrink-0",children:"/"}),n("div",{className:"hidden @min-[350px]:flex items-center gap-1",children:Td.map(m=>c("button",{onClick:()=>t(m.key),className:`px-2.5 py-2.5 text-sm transition-colors cursor-pointer ${e===m.key?"text-[#D7FF63] font-medium":"text-[#8E8E8E] hover:text-white font-light"}`,children:[m.key==="build"&&s&&n("span",{className:"mr-1 inline-flex items-center",style:{verticalAlign:"middle"},children:n(la,{color:"#5ce0d2",dotSize:2})}),m.key==="build"&&r&&!s&&e!=="build"&&n("span",{className:"mr-1 inline-block w-2 h-2 rounded-full bg-[#FF8B43]"}),m.label,m.key==="build"&&a&&!s&&!r&&n("span",{className:"ml-1 inline-block w-2 h-2 rounded-full bg-[#D7FF63]"})]},m.key))})]}),n("div",{className:"flex-1"}),n("button",{onClick:()=>t("settings"),className:`hidden @min-[350px]:block p-1.5 rounded-md transition-colors cursor-pointer ${e==="settings"?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white"}`,title:"Settings",children:c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("circle",{cx:"12",cy:"12",r:"3"}),n("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}),c("div",{className:"@min-[350px]:hidden relative",ref:p,children:[n("button",{onClick:()=>u(!d),className:"p-1.5 rounded-md transition-colors cursor-pointer text-[#8E8E8E] hover:text-white",title:"Menu",children:c("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[n("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),n("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),n("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),d&&c("div",{className:"absolute right-0 top-full mt-1 bg-[#2d2d2d] border border-[#3d3d3d] rounded-lg shadow-lg py-1 min-w-[140px] z-50",children:[Td.map(m=>c("button",{onClick:()=>{t(m.key),u(!1)},className:`w-full text-left px-4 py-2 text-sm transition-colors cursor-pointer bg-transparent border-none ${e===m.key?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white hover:bg-[#3d3d3d]"}`,children:[m.key==="build"&&s&&n("span",{className:"mr-1 inline-flex items-center",style:{verticalAlign:"middle"},children:n(la,{color:"#5ce0d2",dotSize:2})}),m.key==="build"&&r&&!s&&e!=="build"&&n("span",{className:"mr-1 inline-block w-2 h-2 rounded-full bg-[#FF8B43]"}),m.label]},m.key)),n("div",{className:"border-t border-[#3d3d3d] my-1"}),n("button",{onClick:()=>{t("settings"),u(!1)},className:`w-full text-left px-4 py-2 text-sm transition-colors cursor-pointer bg-transparent border-none ${e==="settings"?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white hover:bg-[#3d3d3d]"}`,children:"Settings"})]})]})]}),c("div",{className:`bg-[#161616] flex items-center px-4 border-b border-[#2d2d2d]${e==="build"?" hidden":""}`,style:{height:41},children:[n("nav",{className:"flex items-center gap-2 text-sm min-w-0 flex-1",children:h?c(we,{children:[n("button",{type:"button",onClick:()=>l==null?void 0:l(),className:"text-[#8E8E8E] hover:text-white transition-colors bg-transparent border-none p-0 cursor-pointer shrink-0",children:o||"Untitled Project"}),i.slice(1).map((m,f)=>{const y=f===i.length-2;return c("span",{className:"flex items-center gap-2 min-w-0",children:[n(w3,{}),y?n("span",{className:"text-white truncate",children:m.name}):n("button",{type:"button",onClick:()=>l==null?void 0:l(m.componentName,m.entitySha),className:"text-[#8E8E8E] hover:text-white transition-colors bg-transparent border-none p-0 cursor-pointer truncate",children:m.name})]},m.componentName||m.name)})]}):n("span",{className:"text-[#8E8E8E]",children:o||"Untitled Project"})}),r&&e!=="build"&&c("button",{type:"button",onClick:()=>t("build"),className:"flex items-center gap-2 px-3 py-1.5 rounded-lg border border-[#FF8B43]/60 bg-[#2a1500] cursor-pointer transition-colors hover:bg-[#3a2000] ml-auto shrink-0",children:[n("span",{className:"w-2.5 h-2.5 rounded-full bg-[#FF8B43] shrink-0"}),c("span",{className:"text-sm text-[#FF8B43]",children:["Claude is waiting for you."," ",n("span",{className:"text-[#FF8B43] font-medium underline",children:"Build."})]})]})]})]})}function S3({onMouseDown:e,onDoubleClick:t,isDragging:r}){return c("div",{className:"shrink-0 relative cursor-col-resize group",style:{width:2},onMouseDown:e,onDoubleClick:t,children:[n("div",{className:`absolute inset-0 transition-colors ${r?"bg-[#D7FF63]":"bg-[#646464] group-hover:bg-[#D7FF63]"}`}),n("div",{className:"absolute inset-y-0 -left-[5px] -right-[5px]"})]})}const Md=300,zs=150;function C3(e){const[t,r]=E(null),[s,a]=E(!1),o=be(0),i=be(null);se(()=>{e.current&&r(Math.round(e.current.offsetWidth*.5))},[e]);const l=le(()=>{var x;return((x=e.current)==null?void 0:x.offsetWidth)??(typeof window<"u"?window.innerWidth:1024)},[e]),d=le(x=>{x.preventDefault(),a(!0)},[]),u=le(()=>{r(Math.round(l()*.5))},[l]),p=le(()=>{r(x=>(x&&x>0&&(i.current=x),0))},[]),h=le(()=>{const x=i.current;i.current=null,r(x&&x>=Md?x:Math.round(l()*.5))},[l]),m=le(()=>{r(Math.round(l()*.5))},[l]);se(()=>{if(!s)return;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const x=v=>{cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{var _;const N=(_=e.current)==null?void 0:_.getBoundingClientRect(),w=(N==null?void 0:N.left)??0,k=((N==null?void 0:N.width)??window.innerWidth)-zs,j=v.clientX-w,A=Math.min(Math.max(j,Md),k);r(A)})},b=v=>{var j;cancelAnimationFrame(o.current),a(!1);const N=(j=e.current)==null?void 0:j.getBoundingClientRect(),w=(N==null?void 0:N.left)??0,C=(N==null?void 0:N.width)??window.innerWidth,k=v.clientX-w;k<zs?r(0):C-k<zs&&r(C)};return document.addEventListener("mousemove",x),document.addEventListener("mouseup",b),()=>{cancelAnimationFrame(o.current),document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",b),document.body.style.cursor="",document.body.style.userSelect=""}},[s,e]),se(()=>{const x=()=>{r(b=>{if(b===null||b===0)return b;const v=l();return b>=v?v:Math.min(b,v-zs)})};if(!(typeof window>"u"))return window.addEventListener("resize",x),()=>window.removeEventListener("resize",x)},[l]);const f=l(),y=t===0,g=t!==null&&t>=f;return{editorWidth:t,isDragging:s,isEditorCollapsed:y,isPreviewCollapsed:g,handleMouseDown:d,handleDoubleClick:u,collapseEditor:p,expandEditor:h,expandPreview:m}}function k3({preview:e,viewportWidth:t,scale:r,onDismiss:s,onLoadCommit:a}){const o=t*r;return c("div",{className:"flex flex-col items-center w-full h-full",children:[c("div",{className:"w-full bg-[#2a2200] border-b border-amber-600/40 px-4 py-2 flex items-center justify-center gap-2 shrink-0",children:[n("span",{className:"text-sm text-[#FFBD09]",children:"This is a snapshot from a previous version — not a live preview."}),e.commitSha&&a&&n(j3,{commitSha:e.commitSha,onLoadCommit:a}),n("button",{type:"button",onClick:s,className:"ml-2 text-gray-500 hover:text-white bg-transparent border-none cursor-pointer p-0.5 transition-colors",title:"Dismiss",children:n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M2 2l8 8M10 2l-8 8"})})})]}),n("div",{className:"flex-1 overflow-auto flex justify-center py-6",children:n("div",{className:"rounded-lg border border-[#3d3d3d] shadow-md overflow-hidden shrink-0",style:{width:`${o}px`},children:n("img",{src:e.screenshotUrl,alt:e.scenarioName,className:"block",style:{width:`${o}px`}})})})]})}function j3({commitSha:e,onLoadCommit:t}){const[r,s]=E(!1),[a,o]=E(null);return c(we,{children:[n("button",{onClick:()=>{s(!0),o(null),t(e).then(i=>{i.success||o(i.error||"Failed")}).catch(i=>{o(i instanceof Error?i.message:"Network error")}).finally(()=>s(!1))},disabled:r,className:"text-sm text-[#D7FF63] hover:text-[#D7FF63]/70 underline bg-transparent border-none p-0 cursor-pointer transition-colors disabled:opacity-50",children:r?"Reverting...":"Revert to this code and load this version."}),a&&n("span",{className:"text-xs text-red-400 ml-1",children:a})]})}function _3({preview:e,viewportWidth:t,viewportHeight:r,scale:s,onDismiss:a}){const o=t*s,i=r*s;return c("div",{className:"flex flex-col items-center gap-4 w-full",style:{maxWidth:`${o}px`},children:[c("div",{className:"text-center shrink-0",children:[n("h2",{className:"text-lg font-semibold text-gray-200 m-0 font-['IBM_Plex_Sans']",children:e.scenarioName}),c("div",{className:"flex items-center justify-center gap-2 mt-2",children:[n("span",{className:"inline-block w-2 h-2 rounded-full bg-amber-400 animate-pulse"}),n("p",{className:"text-sm text-amber-400/90 m-0 font-['IBM_Plex_Sans']",children:"The app is being edited - you can control the live preview when building is paused or complete."})]})]}),e.hasScreenshot?n("div",{className:"rounded-lg border-2 border-[#4d4d4d] shadow-md overflow-y-auto overflow-x-hidden shrink",style:{width:`${o}px`,maxHeight:`${i}px`},children:n(cr,{scenarioId:e.scenarioId,screenshotPath:e.screenshotPath,updatedAt:e.updatedAt,alt:e.scenarioName,imgClassName:"block w-full",className:""})}):n("div",{className:"rounded-lg border-2 border-[#4d4d4d] bg-[#1a1a1a] flex items-center justify-center w-[400px] h-[300px]",children:n("span",{className:"text-sm text-gray-500",children:"No screenshot available"})}),n("button",{onClick:a,className:"text-xs text-gray-500 hover:text-gray-300 bg-transparent border-none cursor-pointer transition-colors shrink-0",children:"Dismiss"})]})}function E3({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,onStateChange:o}){const{interactiveServerUrl:i,isStarting:l,isLoading:d}=Un({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:!0});return se(()=>{o(i,l||d)},[i,l,d,o]),null}function P3({onSaveToCurrent:e,onSaveAsNew:t,onDismiss:r,isSaving:s,scenarioName:a}){return c("div",{className:"flex items-center justify-between px-4 py-1.5 bg-emerald-900/60 border-b border-emerald-700/50 text-emerald-200 text-xs",children:[n("span",{className:"font-medium",children:a?c(we,{children:["Data modified in “",a,"”."]}):"Data modified."}),c("div",{className:"flex items-center gap-2",children:[n("button",{onClick:e,disabled:s,className:"px-2.5 py-0.5 bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white text-xs font-medium rounded transition-colors cursor-pointer disabled:cursor-not-allowed",children:s?"Saving...":"Save to Scenario"}),n("button",{onClick:t,disabled:s,className:"px-2.5 py-0.5 bg-emerald-800 hover:bg-emerald-700 disabled:opacity-50 text-emerald-200 text-xs font-medium rounded transition-colors cursor-pointer disabled:cursor-not-allowed",children:"Save as New"}),n("button",{onClick:r,disabled:s,className:"text-emerald-400 hover:text-emerald-200 disabled:opacity-50 transition-colors cursor-pointer disabled:cursor-not-allowed",title:"Dismiss",children:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]})}function A3({latestVersion:e}){const[t,r]=E(!1);if(t)return null;const s=`npm install -g @codeyam/codeyam-cli@${e}`;return c("div",{className:"shrink-0 w-full bg-[#D7FF63] px-4 py-1.5 flex items-center text-xs text-black font-['IBM_Plex_Sans']",children:[c("div",{className:"flex-1 flex items-center justify-center gap-2",children:[n("span",{children:"An update to the codeyam editor is available."}),n("code",{className:"bg-[#2d2d2d] text-white font-mono text-xs px-3 py-0.5 rounded-full",children:s}),n(xt,{content:s,icon:!0,iconSize:12,className:"text-black hover:text-gray-700 transition-colors"})]}),n("button",{type:"button",onClick:()=>r(!0),className:"shrink-0 p-0.5 rounded text-black/60 hover:text-black hover:bg-black/10 transition-colors cursor-pointer bg-transparent border-none","aria-label":"Dismiss upgrade banner",children:n("svg",{className:"w-3.5 h-3.5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:n("path",{d:"M6 18L18 6M6 6l12 12"})})})]})}function T3(e,t){return t.status==="error"?{url:null,proxyUrl:null,isStarting:!1,error:t.errorMessage||"Dev server crashed",canStartServer:e.canStartServer,autoStartAttempted:e.autoStartAttempted,shouldAutoStart:!1}:t.url?{url:t.url,proxyUrl:t.proxyUrl||null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:e.autoStartAttempted,shouldAutoStart:!1}:t.status==="starting"?{...e,isStarting:!0,error:null,canStartServer:!0,shouldAutoStart:!1}:t.status==="stopped"?e.url?{...e,url:null,isStarting:!1,shouldAutoStart:!1}:e.autoStartAttempted?{...e,isStarting:!1,shouldAutoStart:!1}:{...e,autoStartAttempted:!0,shouldAutoStart:!0}:{...e,shouldAutoStart:!1}}function M3(e){const[t,r]=E({url:null,proxyUrl:null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:!1}),s=be(t);s.current=t,se(()=>{let i=!1,l=null;const d=async()=>{try{const u=await fetch("/api/editor-dev-server");if(i)return;const p=await u.json(),h=T3(s.current,p),{shouldAutoStart:m,...f}=h;if(r(f),m&&!(e!=null&&e.skipAutoStart))try{const y=await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})});if(i)return;y.ok?r(g=>({...g,isStarting:!0})):r(g=>({...g,canStartServer:!1}))}catch{}}catch{}};return d(),l=setInterval(()=>void d(),2e3),()=>{i=!0,l&&clearInterval(l)}},[t.url]);const a=le(()=>{r(i=>({...i,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})}).catch(()=>{})},[]),o=le(()=>{r(i=>({...i,error:null,isStarting:!0})),fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})}).catch(()=>{})},[]);return{devServerUrl:t.url,proxyUrl:t.proxyUrl,isStarting:t.isStarting,error:t.error,canStartServer:t.canStartServer,retryServer:a,startServer:o}}function $3(e){const t=be(null),r=be(null);se(()=>{if(typeof document>"u")return;r.current||(r.current=document.createElement("canvas"),r.current.width=64,r.current.height=64);const s=document.querySelector('link[rel="icon"]');if(!s)return;if(t.current||(t.current=s.href),!e){s.href=t.current;return}const a=new Image;a.crossOrigin="anonymous",a.onload=()=>{const o=r.current,i=o.getContext("2d");i.clearRect(0,0,64,64);const l=56,d=(64-l)/2;i.drawImage(a,d,d,l,l);const u=12,p=64-u-1,h=u+1;i.beginPath(),i.arc(p,h,u,0,2*Math.PI),i.fillStyle="#ef4444",i.fill(),s.href=o.toDataURL("image/png")},a.src=t.current},[e]),se(()=>()=>{if(typeof document>"u")return;const s=document.querySelector('link[rel="icon"]');s&&t.current&&(s.href=t.current)},[])}function F3(e){if(!e||typeof e!="object")return[];for(const t of Object.values(e))if(Array.isArray(t))return t;return[]}function D3(e){return G.join(e,".codeyam","migration-state.json")}function lh(e){const t=D3(e);try{const r=Q.readFileSync(t,"utf8"),s=JSON.parse(r);return R3(s)}catch{return null}}function R3(e){const t=Array.isArray(e.pages)?e.pages:[],r=Array.isArray(e.sharedComponents)?e.sharedComponents:[];return{status:e.status||"surveyed",startedAt:e.startedAt||new Date().toISOString(),completedAt:e.completedAt??null,currentPageIndex:typeof e.currentPageIndex=="number"?e.currentPageIndex:0,pages:t.map(s=>({name:s.name||"Unknown",route:s.route||"/",filePath:s.filePath||"",status:s.status||"pending",startedAt:s.startedAt??null,completedAt:s.completedAt??null,extractedComponents:Array.isArray(s.extractedComponents)?s.extractedComponents:[],extractedFunctions:Array.isArray(s.extractedFunctions)?s.extractedFunctions:[],scenarioCount:typeof s.scenarioCount=="number"?s.scenarioCount:0})),sharedComponents:r.map(s=>({name:s.name||"",filePath:s.filePath||"",extractedFromPage:s.extractedFromPage||"",usedInPages:Array.isArray(s.usedInPages)?s.usedInPages:[]}))}}function I3(e,t){if(!Q.existsSync(G.join(e,"package.json"))||t!=null&&t.hasEditorScenarios)return!1;const r=G.join(e,".codeyam","glossary.json");if(Q.existsSync(r))try{const o=JSON.parse(Q.readFileSync(r,"utf8"));if((Array.isArray(o)?o:F3(o)).length>0)return!1}catch{}const s=G.join(e,".codeyam","editor-step.json");if(Q.existsSync(s))try{const o=JSON.parse(Q.readFileSync(s,"utf8"));if(o.feature||o.scaffolded)return!1}catch{}const a=lh(e);return(a==null?void 0:a.status)!=="complete"}function O3(e){const t=G.join(e,".codeyam","editor-step.json");try{const r=Q.readFileSync(t,"utf8");return!!JSON.parse(r).migration}catch{return!1}}function L3({currentUrl:e,nextUrl:t,formMethod:r,defaultShouldRevalidate:s}){return r||e.pathname===t.pathname?s:e.pathname.startsWith("/editor")&&t.pathname.startsWith("/editor")?!1:s}const B3=()=>[{title:"Editor - CodeYam"},{name:"description",content:"CodeYam Code + Data Editor"}];function z3(e){const t=new URL(e).pathname.match(/\/editor\/entity\/([^/]+)/);return t?t[1]:null}async function Y3({request:e}){var S;const t=await ze();let r=!1,s=[],a=[];const o=Ce()||process.cwd();let i={map:{},allFiles:[]};try{i=Oi(o)}catch{}let l=[];try{l=xr()}catch{}if(t){const{project:$}=await Ie(t);r=((S=$.metadata)==null?void 0:S.editorMode)??!1;try{const I=$e();try{const z=await I.selectFrom("editor_scenarios").select(["id","url"]).where("project_id","=",$.id).where("component_name","is",null).where("page_file_path","is",null).execute();if(z.length>0){const{allFiles:B}=i;for(const H of z){const re=H;if(!re.url)continue;const ae=ju(re.url,B);ae&&await I.updateTable("editor_scenarios").set({page_file_path:ae}).where("id","=",re.id).execute()}}}catch(z){console.warn("[editor] page_file_path backfill failed (non-fatal):",z instanceof Error?z.message:z)}const K=await I.selectFrom("editor_scenarios").selectAll().where("project_id","=",$.id).orderBy("created_at","asc").execute(),q=z=>{const B=z;let H=null,re=null;try{B.dimensions&&(H=typeof B.dimensions=="string"?JSON.parse(B.dimensions):B.dimensions)}catch{}try{B.screenshot_paths&&(re=typeof B.screenshot_paths=="string"?JSON.parse(B.screenshot_paths):B.screenshot_paths)}catch{}return{id:z.id,name:z.name,description:z.description||"",componentName:z.component_name||null,componentPath:z.component_path||null,screenshotPath:z.screenshot_path||null,url:B.url||null,type:B.type||null,viewportWidth:B.viewport_width||null,viewportHeight:B.viewport_height||null,dimensions:H,screenshotPaths:re,pageFilePath:B.page_file_path||null,entitySha:B.entity_sha||null,displayName:B.display_name||null,updatedAt:B.updated_at||null}};a=Mt(K,z=>`${z.name}::${z.url||"/"}`).map(q);const J=ap(o);if(J){const z=rs(J),B=K.filter(H=>Ci(H,z));s=Mt(B,H=>`${H.name}::${H.url||"/"}`).map(q)}else s=a}catch{}}const d=[...new Set(a.map($=>$.componentName).filter($=>$!==null))];let u=[];try{const $=G.join(o,".codeyam","glossary.json");if(Q.existsSync($)){const I=Q.readFileSync($,"utf8");u=JSON.parse(I)}}catch{}const p=Dy(u),h={};try{const $=Ji(o),I=p.filter(K=>K.testFile).map(K=>({filePath:K.filePath,testFile:K.testFile}));if(I.length>0){const K=Hi(o,I);for(const[q,J]of Object.entries($.results)){const z=K[q];h[q]={...J,stale:z?xp(J,z.sourceHash,z.testHash):!0}}}}catch{}let m=[],f=[];try{const $=await Yn()||[];m=$.map(I=>({sha:I.sha,name:I.name,entityType:I.entityType||"visual",filePath:I.filePath||""})),f=Ry($,u)}catch{}let y=[];try{if(m.length>0){const $=m.map(I=>I.sha);await We(),y=await et({shas:$})||[]}}catch{}let g={};try{if(y.length>0){const $=new Set([...f.map(I=>I.name),...m.map(I=>I.name),...d,...u.map(I=>I.name)]);g=Iy(y,$)}}catch{}const x=i.map,b=i.allFiles;if(Object.keys(x).length>0&&y.length>0&&(g=Oy(g,x,y)),b.length>0&&y.length>0){const $=new Map;for(const I of y)I.filePath&&$.set(I.filePath,I.name);for(const I of b){const K=Jt(Ft(I));if(g[K])continue;const q=$.get(I);q&&g[q]&&(g[K]=g[q])}}let v={};try{v=(await br({projectRoot:o,scenarioInputs:a,glossaryInputs:p,precomputedPageFilePaths:i,precomputedGitFiles:l,precomputedEntities:y})).entityChangeStatus}catch{}const N=l.filter($=>$.status!=="deleted").map($=>({path:$.path,status:$.status})),w=Ia(o),C=zi(o),k=Li(o),j=op(o);let A=null,_=null,M=null,T=null,D=null,R=null,L=null;try{const $=G.join(o,".codeyam","config.json");if(Q.existsSync($)){const I=JSON.parse(Q.readFileSync($,"utf8"));A=I.projectTitle||null,_=I.projectDescription||null,M=I.defaultScreenSize||null,T=I.screenSizes||null,D=I.appFormats||null,R=I.provider||"claude";const K=I.handoff;K!=null&&K.lastProvider&&K.lastProvider!==R&&(L={from:K.lastProvider,to:R,lastStep:K.lastStep??null,lastStepLabel:(k==null?void 0:k.label)??null,handoffSummary:K.summary??null})}}catch{}D||(D=Bi(o));const U=z3(e.url);let W=null,V=null;if(U&&t)try{await We();const $=await et({}),I=$==null?void 0:$.find(K=>K.sha===U);if(I){const K=I.name,q=I.filePath||"",J=I.entityType||"visual";V={name:K,filePath:q,entityType:J,displayName:K};const z=$==null?void 0:$.find(B=>B.name===I.name&&B.filePath===I.filePath&&B.sha!==U&&B.createdAt&&I.createdAt&&B.createdAt>I.createdAt);z&&(W=z.sha)}}catch{}const F=ip(o),Y=F&&a.some($=>$.id===F)?F:null;let P="none",O=null;try{if(O=lh(projRoot),(O==null?void 0:O.status)==="complete")P="complete";else if((O==null?void 0:O.status)==="in-progress"||(O==null?void 0:O.status)==="surveyed")P="active";else if(O3(projRoot))P="active";else if(t){const $=a.length>0;I3(projRoot,{hasEditorScenarios:$})&&(P="candidate")}}catch{}return ue({projectSlug:t,projectRoot:Ce(),hasProject:!!t,editorMode:r,scenarios:s,allScenarios:a,components:d,analyzedEntities:f,allEntities:m,glossaryFunctions:p,glossaryEntries:u,entityImports:g,pageFilePaths:x,entityChangeStatus:v,modifiedFiles:N,featureName:w,userPrompt:C,projectTitle:A,projectDescription:_,defaultScreenSize:M,screenSizes:T,appFormats:D,editorStep:(k==null?void 0:k.step)??null,editorStepLabel:(k==null?void 0:k.label)??null,claudeSessionId:j,focusedEntitySha:U,newerEntitySha:W,focusedEntity:V,savedActiveScenarioId:Y,migrationMode:P,migrationState:O,cachedTestResults:h,providerSwitch:L,currentProvider:R})}class U3 extends Gh{constructor(){super(...arguments);vt(this,"state",{error:null,errorInfo:null})}static getDerivedStateFromError(r){return{error:r,errorInfo:null}}componentDidCatch(r,s){console.error("[EditorErrorBoundary] Error:",r.message),console.error("[EditorErrorBoundary] Component stack:",s.componentStack),console.error("[EditorErrorBoundary] Loader snapshot:",JSON.stringify(this.props.loaderSnapshot,null,2)),this.setState({errorInfo:s})}render(){var r;return this.state.error?n("div",{className:"fixed inset-0 bg-[#1e1e1e] flex items-center justify-center p-8",children:c("div",{className:"max-w-[600px] w-full space-y-4",children:[n("h2",{className:"text-lg font-semibold text-red-400 font-['IBM_Plex_Sans'] m-0",children:"Something went wrong"}),n("pre",{className:"text-xs text-gray-300 bg-[#2d2d2d] p-3 rounded overflow-auto max-h-[120px]",children:this.state.error.message}),((r=this.state.errorInfo)==null?void 0:r.componentStack)&&c("details",{className:"text-xs text-gray-500",children:[n("summary",{className:"cursor-pointer hover:text-gray-300 transition-colors",children:"Component stack"}),n("pre",{className:"mt-2 bg-[#2d2d2d] p-3 rounded overflow-auto max-h-[200px] text-yellow-300",children:this.state.errorInfo.componentStack})]}),n("p",{className:"text-xs text-gray-500 m-0",children:"Full diagnostics are in the browser console."}),n("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 bg-[#005c75] text-white text-sm rounded hover:bg-[#004d63] transition-colors cursor-pointer",children:"Reload"})]})}):this.props.children}}const W3=tt(function(){var Tl,Ml;const{projectSlug:t,projectRoot:r,hasProject:s,scenarios:a,allScenarios:o,analyzedEntities:i,allEntities:l,glossaryFunctions:d,glossaryEntries:u,entityImports:p,pageFilePaths:h,entityChangeStatus:m,modifiedFiles:f,featureName:y,userPrompt:g,projectTitle:x,projectDescription:b,defaultScreenSize:v,screenSizes:N,appFormats:w,editorStep:C,editorStepLabel:k,claudeSessionId:j,focusedEntitySha:A,newerEntitySha:_,focusedEntity:M,migrationMode:T,migrationState:D,cachedTestResults:R,providerSwitch:L,currentProvider:U}=lt(),W=Fd("root"),V=(W==null?void 0:W.npmUpdate)??null,F=(W==null?void 0:W.isAdmin)??!1,[Y,P]=dr(),O=Yt(),S=be(null),$=be(null),I=be(null),K=be(null),[q,J]=E(A),[z,B]=E(!1),[H,re]=E(!1),[ae,X]=E(!1),[oe,me]=E(0);se(()=>{J(A)},[A]),se(()=>{const ne=ge=>{const Ne=ge.target;(Ne.tagName==="BUTTON"||Ne.closest("button"))&&(Ne.closest("button")??Ne).blur()};return document.addEventListener("mouseup",ne),()=>document.removeEventListener("mouseup",ne)},[]);const ve=fe(()=>ld(q,l),[q,l,o]),je=(ve==null?void 0:ve.displayName)??void 0,te=Y.get("scenario")||((Tl=js(o))==null?void 0:Tl.id)||void 0,[ke,Z]=E(()=>je?[je]:[]),pe=be(null),ie=be([]),de=be(null);se(()=>{var Ue;const ne=te||((Ue=js(o))==null?void 0:Ue.id);if(!Gy(ne,pe.current))return;const ge=o.find(Qe=>Qe.id===ne);if(!ge)return;pe.current=ne;const Ne=ho(ge,ie.current,de.current);Ne&&Vt(Ne);const De=It(ge.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:De,scenarioId:ge.id,scenarioName:ge.name,scenarioType:ge.type})}).catch(()=>{})},[te,o]),se(()=>{const ne=new BroadcastChannel("codeyam-editor");return ne.onmessage=ge=>{var Ne;if(((Ne=ge.data)==null?void 0:Ne.type)==="switch-scenario"&&ge.data.scenarioId){const De=ge.data.scenarioId,Ue=o.find(er=>er.id===De);if(!Ue)return;pe.current=De;const Qe=new URLSearchParams(Y);Qe.set("scenario",De),Qe.delete("zoom"),P(Qe),Ht(null),sn(null),Dt(null),cn(!0);const dn=It(Ue.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:dn,scenarioId:De,scenarioType:Ue.type})}).then(()=>{pt(!1),Vn(er=>er+1)}).catch(()=>{cn(!1)})}},()=>ne.close()},[Y,P,o]),se(()=>{if(Y.get("ref")!=="link"||!te)return;const ne=new BroadcastChannel("codeyam-editor");ne.postMessage({type:"switch-scenario",scenarioId:te}),ne.close(),window.close()},[]);const{devServerUrl:he,proxyUrl:_e,isStarting:ye,error:Re,canStartServer:Je,retryServer:bt,startServer:Ge}=M3({skipAutoStart:T==="candidate"||T==="active"}),[vr,pt]=E(!1),[qe,Ht]=E(null),[wr,sn]=E(null),[Nr,Wn]=E(!1),[wn,Dt]=E(null),[ht,mt]=E(null),ft=le(async ne=>{const Ne=await(await fetch("/api/editor-load-commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commitSha:ne})})).json();return Ne.success&&(Dt(null),pt(!1)),Ne},[]),ct=le((ne,ge)=>{sn(Ne=>(ne&&ne!==Ne&&pt(!1),ne)),!ge&&ne&&pt(!0),Wn(ge)},[]),Sr=le(ne=>{Dt(null),Ht(Ne=>(Ne&&Ne.analysisId===ne.analysisId||(sn(null),Vn(Ue=>Ue+1)),ne)),Wn(!0),pt(!1);const ge=new URLSearchParams(Y);ge.delete("scenario"),ge.delete("zoom"),P(ge)},[Y,P]),[Le,Vt]=E(v?{name:v.name,width:v.width,height:v.height}:{name:"Desktop",width:1440,height:900}),[as,Cr]=E(!1),[dt,kr]=E(!1),os=(w==null?void 0:w.includes("mobile-app"))??!1,is=v?{name:v.name,width:v.width,height:v.height}:null;de.current=is;const ls=Qr(),nt=fe(()=>{const ne=ls.pathname.split("/").filter(Boolean),ge=ne[ne.length-1];return ge==="build"||ge==="history"||ge==="settings"?ge:ge==="structure"?"data":"app"},[ls.pathname]),gt=le(ne=>{J(null),Z([]),B(!1);const ge=ne==="app"?"":`/${ne==="data"?"structure":ne}`,Ne=Y.get("scenario"),De=Ne?`?scenario=${Ne}`:"";O(`/editor${ge}${De}`)},[O,Y]),jr=le(()=>{gt("build"),Nn(!0)},[gt]),Ya=le(()=>{gt("history")},[gt]),Ua=le(()=>{gt("build"),Nn(!0),setTimeout(()=>{var ne;(ne=S.current)==null||ne.sendInput("codeyam editor migrate")},300)},[gt]),[_r,Nn]=E(nt==="build"),an=!!(y&&C),on=C!=null&&C<=1,[Kt,Sn]=E(L&&an&&!on?"provider-switch":an&&!on?"pending":an&&on?"fresh":"no-session"),Er=be(!1);se(()=>{(Kt==="pending"||Kt==="provider-switch")&&!Er.current&&(Er.current=!0,gt("build"),Nn(!0))},[Kt,gt]);const Pr=be(!1);se(()=>{an&&on&&!Pr.current&&(Pr.current=!0,fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}).catch(()=>{}))},[an,on]);const cs=le(()=>{Sn("continue")},[]),ds=le(()=>{fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}).catch(()=>{}),Sn("fresh")},[]),us=le(async()=>{await fetch("/api/editor-handoff",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"accept"})}).catch(()=>{}),await fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear-session-id"})}).catch(()=>{}),Sn("fresh")},[]),ps=le(async()=>{await fetch("/api/editor-handoff",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"dismiss"})}).catch(()=>{}),await fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}).catch(()=>{}),Sn("fresh")},[]),[hs,Jn]=E("none"),ms=le(()=>{Jn("choosing")},[]),fs=le(()=>{var ne;fetch("/api/editor-session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})}).catch(()=>{}),Jn("none"),(ne=S.current)==null||ne.sendInput("/clear"),setTimeout(()=>{var ge;(ge=S.current)==null||ge.sendInput("/codeyam-editor")},500)},[]),gs=le(()=>{Jn("none")},[]),[xe,Fe]=E(!1),[st,Ye]=E(!1),at=be(!1),yt=be(0),Ve=be(!1),ot=le(ne=>{Fe(ne),ne||(Ve.current=!0),ne&&!at.current&&(Ye(!1),yt.current=Date.now()),ne||(yt.current=0),at.current=ne},[]),[He,Cn]=E(!1),kn=be(!1),ch=le(ne=>{ne!==kn.current&&(console.log("[Editor] claudeBuilding: %s → %s",kn.current,ne),kn.current=ne,Cn(ne))},[]);$3(xe);const dl=be(He);se(()=>{var ge;const ne=dl.current&&!He;if(dl.current=He,!He)if(ne){const Ne=Y.get("scenario")||((ge=js(o))==null?void 0:ge.id),De=o.find(Ue=>Ue.id===Ne);if(De){console.log("[Editor] Building stopped, loading live preview for: %s",De.name),mt(null);const Ue=It(De.name);pe.current=De.id,cn(!0),Kn(!1),pt(!1),fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Ue,scenarioId:De.id,scenarioType:De.type,skipBroadcast:!0})}).then(()=>{Vn(Qe=>Qe+1)}).catch(()=>{cn(!1),pt(!0)})}else mt(null)}else mt(null)},[He,Y,o]);const{editorWidth:ul,isDragging:pl,isEditorCollapsed:jn,isPreviewCollapsed:Wa,handleMouseDown:dh,handleDoubleClick:uh,collapseEditor:ph,expandEditor:hl,expandPreview:hh}=C3(K),[Ja,ml]=E(!1),mh=le(()=>{ml(!0),gt("build"),Nn(!0)},[gt]),fl=le(()=>{ml(!1)},[]),fh=le(ne=>{Vt(ne),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:ne,skipBroadcast:!0})})},[]),[gl,yl]=E(sr);se(()=>{const ne=wy();yl(ne),ne.systemNotification&&typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},[]);const gh=le(ne=>{yl(ne),Ny(ne)},[]);se(()=>{if(nt==="build"){Fe(!1);const ne=setTimeout(()=>{var ge,Ne;(ge=S.current)==null||ge.scrollToBottom(),(Ne=S.current)==null||Ne.focus()},50);return()=>clearTimeout(ne)}},[nt]),se(()=>{function ne(){!document.hidden&&nt==="build"&&Fe(!1)}return document.addEventListener("visibilitychange",ne),()=>document.removeEventListener("visibilitychange",ne)},[nt]);const[_n,yh]=E(null);se(()=>{const ne=I.current;if(!ne)return;const ge=new ResizeObserver(Ne=>{const De=Ne[0];De&&yh({width:De.contentRect.width,height:De.contentRect.height})});return ge.observe(ne),()=>ge.disconnect()},[]);const Ar=os&&!dt&&(Le.height??900)>Le.width,ln=fe(()=>_n?Ar?ac(_n,{width:Le.width+Rs.width,height:(Le.height??900)+Rs.height}):ac(_n,Le):1,[_n,Le,Ar]),[Hn,Vn]=E(0),[xl,Ha]=E(null),[ys,cn]=E(!1),xs=be(!1),[xh,Kn]=E(!1),[bh,bl]=E(!1),Va=be(0);se(()=>{Hn>0&&(Va.current=Date.now()+3e3)},[Hn]);const vh=le(()=>{if(Date.now()<Va.current)return;const ne=yt.current;ne===0||Date.now()-ne<5e3||Kn(!0)},[]);se(()=>{const ne=ge=>{var Ne;if(((Ne=ge.data)==null?void 0:Ne.type)==="codeyam-localstorage-changed"){if(Date.now()<Va.current)return;const De=yt.current;if(De===0||Date.now()-De<5e3)return;Kn(!0)}};return window.addEventListener("message",ne),()=>window.removeEventListener("message",ne)},[]);const vl=le(async ne=>{bl(!0);try{let ge;const Ne=$.current;Ne!=null&&Ne.contentWindow&&(ge=await new Promise(Qe=>{const dn=setTimeout(()=>Qe(void 0),2e3),er=$l=>{var Fl;((Fl=$l.data)==null?void 0:Fl.type)==="codeyam-localstorage-state"&&(clearTimeout(dn),window.removeEventListener("message",er),Qe($l.data.data))};window.addEventListener("message",er),Ne.contentWindow.postMessage({type:"codeyam-get-localstorage"},"*")}));const Ue=await(await fetch("/api/editor-save-seed-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:ne,localStorage:ge})})).json();Ue.success?Kn(!1):console.error("[editor] Save seed state failed:",Ue.error)}catch(ge){console.error("[editor] Save seed state error:",ge)}finally{bl(!1)}},[]),wh=le((ne,ge)=>{if(Ha(ne||null),ge){const Ne=new URLSearchParams(Y);Ne.set("scenario",ge),pe.current=ge,P(Ne);const De=o.find(Ue=>Ue.id===ge);if(De){const Ue=ho(De,ie.current,de.current);Ue&&Vt(Ue)}}Dt(null),pt(!1),Vn(Ne=>Ne+1)},[Y,P,o]),{customSizes:Ka,addCustomSize:Nh,removeCustomSize:Sh}=ja(t),Tr=fe(()=>Xp(N,w),[N,w]),bs=fe(()=>[...Tr,...Ka],[Tr,Ka]);ie.current=bs;const Gn=fe(()=>{const ne=new Map;for(const ge of l){ne.set(ge.name,ge.sha);const Ne=Jt(Ft(ge.filePath));Ne!==ge.name&&ne.set(Ne,ge.sha)}return ne},[l]),wl=fe(()=>{const ne=new Map;for(const ge of l)ne.set(ge.sha,ge.name);return ne},[l]),Nl=fe(()=>{const ne=[{name:"App"}];z&&ne.push({name:"Roadmap"}),H&&ne.push({name:"Design System"}),ae&&ne.push({name:"Tech Stack"});for(const ge of ke){const Ne=Gn.get(ge),De=Ne?wl.get(Ne):void 0;ne.push({name:De||ge,componentName:ge,entitySha:Ne})}return ne},[ke,Gn,wl,z,H,ae]),{pageGroups:Sl,componentGroups:Ga}=fe(()=>ll(o),[o]),qn=fe(()=>nh(Sl,Ga),[Sl,Ga]),[Ch,Cl]=E("application"),[Qn,vs]=E([]),[qa,Qa]=E(null),kl=fe(()=>qa?ld(qa,l):null,[qa,l,o]),jl=fe(()=>{const ne=[{name:"App"}];for(const ge of Qn)ne.push({name:ge,componentName:ge,entitySha:Gn.get(ge)});return ne},[Qn,Gn]),Za=le((ne,ge)=>{if(!ne){vs([]),Qa(null);return}const Ne=ge||qn.get(ne);if(!Ne)return;const De=Qn.indexOf(ne);De>=0?vs(Qn.slice(0,De+1)):vs([...Qn,ne]),Qa(Ne)},[Qn,qn]),kh=le((ne,ge)=>{if(!ne)return;const Ne=ge||Gn.get(ne)||qn.get(ne);gt("data"),Cl("components"),vs([ne]),Ne&&Qa(Ne)},[Gn,qn]),_l=le((ne,ge)=>{if(!ne){Z([]),J(null);const Qe=Y.get("scenario"),dn=Qe?`?scenario=${Qe}`:"";O(`/editor${dn}`);return}if(!ge){console.error(`[editor] No entity SHA for "${ne}" — entity missing from database`);return}const Ne=ke.indexOf(ne);Ne>=0?Z(ke.slice(0,Ne+1)):Z([...ke,ne]);const De=o.find(Qe=>Qe.entitySha===ge);J(ge);const Ue=De?`?scenario=${De.id}`:"";O(`/editor/entity/${ge}${Ue}`)},[O,o,ke,Y]),El=le(ne=>{cn(!0),xs.current=!0,Kn(!1),pt(!1);const ge=It(ne.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:ge,scenarioId:ne.id,scenarioType:ne.type,skipBroadcast:!0})}).then(()=>{xs.current=!1,Vn(Ne=>Ne+1)}).catch(()=>{xs.current=!1,cn(!1),pt(!0)})},[]),Zn=le((ne,ge)=>{console.log("[Editor] Scenario selected: %s dimension=%s (claudeBuilding=%s)",ne.name,ge??"default",He),Ht(null),sn(null),Dt(null),Ha(null);let Ne=null;if(ge&&(N!=null&&N[ge])){const Ue=N[ge],Qe=bs.find(dn=>dn.width===Ue.width&&dn.height===Ue.height);Ne={name:(Qe==null?void 0:Qe.name)||ge,...Ue}}Ne||(Ne=ho(ne,bs,is)),Ne&&Vt(Ne),pe.current=ne.id;const De=new URLSearchParams(Y);De.set("scenario",ne.id),P(De),He?mt({scenarioId:ne.id,scenarioName:ne.name,updatedAt:ne.updatedAt,hasScreenshot:!!ne.screenshotPath,screenshotPath:ne.screenshotPath}):(mt(null),El(ne))},[Y,P,bs,N,He,El]),jh=le(()=>{const ne=te;if(!ne)return;const ge=o.find(De=>De.id===ne);if(!ge)return;const Ne=It(ge.name);pt(!1),fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Ne,scenarioId:ge.id,scenarioType:ge.type})}).then(()=>{Vn(De=>De+1)})},[te,o]),Pl=le(ne=>{if(!ne.commitSha){const ge=o.find(Ne=>Ne.name===ne.scenarioName);if(ge){Zn(ge);return}}Dt(ne)},[o,Zn]),_h=ne=>{const ge={name:ne.name,width:ne.width,height:ne.height};Vt(ge),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:ge,skipBroadcast:!0})})},Eh=(ne,ge,Ne)=>{Nh(ne,ge,Ne)},Ph=ne=>{Vt(ne),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:ne,skipBroadcast:!0})})};se(()=>{const ne=ge=>{var Ne;if(((Ne=ge.data)==null?void 0:Ne.type)==="codeyam-preview-ready"&&!qe){if(xs.current)return;pt(!0),cn(!1)}};return window.addEventListener("message",ne),()=>window.removeEventListener("message",ne)},[qe]);const Al=()=>{qe||setTimeout(()=>{pt(ne=>(ne||cn(!1),!0))},5e3)},Xn=fe(()=>Ky({activeAnalyzedScenario:!!qe,analyzedPreviewUrl:wr,activeScenarioId:te||null,scenarios:o,proxyUrl:_e,devServerUrl:he,zoomComponent:je||null}),[_e,he,je,te,o,qe,wr]),Xa=fe(()=>{if(H)return`/api/design-system-showcase?__cb=${oe}`;const ne=Mu(Xn,xl);if(!ne)return null;const ge=ne.includes("?")?"&":"?";return`${ne}${ge}__cb=${Hn}`},[Xn,xl,Hn,H,oe]),Ah=fe(()=>({projectSlug:t,hasProject:s,scenarioCount:a==null?void 0:a.length,allScenarioCount:o==null?void 0:o.length,analyzedEntityCount:i==null?void 0:i.length,glossaryFunctionCount:d==null?void 0:d.length,entityChangeStatusKeys:m?Object.keys(m):[],featureName:y}),[t,s,a,o,i,d,m,y]);return c(we,{children:[n(U3,{loaderSnapshot:Ah,children:c("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[qe&&n(E3,{analysisId:qe.analysisId,scenarioId:qe.scenarioId,scenarioName:qe.scenarioName,entityName:qe.entityName,projectSlug:t,onStateChange:ct},qe.analysisId),V&&n(A3,{latestVersion:V.latestVersion}),c("div",{ref:K,className:"flex-1 flex min-h-0",children:[jn&&n("div",{className:"shrink-0 flex items-center justify-center cursor-pointer hover:bg-[#3d3d3d] transition-colors",style:{width:8,backgroundColor:"#2d2d2d"},onClick:hl,title:"Expand editor",children:n("svg",{width:"6",height:"10",viewBox:"0 0 6 10",fill:"none",stroke:"#888",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M1 1l4 4-4 4"})})}),c("aside",{className:"bg-[#1e1e1e] shrink-0 flex flex-col overflow-hidden",style:{...jn?{display:"none"}:ul!==null?{width:`${ul}px`}:{width:"50%"}},children:[_&&ve&&c("div",{className:"px-3 py-2 text-xs flex items-center justify-between",style:{background:"#2a1f00",borderBottom:"1px solid #3d2e00",color:"#f0c040"},children:[c("span",{children:["Viewing an older version of"," ",n("strong",{children:ve.name}),". A newer version exists."]}),n("a",{href:`/editor/entity/${_}`,className:"px-2 py-0.5 rounded text-xs",style:{background:"#3d2e00",color:"#f0c040",textDecoration:"none"},children:"View latest"})]}),n(N3,{activeTab:nt,onTabChange:ne=>{gt(ne),ne==="build"&&Nn(!0),fetch("/api/telemetry-page-view",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({route:`/editor/${ne}`})}).catch(()=>{})},buildIdle:xe,claudeBuilding:He,buildReady:C==null||C>=18,projectTitle:x,breadcrumbItems:nt==="data"?jl:Nl,onBreadcrumbNavigate:nt==="data"?Za:_l}),c("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:[_r&&c("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:nt==="build"?"visible":"hidden"},children:[n(f5,{projectTitle:x,featureName:y,editorStep:C,editorStepLabel:k,migrationMode:T}),n("div",{className:"flex-1 min-h-0",style:Ja?{flex:"1 1 50%"}:void 0,children:Kt==="provider-switch"&&L?n(o5,{from:L.from,to:L.to,lastStep:L.lastStep,lastStepLabel:L.lastStepLabel,handoffSummary:L.handoffSummary,featureName:y,onContinue:()=>void us(),onStartFresh:()=>void ps()}):Kt==="pending"?n(i5,{featureName:y,editorStep:C,editorStepLabel:k,onContinue:cs,onStartFresh:ds}):c("div",{className:"relative h-full",children:[n(ku,{ref:S,entityName:"Editor",projectSlug:t,entityFilePath:null,scenarioName:null,onRefreshPreview:wh,onShowResults:mh,onHideResults:fl,onSetViewport:fh,onDataMutationForwarded:vh,onFeatureComplete:ms,editorMode:!0,onIdleChange:ot,onBuildingChange:ch,notificationSettings:gl,buildTabActive:nt==="build",claudeStartMode:Kt==="continue"?"resume":"fresh",claudeSessionId:j,editorStepLabel:k,resultsOpen:Ja}),hs==="choosing"&&n(l5,{onStartNextFeature:fs,onContinueInSession:gs})]})}),Ja&&n("div",{style:{flex:"1 1 50%"},className:"min-h-0 border-t-2 border-gray-300",children:n(_5,{scenarios:a,allScenarios:o,glossaryFunctions:d,cachedTestResults:R,projectRoot:r,activeScenarioId:te,onScenarioSelect:Zn,onClose:fl,entityChangeStatus:m,modifiedFiles:f,featureName:y,userPrompt:g})})]}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:nt==="app"?"visible":"hidden"},children:n(v3,{hasProject:s,scenarios:o,analyzedEntities:i,allEntities:l,glossaryFunctions:d,cachedTestResults:R,glossaryEntries:u,projectRoot:r,activeScenarioId:te,onScenarioSelect:Zn,onAnalyzedScenarioSelect:Sr,onSwitchToBuild:jr,onSwitchToHistory:Ya,zoomComponent:je,focusedEntity:ve,onZoomChange:_l,entityImports:p,pageFilePaths:h,projectTitle:x,projectDescription:b,breadcrumbItems:Nl,migrationMode:T,migrationState:D,onStartMigration:Ua,onReseedPreview:jh,isAdmin:F,roadmapView:z,onRoadmapViewChange:B,designSystemView:H,onDesignSystemViewChange:re,onPreviewDesignSystem:()=>{me(ne=>ne+1)},techStackView:ae,onTechStackViewChange:X,buildIdle:xe,onScreenshotClick:Pl,onNavigateToComponent:kh})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:nt==="data"?"visible":"hidden"},children:kl?n(oh,{focusedEntity:kl,breadcrumbItems:jl,onZoomChange:Za,projectRoot:r,scenarios:o,analyzedEntities:[],activeScenarioId:te,onScenarioSelect:Zn,onAnalyzedScenarioSelect:Sr,onSwitchToBuild:jr,entityImports:p,glossaryFunctions:d,cachedTestResults:R,glossaryEntries:u,entityShaMap:qn,componentGroups:Ga,visualEntities:[],isEntityComplete:()=>!0}):n(g5,{scenarios:o,projectRoot:r,activeScenarioId:te,onScenarioSelect:Zn,zoomComponent:void 0,focusedEntity:null,onZoomChange:Za,analyzedEntities:[],glossaryFunctions:d,cachedTestResults:R,activeAnalyzedScenarioId:qe==null?void 0:qe.scenarioId,onAnalyzedScenarioSelect:Sr,entityImports:p,pageFilePaths:h,onSwitchToBuild:jr,entityShaMap:qn,structureTab:Ch,onStructureTabChange:Cl})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:nt==="history"?"visible":"hidden"},children:n(Y5,{isActive:nt==="history",onScreenshotClick:Pl,glossaryFunctions:d,cachedTestResults:R})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:nt==="settings"?"visible":"hidden"},children:c("div",{className:"flex-1 overflow-auto p-4",children:[n("h2",{className:"text-sm font-semibold text-white mb-4",children:"Settings"}),n("p",{className:"text-xs text-gray-400",children:"Settings panel coming soon."})]})})]}),n(Cu,{serverUrl:he,isStarting:ye,projectSlug:t,devServerError:Re,onStartServer:Je?Ge:void 0,notificationSettings:gl,onChangeNotificationSettings:gh})]}),!jn&&!Wa&&n(S3,{onMouseDown:dh,onDoubleClick:uh,isDragging:pl}),Wa&&n("div",{className:"shrink-0 flex items-center justify-center cursor-pointer hover:bg-[#3d3d3d] transition-colors",style:{width:8,backgroundColor:"#2d2d2d"},onClick:hh,title:"Expand preview",children:n("svg",{width:"6",height:"10",viewBox:"0 0 6 10",fill:"none",stroke:"#888",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M5 1l-4 4 4 4"})})}),c("div",{className:"flex-1 flex flex-col min-w-0",style:{...Wa?{display:"none"}:void 0,...pl?{pointerEvents:"none"}:void 0},children:[c("div",{className:"bg-[#2d2d2d] border-b border-[#3d3d3d] shrink-0 z-10 h-10 flex items-center pr-4 relative",children:[n("div",{className:"flex items-center gap-1 shrink-0 z-10",children:n("button",{onClick:()=>{jn?(hl(),setTimeout(()=>{var ne;return(ne=S.current)==null?void 0:ne.focus()},50)):ph()},className:`p-1.5 rounded transition-colors cursor-pointer ${jn?"text-white bg-[#666] hover:bg-[#777]":"text-gray-500 hover:text-gray-300"}`,title:jn?"Show chat":"Hide chat",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:jn?c(we,{children:[n("path",{d:"M13 17l5-5-5-5"}),n("path",{d:"M6 17l5-5-5-5"})]}):c(we,{children:[n("path",{d:"M11 17l-5-5 5-5"}),n("path",{d:"M18 17l-5-5 5-5"})]})})})}),n("div",{className:"absolute inset-0 flex items-center justify-center gap-1 pointer-events-none",children:c("div",{className:"flex items-center gap-1 pointer-events-auto",children:[Tr.map(ne=>{const ge=Hs(ne),Ne=ge==="desktop"?"Desktop":ge==="laptop"?"Laptop":ge==="tablet"?"Tablet":"Mobile";return c("button",{onClick:()=>{dt&&kr(!1),_h(ne)},className:`p-1.5 rounded transition-colors cursor-pointer ${!dt&&Le.name===ne.name?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:`${ne.name} (${ne.width}×${ne.height})`,children:[Ne==="Desktop"&&c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n("path",{d:"M8 21h8M12 17v4"})]}),Ne==="Laptop"&&c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8H4V6z"}),n("path",{d:"M2 18h20"})]}),Ne==="Tablet"&&c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]}),Ne==="Mobile"&&c("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("rect",{x:"7",y:"2",width:"10",height:"20",rx:"2"}),n("path",{d:"M12 18h.01"})]})]},ne.name)}),c("div",{className:"relative",children:[c("button",{onClick:()=>{dt||Cr(ne=>!ne)},className:`flex items-center gap-1.5 px-2 py-1 rounded transition-colors ${dt?"":"cursor-pointer"} ${dt||as||!Tr.some(ne=>ne.name===Le.name)?"text-white bg-[#555]":"text-gray-400 hover:text-gray-200 hover:bg-[#444]"}`,title:"Custom dimensions",children:[n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:n("path",{d:"M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})}),n("span",{className:"text-xs font-mono",children:dt&&_n?`${Math.round(_n.width)} × ${Math.round(_n.height)}`:`${Le.width} × ${Le.height??900}`})]}),as&&n(fy,{currentWidth:Le.width,currentHeight:Le.height??900,devicePresets:Tr,customSizes:Ka,onApply:Ph,onSave:Eh,onRemove:Sh,onClose:()=>Cr(!1)})]}),n("button",{onClick:()=>{kr(ne=>!ne)},className:`p-1.5 rounded transition-colors cursor-pointer ${dt?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:dt?"Exit fullscreen":"Fill page with preview",children:n("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:dt?c(we,{children:[n("polyline",{points:"4 14 10 14 10 20"}),n("polyline",{points:"20 10 14 10 14 4"}),n("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),n("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):c(we,{children:[n("polyline",{points:"15 3 21 3 21 9"}),n("polyline",{points:"9 21 3 21 3 15"}),n("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),n("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})}),n("button",{onClick:()=>{const ne=Xa||Xn;ne&&window.open(ne,"_blank")},className:"p-1.5 rounded text-gray-500 hover:text-gray-300 transition-colors cursor-pointer",title:"Open preview in new window",children:c("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n("polyline",{points:"15 3 21 3 21 9"}),n("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})})]})})]}),xh&&n(P3,{onSaveToCurrent:()=>void vl("overwrite"),onSaveAsNew:()=>void vl("new"),onDismiss:()=>Kn(!1),isSaving:bh,scenarioName:(Ml=o.find(ne=>{var ge;return ne.id===(te||((ge=js(o))==null?void 0:ge.id))}))==null?void 0:Ml.name}),n("div",{ref:I,className:`flex-1 flex overflow-hidden ${dt||wn?"":"items-center justify-center p-8"}`,style:dt?{backgroundColor:"#fff"}:wn?{backgroundImage:`
756
+ linear-gradient(45deg, #333 25%, transparent 25%),
757
+ linear-gradient(-45deg, #333 25%, transparent 25%),
758
+ linear-gradient(45deg, transparent 75%, #333 75%),
759
+ linear-gradient(-45deg, transparent 75%, #333 75%)
760
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#2d2d2d"}:ht?{backgroundColor:"#1e1e1e"}:{backgroundImage:`
761
+ linear-gradient(45deg, #333 25%, transparent 25%),
762
+ linear-gradient(-45deg, #333 25%, transparent 25%),
763
+ linear-gradient(45deg, transparent 75%, #333 75%),
764
+ linear-gradient(-45deg, transparent 75%, #333 75%)
765
+ `,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#2d2d2d"},children:wn?n(k3,{preview:wn,viewportWidth:Le.width,viewportHeight:Le.height??900,scale:ln,onDismiss:()=>Dt(null),onLoadCommit:ft}):ht?n(_3,{preview:ht,viewportWidth:Le.width,viewportHeight:Le.height??900,scale:ln,onDismiss:()=>mt(null)}):Xn?dt?c("div",{className:"relative w-full h-full bg-white",children:[!vr&&!ys&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center justify-center gap-6 bg-[#2a2a2a] rounded-lg p-8 w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Qt,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the app to render"})]})]})}),ys&&n("div",{className:"absolute inset-0 z-20 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.25)",backdropFilter:"blur(1px)",transition:"opacity 200ms ease-out"},children:c("div",{className:"flex flex-col items-center gap-3 animate-pulse",children:[n("svg",{className:"w-6 h-6 text-white/80 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"50 100"})}),n("span",{className:"text-white/70 text-xs font-['IBM_Plex_Sans']",children:"Switching scenario"})]})}),n("iframe",{ref:$,src:Xa||Xn,className:"w-full h-full border-none",title:"Editor preview",onLoad:Al,style:{opacity:vr?1:0}},Hn)]}):n("div",{style:{width:`${(Ar?Le.width+Rs.width:Le.width)*ln}px`,height:`${(Ar?(Le.height??900)+Rs.height:Le.height??900)*ln}px`},children:n("div",{className:"origin-top-left",style:{transform:ln<1?`scale(${ln})`:void 0},children:n(a5,{width:Le.width,height:Le.height??900,enabled:Ar,children:c("div",{className:"relative bg-white",style:{width:`${Le.width}px`,height:`${Le.height??900}px`},children:[!vr&&!ys&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:c("div",{className:"flex flex-col items-center justify-center gap-6 bg-[#2a2a2a] rounded-lg p-8 w-[500px] h-[300px]",children:[n("div",{className:"mb-4",children:n(Qt,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Loading Preview"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Waiting for the app to render"})]})]})}),ys&&n("div",{className:"absolute inset-0 z-20 flex items-center justify-center",style:{backgroundColor:"rgba(0, 0, 0, 0.25)",backdropFilter:"blur(1px)",transition:"opacity 200ms ease-out"},children:c("div",{className:"flex flex-col items-center gap-3 animate-pulse",children:[n("svg",{className:"w-6 h-6 text-white/80 animate-spin",viewBox:"0 0 24 24",fill:"none",children:n("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"50 100"})}),n("span",{className:"text-white/70 text-xs font-['IBM_Plex_Sans']",children:"Switching scenario"})]})}),n("iframe",{ref:$,src:Xa||Xn,className:"w-full h-full border-none",title:"Editor preview",onLoad:Al,style:{opacity:vr?1:0}},Hn)]})})})}):n("div",{className:"bg-[#2a2a2a] rounded-lg flex flex-col items-center justify-center",style:{width:`${Le.width*ln}px`,height:`${(Le.height??900)*ln}px`},children:Re?c("div",{className:"flex flex-col gap-4 text-center px-8 max-w-[600px]",children:[n("h2",{className:"text-xl font-medium text-red-400 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Dev Server Failed"}),n("pre",{className:"text-xs text-left bg-[#1e1e1e] text-gray-300 p-4 rounded overflow-auto max-h-[300px] w-full font-mono whitespace-pre-wrap",children:Re}),n("button",{onClick:bt,className:"mx-auto px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded hover:bg-[#004d63] transition-colors cursor-pointer",children:"Retry"})]}):ye||Nr?c(we,{children:[n("div",{className:"mb-4",children:n(Qt,{})}),c("div",{className:"flex flex-col gap-3 text-center",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:Nr?"Starting Interactive Mode":"Starting Dev Server"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:Nr?"Loading component preview...":"Your dev server is starting up..."})]})]}):c("div",{className:"flex flex-col gap-3 text-center px-8",children:[n("h2",{className:"text-xl font-medium text-gray-200 leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Live Preview"}),n("p",{className:"text-sm text-gray-500 leading-5 m-0 font-['IBM_Plex_Sans']",children:"Describe what you want to build in the Build tab"})]})})})]})]})]})}),n($d,{})]})}),J3=Object.freeze(Object.defineProperty({__proto__:null,default:W3,loader:Y3,meta:B3,shouldRevalidate:L3},Symbol.toStringTag,{value:"Module"})),H3=tt(function(){return null}),rr=Object.freeze(Object.defineProperty({__proto__:null,default:H3},Symbol.toStringTag,{value:"Module"})),Xj={entry:{module:"/assets/entry.client-j1Vi0bco.js",imports:["/assets/jsx-runtime-D_zvdyIk.js","/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/index-vyrZD2g4.js"],css:[]},routes:{root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!0,module:"/assets/root-CLedrjXQ.js",imports:["/assets/jsx-runtime-D_zvdyIk.js","/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/index-vyrZD2g4.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/ReportIssueModal-DQsceHVv.js","/assets/useReportContext-jkCytuYz.js","/assets/loader-circle-D-q28GLF.js","/assets/createLucideIcon-BwyFiRot.js","/assets/book-open-BFSIqZgO.js","/assets/useToast-BgqkixU9.js","/assets/useLastLogLine-C8QvIe05.js","/assets/LogViewer-C-9zQdXg.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/chevron-down-B9fDzFVh.js","/assets/circle-check-DLPObLUx.js","/assets/CopyButton-DTBZZfSk.js","/assets/triangle-alert-D87ekDl8.js","/assets/copy-DXEmO0TD.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-DziaVQX1.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/Spinner-CIil5-gb.js","/assets/useLastLogLine-C8QvIe05.js","/assets/ViewportInspectBar-BqkA9zyZ.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/InlineSpinner-ByaELMbv.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.scenarios.$scenarioId.dev":{id:"routes/entity.$sha.scenarios.$scenarioId.dev",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/dev",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.dev-C8AyYgYT.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/Spinner-CIil5-gb.js","/assets/useLastLogLine-C8QvIe05.js","/assets/ViewportInspectBar-BqkA9zyZ.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/InlineSpinner-ByaELMbv.js","/assets/editorPreview-C6fEYHrh.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/preload-helper-ckwbz45p.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-switch-scenario":{id:"routes/api.interactive-switch-scenario",parentId:"root",path:"api/interactive-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-switch-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-save-scenario-data":{id:"routes/api.editor-save-scenario-data",parentId:"root",path:"api/editor-save-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-save-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-D_O_ajfZ.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/InteractivePreview-6WjVfhxX.js","/assets/Spinner-CIil5-gb.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C8QvIe05.js","/assets/InlineSpinner-ByaELMbv.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-register-scenario":{id:"routes/api.editor-register-scenario",parentId:"root",path:"api/editor-register-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-register-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-coverage":{id:"routes/api.editor-scenario-coverage",parentId:"root",path:"api/editor-scenario-coverage",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-coverage-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-BTcpgIpC.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/InteractivePreview-6WjVfhxX.js","/assets/Spinner-CIil5-gb.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-C8QvIe05.js","/assets/InlineSpinner-ByaELMbv.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-capture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-database-verify":{id:"routes/api.editor-database-verify",parentId:"root",path:"api/editor-database-verify",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-database-verify-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-image._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-recapture-stale":{id:"routes/api.editor-recapture-stale",parentId:"root",path:"api/editor-recapture-stale",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-recapture-stale-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-rename-scenario":{id:"routes/api.editor-rename-scenario",parentId:"root",path:"api/editor-rename-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-rename-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-save-seed-state":{id:"routes/api.editor-save-seed-state",parentId:"root",path:"api/editor-save-seed-state",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-save-seed-state-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-prompt":{id:"routes/api.editor-scenario-prompt",parentId:"root",path:"api/editor-scenario-prompt",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-prompt-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-switch-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.generate-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-hosting-verify":{id:"routes/api.editor-hosting-verify",parentId:"root",path:"api/editor-hosting-verify",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-hosting-verify-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-update-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-client-errors-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-entity-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-github-verify":{id:"routes/api.editor-github-verify",parentId:"root",path:"api/editor-github-verify",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-github-verify-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-entry-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenario-data-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-verify-routes":{id:"routes/api.editor-verify-routes",parentId:"root",path:"api/editor-verify-routes",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-verify-routes-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.llm-calls._entitySha-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-project-info":{id:"routes/api.editor-project-info",parentId:"root",path:"api/editor-project-info",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-project-info-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-test-results-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.branch-entity-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.capture-screenshot-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-load-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.agent-transcripts-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-dev-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.logs._projectSlug-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-diff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.execute-function-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.interactive-mode-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.delete-scenario-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.dev-mode-events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.generate-report-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-handoff":{id:"routes/api.editor-handoff",parentId:"root",path:"api/editor-handoff",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-handoff-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-journal-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-refresh-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-roadmap":{id:"routes/api.editor-roadmap",parentId:"root",path:"api/editor-roadmap",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-roadmap-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-session":{id:"routes/api.editor-session",parentId:"root",path:"api/editor-session",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-session-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.memory-profile-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.process-status-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.restart-server-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/agent-transcripts-B8NCeOrm.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/createLucideIcon-BwyFiRot.js","/assets/terminal-DHemCJIs.js","/assets/search-BooqacKS.js","/assets/chevron-down-B9fDzFVh.js","/assets/book-open-BFSIqZgO.js","/assets/triangle-alert-D87ekDl8.js","/assets/copy-DXEmO0TD.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-commit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-schema":{id:"routes/api.editor-schema",parentId:"root",path:"api/editor-schema",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-schema-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-audit-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.kill-process-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.save-fixture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.screenshot._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-DqM9hbNE.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/LogViewer-C-9zQdXg.js","/assets/useLastLogLine-C8QvIe05.js","/assets/useReportContext-jkCytuYz.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/EntityTypeBadge-CQgyEGV-.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LoadingDots-By5zI316.js","/assets/loader-circle-D-q28GLF.js","/assets/pause-BP6fitdh.js","/assets/createLucideIcon-BwyFiRot.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.debug-setup-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.editor-file-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.labs-unlock-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.recapture-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.rule-path-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/entity._sha._-pc-vc6wO.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useLastLogLine-C8QvIe05.js","/assets/Spinner-CIil5-gb.js","/assets/InteractivePreview-6WjVfhxX.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LibraryFunctionPreview-ChX-Hp7W.js","/assets/LoadingDots-By5zI316.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-Cl4oOA3A.js","/assets/createLucideIcon-BwyFiRot.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/CopyButton-DTBZZfSk.js","/assets/LogViewer-C-9zQdXg.js","/assets/MiniClaudeChat-Bs2_Oua4.js","/assets/useReportContext-jkCytuYz.js","/assets/preload-helper-ckwbz45p.js","/assets/InlineSpinner-ByaELMbv.js","/assets/ViewportInspectBar-BqkA9zyZ.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/ReportIssueModal-DQsceHVv.js","/assets/circle-check-DLPObLUx.js","/assets/triangle-alert-D87ekDl8.js","/assets/copy-DXEmO0TD.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.analyze-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/simulations-ovy6FjRY.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LoadingDots-By5zI316.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/chevron-down-B9fDzFVh.js","/assets/search-BooqacKS.js","/assets/loader-circle-D-q28GLF.js","/assets/createLucideIcon-BwyFiRot.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.events-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.health-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.memory-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/api.queue-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/dev.empty-iRhRIFlp.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/ScenarioViewer-Cl4oOA3A.js","/assets/InteractivePreview-6WjVfhxX.js","/assets/ViewportInspectBar-BqkA9zyZ.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/LogViewer-C-9zQdXg.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/useLastLogLine-C8QvIe05.js","/assets/Spinner-CIil5-gb.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-DQsceHVv.js","/assets/createLucideIcon-BwyFiRot.js","/assets/circle-check-DLPObLUx.js","/assets/triangle-alert-D87ekDl8.js","/assets/copy-DXEmO0TD.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/InlineSpinner-ByaELMbv.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/settings-BM0nbryO.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/CopyButton-DTBZZfSk.js","/assets/copy-DXEmO0TD.js","/assets/createLucideIcon-BwyFiRot.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!1,hasErrorBoundary:!1,module:"/assets/static._-l0sNRNKZ.js",imports:[],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/_index-DnOgyseQ.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useLastLogLine-C8QvIe05.js","/assets/useToast-BgqkixU9.js","/assets/useReportContext-jkCytuYz.js","/assets/LogViewer-C-9zQdXg.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-BwyFiRot.js","/assets/circle-check-DLPObLUx.js","/assets/loader-circle-D-q28GLF.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/memory-CEWIUC4t.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/createLucideIcon-BwyFiRot.js","/assets/terminal-DHemCJIs.js","/assets/copy-DXEmO0TD.js","/assets/CopyButton-DTBZZfSk.js","/assets/chevron-down-B9fDzFVh.js","/assets/search-BooqacKS.js","/assets/pause-BP6fitdh.js","/assets/book-open-BFSIqZgO.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/files-kuny2Q_s.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/EntityItem-BxclONWq.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/chevron-down-B9fDzFVh.js","/assets/search-BooqacKS.js","/assets/createLucideIcon-BwyFiRot.js","/assets/useToast-BgqkixU9.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LibraryFunctionPreview-ChX-Hp7W.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-D87ekDl8.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/EntityTypeBadge-CQgyEGV-.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/labs-c3yLxSEp.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,hasAction:!0,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/git-DgCZPMie.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-jkCytuYz.js","/assets/EntityItem-BxclONWq.js","/assets/LogViewer-C-9zQdXg.js","/assets/index-SqjQKTdH.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/createLucideIcon-BwyFiRot.js","/assets/useToast-BgqkixU9.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/SafeScreenshot-DThcm_9M.js","/assets/LibraryFunctionPreview-ChX-Hp7W.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-D87ekDl8.js","/assets/EntityTypeIcon-BsnEOJZ_.js","/assets/EntityTypeBadge-CQgyEGV-.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"routes/editor.entity.($sha)":{id:"routes/editor.entity.($sha)",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!0,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor.entity.(_sha)-DOXe0Qx7.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useCustomSizes-Dk0Tciqg.js","/assets/editorPreview-C6fEYHrh.js","/assets/CopyButton-DTBZZfSk.js","/assets/MiniClaudeChat-Bs2_Oua4.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-Coe5NhbS.js","/assets/Spinner-CIil5-gb.js","/assets/copy-DXEmO0TD.js","/assets/createLucideIcon-BwyFiRot.js","/assets/useLastLogLine-C8QvIe05.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-index":{id:"editor-tab-index",parentId:"routes/editor.entity.($sha)",path:void 0,index:!0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-build":{id:"editor-tab-build",parentId:"routes/editor.entity.($sha)",path:"build",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-structure":{id:"editor-tab-structure",parentId:"routes/editor.entity.($sha)",path:"structure",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-history":{id:"editor-tab-history",parentId:"routes/editor.entity.($sha)",path:"history",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-settings":{id:"editor-tab-settings",parentId:"routes/editor.entity.($sha)",path:"settings",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-entity":{id:"editor-tab-entity",parentId:"routes/editor.entity.($sha)",path:"entity/:sha",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-BZPBzV73.js",imports:["/assets/chunk-UVKPFVEO-Bmq2apuh.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-30c44d84.js",version:"30c44d84",sri:void 0},e_="build/client",t_="/",n_={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,unstable_previewServerPrerendering:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},r_=!0,s_=!1,a_=[],o_={mode:"lazy",manifestPath:"/__manifest"},i_="/",l_={module:ef},c_={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:hy},"routes/entity.$sha.scenarios.$scenarioId.fullscreen":{id:"routes/entity.$sha.scenarios.$scenarioId.fullscreen",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/fullscreen",index:void 0,caseSensitive:void 0,module:by},"routes/entity.$sha.scenarios.$scenarioId.dev":{id:"routes/entity.$sha.scenarios.$scenarioId.dev",parentId:"root",path:"entity/:sha/scenarios/:scenarioId/dev",index:void 0,caseSensitive:void 0,module:Zy},"routes/api.interactive-switch-scenario":{id:"routes/api.interactive-switch-scenario",parentId:"root",path:"api/interactive-switch-scenario",index:void 0,caseSensitive:void 0,module:$x},"routes/api.editor-journal-screenshot":{id:"routes/api.editor-journal-screenshot",parentId:"root",path:"api/editor-journal-screenshot",index:void 0,caseSensitive:void 0,module:Dx},"routes/api.editor-save-scenario-data":{id:"routes/api.editor-save-scenario-data",parentId:"root",path:"api/editor-save-scenario-data",index:void 0,caseSensitive:void 0,module:Ix},"routes/entity.$sha_.edit.$scenarioId":{id:"routes/entity.$sha_.edit.$scenarioId",parentId:"root",path:"entity/:sha/edit/:scenarioId",index:void 0,caseSensitive:void 0,module:ab},"routes/api.editor-register-scenario":{id:"routes/api.editor-register-scenario",parentId:"root",path:"api/editor-register-scenario",index:void 0,caseSensitive:void 0,module:Eb},"routes/api.editor-scenario-coverage":{id:"routes/api.editor-scenario-coverage",parentId:"root",path:"api/editor-scenario-coverage",index:void 0,caseSensitive:void 0,module:Mb},"routes/entity.$sha_.create-scenario":{id:"routes/entity.$sha_.create-scenario",parentId:"root",path:"entity/:sha/create-scenario",index:void 0,caseSensitive:void 0,module:Lb},"routes/api.editor-capture-scenario":{id:"routes/api.editor-capture-scenario",parentId:"root",path:"api/editor-capture-scenario",index:void 0,caseSensitive:void 0,module:Yb},"routes/api.editor-scenario-image.$":{id:"routes/api.editor-scenario-image.$",parentId:"root",path:"api/editor-scenario-image/*",index:void 0,caseSensitive:void 0,module:Wb},"routes/api.editor-database-verify":{id:"routes/api.editor-database-verify",parentId:"root",path:"api/editor-database-verify",index:void 0,caseSensitive:void 0,module:qb},"routes/api.editor-journal-image.$":{id:"routes/api.editor-journal-image.$",parentId:"root",path:"api/editor-journal-image/*",index:void 0,caseSensitive:void 0,module:Zb},"routes/api.editor-recapture-stale":{id:"routes/api.editor-recapture-stale",parentId:"root",path:"api/editor-recapture-stale",index:void 0,caseSensitive:void 0,module:pv},"routes/api.editor-rename-scenario":{id:"routes/api.editor-rename-scenario",parentId:"root",path:"api/editor-rename-scenario",index:void 0,caseSensitive:void 0,module:mv},"routes/api.editor-save-seed-state":{id:"routes/api.editor-save-seed-state",parentId:"root",path:"api/editor-save-seed-state",index:void 0,caseSensitive:void 0,module:gv},"routes/api.editor-scenario-prompt":{id:"routes/api.editor-scenario-prompt",parentId:"root",path:"api/editor-scenario-prompt",index:void 0,caseSensitive:void 0,module:xv},"routes/api.editor-switch-scenario":{id:"routes/api.editor-switch-scenario",parentId:"root",path:"api/editor-switch-scenario",index:void 0,caseSensitive:void 0,module:vv},"routes/api.generate-scenario-data":{id:"routes/api.generate-scenario-data",parentId:"root",path:"api/generate-scenario-data",index:void 0,caseSensitive:void 0,module:Pw},"routes/api.editor-hosting-verify":{id:"routes/api.editor-hosting-verify",parentId:"root",path:"api/editor-hosting-verify",index:void 0,caseSensitive:void 0,module:Mw},"routes/api.editor-journal-update":{id:"routes/api.editor-journal-update",parentId:"root",path:"api/editor-journal-update",index:void 0,caseSensitive:void 0,module:Jw},"routes/api.editor-client-errors":{id:"routes/api.editor-client-errors",parentId:"root",path:"api/editor-client-errors",index:void 0,caseSensitive:void 0,module:Vw},"routes/api.editor-entity-status":{id:"routes/api.editor-entity-status",parentId:"root",path:"api/editor-entity-status",index:void 0,caseSensitive:void 0,module:Gw},"routes/api.editor-github-verify":{id:"routes/api.editor-github-verify",parentId:"root",path:"api/editor-github-verify",index:void 0,caseSensitive:void 0,module:eN},"routes/api.editor-journal-entry":{id:"routes/api.editor-journal-entry",parentId:"root",path:"api/editor-journal-entry",index:void 0,caseSensitive:void 0,module:nN},"routes/api.editor-scenario-data":{id:"routes/api.editor-scenario-data",parentId:"root",path:"api/editor-scenario-data",index:void 0,caseSensitive:void 0,module:sN},"routes/api.editor-verify-routes":{id:"routes/api.editor-verify-routes",parentId:"root",path:"api/editor-verify-routes",index:void 0,caseSensitive:void 0,module:oN},"routes/api.llm-calls.$entitySha":{id:"routes/api.llm-calls.$entitySha",parentId:"root",path:"api/llm-calls/:entitySha",index:void 0,caseSensitive:void 0,module:cN},"routes/api.editor-project-info":{id:"routes/api.editor-project-info",parentId:"root",path:"api/editor-project-info",index:void 0,caseSensitive:void 0,module:pN},"routes/api.editor-test-results":{id:"routes/api.editor-test-results",parentId:"root",path:"api/editor-test-results",index:void 0,caseSensitive:void 0,module:NN},"routes/api.branch-entity-diff":{id:"routes/api.branch-entity-diff",parentId:"root",path:"api/branch-entity-diff",index:void 0,caseSensitive:void 0,module:PN},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:TN},"routes/api.editor-load-commit":{id:"routes/api.editor-load-commit",parentId:"root",path:"api/editor-load-commit",index:void 0,caseSensitive:void 0,module:YN},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:HN},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:o1},"routes/api.editor-dev-server":{id:"routes/api.editor-dev-server",parentId:"root",path:"api/editor-dev-server",index:void 0,caseSensitive:void 0,module:d1},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:h1},"routes/api.editor-file-diff":{id:"routes/api.editor-file-diff",parentId:"root",path:"api/editor-file-diff",index:void 0,caseSensitive:void 0,module:f1},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,module:y1},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:v1},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:S1},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:k1},"routes/api.dev-mode-events":{id:"routes/api.dev-mode-events",parentId:"root",path:"api/dev-mode-events",index:void 0,caseSensitive:void 0,module:E1},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:L1},"routes/api.editor-handoff":{id:"routes/api.editor-handoff",parentId:"root",path:"api/editor-handoff",index:void 0,caseSensitive:void 0,module:W1},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,module:H1},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,module:eS},"routes/api.editor-roadmap":{id:"routes/api.editor-roadmap",parentId:"root",path:"api/editor-roadmap",index:void 0,caseSensitive:void 0,module:mS},"routes/api.editor-session":{id:"routes/api.editor-session",parentId:"root",path:"api/editor-session",index:void 0,caseSensitive:void 0,module:gS},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:wS},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:kS},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:PS},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:TS},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:VS},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,module:GS},"routes/api.editor-schema":{id:"routes/api.editor-schema",parentId:"root",path:"api/editor-schema",index:void 0,caseSensitive:void 0,module:XS},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,module:tC},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:rC},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:cC},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:uC},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:wC},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:CC},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,module:jC},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:AC},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:MC},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,module:IC},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:i2},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:d2},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:y2},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:b2},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:w2},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:D2},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:O2},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:z2},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:K2},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:q2},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:ak},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:Ak},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Rk},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:Jk},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:n5},"routes/editor.entity.($sha)":{id:"routes/editor.entity.($sha)",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,module:J3},"editor-tab-index":{id:"editor-tab-index",parentId:"routes/editor.entity.($sha)",path:void 0,index:!0,caseSensitive:void 0,module:rr},"editor-tab-build":{id:"editor-tab-build",parentId:"routes/editor.entity.($sha)",path:"build",index:void 0,caseSensitive:void 0,module:rr},"editor-tab-structure":{id:"editor-tab-structure",parentId:"routes/editor.entity.($sha)",path:"structure",index:void 0,caseSensitive:void 0,module:rr},"editor-tab-history":{id:"editor-tab-history",parentId:"routes/editor.entity.($sha)",path:"history",index:void 0,caseSensitive:void 0,module:rr},"editor-tab-settings":{id:"editor-tab-settings",parentId:"routes/editor.entity.($sha)",path:"settings",index:void 0,caseSensitive:void 0,module:rr},"editor-tab-entity":{id:"editor-tab-entity",parentId:"routes/editor.entity.($sha)",path:"entity/:sha",index:void 0,caseSensitive:void 0,module:rr}},d_=!1;export{Vf as $,Yg as A,Lg as B,Jg as C,Rg as D,$e as E,og as F,ig as G,zn as H,zj as I,kf as J,_f as K,Ef as L,Pf as M,Gd as N,Tf as O,Mf as P,qd as Q,Ff as R,Df as S,qf as T,Qd as U,Lf as V,zf as W,Yf as X,Uf as Y,Jf as Z,Hf as _,xf as a,Kf as a0,Sf as a1,Cf as a2,Gf as a3,Xs as a4,Zf as a5,Xf as a6,eg as a7,tg as a8,rg as a9,s_ as aA,a_ as aB,o_ as aC,i_ as aD,l_ as aE,c_ as aF,d_ as aG,Xj as aH,ng as aa,Hj as ab,xi as ac,Vj as ad,Gj as ae,Kj as af,Jj as ag,Zj as ah,Ie as ai,r0 as aj,t0 as ak,m0 as al,ts as am,Yj as an,ru as ao,qg as ap,Qg as aq,q1 as ar,Qj as as,vn as at,Uj as au,Wj as av,e_ as aw,t_ as ax,n_ as ay,r_ as az,In as b,Rn as c,en as d,es as e,hi as f,ga as g,Kd as h,gf as i,vg as j,wg as k,yn as l,tn as m,fi as n,Pg as o,ta as p,et as q,eu as r,tu as s,gi as t,hn as u,nu as v,mr as w,ir as x,xg as y,Vl as z};