@codeyam/codeyam-cli 0.1.20 → 0.1.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/analyzer-template/.build-info.json +7 -7
- package/analyzer-template/log.txt +3 -3
- package/analyzer-template/package.json +1 -1
- package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +36 -9
- package/analyzer-template/packages/ai/src/lib/dataStructure/equivalencyManagers/ParentScopeManager.ts +10 -3
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +16 -6
- package/analyzer-template/packages/analyze/index.ts +4 -1
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +28 -2
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +5 -36
- package/analyzer-template/packages/analyze/src/lib/files/analyze/findOrCreateEntity.ts +1 -0
- package/analyzer-template/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.ts +21 -0
- package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +82 -10
- package/analyzer-template/packages/analyze/src/lib/files/analyzeChange.ts +4 -0
- package/analyzer-template/packages/analyze/src/lib/files/analyzeInitial.ts +4 -0
- package/analyzer-template/packages/analyze/src/lib/files/analyzeNextRoute.ts +8 -3
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +235 -58
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +170 -26
- package/analyzer-template/packages/aws/package.json +1 -1
- package/analyzer-template/packages/database/src/lib/loadEntity.ts +11 -4
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.d.ts +4 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.js +4 -4
- package/analyzer-template/packages/github/dist/database/src/lib/loadEntity.js.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts +3 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js +22 -1
- package/analyzer-template/packages/utils/dist/utils/src/lib/fs/rsyncCopy.js.map +1 -1
- package/analyzer-template/packages/utils/src/lib/fs/rsyncCopy.ts +27 -0
- package/codeyam-cli/src/commands/__tests__/editor.auditNoAutoAnalysis.test.js +63 -0
- package/codeyam-cli/src/commands/__tests__/editor.auditNoAutoAnalysis.test.js.map +1 -0
- package/codeyam-cli/src/commands/editor.js +553 -93
- package/codeyam-cli/src/commands/editor.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +991 -31
- package/codeyam-cli/src/utils/__tests__/editorAudit.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/editorPreview.test.js +11 -3
- package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js +33 -1
- package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js.map +1 -1
- package/codeyam-cli/src/utils/__tests__/manualEntityAnalysis.test.js +302 -0
- package/codeyam-cli/src/utils/__tests__/manualEntityAnalysis.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/registerScenarioResult.test.js +127 -0
- package/codeyam-cli/src/utils/__tests__/registerScenarioResult.test.js.map +1 -0
- package/codeyam-cli/src/utils/__tests__/testRunner.test.js +217 -0
- package/codeyam-cli/src/utils/__tests__/testRunner.test.js.map +1 -0
- package/codeyam-cli/src/utils/analysisRunner.js +28 -1
- package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
- package/codeyam-cli/src/utils/analyzer.js +11 -1
- package/codeyam-cli/src/utils/analyzer.js.map +1 -1
- package/codeyam-cli/src/utils/editorAudit.js +210 -14
- package/codeyam-cli/src/utils/editorAudit.js.map +1 -1
- package/codeyam-cli/src/utils/editorPreview.js +5 -3
- package/codeyam-cli/src/utils/editorPreview.js.map +1 -1
- package/codeyam-cli/src/utils/entityChangeStatus.server.js +16 -0
- package/codeyam-cli/src/utils/entityChangeStatus.server.js.map +1 -1
- package/codeyam-cli/src/utils/manualEntityAnalysis.js +196 -0
- package/codeyam-cli/src/utils/manualEntityAnalysis.js.map +1 -0
- package/codeyam-cli/src/utils/queue/job.js +20 -2
- package/codeyam-cli/src/utils/queue/job.js.map +1 -1
- package/codeyam-cli/src/utils/registerScenarioResult.js +52 -0
- package/codeyam-cli/src/utils/registerScenarioResult.js.map +1 -0
- package/codeyam-cli/src/utils/testRunner.js +199 -1
- package/codeyam-cli/src/utils/testRunner.js.map +1 -1
- package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js +35 -0
- package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js.map +1 -1
- package/codeyam-cli/src/webserver/app/lib/clientErrors.js +3 -0
- package/codeyam-cli/src/webserver/app/lib/clientErrors.js.map +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/MiniClaudeChat-CQENLSrF.js +36 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-save-scenario-data-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/api.editor-schema-l0sNRNKZ.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-Coe5NhbS.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{cy-logo-cli-CCKUIm0S.svg → cy-logo-cli-DoA97ML3.svg} +2 -2
- package/codeyam-cli/src/webserver/build/client/assets/editor.entity.(_sha)-aIHKLB-m.js +96 -0
- package/codeyam-cli/src/webserver/build/client/assets/editorPreview-CluPkvXJ.js +41 -0
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-Blfy9UlN.js → entity._sha._-ByHz6rAQ.js} +13 -12
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha.scenarios._scenarioId.dev-KTQuL0aj.js → entity._sha.scenarios._scenarioId.dev-CmLO432x.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/{entity._sha.scenarios._scenarioId.fullscreen-C6eeL24i.js → entity._sha.scenarios._scenarioId.fullscreen-Bz9sCUF_.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/globals-oyPmV37k.css +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/manifest-bcbb3d49.js +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{root-BxUQigda.js → root-D2_tktnk.js} +26 -13
- package/codeyam-cli/src/webserver/build/server/assets/analysisRunner-DjF-soOH.js +16 -0
- package/codeyam-cli/src/webserver/build/server/assets/{index-CjLhfz6Z.js → index-nAvHGWbz.js} +1 -1
- package/codeyam-cli/src/webserver/build/server/assets/{init-BEqlbI84.js → init-XhpIt-OT.js} +1 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-DVwiibFu.js +644 -0
- package/codeyam-cli/src/webserver/build/server/index.js +1 -1
- package/codeyam-cli/src/webserver/build-info.json +5 -5
- package/codeyam-cli/src/webserver/idleDetector.js +15 -0
- package/codeyam-cli/src/webserver/idleDetector.js.map +1 -1
- package/codeyam-cli/src/webserver/terminalServer.js +18 -5
- package/codeyam-cli/src/webserver/terminalServer.js.map +1 -1
- package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +2 -2
- package/package.json +1 -1
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +27 -10
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/ParentScopeManager.js +9 -2
- package/packages/ai/src/lib/dataStructure/equivalencyManagers/ParentScopeManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +14 -4
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
- package/packages/analyze/index.js +1 -1
- package/packages/analyze/index.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +16 -2
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +6 -26
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js +1 -0
- package/packages/analyze/src/lib/files/analyze/findOrCreateEntity.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js +14 -0
- package/packages/analyze/src/lib/files/analyze/trackEntityCircularDependencies.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +44 -11
- package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeChange.js +1 -0
- package/packages/analyze/src/lib/files/analyzeChange.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeInitial.js +1 -0
- package/packages/analyze/src/lib/files/analyzeInitial.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeNextRoute.js +5 -1
- package/packages/analyze/src/lib/files/analyzeNextRoute.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +116 -28
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +139 -24
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
- package/packages/database/src/lib/loadEntity.js +4 -4
- package/packages/database/src/lib/loadEntity.js.map +1 -1
- package/packages/utils/src/lib/fs/rsyncCopy.js +22 -1
- package/packages/utils/src/lib/fs/rsyncCopy.js.map +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/cy-logo-cli-DcX-ZS3p.js +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/editor.entity.(_sha)-DII1pg_z.js +0 -58
- package/codeyam-cli/src/webserver/build/client/assets/editorPreview-oepecPae.js +0 -41
- package/codeyam-cli/src/webserver/build/client/assets/globals-Yn9W3zp3.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/manifest-cdf2c0a7.js +0 -1
- package/codeyam-cli/src/webserver/build/server/assets/analysisRunner-B_PsTAb1.js +0 -13
- package/codeyam-cli/src/webserver/build/server/assets/server-build-YI63xTu4.js +0 -553
|
@@ -1,553 +0,0 @@
|
|
|
1
|
-
var cu=Object.defineProperty;var hi=e=>{throw TypeError(e)};var du=(e,t,r)=>t in e?cu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Rt=(e,t,r)=>du(e,typeof t!="symbol"?t+"":t,r),uu=(e,t,r)=>t.has(e)||hi("Cannot "+r);var fi=(e,t,r)=>(uu(e,t,"read from private field"),r?r.call(e):t.get(e)),gi=(e,t,r)=>t.has(e)?hi("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 d,Fragment as xe}from"react/jsx-runtime";import{PassThrough as pu}from"node:stream";import{createReadableStreamFromReadable as mu}from"@react-router/node";import{ServerRouter as hu,useFetcher as Ue,useLocation as Sr,useNavigate as Pt,Link as Ce,UNSAFE_withComponentProps as Qe,Meta as fu,Links as gu,ScrollRestoration as yu,Scripts as xu,UNSAFE_withErrorBoundaryProps as bu,useRouteError as wu,isRouteErrorResponse as da,useLoaderData as tt,useRevalidator as Lt,Outlet as zl,data as X,useSearchParams as Ln,useRouteLoaderData as vu,useParams as Bl,useActionData as Nu,redirect as Su}from"react-router";import{isbot as Cu}from"isbot";import{renderToPipeableStream as _u}from"react-dom/server";import{useState as M,useEffect as re,useCallback as oe,createContext as to,useContext as Cs,useRef as ge,useMemo as ae,forwardRef as ku,useImperativeHandle as Eu,Component as Au}from"react";import{Settings as yi,CheckCircle2 as no,Bug as Yl,AlertTriangle as is,Check as Nt,Copy as Et,Loader2 as kt,PencilRuler as Pu,HomeIcon as ju,GitCommitIcon as xi,File as Tu,RefreshCw as Mu,BookOpen as ls,FlaskConical as $u,SettingsIcon as Iu,PanelsTopLeftIcon as Ru,ComponentIcon as Du,FileText as bi,Code as wi,Box as Ou,List as Fu,BarChart3 as Lu,Tag as zu,Image as yr,Code2 as Ul,Activity as ua,ChevronDown as wt,CircleEqual as Bu,ArrowLeft as Yu,Terminal as cs,Search as Cr,ChevronLeft as Uu,ChevronRight as Xt,Save as Wu,MessageSquare as Ju,Pause as Wl,ListTodo as Hu,PauseCircle as Vu,FileCode as ds,GripVertical as Gu,Ban as Ku,CheckCircle as qu,FolderOpen as Qu,CodeXml as Zu,Zap as Xu,Pencil as ep,Trash2 as tp,X as zn,Folder as Jl,Info as Ia,Plus as ro,Eye as np,FolderTree as rp,ChevronsUpDown as Hl,ChevronsDownUp as Vl}from"lucide-react";import"fetch-retry";import sp from"better-sqlite3";import{Pool as ap}from"pg";import*as K from"fs";import ue,{existsSync as xt,readdirSync as op,rmSync as pa,readFileSync as vi}from"fs";import*as L from"path";import ee,{join as xr}from"path";import{OperationNodeTransformer as ip,sql as ct,Kysely as Gl,ParseJSONResultsPlugin as lp,SqliteDialect as cp,PostgresDialect as dp}from"kysely";import*as up from"kysely/helpers/sqlite";import*as pp from"kysely/helpers/postgres";import Ke from"typescript";import*as Ae from"fs/promises";import Pe,{writeFile as dr,readFile as Ra,mkdir as mp}from"fs/promises";import*as so from"os";import Da,{homedir as hp}from"os";import fp from"prompts";import us from"chalk";import*as Kl from"crypto";import Bn,{randomUUID as ao,createHmac as gp}from"crypto";import{execSync as $e,spawn as St,exec as oo}from"child_process";import{fileURLToPath as _s}from"url";import{promisify as io}from"util";import yp from"dotenv";import xp,{EventEmitter as _r}from"events";import{v4 as bp}from"uuid";import lo from"http";import ql from"net";import{WebSocket as co}from"ws";import"node-pty";import wp from"openai";import vp from"p-queue";import Ni from"p-retry";import{DynamoDBClient as ks,PutItemCommand as Np}from"@aws-sdk/client-dynamodb";import{LRUCache as uo}from"lru-cache";import"pluralize";import"piscina";import Sp from"json5";import{marshall as Cp}from"@aws-sdk/util-dynamodb";import _p from"v8";import{Prism as kp}from"react-syntax-highlighter";import{vscDarkPlus as Ep}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as Ap}from"node:crypto";import{minimatch as Oa}from"minimatch";import Pp from"react-markdown";import jp from"remark-gfm";import Tp from"react-diff-viewer-continued";const Ql=5e3;function Mp(e,t,r,s,a){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:t,headers:r}):new Promise((o,i)=>{let l=!1,c=e.headers.get("user-agent"),p=c&&Cu(c)||s.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>h(),Ql+1e3);const{pipe:m,abort:h}=_u(n(hu,{context:s,url:e.url}),{[p](){l=!0;const f=new pu({final(y){clearTimeout(u),u=void 0,y()}}),g=mu(f);r.set("Content-Type","text/html"),m(f),o(new Response(g,{headers:r,status:t}))},onShellError(f){i(f)},onError(f){t=500,l&&console.error(f)}})})}const $p=Object.freeze(Object.defineProperty({__proto__:null,default:Mp,streamTimeout:Ql},Symbol.toStringTag,{value:"Module"})),Ip=2e3,Rp=5e3;function Dp(e){return e.startsWith("/editor")?Rp:Ip}function Op(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 Fp({id:e,selected:t,onClick:r,icon:s,name:a}){const[o,i]=M(!1);re(()=>{i(!0)},[]);const l=oe(()=>{r==null||r(e)},[r,e]);return d("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 Es="/assets/cy-logo-cli-CCKUIm0S.svg";function Lp(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 zp({content:e,className:t=""}){const[r,s]=M(!1),a=oe(()=>{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?d(xe,{children:[n(Nt,{size:14}),"Copied"]}):d(xe,{children:[n(Et,{size:14}),"Copy"]})})}function Zl({isOpen:e,onClose:t,context:r,defaultEmail:s="",screenshotDataUrl:a}){const[o,i]=M(""),[l,c]=M(s),[p,u]=M(!1),[m,h]=M(!1),[f,g]=M(null),[y,x]=M(null),w=Ue(),b=w.state!=="idle",v=!!(r.scenarioId||r.analysisId),N=r.analysisId||r.scenarioId||"",C=()=>{const S=`/codeyam-diagnose ${N}`;return o.trim()?`${S} ${o.trim()}`:S};if(w.data&&!m&&!y){const S=w.data;S.success&&S.reportId?(h(!0),g(S.reportId)):S.error&&x(S.error)}const E=async()=>{x(null);const S=new FormData;if(S.append("issueType","other"),S.append("description",o),S.append("email",l),S.append("source",r.source),S.append("entitySha",r.entitySha||""),S.append("scenarioId",r.scenarioId||""),S.append("analysisId",r.analysisId||""),S.append("currentUrl",r.currentUrl),S.append("entityName",r.entityName||""),S.append("entityType",r.entityType||""),S.append("scenarioName",r.scenarioName||""),S.append("errorMessage",r.errorMessage||""),a)try{const $=await(await fetch(a)).blob();S.append("screenshot",$,"screenshot.jpg")}catch(j){console.error("Failed to convert screenshot:",j)}w.submit(S,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},k=()=>{i(""),u(!1),h(!1),g(null),x(null),t()},_=S=>{S.key==="Escape"&&k()};return e?n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:_,children:d("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[d("div",{className:"flex items-center justify-between mb-6",children:[d("div",{className:"flex items-center gap-3",children:[b?n("div",{className:"animate-spin",children:n(yi,{size:24,style:{strokeWidth:1.5}})}):m?n(no,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):n(Yl,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),n("h2",{className:"text-xl font-semibold text-gray-900",children:m?"Report Submitted":"Report Issue"})]}),n("button",{onClick:k,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"})})})]}),m?d("div",{children:[d("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!"}),d("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:k,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):d("div",{children:[d("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[d("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:Lp(r)}),n("button",{type:"button",onClick:()=>u(!p),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:p?"Hide":"Details"})]}),p&&d("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[d("div",{children:[n("span",{className:"text-gray-400",children:"Source:"})," ",r.source]}),d("div",{children:[n("span",{className:"text-gray-400",children:"URL:"})," ",r.currentUrl]}),r.entitySha&&d("div",{children:[n("span",{className:"text-gray-400",children:"Entity:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.entitySha})]}),r.scenarioId&&d("div",{children:[n("span",{className:"text-gray-400",children:"Scenario:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.scenarioId})]}),r.analysisId&&d("div",{children:[n("span",{className:"text-gray-400",children:"Analysis:"})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:r.analysisId})]})]})]}),a&&d("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"})]}),d("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:S=>i(S.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"})]}),v&&d(xe,{children:[d("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[d("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."}),d("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(zp,{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"})]})]}),d("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"})})]})]}),d("div",{className:v?"opacity-75":"",children:[v&&d("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)"})]}),d("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:S=>c(S.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]"})]}),d("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[n(is,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),d("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."})]})]}),b&&n("div",{className:"mb-4 text-center",children:n("p",{className:"text-sm text-gray-600",children:w.formData?"Uploading report...":"Creating archive..."})}),y&&d("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[n(is,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),d("div",{className:"text-xs text-red-800",children:[n("p",{className:"font-medium mb-1",children:"Upload failed"}),n("p",{children:y})]})]}),d("div",{className:"flex gap-3 justify-end",children:[n("button",{onClick:k,disabled:b,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 E(),disabled:b,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:b?d(xe,{children:[n("div",{className:"animate-spin",children:n(yi,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):y?"Try Again":"Submit Report"})]})]})]})]})}):null}const Si={source:"navbar"},po=to(void 0);function Bp({children:e}){const[t,r]=M(Si),s=oe(o=>{r(o)},[]),a=oe(()=>{r(Si)},[]);return n(po.Provider,{value:{contextData:t,setContextData:s,resetContextData:a},children:e})}function jt(e){const t=Cs(po),r=ge(t);re(()=>{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 Yp(){const e=Cs(po),t=Sr();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 Up({labs:e,isAdmin:t,editorMode:r}){var E;const s=Sr(),a=Pt(),[o,i]=M(),[l,c]=M(!1),[p,u]=M(!1),[m,h]=M(null),f=Ue();re(()=>{f.state==="idle"&&!f.data&&f.load("/api/generate-report")},[f]);const g=((E=f.data)==null?void 0:E.defaultEmail)||"",y={width:"20px",height:"20px",strokeWidth:1.5},x=(e==null?void 0:e.simulations)??!1,w=[{id:"editor",icon:n(Pu,{style:y}),link:"/editor",name:"Editor",hidden:!r,newTab:!0},{id:"dashboard",icon:n(ju,{style:y}),link:"/",name:"Dashboard",hidden:!x||r},{id:"simulations",icon:d("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:y,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(xi,{style:y}),link:"/git",name:"Git",hidden:!x||r},{id:"files",icon:n(Tu,{style:y}),link:"/files",name:"Files",hidden:!x||r},{id:"activity",icon:n(Mu,{style:y}),link:"/activity",name:"Activity",hidden:!x||r},{id:"memory",icon:n(ls,{style:y}),link:"/memory",name:"Memory"},{id:"labs",icon:n($u,{style:y}),link:"/labs",name:"Labs"},{id:"settings",icon:n(Iu,{style:y}),link:"/settings",name:"Settings"},{id:"commits",icon:n(xi,{style:y}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:n(Ru,{style:y}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:n(Du,{style:y}),link:"/components",name:"Components",hidden:!0}],b=oe(k=>{const _=w.find(S=>S.id===k);_!=null&&_.link&&(_.newTab?window.open(_.link,"_blank"):a(_.link)),i(S=>S===k?void 0:k)},[w,a]);re(()=>{const k={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[_,S]of Object.entries(k))if(S.some(j=>j==="/"?s.pathname==="/":s.pathname.includes(j))){i(_);return}i(void 0)},[s]);const v=async()=>{u(!0);try{const{default:k}=await import("html2canvas-pro"),S=(await k(document.body)).toDataURL("image/jpeg",.8);h(S),c(!0)}catch(k){console.error("Screenshot capture failed:",k),c(!0)}finally{u(!1)}},N=()=>{c(!1),h(null)},C=Yp();return d(xe,{children:[d("div",{id:"sidebar",className:"sticky top-0 w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[d("div",{className:"w-full flex flex-col items-center",children:[n("div",{className:"py-3 mt-2 mb-4",children:n(Ce,{to:"/",className:"flex items-center justify-center cursor-pointer",children:n("img",{src:Es,alt:"CodeYam",className:"h-6"})})}),w.filter(k=>!k.hidden).map(k=>n(Fp,{id:k.id,selected:k.id===o,onClick:b,icon:k.icon,name:k.name},`sidebar-button-${k.id}`))]}),t&&n("div",{className:"w-full flex flex-col items-center pb-2",children:d("button",{onClick:()=>void v(),disabled:p,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:p?n(kt,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):n(Yl,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),n("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:p?"Capturing...":`Report
|
|
6
|
-
Bug`})]})})]}),l&&n(Zl,{isOpen:!0,onClose:N,context:C,defaultEmail:g,screenshotDataUrl:m??void 0})]})}const Xl=to(void 0);function Wp({children:e}){const[t,r]=M([]),s=oe((o,i="info",l=5e3)=>{const p={id:`toast-${Date.now()}-${Math.random()}`,message:o,type:i,duration:l};r(u=>[...u,p])},[]),a=oe(o=>{r(i=>i.filter(l=>l.id!==o))},[]);return n(Xl.Provider,{value:{toasts:t,showToast:s,closeToast:a},children:e})}function mo(){const e=Cs(Xl);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function Jp({toast:e,onClose:t}){re(()=>{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 d("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 Hp({toasts:e,onClose:t}){return e.length===0?null:d("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(Jp,{toast:r,onClose:t},r.id))]})}function zt(e,t){const[r,s]=M(""),[a,o]=M(!1),[i,l]=M(null),[c,p]=M(!1);re(()=>{t&&(p(!1),o(!1),l(null))},[t]),re(()=>{if(!e||!t){t||s("");return}const m=async()=>{if(!c)try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const y=(await f.text()).trim().split(`
|
|
18
|
-
`).filter(b=>b.length>0);if(y.length<3){o(!1),p(!1),l(null),s("");return}const x=y.filter(b=>b.includes("CodeYam Log Level 1"));if(x.length>0){const b=x[x.length-1];s(b.replace(/.*CodeYam Log Level 1: /,""))}const w=y.find(b=>b.includes("$$INTERACTIVE_SERVER_URL$$:"));if(w){const b=w.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();l(b),p(!0)}y.some(b=>b.includes("CodeYam: Exiting start.js"))&&o(!0)}}catch{}};m().catch(()=>{});const h=setInterval(()=>{m().catch(()=>{})},500);return()=>clearInterval(h)},[e,t,c]);const u=oe(()=>{s(""),o(!1),l(null),p(!1)},[]);return{lastLine:r,interactiveUrl:i,isCompleted:a,resetLogs:u}}function qt({projectSlug:e,onClose:t}){const[r,s]=M("Loading logs..."),[a,o]=M(!0),[i,l]=M(!0),[c,p]=M("all"),u=ge(null);return re(()=>{const m=async()=>{try{const h=await fetch(`/api/logs/${e}`);if(h.ok){const f=await h.text();if(c==="all")s(f);else{const g=f.trim().split(`
|
|
19
|
-
`).filter(y=>{if(y.length===0)return!1;const x=y.match(/^.*CodeYam Log Level (\d+):/);return!!x&&Number(x[1])<=c});s(g.map(y=>y.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
|
|
20
|
-
`))}i&&u.current&&setTimeout(()=>{var g;(g=u.current)==null||g.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else s(`Error: ${h.status} - ${await h.text()}`)}catch(h){s(`Error fetching logs: ${h.message}`)}};if(m().catch(()=>{}),a){const h=setInterval(()=>{m().catch(()=>{})},2e3);return()=>clearInterval(h)}},[e,a,i,c]),re(()=>{const m=h=>{h.key==="Escape"&&t()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t]),n("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:t,children:d("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:m=>m.stopPropagation(),children:[d("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[d("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),d("div",{className:"flex items-center gap-4",children:[d("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[n("span",{children:"Log Level:"}),d("select",{value:c,onChange:m=>p(m.target.value==="all"?"all":Number(m.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"})]})]}),d("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:m=>o(m.target.checked),className:"cursor-pointer"}),n("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),d("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:m=>l(m.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:u,children:r})]})})}function dt({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(Ul,{size:a,color:s.iconColor});case"visual":return n(yr,{size:a,color:s.iconColor});case"type":return n(zu,{size:a,color:s.iconColor});case"data":return n(Lu,{size:a,color:s.iconColor});case"index":return n(Fu,{size:a,color:s.iconColor});case"functionCall":return n(wi,{size:a,color:s.iconColor});case"class":return n(Ou,{size:a,color:s.iconColor});case"method":return n(wi,{size:a,color:s.iconColor});case"other":return n(bi,{size:a,color:s.iconColor});default:return n(bi,{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 ec({filePath:e,maxLength:t=60,className:r,style:s}){const o=((l,c)=>{if(l.length<=c)return l;const p="...",u=c-p.length,m=Math.ceil(u*.4),h=Math.floor(u*.6),f=l.slice(0,m),g=l.slice(-h),y=f.lastIndexOf("/"),x=g.indexOf("/"),w=y>m*.5?f.slice(0,y+1):f,b=x!==-1&&x<h*.5?g.slice(x):g;return`${w}${p}${b}`})(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 ma({entity:e,nameSize:t="11px",pathSize:r="10px",pathMaxLength:s=50,showScenarioCount:a=!1,scenarioCount:o=0,additionalContent:i}){return d("div",{className:"flex flex-col gap-1",children:[d("div",{className:"flex items-center gap-1",children:[n(dt,{type:e.entityType||"other"}),d(Ce,{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(ec,{filePath:e.filePath,maxLength:s,style:{fontSize:r,color:"#8E8E8E"}})]}),i]})}const ha={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function Vp({currentRun:e,projectSlug:t,currentEntities:r=[],isAnalysisStarting:s=!1,queuedJobCount:a=0,queueJobs:o=[],currentlyExecuting:i=null,historicalRuns:l=[]}){var W,F,J;const[c,p]=M(!1),[u,m]=M(!1),[h,f]=M(null),[g,y]=M(new Set),[x,w]=M(new Set),[b,v]=M(!1),N=!!i||o.length>0,C=!!i,E=(i==null?void 0:i.entities)||r,k=!!(e!=null&&e.analysisCompletedAt),_=(e==null?void 0:e.readyToBeCaptured)??0,S=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||k&&(_===0||S>=_);const j=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,$=N,{lastLine:T}=zt(t,$),R=C||o.length>0,I=new Set(((W=i==null?void 0:i.entities)==null?void 0:W.map(Y=>Y.sha))||[]),P=l.filter(Y=>!(Y.currentEntityShas||[]).some(A=>I.has(A))),H=(()=>{const z=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&j){const A=e.analysisCompletedAt||e.createdAt;if(new Date(A).getTime()>z)return!0}if(P.length>0){const A=P[0],B=A.analysisCompletedAt||A.archivedAt||A.createdAt;if(B&&new Date(B).getTime()>z)return!0}return!1})();return re(()=>{const Y=(i==null?void 0:i.id)||null;N&&!u&&Y!==h&&m(!0),!N&&h!==null&&f(null)},[N,i==null?void 0:i.id,u,h]),d(xe,{children:[d("div",{className:`fixed bottom-4 right-4 z-9998 bg-white rounded shadow-lg border-2 border-primary-100 transition-all duration-200 ${u?"min-w-[350px] max-w-[500px]":"w-auto"}`,children:[!u&&d("div",{onClick:()=>{m(!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(kt,{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(ua,{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:Y=>{Y.stopPropagation(),p(!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"})]}),u&&d("div",{children:[d("div",{className:"flex items-center justify-between px-3 py-2",children:[d("div",{className:"flex items-center gap-2",children:[R?n(kt,{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(ua,{size:16,style:{color:"#005C75"}})}),n("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:R?"Analyzing...":"Activity"})]}),d("div",{className:"flex items-center gap-2",children:[n("button",{onClick:()=>p(!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:()=>{m(!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(wt,{size:16,style:{color:"#646464"}})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),d("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[R&&i&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(ua,{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:E.length>0?d("div",{className:"space-y-1.5",children:[(b?E:E.slice(0,3)).map(Y=>n(ma,{entity:Y,nameSize:"11px",pathSize:"10px",pathMaxLength:150},Y.sha)),E.length>3&&n("button",{onClick:()=>v(Y=>!Y),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:ha,"aria-label":b?"Show fewer entities":`Show ${E.length-3} more entities`,children:b?"Show less":`+${E.length-3} more`}),T&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:T})]}):d("div",{children:[i.entityNames&&i.entityNames.length>0?d("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((Y,z)=>n("div",{style:{fontSize:"11px",color:"#343434"},children:Y},z)),i.entityNames.length>5&&d("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):d("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((F=i.entityShas)==null?void 0:F.length)||0," ",((J=i.entityShas)==null?void 0:J.length)===1?"entity":"entities","..."]}),T&&n("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:T})]})})]}),o.length>0&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(Bu,{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(Y=>{var B,G;const z=g.has(Y.id),A=z?Y.entities:Y.entities.slice(0,3);return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:Y.entities.length>0?d("div",{className:"space-y-1.5",children:[A.map(q=>n(ma,{entity:q,nameSize:"10px",pathSize:"9px",pathMaxLength:120},q.sha)),Y.entities.length>3&&n("button",{onClick:()=>{y(q=>{const Q=new Set(q);return Q.has(Y.id)?Q.delete(Y.id):Q.add(Y.id),Q})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:ha,"aria-label":z?"Show fewer entities":`Show ${Y.entities.length-3} more entities`,children:z?"Show less":`+${Y.entities.length-3} more`})]}):d("div",{style:{fontSize:"10px",color:"#343434"},children:[Y.type==="analysis"&&n(xe,{children:Y.entityNames&&Y.entityNames.length>0?d("div",{className:"space-y-0.5",children:[Y.entityNames.slice(0,5).map((q,Q)=>n("div",{children:q},Q)),Y.entityNames.length>5&&d("div",{className:"italic",children:["+",Y.entityNames.length-5," more"]})]}):`Analyzing ${((B=Y.entityShas)==null?void 0:B.length)||0} ${((G=Y.entityShas)==null?void 0:G.length)===1?"entity":"entities"}`}),Y.type==="recapture"&&"Recapturing scenario",Y.type==="debug-setup"&&"Setting up debug environment"]})},Y.id)})})]}),H&&P.length>0&&d("div",{children:[d("div",{className:"flex items-center gap-1.5 mb-2",children:[n(no,{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:P.slice(0,3).map((Y,z)=>{const A=Y.entities||[],B=Y.analysisCompletedAt||Y.archivedAt||Y.createdAt||"",G=(()=>{if(!B)return"";const D=Date.now()-new Date(B).getTime(),O=Math.floor(D/6e4),V=Math.floor(D/36e5);return V>0?`${V}h ago`:O>0?`${O}m ago`:"just now"})(),q=x.has(z),U=(q?A:A.slice(0,3)).map(D=>{var O,V,ne;return{...D,scenarioCount:((ne=(V=(O=D.analyses)==null?void 0:O[0])==null?void 0:V.scenarios)==null?void 0:ne.length)||0}});return n("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:A.length>0&&d("div",{className:"space-y-1.5",children:[U.map((D,O)=>d("div",{className:"flex items-start justify-between gap-2",children:[n("div",{className:"flex-1 min-w-0",children:n(ma,{entity:D,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:D.scenarioCount})}),O===0&&G&&n("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:G})]},D.sha)),A.length>3&&n("button",{onClick:()=>{w(D=>{const O=new Set(D);return O.has(z)?O.delete(z):O.add(z),O})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:ha,"aria-label":q?"Show fewer entities":`Show ${A.length-3} more entities`,children:q?"Show less":`+${A.length-3} more`})]})},z)})})]})]}),n("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),n("div",{className:"px-3 pb-2",children:n(Ce,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),c&&t&&n(qt,{projectSlug:t,onClose:()=>p(!1)})]})}function pt(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r===null?void 0:r]))}function kr(e){const{file_id:t,project_id:r,commit_id:s,file_path:a,entity_type:o,entity_branches:i,analyses:l,commit:c,created_at:p,updated_at:u,...m}=e,h=(i??[]).map(y=>y.branch_id),f=l?l.map(Bt):void 0,g=c?fn(c):void 0;return pt({...m,fileId:t,projectId:r,commitId:s,filePath:a,entityType:o,commit:g,analyses:f,branchIds:h,createdAt:p,updatedAt:u})}function ho(e){return pt({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 As(e){const{branches:t,files:r,analyzed_at:s,content_changed_at:a,created_at:o,updated_at:i,github_token:l,configuration:c,team_id:p,...u}=e;return pt({...u,branches:t?t.map(gn):void 0,files:r?r.map(ho):void 0,analyzedAt:s,contentChangedAt:a,createdAt:o,updatedAt:i})}function Gp(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 pt({id:t,projectId:r,userId:s,scenarioId:a,thumbsUp:!!o,user:l})}function Kp(e){const{id:t,project_id:r,user_id:s,scenario_id:a,text:o,created_at:i,updated_at:l,user:c}=e,p=c?{username:c.github_username,avatarUrl:c.github_user.avatar_url}:void 0;return pt({id:t,projectId:r,userId:s,scenarioId:a,text:o,createdAt:i,updatedAt:l,user:p})}function tc(e){const{project_id:t,analysis_id:r,previous_version_id:s,analysis:a,user_scenarios:o,scenario_comments:i,approved:l,...c}=e,p=a?Bt(a):void 0,u=o?o.map(Gp):void 0,m=i?i.map(Kp):void 0;return pt({...c,projectId:t,analysisId:r,previousVersionId:s,analysis:p,userScenarios:u,comments:m})}function qp(e){return pt({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?Bt(e.analysis):void 0,entity:e.entity?kr(e.entity):void 0,branch:e.branch?gn(e.branch):void 0,createdAt:e.created_at})}function Bt(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:c,file:p,entity:u,commit:m,project:h,scenarios:f,analysis_branches:g,dependency_analyzed_tree_sha:y,analyzed_tree_sha:x,branch_commit_sha:w,committed_at:b,completed_at:v,created_at:N,updated_at:C,indirect:E,...k}=e,_=u?kr(u):void 0,S=p?ho(p):void 0,j=h?As(h):void 0,$=m?fn(m):void 0,T=f?f.map(tc):void 0,R=g?g.map(qp):void 0,I=R?R.map(P=>P.branch):void 0;return pt({...k,projectId:t,commitId:r,fileId:s,filePath:a,entitySha:o,entityType:i,entityName:l,previousAnalysisId:c,entity:_,file:S,commit:$,project:j,scenarios:T,analysisBranches:R,branches:I,dependencyAnalyzedTreeSha:y,analyzedTreeSha:x,branchCommitSha:w,committedAt:b,completedAt:v,createdAt:N,updatedAt:C,indirect:!!E})}function fo(e){return pt({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?fn(e.commit):void 0,branch:e.branch?gn(e.branch):void 0})}function Qp(e){const{project_id:t,commit_id:r,created_at:s,updated_at:a,success:o,...i}=e;return pt({...i,projectId:t,commitId:r,createdAt:s,updatedAt:a,success:!!o})}function fn(e){const{project_id:t,branch_id:r,branch:s,background_jobs:a,merged_branch_id:o,mergedBranch:i,ai_message:l,html_url:c,author:p,analyses:u,entities:m,commit_branches:h,committed_at:f,analyzed_at:g,...y}=e,x=s?gn(s):void 0,w=i?gn(i):void 0,b=(a==null?void 0:a.length)>0?Qp(a[a.length-1]):void 0,v=(u??[]).map(Bt),N=(m??[]).map(kr),C=(h==null?void 0:h.length)>0?h.map(fo):void 0;return p&&(p.username=p.preferredUsername??p.username),pt({...y,projectId:t,branchId:r,branch:x,backgroundJob:b,mergedBranchId:o,mergedBranch:w,aiMessage:l,htmlUrl:c,author:p,analyses:v,entities:N,commitBranches:C,committedAt:f,analyzedAt:g})}function gn(e){const{project_id:t,content_changed_at:r,commits:s,analysis_branches:a,active_at:o,created_at:i,updated_at:l,primary:c,...p}=e,u=s?s.map(fn):void 0,m=a?a.flatMap(h=>Bt(h.analysis)):void 0;return pt({...p,projectId:t,contentChangedAt:r,commits:u,analyses:m,activeAt:o,createdAt:i,updatedAt:l,primary:!!c})}var Ns;class Zp{constructor(){gi(this,Ns,new Xp)}transformQuery(t){return fi(this,Ns).transformNode(t.node)}transformResult(t){return Promise.resolve(t.result)}}Ns=new WeakMap;class Xp extends ip{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 me=()=>null;function Oe(e=!1){return t=>(t=t.defaultTo(ct`CURRENT_TIMESTAMP`),e&&(t=t.notNull()),t)}const em={analyzed_at:me(),configuration:me(),content_changed_at:me(),created_at:me(),description:me(),github_token:me(),id:me(),metadata:me(),name:me(),path:me(),slug:me(),team_id:me(),updated_at:me()},tm=Object.keys(em);async function nm(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",Oe(!0)).addColumn("updated_at","datetime",Oe()).addColumn("team_id","integer").ifNotExists().execute()}async function rm(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",Oe(!0)).addColumn("updated_at","datetime",Oe(!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 sm={active:me(),analysis_id:me(),branch_id:me(),created_at:me(),entity_sha:me(),id:me()},am=Object.keys(sm);async function om(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",Oe()).ifNotExists().execute()}async function im(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",Oe(!0)).addColumn("updated_at","datetime").addPrimaryKeyConstraint("background_jobs_pkey",["project_id","commit_id"]).ifNotExists().execute()}const lm={active_at:me(),content_changed_at:me(),created_at:me(),id:me(),metadata:me(),name:me(),primary:me(),project_id:me(),ref:me(),sha:me(),updated_at:me()},nc=Object.keys(lm);async function cm(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",Oe()).addColumn("active_at","datetime").addColumn("created_at","datetime",Oe(!0)).addColumn("updated_at","datetime",Oe()).ifNotExists().execute()}async function dm(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",Oe(!0)).ifNotExists().execute()}const um={ai_message:me(),analyzed_at:me(),author_github_username:me(),branch_id:me(),committed_at:me(),created_at:me(),files:me(),html_url:me(),id:me(),merged_branch_id:me(),message:me(),metadata:me(),project_id:me(),sha:me(),title:me(),url:me()},rc=Object.keys(um),pm=rc.filter(e=>e!=="files");async function mm(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",Oe(!0)).ifNotExists().execute()}async function hm(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",Oe(!0)).addColumn("uploaded_at","datetime").addColumn("base_sha","varchar").addColumn("delta_size_bytes","bigint").ifNotExists().execute()}async function fm(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",Oe(!0)).addColumn("approved_at","datetime").ifNotExists().execute()}const gm={commit_id:me(),created_at:me(),description:me(),documentation:me(),entity_type:me(),file_id:me(),file_path:me(),metadata:me(),name:me(),project_id:me(),quality:me(),sha:me(),updated_at:me()},sc=Object.keys(gm);async function ym(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",Oe(!0)).addColumn("updated_at","datetime").ifNotExists().execute()}const xm={active:me(),branch_id:me(),entity_sha:me()},bm=Object.keys(xm);async function wm(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 vm(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",Oe(!0)).ifNotExists().execute()}const Nm={created_at:me(),deleted:me(),id:me(),metadata:me(),name:me(),path:me(),project_id:me(),updated_at:me()},Sm=Object.keys(Nm);async function Cm(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",Oe(!0)).addColumn("updated_at","datetime",Oe()).addColumn("metadata","text").ifNotExists().execute()}async function _m(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",Oe(!0)).ifNotExists().execute()}async function km(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",Oe(!0)).addColumn("updated_at","datetime",Oe()).ifNotExists().execute()}async function Em(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",Oe(!0)).addColumn("updated_at","datetime",Oe(!0)).ifNotExists().execute()}async function Am(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",Oe(!0)).addColumn("updated_at","datetime",Oe(!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 Pm={analysis_id:me(),approved:me(),created_at:me(),description:me(),id:me(),metadata:me(),name:me(),previous_version_id:me(),project_id:me()},ps=Object.keys(Pm);async function jm(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",Oe(!0)).ifNotExists().execute()}async function Tm(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",Oe(!0)).ifNotExists().execute()}async function Mm(e){await e.schema.createTable("teams").addColumn("id","serial",t=>t.primaryKey()).addColumn("name","varchar",t=>t.notNull()).addColumn("created_at","datetime",Oe(!0)).ifNotExists().execute()}async function $m(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",Oe(!0)).ifNotExists().execute()}async function Im(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 Rm(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",Oe(!0)).addColumn("updated_at","datetime",Oe()).ifNotExists().execute()}const Dm=!!yn("ENABLE_QUERY_LOGGING"),Om=!!yn("ENABLE_QUERY_ERROR_LOGGING");yn("USE_LOCAL_POSTGRESQL_FOR_TESTING");let Ur;function Te(){if(!Ur){const e=oc();if(e==="sqlite")Ur=Fm();else if(e==="postgresql")Ur=Lm();else throw new Error(`Unknown database type: ${e}`)}return Ur}function Fm(e){if(e||(e=yn("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const t=K.existsSync(e),r=L.dirname(e);if(!K.existsSync(r))K.mkdirSync(r,{recursive:!0,mode:493});else try{K.chmodSync(r,493)}catch(a){console.warn(`Warning: Could not set permissions on database directory: ${a.message}`)}const s=new sp(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 Gl({dialect:new cp({database:s}),plugins:[new lp,new Zp],log:ac})}function Lm(){const e=Bm();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const t=new ap({connectionString:e,max:3,idleTimeoutMillis:1e4});return t.on("error",(r,s)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",r)}),new Gl({dialect:new dp({pool:t}),log:ac})}let fa=null;function bn(){return fa||(fa=zm(oc())),fa}function ac(e){e.level==="error"?Om&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):Dm&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function zm(e){if(e==="sqlite")return up;if(e==="postgresql")return pp;throw new Error(`Unknown database type: ${e}`)}function oc(){if(yn("SQLITE_PATH"))return"sqlite";if(yn("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}async function $2(e){await nm(e),await rm(e),await om(e),await im(e),await cm(e),await dm(e),await mm(e),await hm(e),await Am(e),await ym(e),await wm(e),await vm(e),await Cm(e),await _m(e),await km(e),await fm(e),await Em(e),await jm(e),await Tm(e),await Mm(e),await $m(e),await Im(e),await Rm(e)}function Bm(){const e=yn("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function yn(e){var t;return typeof window<"u"?(t=window.env)==null?void 0:t[e]:process.env[e]}const Ym=()=>crypto.randomUUID();function Um(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??Ym(),project_id:r,active_at:s,content_changed_at:a,metadata:o?JSON.stringify(o):null}}var et=(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))(et||{});const Ps="Default Scenario";let Wm="<main>";function Jm(){return Wm}function Ci(e,...t){De(`CodeYam Log Level ${e}: ${t[0]}`,...t.slice(1))}function De(...e){const t=Jm(),r=e.map(a=>{if(a)return typeof a=="string"?a:a instanceof Error?`${a.name}: ${a.message}
|
|
21
|
-
${a.stack}`:typeof a=="object"?Hm(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 Hm(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 c=r(l,a);return typeof l=="string"?`"${c}"`:c}).join(",")}]`:`{${Object.entries(s).map(([i,l])=>{let c;return typeof l>"u"?null:(typeof l=="function"?c=`"(function: ${l.name||"anonymous"})"`:l instanceof Date?c=`"${l.toISOString()}"`:typeof l=="object"&&l!==null?c=r(l,a):typeof l=="string"?c=`"${l.replace(/"/g,'\\"')}"`:c=JSON.stringify(l),`"${i.replace(/"/g,'\\"')}":${c}`)}).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 ms(e,t){try{let r=function(o){var i,l;if(Ke.isFunctionDeclaration(o)&&sr(o)){const c=((i=o.name)==null?void 0:i.text)||"default",p=o.getText(s),u=ga(o);a.push({name:c,code:p,sha:sn(t,c,p),entityType:"function",isDefault:u})}else if(Ke.isClassDeclaration(o)&&sr(o)){const c=((l=o.name)==null?void 0:l.text)||"default",p=o.getText(s),u=ga(o),m=p.includes("React.")||p.includes("jsx")||p.includes("tsx");a.push({name:c,code:p,sha:sn(t,c,p),entityType:m?"component":"class",isDefault:u})}else if(Ke.isInterfaceDeclaration(o)&&sr(o)){const c=o.name.text,p=o.getText(s);a.push({name:c,code:p,sha:sn(t,c,p),entityType:"interface",isDefault:!1})}else if(Ke.isTypeAliasDeclaration(o)&&sr(o)){const c=o.name.text,p=o.getText(s);a.push({name:c,code:p,sha:sn(t,c,p),entityType:"type",isDefault:!1})}else if(Ke.isVariableStatement(o)&&sr(o)){const c=ga(o);o.declarationList.declarations.forEach(p=>{var u;if(Ke.isIdentifier(p.name)){const m=p.name.text,h=o.getText(s),f=((u=p.initializer)==null?void 0:u.getText(s))||"",g=(t.endsWith(".tsx")||t.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));a.push({name:m,code:h,sha:sn(t,m,h),entityType:g?"component":"variable",isDefault:c})}})}else if(Ke.isExportAssignment(o)){const c=o.getText(s);a.push({name:"default",code:c,sha:sn(t,"default",c),entityType:"unknown",isDefault:!0})}else if(Ke.isExportDeclaration(o)&&o.exportClause&&Ke.isNamedExports(o.exportClause)){const c=o.getText(s);for(const p of o.exportClause.elements){const u=p.name.text;a.push({name:u,code:c,sha:sn(t,u,c),entityType:"unknown",isDefault:!1})}}Ke.forEachChild(o,r)};const s=Ke.createSourceFile(t,e,Ke.ScriptTarget.Latest,!0),a=[];return r(s),a}catch(r){return console.error(`Failed to extract entities from ${t}:`,r),[]}}function sr(e){if(!Ke.canHaveModifiers(e))return!1;const t=Ke.getModifiers(e);return t?t.some(r=>r.kind===Ke.SyntaxKind.ExportKeyword):!1}function ga(e){if(!Ke.canHaveModifiers(e))return!1;const t=Ke.getModifiers(e);return t?t.some(r=>r.kind===Ke.SyntaxKind.DefaultKeyword):!1}function sn(e,t,r){const s=Bn.createHash("sha256");return s.update(`${e}:${t}:${r}`),s.digest("hex").substring(0,40)}function Vm(e){var p;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=((p=o.args)==null?void 0:p.map(u=>u.replace(/\$PORT/g,String(r))))??[],l=[];for(const u of s)if(u.key&&u.value!==void 0){const m=String(u.value).replace(/'/g,"'\\''");l.push(`${u.key}='${m}'`)}if(o.env)for(const[u,m]of Object.entries(o.env)){const f=String(m).replace(/\$PORT/g,String(r)).replace(/'/g,"'\\''");l.push(`${u}='${f}'`)}const c=l.length>0?l.join(" ")+" ":"";return o.command==="sh"&&i[0]==="-c"&&i[1]?`${c}sh -c "${i[1]}"`:`${c}${o.command} ${i.join(" ")}`}function Gm(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];const r=L.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=L.normalize(a.path??".");if(o==="."||r.startsWith(o+L.sep)||r===o)return a}return t[0]}function Km(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=Gm(t,r);if(!i)throw new Error("Could not find webapp for file path: "+t);const l=Vm({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 Yn(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 qm(e){if(e.length===0)return[];const t=Te(),r=e.map(Um);try{return(await t.insertInto("branches").values(r).onConflict(Yn(r[0],"id",["created_at"])).returningAll().execute()).map(gn)}catch(s){return De("CodeYam Error: Database error upserting branches",s,{branchCount:e.length,branchIds:e.map(a=>a.id)}),[]}}function Qm(e){const{jsonObjectFrom:t}=bn();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 Zm({ids:e,analysisId:t}){const r=Te();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 De("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 De("CodeYam Error: Database error deleting scenarios",s,{ids:e,analysisId:t}),s}}function Xm(...e){try{const t=Bn.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 ya(e,t){return t.map(r=>eh(e,r))}function eh(e,t){return ct` ${ct.ref(e)}.${ct.ref(t)}`.as(t)}function th(e,t,r){return t.map(s=>nh(e,s,r))}function nh(e,t,r){return ct` ${ct.ref(e)}.${ct.ref(t)}`.as(`_cy_${r}:${t}`)}function rh(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 sh=50;function ah(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 _i({projectId:e,ids:t,fileIds:r,entityName:s,entityShas:a,commitIds:o,branchCommitSha:i,limit:l,excludeMetadata:c}){const p=Te(),{jsonObjectFrom:u,jsonArrayFrom:m}=bn();let h=c?p.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"]):p.selectFrom("analyses").selectAll("analyses");if(e&&(h=h.where("project_id","=",e)),t){if(t.length===0)return null;h=h.where("id","in",t)}if(r){if(r.length===0)return null;h=h.where("file_id","in",r)}if(o){if(o.length===0)return null;h=h.where("commit_id","in",o)}return s&&(h=h.where("entity_name","=",s)),a&&(h=h.where("entity_sha","in",a)),i&&(h=h.where("branch_commit_sha","=",i)),l&&(h=h.limit(l)),c?p.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[m(f.selectFrom("scenarios").select(ya("scenarios",ps)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):p.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(ya("entities",sc)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),m(f.selectFrom("scenarios").select(ya("scenarios",ps)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),m(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function Zt(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(([c,{arr:p}])=>(p==null?void 0:p.length)>0);let l=[];if(i){const[c,{arr:p,key:u}]=i,m=ah(p,sh),h=[];for(let f=0;f<m.length;f++){const g=m[f],x=await _i({...e,[u]:g}).execute();x&&h.push(...x)}l=h}else{const p=await _i(e).execute();if(!p||p.length===0)return De("CodeYam: No analyses found",null,e),null;l=p}return l.length===0?null:l.map(Bt)}catch(o){return De("CodeYam Error: Database error in loadAnalyses",o,e),null}}function oh(e,t){const{jsonArrayFrom:r,jsonObjectFrom:s}=bn();let a=e.selectFrom("analysis_branches").select(am).select(o=>s(o.selectFrom("branches").select(nc).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return t&&(a=t(a)),r(a)}async function Yt({id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:p,includeCommitAndBranch:u,includeScenarios:m,includeBranches:h}){const f=Te(),g=Date.now();try{let y=f.selectFrom("analyses").selectAll("analyses");e&&(y=y.where("id","=",e)),r&&(y=y.where("project_id","=",r)),i?y=y.where("dependency_analyzed_tree_sha","=",i):l?y=y.where("analyzed_tree_sha","=",l):s&&(y=y.where("file_id","=",s)),o&&(y=y.where("entity_name","=",o)),a?y=y.where("commit_id","=",a):y=y.orderBy("created_at","desc").limit(1),t&&(y=y.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",t));const{jsonObjectFrom:x,jsonArrayFrom:w}=bn();y=y.select(N=>{const C=[];return C.push(x(N.selectFrom("entities").select(sc).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),c&&C.push(x(N.selectFrom("files").select(Sm).whereRef("files.id","=","analyses.file_id")).as("file")),p&&C.push(x(N.selectFrom("projects").select(tm).whereRef("projects.id","=","analyses.project_id")).as("project")),m&&C.push(w(N.selectFrom("scenarios").select(ps).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),h&&C.push(oh(N,E=>E.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&C.push(x(N.selectFrom("commits").select(rc).select(E=>Qm(E).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),C});const b=await y.executeTakeFirst(),v=Date.now()-g;if(!b)return De(`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:c,includeProject:p,includeCommitAndBranch:u,includeScenarios:m,includeBranches:h}),null;if(v>100&&u){const N=b.commit,C=N!=null&&N.files?JSON.stringify(N.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${v}ms (files: ${Math.round(C/1024)}KB)`,{id:b.id,entityName:b.entity_name})}return Bt(b)}catch(y){return De("CodeYam Error: Database error loading analysis",y,{id:e,analysisBranchId:t,projectId:r,fileId:s,commitId:a,entityName:o,dependencyAnalyzedTreeSha:i,analyzedTreeSha:l,includeFile:c,includeProject:p,includeCommitAndBranch:u,includeScenarios:m,includeBranches:h}),null}}async function go({projectId:e,ids:t,names:r,includeInactive:s}){const a=Te();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(gn)}catch(o){return De("CodeYam Error: Database error loading branches",o,{projectId:e,ids:t,names:r,includeInactive:s}),[]}}async function ih({projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}){const o=Te();try{let i=o.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(a,p=>p.select(th("branches",nc,"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(p=>rh(p,"branch")).map(fo)}catch(i){return De("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:t,branchId:r,active:s,includeBranches:a}),null}}async function lh(e){if(e.length===0)return new Map;const t=Te();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 De("CodeYam Error: Loading branches for commits",r,{commitIds:e}),new Map}}async function ch(e){if(e.length===0)return new Map;const t=Te(),{jsonObjectFrom:r,jsonArrayFrom:s}=bn();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(ps).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 De("CodeYam Error: Loading analyses for commits",a,{commitIds:e}),new Map}}async function dh(e){if(e.length===0)return new Map;const t=Te();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 De("CodeYam Error: Loading entities for commits",r,{commitIds:e}),new Map}}async function hs({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=Te(),{jsonObjectFrom:c}=bn(),p=Date.now();try{let u;if(i){const b=pm.map(v=>`commits.${v}`);u=l.selectFrom("commits").select(b)}else u=l.selectFrom("commits").selectAll("commits").select(b=>[c(b.selectFrom("github_users").select(["username","preferred_username as preferredUsername","avatar_url as avatarUrl"]).where("github_users.username","=",b.ref("commits.author_github_username"))).as("author")]);if(e&&(u=u.where("project_id","=",e)),r){if(r.length===0)return[];u=u.where("id","in",r)}if(s){if(s.length===0)return[];u=u.where("sha","in",s)}if(a&&a.length>0){const b=ct.join(a.map(v=>ct`${v}`),ct`, `);u=u.where(ct`
|
|
24
|
-
EXISTS (
|
|
25
|
-
SELECT 1
|
|
26
|
-
FROM json_each(${ct.ref("commits.files")}) AS f
|
|
27
|
-
WHERE json_extract(f.value, '$.fileName') IN (${b})
|
|
28
|
-
)
|
|
29
|
-
`)}t&&(u=u.where("branch_id","=",t));const m=await u.orderBy("committed_at","desc").limit(o).execute(),h=Date.now()-p;if(!m||m.length===0)return[];if(h>100){const b=m.reduce((v,N)=>v+(N.files?JSON.stringify(N.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${h}ms (${m.length} commits, totalFiles: ${Math.round(b/1024)}KB)`)}if(i)return m.map(v=>({...v,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(fn);const f=m.map(b=>b.id),[g,y,x]=await Promise.all([lh(f),ch(f),dh(f)]);return m.map(b=>{const v=b.branch_id?g.get(b.branch_id):void 0,N=b.merged_branch_id?g.get(b.merged_branch_id):void 0,C=y.get(b.id)||[],E=x.get(b.id)||[];return{...b,branch:v,mergedBranch:N,analyses:C,entities:E}}).map(fn)}catch(u){return De("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:t,ids:r,shas:s,limit:o}),[]}}async function qe({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 c=[];for(let p=0;p<o.length;p+=50){const u=o.slice(p,p+50),m=await qe({projectId:e,branchId:t,fileIds:r,filePaths:s,names:a,shas:u,excludeMetadata:i});m&&c.push(...m)}return c}const l=Te();try{const u=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,m=>m.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",t)).$if(!!e,m=>m.where("entities.project_id","=",e)).$if(!!o,m=>m.where("entities.sha","in",o)).$if(!!s,m=>m.where("entities.file_path","in",s)).$if(!!a,m=>m.where("entities.name","in",a)).$if(!!r,m=>m.where("entities.file_id","in",r)).execute();return!u||u.length===0?null:u.map(kr)}catch(c){return console.log("Load Entities: Error occurred",c,{projectId:e,fileIds:r,filePaths:s,shas:o}),null}}function uh(e,t){const{jsonArrayFrom:r}=bn();let s=e.selectFrom("entity_branches").select(bm);return t&&(s=t(s)),r(s)}async function ic({projectId:e,sha:t}){const r=Te();try{const s=await r.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(a=>uh(a,o=>o.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",t).executeTakeFirst();return s?kr(s):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&De(`CodeYam Error: Load Entity: Entity not found (sha=${t==null?void 0:t.substring(0,12)})`,null,{projectId:e,sha:t}),null)}catch(s){return De("CodeYam Error: Load Entity: Database error",s,{projectId:e,sha:t}),null}}const xa=1e3;async function lc({projectId:e,filePaths:t,fileIds:r,fileNames:s}){if(t&&t.length>50){const l=[];for(let c=0;c<t.length;c+=50){const p=t.slice(c,c+50),u=await lc({projectId:e,filePaths:p,fileIds:r,fileNames:s});u&&l.push(...u)}return l}const a=Te(),o=[];let i=0;try{for(;;){let l=a.selectFrom("files").selectAll().where("project_id","=",e).limit(xa).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 c=await l.execute();if(!c||c.length===0||(o.push(...c),c.length<xa))break;i+=xa}return o==null?void 0:o.map(ho)}catch(l){return console.log("CodeYam Error: Error loading project files in loadFiles",l),null}}async function yo({id:e,slug:t,withBranches:r,withFiles:s,silent:a}){try{let i=Te().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 c=As(l);return s&&(c.files=await lc({projectId:c.id})),r&&(c.branches=await go({projectId:c.id,includeInactive:!1})),c}catch{return null}}function fs(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]=fs(o,a):a!==void 0&&(r[s]=a)}return r}async function Kt({commitId:e,commitSha:t,metadataUpdate:r,runStatusUpdate:s,archiveCurrentRun:a,updateCallback:o}){for(let c=0;c<=4;c++)try{return await Te().transaction().execute(async p=>{const u=await p.selectFrom("commits").select(["id","metadata"]).$if(!!e,f=>f.where("id","=",e)).$if(!!t,f=>f.where("sha","=",t)).executeTakeFirst();if(!u)return De(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const m=u.metadata||{};if(s)s.lastUpdatedAt??(s.lastUpdatedAt=new Date().toISOString()),r=fs(r??{},{currentRun:s});else if(!r&&!o)return m;const h=r?fs(m,r):m;if(a&&h.currentRun){const f={...h.currentRun,archivedAt:new Date().toISOString()};h.historicalRuns=[...h.historicalRuns||[],f]}o&&await o(h);try{return await p.updateTable("commits").set({metadata:JSON.stringify(h)}).where("id","=",u.id).returning(["id"]).executeTakeFirst()?h:(De(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),m)}catch(f){return De(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,f),m}})}catch(p){const u=p instanceof Error&&p.message.includes("database is locked");if(u&&c<4){const m=250*Math.pow(2,c);await new Promise(h=>setTimeout(h,m));continue}return De(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}${u?` after ${c+1} attempts`:""}`,p),null}return null}async function cc(e,t,r="analysis"){try{return await Te().transaction().execute(async s=>{const a=await s.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!a)return De(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const o=Bt(a);return t(o.metadata,o),await s.updateTable("analyses").set({metadata:JSON.stringify(o.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?o.metadata:(De(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${r})`,null,{analysisId:e,source:r}),null)})}catch(s){return De(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${r})`,s,{analysisId:e,source:r}),null}}async function Un(e,t,r="capture"){for(let o=0;o<=4;o++)try{return await Te().transaction().execute(async i=>{const l=await i.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!l)return De(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${r})`,null,{analysisId:e,source:r}),null;const c=Bt(l);return t(c.status,c),await i.updateTable("analyses").set({status:JSON.stringify(c.status)}).where("id","=",e).returningAll().executeTakeFirst()?c.status:(De(`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 c=250*Math.pow(2,o);await new Promise(p=>setTimeout(p,c));continue}return De(`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 Dn({projectId:e,projectSlug:t,metadataUpdate:r,updateCallback:s}){if(!e&&!t)throw new Error("Either projectId or projectSlug must be provided");try{return await Te().transaction().execute(async a=>{const o=await a.selectFrom("projects").selectAll().$if(!!e,c=>c.where("id","=",e)).$if(!!t,c=>c.where("slug","=",t)).executeTakeFirst();if(!o)return De(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=o.metadata||{};if(!r&&!s)return i;const l=r?fs(i,r):i;s&&await s(l,As(o));try{return await a.updateTable("projects").set({metadata:JSON.stringify(l)}).where("id","=",o.id).returningAll().executeTakeFirst()?l:(De(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(c){return De(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,c),null}})}catch(a){return De(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,a),null}}const ph=()=>crypto.randomUUID();function mh(e){const{id:t,projectId:r,analysisId:s,previousVersionId:a,analysis:o,metadata:i,data:l,...c}=e;return delete c.userScenarios,delete c.comments,"created_at"in c&&delete c.created_at,{...c,id:t??ph(),metadata:i?JSON.stringify(i):null,project_id:r,analysis_id:s,previous_version_id:a}}async function hh(e){if(e.length===0)return[];const t=Te(),r=e.map(mh);try{return(await t.insertInto("scenarios").values(r).onConflict(Yn(r[0],"id",["created_at"])).returningAll().execute()).map(tc)}catch(s){return De("CodeYam Error: Database error upserting scenarios",s,{scenarioCount:e.length}),null}}const fh=()=>crypto.randomUUID();function gh(e){const{id:t,commitId:r,branchId:s,...a}=e;return delete a.commit,delete a.branch,{...a,id:t??fh(),commit_id:r,branch_id:s}}async function ki(e){if(e.length===0)return[];const t=Te(),r=e.map(gh);try{return(await t.insertInto("commit_branches").values(r).onConflict(Yn(r[0],"id",["created_at"])).returningAll().execute()).map(fo)}catch(s){return De("CodeYam Error: Database error upserting commit branches",s,{commitBranchCount:e.length,commitBranchIds:e.map(a=>a.id)}),[]}}async function yh(e,t){const r=Te(),s={username:e,avatar_url:t};try{return await r.insertInto("github_users").values(s).onConflict(Yn(s,"username",[])).returningAll().executeTakeFirst()||null}catch(a){return De("CodeYam Error: Error upserting github user",a,{username:e,avatarUrl:t}),null}}const xh=()=>crypto.randomUUID();function bh(e,t){const{id:r,projectId:s,branchId:a,mergedBranchId:o,aiMessage:i,htmlUrl:l,analyzedAt:c,committedAt:p,author:u,metadata:m,files:h,...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??xh(),project_id:s??String(t),metadata:m?JSON.stringify(m):void 0,files:h?JSON.stringify(h):void 0,branch_id:a,merged_branch_id:o,author_github_username:u==null?void 0:u.username,html_url:l,ai_message:i,analyzed_at:c,committed_at:p}}async function wh({projectId:e,commits:t}){const r=Te();try{const s=t.reduce((i,l)=>{const{author:c}=l;return c!=null&&c.username&&(c!=null&&c.avatarUrl)&&(i[c.username]=c.avatarUrl),i},{});for(const i in s)await yh(i,s[i]);const a=t.map(i=>bh(i,e));return(await r.insertInto("commits").values(a).onConflict(Yn(a[0],"id",["created_at"])).returningAll().execute()).map(fn)}catch(s){return De("CodeYam Error: Error saving commits",s,{projectId:e,commitCount:t.length,commitIds:t.map(a=>a.id).filter(Boolean)}),[]}}const vh=()=>crypto.randomUUID();function Nh(e){const{id:t,files:r,branches:s,team:a,analyzedAt:o,contentChangedAt:i,createdAt:l,updatedAt:c,metadata:p,...u}=e;return{...u,id:t??vh(),analyzed_at:o||null,content_changed_at:i||null,created_at:l||new Date().toISOString(),updated_at:c||null,metadata:p?JSON.stringify(p):null,github_token:null,configuration:null,team_id:null}}async function Sh(e){try{if(e.length===0)return null;const t=Te(),r=e.map(o=>Nh(o)),s=await t.insertInto("projects").values(r).onConflict(Yn(r[0],"id",["created_at"])).returningAll().execute(),a=s==null?void 0:s[0];return a?As(a):null}catch(t){return console.log("Error saving project",t),null}}const gs=L.join(so.homedir(),".codeyam","secrets.json"),ys=L.join(process.cwd(),".codeyam","secrets.json");async function en(){let e={};try{if(K.existsSync(ys)){const o=await Ae.readFile(ys,"utf8");e=JSON.parse(o)}}catch{console.warn(us.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(K.existsSync(gs)){const o=await Ae.readFile(gs,"utf8");e={...JSON.parse(o),...e}}}catch{console.warn(us.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 Ch(e,t=!0){const r=t?gs:ys,s=L.dirname(r);await Ae.mkdir(s,{recursive:!0}),await Ae.writeFile(r,JSON.stringify(e,null,2)),await Ae.chmod(r,384)}function _h(e=!0){return e?gs:ys}async function Ei(){const e=await en(),t=[];for(const r of t)e[r];return{isValid:!0,missing:[],secrets:e}}async function kh(e){console.log(),console.log(us.blue("ℹ Configuration needed")),console.log();const t={};for(const r of e)switch(r){case"OPENAI_API_KEY":const s=await fp({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 Eh(e=!0){const t=await Ei();if(t.isValid)return t.secrets;const r=await kh(t.missing),a={...await en(),...r};await Ch(a,e);const o=_h(e);return console.log(us.green(`✓ Configuration saved to ${o}`)),(await Ei()).secrets}function Ah(e){const t=L.resolve(e),r=L.parse(t).root;return t===r||t===L.resolve(so.homedir())}function dc(e=process.cwd()){let t=L.resolve(e);const r=L.parse(t).root;for(;t!==r;){if(Ah(t))return null;const s=L.join(t,".codeyam","config.json");if(K.existsSync(s))return t;t=L.dirname(t)}return null}let uc=dc();function Ne(){return uc}function Ph(e){uc=e}function pc(e){const t={...e};for(const r in e)if(r.includes(".")){const s=r.replace(/\./g,"");t[s]=e[r]}return t}const jh={"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>`};pc(jh);const Th={"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>`};pc(Th);function ur(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]=ur(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]=ur(o[i],l,r):s[a][i]=l}}else typeof t[a]=="object"&&t[a]!==null?s[a]=ur(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 Mh({projectId:e,commit:t,branch:r}){var l,c,p,u,m,h,f;let s;const a={commitId:t.id,branchId:r.id,active:!0},o=await ih({projectId:e,commitId:t.id,includeBranches:!0});if(o&&o.length>0){s=(l=o.sort((y,x)=>{var w,b,v,N;return(((b=(w=y.branch.metadata)==null?void 0:w.permanent)==null?void 0:b.order)??999)-(((N=(v=x.branch.metadata)==null?void 0:v.permanent)==null?void 0:N.order)??999)})[0])==null?void 0:l.branch,s&&((p=(c=r.metadata)==null?void 0:c.permanent)==null?void 0:p.order)!==void 0&&(((m=(u=r.metadata)==null?void 0:u.permanent)==null?void 0:m.order)<=((f=(h=s.metadata)==null?void 0:h.permanent)==null?void 0:f.order)?s=r:a.active=!1);const g=o.filter(y=>y.active&&y.branch.id!==s.id||!y.active&&y.branch.id===s.id);g.length>0&&await ki(g.map(y=>({...y,active:y.branchId===s.id})))}(o==null?void 0:o.find(g=>g.branchId===a.branchId))||await ki([a])}let Ai=!1;function tn(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=Ne();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 ze(){if(!Ai){Ai=!0;const t=Ne();t&&await Ih(t)}const e=await Eh();process.env.SQLITE_PATH=tn(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function I2(){try{return await ze(),await yo({slug:"__test_connection__",silent:!0}),!0}catch(e){return console.error("Database connection test failed:",e),!1}}async function Re(e){await ze();const t=await yo({slug:e,silent:!0});if(!t)throw new Error(`Project with slug "${e}" not found in database`);const r=await go({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 R2(e){await ze();const t=await yo({slug:e.slug,silent:!0});if(t)return{project:t,created:!1};const r={id:ao(),name:e.slug,slug:e.slug,path:`local:${process.cwd()}`,metadata:{packageManager:e.packageManager,unapprovedPaths:e.unapprovedPaths,webapps:e.webapps}};try{return{project:await Sh([r]),created:!0}}catch(s){throw new Error(`Failed to create project: ${s.message}`)}}async function D2(e){await ze();const t=await go({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 qm([r]);if(!s||s.length===0)throw new Error("Failed to create _local branch");return{branch:s[0],created:!0}}async function $h(e,t,r){await ze();const s=Ne(),a=Xm(`${e.slug}-local-${Date.now()}-${Math.random()}`),o=r.map(c=>{let p="";if(s)try{if(p=$e(`git diff HEAD -- "${c}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!p)try{const u=$e(`cat "${c}"`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const m=u.split(`
|
|
30
|
-
`);p=`@@ -0,0 +1,${m.length} @@
|
|
31
|
-
${m.map(h=>`+${h}`).join(`
|
|
32
|
-
`)}`}}catch{}}catch{}return{fileName:c,status:"modified",patch:p}}),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 wh({projectId:e.id,commits:[i]});if(!l||l.length===0)throw new Error("Failed to create fake commit");return await Mh({projectId:e.id,commit:l[0],branch:t}),l[0]}async function Ih(e){const t=ee.join(e,".codeyam","db.sqlite3"),r=ee.join(e,".codeyam","config.json");if(K.existsSync(t)||!K.existsSync(r))return!1;const{default:s}=await import("./init-BEqlbI84.js");return await s.handler({force:!0,autoInit:!0,$0:"",_:[]}),!0}async function wn(){await ze();const e=await qe({excludeMetadata:!0});if(!e||e.length===0)return[];const t=new Map;for(const c of e){const p=`${c.name}::${c.filePath}`,u=t.get(p);(!u||c.createdAt&&u.createdAt&&c.createdAt>u.createdAt)&&t.set(p,c)}const r=[...t.values()],s=e.map(c=>c.sha),a=await Zt({entityShas:s,excludeMetadata:!0}),o=new Map;if(a)for(const c of a)o.has(c.entitySha)||o.set(c.entitySha,[]),o.get(c.entitySha).push(c);const i=new Map;for(const c of e){const p=`${c.name}::${c.filePath}`,u=i.get(p)||[];u.push(c.sha),i.set(p,u)}return r.map(c=>{const p=o.get(c.sha)||[];if(p.length>0)return{...c,analyses:p};const u=`${c.name}::${c.filePath}`,m=i.get(u)||[];for(const h of m){if(h===c.sha)continue;const f=o.get(h);if(f&&f.length>0)return{...c,analyses:f}}return{...c,analyses:[]}})}async function Rh(e){await ze();const t=await qe(e);return!t||t.length===0?[]:t.filter(r=>{var s;return!((s=r.metadata)!=null&&s.isSuperseded)})}async function js(e,t){await ze();const r=await Zt({entityShas:[e],limit:1});if(r&&r.length>0&&t){const s=await ic({projectId:r[0].projectId,sha:e});if(s)for(const a of r)a.entity=s}return r||[]}async function Ts(e){if(await ze(),e.name&&e.projectId){const r=await Zt({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 Zt({entityShas:[e.sha],limit:1});return t&&t.length>0?t[0]:null}async function mc(e){await ze();const t=await Zt({entityShas:[e],limit:1});return(t==null?void 0:t[0])??null}async function xn(e){await ze();const t=await Fe();if(!t)return null;const{project:r}=await Re(t);return await ic({projectId:r.id,sha:e})}async function hc(e){var s,a,o,i,l,c,p,u;await ze();const t=[],r=[];if((s=e.metadata)!=null&&s.importedExports&&e.metadata.importedExports.length>0){const m=e.metadata.importedExports;for(const h of m){if(!h.filePath||!h.name)continue;const f=h.resolvedFilePath??h.filePath,g=h.resolvedName??h.name;let y=await qe({projectId:e.projectId,filePaths:[f],names:[g]});if((!y||y.length===0)&&h.resolvedIsDefault&&(y=await qe({projectId:e.projectId,filePaths:[f],names:["default"]})),y&&y.length>0){const x=y[0],w=await Zt({entityShas:[x.sha],limit:1});let b,v,N;if(w&&w.length>0&&w[0].scenarios){const C=w[0],E=C.scenarios||[],k=E.length,_=E.find(j=>{var $,T;return(T=($=j.metadata)==null?void 0:$.screenshotPaths)==null?void 0:T[0]});_&&(b=(o=(a=_.metadata)==null?void 0:a.screenshotPaths)==null?void 0:o[0],v=_.name),N={status:((i=x.metadata)==null?void 0:i.previousVersionWithAnalyses)||C.entitySha!==x.sha?"out_of_date":"up_to_date",scenarioCount:k,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 N={status:"not_analyzed"};t.push({...x,screenshotPath:b,scenarioName:v,analysisStatus:N})}}}if((l=e.metadata)!=null&&l.importedBy){const m=[];for(const h in e.metadata.importedBy)for(const f in e.metadata.importedBy[h]){const g=e.metadata.importedBy[h][f];g.shas&&m.push(...g.shas)}if(m.length>0){const h=await qe({projectId:e.projectId,shas:m});if(h)for(const f of h){const g=await Zt({entityShas:[f.sha],limit:1});let y,x,w;if(g&&g.length>0&&g[0].scenarios){const b=g[0],v=b.scenarios||[],N=v.length,C=v.find(k=>{var _,S;return(S=(_=k.metadata)==null?void 0:_.screenshotPaths)==null?void 0:S[0]});C&&(y=(p=(c=C.metadata)==null?void 0:c.screenshotPaths)==null?void 0:p[0],x=C.name),w={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||b.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:N,timestamp:b.createdAt?new Date(b.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"};r.push({...f,screenshotPath:y,scenarioName:x,analysisStatus:w})}}}return{importedEntities:t,importingEntities:r}}async function Fe(){try{const e=Ne();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await Pe.readFile(t,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function Wn(){await ze();try{const e=await Fe();if(!e)return null;const{project:t,branch:r}=await Re(e),s=await hs({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 Ms(){try{const e=Ne();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await Pe.readFile(t,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function fc(e){try{const t=Ne();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 Pe.readFile(r,"utf8")}catch(t){return console.error("[getEntityCodeFromFilesystem] Error reading file:",t),null}}async function gc(e){try{const t=Ne();if(!t||!e.filePath)return!1;const r=ee.join(t,e.filePath),a=(await Pe.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 yc(e){if(await ze(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const t=await qe({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!t||t.length===0)return[];const r=t.map(i=>i.sha),s=await Zt({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((c,p)=>{const u=new Date(c.createdAt||0).getTime();return new Date(p.createdAt||0).getTime()-u});const o=t.map(i=>({...i,analyses:a.get(i.sha)||[]}));return o.sort((i,l)=>{var u,m;const c=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",p=((m=l.analyses[0])==null?void 0:m.createdAt)||l.createdAt||"";return new Date(p).getTime()-new Date(c).getTime()}),o}async function xc(e){try{const t=Ne();if(!t)return console.error("[updateProjectConfig] No project root found"),!1;const r=ee.join(t,".codeyam","config.json"),s=await Pe.readFile(r,"utf8"),a=JSON.parse(s),o={...a,...e},i=JSON.stringify(o,null,2);if(await Pe.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 Dn({projectSlug:a.projectSlug,metadataUpdate:l})}return!0}catch(t){return console.error("[updateProjectConfig] Error:",t),!1}}const Dh=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:wn,getAnalysesForEntity:js,getAnalysisForExactEntitySha:mc,getCurrentCommit:Wn,getCurrentEntities:Rh,getEntityBySha:xn,getEntityCodeFromFilesystem:fc,getEntityHistory:yc,getLatestAnalysisForEntity:Ts,getProjectConfig:Ms,getProjectSlug:Fe,getRelatedEntities:hc,hasFileBeenModifiedSinceEntity:gc,requireBranchAndProject:Re,updateProjectConfig:xc},Symbol.toStringTag,{value:"Module"})),bc="secrets.json";function wc(e){return ee.join(e,".codeyam",bc)}function vc(){return ee.join(Da.homedir(),".codeyam",bc)}async function $s(e){let t={};try{const r=vc(),s=await Pe.readFile(r,"utf-8");t=JSON.parse(s)}catch{}try{const r=wc(e),s=await Pe.readFile(r,"utf-8"),a=JSON.parse(s);t={...t,...a}}catch{}return t}async function Oh(e,t,r=!0){const s=r?vc():wc(e),a=ee.dirname(s);await Pe.mkdir(a,{recursive:!0}),await Pe.writeFile(s,JSON.stringify(t,null,2)+`
|
|
33
|
-
`,"utf-8")}async function Fh(e){const t=await $s(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 Lh=3;let ar=0;async function Wr(e){if(!e||e.length===0)return[];if(ar>=Lh)return console.warn(`[Loader] Circuit breaker open (${ar} 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,ar++,console.warn(`[Loader] Entity fetch timeout after ${t}ms for ${e.length} entities`),r([]))},t);qe({shas:e,excludeMetadata:!0}).then(o=>{s||(s=!0,clearTimeout(a),ar=0,r(o||[]))}).catch(()=>{s||(s=!0,clearTimeout(a),ar++,r([]))})})}function zh({sourcePath:e,destinationPath:t,excludes:r,silent:s}){if(process.platform!=="darwin")return!1;if(xt(t))try{if(op(t).length>0)return!1;pa(t,{recursive:!0})}catch{return!1}try{$e(`cp -c -R "${e}" "${t}"`,{stdio:"pipe",timeout:3e5});for(const a of r)if(a.includes("*"))try{$e(`rm -rf "${xr(t,a)}"`,{stdio:"pipe",shell:"/bin/sh"})}catch{}else{const o=xr(t,a);xt(o)&&pa(o,{recursive:!0,force:!0})}return s||console.log(`Directory cloned (APFS CoW) from ${e} to ${t}`),!0}catch{if(xt(t))try{pa(t,{recursive:!0})}catch{}return!1}}async function Bh({sourcePath:e,destinationPath:t,excludes:r=[],keepExisting:s=!1,silent:a=!1,extraArgs:o=[]}){const i=Date.now();if(!s&&o.length===0&&zh({sourcePath:e,destinationPath:t,excludes:r,silent:a})){if(!a){const c=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${c}s]`)}return}return new Promise((l,c)=>{const p=e.endsWith("/")?e:`${e}/`,u=t.endsWith("/")?t:`${t}/`,m=["-a","--no-specials"];s||m.push("--delete","--force"),m.push(...o);for(const f of r)m.push(`--exclude=${f}`);m.push(p,u);const h=St("rsync",m);h.on("exit",f=>{if(f===0){if(!a){const g=((Date.now()-i)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${t} [Time: ${g}s]`)}l()}else console.error(`CodeYam Error: rsync failed with code: ${f}`,JSON.stringify({rsyncArgs:m},null,2)),c(new Error(`rsync failed with exit code ${f}`))}),h.on("error",f=>{a||console.log("Error occurred:",f),c(f)})})}const Yh=io(oo);async function Uh(e){return new Promise(t=>setTimeout(t,e))}function Wh(e){try{return process.kill(e,0),!0}catch{return!1}}async function Nc(e){try{const{stdout:t}=await Yh(`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 Nc(a);s.push(...o)}return s}catch{return[]}}function Pi(e,t,r){try{process.kill(e,t)}catch(s){r==null||r(`Error sending ${t} to process ${e}: ${s}`)}}async function Jh(e,t,r){const s=await Nc(e);for(const a of s.reverse())await Pi(a,t,r);await Pi(e,t,r)}async function br(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 Jh(e,o,t);for(let l=0;l<i;l++)if(await Uh(1e3),s+=1e3,!await Wh(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 Hh(e){const t=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=t,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:Ap(),createdAt:t}}yp.config({quiet:!0});var Sc=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(Sc||{});class Vh extends xp{constructor(){super(...arguments),this.processes=new Map}register(t){const r=bp(),{process:s,type:a,name:o,metadata:i,parentId:l}=t,c={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:c,process:s}),l){const m=this.processes.get(l);m&&(m.info.children=m.info.children||[],m.info.children.push(r))}const p=(m,h)=>{this.handleProcessExit(r,m,h)},u=m=>{this.handleProcessError(r,m)};return s.on("exit",p),s.on("error",u),s.__cleanup=()=>{s.removeListener("exit",p),s.removeListener("error",u)},this.emit("processStarted",c),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 br(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 ba=null;function Gh(){return ba||(ba=new Vh),ba}const Kh={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function qh({command:e,args:t,workingDir:r,outputOptions:s=Kh,processName:a,env:o}){const i={...process.env,...o||{},CODEYAM_PROCESS_NAME:`codeyam-${a}`},l=St(e,t,{cwd:r,env:i});return Gh().register({process:l,type:Sc.Other,name:a,metadata:{command:e,args:t,workingDir:r}}),{promise:new Promise(u=>{const m=f=>{const g=ee.join(r,"log.txt");K.appendFile(g,f,y=>{y&&console.log("Error writing to log file:",y)})},h=(f,g="")=>{const y=new Date().toLocaleString();return f.split(`
|
|
35
|
-
`).map(w=>w.trim()?`[${y}]${g} ${w}`:w).join(`
|
|
36
|
-
`)};l.stdout.on("data",function(f){const g=(f==null?void 0:f.toString())??"",y=h(g);s.stdoutToConsole&&console.log(y),s.stdoutToFile&&m(y+`
|
|
37
|
-
`),s.stdoutCallback&&s.stdoutCallback(g)}),l.stderr.on("data",function(f){const g=(f==null?void 0:f.toString())??"",y=h(g,"<STDERR>");s.stderrToConsole&&console.error(y),s.stderrToFile&&m(y+`
|
|
38
|
-
`),s.stderrCallback&&s.stderrCallback(g)}),l.on("exit",function(f){u(f)})}),process:l}}function Qh(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 Zh({absoluteCodeyamRootPath:e,startEnv:t,startArgs:r,outputOptions:s}){const a=Object.entries(t).map(([i,l])=>`${i}=${l}`).join(`
|
|
39
|
-
`);K.writeFileSync(`${e}/.env`,a);const o=Qh(r);return qh({command:"node",args:["--enable-source-maps","./dist/project/start.js",...o],workingDir:e,outputOptions:s,processName:"analyzer",env:t})}const Xh="/tmp/codeyam/local-dev";function Cc(e){return L.join(Xh,e)}function _c(e){return L.join(Cc(e),"codeyam")}function At(e){return L.join(Cc(e),"project")}function Is(e){return L.join(_c(e),"log.txt")}const ef=[".sync-metadata.json","__codeyamMocks__"];async function tf(e,t={}){const{port:r,silent:s=!0}=t,a=At(e);if(r)try{$e(`lsof -ti:${r} | xargs kill -9 2>/dev/null || true`,{stdio:s?"ignore":"inherit"})}catch{}try{$e(`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 nf(e,t={}){const{killProcesses:r=!0,port:s,silent:a=!0}=t,o=At(e),i=[],l=[];if(!K.existsSync(o))return{removed:i,errors:l};r&&await tf(e,{port:s,silent:a});for(const c of ef){const p=L.join(o,c);if(K.existsSync(p))try{(await Ae.stat(p)).isDirectory()?await Ae.rm(p,{recursive:!0,force:!0}):await Ae.unlink(p),i.push(c)}catch(u){l.push(`${c}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:l}}const rf=L.dirname(_s(import.meta.url));function sf(e){let t=e;for(;t!==L.dirname(t);){const r=L.join(t,"package.json");if(K.existsSync(r))try{if(JSON.parse(K.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return t}catch{}t=L.dirname(t)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function Rs(){const e=sf(rf);return L.join(e,"analyzer-template")}function Jn(e){return _c(e)}function af(){const e=Rs();return K.existsSync(L.join(e,".finalized"))}async function ji(e){const t=Rs(),r=Jn(e);if(!K.existsSync(t))throw new Error(`Analyzer template not found at ${t}. Did the build process complete successfully?`);await Ae.mkdir(L.dirname(r),{recursive:!0}),await Bh({sourcePath:t,destinationPath:r,silent:!0}),K.existsSync(L.join(r,"dist"))||$e("npm install --include=dev && npm run build",{cwd:r,stdio:"pipe",timeout:3e5})}function Hn(e,t,r,s){const a=Jn(e);if(!K.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 Zh({absoluteCodeyamRootPath:a,startEnv:t,startArgs:r,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:o,stderrToConsole:!1,stderrToFile:!0,stderrCallback:o}})}function of(e){const t=Rs(),r=Jn(e),s=L.join(t,".build-info.json"),a=L.join(r,".build-info.json");if(!K.existsSync(s))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!K.existsSync(r))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!K.existsSync(a))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const o=JSON.parse(K.readFileSync(s,"utf8")),i=JSON.parse(K.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 Er(e,t){const r=Jn(e);if(!K.existsSync(r)){t.update("Creating analyzer..."),await ji(e);return}const s=of(e);s.isFresh||(t.update(`Updating analyzer (${s.reason})...`),await ji(e))}async function xo(e){await nf(e,{killProcesses:!1})}const lf=L.dirname(_s(import.meta.url));function Ds(){let e=lf;for(;e!==L.dirname(e);){const t=L.join(e,"package.json");if(K.existsSync(t))try{if(JSON.parse(K.readFileSync(t,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=L.dirname(e)}return null}function Rn(e){if(!K.existsSync(e))return null;try{return JSON.parse(K.readFileSync(e,"utf8"))}catch{return null}}function cf(){const e=Ds();if(e){const t=[L.join(e,"src/webserver/build-info.json"),L.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const r of t){const s=Rn(r);if(s!=null&&s.semanticVersion)return s.semanticVersion}}return"unknown"}function df(){const e=Ds();if(e){const t=L.join(e,"package.json");try{const r=JSON.parse(K.readFileSync(t,"utf8"));if(r.version)return r.version}catch{}}return"unknown"}const bo=cf(),wa=df();function wo(){if(wa!=="unknown"&&wa!=="0.1.0")return wa;const e=Ds();if(e)for(const t of[L.join(e,"src/webserver/build-info.json"),L.join(e,"codeyam-cli/src/webserver/build-info.json")]){const r=Rn(t);if(r!=null&&r.buildNumber)return`dev (build ${r.buildNumber})`}return"dev"}function kc(e){const t=Ds();let r=null;if(t){const c=[L.join(t,"src/webserver/build-info.json"),L.join(t,"codeyam-cli/src/webserver/build-info.json")];for(const p of c)if(r=Rn(p),r)break}const s=Rs(),a=L.join(s,".build-info.json"),o=Rn(a);let i=null;if(e){const c=Jn(e),p=L.join(c,".build-info.json");i=Rn(p)}let l=!1;return o&&i?l=o.buildTime>i.buildTime:o&&!i&&e&&(l=!0),{cliVersion:bo,webserverVersion:r,templateVersion:o,cachedAnalyzerVersion:i,isCacheStale:l}}function Os(e){const t=Jn(e),r=L.join(t,".build-info.json"),s=Rn(r);return(s==null?void 0:s.version)??null}function vo(){const e=Ne();return e?L.join(e,".codeyam","server.json"):null}function O2(e){const t=vo();t&&K.writeFileSync(t,JSON.stringify(e,null,2))}function Fs(){const e=vo();if(!e||!K.existsSync(e))return null;try{const t=K.readFileSync(e,"utf8");return JSON.parse(t)}catch{return null}}function No(){const e=vo();if(e)try{K.unlinkSync(e)}catch{}}function Ec(e){try{return process.kill(e,0),!0}catch{return!1}}function Ac(){try{const e=process.platform==="win32",r=$e(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{$e(`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 F2(){const e=Fs();if(e)if(!Ec(e.pid))No();else return{running:!0,state:e};const t=Ac();return t.length>0?{running:!0,pids:t}:{running:!1}}function uf(e,t=5e3){if(e.length===0)return!0;const r=Date.now()+t;for(;Date.now()<r;){if(!e.some(a=>Ec(a)))return!0;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,100)}return!1}function L2(){let e=!1;const t=[],r=Fs();if(r){try{process.kill(r.pid,"SIGTERM"),t.push(r.pid),e=!0}catch{}No()}const s=Ac();for(const a of s)try{process.kill(a,"SIGTERM"),t.includes(a)||t.push(a),e=!0}catch{}return uf(t),e}function z2(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 B2(e){try{return $e(`lsof -ti:${e}`,{encoding:"utf8",stdio:["pipe","pipe","pipe"]}),!1}catch{return!0}}const pf="/assets/globals-Yn9W3zp3.css";function Ti({text:e,subtext:t,linkText:r,linkTo:s}){const[a,o]=M(!1);return a?null:n("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:d("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[d("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"})})}),d("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(Ce,{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 mf({version:e}){return n("div",{className:"px-6 sm:px-12 pb-8 mt-auto pt-8",children:d("div",{className:"border-t border-cygray-30 pt-6 flex flex-wrap justify-between items-center gap-4",children:[d("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})]}),d("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 hf({serverVersion:e}){const[t,r]=M("stale"),[s,a]=M(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 c=30,p=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}l++,l<c?setTimeout(()=>void u(),p):(a("Server took too long to restart. Please refresh manually."),r("stale"))};setTimeout(()=>void u(),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:d("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"})})}),d("div",{className:"flex-1",children:[t==="stale"&&d(xe,{children:[n("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),d("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"&&d(xe,{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"&&d(xe,{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")&&d("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[d("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 mt({content:e,label:t="Copy",copiedLabel:r="✓ Copied!",className:s="",duration:a=2e3,ariaLabel:o,icon:i=!1,iconSize:l=14}){const[c,p]=M(!1),u=oe(()=>{navigator.clipboard.writeText(e).then(()=>{p(!0),setTimeout(()=>p(!1),a)}).catch(m=>{console.error("Failed to copy:",m)})},[e,a]);return n("button",{onClick:u,className:`cursor-pointer ${s}`,disabled:c,"aria-label":o||(c?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?c?n(Nt,{size:l,className:"text-green-500"}):n(Et,{size:l}):c?r:t})}function ff({currentVersion:e,latestVersion:t}){const[r,s]=M(!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:d("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[d("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"})})}),d("div",{className:"flex-1",children:[n("p",{className:"text-sm font-medium text-emerald-900",children:"A new version of CodeYam CLI is available"}),d("p",{className:"text-xs text-emerald-700 mt-0.5",children:["Current: ",e," → Latest: ",t]})]}),d("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(mt,{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 or=null,Jr=0;const gf=3600*1e3;function yf(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 xf(){const e=wo();if(or&&Date.now()-Jr<gf)return or;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 or=l,Jr=Date.now(),l}const o=(await s.json()).version;if(!o){const l={updateAvailable:!1,latestVersion:null,currentVersion:e};return or=l,Jr=Date.now(),l}const i={updateAvailable:yf(o,e),latestVersion:o,currentVersion:e};return or=i,Jr=Date.now(),i}catch{return{updateAvailable:!1,latestVersion:null,currentVersion:e}}}function xs(e){return L.join(e,".codeyam","queue.json")}function pr(e){const t=xs(e);if(!K.existsSync(t))return{paused:!1,jobs:[]};try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch(r){return console.error("Failed to load queue state:",r),{paused:!1,jobs:[]}}}function bf(e,t){const r=xs(e),s=L.dirname(r);K.existsSync(s)||K.mkdirSync(s,{recursive:!0});try{K.writeFileSync(r,JSON.stringify(t,null,2),"utf8")}catch(a){throw console.error("Failed to save queue state:",a),a}}const Ss=class Ss extends _r{constructor(t){super(),this.watcher=null,this.debounceTimers=new Map,this.DEBOUNCE_MS=300,this.options=t}start(){try{this.watcher=ue.watch(this.options.projectRootPath,{recursive:!0},(t,r)=>{if(!r||!/\.(ts|tsx|js|jsx|css|scss|json|svg|html)$/.test(r)||Ss.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(!ue.existsSync(r)){ue.existsSync(s)&&(ue.unlinkSync(s),console.log(`[InteractiveSyncWatcher] Removed: ${t}`));return}const a=ee.dirname(s);ue.existsSync(a)||ue.mkdirSync(a,{recursive:!0}),ue.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")}};Ss.IGNORED_DIRS=["node_modules",".git",".codeyam","__codeyamMocks__",".next","dist","build",".turbo",".vercel","coverage",".cache"];let Fa=Ss,wf=class extends _r{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 La="__codeyam_dev_mode_event_emitter__";globalThis[La]||(globalThis[La]=new wf);const Mi=globalThis[La],za=new Map;async function vf(e,t,r){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Nf(e,t,r);else if(e.type==="baseline")await Sf(e,t,r);else if(e.type==="recapture")await Cf(e,t,r);else if(e.type==="capture-only")await _f(e,t,r);else if(e.type==="debug-setup")await kf(e,t,r);else if(e.type==="interactive-start")await Ef(e,t,r);else if(e.type==="interactive-stop")await Af(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 Nf(e,t,r){var y,x,w,b;const{projectSlug:s,commitSha:a,entityShas:o}=e;if(!a)throw new Error("Analysis job missing commitSha");const i=o||[],l=e.onlyDataStructure,{project:c}=await Re(s);await xo(s),await Er(s,{update:v=>console.log(`[Queue] ${v}`)});const p=Os(s),u={...await en(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:tn(),...!l&&i.length>0?{ENTITY_SHAS:i.join(",")}:{},...l?{ONLY_DATA_STRUCTURE:"true"}:{},...p?{ANALYZER_VERSION:p}:{},...process.env.CODEYAM_TRACE_TRANSFORMS?{CODEYAM_TRACE_TRANSFORMS:process.env.CODEYAM_TRACE_TRANSFORMS}:{}},m=(x=(y=c.metadata)==null?void 0:y.webapps)==null?void 0:x[0];if(!m)throw new Error("No webapps found in project metadata");const h={packageManager:((w=c.metadata)==null?void 0:w.packageManager)||"npm",absoluteProjectRootPath:At(s),port:0,noServer:!0,framework:m.framework,...l?{}:{orchestrateCapture:"local-sequential"}},f=Hn(s,u,h),g=v=>{try{return process.kill(v,0),!0}catch{return!1}};await Kt({commitSha:a,runStatusUpdate:{currentEntityShas:i,entityCount:i.length||((b=e.filePaths)==null?void 0:b.length)||0,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString(),analyzerPid:f.process.pid}}),r==null||r.notifyChange("commit");try{try{const v=new Promise((N,C)=>setTimeout(()=>C(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,v]),await Kt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),r==null||r.notifyChange("commit"),await Kt({commitSha:a,runStatusUpdate:{currentEntityShas:[]}}),r==null||r.notifyChange("commit"),await new Promise(N=>setTimeout(N,2e3))}finally{if(f.process.pid)try{g(f.process.pid)&&await br(f.process.pid,()=>{})}catch{}}}catch(v){if(console.error(`[Queue] Analysis job ${e.id} failed:`,v),f.process.pid&&g(f.process.pid))try{await br(f.process.pid,()=>{})}catch{}try{await Kt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:v instanceof Error?v.message:String(v)}}),r==null||r.notifyChange("commit")}catch(N){console.error("[Queue] Failed to update commit metadata after job failure:",N)}throw v}}async function Sf(e,t,r){var h,f,g;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 Re(s);await xo(s),await Er(s,{update:y=>console.log(`[Queue] ${y}`)});const i=Os(s),l={...await en(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:a,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:tn(),...i?{ANALYZER_VERSION:i}:{}},c=(f=(h=o.metadata)==null?void 0:h.webapps)==null?void 0:f[0];if(!c)throw new Error("No webapps found in project metadata");const p={packageManager:((g=o.metadata)==null?void 0:g.packageManager)||"npm",absoluteProjectRootPath:At(s),port:0,noServer:!0,framework:c.framework,orchestrateCapture:"local-sequential"},u=Hn(s,l,p),m=y=>{try{return process.kill(y,0),!0}catch{return!1}};await Kt({commitSha:a,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),r==null||r.notifyChange("commit");try{const y=new Promise((x,w)=>setTimeout(()=>w(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,y]),await Kt({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(u.process.pid)try{m(u.process.pid)&&await br(u.process.pid,()=>{})}catch{}}}async function Cf(e,t,r){var f,g,y,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Recapture job missing analysisId");const l=await Yt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:w}=await import("./index-CjLhfz6Z.js"),b=w(),v=await b.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let N={};v!=null&&v.metadata&&(typeof v.metadata=="string"?N=JSON.parse(v.metadata):N=v.metadata),N.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(N)}).where("sha","=",l.entitySha).execute()}await Un(a,w=>{if(w.readyToBeCaptured=!0,w.scenarios)for(const b of w.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete w.finishedAt});const{project:c}=await Re(s);await Er(s,{update:w=>console.log(`[Queue] ${w}`)});const p=Os(s),u={...await en(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:tn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...p?{ANALYZER_VERSION:p}:{}},m={packageManager:((f=c.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:At(s),port:void 0,noServer:!0,framework:((x=(y=(g=c.metadata)==null?void 0:g.webapps)==null?void 0:y[0])==null?void 0:x.framework)??et.Next,orchestrateCapture:"local-sequential"},h=Hn(s,u,m);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function _f(e,t,r){var f,g,y,x;const{projectSlug:s,analysisId:a,scenarioId:o,defaultWidth:i}=e;if(!a)throw new Error("Capture-only job missing analysisId");const l=await Yt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!l||!l.commit)throw new Error(`Analysis ${a} not found`);if(i){const{getDatabase:w}=await import("./index-CjLhfz6Z.js"),b=w(),v=await b.selectFrom("entities").select(["metadata"]).where("sha","=",l.entitySha).executeTakeFirst();let N={};v!=null&&v.metadata&&(typeof v.metadata=="string"?N=JSON.parse(v.metadata):N=v.metadata),N.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(N)}).where("sha","=",l.entitySha).execute()}await Un(a,w=>{if(w.readyToBeCaptured=!0,w.scenarios)for(const b of w.scenarios)(!o||b.name===o)&&(delete b.finishedAt,delete b.startedAt,delete b.screenshotStartedAt,delete b.screenshotFinishedAt,delete b.interactiveStartedAt,delete b.interactiveFinishedAt,delete b.error,delete b.errorStack);delete w.finishedAt});const{project:c}=await Re(s);await Er(s,{update:w=>console.log(`[Queue] ${w}`)});const p=Os(s);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await en(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:l.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:tn(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:a,...o?{SCENARIO_IDS:o}:{},...p?{ANALYZER_VERSION:p}:{}},m={packageManager:((f=c.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:At(s),port:void 0,noServer:!0,fast:!0,framework:((x=(y=(g=c.metadata)==null?void 0:g.webapps)==null?void 0:y[0])==null?void 0:x.framework)??et.Next,orchestrateCapture:"local-sequential"},h=Hn(s,u,m);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function kf(e,t,r){var h,f,g,y;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Debug setup job missing analysisId");const i=await Yt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:l}=await Re(s);await xo(s),await Er(s,{update:x=>console.log(`[Queue] ${x}`)});const c={...await en(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:tn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,PREP_ONLY:"true"};o&&(c.SCENARIO_IDS=o);const p={packageManager:((h=l.metadata)==null?void 0:h.packageManager)||"npm",absoluteProjectRootPath:At(s),port:void 0,noServer:!1,framework:((y=(g=(f=l.metadata)==null?void 0:f.webapps)==null?void 0:g[0])==null?void 0:y.framework)||et.Next},m=await Hn(s,c,p).promise;if(m!==0)throw new Error(`Prep process exited with code ${m}`)}async function Ef(e,t,r){var x,w,b,v;const{projectSlug:s,analysisId:a,scenarioId:o}=e;if(!a)throw new Error("Interactive start job missing analysisId");const i=await Yt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${a} not found`);const{project:l}=await Re(s),c={...await en(),PROJECT_SLUG:s,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:t,SQLITE_PATH:tn(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:a,INTERACTIVE_MODE:"true"};o&&(c.SCENARIO_IDS=o);const p=At(s),u=ee.join(p,".next","dev","lock");if(ue.existsSync(u)){console.log("[Queue] Found stale .next/dev/lock, cleaning up old processes");try{const N=$e(`pgrep -f ${JSON.stringify(p)} 2>/dev/null || true`,{encoding:"utf-8"}).trim();if(N)for(const C of N.split(`
|
|
42
|
-
`).filter(Boolean))try{process.kill(parseInt(C,10),"SIGTERM"),console.log(`[Queue] Killed stale process ${C}`)}catch{}}catch{}try{ue.unlinkSync(u),console.log("[Queue] Removed stale lock file")}catch{}}const m=ue.existsSync(p)&&ue.existsSync(ee.join(p,"package.json")),h={packageManager:((x=l.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:p,port:void 0,noServer:!1,fast:m,framework:((v=(b=(w=l.metadata)==null?void 0:w.webapps)==null?void 0:b[0])==null?void 0:v.framework)||et.Next};await Un(a,N=>{N.readyToBeCaptured=!0});const f=Hn(s,c,h);await cc(a,N=>{N.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 g=At(s),y=new Fa({projectRootPath:t,tmpProjectPath:g});y.on("sync",N=>{N.type==="file-synced"?Mi.emitFileSynced(N.fileName,N.filePath):N.type==="error"&&Mi.emitError(N.fileName,N.filePath)}),y.start(),za.set(a,y),console.log(`[Queue] File sync watcher started for analysis ${a}`)}async function Af(e,t,r){var p;const{projectSlug:s,analysisId:a}=e;if(!a)throw new Error("Interactive stop job missing analysisId");const o=await Yt({id:a,includeScenarios:!0,includeCommitAndBranch:!0});if(!o)throw new Error(`Analysis ${a} not found`);const i=(p=o.metadata)==null?void 0:p.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${a}`);return}const l=za.get(a);l&&(l.stop(),za.delete(a),console.log(`[Queue] File sync watcher stopped for analysis ${a}`));const c=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${a}, killing PID: ${c}`);try{try{process.kill(c,0)}catch{console.log(`[Queue] Process ${c} already exited`);return}await br(c,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${c}`)}catch(u){throw console.error(`[Queue] Failed to kill process ${c}:`,u),u}finally{await cc(a,u=>{u.interactiveMode=null})}}class Pf{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=pr(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||ao(),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 vf(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(){bf(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class jf{constructor(t,r,s=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=t,this.onChange=r,this.debounceMs=s}start(){const t=xs(this.projectRoot);if(!K.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=xs(this.projectRoot),r=t.substring(0,t.lastIndexOf("/"));try{this.watcher=K.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=K.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 Tf{constructor(t,r,s){this.fileWatcher=null,this.serverInfo=t,this.projectRoot=r,this.onStateChange=s,this.cachedState=pr(r)}start(){this.cachedState=pr(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 jf(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=pr(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=pr(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 Mf(e){const t=L.join(e,".codeyam","server.json");if(!K.existsSync(t))return null;try{const r=K.readFileSync(t,"utf8");return JSON.parse(r)}catch{return null}}function $f(e){try{return process.kill(e,0),!0}catch{return!1}}async function If(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 Rf(e){const t=Mf(e);return!t||!$f(t.pid)||!await If(t.url)?null:{url:t.url,port:t.port,pid:t.pid}}class Df extends _r{constructor(){super();Rt(this,"watcher",null);Rt(this,"dbPath",null);Rt(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=tn();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 bt=new Df;let mn=null,mr=null;async function Of(){if(!mn){if(mr){await mr;return}mr=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||dc()||process.cwd();if(Ph(e),console.log(`[GlobalQueue] Project root: ${e}`),await ze(),process.env.NODE_ENV==="development")try{const r=ee.join(e,".codeyam","config.json"),a=JSON.parse(await ue.promises.readFile(r,"utf8")).projectSlug;a&&(await Dn({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 Rf(e);if(t){console.log(`[GlobalQueue] Detected background server at ${t.url} (PID: ${t.pid})`),console.log("[GlobalQueue] Using proxy queue");const r=new Tf(t,e,()=>{bt.notifyChange("unknown")});await r.start(),mn=r}else{console.log("[GlobalQueue] No background server detected, using local queue");const r=new Pf(e,bt);await r.start(),mn=r}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await mr}}async function Ut(){return mn||await Of(),mn}function Ff(){return mn||(mr&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const Lf=()=>[{rel:"stylesheet",href:pf},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}],zf={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:wo()};async function Bf({request:e,context:t}){var r,s,a,o,i,l,c,p,u,m,h;try{const f=e.signal,g=()=>{if(f.aborted)throw new Response(null,{status:499})};g();const y=Ne()||process.cwd(),[x,w,b]=await Promise.all([Fe(),$s(y),xf().catch(()=>null)]);if(!x)throw new Error("Project slug not found");const{project:v,branch:N}=await Re(x);g();const C=await hs({projectId:v.id,branchId:N.id,limit:20,skipRelations:!0});g();const E=C.length>0?C[0]:null,k=t.analysisQueue||Ff(),_=k==null?void 0:k.getState();g();const S=await Promise.all(((_==null?void 0:_.jobs)||[]).map(async V=>{var ie;const ne=await Wr(V.entityShas||[]);return ne.length===0&&((ie=V.entityShas)!=null&&ie.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",V.id),{...V,entities:ne}}));let j=null;if(_!=null&&_.currentlyExecuting){const V=_.currentlyExecuting,ne=await Wr(V.entityShas||[]);ne.length===0&&((r=V.entityShas)!=null&&r.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",V.id),j={...V,entities:ne}}const $=j?S.filter(V=>V.id!==j.id):S;let T=((a=(s=E==null?void 0:E.metadata)==null?void 0:s.currentRun)==null?void 0:a.currentEntityShas)||[];if(T.length===0){const V=((o=E==null?void 0:E.metadata)==null?void 0:o.historicalRuns)||[];if(V.length>0){const ie=[...V].sort((we,le)=>{const ce=we.archivedAt||we.createdAt||"";return(le.archivedAt||le.createdAt||"").localeCompare(ce)})[0];if(ie){const we=ie.analysisCompletedAt||ie.createdAt;if(we){const le=new Date(we).getTime(),ve=Date.now()-1440*60*1e3;le>ve&&(T=ie.currentEntityShas||[])}}}}const R=await Wr(T),I=[];w.ANTHROPIC_API_KEY&&I.push("ANTHROPIC_API_KEY"),w.GROQ_API_KEY&&I.push("GROQ_API_KEY"),w.OPENAI_API_KEY&&I.push("OPENAI_API_KEY"),w.OPENROUTER_API_KEY&&I.push("OPENROUTER_API_KEY"),g();const P=[];for(const V of C){const ne=((i=V.metadata)==null?void 0:i.historicalRuns)||[];for(const ie of ne)P.push(ie)}P.sort((V,ne)=>{const ie=V.archivedAt||V.analysisCompletedAt||V.createdAt||"";return(ne.archivedAt||ne.analysisCompletedAt||ne.createdAt||"").localeCompare(ie)});const H=new Set(((l=j==null?void 0:j.entities)==null?void 0:l.map(V=>V.sha))||[]),F=P.filter(V=>!(V.currentEntityShas||[]).some(ie=>H.has(ie))).slice(0,3),J=new Set;for(const V of F)for(const ne of V.currentEntityShas||[])J.add(ne);const Y=await Wr(Array.from(J)),z=new Map;for(const V of Y)z.set(V.sha,V);const A=F.map(V=>({...V,entities:(V.currentEntityShas||[]).map(ne=>z.get(ne)).filter(ne=>ne!=null)})),B=Fs(),G=(B==null?void 0:B.cliVersion)??"unknown",q=G!=="unknown"&&G!==bo,Q=((p=(c=v.metadata)==null?void 0:c.labs)==null?void 0:p.simulations)??!1,U=Q?af():!1,D=((u=v.metadata)==null?void 0:u.editorMode)??!1,O={currentRun:(m=E==null?void 0:E.metadata)==null?void 0:m.currentRun,projectSlug:x,currentEntities:R,availableAPIKeys:I,queuedJobCount:$.length,queueJobs:$,currentlyExecuting:j,historicalRuns:A,isServerOutOfDate:q,serverVersion:G,npmUpdate:b!=null&&b.updateAvailable&&b.latestVersion?{latestVersion:b.latestVersion,currentVersion:b.currentVersion}:null,labs:((h=v.metadata)==null?void 0:h.labs)??null,simulationsEnabled:Q,isSimulationsReady:U,isAdmin:!!process.env.CODEYAM_ADMIN,editorMode:D,displayVersion:wo()};return X(O)}catch(f){return f instanceof Response&&f.status===499||console.error("Failed to load root data:",f),X(zf)}}function Yf(){const{currentRun:e,projectSlug:t,currentEntities:r,availableAPIKeys:s,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:l,isServerOutOfDate:c,serverVersion:p,npmUpdate:u,labs:m,simulationsEnabled:h,isSimulationsReady:f,isAdmin:g,editorMode:y,displayVersion:x}=tt(),{toasts:w,closeToast:b}=mo(),v=Lt(),N=ge(v),C=Sr(),E=ge(C.pathname);re(()=>{N.current=v},[v]),re(()=>{E.current=C.pathname},[C.pathname]);const k=C.pathname.startsWith("/entity/")&&C.pathname.includes("/edit/")||C.pathname.startsWith("/dev/")||C.pathname.startsWith("/editor"),_=C.pathname.includes("/fullscreen")||C.pathname.startsWith("/editor");return re(()=>{let S=null,j=null,$=0;function T(){S||(S=new EventSource("/api/events"),S.addEventListener("message",P=>{const H=JSON.parse(P.data);(H.type==="queue"||H.type==="db-change")&&H.type;const W=Dp(E.current),F=Op({now:Date.now(),lastRevalidation:$,throttleMs:W});F==="immediate"?(N.current.revalidate(),$=Date.now()):(j&&clearTimeout(j),j=setTimeout(()=>{N.current.revalidate(),$=Date.now(),j=null},F.delayMs))}),S.addEventListener("error",()=>{}))}function R(){j&&(clearTimeout(j),j=null),S&&(S.close(),S=null)}function I(){document.hidden?R():(T(),N.current.revalidate())}return document.hidden||T(),document.addEventListener("visibilitychange",I),()=>{document.removeEventListener("visibilitychange",I),R()}},[]),d(xe,{children:[d("div",{className:`min-h-screen ${k?"":"grid"} bg-cygray-10`,style:k?void 0:{gridTemplateColumns:"65px minmax(0, 1fr)"},children:[!k&&n(Up,{labs:m,isAdmin:g,editorMode:y}),d("div",{className:"max-h-screen overflow-auto bg-cygray-10 flex flex-col min-h-screen",children:[c&&n(hf,{serverVersion:p}),u&&u.currentVersion&&n(ff,{currentVersion:u.currentVersion,latestVersion:u.latestVersion}),h&&!y&&s.length===0&&n(Ti,{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"}),h&&!y&&!f&&n(Ti,{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(zl,{})}),n(mf,{version:x})]})]}),n(Hp,{toasts:w,onClose:b}),!_&&h&&n(Vp,{currentRun:e,projectSlug:t,currentEntities:r,isAnalysisStarting:!1,queuedJobCount:a,queueJobs:o,currentlyExecuting:i,historicalRuns:l})]})}const Uf=Qe(function(){return d("html",{lang:"en",children:[d("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),n(fu,{}),n(gu,{})]}),d("body",{children:[n(Wp,{children:n(Bp,{children:n(Yf,{})})}),n(yu,{}),n(xu,{})]})]})});function Wf(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 Jf=bu(function(){const t=wu(),r=!da(t)&&Wf(t),s=da(t)?t.status:500,a=da(t)?t.statusText||"Server Error":"Something went wrong";return d("html",{lang:"en",children:[d("head",{children:[n("meta",{charSet:"utf-8"}),n("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),d("title",{children:[s," - CodeYam"]})]}),n("body",{style:{margin:0,fontFamily:'"IBM Plex Sans", system-ui, -apple-system, sans-serif',backgroundColor:"#F8F7F6",color:"#232323",display:"flex",alignItems:"center",justifyContent:"center",minHeight:"100vh"},children:d("div",{style:{maxWidth:520,width:"100%",padding:"48px 32px",textAlign:"center"},children:[n("div",{style:{fontSize:64,fontWeight:700,color:"#005C75",lineHeight:1,marginBottom:8},children:s}),n("h1",{style:{fontSize:22,fontWeight:600,margin:"0 0 16px",color:"#232323"},children:a}),r?d("div",{children:[n("p",{style:{fontSize:15,color:"#3E3E3E",lineHeight:1.6,margin:"0 0 24px"},children:"It looks like the CodeYam server is no longer running. This usually happens when the terminal session that started it was closed."}),n("div",{style:{backgroundColor:"#232323",color:"#D7FF63",borderRadius:8,padding:"14px 20px",fontFamily:'"IBM Plex Mono", monospace',fontSize:14,marginBottom:24,display:"inline-block"},children:"codeyam editor"}),n("p",{style:{fontSize:14,color:"#8E8E8E",margin:0},children:"Run this command in your project directory to restart the server, then refresh this page."})]}):d("div",{children:[n("p",{style:{fontSize:15,color:"#3E3E3E",lineHeight:1.6,margin:"0 0 24px"},children:"An unexpected error occurred. Try refreshing the page."}),t instanceof Error&&t.message&&n("pre",{style:{backgroundColor:"#EFEFEF",borderRadius:8,padding:"14px 20px",fontFamily:'"IBM Plex Mono", monospace',fontSize:13,color:"#3E3E3E",textAlign:"left",overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0},children:t.message})]})]})})]})}),Hf=Object.freeze(Object.defineProperty({__proto__:null,ErrorBoundary:Jf,default:Uf,links:Lf,loader:Bf},Symbol.toStringTag,{value:"Module"}));function Hr(e){const t=e.replace(/[^a-zA-Z0-9_]+/g,"_");return t.slice(0,1).toUpperCase()+t.slice(1)}function vn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:o=!0,refreshTrigger:i=0}){const l=Ue(),[c,p]=M(null),[u,m]=M(!1),[h,f]=M(!1),[g,y]=M(!1),x=ge(!1),w=ge(null),b=ge(null),v=ge(null),[N,C]=M(0),[E,k]=M(0),_=ge(null),S=ge(!1),{interactiveUrl:j,resetLogs:$}=zt(a,o),T=ge(t),R=ge(i);re(()=>{R.current!==i&&(R.current=i,c&&(console.log("[useInteractiveMode] Manual refresh triggered"),f(!0),y(!1),C(0),k(P=>P+1),S.current=!1,_.current&&(clearTimeout(_.current),_.current=null)))},[i,c]),re(()=>{if(T.current!==t&&(T.current=t,w.current&&b.current&&r)){let P=w.current;if(v.current&&s){const F=Hr(v.current),J=Hr(s);F!==J&&(P=P.replace(F,J),v.current=s)}const H=Hr(b.current),W=Hr(r);P=P.replace(H,W),b.current=r,p(P),f(!0),y(!1),C(0),k(F=>F+1),S.current=!1,_.current&&(clearTimeout(_.current),_.current=null);return}},[t,r,s]),re(()=>{if(j){const P=j+"?width=600px";w.current=P,r&&(b.current=r),s&&(v.current=s),p(P),m(!1),f(!0)}},[j]),re(()=>{const P=H=>{H.data.type==="codeyam-resize"&&(S.current||(S.current=!0,_.current&&(clearTimeout(_.current),_.current=null),C(0),y(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{f(!1)})})))};return window.addEventListener("message",P),()=>window.removeEventListener("message",P)},[]);const I=()=>{S.current=!1,_.current&&clearTimeout(_.current);const P=300*Math.pow(2,N);_.current=setTimeout(()=>{S.current||(N<2?(C(H=>H+1),k(H=>H+1),f(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),y(!0),f(!1)))},P)};return re(()=>{o&&!x.current&&t&&e&&(x.current=!0,m(!0),y(!1),p(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(H){console.error("[useInteractiveMode] Failed to clear log file:",H)}$(),l.submit({action:"start",analysisId:e,scenarioId:t},{method:"post",action:"/api/interactive-mode"})})())},[o,t,e,$,a]),re(()=>{const P=e,H=()=>{if(x.current&&P){const F=new URLSearchParams({action:"stop",analysisId:P});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const J=navigator.sendBeacon("/api/interactive-mode",F);console.log("[useInteractiveMode] sendBeacon result:",J),J||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:F,keepalive:!0}).catch(Y=>console.error("Failed to stop interactive mode:",Y)))}},W=()=>{H()};return window.addEventListener("beforeunload",W),()=>{window.removeEventListener("beforeunload",W),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:x.current,analysisId:P}),H()}},[e]),{interactiveServerUrl:c,isStarting:u,isLoading:h,showIframe:g,iframeKey:E,onIframeLoad:I}}const Vr=10,Vf=1024;function So({currentViewportWidth:e,currentPresetName:t,onDevicePresetClick:r,devicePresets:s,onHoverChange:a,hideLabel:o=!1,lightMode:i=!1}){const[l,c]=M(null),p=ge(null),u=ae(()=>[...s].sort((b,v)=>b.width-v.width),[s]),{fittingPresets:m,overflowPresets:h}=ae(()=>{const b=[],v=[];for(const N of u)N.width<=Vf?b.push(N):v.push(N);return v.sort((N,C)=>C.width-N.width),{fittingPresets:b,overflowPresets:v}},[u]),f=oe(b=>{if(!p.current)return null;const v=p.current.getBoundingClientRect(),N=b-v.left,C=v.width,E=C/2,_=(m.length>0?m[m.length-1].width:0)/2,S=E-_,j=E+_,$=h.length>0?(h.length-1)*Vr:0;if(h.length>0){if(N<S){if(N<=$){const R=Math.min(Math.floor(N/Vr),h.length-1);return h[R]}return h[h.length-1]}if(N>j){const R=C-N;if(R<=$){const I=Math.min(Math.floor(R/Vr),h.length-1);return h[I]}return h[h.length-1]}}const T=Math.abs(N-E);for(let R=m.length-1;R>=0;R--){const I=m[R],P=m[R-1],H=I.width/2,W=P?P.width/2:0;if(T<=H&&T>=W)return I}return m[0]||h[h.length-1]||null},[m,h]),g=oe(b=>{const v=f(b.clientX);c(v),a==null||a(v)},[f,a]),y=oe(()=>{c(null),a==null||a(null)},[a]),x=oe(b=>{const v=f(b.clientX);v&&r(v)},[f,r]),w=l||{name:t,width:e};return d("div",{ref:p,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:g,onMouseLeave:y,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:m.map(b=>{const v=b.width===e,N=(l==null?void 0:l.name)===b.name,C=b.width/2;return d("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 ${v||N?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 ${v||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),n("div",{className:"absolute inset-0 pointer-events-none",children:h.map((b,v)=>{const N=v*Vr,C=b.width===e,E=(l==null?void 0:l.name)===b.name;return d("div",{children:[n("div",{className:"absolute top-0 bottom-0",style:{left:`${N}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||E?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:`${N}px`},children:n("div",{className:`w-0.5 h-full transition-colors duration-75 ${C||E?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),!o&&n("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:d("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:[w.name," - ",w.width,"px"]})})]})}function Gf({currentWidth:e,currentHeight:t,devicePresets:r,customSizes:s,onApply:a,onSave:o,onRemove:i,onClose:l}){const[c,p]=M(String(e)),[u,m]=M(String(t)),[h,f]=M(""),[g,y]=M(!1),x=ge(null),w=ge(null);re(()=>{const S=j=>{x.current&&!x.current.contains(j.target)&&l()};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[l]),re(()=>{const S=j=>{j.key==="Escape"&&l()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[l]),re(()=>{var S;(S=w.current)==null||S.select()},[]);const b=parseInt(c,10),v=parseInt(u,10),N=b>0&&v>0,C=N&&(b!==e||v!==t),E=()=>{N&&(a({name:"Custom",width:b,height:v}),l())},k=()=>{const S=h.trim();!S||!N||(o(S,b,v),a({name:S,width:b,height:v}),l())},_=S=>{S.key==="Enter"&&(g&&h.trim()?k():C&&E())};return d("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&&d("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(S=>d("button",{onClick:()=>{a(S),l()},className:`w-full px-3 py-1.5 text-left text-xs transition-colors cursor-pointer ${S.width===e&&S.height===t?"text-white bg-[#444]":"text-gray-300 hover:text-white hover:bg-[#333]"}`,children:[n("span",{className:"font-medium",children:S.name}),d("span",{className:"text-gray-500 ml-1.5",children:[S.width,"×",S.height]})]},S.name))]}),s.length>0&&d("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(S=>d("div",{className:"flex items-center group hover:bg-[#333] transition-colors",children:[d("button",{onClick:()=>{a(S),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:S.name}),d("span",{className:"text-gray-500 ml-1.5",children:[S.width,"×",S.height]})]}),n("button",{onClick:()=>i(S.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"})})})]},S.name))]}),d("div",{className:"p-3",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n("input",{ref:w,type:"number",value:c,onChange:S=>p(S.target.value),onKeyDown:_,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:u,onChange:S=>m(S.target.value),onKeyDown:_,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"})]}),d("div",{className:"flex gap-2",children:[n("button",{onClick:E,disabled:!N||!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"}),g?d("div",{className:"flex gap-1",children:[n("input",{type:"text",value:h,onChange:S=>f(S.target.value),onKeyDown:_,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:k,disabled:!h.trim()||!N,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:()=>y(!0),disabled:!N,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 Co({width:e,height:t,onSave:r,onCancel:s}){const[a,o]=M(""),[i,l]=M(""),c=()=>{const p=a.trim();if(!p){l("Please enter a name");return}r(p)};return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:d("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[d("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"})})})]}),d("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"}),d("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",t,"px"]})]}),d("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:p=>{o(p.target.value),l("")},onKeyDown:p=>{p.key==="Enter"&&a.trim()&&c(),p.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})]}),d("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:c,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 Ls(e){const[t,r]=M([]),s=e?`codeyam-custom-sizes-${e}`:null;re(()=>{if(!s||typeof window>"u"){r([]);return}try{const l=localStorage.getItem(s);if(l){const c=JSON.parse(l);Array.isArray(c)&&r(c)}}catch(l){console.error("[useCustomSizes] Failed to load custom sizes:",l),r([])}},[s]);const a=oe(l=>{if(!(!s||typeof window>"u"))try{localStorage.setItem(s,JSON.stringify(l))}catch(c){console.error("[useCustomSizes] Failed to save custom sizes:",c)}},[s]),o=oe((l,c,p)=>{r(u=>{const m=u.findIndex(g=>g.name===l),h={name:l,width:c,height:p};let f;return m>=0?(f=[...u],f[m]=h):f=[...u,h],a(f),f})},[a]),i=oe(l=>{r(c=>{const p=c.filter(u=>u.name!==l);return a(p),p})},[a]);return{customSizes:t,addCustomSize:o,removeCustomSize:i}}function Ft(){return d("div",{className:"spinner-container",children:[n("span",{className:"loader"}),n("style",{children:`
|
|
43
|
-
.loader {
|
|
44
|
-
width: 48px;
|
|
45
|
-
height: 48px;
|
|
46
|
-
border: 3px solid rgba(0, 92, 117, 0.2);
|
|
47
|
-
border-radius: 50%;
|
|
48
|
-
display: inline-block;
|
|
49
|
-
position: relative;
|
|
50
|
-
box-sizing: border-box;
|
|
51
|
-
animation: rotation 1s linear infinite;
|
|
52
|
-
}
|
|
53
|
-
.loader::after {
|
|
54
|
-
content: '';
|
|
55
|
-
box-sizing: border-box;
|
|
56
|
-
position: absolute;
|
|
57
|
-
left: 50%;
|
|
58
|
-
top: 50%;
|
|
59
|
-
transform: translate(-50%, -50%);
|
|
60
|
-
width: 56px;
|
|
61
|
-
height: 56px;
|
|
62
|
-
border-radius: 50%;
|
|
63
|
-
border: 3px solid;
|
|
64
|
-
border-color: #005c75 transparent;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
@keyframes rotation {
|
|
68
|
-
0% {
|
|
69
|
-
transform: rotate(0deg);
|
|
70
|
-
}
|
|
71
|
-
100% {
|
|
72
|
-
transform: rotate(360deg);
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
`})]})}const $i=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],Kf=80;function On(){const[e,t]=M(0);return re(()=>{const r=setInterval(()=>{t(s=>(s+1)%$i.length)},Kf);return()=>clearInterval(r)},[]),n("span",{className:"inline-block mr-2",children:$i[e]})}async function qf({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw X("Invalid parameters",{status:400});const s=await xn(t);if(!s)throw X("Entity not found",{status:404});const a=await Ts(s),o=((l=a==null?void 0:a.scenarios)==null?void 0:l.find(c=>c.id===r))||null;if(!o)throw X("Scenario not found",{status:404});const i=await Fe();return X({entity:s,scenario:o,analysis:a,projectSlug:i})}const va=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1920,height:1080}],Qf=Qe(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=tt(),o=Pt(),[i]=Ln(),[l,c]=M(null),[p,u]=M(1920),[m,h]=M({name:"Desktop",width:1920,height:1080}),[f,g]=M(!1),[y,x]=M(null),{customSizes:w,addCustomSize:b}=Ls(a),v=ae(()=>[...va,...w],[w]),N=ge(null),[C,E]=M(1),k=oe(()=>{if(!N.current)return;const D=32,O=N.current.clientWidth-D,V=N.current.clientHeight-D,ne=m.width,ie=m.height??900,we=Math.min(1,O/ne,V/ie);E(we)},[m.width,m.height]);re(()=>(k(),window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)),[k]);const{interactiveServerUrl:_,isStarting:S,isLoading:j,showIframe:$,iframeKey:T,onIframeLoad:R}=vn({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:I}=zt(a,S||j),P=()=>{o(`/entity/${t.sha}`)},H=(D,O)=>{u(D);const V=v.find(ie=>ie.width===D&&ie.height===O);c(V||null),h({name:(V==null?void 0:V.name)||"Custom",width:D,height:O})},W=D=>{c(D),u(D.width),h({name:D.name,width:D.width,height:D.height})},F=D=>{b(D,m.width,m.height??900),g(!1),h(O=>({...O,name:D}))},J=((s==null?void 0:s.scenarios)||[]).filter(D=>{var O;return!((O=D.metadata)!=null&&O.sameAsDefault)}),Y=J.findIndex(D=>D.id===(r==null?void 0:r.id)),z=Y+1,A=J.length,B=Y>0,G=Y<J.length-1,q=()=>{if(B){const D=J[Y-1],O=encodeURIComponent(`/entity/${t.sha}/scenarios/${D.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${D.id}/fullscreen?from=${O}`)}},Q=()=>{if(G){const D=J[Y+1],O=encodeURIComponent(`/entity/${t.sha}/scenarios/${D.id}/fullscreen`);o(`/entity/${t.sha}/scenarios/${D.id}/fullscreen?from=${O}`)}},U=S||j||!$;return d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[d("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:Es,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),d("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:q,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"})})}),d("span",{className:"text-gray-400 text-sm",children:[z,"/",A]}),n("button",{onClick:Q,disabled:!G,className:`${G?"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"})})})]}),d("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)&&d("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:P,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"})})})]}),d("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:`${va[va.length-1].width}px`,width:"100%"},children:n(So,{currentViewportWidth:p,currentPresetName:m.name,onDevicePresetClick:W,devicePresets:v,hideLabel:!0,onHoverChange:x,lightMode:!0})})}),d("div",{className:"relative z-10 flex items-center gap-2",children:[d("div",{className:"relative w-28 h-5",children:[d("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:(y==null?void 0:y.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"})})]}),d("select",{value:m.name,onChange:D=>{const O=v.find(V=>V.name===D.target.value);O&&W(O)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[v.map(D=>n("option",{value:D.name,children:D.name},D.name)),m.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:m.width,onChange:D=>{const O=parseInt(D.target.value,10);!isNaN(O)&&O>0&&H(O,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:"×"}),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",{ref:N,className:"flex-1 flex items-center justify-center overflow-hidden p-4",style:{backgroundImage:`
|
|
76
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
77
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
78
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
79
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
80
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:_?d("div",{className:"relative bg-white",style:{width:`${m.width}px`,height:`${m.height??900}px`,transform:`scale(${C})`,transformOrigin:"center center"},children:[U&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("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(Ft,{})}),d("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"}),I&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(On,{}),I]})]})]})}),n("iframe",{src:_,className:"w-full h-full border-none",title:`Interactive preview: ${r==null?void 0:r.name}`,onLoad:R,style:{opacity:$?1:0}},T)]}):d("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(Ft,{})}),d("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"}),I&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(On,{}),I]})]})]})}),f&&n(Co,{width:m.width,height:m.height??900,onSave:F,onCancel:()=>g(!1)})]})}),Zf=Object.freeze(Object.defineProperty({__proto__:null,default:Qf,loader:qf},Symbol.toStringTag,{value:"Module"})),$n={sound:"soft-double-tap",systemNotification:!0},Xf=[{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"}],Pc="codeyam-editor-notifications";function eg(){try{const e=localStorage.getItem(Pc);if(!e)return $n;const t=JSON.parse(e);return typeof t=="string"?t==="true"?$n:{...$n,sound:"off",systemNotification:!1}:{...$n,...t}}catch{return $n}}function tg(e){localStorage.setItem(Pc,JSON.stringify(e))}function jc(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 Tc({serverUrl:e,isStarting:t,projectSlug:r,devServerError:s,onStartServer:a,notificationSettings:o,onChangeNotificationSettings:i}){const[l,c]=M(null),[p,u]=M(!1),m=ge(null),h=ge(null);re(()=>{if(!r)return;const w=new EventSource("/api/dev-mode-events");return w.onmessage=b=>{try{const v=JSON.parse(b.data);v.type==="file-synced"&&(c(v.fileName),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{c(null)},5e3))}catch{}},()=>{w.close(),h.current&&clearTimeout(h.current)}},[r]),re(()=>{if(!p)return;function w(b){m.current&&!m.current.contains(b.target)&&u(!1)}return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[p]);let f;s?f="error":t?f="starting":e?f="running":f="stopped";const g={starting:"bg-yellow-400",running:"bg-green-400",stopped:"bg-gray-400",error:"bg-red-400"},y={starting:"Starting...",running:e||"Running",stopped:"Stopped",error:"Error"},x=o&&(o.sound!=="off"||o.systemNotification);return d("div",{className:"bg-[#1e1e1e] border-t border-[#3d3d3d] h-7 flex items-center px-4 gap-4 shrink-0 text-xs font-mono",children:[d("div",{className:"flex items-center gap-2",children:[n("div",{className:`w-2 h-2 rounded-full ${g[f]}`}),d("span",{className:"text-gray-400",children:["Server:"," ",n("span",{className:"text-gray-300",children:y[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&&d(xe,{children:[d("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"})}),d("span",{className:"text-green-400",children:["Synced: ",l]})]}),n("div",{className:"w-px h-3 bg-[#3d3d3d]"})]}),n("div",{className:"flex-1"}),i&&o&&d("div",{className:"relative",ref:m,children:[n("button",{onClick:()=>u(!p),className:`text-[11px] rounded transition-colors cursor-pointer ${x?"text-green-400 hover:text-green-300":"text-gray-500 hover:text-gray-300"}`,children:x?"Notifications On":"Notifications Off"}),p&&d("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:[d("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:Xf.map(w=>n("button",{onClick:()=>{i({...o,sound:w.id}),w.id!=="off"&&jc(w.id)},className:`text-left text-[11px] px-2 py-1 rounded cursor-pointer transition-colors ${o.sound===w.id?"bg-[#444] text-white":"text-gray-300 hover:bg-[#3a3a3a]"}`,children:w.label},w.id))})]}),d("div",{className:"border-t border-[#4d4d4d] pt-2",children:[d("label",{className:"flex items-center gap-2 cursor-pointer",children:[n("input",{type:"checkbox",checked:o.systemNotification,onChange:w=>{const b=w.target.checked;i({...o,systemNotification:b}),b&&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 ng(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(),Ii(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 Ii(e);return r||(t==null||t("canvas","dom",new Error("Canvas addon failed")),{type:"dom",dispose:()=>{}})}async function Ii(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 rg{constructor(t,r){Rt(this,"deferred",!1);Rt(this,"userActiveSinceLastOutput",!1);Rt(this,"actions");Rt(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"}}const sg=`
|
|
81
|
-
.xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
|
|
82
|
-
.xterm.focus, .xterm:focus { outline: none; }
|
|
83
|
-
.xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
|
|
84
|
-
.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; }
|
|
85
|
-
.xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
|
|
86
|
-
.xterm .composition-view.active { display: block; }
|
|
87
|
-
.xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
|
|
88
|
-
.xterm .xterm-screen { position: relative; }
|
|
89
|
-
.xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
|
|
90
|
-
.xterm .xterm-scroll-area { visibility: hidden; }
|
|
91
|
-
.xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
|
|
92
|
-
.xterm.enable-mouse-events { cursor: default; }
|
|
93
|
-
.xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
|
|
94
|
-
.xterm.column-select.focus { cursor: crosshair; }
|
|
95
|
-
.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; }
|
|
96
|
-
.xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
|
|
97
|
-
.xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
|
|
98
|
-
.xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
|
|
99
|
-
.xterm-dim { opacity: 1 !important; }
|
|
100
|
-
.xterm-underline-1 { text-decoration: underline; }
|
|
101
|
-
.xterm-underline-2 { text-decoration: double underline; }
|
|
102
|
-
.xterm-underline-3 { text-decoration: wavy underline; }
|
|
103
|
-
.xterm-underline-4 { text-decoration: dotted underline; }
|
|
104
|
-
.xterm-underline-5 { text-decoration: dashed underline; }
|
|
105
|
-
.xterm-overline { text-decoration: overline; }
|
|
106
|
-
.xterm-strikethrough { text-decoration: line-through; }
|
|
107
|
-
.xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
|
|
108
|
-
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
|
|
109
|
-
.xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
|
|
110
|
-
.xterm-decoration-top { z-index: 2; position: relative; }
|
|
111
|
-
`;function ag(){let e=document.getElementById("xterm-css");e||(e=document.createElement("style"),e.id="xterm-css",document.head.appendChild(e)),e.textContent=sg}const Mc=ku(function({entityName:t,entityType:r,entitySha:s,entityFilePath:a,scenarioName:o,scenarioDescription:i,analysisId:l,projectSlug:c,onRefreshPreview:p,onShowResults:u,onHideResults:m,onSetViewport:h,editorMode:f,onIdleChange:g,notificationSettings:y,buildTabActive:x,claudeStartMode:w,claudeSessionId:b,onDataMutationForwarded:v,resultsOpen:N},C){const E=ge(null),k=ge(null),_=ge(null),S=ge(null),j=ge(null),$=ge(!1),T=ge(0),R=ge(!1),I=ge(g);I.current=g;const P=ge(y);P.current=y;const H=ge(x);H.current=x;const W=ge(N);W.current=N;const F=ge(null),J=ge(!1),Y=ge(null);Y.current||(Y.current=new rg({playSound:G=>jc(G),showSystemNotification:()=>{F.current&&F.current.close();const G=new Notification("Claude is ready for you",{body:"Claude has finished and is waiting for your input.",tag:"claude-idle"});G.onclick=()=>{window.focus(),G.close()},F.current=G}},{hasBrowserFocus:()=>document.hasFocus(),hasNotificationPermission:()=>typeof Notification<"u"&&Notification.permission==="granted"}));function z(){F.current&&(F.current.close(),F.current=null)}function A(){var G,q;J.current&&(J.current=!1,z(),(G=I.current)==null||G.call(I,!1),(q=Y.current)==null||q.onUserEngagement())}re(()=>{function G(){var D;document.hasFocus()&&H.current&&A(),H.current&&document.hasFocus()&&((D=Y.current)==null||D.reportUserActivity())}function q(){!document.hidden&&H.current&&A()}function Q(){var D;document.hasFocus()&&H.current&&A(),H.current&&document.hasFocus()&&((D=Y.current)==null||D.reportUserActivity())}function U(){var D;H.current&&A(),H.current&&((D=Y.current)==null||D.reportUserActivity())}return window.addEventListener("focus",U),document.addEventListener("visibilitychange",q),document.addEventListener("mousemove",G),document.addEventListener("mousedown",Q),document.addEventListener("keydown",G),()=>{window.removeEventListener("focus",U),document.removeEventListener("visibilitychange",q),document.removeEventListener("mousemove",G),document.removeEventListener("mousedown",Q),document.removeEventListener("keydown",G)}},[]),re(()=>{var G;x&&J.current&&document.hasFocus()&&A(),(G=Y.current)==null||G.onBuildTabChange(!!x,P.current)},[x]);const B=oe(()=>{var G;(G=_.current)==null||G.focus()},[]);return Eu(C,()=>({sendInput(G){const q=S.current;q&&q.readyState===WebSocket.OPEN&&(q.send(JSON.stringify({type:"input",data:G})),setTimeout(()=>{q.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"input",data:"\r"}))},100))},focus(){var G;(G=_.current)==null||G.focus()},scrollToBottom(){var q;const G=(q=E.current)==null?void 0:q.querySelector(".xterm-viewport");G&&(G.scrollTop=G.scrollHeight)}})),re(()=>{const G=E.current;if(!G)return;let q=!1;return ag(),Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),import("@xterm/addon-web-links")]).then(([Q,U,D])=>{if(q)return;const O=new Q.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(he,Z){try{const Se=new URL(Z),fe=Se.searchParams.get("scenario");if(fe&&Se.pathname.startsWith("/editor")){const se=new BroadcastChannel("codeyam-editor");se.postMessage({type:"switch-scenario",scenarioId:fe}),se.close();return}}catch{}window.open(Z,"_blank")}}}),V=new U.FitAddon;O.loadAddon(V),O.loadAddon(new D.WebLinksAddon),O.open(G),O.attachCustomKeyEventHandler(he=>{if(W.current&&(he.key==="ArrowLeft"||he.key==="ArrowRight")&&!he.ctrlKey&&!he.altKey&&!he.metaKey&&he.type==="keydown"){const Z=he.key==="ArrowLeft"?"\x1B[D":"\x1B[C",Se=S.current;return Se&&Se.readyState===WebSocket.OPEN&&Se.send(JSON.stringify({type:"input",data:Z})),!1}return!0}),O.write("\x1B[?25l");let ne=null;ng(O,(he,Z,Se)=>{console.warn(`[Terminal] Renderer fallback: ${he} → ${Z}`,Se)}).then(he=>{if(q){he.dispose();return}console.log(`[Terminal] Using ${he.type} renderer`),ne=he.dispose}),requestAnimationFrame(()=>{try{V.fit()}catch{}}),_.current=O,O.focus(),setTimeout(()=>O.focus(),100),setTimeout(()=>O.focus(),500);const ie=window.location.protocol==="https:"?"wss:":"ws:",we=window.location.host;function le(he){const Z=new URLSearchParams;return Z.set("entityName",t),r&&Z.set("entityType",r),s&&Z.set("entitySha",s),a&&Z.set("entityFilePath",a),o&&Z.set("scenarioName",o),i&&Z.set("scenarioDescription",i),l&&Z.set("analysisId",l),c&&Z.set("projectSlug",c),f&&Z.set("editorMode","true"),he&&Z.set("reconnectId",he),w&&Z.set("claudeStartMode",w),b&&Z.set("claudeSessionId",b),`${ie}//${we}/ws/terminal?${Z.toString()}`}function ce(he){const Z=le(he),Se=new WebSocket(Z);S.current=Se,Se.onopen=()=>{T.current=0,R.current=!1,Se.send(JSON.stringify({type:"resize",cols:O.cols,rows:O.rows}))},Se.onmessage=fe=>{var se,pe,_e,Le,de,We,Je;try{const Ie=JSON.parse(fe.data);if(Ie.type==="session-id"){j.current=Ie.sessionId;return}if(Ie.type==="refresh-preview"){p==null||p(Ie.path,Ie.scenarioId);return}if(Ie.type==="show-results"){u==null||u();return}if(Ie.type==="hide-results"){m==null||m();return}if(Ie.type==="data-mutation-forwarded"){v==null||v();return}if(Ie.type==="set-viewport"){h==null||h({name:Ie.name,width:Ie.width,height:Ie.height});return}if(Ie.type==="claude-idle"){((se=Y.current)==null?void 0:se.onIdle(P.current,H.current??!1))!=="suppressed"&&(J.current=!0,(pe=I.current)==null||pe.call(I,!0));return}if(Ie.type==="claude-active"){J.current=!1,(_e=I.current)==null||_e.call(I,!1),(Le=Y.current)==null||Le.onActive(),(de=Y.current)==null||de.resetActivityFlag(),F.current&&(F.current.close(),F.current=null);return}Ie.type==="output"&&(O.write(Ie.data),(We=I.current)==null||We.call(I,!1),(Je=Y.current)==null||Je.resetActivityFlag())}catch{O.write(fe.data)}},Se.onclose=()=>{if($.current){O.write(`\r
|
|
112
|
-
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
113
|
-
`);return}const fe=T.current;if(fe<5&&j.current){const se=1e3*Math.pow(2,Math.min(fe,3));T.current=fe+1,O.write(`\r
|
|
114
|
-
\x1B[33m[Reconnecting...]\x1B[0m\r
|
|
115
|
-
`),setTimeout(()=>{$.current||ce(j.current)},se)}else R.current?O.write(`\r
|
|
116
|
-
\x1B[90m[Terminal session ended]\x1B[0m\r
|
|
117
|
-
`):(R.current=!0,O.write(`\r
|
|
118
|
-
\x1B[33m[Starting new session...]\x1B[0m\r
|
|
119
|
-
`),j.current=null,T.current=0,ce())},Se.onerror=()=>{}}ce(),O.onData(he=>{const Z=S.current;Z&&Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"input",data:he})),A()});let ve=null;const Ee=new ResizeObserver(()=>{ve&&clearTimeout(ve),ve=setTimeout(()=>{let he;try{he=V.proposeDimensions()}catch{return}if(!he||he.cols===O.cols&&he.rows===O.rows)return;const Z=G.querySelector(".xterm-viewport");let Se,fe=!0;Z&&(Se=Z.scrollTop,fe=Z.scrollTop+Z.clientHeight>=Z.scrollHeight-10),V.fit(),Z&&Se!==void 0&&(fe?Z.scrollTop=Z.scrollHeight:Z.scrollTop=Se);const se=S.current;se&&se.readyState===WebSocket.OPEN&&se.send(JSON.stringify({type:"resize",cols:O.cols,rows:O.rows}))},150)});Ee.observe(G),k.current=()=>{var he;ve&&clearTimeout(ve),Ee.disconnect(),$.current=!0,(he=S.current)==null||he.close(),S.current=null,ne==null||ne(),O.dispose(),_.current=null}}),()=>{var Q;q=!0,(Q=k.current)==null||Q.call(k),k.current=null}},[]),n("div",{ref:E,onClick:B,className:"w-full h-full relative overflow-hidden",style:{padding:"4px 0 0 8px"}})});function rt({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:a}){const[o,i]=M("loading"),[l,c]=M(!1),p=ge(null),u=t?`/api/screenshot/${e}?cb=${t}`:`/api/screenshot/${e}`,m=()=>{i("success"),c(!0)},h=()=>{i("error"),c(!1)};return re(()=>{i("loading"),c(!1);const f=p.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),c(!0)):(i("error"),c(!1)))},[u]),e?d("div",{className:"relative w-full h-full flex items-center justify-center",title:a,children:[n("img",{ref:p,src:u,alt:r,onLoad:m,onError:h,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"&&d("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 og({scenarios:e,currentScenarioId:t,entitySha:r,cacheBuster:s}){const a=Pt();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 c,p;const i=o.id===t,l=(p=(c=o.metadata)==null?void 0:c.screenshotPaths)==null?void 0:p[0];return d("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(rt,{screenshotPath:l,cacheBuster:s,alt:o.name,className:"w-full h-full object-cover object-top"})}),d("div",{className:"p-2.5 min-w-0 flex-1",children:[d("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 Ct(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(c=>!c.startsWith("(")),i.length===0?"/":"/"+i.join("/")}function Tt(e){return e==="/"?"Home":e.replace(/^\//,"").split("/").map(r=>r.startsWith("[")?r:r.charAt(0).toUpperCase()+r.slice(1)).join(" / ")}function $c(e,t){if(!e)return null;const r=e.split("?")[0].replace(/\/+$/,"")||"/",s=t.map(l=>({filePath:l,pattern:Ct(l)})),a=r==="/"?[]:r.replace(/^\//,"").split("/");let o=null,i=-1;for(const l of s){const c=l.pattern==="/"?[]:l.pattern.replace(/^\//,"").split("/");if(c.length!==a.length)continue;let p=!0,u=0;for(let m=0;m<c.length;m++){const h=c[m],f=a[m];if(!(h.startsWith("[")&&h.endsWith("]")))if(h===f)u++;else{p=!1;break}}p&&u>i&&(i=u,o=l.filePath)}return o}function Ic(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 ut(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 zs(e){return e?e.includes("/isolated-components")||e.includes("/codeyam-isolate"):!1}function nn(e){return e.componentName?e.componentName:e.pageFilePath?Tt(Ct(e.pageFilePath)):ut(e.url)}function Rc(e,t,r){var o;const s=[],a=new Set;for(const i of e){let l=null,c=null;if(i.componentName&&i.componentPath)l=i.componentName,c=i.componentPath;else if(!i.componentName&&i.pageFilePath)l=i.displayName||(i.pageFilePath.startsWith("app/")?Tt(Ct(i.pageFilePath)):ut(i.url)),c=i.pageFilePath;else if(!i.componentName&&i.url!==void 0){const p=ut(i.url);t[p]&&(l=p,c=t[p])}if(l&&c&&!a.has(l)){a.add(l);const p=r.find(u=>u.name===l)||(c?r.find(u=>u.filePath===c):void 0);s.push({name:l,filePath:c,importedBy:(o=p==null?void 0:p.metadata)==null?void 0:o.importedBy})}}return s}function ig(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 lg(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>t[r.name])}function cg(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>{if("componentName"in r){const a=nn(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 dg(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 c of Object.keys(o[l]))if(t.has(c))i.add(c);else{const p=r.get(l);p&&p!==a.name?i.add(p):i.add(c)}i.size>0&&s.set(a.name,i)}return s}function ug(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 pg=20;function Dc(e,t,r=pg){const s={};if(t.length===0||e.size===0)return s;const a=new Map;for(const p of t)a.set(p.name,p);const o=dg(t),i=ug(e,t);for(const[p,u]of i)s[p]={status:u};const l=new Map;for(const[p]of i)l.set(p,new Set([p]));const c=[];for(const[p]of i)c.push({name:p,depth:0});for(;c.length>0;){const{name:p,depth:u}=c.shift();if(u>=r)continue;const m=l.get(p)||new Set,h=o.get(p);if(h)for(const f of h){if(!a.has(f))continue;l.has(f)||l.set(f,new Set);const g=l.get(f);let y=!1;for(const x of m)g.has(x)||(g.add(x),y=!0);y&&c.push({name:f,depth:u+1})}}for(const[p,u]of l){if(i.has(p))continue;const m=[];for(const h of u){const f=a.get(h),g=i.get(h);f&&g&&m.push({name:h,filePath:f.filePath,changeType:g})}m.sort((h,f)=>h.name.localeCompare(f.name)),s[p]={status:"impacted",impactedBy:m.length>0?m:void 0}}return s}function _o(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 mg(e){return _o(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 Ri(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 hg(e,t){return e.filter(r=>r.analyses&&r.analyses.length>0).map(r=>{var m;const s=r.analyses[0],a=s.scenarios||[],o=!((m=s.status)!=null&&m.finishedAt),i=r.entityType||"visual",l=i==="library"||i==="functionCall",c=a.filter(h=>Ri(h,l)),p=a.filter(h=>!Ri(h,l)),u=t.find(h=>h.filePath===(r.filePath||""));return{sha:r.sha,name:r.name,entityType:i,filePath:r.filePath||"",analysisId:s.id,isAnalyzing:o,scenarioCount:a.length,scenarios:c.map(h=>{var f,g;return{id:h.id,name:h.name,description:h.description||"",screenshotPath:((g=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0])||null}}),pendingScenarios:p.map(h=>h.name),testFile:u==null?void 0:u.testFile}})}function fg(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 gg(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 vt(e,t){const r=new Map;for(const s of e)r.set(t(s),s);return[...r.values()]}function Qt(e){return e.replace(/[^a-zA-Z0-9_]+/g,"_")}function Oc(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ar(e){return e.replace("T"," ").replace(/\.\d{3}Z$/,"")}function ko(e,t){return!!(e.created_at&&e.created_at>=t||e.updated_at&&e.updated_at>=t)}const yg=["defaultScreenSize","screenSizes","projectTitle","projectDescription"];function U2(e){try{const t=JSON.parse(ue.readFileSync(e,"utf8")),r={};for(const s of yg)t[s]!==void 0&&(r[s]=t[s]);return r}catch{return{}}}function xg(e){const t=ee.join(e,".codeyam","editor-step.json");try{ue.unlinkSync(t)}catch{}}function Eo(e,t,r){const s=e&&e.startsWith("/");return s&&t?`${t}${e}`:e&&!s?e:t||r||null}function bg(e){var t,r;try{const s=ee.join(e,".codeyam","config.json"),a=JSON.parse(ue.readFileSync(s,"utf8"));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 Ao(e){try{const t=ee.join(e,".codeyam","config.json"),r=JSON.parse(ue.readFileSync(t,"utf8"));if(r.screenSizes&&typeof r.screenSizes=="object"&&!Array.isArray(r.screenSizes))return r.screenSizes}catch{}return{}}function wg(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 Bs(e){let t=null;if(e.dimension){const a=Ao(e.codeyamRoot)[e.dimension];a!=null&&a.width&&(a!=null&&a.height)&&(t={width:a.width,height:a.height})}const r=t||bg(e.codeyamRoot);return wg({bodyWidth:e.bodyWidth,bodyHeight:e.bodyHeight,projectDefault:r})}async function vg(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 c=a[0].id,p={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&&(p.dimensions=r,p.screenshot_paths=s),t.pageFilePath!==void 0&&(p.page_file_path=t.pageFilePath),t.entitySha!==void 0&&(p.entity_sha=t.entitySha),t.displayName!==void 0&&(p.display_name=t.displayName),await e.updateTable("editor_scenarios").set(p).where("id","=",c).execute();const u=a.slice(1).map(m=>m.id);return u.length>0&&await e.deleteFrom("editor_scenarios").where("id","in",u).execute(),{scenarioId:c,isNew:!1,cleanedUpIds:u}}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 Ng(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{ue.unlinkSync(ee.join(r,o))}catch{}try{const o=ue.readdirSync(s);for(const i of o)if(i.startsWith(`${a}--`)&&i.endsWith(".png"))try{ue.unlinkSync(ee.join(s,i))}catch{}}catch{}}}function Sg(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(ue.readFileSync(a,"utf8"));o=_o(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 Cg(e){const{componentName:t,url:r}=e;return!t||!r?{valid:!0}:zs(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 _g=Fc;async function Fc(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,c=l.component_path||l.page_file_path;if(!c)continue;const p=l.component_name&&r.get(`${l.component_name}::${c}`)||s.get(c);if(!p||l.entity_sha===p.sha)continue;let u=null;l.component_name?u=l.component_name:l.page_file_path&&l.page_file_path.startsWith("app/")?u=Tt(Ct(l.page_file_path)):l.url&&(u=ut(l.url)),await e.updateTable("editor_scenarios").set({entity_sha:p.sha,...u?{display_name:u}:{}}).where("id","=",l.id).execute(),o++}return{updated:o}}function kg(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 p=a.find(u=>u.id===s);if(p!=null&&p.url){const u=o||i;return u?p.url.startsWith("/")?`${u}${p.url}`:p.url:null}}const c=o||i;if(!c)return null;if(l&&s){const p=a.find(m=>m.id===s),u=p?Qt(p.name):"Default";return`${c}/__codeyam__/${l}/${u}`}return c}function Lc(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 Eg(e,t){return e?e!==t:!1}function Di(e){if(e.length!==0)return e.find(t=>t.type==="application")||e[0]}function Na(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 Ag(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 Pg({params:e}){var l;const{sha:t,scenarioId:r}=e;if(!t||!r)throw X("Invalid parameters",{status:400});const s=await xn(t);if(!s)throw X("Entity not found",{status:404});const a=await Ts(s),o=((l=a==null?void 0:a.scenarios)==null?void 0:l.find(c=>c.id===r))||null;if(!o)throw X("Scenario not found",{status:404});const i=await Fe();return X({entity:s,scenario:o,analysis:a,projectSlug:i})}const Sa=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],jg=Qe(function(){const{entity:t,scenario:r,analysis:s,projectSlug:a}=tt(),o=Pt(),i=ge(null),l=ge(null),[c,p]=M(null),[u,m]=M(1440),[h,f]=M({name:"Desktop",width:1440,height:900}),[g,y]=M(!1),[x,w]=M(null),[b,v]=M("chat"),[N,C]=M(0),[E,k]=M(null),_=oe(le=>{k(le||null),C(ce=>ce+1)},[]),{customSizes:S,addCustomSize:j}=Ls(a),$=ae(()=>[...Sa,...S],[S]),{interactiveServerUrl:T,isStarting:R,isLoading:I,showIframe:P,iframeKey:H,onIframeLoad:W}=vn({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:N}),F=ae(()=>Lc(T,E),[T,E]),{lastLine:J}=zt(a,R||I),Y=()=>{o(`/entity/${t.sha}`)},z=(le,ce)=>{m(le);const ve=$.find(he=>he.width===le&&he.height===ce);p(ve||null),f({name:(ve==null?void 0:ve.name)||"Custom",width:le,height:ce})},A=le=>{p(le),m(le.width),f({name:le.name,width:le.width,height:le.height})},B=le=>{j(le,h.width,h.height??900),y(!1),f(ce=>({...ce,name:le}))},G=()=>{var ce;v("chat"),(ce=l.current)==null||ce.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.")},q=((s==null?void 0:s.scenarios)||[]).filter(le=>{var ce;return!((ce=le.metadata)!=null&&ce.sameAsDefault)}),Q=q.findIndex(le=>le.id===(r==null?void 0:r.id)),U=Q+1,D=q.length,O=Q>0,V=Q<q.length-1,ne=()=>{if(O){const le=q[Q-1];o(`/entity/${t.sha}/scenarios/${le.id}/dev`)}},ie=()=>{if(V){const le=q[Q+1];o(`/entity/${t.sha}/scenarios/${le.id}/dev`)}},we=R||I||!P;return d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[d("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n("img",{src:Es,alt:"CodeYam",className:"h-6 brightness-0 invert"}),n("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:t.name}),d("div",{className:"flex items-center gap-2 shrink-0",children:[n("button",{onClick:ne,disabled:!O,className:`${O?"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"})})}),d("span",{className:"text-gray-400 text-sm",children:[U,"/",D]}),n("button",{onClick:ie,disabled:!V,className:`${V?"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"})})})]}),d("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)&&d("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:Y,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"})})})]}),d("div",{className:"flex-1 flex min-h-0",children:[d("div",{className:"flex-1 flex flex-col min-w-0",children:[d("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:`${Sa[Sa.length-1].width}px`,width:"100%"},children:n(So,{currentViewportWidth:u,currentPresetName:h.name,onDevicePresetClick:A,devicePresets:$,hideLabel:!0,onHoverChange:w,lightMode:!0})})}),d("div",{className:"relative z-10 flex items-center gap-2",children:[d("div",{className:"relative w-28 h-5",children:[d("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)||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"})})]}),d("select",{value:h.name,onChange:le=>{const ce=$.find(ve=>ve.name===le.target.value);ce&&A(ce)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[$.map(le=>n("option",{value:le.name,children:le.name},le.name)),h.name==="Custom"&&n("option",{value:"Custom",children:"Custom"})]})]}),n("input",{type:"number",value:h.width,onChange:le=>{const ce=parseInt(le.target.value,10);!isNaN(ce)&&ce>0&&z(ce,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:"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: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",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
|
|
120
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
121
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
122
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
123
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
124
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:T?d("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${h.width}px`,maxHeight:`${h.height}px`},children:[we&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("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(Ft,{})}),d("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"}),J&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(On,{}),J]})]})]})}),n("iframe",{ref:i,src:F||T,className:"w-full h-full border-none",title:`Dev mode preview: ${r==null?void 0:r.name}`,onLoad:W,style:{opacity:P?1:0}},H)]}):d("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(Ft,{})}),d("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"}),J&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(On,{}),J]})]})]})})]}),d("aside",{className:"w-[50%] min-w-[400px] max-w-[800px] bg-[#1e1e1e] border-l border-[#3d3d3d] shrink-0 flex flex-col overflow-hidden",children:[d("div",{className:"border-b border-[#3d3d3d] px-4 shrink-0 flex items-center justify-between",children:[d("div",{className:"flex items-center gap-0",children:[d("button",{onClick:()=>v("chat"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${b==="chat"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Chat",b==="chat"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]}),d("button",{onClick:()=>v("scenarios"),className:`px-3 py-2 text-xs font-medium transition-colors relative cursor-pointer ${b==="scenarios"?"text-white":"text-gray-500 hover:text-gray-300"}`,children:["Scenarios",b==="scenarios"&&n("span",{className:"absolute bottom-0 left-3 right-3 h-0.5 bg-[#005c75]"})]})]}),b==="chat"&&n("button",{onClick:G,disabled:!T,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:b==="chat"?"flex":"none"},className:"flex-1 overflow-hidden flex-col",children:n(Mc,{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:_})}),b==="scenarios"&&n(og,{scenarios:q,currentScenarioId:r==null?void 0:r.id,entitySha:t.sha,cacheBuster:0})]})]}),n(Tc,{serverUrl:T,isStarting:R,projectSlug:a}),g&&n(Co,{width:h.width,height:h.height??900,onSave:B,onCancel:()=>y(!1)})]})}),Tg=Object.freeze(Object.defineProperty({__proto__:null,default:jg,loader:Pg},Symbol.toStringTag,{value:"Module"}));async function Mg({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=L.join(i,".codeyam","journal","screenshots");await Ae.mkdir(l,{recursive:!0});const c=s.replace(/[^a-zA-Z0-9_\-T]/g,"_"),p=L.join(l,`${c}.png`),u=L.dirname(new URL(import.meta.url).pathname);let m=u;for(let b=0;b<5;b++){const v=L.dirname(m);if(L.basename(v)==="webserver"||L.basename(m)==="webserver"){m=L.basename(m)==="webserver"?m:v;break}m=v}const h=[L.join(m,"scripts","journalCapture.ts"),L.join(m,"app","lib","journalCapture.ts"),L.join(i,"codeyam-cli","src","webserver","app","lib","journalCapture.ts"),L.resolve(u,"..","lib","journalCapture.ts")];let f="";for(const b of h)try{await Ae.access(b),f=b;break}catch{}f||(console.warn(`[editor-journal-screenshot] journalCapture.ts not found in any of: ${h.join(", ")}`),f=h[0]);const g=Bs({bodyWidth:a,bodyHeight:o,codeyamRoot:i}),y=JSON.stringify({url:r,outputPath:p,viewportWidth:g.width,viewportHeight:g.height}),x=await new Promise(b=>{const v=St("npx",["tsx",f,y],{cwd:i,env:{...process.env}});let N="",C="";v.stdout.on("data",E=>{N+=E.toString()}),v.stderr.on("data",E=>{C+=E.toString()}),v.on("close",E=>{b(E===0?{success:!0,output:N}:{success:!1,output:N,error:C||`Process exited with code ${E}`})}),v.on("error",E=>{b({success:!1,output:"",error:E.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 w=`screenshots/${c}.png`;return new Response(JSON.stringify({success:!0,path:w}),{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 $g=Object.freeze(Object.defineProperty({__proto__:null,action:Mg},Symbol.toStringTag,{value:"Module"})),zc=to({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),Po=()=>{const e=Cs(zc);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Ys=({children:e})=>{const[t,r]=M({height:720,width:1200}),[s,a]=M(1),[o,i]=M(1200),l=ge(null),c=oe(({height:m,width:h})=>{r(f=>({height:m??f.height,width:h??f.width}))},[]),p=oe(m=>{a(m)},[]),u=oe(m=>{i(m)},[]);return n(zc.Provider,{value:{dimensions:t,updateDimensions:c,iframeRef:l,scale:s,updateScale:p,maxWidth:o,updateMaxWidth:u},children:e})},Ig=typeof window<"u";function Rg(){const[e,t]=M(null);return re(()=>{import("react-resizable").then(r=>{t(()=>r.ResizableBox)}),Promise.resolve({ })},[]),e}const Dg=1200,Og=720,Oi=30,Fg=({id:e,scenarioName:t,iframeUrl:r,defaultWidth:s=1440,defaultHeight:a=900,onDataOverride:o,onIframeLoad:i,onScaleChange:l,onDimensionChange:c})=>{const p=Rg(),[u,m]=M(!1),[h,f]=M(!1),[g,y]=M(Dg),[x,w]=M(Og),[b,v]=M(null),[N,C]=M(null),{dimensions:E,updateDimensions:k,iframeRef:_,updateScale:S,updateMaxWidth:j}=Po(),$=ae(()=>Math.min(1,g/E.width),[g,E.width]),T=N!==null?N:$;re(()=>{u||(S(T),l==null||l(T))},[T,S,l,u]),re(()=>{j(g)},[g,j]);const R=oe(()=>{m(!0),C($)},[$]),I=oe(()=>{m(!1),C(null)},[]),P=oe((Y,z)=>{const A=N!==null?N:1,B=Math.round(z.size.width/A);k({width:B}),c==null||c(B,E.height)},[k,N,c,E.height]),H=oe(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);re(()=>{const Y=z=>{if(z.data.type==="codeyam-resize"){if(t&&z.data.name!==t||E.height===z.data.height||z.data.height===0)return;k({height:z.data.height})}};return window.addEventListener("message",Y),()=>{window.removeEventListener("message",Y)}},[_,t,s,E,k]),re(()=>{h&&o&&o(_.current)},[h,o,_]),re(()=>{if(!t)return;const Y=setInterval(()=>{var z,A;(A=(z=_==null?void 0:_.current)==null?void 0:z.contentWindow)==null||A.postMessage({type:"codeyam-respond",name:t},"*")},1e3);return()=>clearInterval(Y)},[t,_]),re(()=>{const Y=()=>{const z=document.getElementById("scenario-container");if(!z)return;const A=z.getBoundingClientRect(),B=z.clientWidth-Oi*2,G=window.innerHeight-A.top-Oi*2,q=Math.max(G,400),Q=window.innerHeight-A.top;y(B),w(q),v(Q)};return Y(),window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[]),re(()=>{k({width:s,height:a})},[s,a,k]);const W=ae(()=>E.width*T,[E.width,T]),F=ae(()=>{const Y=E.height,z=Y*T;return Y&&Y!==720&&Y!==900&&z<x?z:x},[E.height,x,T]),J=oe(()=>{window.history.back()},[]);return!Ig||!p?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..."})}):d("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:b?{height:`${b}px`}:{},children:[u&&n("div",{className:"fixed inset-0 z-50 bg-transparent"}),n("style",{children:`
|
|
125
|
-
.react-resizable-handle-e {
|
|
126
|
-
display: flex !important;
|
|
127
|
-
align-items: center !important;
|
|
128
|
-
justify-content: center !important;
|
|
129
|
-
width: 6px !important;
|
|
130
|
-
height: 48px !important;
|
|
131
|
-
right: -8px !important;
|
|
132
|
-
top: 50% !important;
|
|
133
|
-
transform: translateY(-50%) !important;
|
|
134
|
-
cursor: ew-resize !important;
|
|
135
|
-
background: #d1d5db !important;
|
|
136
|
-
border-radius: 3px !important;
|
|
137
|
-
opacity: 0 !important;
|
|
138
|
-
transition: all 0.2s ease !important;
|
|
139
|
-
}
|
|
140
|
-
.react-resizable-handle-e:hover {
|
|
141
|
-
opacity: 0.8 !important;
|
|
142
|
-
background: #9ca3af !important;
|
|
143
|
-
}
|
|
144
|
-
.react-resizable:hover .react-resizable-handle-e {
|
|
145
|
-
opacity: 0.4 !important;
|
|
146
|
-
}
|
|
147
|
-
`}),n(p,{width:W,height:F,minConstraints:[300,200],maxConstraints:[g,x],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:R,onResizeStop:I,onResize:P,children:n("div",{className:"overflow-auto",style:{width:`${W}px`,height:`${F}px`},children:n("div",{style:{width:`${E.width}px`,height:`${E.height}px`,transform:`scale(${T})`,transformOrigin:"top left"},children:r?n("iframe",{ref:_,className:"w-full h-full rounded-lg",src:r,onLoad:H,sandbox:"allow-scripts allow-same-origin"}):d("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:J,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function Lg({presets:e,customSizes:t,currentWidth:r,currentHeight:s,scale:a,onSizeChange:o,onSaveCustomSize:i,onRemoveCustomSize:l,className:c=""}){const[p,u]=M(!1),[m,h]=M(String(r)),[f,g]=M(String(s)),[y,x]=M(!1),[w,b]=M(!1),v=ge(null);re(()=>{y||h(String(r))},[r,y]),re(()=>{w||g(String(s))},[s,w]),re(()=>{const T=R=>{v.current&&!v.current.contains(R.target)&&u(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[]);const N=ae(()=>{const T=e.find(I=>I.width===r&&I.height===s);if(T)return T.name;const R=t.find(I=>I.width===r&&I.height===s);return R?R.name:"Custom"},[e,t,r,s]),C=N==="Custom",E=T=>{o(T.width,T.height),u(!1)},k=T=>{const R=T.target.value;h(R);const I=parseInt(R,10);!isNaN(I)&&I>0&&o(I,s)},_=T=>{const R=T.target.value;g(R);const I=parseInt(R,10);!isNaN(I)&&I>0&&o(r,I)},S=()=>{x(!1);const T=parseInt(m,10);(isNaN(T)||T<=0)&&h(String(r))},j=()=>{b(!1);const T=parseInt(f,10);(isNaN(T)||T<=0)&&g(String(s))},$=T=>{(T.key==="Enter"||T.key==="Escape")&&T.target.blur()};return d("div",{className:`flex items-center gap-3 ${c}`,children:[d("div",{className:"relative",ref:v,children:[d("button",{onClick:()=>u(!p),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:N}),n("svg",{className:`w-4 h-4 transition-transform ${p?"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"})})]}),p&&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:d("div",{className:"py-1",children:[e.length>0&&d(xe,{children:[n("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(T=>d("button",{onClick:()=>E(T),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${N===T.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[n("span",{children:T.name}),d("span",{className:"text-xs text-gray-500",children:[T.width," x ",T.height]})]},T.name))]}),t.length>0&&d(xe,{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((T,R)=>T.width-R.width).map(T=>d("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${N===T.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[d("button",{onClick:()=>E(T),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:T.name}),d("span",{className:"text-xs text-gray-500",children:[T.width," x ",T.height]})]}),l&&n("button",{onClick:R=>{R.stopPropagation(),N===T.name&&e.length>0&&o(e[0].width,e[0].height),l(T.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"})})})]},T.name))]})]})})]}),d("div",{className:"flex items-center gap-1 text-sm",children:[d("div",{className:"flex items-center",children:[n("input",{type:"text",value:m,onChange:k,onFocus:()=>x(!0),onBlur:S,onKeyDown:$,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:"×"}),d("div",{className:"flex items-center",children:[n("input",{type:"text",value:f,onChange:_,onFocus:()=>b(!0),onBlur:j,onKeyDown:$,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&&d("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 Ca(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 Ba(e){return e&&(typeof e=="object"||Array.isArray(e))}function zg(e){return Array.isArray(e)?e.length:void 0}function Bg(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=Ba(t[a]),l=Ba(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 Yg({scenarioFormData:e,handleInputChange:t}){return d("div",{className:"p-3 flex flex-col gap-3",children:[d("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"})]}),d("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 Ug({path:e,namedPath:t,isArray:r,count:s,onClick:a}){const o=oe(()=>{a&&a(e)},[a,e]);return d("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:[d("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"})}),d("div",{className:"capitalize font-medium text-gray-900",children:[t[t.length-1],s!==void 0&&` (${s})`]})]}),d("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 Bc=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(Bc||{});const Wg=({name:e,value:t,options:r,onChange:s})=>{const a=oe(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))})},Jg=({name:e,value:t,onChange:r})=>{const s=oe(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
|
|
148
|
-
bg-gray-300 checked:bg-blue-600
|
|
149
|
-
after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
|
|
150
|
-
after:bg-white after:rounded-full after:transition-transform
|
|
151
|
-
checked:after:translate-x-4`})})};function Hg({dataType:e,path:t,value:r,onChange:s}){const a=ae(()=>t[t.length-1],[t]),o=ae(()=>t.join("-"),[t]),i=oe(c=>{s(t,c.target.value)},[s,t]),l=oe(c=>{s(t,c.target.value)},[s,t]);return d("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(Wg,{name:o,value:r,options:e.split("|"),onChange:i}):e===Bc.BOOLEAN?n(Jg,{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 Vg({analysis:e,scenarioName:t,dataItem:r,onResult:s,onGenerateData:a}){const[o,i]=M(!1),[l,c]=M(""),p=oe(async()=>{if(!a){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const m=e.scenarios.find(x=>x.name===t);if(!m)throw new Error("Scenario not found");const h=e.scenarios.find(x=>x.name===Ps),f=await a(l,r);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const g=(x,w)=>{const b=Object.assign({},x);return y(x)&&y(w)&&Object.keys(w).forEach(v=>{y(w[v])?v in x?b[v]=g(x[v],w[v]):Object.assign(b,{[v]:w[v]}):Object.assign(b,{[v]:w[v]})}),b},y=x=>x&&typeof x=="object"&&!Array.isArray(x);m.metadata.data=g(g((h==null?void 0:h.metadata.data)||{},m.metadata.data),f.data||{}),s(m),i(!1),c("")}catch(m){console.error("Error generating AI data:",m),i(!1)}},[e,l,r,t,s,a]),u=oe(m=>{c(m.target.value)},[]);return d("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:u,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 p(),children:o?d(xe,{children:[d("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 Gg({namedPath:e,path:t,last:r,onClick:s}){const a=oe(()=>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 Kg({dataItem:e,onClick:t}){const r=oe(()=>t([]),[t]),s=ae(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return d("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&&d("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)=>d("div",{className:"flex items-center gap-1",children:[n(Gg,{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 Fi({analysis:e,scenarioName:t,dataItem:r,onClick:s,onChange:a,onAIResult:o,onGenerateData:i,saveFeedback:l}){const c=ae(()=>r.data,[r]),p=ae(()=>Bg(r),[r]);return d("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[r.path.length>0&&n(Kg,{dataItem:r,onClick:s}),d("div",{className:"flex flex-col gap-3",children:[n(Vg,{analysis:e,scenarioName:t,dataItem:r,onResult:o,onGenerateData:i}),p==null?void 0:p.map((u,m)=>{var f;if(Ba(c[u])){let g=u;isNaN(Number(u))||(g=c[u].name??c[u].title??c[u].id??`${r.path[r.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const y=[...r.path,u],x=[...r.namedPath,g];return n(Ug,{path:y,namedPath:x,isArray:Array.isArray(c),count:zg(c[u]),onClick:s},`data-${u}-${m}`)}if(u==="id")return null;const h=[...r.path,u];return n(Hg,{dataType:((f=r.structure)==null?void 0:f[u])??"string",path:h,value:c[u],onChange:a},`InputField-${h.join("-")}`)})]}),n("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),d("div",{className:"flex gap-2",children:[n("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.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 u=document.getElementById("recapture-input");u&&(u.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 Li({title:e,children:t,defaultOpen:r=!1,borderT:s=!1,borderB:a=!1}){const[o,i]=M(r),l=[];return s&&l.push("border-t"),a&&l.push("border-b"),d("div",{className:`${l.join(" ")} border-gray-300`,children:[d("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 qg=({currentScenario:e,defaultScenario:t,dataStructure:r,analysis:s,shouldCreateNewScenario:a,onSave:o,onNavigate:i,iframeRef:l,onGenerateData:c,saveFeedback:p})=>{const u=oe((k,_)=>{const S=Object.assign({},k),j=$=>$&&typeof $=="object"&&!Array.isArray($);return j(k)&&j(_)&&Object.keys(_).forEach($=>{j(_[$])?$ in k?S[$]=u(k[$],_[$]):Object.assign(S,{[$]:_[$]}):Object.assign(S,{[$]:_[$]})}),S},[]),[m,h]=M({name:e.name,description:e.description,data:u(t.metadata.data,e.metadata.data)}),[f,g]=M(null),y=ae(()=>({...m.data}),[m]),x=ae(()=>({...y.mockData?{"Retrieved Data":y.mockData}:{},...y.argumentsData?{"Function Arguments":y.argumentsData}:{}}),[y]),w=ae(()=>{const k={...r.arguments?{"Function Arguments":r.arguments}:{},...r.dataForMocks?{"Retrieved Data":r.dataForMocks}:{}};return Object.keys(k).reduce((_,S)=>{if(S.includes(".")){const[j,$]=S.split(".");_[j]||(_[j]={}),_[j][$]=k[S]}else _[S]=k[S];return _},{})},[r]),b=oe(async k=>{k.preventDefault();const _=k.target.querySelector('input[name="recapture"]'),S=(_==null?void 0:_.value)==="true",j={mockData:m.data.mockData??{},argumentsData:m.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:m.name,shouldRecapture:S,dataToSave:j,rawFormData:m.data,iframePayload:{arguments:y.argumentsData??[],...y.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(j,null,2).substring(0,1e3));const $=s==null?void 0:s.scenarios.map(T=>!a&&T.name===e.name?{...T,name:m.name,description:m.description,metadata:{...T.metadata,data:j}}:T);a&&$.push({name:m.name,description:m.description,metadata:{data:j,interactiveExamplePath:s==null?void 0:s.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",$),o&&await o($,{recapture:S}),i&&i(m.name)},[s,e.name,m,y,a,o,i]),v=oe(k=>{h(_=>({..._,[k.target.name]:k.target.value}))},[]),N=oe(k=>{g(_=>{if(!_)return null;for(const S of[{arguments:k.metadata.data.argumentsData},k.metadata.data.mockData]){let j=S;for(const $ of _.path)if(j=Ca(j,$),!j)break;j&&(_.data=j)}return{..._}}),h({name:k.name,description:k.description,data:k.metadata.data})},[]),C=oe((k,_)=>{h(S=>{for(const j of[{"Function Arguments":S.data.argumentsData},{"Retrieved Data":S.data.mockData}]){let $=j;for(const T of k.slice(0,-1))if($=Ca($,T),!$)break;if($){const T=$[k[k.length-1]];g(R=>R?(R.namedPath[R.namedPath.length-1]===T&&(R.namedPath[R.namedPath.length-1]=_.toString()),R.data[k[k.length-1]]=_,{...R}):null),$[k[k.length-1]]=_}}return{...S}})},[]),E=oe(k=>{var $,T,R;if(k.length===0){g(null);return}let _=x;const S=[];let j=w;for(const I of k){if(S.push(isNaN(parseInt(I))?I:(($=_[I])==null?void 0:$.name)??((T=_[I])==null?void 0:T.title)??((R=_[I])==null?void 0:R.id)??I),_=Ca(_,I),!_){console.log("Data not found",_,I),g(null);return}Array.isArray(j)?j=j[0]:j=j[I]}g({path:k,namedPath:S,data:_,structure:j})},[x,w]);return re(()=>{const k=_=>{var S;_.data.type==="codeyam-log"&&((S=_.data.data)!=null&&S.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",_.data.data)};return window.addEventListener("message",k),()=>window.removeEventListener("message",k)},[]),re(()=>{var k;if((k=l==null?void 0:l.current)!=null&&k.contentWindow){const _={arguments:y.argumentsData??[],...y.mockData??{}},S={type:"codeyam-override-data",name:e.name,data:JSON.stringify(_)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:S.type,name:S.name,dataPreview:JSON.stringify(_).substring(0,200)+"...",fullData:_}),l.current.contentWindow.postMessage(S,"*")}},[y,e,l]),n("form",{method:"post",onSubmit:k=>void b(k),children:f?n(Fi,{analysis:s,scenarioName:m.name,dataItem:f,onClick:E,onChange:C,onAIResult:N,onGenerateData:c,saveFeedback:p}):d(xe,{children:[n(Li,{title:"Edit Name and Description",borderT:!0,children:n(Yg,{scenarioFormData:m,handleInputChange:v})}),e.metadata.data&&n(Li,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:n(Fi,{analysis:s,scenarioName:m.name,dataItem:{path:[],namedPath:[],data:x,structure:w},onClick:E,onChange:C,onAIResult:N,onGenerateData:c,saveFeedback:p})})]})})};function Us({scenarioId:e,scenarioName:t,iframeUrl:r,isStarting:s,isLoading:a,showIframe:o,iframeKey:i,onIframeLoad:l,onScaleChange:c,onDimensionChange:p,projectSlug:u,defaultWidth:m=1440,defaultHeight:h=900,retryCount:f=0}){const{lastLine:g}=zt(u??null,s||a);return r?d("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[n("div",{style:{opacity:o?1:0,background:"transparent"},children:n(Fg,{id:e,scenarioName:t,iframeUrl:r,defaultWidth:m,defaultHeight:h,onIframeLoad:l,onScaleChange:c,onDimensionChange:p},i)}),!o&&(s||a)&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("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(Ft,{})}),d("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"}),g&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(On,{}),g]})]})]})})]}):n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:d("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(Ft,{})}),d("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"}),g&&d("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[n(On,{}),g]})]})]})})}const Qg=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Zg({params:e}){var c,p;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 js(t,!0),a=s&&s.length>0?s[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=(c=a.scenarios)==null?void 0:c.find(u=>u.id===r);if(!o)throw new Response("Scenario not found",{status:404});const i=(p=a.scenarios)==null?void 0:p.find(u=>u.name===Ps),l=await Fe();return X({analysis:a,scenario:o,defaultScenario:i||o,entitySha:t,projectSlug:l})}function Xg(){var I,P,H;const e=tt(),t=e.analysis,r=e.scenario,s=e.defaultScenario,a=e.entitySha,o=e.projectSlug,i=Pt(),{iframeRef:l}=Po(),[c,p]=M(!1),[u,m]=M(null),[h,f]=M(null),[g,y]=M(!1),[x,w]=M(!1),[b,v]=M(null),{interactiveServerUrl:N,isStarting:C,isLoading:E,showIframe:k,iframeKey:_,onIframeLoad:S}=vn({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}),j=oe(async(W,F)=>{p(!0),m(null),f(null),console.log("[EditScenario] Starting save with options:",F),console.log("[EditScenario] Scenarios to save:",W);try{const J={analysis:t,scenarios:W};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:t.id,scenarioCount:W.length,scenarioNames:W.map(A=>A.name)});const Y=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J)}),z=await Y.json();if(console.log("[EditScenario] API response:",z),!Y.ok||!z.success)throw new Error(z.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),F!=null&&F.recapture&&r.id&&N){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:r.id,projectId:t.projectId,serverUrl:N}),m("Changes saved. Capturing screenshot...");const A={serverUrl:N,scenarioId:r.id,projectId:t.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",A);const B=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});console.log("[EditScenario] Capture response status:",B.status);const G=await B.json();if(console.log("[EditScenario] Capture response body:",G),!B.ok||!G.success)throw console.error("[EditScenario] Capture failed:",G),new Error(G.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",G),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),m("Recapture successful")}else if(F!=null&&F.recapture&&!N){console.log("[EditScenario] No running server, using queued recapture");const A=new FormData;A.append("analysisId",t.id||""),A.append("scenarioId",r.id||"");const B=await fetch("/api/recapture-scenario",{method:"POST",body:A}),G=await B.json();if(!B.ok||!G.success)throw new Error(G.error||"Failed to trigger recapture");console.log("Recapture queued:",G),f(G.jobId),m("Changes saved. Screenshot recapture queued.")}else m("Changes saved successfully.")}catch(J){console.error("Error saving scenarios:",J),m(`Error: ${J instanceof Error?J.message:String(J)}`)}finally{p(!1)}},[t,r.id,N]),$=oe(W=>{},[]),T=oe(async(W,F)=>{var z;const J=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:W,existingScenarios:t.scenarios,scenariosDataStructure:(z=t.metadata)==null?void 0:z.scenariosDataStructure,editingMockName:r.name,editingMockData:F==null?void 0:F.data})}),Y=await J.json();if(!J.ok||!Y.success)throw new Error(Y.error||"Failed to generate scenario data");return Y.data},[t,r.name]),R=oe(async()=>{var W;if(!r.id){v("Cannot delete scenario without ID");return}y(!0),v(null);try{const F=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:r.id,screenshotPaths:((W=r.metadata)==null?void 0:W.screenshotPaths)||[]})}),J=await F.json();if(!F.ok||!J.success)throw new Error(J.error||"Failed to delete scenario");i(`/entity/${a}`)}catch(F){console.error("[EditScenario] Error deleting scenario:",F),v(F instanceof Error?F.message:"Failed to delete scenario"),w(!1)}finally{y(!1)}},[r.id,(I=r.metadata)==null?void 0:I.screenshotPaths,a,i]);return d("div",{className:"h-screen bg-gray-50 flex flex-col",children:[d("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[n("div",{className:"mb-4",children:d(Ce,{to:`/entity/${a}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(P=t.entity)==null?void 0:P.name]})}),d("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})]}),d("div",{className:"flex flex-1 gap-0 min-h-0",children:[d("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[n(qg,{currentScenario:r,defaultScenario:s,dataStructure:((H=t.metadata)==null?void 0:H.scenariosDataStructure)||{},analysis:t,shouldCreateNewScenario:!1,onSave:j,onNavigate:$,iframeRef:l,onGenerateData:T,saveFeedback:{isSaving:c,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&n("div",{className:"px-4 pb-4",children:n(Ce,{to:`/entity/${a}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),d("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?d("div",{className:"space-y-3",children:[d("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',r.name,'"?']}),d("div",{className:"flex gap-2",children:[n("button",{onClick:()=>void R(),disabled:g,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:g?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>w(!1),disabled:g,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:()=>w(!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"}),b&&n("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:b})]})]}),n("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:n(Us,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:N,isStarting:C,isLoading:E,showIframe:k,iframeKey:_,onIframeLoad:S,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const e0=Qe(function(){return n(Ys,{children:n(Xg,{})})}),t0=Object.freeze(Object.defineProperty({__proto__:null,default:e0,loader:Zg,meta:Qg},Symbol.toStringTag,{value:"Module"}));function n0(e){return Bn.createHash("sha256").update(JSON.stringify(e)).digest("hex")}function r0(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 s0(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 a0(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 o0(){let e=[],t={},r=null,s=null,a=!1,o=null;function i(p){const u=[],m=p.routes;if(m&&typeof m=="object")for(const[h,f]of Object.entries(m)){const{method:g,pathPattern:y}=r0(h),{regex:x,paramNames:w}=s0(y),b=typeof f=="object"&&f!==null?f:{body:f};u.push({method:g,pathPattern:y,pathRegex:x,paramNames:w,response:{body:b.body,status:typeof b.status=="number"?b.status:200}})}return u}function l(p){const u=p.state;if(u&&typeof u=="object"){a=!0,t={};for(const[m,h]of Object.entries(u))t[m]=Array.isArray(h)?JSON.parse(JSON.stringify(h)):[];r=JSON.stringify(u)}else a=!1,t={},r=null}return{loadScenario(p){const u=n0(p);s&&u===s||(s=u,o=p,e=i(p),l(p))},matchRequest(p,u,m){if(!o&&e.length===0&&!a)return null;const h=Object.keys(t);if(a){const g=a0(u,h);if(g&&p==="GET"&&g===u)return{body:t[g],status:200};if(g){const y=c(p,u);if(p==="POST"&&g===u&&y){const x=t[g],w=typeof m=="object"&&m!==null?{...m}:{};if(!("id"in w)){const b=x.reduce((v,N)=>{const C=typeof N.id=="number"?N.id:0;return Math.max(v,C)},0);w.id=b+1}return x.push(w),{body:w,status:y.response.status}}if(p==="DELETE"&&y&&y.params){const x=y.params.id,w=t[g],b=w.findIndex(v=>String(v.id)===String(x));return b===-1?{body:{error:"Not found"},status:404}:(w.splice(b,1),{body:null,status:y.response.status})}if(p==="PUT"&&y&&y.params){const x=y.params.id,w=t[g],b=w.findIndex(N=>String(N.id)===String(x));if(b===-1)return{body:{error:"Not found"},status:404};const v=typeof m=="object"&&m!==null?{...m}:w[b];return w[b]=v,{body:v,status:y.response.status}}}}const f=c(p,u);if(f)return{body:f.response.body??null,status:f.response.status,params:f.params};if(o&&p==="GET"){const g=u.match(/^\/api\/(.+)$/);if(g){const y=g[1];if(y in o&&y!=="routes"&&y!=="state")return{body:o[y],status:200}}}return null},resetState(){if(r){const p=JSON.parse(r);t={};for(const[u,m]of Object.entries(p))t[u]=Array.isArray(m)?JSON.parse(JSON.stringify(m)):[]}},getState(){return{...t}}};function c(p,u){for(const m of e)if(m.method!==null&&m.method===p&&m.paramNames.length===0&&m.pathRegex.exec(u))return{response:m.response};if(p==="GET"){for(const m of e)if(m.method===null&&m.paramNames.length===0&&m.pathRegex.exec(u))return{response:m.response}}for(const m of e)if(m.paramNames.length>0){if((m.method??"GET")!==p)continue;const f=m.pathRegex.exec(u);if(f){const g={};for(let y=0;y<m.paramNames.length;y++)g[m.paramNames[y]]=f[y+1];return{response:m.response,params:g}}}return null}}function i0(e){var a,o;const t=ee.join(e,"package.json");if(!ue.existsSync(t))return{error:"No package.json found."};let r="npm",s=["run","dev"];try{const i=JSON.parse(ue.readFileSync(t,"utf8"));if(ue.existsSync(ee.join(e,"pnpm-lock.yaml"))?r="pnpm":ue.existsSync(ee.join(e,"yarn.lock"))?r="yarn":ue.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 l0(e,t){const r=t.toString(),s={PORT:r},a=ee.join(e,".codeyam","config.json");if(ue.existsSync(a))try{const c=(JSON.parse(ue.readFileSync(a,"utf8")).webapps||[])[0];if(c!=null&&c.startCommand){const{command:p,args:u,env:m}=c.startCommand,h=(u||[]).map(f=>f.includes("$PORT")?f.replace(/\$PORT/g,r):f);if(m)for(const[f,g]of Object.entries(m))typeof g=="string"&&g.includes("$PORT")?s[f]=g.replace(/\$PORT/g,r):typeof g=="string"&&(s[f]=g);return{command:p,args:h,env:s}}}catch{}const o=i0(e);return"error"in o?o:{command:o.command,args:o.args,env:s}}function Yc(e){return{proxyPort:e+1,devServerPort:e+2}}const c0=[/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 d0(e){for(const t of c0){const r=e.match(t);if(r){const s=r[1]||r[0];return u0(s).trim()}}return null}function u0(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function jo(){const e=globalThis.__codeyam_editor_dev_server__;return e&&e.status==="running"&&e.url?e.url:null}async function p0(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 m0(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 h0 extends _r{emitDataMutationForwarded(t,r){this.emit("event",{type:"data-mutation-forwarded",method:t,pathname:r,timestamp:Date.now()})}}const Ya="__codeyam_mock_state_event_emitter__";if(!globalThis[Ya]){const e=new h0;e.setMaxListeners(20),globalThis[Ya]=e}const f0=globalThis[Ya];function g0(e){try{return new URL(e).toString().replace(/\/$/,"")}catch{return e}}async function y0(e){const t=["127.0.0.1","::1"];for(const r of t)try{if(await new Promise(a=>{const o=new ql.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 Uc="__codeyam_editor_proxy__",Wc="__codeyam_preview_health__";function Jc(){return globalThis[Wc]??null}function Hc(e){globalThis[Wc]=e}function x0(){return Jc()}function Vc(){Hc(null)}const b0=`<script data-codeyam-health>
|
|
152
|
-
(function() {
|
|
153
|
-
var errors = [];
|
|
154
|
-
var reported = false;
|
|
155
|
-
function report(type, msg, stack) {
|
|
156
|
-
errors.push({ type: type, message: msg, stack: stack, timestamp: Date.now() });
|
|
157
|
-
if (!reported) {
|
|
158
|
-
reported = true;
|
|
159
|
-
setTimeout(function() { flush(); }, 500);
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
function flush() {
|
|
163
|
-
fetch('/__codeyam__/preview-health', {
|
|
164
|
-
method: 'POST',
|
|
165
|
-
headers: { 'Content-Type': 'application/json' },
|
|
166
|
-
body: JSON.stringify({ errors: errors, url: location.href })
|
|
167
|
-
}).catch(function(){});
|
|
168
|
-
reported = false;
|
|
169
|
-
errors = [];
|
|
170
|
-
}
|
|
171
|
-
window.addEventListener('error', function(e) {
|
|
172
|
-
report('error', e.message, e.error && e.error.stack);
|
|
173
|
-
});
|
|
174
|
-
window.addEventListener('unhandledrejection', function(e) {
|
|
175
|
-
report('unhandledrejection', String(e.reason), e.reason && e.reason.stack);
|
|
176
|
-
});
|
|
177
|
-
var origError = console.error;
|
|
178
|
-
console.error = function() {
|
|
179
|
-
report('console.error', Array.prototype.join.call(arguments, ' '));
|
|
180
|
-
origError.apply(console, arguments);
|
|
181
|
-
};
|
|
182
|
-
window.addEventListener('load', function() {
|
|
183
|
-
setTimeout(function() {
|
|
184
|
-
var hasContent = document.body && document.body.innerText.trim().length > 0;
|
|
185
|
-
fetch('/__codeyam__/preview-health', {
|
|
186
|
-
method: 'POST',
|
|
187
|
-
headers: { 'Content-Type': 'application/json' },
|
|
188
|
-
body: JSON.stringify({
|
|
189
|
-
loaded: true,
|
|
190
|
-
hasContent: hasContent,
|
|
191
|
-
url: location.href,
|
|
192
|
-
errorCount: errors.length
|
|
193
|
-
})
|
|
194
|
-
}).catch(function(){});
|
|
195
|
-
}, 1000);
|
|
196
|
-
});
|
|
197
|
-
})();
|
|
198
|
-
<\/script>`,w0=500;let Ot={data:null,timestamp:0},un,hr,Ws=null,Js=null,Hs=null,Ua=null;const zi=10*1024*1024;function Vs(){return globalThis[Uc]??null}function Gc(e){globalThis[Uc]=e}function Kc(){const e="__codeyam_mock_state__";return globalThis[e]||(globalThis[e]=o0()),globalThis[e]}function qc(){const e=Vs();return e?`http://localhost:${e.port}`:null}function v0(){const e=Date.now();if(Ot.data!==null&&e-Ot.timestamp<w0)return Ot.data;const t=Ne()||process.env.CODEYAM_ROOT_PATH||process.cwd(),r=ee.join(t,".codeyam","active-scenario.json");try{if(!ue.existsSync(r))return Ot={data:null,timestamp:e},null;const s=JSON.parse(ue.readFileSync(r,"utf-8")),a=s.scenarioId;if(!a)return Hs=s.prototypeId||null,Ot={data:null,timestamp:e},null;const o=ee.join(t,".codeyam","editor-scenarios",`${a}.json`);if(!ue.existsSync(o))return console.log(`[editorProxy] Scenario data file not found: ${o}`),Ot={data:null,timestamp:e},null;const i=JSON.parse(ue.readFileSync(o,"utf-8"));un=i.session||null,hr=i.sessionCookies||void 0,Ws=i.localStorage||null,Js=a;const l=s.type||i.type||null;Ua=l;let c;return(l==="application"||l==="user")&&i.seed?i.externalApis&&typeof i.externalApis=="object"?c={routes:i.externalApis}:c={}:c=i,Ot={data:c,timestamp:e},Kc().loadScenario(c),c}catch(s){return console.warn("[editorProxy] Error reading scenario data:",s),Ot={data:null,timestamp:e},null}}function N0(e){return new Promise(t=>{const r=[];let s=0;e.on("data",a=>{s+=a.length,s>zi?(t(null),e.resume()):r.push(a)}),e.on("end",()=>{s>zi||t(Buffer.concat(r))}),e.on("error",()=>{t(null)})})}function To(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Bi(e,t,r,s){const a=new URL(r),o=To(a.hostname),i={...e.headers,host:`${a.hostname}:${a.port}`};delete i["accept-encoding"],s&&(i["content-length"]=String(s.length));const l={hostname:o,port:a.port,path:e.url,method:e.method,headers:i},c=lo.request(l,p=>{const u=p.statusCode||200;u>=400&&console.warn(`[editorProxy] Target returned ${u} for ${e.method} ${e.url}`);const m={...p.headers};if(Qc(m),(p.headers["content-type"]||"").includes("text/html")){Vc();const f=[];p.on("data",g=>f.push(g)),p.on("end",()=>{const g=Buffer.concat(f).toString("utf-8"),y=Zc(Ws,Js||"",Hs),x=Xc(g,y);delete m["content-length"],delete m["content-encoding"],m["cache-control"]="no-store, must-revalidate",t.writeHead(u,m),t.end(x)});return}t.writeHead(u,m),p.pipe(t,{end:!0})});c.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"))}),s&&s.length>0?c.end(s):c.end()}function S0(e,t,r){const s=new URL(r),a=To(s.hostname),{"accept-encoding":o,...i}=e.headers,l={hostname:a,port:s.port,path:e.url,method:e.method,headers:{...i,host:`${s.hostname}:${s.port}`}},c=lo.request(l,p=>{const u=p.statusCode||200;u>=400&&console.warn(`[editorProxy] Target returned ${u} for ${e.method} ${e.url}`);const m={...p.headers};if(Qc(m),(p.headers["content-type"]||"").includes("text/html")){Vc();const f=[];p.on("data",g=>f.push(g)),p.on("end",()=>{const g=Buffer.concat(f).toString("utf-8"),y=Zc(Ws,Js||"",Hs),x=Xc(g,y);delete m["content-length"],delete m["content-encoding"],m["cache-control"]="no-store, must-revalidate",t.writeHead(u,m),t.end(x)});return}t.writeHead(u,m),p.pipe(t,{end:!0})});c.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(c,{end:!0})}function Qc(e){const t=[];if(un!==void 0&&(un!=null&&un.cookieValue?t.push(`session-token=${un.cookieValue}; Path=/; SameSite=Lax`):t.push("session-token=; Path=/; Max-Age=0")),hr&&hr.length>0)for(const s of hr){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 C0(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 Zc(e,t,r){if(!e||typeof e!="object")return r?`<script data-codeyam-ls>
|
|
199
|
-
(function() {
|
|
200
|
-
if (localStorage.getItem('__codeyam_proto__') === ${JSON.stringify(r)}) return;
|
|
201
|
-
localStorage.clear();
|
|
202
|
-
localStorage.setItem('__codeyam_proto__', ${JSON.stringify(r)});
|
|
203
|
-
})();
|
|
204
|
-
<\/script>`:"";const s=Object.entries(e),a=s.map(([c])=>c),o=s.map(([c,p])=>{const u=typeof p=="string"?p:JSON.stringify(p);return`localStorage.setItem(${JSON.stringify(c)}, ${JSON.stringify(u)});`}).join(`
|
|
205
|
-
`),i=C0(JSON.stringify(e)),l=`${t}:${i}`;return`<script data-codeyam-ls>
|
|
206
|
-
(function() {
|
|
207
|
-
if (localStorage.getItem('__codeyam_ls_sid__') === ${JSON.stringify(l)}) return;
|
|
208
|
-
var prev = JSON.parse(localStorage.getItem('__codeyam_ls_keys__') || '[]');
|
|
209
|
-
for (var i = 0; i < prev.length; i++) localStorage.removeItem(prev[i]);
|
|
210
|
-
${o}
|
|
211
|
-
localStorage.setItem('__codeyam_ls_keys__', ${JSON.stringify(JSON.stringify(a))});
|
|
212
|
-
localStorage.setItem('__codeyam_ls_sid__', ${JSON.stringify(l)});
|
|
213
|
-
})();
|
|
214
|
-
<\/script>`+_0()}function _0(){return`<script data-codeyam-ls-watcher>
|
|
215
|
-
(function() {
|
|
216
|
-
if (window.__codeyam_ls_watcher_installed__) return;
|
|
217
|
-
window.__codeyam_ls_watcher_installed__ = true;
|
|
218
|
-
|
|
219
|
-
var origSet = localStorage.setItem.bind(localStorage);
|
|
220
|
-
var origRemove = localStorage.removeItem.bind(localStorage);
|
|
221
|
-
var origClear = localStorage.clear.bind(localStorage);
|
|
222
|
-
window.__codeyam_orig_setItem__ = origSet;
|
|
223
|
-
window.__codeyam_orig_removeItem__ = origRemove;
|
|
224
|
-
window.__codeyam_orig_clear__ = origClear;
|
|
225
|
-
|
|
226
|
-
function isInternal(key) {
|
|
227
|
-
return typeof key === 'string' && key.indexOf('__codeyam_') === 0;
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
localStorage.setItem = function(key, value) {
|
|
231
|
-
origSet(key, value);
|
|
232
|
-
if (!isInternal(key) && window.parent !== window) {
|
|
233
|
-
window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'set', key: key }, '*');
|
|
234
|
-
}
|
|
235
|
-
};
|
|
236
|
-
|
|
237
|
-
localStorage.removeItem = function(key) {
|
|
238
|
-
origRemove(key);
|
|
239
|
-
if (!isInternal(key) && window.parent !== window) {
|
|
240
|
-
window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'remove', key: key }, '*');
|
|
241
|
-
}
|
|
242
|
-
};
|
|
243
|
-
|
|
244
|
-
localStorage.clear = function() {
|
|
245
|
-
origClear();
|
|
246
|
-
if (window.parent !== window) {
|
|
247
|
-
window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'clear' }, '*');
|
|
248
|
-
}
|
|
249
|
-
};
|
|
250
|
-
|
|
251
|
-
window.addEventListener('message', function(event) {
|
|
252
|
-
if (event.data && event.data.type === 'codeyam-get-localstorage') {
|
|
253
|
-
var data = {};
|
|
254
|
-
for (var i = 0; i < localStorage.length; i++) {
|
|
255
|
-
var k = localStorage.key(i);
|
|
256
|
-
if (k && !isInternal(k)) {
|
|
257
|
-
data[k] = localStorage.getItem(k);
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
event.source.postMessage({ type: 'codeyam-localstorage-state', data: data }, '*');
|
|
261
|
-
}
|
|
262
|
-
});
|
|
263
|
-
})();
|
|
264
|
-
<\/script>`}function Xc(e,t){const r=(t||"")+b0;return e.includes("</head>")?e.replace("</head>",r+"</head>"):e.includes("</body>")?e.replace("</body>",r+"</body>"):e+r}function k0(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=Jc()||{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(),Hc(a)}catch{}t.writeHead(204),t.end()})}function E0(e,t,r,s){const a=new URL(s),o=To(a.hostname),i=parseInt(a.port,10)||80;console.log(`[editorProxy] WebSocket upgrade: ${e.url} → ${o}:${i}`);const l=ql.connect(i,o,()=>{const c=`${e.method} ${e.url} HTTP/${e.httpVersion}\r
|
|
265
|
-
`,p=Object.entries(e.headers).filter(([,u])=>u!=null).map(([u,m])=>`${u}: ${Array.isArray(m)?m.join(", "):m}`).join(`\r
|
|
266
|
-
`);l.write(c+p+`\r
|
|
267
|
-
\r
|
|
268
|
-
`),r.length>0&&l.write(r),l.pipe(t,{end:!0}),t.pipe(l,{end:!0})});l.on("error",c=>{console.warn(`[editorProxy] WebSocket proxy error: ${c.message}`),t.destroy()}),t.on("error",()=>{l.destroy()})}function A0(e,t){const r=Ne()||process.env.CODEYAM_ROOT_PATH||process.cwd(),s=ee.join(r,".codeyam","proxy-config.json");try{ue.mkdirSync(ee.dirname(s),{recursive:!0}),ue.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 P0(){const e=Ne()||process.env.CODEYAM_ROOT_PATH||process.cwd(),t=ee.join(e,".codeyam","proxy-config.json");try{ue.existsSync(t)&&ue.unlinkSync(t)}catch{}}async function Wa(e){const t=Vs();if(t)return console.log(`[editorProxy] Proxy already running on port ${t.port} → ${t.targetUrl}`),{port:t.port};await ed();let r=g0(e.targetUrl),s=e.port;try{const l=new URL(r);if(l.hostname==="localhost"){const c=parseInt(l.port||"80",10),p=await y0(c);p&&(l.hostname=p,r=l.toString().replace(/\/$/,""),console.log(`[editorProxy] Resolved localhost to ${p} for port ${c}`))}}catch{}console.log(`[editorProxy] Starting proxy (requested port ${s}, target ${r})`);const a=Kc(),o=lo.createServer((l,c)=>{(async()=>{const u=new URL(l.url||"/",`http://localhost:${s}`).pathname,m=l.method||"GET";if(m==="OPTIONS"){c.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"}),c.end();return}if(m==="POST"&&u==="/__codeyam__/preview-health"){k0(l,c);return}if(v0(),m==="POST"||m==="PUT"||m==="DELETE"||m==="PATCH"){const g=await N0(l);if(g===null){Bi(l,c,r,null);return}let y;if(g.length>0)try{y=JSON.parse(g.toString("utf-8"))}catch{}const x=a.matchRequest(m,u,y);if(x){console.log(`[editorProxy] Intercepted ${m} ${u} → mock response (status ${x.status})`),c.writeHead(x.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data","Cache-Control":"no-store"}),c.end(x.body!=null?JSON.stringify(x.body):"");return}(Ua==="application"||Ua==="user")&&u.startsWith("/api/")&&f0.emitDataMutationForwarded(m,u),Bi(l,c,r,g);return}const f=a.matchRequest(m,u);if(f){console.log(`[editorProxy] Intercepted ${m} ${u} → mock response (status ${f.status})`),c.writeHead(f.status,{"Content-Type":"application/json","Access-Control-Allow-Origin":"*","X-CodeYam-Proxy":"scenario-data","Cache-Control":"no-store"}),c.end(f.body!=null?JSON.stringify(f.body):"");return}S0(l,c,r)})()});o.on("upgrade",(l,c,p)=>{E0(l,c,p,r)});const i=10;for(let l=0;l<i;l++){const c=s+l;try{await new Promise((m,h)=>{o.once("error",h),o.listen(c,"0.0.0.0",()=>{o.removeListener("error",h),m()})});const p=o.address();return s=typeof p=="object"&&p!==null?p.port:c,Gc({server:o,port:s,targetUrl:r}),A0(s,r),console.log(`[editorProxy] Proxy started on port ${s}, forwarding to ${r}`),{port:s}}catch(p){if((p==null?void 0:p.code)==="EADDRINUSE"&&l<i-1){console.log(`[editorProxy] Port ${c} in use, trying ${c+1}`);continue}return console.error("[editorProxy] Failed to start proxy:",p),null}}return null}async function ed(){const e=Vs();if(e)return console.log(`[editorProxy] Stopping proxy on port ${e.port}`),P0(),new Promise(t=>{e.server.close(()=>{console.log("[editorProxy] Proxy stopped"),t()}),Gc(null),setTimeout(t,2e3)})}function Fn(){Ot={data:null,timestamp:0},un=void 0,hr=void 0,Ws=null,Js=null,Hs=null}async function Yi(){const e=Vs();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 Mo(){const e=qc();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}=Yc(r);console.log(`[editorProxy] Proxy not running, starting on-demand (port ${s}, target ${t.url})`);const a=await Wa({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}const j0=["/api/health","/__codeyam__/preview-health"];function td(e){const t=[];for(const r of e.split(`
|
|
269
|
-
`))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(j0.some(s=>r.includes(s)))continue;t.push(r.replace(/.*\[JournalCapture\] /,""))}return t}function T0(e){for(const t of e.split(`
|
|
270
|
-
`))if(t.includes("[JournalCapture] Visible text: "))return t.replace(/.*\[JournalCapture\] Visible text: /,"");return null}async function nd(e,t,r,s){const a=L.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(L.dirname(a),{recursive:!0}),await Ae.writeFile(a,JSON.stringify(o,null,2),"utf8")}async function rd(e){const t=L.join(e,".codeyam","editor-scenarios","client-errors.json");try{const r=await Ae.readFile(t,"utf8");return JSON.parse(r)}catch{return{}}}function $o(e){let r=L.dirname(new URL(e).pathname);for(let s=0;s<5;s++){const a=L.dirname(r);if(L.basename(a)==="webserver"||L.basename(r)==="webserver")return L.basename(r)==="webserver"?r:a;r=a}return r}async function Io(e,t){const r=[L.join(e,"scripts","journalCapture.ts"),L.join(e,"app","lib","journalCapture.ts"),L.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 Ro(e,t,r){return new Promise(s=>{const a=e.endsWith(".ts"),l=St(a?"npx":e,a?["tsx",e,t]:[t],{cwd:r,env:{...process.env}});let c="",p="";l.stdout.on("data",u=>{c+=u.toString()}),l.stderr.on("data",u=>{p+=u.toString()}),l.on("close",u=>{s(u===0?{success:!0,output:c}:{success:!1,output:c,error:p||`Process exited with code ${u}`})}),l.on("error",u=>{s({success:!1,output:"",error:u.message})})})}const sd=3e4,M0="seed-session.json";function $0(e){const t={};try{const r=K.readFileSync(e,"utf-8");for(const s of r.split(`
|
|
271
|
-
`)){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 ad(e){const t=[".env",".env.local",".env.development",".env.development.local"];let r={};for(const s of t){const a=$0(L.join(e,s));r={...r,...a}}return r}function od(e){const t={};try{const r=L.join(e,".codeyam","config.json"),s=JSON.parse(K.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 I0(e){const t=L.join(e,".codeyam","tmp",M0);try{if(!K.existsSync(t))return;const r=K.readFileSync(t,"utf-8"),s=JSON.parse(r);return K.unlinkSync(t),s.cookies&&Array.isArray(s.cookies)?s.cookies:void 0}catch{return}}function Do(e,t,r){const s=sd,a=L.basename(L.dirname(e))===".codeyam"?L.dirname(L.dirname(e)):L.dirname(e);return new Promise(o=>{const i=Date.now(),l=e.endsWith(".ts"),c=l?"npx":e,p=l?["tsx",e,t]:[t],u=ad(a),m=od(a),h=St(c,p,{cwd:a,env:{...u,...m,...process.env}});let f="",g="",y=!1;const x=setTimeout(()=>{y=!0,h.kill("SIGTERM")},s);h.stdout.on("data",w=>{f+=w.toString()}),h.stderr.on("data",w=>{g+=w.toString()}),h.on("close",w=>{clearTimeout(x);const b=Date.now()-i;if(y)o({success:!1,output:f,error:`Seed adapter timeout after ${s}ms`,durationMs:b});else if(w===0){const v=I0(a);o({success:!0,output:f,durationMs:b,sessionCookies:v})}else o({success:!1,output:f,error:g||`Seed adapter exited with code ${w}`,durationMs:b})}),h.on("error",w=>{clearTimeout(x),o({success:!1,output:"",error:w.message,durationMs:Date.now()-i})})})}function R0(e,t,r){const s=sd,a=L.basename(L.dirname(e))===".codeyam"?L.dirname(L.dirname(e)):L.dirname(e);return new Promise(o=>{const i=Date.now(),l=e.endsWith(".ts"),c=l?"npx":e,p=l?["tsx",e,"--export",t]:["--export",t],u=ad(a),m=od(a),h=St(c,p,{cwd:a,env:{...u,...m,...process.env}});let f="",g="",y=!1;const x=setTimeout(()=>{y=!0,h.kill("SIGTERM")},s);h.stdout.on("data",w=>{f+=w.toString()}),h.stderr.on("data",w=>{g+=w.toString()}),h.on("close",w=>{clearTimeout(x);const b=Date.now()-i;o(y?{success:!1,output:f,error:`Seed adapter export timeout after ${s}ms`,durationMs:b}:w===0?{success:!0,output:f,durationMs:b}:{success:!1,output:f,error:g||`Seed adapter export exited with code ${w}`,durationMs:b})}),h.on("error",w=>{clearTimeout(x),o({success:!1,output:"",error:w.message,durationMs:Date.now()-i})})})}function wr(e){const t=["seed-adapter.ts","seed-adapter.js"];for(const r of t){const s=L.join(e,".codeyam",r);try{return K.accessSync(s),s}catch{}}return null}function D0(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}function O0(e){const t=L.join(e,".codeyam","editor-scenarios");let r;try{r=K.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=L.join(t,a);try{if(!K.statSync(o).isFile())continue;const l=JSON.parse(K.readFileSync(o,"utf8"));if(l._metadata){const c=a.replace(/\.json$/,"");s.push({id:c,metadata:l._metadata})}}catch{}}return s}function id(e,t,r){const s=L.join(e,".codeyam","editor-scenarios",`${t}.json`);let a={};try{a=JSON.parse(K.readFileSync(s,"utf8"))}catch{return}a._metadata=r,K.writeFileSync(s,JSON.stringify(a,null,2),"utf8")}function F0(e,t,r){const s=L.join(e,".codeyam","editor-scenarios",`${t}.json`);let a={};try{a=JSON.parse(K.readFileSync(s,"utf8"))}catch{return}a._metadata&&typeof a._metadata=="object"&&(a._metadata.screenshotPath=r,a._metadata.updatedAt=new Date().toISOString(),K.writeFileSync(s,JSON.stringify(a,null,2),"utf8"))}function L0(e,t,r,s={}){const a=L.join(e,".codeyam","editor-scenarios");K.mkdirSync(a,{recursive:!0});const o=L.join(a,`${t}.json`);let i={};try{i=JSON.parse(K.readFileSync(o,"utf8"))}catch{}const l={...i,_metadata:r,...s};K.writeFileSync(o,JSON.stringify(l,null,2),"utf8")}function z0(e,t){const r=L.join(e,".codeyam","editor-scenarios");for(const s of[".json",".seed.json"]){const a=L.join(r,`${t}${s}`);try{K.unlinkSync(a)}catch{}}}const Oo=globalThis.__codeyamTerminalSessions??(globalThis.__codeyamTerminalSessions=new Set);globalThis.__codeyamDetachedPtys??(globalThis.__codeyamDetachedPtys=new Map);function Fo(e,t){const r=JSON.stringify({type:"refresh-preview",...e&&{path:e},...t&&{scenarioId:t}});let s=0;for(const a of Oo)try{a.ws.readyState===co.OPEN&&(a.ws.send(r),s++)}catch{}return s}function B0(){const e=JSON.stringify({type:"hide-results"});let t=0;for(const r of Oo)try{r.ws.readyState===co.OPEN&&(r.ws.send(e),t++)}catch{}return t}function Lo(e){const t=JSON.stringify({type:"set-viewport",...e});let r=0;for(const s of Oo)try{s.ws.readyState===co.OPEN&&(s.ws.send(t),r++)}catch{}return r}const Y0=Object.freeze(Object.defineProperty({__proto__:null,broadcastHideResults:B0,broadcastPreviewRefresh:Fo,broadcastSetViewport:Lo},Symbol.toStringTag,{value:"Module"}));function U0(e){if(e.dimension)try{Lo({name:e.dimension,width:e.viewport.width,height:e.viewport.height})}catch{}Fo(e.refreshPath,e.scenarioId)}let an=null;async function zo(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`);ue.existsSync(m)?o=JSON.parse(ue.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`);ue.existsSync(m)&&(i=JSON.parse(ue.readFileSync(m,"utf-8")).type||null)}catch{}const l=ee.join(s,"active-scenario.json");ue.mkdirSync(s,{recursive:!0}),ue.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 c=null,p;const u=i==="application"||i==="user";if(u)if(an&&an.scenarioId===t)c=await an.promise;else{const m=wr(r),h=ee.join(a,`${t}.seed.json`);if(m&&ue.existsSync(h)){const f=Do(m,h).then(g=>({success:g.success,error:g.error,sessionCookies:g.sessionCookies}));an={scenarioId:t,promise:f};try{const g=await f;c={success:g.success,error:g.error},p=g.sessionCookies}finally{an&&an.scenarioId===t&&(an=null)}if(c!=null&&c.success&&p&&p.length>0)try{const g=ee.join(a,`${t}.json`),y=JSON.parse(ue.readFileSync(g,"utf-8"));y.sessionCookies=p,ue.writeFileSync(g,JSON.stringify(y,null,2))}catch{}}else m||(c={success:!1,error:"No seed adapter found"})}return{success:!0,scenarioSlug:o,scenarioId:t,type:i,seeded:u,...c?{seedResult:c}:{},...p&&p.length>0?{sessionCookies:p}:{}}}function W0(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const r=$e("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return J0(r)}catch{return[]}}function J0(e){const t=e.trim().split(`
|
|
272
|
-
`).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,c=!1,p;if(a==="A"||o==="A")l="added",c=a==="A";else if(a==="M"||o==="M")l="modified",c=a==="M";else if(a==="D"||o==="D")l="deleted",c=a==="D";else if(a==="R"||o==="R"){l="renamed",c=a==="R";const u=i.indexOf(" -> ");u!==-1&&(p=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else o==="?"?(l="untracked",c=!1):(l="modified",c=a!==" "&&a!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=ee.join(u,i);try{const h=(g,y)=>{const x=ue.readdirSync(g,{withFileTypes:!0}),w=[];for(const b of x){const v=ee.join(g,b.name),N=ee.relative(u,v);b.isDirectory()?w.push(...h(v,y)):b.isFile()&&w.push(N)}return w},f=h(m,u);for(const g of f)r.push({path:g,status:l,staged:c,...p&&{oldPath:p}})}catch(h){console.error(`Failed to expand directory ${i}:`,h)}}else r.push({path:i,status:l,staged:c,...p&&{oldPath:p}})}return r}function H0(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return $e("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 V0(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const s=$e('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 $e("git show-ref --verify --quiet refs/heads/main",{cwd:t,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return $e("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 G0(e){const t=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return $e('git branch --format="%(refname:short)"',{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
273
|
-
`).filter(s=>s.length>0)}catch(r){return console.error("Failed to get branches:",r),[]}}function Vn(){const e=Ne();return e?W0(e):[]}function K0(){const e=Ne();return e?H0(e):null}function q0(){const e=Ne();return e?V0(e):"main"}function Q0(){const e=Ne();return e?G0(e):[]}function ld(e,t){const r=Ne();return r?Z0(e,t,r):[]}function Z0(e,t,r){const s=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return $e(`git diff --name-status ${e}...${t}`,{cwd:s,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
274
|
-
`).filter(i=>i.length>0).map(i=>{const l=i.split(" "),c=l[0];let p=l[1],u,m;return c==="A"?m="added":c==="M"?m="modified":c==="D"?m="deleted":c.startsWith("R")?(m="renamed",u=l[1],p=l[2]):m="modified",{path:p,status:m,...u&&{oldPath:u}}})}catch(a){return console.error("Failed to get branch diff:",a),[]}}function cd(e,t){const r=t||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=$e(`git show HEAD:"${e}"`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let a="";try{a=ue.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 X0(e){const t=Ne();return t?cd(e,t):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function ey(e,t,r,s){const a=s||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let o="";try{o=$e(`git show ${t}:"${e}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{o=""}let i="";try{i=$e(`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 rs(e,t,r){const s=Ne();return s?ey(e,t,r,s):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}async function ty(e,t,r){const s=L.join(e,".codeyam","journal"),a=L.join(s,"index.json");L.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 c=0;c<l.scenarioScreenshots.length;c++){const p=l.scenarioScreenshots[c];if(p.name!==t)continue;const u=L.join(s,p.path);try{await Ae.copyFile(r,u),i=!0,console.log(`[editor-register-scenario] Updated journal screenshot for "${t}" in entry "${l.title}"`)}catch(m){console.warn(`[editor-register-scenario] Failed to update journal screenshot: ${m instanceof Error?m.message:m}`)}}i&&bt.notifyChange("journal")}const Ui=jo;async function ny({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=Cg({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:c}=s;if(!o)return new Response(JSON.stringify({error:"name is required"}),{status:400,headers:{"Content-Type":"application/json"}});const p=await Fe();if(!p)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:u}=await Re(p),m=Te(),h=process.env.CODEYAM_ROOT_PATH||process.cwd();let f,g,y;if(!s.viewportWidth&&!s.viewportHeight&&!s.dimension&&!s.dimensions){const Q=await m.selectFrom("editor_scenarios").selectAll().where("name","=",o).where("project_id","=",u.id).orderBy("created_at","desc").executeTakeFirst();if(Q){f=Q.viewport_width||void 0,g=Q.viewport_height||void 0;try{const U=Q.dimensions?JSON.parse(Q.dimensions):void 0;Array.isArray(U)&&(y=U)}catch{}}}let x=null;s.dimensions&&s.dimensions.length>0?x=s.dimensions:s.dimension?x=[s.dimension]:y&&y.length>0&&(x=y);const w=(x==null?void 0:x[0])||void 0,b=Bs({bodyWidth:s.viewportWidth||f,bodyHeight:s.viewportHeight||g,dimension:w,codeyamRoot:h});let v=null;if(!l){if(s.pageFilePath)v=s.pageFilePath;else if(s.url){const{scanPageFilePaths:Q}=await Promise.resolve().then(()=>sy),U=Ne()||process.cwd(),{allFiles:D}=Q(U);if(v=$c(s.url,D),!v){const O=await import("fs"),V=await import("path"),ne=["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 ie of ne)if(O.existsSync(V.join(U,ie))){v=ie;break}}}}let N=null,C=null;const E=c||v;if(E)try{await ze();const U=(await qe({})||[]).filter(V=>V.filePath===E),O=U.find(V=>{var ne,ie;return((ne=V.metadata)==null?void 0:ne.notExported)===!1&&((ie=V.metadata)==null?void 0:ie.namedExport)===!1})||U[0];O&&(N=O.sha)}catch{}const k=s.type==="application"||s.type==="user";if(!N&&k&&E){const Q=Ne()||process.cwd(),U=Sg({lookupFilePath:E,scenarioType:s.type||null,projectRoot:Q});if(!U.valid)return Response.json({error:U.error},{status:400});if(U.needsAnalysis)try{const{runAnalysisForEntities:D}=await import("./analysisRunner-B_PsTAb1.js");await D({projectRoot:Q,filePaths:[E],onlyDataStructure:!0});try{const V=(await qe({})||[]).filter(we=>we.filePath===E),ie=V.find(we=>{var le,ce;return((le=we.metadata)==null?void 0:le.notExported)===!1&&((ce=we.metadata)==null?void 0:ce.namedExport)===!1})||V[0];ie&&(N=ie.sha)}catch{}if(N)try{const O=await qe({});await _g(m,(O||[]).map(V=>{var ne,ie;return{sha:V.sha,name:V.name,filePath:V.filePath||"",isDefaultExport:((ne=V.metadata)==null?void 0:ne.notExported)===!1&&((ie=V.metadata)==null?void 0:ie.namedExport)===!1}}))}catch{}}catch(D){console.warn(`[editor-register-scenario] Auto analyze-imports failed for ${E}: ${D.message}`)}}l?C=l:v&&v.startsWith("app/")?C=Tt(Ct(v)):s.url&&(C=ut(s.url));const _=await vg(m,{projectId:u.id,name:o,description:i||null,componentName:l||null,componentPath:c||null,url:s.url||null,type:s.type||null,viewportWidth:b.width,viewportHeight:b.height,dimensions:x,screenshotPaths:null,pageFilePath:v,entitySha:N,displayName:C}),S=_.scenarioId;_.cleanedUpIds.length>0&&(Ng(h,_.cleanedUpIds),console.log(`[editor-register-scenario] Cleaned up ${_.cleanedUpIds.length} duplicate(s) for "${o}"`));const j=s.type==="application"||s.type==="user",$=new Date().toISOString(),T={name:o,description:i||null,componentName:l||null,componentPath:c||null,url:s.url||null,type:s.type||(j?null:"component"),screenshotPath:null,viewportWidth:b.width,viewportHeight:b.height,dimensions:x,screenshotPaths:null,pageFilePath:v,entitySha:N,displayName:C,createdAt:$,updatedAt:$},R={};if(j&&s.seed){let Q=s.seed;if(s.type==="user"&&s.baseScenario)try{const D=L.join(h,".codeyam","editor-scenarios",`${s.baseScenario}.json`),O=await Ae.readFile(D,"utf-8"),V=JSON.parse(O);V.seed&&(Q=D0(V.seed,s.seed),console.log(`[editor-register-scenario] Merged seed data from base scenario ${s.baseScenario}`))}catch(D){console.warn(`[editor-register-scenario] Could not read base scenario ${s.baseScenario}: ${D instanceof Error?D.message:D}`)}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 U=L.join(h,".codeyam","editor-scenarios");await Ae.mkdir(U,{recursive:!0}),await Ae.writeFile(L.join(U,`${S}.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 I=null;if(j&&!s.seed&&wr(h)){const U=L.join(h,".codeyam","editor-scenarios",`${S}.json`);let D=!1;try{D=!!JSON.parse(await Ae.readFile(U,"utf-8")).seed}catch{}D||(I='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] ${I}`))}L0(h,S,T,R);let P=null;if(j&&s.seed){const Q=wr(h);if(Q){const U=L.join(h,".codeyam","editor-scenarios",`${S}.seed.json`);console.log(`[editor-register-scenario] Running seed adapter: ${Q}`);const D=await Do(Q,U);if(P={success:D.success,error:D.error},D.success){if(console.log(`[editor-register-scenario] Seed adapter completed in ${D.durationMs}ms`),D.sessionCookies&&D.sessionCookies.length>0)try{const O=L.join(h,".codeyam","editor-scenarios",`${S}.json`),V=JSON.parse(await Ae.readFile(O,"utf-8"));V.sessionCookies=D.sessionCookies,await Ae.writeFile(O,JSON.stringify(V,null,2)),console.log(`[editor-register-scenario] Saved ${D.sessionCookies.length} session cookie(s) to scenario data`)}catch(O){console.warn(`[editor-register-scenario] Failed to save session cookies: ${O}`)}}else console.warn(`[editor-register-scenario] Seed adapter failed: ${D.error}`)}else console.warn(`[editor-register-scenario] No seed adapter found at ${h}/.codeyam/seed-adapter.ts`),P={success:!1,error:"No seed adapter found. Create .codeyam/seed-adapter.ts to use seed-based scenarios."}}bt.notifyChange("scenario"),console.log(`[editor-register-scenario] Starting auto-capture for scenario "${o}" (id: ${S})`);const H=s.url&&s.url.startsWith("/"),W=!s.url||H?await Mo():null,F=Ui(),J=Eo(s.url||null,W,F);console.log(`[editor-register-scenario] Capture URL resolution: explicit=${s.url||"none"}, isPath=${H}, proxy=${W||"none"}, devServer=${F||"none"} → using ${J||"none"}`);let Y=null,z=null,A=[],B=null,G=null,q={};if(J){const Q=Qt(o),U=await zo({scenarioId:S,scenarioSlug:Q,scenarioType:s.type||void 0,projectRoot:h});Fn(),!P&&U.seedResult&&(P=U.seedResult),console.log(`[editor-register-scenario] Active scenario set to "${Q}" (${S}), type=${U.type}, seeded=${U.seeded}, seedResult=${JSON.stringify(U.seedResult??null)}, cache invalidated`),await new Promise(ce=>setTimeout(ce,300));const D=(t=s.url)!=null&&t.startsWith("/")?`${Ui()||"http://localhost:3113"}${s.url}`:J;for(let ce=0;ce<5;ce++){try{const ve=await fetch(D,{method:"GET",signal:AbortSignal.timeout(3e3)});if(ve.status<500)break;console.log(`[editor-register-scenario] Route returned ${ve.status}, waiting for HMR (attempt ${ce+1}/5)...`)}catch{console.log(`[editor-register-scenario] Route not reachable, waiting for HMR (attempt ${ce+1}/5)...`)}await new Promise(ve=>setTimeout(ve,2e3))}const O=L.join(h,".codeyam","editor-scenarios","screenshots");await Ae.mkdir(O,{recursive:!0});const V=$o(import.meta.url),ne=await Io(V,h);console.log(`[editor-register-scenario] Capture script: ${ne}`);const ie=Ao(h),we=x&&x.length>0?x:[null];q={};let le=null;for(let ce=0;ce<we.length;ce++){const ve=we[ce];let Ee=b;if(ve){const de=ie[ve];de!=null&&de.width&&(de!=null&&de.height)&&(Ee={width:de.width,height:de.height})}const he=ve?Oc(ve):null,Z=he&&we.length>1?`${S}--${he}.png`:`${S}.png`,Se=L.join(O,Z),fe=`screenshots/${Z}`;ce===0&&(G=Ee,le=Se);const se=JSON.stringify({url:J,outputPath:Se,viewportWidth:Ee.width,viewportHeight:Ee.height,...l?{selector:"#codeyam-capture"}:{}});console.log(`[editor-register-scenario] Capture ${ve||"default"}: ${Ee.width}×${Ee.height} → ${Z}`);const pe=Date.now(),_e=await Ro(ne,se,h),Le=Date.now()-pe;console.log(`[editor-register-scenario] Capture ${ve||"default"} ${_e.success?"succeeded":"FAILED"} in ${Le}ms`),_e.success||(console.warn(`[editor-register-scenario] Capture stdout: ${_e.output.slice(0,500)}`),console.warn(`[editor-register-scenario] Capture stderr: ${(_e.error||"").slice(0,500)}`)),ce===0&&(A=td(_e.output),B=T0(_e.output),await nd(h,S,o,A),A.length>0&&console.warn(`[editor-register-scenario] ${A.length} client-side error(s) detected:`,A)),_e.success?(ve&&(q[ve]=fe),ce===0&&(Y=fe)):ce===0&&(z=_e.error||"Unknown capture error",console.warn(`[editor-register-scenario] Screenshot capture failed (non-blocking): ${z}`))}if(Y){try{await m.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}const ce={screenshot_path:Y,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};Object.keys(q).length>0&&(ce.screenshot_paths=JSON.stringify(q)),await m.updateTable("editor_scenarios").set(ce).where("id","=",S).execute(),bt.notifyChange("scenario"),le&&await ty(h,o,le)}}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=${Y?"captured":"skipped"}`),J&&Y)try{const Q=Ne()||process.cwd(),U=L.join(Q,".codeyam","editor-step.json");let D=null;try{const O=K.readFileSync(U,"utf8");D=JSON.parse(O).featureStartedAt||null}catch{}if(D){const O=Ar(D),V=await m.selectFrom("editor_scenarios").selectAll().where("project_id","=",u.id).orderBy("created_at","asc").execute(),ne=vt(V,we=>`${we.name}::${we.url||"/"}`),ie=Vn();if(ie.length>0){let we=!1;try{const{execSync:pe}=await import("child_process"),_e=pe("git rev-list --count HEAD",{cwd:Q,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();we=parseInt(_e,10)<=1}catch{we=!0}const le=Ic(ie,we),ce={},ve=L.join(Q,"app");if(K.existsSync(ve)){const pe=(_e,Le)=>{for(const de of K.readdirSync(_e,{withFileTypes:!0}))if(de.name!=="isolated-components"){if(de.isDirectory())pe(L.join(_e,de.name),Le?`${Le}/${de.name}`:de.name);else if(de.name==="page.tsx"||de.name==="page.js"){const We=ut(Le?`/${Le}`:"/");ce[We]=Le?`app/${Le}/${de.name}`:`app/${de.name}`}}};pe(ve,"")}let Ee=[];try{await ze(),Ee=await qe({})||[]}catch{}const he=ne.map(pe=>({componentName:pe.component_name||null,componentPath:pe.component_path||null,pageFilePath:pe.page_file_path??null,url:pe.url??null,displayName:pe.display_name??null})),Z=Rc(he,ce,Ee),Se=Dc(le,Z),fe=ne.filter(pe=>pe.created_at<O),se=new Map;for(const pe of fe){const _e=nn({componentName:pe.component_name,pageFilePath:pe.page_file_path,url:pe.url});((r=Se[_e])==null?void 0:r.status)==="impacted"&&se.set(_e,pe)}if(se.size>0){console.log(`[editor-register-scenario] Recapturing ${se.size} impacted older scenario(s): ${[...se.keys()].join(", ")}`);const{recaptureScenarios:pe}=await Promise.resolve().then(()=>My),_e=[...se.values()].map(de=>({id:de.id,name:de.name,url:de.url,component_name:de.component_name,dimensions:de.dimensions,viewport_width:de.viewport_width,viewport_height:de.viewport_height}));await pe({scenarios:_e,codeyamRoot:h,proxyUrl:W,devUrl:F,db:m,importMetaUrl:import.meta.url});const Le=L.join(h,".codeyam","active-scenario.json");await Ae.writeFile(Le,JSON.stringify({scenarioId:S,scenarioSlug:Qt(o),type:s.type||null,timestamp:new Date().toISOString()})),Fn(),bt.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(),U=Object.keys(q).length>0?q:null;id(h,S,{name:o,description:i||null,componentName:l||null,componentPath:c||null,url:s.url||null,type:s.type||null,screenshotPath:Y||null,viewportWidth:b.width,viewportHeight:b.height,dimensions:x,screenshotPaths:U,pageFilePath:v,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{U0({dimension:w,viewport:b,refreshPath:s.url||void 0,scenarioId:S})}catch{}return new Response(JSON.stringify({success:!0,scenario:{id:S,name:o,description:i,componentName:l||null,componentPath:c||null,screenshotPath:Y,url:s.url||null,type:s.type||null,viewportWidth:b.width,viewportHeight:b.height,dimensions:x,screenshotPaths:Object.keys(q).length>0?q:null},updated:!_.isNew,screenshotCaptured:Y!==null,capturedViewport:G,captureError:z,clientErrors:A,...B?{visibleText:B}:{},...P?{seedResult:P}:{},...I?{missingSeedWarning:I}:{}}),{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 ry=Object.freeze(Object.defineProperty({__proto__:null,action:ny},Symbol.toStringTag,{value:"Module"}));function Bo(e){const t={},r=[],s=L.join(e,"app");if(!K.existsSync(s))return{map:t,allFiles:r};const a=c=>c.split("/").filter(p=>!p.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=(c,p)=>{for(const u of K.readdirSync(c,{withFileTypes:!0}))if(u.name!=="isolated-components")if(u.isDirectory())l(L.join(c,u.name),p?`${p}/${u.name}`:u.name);else if(u.name==="page.tsx"||u.name==="page.js"){const m=p?`app/${p}/${u.name}`:`app/${u.name}`;r.push(m);const h=a(p);t[ut(h?`/${h}`:"/")]=m}else{if(o.has(u.name))continue;{const m=L.extname(u.name);if(!i.has(m))continue;const h=L.basename(u.name,m),f=p?`app/${p}/${u.name}`:`app/${u.name}`,g=a(p);let y;h==="index"?y=g?`/${g}`:"/":y=g?`/${g}/${h}`:`/${h}`,r.push(f);const x=ut(y);t[x]||(t[x]=f)}}};return l(s,""),{map:t,allFiles:r}}function dd(e){try{const t=$e("git rev-list --count HEAD",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim();return parseInt(t,10)<=1}catch{return!0}}function ud(e){try{const t=L.join(e,".codeyam","editor-step.json"),r=K.readFileSync(t,"utf8");return JSON.parse(r).featureStartedAt||null}catch{return null}}function Yo(e){try{const t=L.join(e,".codeyam","editor-step.json"),r=K.readFileSync(t,"utf8");return JSON.parse(r).feature||null}catch{return null}}function pd(e){try{const t=L.join(e,".codeyam","editor-step.json"),r=K.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 md(e){try{const t=L.join(e,".codeyam","claude-session-id.txt");return K.readFileSync(t,"utf8").trim()||null}catch{return null}}function Uo(e){try{const t=L.join(e,".codeyam","editor-user-prompt.txt");return K.readFileSync(t,"utf8").trim()||null}catch{return null}}const sy=Object.freeze(Object.defineProperty({__proto__:null,detectFirstFeature:dd,readEditorFeature:Yo,readEditorSessionId:md,readEditorStep:pd,readEditorUserPrompt:Uo,readFeatureStartedAt:ud,scanPageFilePaths:Bo},Symbol.toStringTag,{value:"Module"}));async function Gn(e){const{projectRoot:t,scenarioInputs:r,glossaryInputs:s}=e,o=(e.precomputedPageFilePaths??Bo(t)).map,i=new Set(Object.keys(o)),l=e.precomputedGitFiles??Vn();if(l.length===0)return{entityChangeStatus:{},pageEntityNames:i};const c=dd(t),p=Ic(l,c);let u=[];if(e.precomputedEntities)u=e.precomputedEntities;else try{await ze(),u=await qe({})||[]}catch{}const m=Rc(r,o,u);let h=m;if(s&&s.length>0){const g=new Set(m.map(x=>x.name)),y=ig(s,g);h=[...m,...y]}return{entityChangeStatus:Dc(p,h),pageEntityNames:i}}function ay(e,t,r,s){const a=s?s.replace("T"," ").replace(/\.\d{3}Z$/,""):null,o=[],i=[],l=new Set;for(const u of e){const m=nn({componentName:u.component_name,pageFilePath:u.page_file_path,url:u.url});if(!m)continue;const h=t[m];if(!h||u.component_name)continue;const f=u.created_at||"",g=u.updated_at||"";(a?f>=a||g>=a:!0)?(i.push({name:u.name,url:u.url,entityName:m}),l.add(m)):o.push({name:u.name,url:u.url,entityName:m,changeStatus:h.status,lastCaptured:f})}const c=[];for(const[u,m]of Object.entries(t)){if(!r.has(u)||l.has(u))continue;o.some(f=>f.entityName===u)||c.push({entityName:u,changeStatus:m.status})}const p=o.length===0&&c.length===0;return{staleScenarios:o,freshScenarios:i,uncoveredPages:c,pass:p}}async function oy(){const e=Ne()||process.cwd(),t=await Fe();if(!t)return Response.json({error:"No project configured"},{status:400});const r=L.join(e,".codeyam","editor-step.json");let s=null;try{const f=K.readFileSync(r,"utf8");s=JSON.parse(f).featureStartedAt||null}catch{}const{project:a}=await Re(t),i=await Te().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=vt(i,f=>`${f.name}::${f.url||"/"}`),c=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 p={},u=new Set;try{const f=await Gn({projectRoot:e,scenarioInputs:c});p=f.entityChangeStatus,u=f.pageEntityNames}catch{}if(Object.keys(p).length===0)return Response.json({staleScenarios:[],uncoveredPages:[],freshScenarios:[],pass:!0,note:"No entity change data available — cannot determine coverage."});const m=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})),h=ay(m,p,u,s);return Response.json(h)}const iy=Object.freeze(Object.defineProperty({__proto__:null,loader:oy},Symbol.toStringTag,{value:"Module"}));function ly({executionFlows:e,selections:t,onChange:r,disabled:s=!1}){const a=oe(i=>t.some(l=>l.flowId===i),[t]),o=oe(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),c=i.usedInScenarios.length>0;return d("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[d("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"}),d("div",{className:"flex-1 min-w-0",children:[d("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}),!c&&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&&d("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((p,u)=>d("li",{className:"text-gray-600",children:[n("code",{className:"bg-gray-100 px-1 rounded",children:p.attributePath})," ",n("span",{className:"text-gray-400",children:p.comparison})," ",n("code",{className:"bg-gray-100 px-1 rounded",children:p.value})]},u))})]})]},i.id)})})}function Wo(e,t){const r=(e||[]).map(c=>({...c,usedInScenarios:[]})),s=new Map;r.forEach(c=>{s.set(c.id,c)});const a=[];t.forEach(c=>{var u;const p=((u=c.metadata)==null?void 0:u.coveredFlows)||[];p.forEach(m=>{const h=s.get(m);h&&h.usedInScenarios.push({id:c.id||"",name:c.name})}),a.push({scenario:c,coveredFlowIds:p})});const o=r.length,i=r.filter(c=>c.usedInScenarios.length>0).length,l=o>0?i/o*100:0;return{executionFlows:r,totalFlows:o,coveredFlows:i,coveragePercentage:l,scenariosWithFlows:a}}function cy(e){return e.executionFlows.filter(t=>t.usedInScenarios.length===0)}const dy=({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 uy({params:e}){var i;const{sha:t}=e;if(!t)throw new Response("Entity SHA is required",{status:400});const r=await js(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===Ps);if(!a)throw new Response("Default scenario not found",{status:404});const o=await Fe();return X({analysis:s,defaultScenario:a,entity:s.entity,entitySha:t,projectSlug:o})}function py(){var J;const{analysis:e,defaultScenario:t,entity:r,entitySha:s,projectSlug:a}=tt(),o=Pt(),{iframeRef:i}=Po(),[l,c]=M(""),[p,u]=M(400),[m,h]=M(!1),[f,g]=M(!1),[y,x]=M(!1),[w,b]=M(null),[v,N]=M(null),[C,E]=M([]),k=ae(()=>{var z;return!((z=e==null?void 0:e.metadata)!=null&&z.executionFlows)||!(e!=null&&e.scenarios)?[]:Wo(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:_,isStarting:S,isLoading:j,showIframe:$,iframeKey:T,onIframeLoad:R}=vn({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}),I=oe(async()=>{var Y,z,A,B;if(!l.trim()&&C.length===0){b("Please describe how you want to change the scenario or select execution flows");return}g(!0),b(null),N("Generating scenario with AI...");try{const G=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:l,existingScenarios:e.scenarios,scenariosDataStructure:(Y=e.metadata)==null?void 0:Y.scenariosDataStructure,flowSelections:C.length>0?C:void 0})}),q=await G.json();if(!G.ok||!q.success)throw new Error(q.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",q.data);const Q=q.data;if(!Q.name||!Q.data)throw new Error("AI response missing required fields (name or data)");N("Saving new scenario..."),x(!0);const U={name:Q.name,description:Q.description||l,metadata:{data:Q.data,interactiveExamplePath:(z=t.metadata)==null?void 0:z.interactiveExamplePath}},D=[...e.scenarios||[],U],O=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:D})}),V=await O.json();if(!O.ok||!V.success)throw new Error(V.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",V);const ne=(B=(A=V.analysis)==null?void 0:A.scenarios)==null?void 0:B.find(ie=>ie.name===Q.name);if(!(ne!=null&&ne.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),N("Scenario created! Redirecting..."),setTimeout(()=>void o(`/entity/${s}`),1e3);return}if(_){N("Capturing screenshot...");const ie=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:_,scenarioId:ne.id,projectId:e.projectId,viewportWidth:1440})}),we=await ie.json();!ie.ok||!we.success?(console.error("[CreateScenario] Capture failed:",we),N("Scenario created! (Screenshot capture failed)")):N("Scenario created and captured!")}else N("Scenario created!");setTimeout(()=>{o(`/entity/${s}/scenarios/${ne.id}`)},1e3)}catch(G){console.error("[CreateScenario] Error:",G),b(G instanceof Error?G.message:String(G)),N(null)}finally{g(!1),x(!1)}},[l,C,e,t,s,_,o]),P=f||y,H=oe(()=>{h(!0)},[]),W=oe(Y=>{if(!m)return;const z=Y.clientX;z>=250&&z<=600&&u(z)},[m]),F=oe(()=>{h(!1)},[]);return re(()=>(m?(document.addEventListener("mousemove",W),document.addEventListener("mouseup",F)):(document.removeEventListener("mousemove",W),document.removeEventListener("mouseup",F)),()=>{document.removeEventListener("mousemove",W),document.removeEventListener("mouseup",F)}),[m,W,F]),d("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:d("div",{className:"flex items-end h-full px-6 gap-6",children:[d("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})]}),d("div",{className:"flex items-end gap-8 shrink-0",children:[n(Ce,{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:d("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:((J=e==null?void 0:e.scenarios)==null?void 0:J.length)||0})]})}),n(Ce,{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(Ce,{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(Ce,{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(Ce,{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"})]})]})}),d("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[d("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${p}px`},children:[d("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."})]}),k.length>0&&d("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[d("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&&d("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(ly,{executionFlows:k,selections:C,onChange:E,disabled:P})})]}),d("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:Y=>c(Y.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:P})]}),d("div",{className:"space-y-2",children:[n("button",{onClick:()=>void I(),disabled:P||!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:P?"Creating...":"Create Scenario"}),v&&n("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:v}),w&&n("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:w})]})]}),d("div",{onMouseDown:H,style:{width:"20px",position:"absolute",top:0,left:`${p-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:m?"#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:`
|
|
275
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
276
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
277
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
278
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
279
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:n(Us,{scenarioId:t.id||t.name,scenarioName:t.name,iframeUrl:_,isStarting:S,isLoading:j,showIframe:$,iframeKey:T,onIframeLoad:R,projectSlug:a,defaultWidth:1440,defaultHeight:900})})]})]})}const my=Qe(function(){return n(Ys,{children:n(py,{})})}),hy=Object.freeze(Object.defineProperty({__proto__:null,default:my,loader:uy,meta:dy},Symbol.toStringTag,{value:"Module"})),fy=jo;async function gy({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 Fe();if(!i)return new Response(JSON.stringify({error:"Project not initialized"}),{status:400,headers:{"Content-Type":"application/json"}});const{project:l}=await Re(i),c=Te(),p=await c.selectFrom("editor_scenarios").selectAll().where("id","=",r).where("project_id","=",l.id).executeTakeFirst();if(!p)return new Response(JSON.stringify({error:"Scenario not found"}),{status:404,headers:{"Content-Type":"application/json"}});const u=s??p.url??null,m=u&&u.startsWith("/"),h=!u||m?await Mo():null,f=fy(),g=Eo(u,h,f);if(console.log(`[editor-capture-scenario] URL resolution: explicit=${s||"none"}, db=${p.url||"none"}, proxy=${h||"none"}, devServer=${f||"none"} → captureUrl=${g||"none"}`),!g)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 "${p.name}" (id: ${r}), url: ${g}`);const y=process.env.CODEYAM_ROOT_PATH||process.cwd(),x=Qt(p.name);await zo({scenarioId:r,scenarioSlug:x,scenarioType:p.type||void 0,projectRoot:y}),Fn(),console.log(`[editor-capture-scenario] Active scenario set to "${x}", cache invalidated`),await new Promise($=>setTimeout($,300));const w=L.join(y,".codeyam","editor-scenarios","screenshots");await Ae.mkdir(w,{recursive:!0});const b=$o(import.meta.url),v=await Io(b,y);console.log(`[editor-capture-scenario] Capture script: ${v}`);let N;const C=p;if(t.dimensions&&t.dimensions.length>0)N=t.dimensions;else if(C.dimensions)try{const $=JSON.parse(C.dimensions);N=Array.isArray($)&&$.length>0?$:[null]}catch{N=[null]}else N=[null];const E=Ao(y);let k=null;const _={};let S=[],j=null;for(let $=0;$<N.length;$++){const T=N[$];let R;T&&E[T]?R=E[T]:R=Bs({bodyWidth:a||C.viewport_width||void 0,bodyHeight:o||C.viewport_height||void 0,dimension:T||void 0,codeyamRoot:y});const I=T?Oc(T):null,P=I&&N.length>1?`${r}--${I}.png`:`${r}.png`,H=L.join(w,P),W=`screenshots/${P}`,F=JSON.stringify({url:g,outputPath:H,viewportWidth:R.width,viewportHeight:R.height,...p.component_name?{selector:"#codeyam-capture"}:{}});console.log(`[editor-capture-scenario] Capture ${T||"default"}: ${R.width}×${R.height} → ${P}`);const J=Date.now(),Y=await Ro(v,F,y),z=Date.now()-J;if(console.log(`[editor-capture-scenario] Capture ${T||"default"} ${Y.success?"succeeded":"FAILED"} in ${z}ms`),!Y.success){console.warn(`[editor-capture-scenario] Capture stdout: ${Y.output.slice(0,500)}`),console.warn(`[editor-capture-scenario] Capture stderr: ${(Y.error||"").slice(0,500)}`),$===0&&(j=Y.error||"Unknown capture error");continue}if($===0){k=W;const A=td(Y.output);S=A,await nd(y,r,p.name,A)}T&&(_[T]=W)}if(!k&&j)return new Response(JSON.stringify({error:"Failed to capture screenshot",details:j}),{status:500,headers:{"Content-Type":"application/json"}});if(k){try{await c.schema.alterTable("editor_scenarios").addColumn("screenshot_path","varchar").execute()}catch{}const $={screenshot_path:k,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")};Object.keys(_).length>0&&($.screenshot_paths=JSON.stringify(_)),await c.updateTable("editor_scenarios").set($).where("id","=",r).execute()}return S.length>0&&console.warn(`[editor-capture-scenario] ${S.length} client-side error(s) detected:`,S),bt.notifyChange("scenario"),new Response(JSON.stringify({success:!0,screenshotPath:k,screenshotPaths:Object.keys(_).length>0?_:null,clientErrors:S}),{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 yy=Object.freeze(Object.defineProperty({__proto__:null,action:gy},Symbol.toStringTag,{value:"Module"}));async function xy({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 Pe.stat(a),c=`"${l.mtimeMs}-${l.size}"`;if(e.headers.get("If-None-Match")===c)return new Response(null,{status:304,headers:{ETag:c,"Cache-Control":"public, max-age=300"}});const u=await Pe.readFile(a),m=ee.extname(a).toLowerCase(),h=m===".png"?"image/png":m===".jpg"||m===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(u,{status:200,headers:{"Content-Type":h,"Cache-Control":"public, max-age=300",ETag:c}})}catch{return new Response("Image not found",{status:404})}}const by=Object.freeze(Object.defineProperty({__proto__:null,loader:xy},Symbol.toStringTag,{value:"Module"}));async function wy({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 Pe.readFile(s),l=ee.extname(s).toLowerCase(),c=l===".png"?"image/png":l===".jpg"||l===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(i,{status:200,headers:{"Content-Type":c,"Cache-Control":"no-store"}})}catch{return new Response("Image not found",{status:404})}}const vy=Object.freeze(Object.defineProperty({__proto__:null,loader:wy},Symbol.toStringTag,{value:"Module"})),Ny=["JSX","React","Element","ReactNode"];function Sy(e){return e.returnType?Ny.some(t=>e.returnType.includes(t)):!1}function Cy(e){const t=[],r=[];for(const s of e)Sy(s)?t.push(s):r.push(s);return{components:t,functions:r}}function _y({components:e,functions:t,scenarioCounts:r,testFileExistence:s,testResults:a,clientErrors:o,totalScenarioCounts:i,entityChangeStatus:l}){const c=e.map(v=>{const N=r[v.name]||0,C=(i==null?void 0:i[v.name])||0,E=l==null?void 0:l[v.name],k=o==null?void 0:o[v.name],_=N>0&&k&&k.length>0;let S;return N===0?E&&C>0?S="needs_recapture":S="missing":_?S="has_errors":S="ok",{name:v.name,filePath:v.filePath,scenarioCount:S==="needs_recapture"?C:N,status:S,..._?{clientErrors:k}:{}}}),p=t.map(v=>{if(!(v.testFile?s[v.testFile]??!1:!1))return{name:v.name,filePath:v.filePath,testFile:v.testFile,testFileExists:!1,status:"missing"};const C=v.testFile&&a?a[v.testFile]:void 0;if(!C)return{name:v.name,filePath:v.filePath,testFile:v.testFile,testFileExists:!0,status:"ok"};let E;return!C.passing&&C.errorMessage?E="runner_error":C.passing?C.hasEntityNameDescribe?E="ok":E="name_mismatch":E="failing",{name:v.name,filePath:v.filePath,testFile:v.testFile,testFileExists:!0,testsPassing:C.passing,testsVisibleInUi:C.hasEntityNameDescribe,status:E,...C.errorMessage?{errorMessage:C.errorMessage}:{}}}),u=c.filter(v=>v.status==="ok"||v.status==="needs_recapture").length,m=c.filter(v=>v.status==="has_errors").length,h=c.filter(v=>v.status==="missing").length,f=c.filter(v=>v.status==="needs_recapture").length,g=p.filter(v=>v.status==="ok").length,y=p.filter(v=>v.status==="failing").length,x=p.filter(v=>v.status==="runner_error").length,w=p.filter(v=>v.status==="name_mismatch").length,b=p.filter(v=>v.status==="missing").length;return{components:c,functions:p,summary:{totalComponents:c.length,componentsOk:u,componentsMissing:h,componentsWithErrors:m,componentsNeedingRecapture:f,totalFunctions:p.length,functionsOk:g,functionsMissing:b,functionsFailing:y,functionsRunnerError:x,functionsNameMismatch:w,allPassing:h===0&&m===0&&y===0&&x===0&&w===0&&b===0}}}function ky({featureStartedAt:e,entityChangeStatus:t}){return t&&Object.keys(t).length>0?{featureStartedAt:e,entityChangeStatus:t}:{featureStartedAt:null,entityChangeStatus:t}}function Ey(e,t){return!t||Object.keys(t).length===0?e:e.filter(r=>!!(t[r.name]||t[r.filePath]))}async function Ay(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(N=>N.entity_sha),i=await e.selectFrom("analyses").select("entity_sha").where("entity_sha","in",o).groupBy("entity_sha").execute(),l=new Set(i.map(N=>N.entity_sha)),c=a.filter(N=>!l.has(N.entity_sha));if(c.length===0)return[];const p=c.map(N=>N.entity_sha),u=await e.selectFrom("entities").select(["sha","name","file_path"]).where("sha","in",p).execute(),m=new Map(u.map(N=>[N.sha,N.name])),h=new Map(u.map(N=>[N.sha,N.file_path])),f=[...new Set(u.map(N=>`${N.name}::${N.file_path}`).filter(N=>!N.startsWith("::")&&!N.endsWith("::")))];let g=new Set;if(f.length>0){const N=[...new Set(u.map(E=>E.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",N).groupBy(["entities.name","entities.file_path"]).execute();g=new Set(C.map(E=>`${E.name}::${E.file_path}`))}const y=c.filter(N=>{const C=N.entity_sha,E=m.get(C),k=h.get(C);if(!E)return!0;const _=`${E}::${k}`;return!g.has(_)});if(y.length===0)return[];const x=y.map(N=>N.entity_sha),w=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(),b=new Map(w.map(N=>[N.entity_sha,N.component_name]));let v=new Set;if(r){const N=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(E=>E.or([E("created_at",">=",N),E("updated_at",">=",N)])).groupBy("entity_sha").execute();v=new Set(C.map(E=>E.entity_sha))}return y.map(N=>{const C=N.entity_sha;return{entitySha:C,name:m.get(C)||b.get(C)||"Unknown",scenarioCount:Number(N.count),preExisting:r?!v.has(C):!1}})}async function Py(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(c=>c.or([c("created_at",">=",l),c("updated_at",">=",l)]))}const o=(await s.execute()).filter(l=>l.url&&!zs(l.url));if(o.length===0)return[];const i=new Map;for(const l of o){const c=`${l.component_name}::${l.url}`,p=i.get(c);p?p.scenarioNames.push(l.name):i.set(c,{componentName:l.component_name,scenarioNames:[l.name],url:l.url})}return[...i.values()]}async function Wi(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 Ji(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 jy(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(c=>c.or([c("created_at",">=",l),c("updated_at",">=",l)]))}const a=await s.execute();if(a.length===0)return[];const o=new Map;for(const l of a){const c=l,p=c.component_path||c.page_file_path,u=o.get(p);if(u)u.scenarioNames.push(c.name);else{const m=c.component_name||((i=p.split("/").pop())==null?void 0:i.replace(/\.\w+$/,""))||p;o.set(p,{name:m,filePath:p,scenarioNames:[c.name]})}}return[...o.values()].map(l=>({name:l.name,filePath:l.filePath,scenarioCount:l.scenarioNames.length,scenarioNames:l.scenarioNames}))}function Ty(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 hd(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&&s.push({scenarioName:a.name,entityName:a.entityName,status:o})}return s}async function fd(e){const{scenarios:t,codeyamRoot:r,proxyUrl:s,devUrl:a,db:o,importMetaUrl:i,onProgress:l}=e,c={recaptured:[],failed:[]};if(t.length===0)return c;const p=$o(i),u=await Io(p,r),m=L.join(r,".codeyam","editor-scenarios","screenshots");for(const h of t)try{const f=Qt(h.name);await zo({scenarioId:h.id,scenarioSlug:f,projectRoot:r}),Fn(),await new Promise(N=>setTimeout(N,300));const g=Eo(h.url||null,s,a);if(!g){c.failed.push({name:h.name,error:"No capture URL available"});continue}const y=L.join(m,`${h.id}.png`);let x;try{const N=h.dimensions?JSON.parse(h.dimensions):null;Array.isArray(N)&&N.length>0&&(x=N[0])}catch{}const w=Bs({bodyWidth:h.viewport_width||void 0,bodyHeight:h.viewport_height||void 0,dimension:x,codeyamRoot:r}),b=JSON.stringify({url:g,outputPath:y,viewportWidth:w.width,viewportHeight:w.height,...h.component_name?{selector:"#codeyam-capture"}:{}});l==null||l(`Capturing "${h.name}"...`),console.log(`[recapture] Capturing "${h.name}" at ${w.width}x${w.height}`);const v=await Ro(u,b,r);if(v.success)await o.updateTable("editor_scenarios").set({screenshot_path:`screenshots/${h.id}.png`,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")}).where("id","=",h.id).execute(),c.recaptured.push(h.name),l==null||l(`Recaptured "${h.name}"`),console.log(`[recapture] Succeeded: "${h.name}"`);else{const N=v.error||"Unknown capture error";c.failed.push({name:h.name,error:N}),l==null||l(`Failed: "${h.name}" — ${N}`),console.warn(`[recapture] Failed: "${h.name}": ${N}`)}}catch(f){const g=f instanceof Error?f.message:String(f);c.failed.push({name:h.name,error:g}),console.warn(`[recapture] Error for "${h.name}": ${g}`)}return c}const My=Object.freeze(Object.defineProperty({__proto__:null,recaptureScenarios:fd},Symbol.toStringTag,{value:"Module"}));async function $y({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ne()||process.cwd(),r=await Fe();if(!r)return Response.json({error:"No project configured"},{status:400});const{project:s}=await Re(r),a=Te(),o=process.env.CODEYAM_ROOT_PATH||process.cwd(),i=L.join(t,".codeyam","editor-step.json");let l=null;try{const C=K.readFileSync(i,"utf8");l=JSON.parse(C).featureStartedAt||null}catch{}try{await ze();const C=await qe({})||[];await Fc(a,C.map(E=>{var k,_;return{sha:E.sha,name:E.name,filePath:E.filePath||"",isDefaultExport:((k=E.metadata)==null?void 0:k.notExported)===!1&&((_=E.metadata)==null?void 0:_.namedExport)===!1}}))}catch{}const c=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(),p=vt(c,C=>`${C.name}::${C.url||"/"}`),u=p.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:m}=await Gn({projectRoot:t,scenarioInputs:u});if(Object.keys(m).length===0)return Response.json({type:"done",recaptured:[],failed:[],total:0,note:"No entity changes detected."});const h=l?Ar(l):null,f=p.map(C=>({name:C.name,entityName:nn({componentName:C.component_name,pageFilePath:C.page_file_path,url:C.url}),updatedInSession:h?ko({created_at:C.created_at,updated_at:C.updated_at},h):!1})),g=hd({scenarios:f,entityChangeStatus:m});if(g.length===0)return Response.json({type:"done",recaptured:[],failed:[],total:0,note:"All scenarios are up to date."});const y=new Set(g.map(C=>C.scenarioName)),x=p.filter(C=>y.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})),w=await Mo(),b=jo(),v=new Map(p.map(C=>[C.name,C])),N=new ReadableStream({async start(C){const E=_=>{C.enqueue(new TextEncoder().encode(JSON.stringify(_)+`
|
|
280
|
-
`))};E({type:"start",total:g.length});const k=await fd({scenarios:x,codeyamRoot:o,proxyUrl:w,devUrl:b,db:a,importMetaUrl:import.meta.url,onProgress:_=>{if(_.startsWith('Recaptured "')){const S=_.slice(12,-1);E({type:"success",name:S});const j=v.get(S);if(j)try{F0(o,j.id,`screenshots/${j.id}.png`)}catch{}}else if(_.startsWith('Failed: "')){const S=_.match(/^Failed: "(.+?)" — (.+)$/);S&&E({type:"failure",name:S[1],error:S[2]})}else if(_.startsWith('Capturing "')){const S=_.slice(11,_.indexOf('"',11));E({type:"capturing",name:S})}}});E({type:"done",recaptured:k.recaptured,failed:k.failed,total:g.length}),C.close()}});return new Response(N,{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 Iy=Object.freeze(Object.defineProperty({__proto__:null,action:$y},Symbol.toStringTag,{value:"Module"}));async function Ry({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 Te().updateTable("editor_scenarios").set({name:a,updated_at:new Date().toISOString().replace("T"," ").replace(/\.\d{3}Z$/,"")}).where("id","=",r).execute();const l=Ne()||process.cwd(),p=O0(l).find(u=>u.id===r);return p&&id(l,r,{...p.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 Dy=Object.freeze(Object.defineProperty({__proto__:null,action:Ry},Symbol.toStringTag,{value:"Module"}));async function Oy({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=Ne()||process.cwd(),o=ee.join(a,".codeyam"),i=ee.join(o,"active-scenario.json");if(!ue.existsSync(i))return new Response(JSON.stringify({error:"No active scenario"}),{status:400,headers:{"Content-Type":"application/json"}});const c=JSON.parse(ue.readFileSync(i,"utf-8")).scenarioId;if(!c)return new Response(JSON.stringify({error:"No active scenario ID"}),{status:400,headers:{"Content-Type":"application/json"}});const p=ee.join(o,"editor-scenarios"),u=wr(a);let m=null;if(u){const f=ee.join(o,"tmp",`export-${Date.now()}.json`);ue.mkdirSync(ee.dirname(f),{recursive:!0});const g=await R0(u,f);if(!g.success)return new Response(JSON.stringify({error:`Export failed: ${g.error}`}),{status:500,headers:{"Content-Type":"application/json"}});try{m=JSON.parse(ue.readFileSync(f,"utf-8"))}finally{try{ue.unlinkSync(f)}catch{}}}if(!m&&!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 h=c;if(r==="new"){h=Bn.randomUUID();const f=ee.join(p,`${c}.json`);let g={_metadata:{type:"application"}};ue.existsSync(f)&&(g=JSON.parse(ue.readFileSync(f,"utf-8"))),m&&(g.seed=m),s&&(g.localStorage=s),ue.writeFileSync(ee.join(p,`${h}.json`),JSON.stringify(g,null,2)),m&&ue.writeFileSync(ee.join(p,`${h}.seed.json`),JSON.stringify(m,null,2))}else{const f=ee.join(p,`${c}.json`);if(ue.existsSync(f)){const g=JSON.parse(ue.readFileSync(f,"utf-8"));m&&(g.seed=m),s&&(g.localStorage=s),ue.writeFileSync(f,JSON.stringify(g,null,2))}m&&ue.writeFileSync(ee.join(p,`${c}.seed.json`),JSON.stringify(m,null,2))}return Fn(),new Response(JSON.stringify({success:!0,mode:r,scenarioId:h}),{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 Fy=Object.freeze(Object.defineProperty({__proto__:null,action:Oy},Symbol.toStringTag,{value:"Module"}));async function Ly({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=Ne()||process.cwd(),a=L.join(s,".codeyam","tmp");K.mkdirSync(a,{recursive:!0});const o=Kl.randomUUID().slice(0,8),i=L.join(a,`scenario-prompt-${o}.md`);return K.writeFileSync(i,r,"utf8"),Response.json({promptFile:i})}const zy=Object.freeze(Object.defineProperty({__proto__:null,action:Ly},Symbol.toStringTag,{value:"Module"}));let on=null;async function By({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=Ne()||process.cwd(),c=ee.join(l,".codeyam"),p=ee.join(c,"active-scenario.json");let u=o||null;if(!u&&s){const g=ee.join(c,"editor-scenarios",`${s}.json`);try{ue.existsSync(g)&&(u=JSON.parse(ue.readFileSync(g,"utf-8")).type||null)}catch{}}ue.mkdirSync(c,{recursive:!0}),ue.writeFileSync(p,JSON.stringify({scenarioSlug:r,scenarioName:a||null,scenarioId:s||null,type:u,dataFile:s?`.codeyam/editor-scenarios/${s}.json`:null,switchedAt:new Date().toISOString()},null,2));let m=null;const h=u==="application"||u==="user";if(h&&s)if(on&&on.scenarioId===s)console.log(`[editor-switch-scenario] Seed already in progress for "${s}" — reusing`),m=await on.promise;else{const g=wr(l),y=ee.join(c,"editor-scenarios",`${s}.seed.json`);if(g&&ue.existsSync(y)){console.log(`[editor-switch-scenario] Running seed adapter for ${u} scenario "${a||r}"`);const x=Do(g,y).then(w=>{const b={success:w.success,error:w.error};if(w.success){if(console.log(`[editor-switch-scenario] Seed adapter completed in ${w.durationMs}ms`),w.sessionCookies&&w.sessionCookies.length>0)try{const v=ee.join(c,"editor-scenarios",`${s}.json`);if(ue.existsSync(v)){const N=JSON.parse(ue.readFileSync(v,"utf-8"));N.sessionCookies=w.sessionCookies,ue.writeFileSync(v,JSON.stringify(N,null,2))}}catch{}}else console.warn(`[editor-switch-scenario] Seed adapter failed: ${w.error}`);return b});on={scenarioId:s,promise:x};try{m=await x}finally{on&&on.scenarioId===s&&(on=null)}}else g||(console.warn("[editor-switch-scenario] No seed adapter found — skipping database seeding"),m={success:!1,error:"No seed adapter found"})}Fn();const f=i?0:Fo();return new Response(JSON.stringify({success:!0,scenarioSlug:r,refreshedClients:f,seeded:h,...m?{seedResult: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 Yy=Object.freeze(Object.defineProperty({__proto__:null,action:By},Symbol.toStringTag,{value:"Module"}));var ke;(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={}))})(ke||(ke={}));function gd(e,t){return e?Object.values(ke.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${t}`),t):t}const yd=gd(process.env.DEFAULT_SMALLER_MODEL,ke.Model.OPENAI_GPT4_1_MINI),Uy=gd(process.env.DEFAULT_LARGER_MODEL,ke.Model.OPENAI_GPT4_1),_t={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},_a={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},Wy={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},ka={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},Vt={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},Jy={[ke.Model.OPENAI_GPT5_1]:{id:ke.Model.OPENAI_GPT5_1,provider:_t,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[ke.Model.OPENAI_GPT5]:{id:ke.Model.OPENAI_GPT5,provider:_t,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[ke.Model.OPENAI_GPT5_MINI]:{id:ke.Model.OPENAI_GPT5_MINI,provider:_t,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[ke.Model.OPENAI_GPT5_NANO]:{id:ke.Model.OPENAI_GPT5_NANO,provider:_t,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[ke.Model.OPENAI_GPT4_1]:{id:ke.Model.OPENAI_GPT4_1,provider:_t,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[ke.Model.OPENAI_GPT4_1_MINI]:{id:ke.Model.OPENAI_GPT4_1_MINI,provider:_t,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ke.Model.OPENAI_GPT4_O]:{id:ke.Model.OPENAI_GPT4_O,provider:_t,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[ke.Model.OPENAI_GPT4_O_MINI]:{id:ke.Model.OPENAI_GPT4_O_MINI,provider:_t,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[ke.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:ke.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:_a,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[ke.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:ke.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:_a,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[ke.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:ke.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:_a,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[ke.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:ke.Model.OPENAI_GPT_OSS_120B_GROQ,provider:Wy,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[ke.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:ke.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:Vt,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[ke.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:ke.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:Vt,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[ke.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:ke.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:Vt,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ke.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:ke.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:Vt,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[ke.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:ke.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:Vt,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[ke.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:ke.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:ka,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[ke.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:ke.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:ka,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[ke.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:ke.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:ka,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[ke.Model.PHIND_CODELLAMA]:{id:ke.Model.PHIND_CODELLAMA,provider:_t,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ke.Model.GOOGLE_GEMINI_PRO]:{id:ke.Model.GOOGLE_GEMINI_PRO,provider:Vt,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ke.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:ke.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:Vt,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ke.Model.META_CODELLAMA_34B_INSTRUCT]:{id:ke.Model.META_CODELLAMA_34B_INSTRUCT,provider:Vt,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ke.Model.OPENAI_GPT4_PREVIEW]:{id:ke.Model.OPENAI_GPT4_PREVIEW,provider:_t,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function Gs(e){const t=Jy[e];if(!t)throw new Error(`Unknown model: ${e}`);return t}function Hy(e){return Gs(e).maxCompletionTokens}function Vy(e){return Gs(e).pricing}const Hi=1e6;function Gy({model:e,usage:t}){const r=Vy(e);return r?t.prompt_tokens*(r.input/Hi)+t.completion_tokens*(r.output/Hi):null}function Ky({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=Gy({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 qy({messages:{system:e,prompt:t},model:r,responseType:s,jsonSchema:a}){const o=r??yd,i=Gs(o);Hy(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 fr=null;function Qy(e){if(typeof process>"u"||!process.versions||!process.versions.node)return!1;try{const t=xr(e,".codeyam","secrets.json");if(xt(t)){const s=JSON.parse(vi(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=xr(hp(),".codeyam","secrets.json");if(xt(r)){const s=JSON.parse(vi(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 Zy(e){if(typeof process>"u"||!process.versions||!process.versions.node)return!1;const t=xr(e,".claude");return xt(t)}function W2(e){if(Qy(e))return fr={mode:"direct-api",projectRoot:e},"direct-api";if(Zy(e))return fr={mode:"claude-cli",projectRoot:e},"claude-cli";throw new Error(`No AI service configured. Please either:
|
|
281
|
-
1. Add an API key to ~/.codeyam/secrets.json (shared across projects) or .codeyam/secrets.json (project-specific), or
|
|
282
|
-
2. Use Claude Code CLI (detected by .claude folder)`)}function Xy(){return(fr==null?void 0:fr.mode)==="claude-cli"}const Ja="/tmp/codeyam-e2e-tracking";let Ea,Aa;function ex(){return Ea===void 0&&(Ea=process.env.CODEYAM_E2E_TRACK_DATA==="true"),Ea}function tx(){return Aa===void 0&&(Aa=!process.env.CODEYAM_LLM_FIXTURES_DIR),Aa}function nx(){K.existsSync(Ja)||K.mkdirSync(Ja,{recursive:!0})}function rx(e){const t=JSON.stringify(e,null,0);return Kl.createHash("md5").update(t).digest("hex")}function sx(e,t,r){return[e].join("_")+".json"}function xd(e,t,r,s){if(!ex())return;nx();const a=sx(e),o=L.join(Ja,a),i=rx(t);if(tx()){const l={timestamp:Date.now(),checkpoint:e,entityName:r,scenarioName:s,dataHash:i,data:t};K.writeFileSync(o,JSON.stringify(l,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(K.existsSync(o)){const l=JSON.parse(K.readFileSync(o,"utf-8")),c={matches:i===l.dataHash,firstRunHash:l.dataHash};if(c.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{c.differences=Ha(l.data,t),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${l.dataHash}`),console.log(` Second run hash: ${i}`);const p=o.replace(".json","_DIFF.json");K.writeFileSync(p,JSON.stringify({checkpoint:e,entityName:r,scenarioName:s,firstRun:l.data,secondRun:t,differences:c.differences},null,2)),console.log(` Diff saved to: ${p}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function Ha(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(...Ha(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 c=e[l],p=t[l];l in e?l in t?s.push(...Ha(c,p,`${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 Vi=io(oo),Gi=2;function ax(e){try{return JSON.parse(e),{valid:!0}}catch(t){return{valid:!1,error:t.message}}}function ox(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 bd(e,t,r,s=0){try{const a=`${e}
|
|
283
|
-
|
|
284
|
-
${t}${r?`
|
|
285
|
-
|
|
286
|
-
Respond with valid JSON only.`:""}`;let o="claude";try{const{stdout:c}=await Vi("which claude",{timeout:1e3});o=c.trim()}catch{const c=["/usr/local/bin/claude",`${process.env.HOME}/.nvm/versions/node/v20.16.0/bin/claude`,`${process.env.HOME}/.npm-global/bin/claude`];for(const p of c)try{await Vi(`test -x "${p}"`,{timeout:1e3}),o=p;break}catch{}}const{stdout:i,stderr:l}=await new Promise((c,p)=>{var y,x,w;const m=St(o,["-p",a,"--output-format","json","--max-turns","1"],{env:{...process.env}});(y=m.stdin)==null||y.end();let h="",f="";(x=m.stdout)==null||x.on("data",b=>{const v=b.toString();h+=v}),(w=m.stderr)==null||w.on("data",b=>{f+=b.toString()}),m.on("error",b=>{p(b)}),m.on("close",(b,v)=>{if(b===0)c({stdout:h,stderr:f});else{const N=new Error(`Command failed with exit code ${b}. stderr: ${f.substring(0,500)}`);N.code=b,N.stdout=h,N.stderr=f,p(N)}});const g=setTimeout(()=>{m.kill("SIGTERM"),setTimeout(()=>{m.killed||m.kill("SIGKILL")},5e3),p(new Error("Claude CLI command timed out after 60 seconds"))},6e4);m.on("close",()=>clearTimeout(g))});try{const c=JSON.parse(i);let p=c.result||c.response||c.text||c.content;if(!p)throw new Error("No response content from Claude CLI");const u=p.match(/^```(?:json)?\s*\n([\s\S]*?)\n```\s*$/);if(u&&(p=u[1]),r){const m=ax(p);if(m.valid)console.log("✅ Claude CLI: JSON validation passed");else{console.log(`⚠️ Claude CLI: Invalid JSON response (attempt ${s+1}/${Gi+1})`),console.log(`⚠️ Claude CLI: JSON error: ${m.error}`),console.log(`⚠️ Claude CLI: Response length: ${p.length} bytes`);const h=ox(p);if(console.log(`⚠️ Claude CLI: Appears truncated: ${h}`),h&&s<Gi){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:
|
|
287
|
-
|
|
288
|
-
\`\`\`json
|
|
289
|
-
${p}
|
|
290
|
-
\`\`\`
|
|
291
|
-
|
|
292
|
-
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 bd(e,f,r,s+1)}catch(g){console.log(`⚠️ Claude CLI: Recovery attempt failed: ${g}`)}}console.log(`⚠️ Claude CLI: Returning invalid JSON response after ${s+1} attempts`),console.log(`⚠️ Claude CLI: Downstream parsing will likely fail. First 500 chars: ${p.substring(0,500)}`)}}return p}catch(c){if(i.trim())return i.trim();throw new Error(`Failed to parse Claude CLI response: ${c}`)}}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 Gr=new vp({concurrency:100,timeout:1200*1e3,autoStart:!0}),Ki={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},Gt={};async function Va({type:e,systemMessage:t,prompt:r,jsonResponse:s=!0,jsonSchema:a,model:o=yd,attempts:i=0}){var k,_,S,j,$,T,R;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await ix(e,process.env.CODEYAM_LLM_FIXTURES_DIR,t);console.log(`CodeYam Debug: LLM Pool [queued=${Gr.size}, running=${Gr.pending}]`);const l=Date.now();let c,p=0;if(Xy()){console.log("Using Claude CLI mode for AI request");const I=await bd(t,r,s);return{finishReason:"stop",completion:I,stats:{model:"claude-sonnet-4-5",prompt_type:e,system_message:t,prompt_text:r,response:I,input_tokens:0,output_tokens:0,cost:0}}}const u=Gs(o),m=process.env[u.provider.apiKeyEnvVar];if(!m)throw new Error(`API key not found for provider ${u.provider.name}. Please set ${u.provider.apiKeyEnvVar} environment variable.`);console.log(`Using ${u.provider.name} for AI request`);const h=new wp({apiKey:m,baseURL:u.provider.baseURL}),f={type:e,messages:{system:t,prompt:r},model:o,responseType:a?"json_schema":s?"json_object":"text",jsonSchema:a},g=qy(f),y=await Gr.add(()=>(c=Date.now(),Ni(async()=>{const I=Date.now(),P=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],H=setInterval(()=>{const W=Math.floor((Date.now()-I)/1e3),F=Math.floor(W/10)%P.length;Ci(1,`${P[F]} [type=${e}, model=${o}, elapsed=${W}s]`)},1e4);try{return await h.chat.completions.create(g,{timeout:300*1e3})}finally{clearInterval(H)}},{...Ki,onFailedAttempt:I=>{p++,console.log(`CodeYam Error: Completion call failed [model=${o}]`,{error:I,prompt:r,systemMessage:t,attempts:i,retryCount:p})}})));if(!y)throw new Error("Completion call returned no result");const x=y,w=Date.now(),b=Ky({chatRequest:f,chatCompletion:x,model:o});if(!b)throw new Error("Failed to get LLM call stats");b.retries=p,b.wait_ms=c-l,b.duration_ms=w-l;const v=(k=x.choices)==null?void 0:k[0];let N=null;if(v){if(!v.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");N=(_=v.message)==null?void 0:_.content}let C=N;N&&(C=N.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const E=s?C&&(((S=C.match(/\{[\s\S]*\}/))==null?void 0:S[0])??C):C;if(!E){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:E,rawCompletion:N,chatCompletion:x,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:r,systemMessage:t,attempts:i}),await Va({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(E.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:N,prompt:r,systemMessage:t}),new Error("Empty completion");if(s)try{JSON.parse(E)}catch(I){if(console.log("CodeYam Error: Invalid JSON in completion",{error:I.message,model:o,completion:E.substring(0,500),rawCompletion:N==null?void 0:N.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:I.message});const P=`Your previous response contained invalid JSON with the following error:
|
|
293
|
-
|
|
294
|
-
${I.message}
|
|
295
|
-
|
|
296
|
-
Here was your previous response:
|
|
297
|
-
\`\`\`
|
|
298
|
-
${E}
|
|
299
|
-
\`\`\`
|
|
300
|
-
|
|
301
|
-
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,H=await Gr.add(()=>Ni(async()=>{const z=Date.now(),A=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],B=setInterval(()=>{const G=Math.floor((Date.now()-z)/1e3),q=Math.floor(G/10)%A.length;Ci(1,`${A[q]} [type=${e}, model=${o}, elapsed=${G}s]`)},1e4);try{return await h.chat.completions.create({...g,messages:[{role:"system",content:t},{role:"user",content:r},{role:"assistant",content:E},{role:"user",content:P}]},{timeout:300*1e3})}finally{clearInterval(B)}},{...Ki,onFailedAttempt:z=>{console.log("CodeYam Error: Correction call failed",{error:z,attempts:i})}}));if(!H)throw new Error("Correction call returned no result");const W=H,F=(T=($=(j=W.choices)==null?void 0:j[0])==null?void 0:$.message)==null?void 0:T.content;let J=F;F&&(J=F.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const Y=J&&(((R=J.match(/\{[\s\S]*\}/))==null?void 0:R[0])??J);if(!Y)throw new Error("Correction attempt returned empty completion");try{JSON.parse(Y),console.log("CodeYam: JSON correction successful");const z=Date.now();return b.duration_ms=z-l,{finishReason:W.choices[0].finish_reason,completion:Y,stats:b}}catch(z){return console.log("CodeYam Error: Corrected JSON still invalid",{error:z.message,correctedCompletion:Y.substring(0,500)}),await Va({type:e,systemMessage:t,prompt:r,jsonResponse:s,model:o,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${I.message}`)}return xd(`completionCall_${e}`,{completion:E,finishReason:x.choices[0].finish_reason}),{finishReason:x.choices[0].finish_reason,completion:E,stats:b}}async function ix(e,t,r){var o,i,l,c,p;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 u=s.readdirSync(t).filter(b=>b.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${t}`);const m={};for(const b of u)try{const v=s.readFileSync(a.join(t,b),"utf-8"),N=JSON.parse(v);m[N.prompt_type]||(m[N.prompt_type]=[]),m[N.prompt_type].push(N)}catch(v){console.warn(`Failed to parse LLM fixture file ${b}:`,v)}for(const b of Object.keys(m))m[b].sort((v,N)=>{const C=v.created_at??0,E=N.created_at??0;return C-E});const h=m[e];if(!h||h.length===0){const b=Object.keys(m).join(", ");return console.warn(`CodeYam Test: No captured LLM call found for type '${e}'. Available types: ${b}`),{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 b=r.match(/Scenario name must match exactly: "([^"]+)"/),v=b==null?void 0:b[1];if(v){const N={};for(const E of h)try{const _=((o=JSON.parse(E.props||"{}").scenario)==null?void 0:o.name)||"__NO_SCENARIO__";N[_]||(N[_]=[]),N[_].push(E)}catch{}const C=N[v];if(C&&C.length>0){const E=`${t}::${e}::${v}`;Gt[E]===void 0&&(Gt[E]=0);const k=Gt[E];Gt[E]=(k+1)%C.length,f=C[k],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${v}' [${k+1}/${C.length}]`)}else{const E=Object.keys(N).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${v}'. Available: [${E}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const b=`${t}::${e}`;Gt[b]===void 0&&(Gt[b]=0);const v=Gt[b];Gt[b]=(v+1)%h.length,f=h[v],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${v+1}/${h.length}]`)}let y;try{y=((c=(l=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:l.message)==null?void 0:c.content)||f.response}catch{y=f.response}let x=y;y&&(x=y.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const w=x&&(((p=x.match(/\{[\s\S]*\}/))==null?void 0:p[0])??x);return xd(`completionCall_${e}`,{completion:w||"",finishReason:"stop"}),{finishReason:"stop",completion:w||"",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(u){throw console.error("CodeYam Test Error: Failed to replay LLM call:",u),u}}function qi(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function lx(e){const{propsJson:t,...r}=e,s=JSON.stringify(t,null,2),a=ao(),o=Date.now(),i={...r,id:a,created_at:o,props:s};let l;const c=`${i.object_id}_${a}.json`;if(process.env.DYNAMODB_PATH?l=L.join(process.env.DYNAMODB_PATH,c):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(l=L.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",c)),l)try{const u=L.dirname(l);return await Ae.mkdir(u,{recursive:!0}),await Ae.writeFile(l,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${l}`),{id:a}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const p=qi();if(!p)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,m]of Object.entries(i))typeof m>"u"&&console.log(`CodeYam Warning: LLM call ${a} property ${u} with explicit value 'undefined'`);try{return await new ks().send(new Np({TableName:qi(),Item:Cp(i,{removeUndefinedValues:!0})})),{id:a}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${p}`,u),{id:"-1"}}}new ks({});new ks({});new ks({});const cx=3,dx=2,Jo=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,t)=>16+cx*String(t).length*(1+dx)});new uo(Jo());new uo(Jo());new uo(Jo());class ux{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 px{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 mx{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 hx{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 fx{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 gx{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 yx{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 xx{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown");const a=t.withReturnValues();s.addType(a,"unknown")}isComplete(){return!0}}class bx{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 wx{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 vx{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 Nx{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 Sx{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 Cx{getReturnType(){return"unknown"}addEquivalences(t,r,s){s.addType(r,"unknown"),s.addEquivalence(t.withReturnValues(),r.withElement("*"))}isComplete(){return!0}}class _x{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 kx{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 Ex{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 Ax{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 Px{getReturnType(){return"unknown"}addEquivalences(t,r,s){t.getLastFunctionCallSegment()}isComplete(){return!0}}class jx{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}}function Tx(){const e=new ux;return e.register("filter",new px,"Array"),e.register("map",new Nx,"Array"),e.register("flatMap",new Sx,"Array"),e.register("join",new vx,"Array"),e.register("find",new fx,"Array"),e.register("findLast",new _x,"Array"),e.register("at",new Cx,"Array"),e.register("reduce",new gx,"Array"),e.register("concat",new yx,"Array"),e.register("slice",new xx,"Array"),e.register("splice",new bx,"Array"),e.register("push",new wx,"Array"),e.register("some",new mx,"Array"),e.register("every",new hx,"Array"),e.register("fromEntries",new kx,"Object"),e.register("split",new Ex,"String"),e.register("then",new Ax,"Promise"),e.register("useState",new jx,"React"),e.register("useMemo",new Px,"React"),e}Tx();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 Mx=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),$x=new Set(["find","findLast","at","pop","shift"]),Ix=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),Rx=new Set([...Mx,...$x,...Ix]),Dx=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Ox=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Fx=new Set([...Dx,...Ox]);[...Rx,...Fx];class Lx{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 Lx({enabled:!1});function ln(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 zx(e){return Object.keys(e.added).length>0||Object.keys(e.removed).length>0||Object.keys(e.changed).length>0}function Kr(e){return Object.keys(e.added).length+Object.keys(e.removed).length+Object.keys(e.changed).length}let Bx=0;class Ho{constructor(t){this.traces=new Map,this.currentEntity=null,this.currentStage=null,this.tracerId=++Bx,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 c,p,u,m;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:ln(l.data.signatureSchema,o.signatureSchema),returnValueSchema:ln(l.data.returnValueSchema,o.returnValueSchema)},o.dependencySchemas||l.data.dependencySchemas)){i.diffFromPrevious.dependencySchemas={};const h=new Set([...Object.keys(o.dependencySchemas??{}),...Object.keys(l.data.dependencySchemas??{})]);for(const f of h){const g=(c=l.data.dependencySchemas)==null?void 0:c[f],y=(p=o.dependencySchemas)==null?void 0:p[f];for(const x of new Set([...Object.keys(g??{}),...Object.keys(y??{})])){const w=`${f}::${x}`,b=(u=g==null?void 0:g[x])==null?void 0:u.returnValueSchema,v=(m=y==null?void 0:y[x])==null?void 0:m.returnValueSchema,N=ln(b,v);zx(N)&&(i.diffFromPrevious.dependencySchemas[w]=N)}}}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 c of i.stages){if(!c.diffFromPrevious)continue;const u=`${((a=i.stages[i.stages.indexOf(c)-1])==null?void 0:a.stage)??"start"}→${c.stage}`;if(t[u]||(t[u]={added:0,removed:0,changed:0}),c.diffFromPrevious.signatureSchema){const m=c.diffFromPrevious.signatureSchema;t[u].added+=Object.keys(m.added).length,t[u].removed+=Object.keys(m.removed).length,t[u].changed+=Object.keys(m.changed).length,l+=Kr(m)}if(c.diffFromPrevious.returnValueSchema){const m=c.diffFromPrevious.returnValueSchema;t[u].added+=Object.keys(m.added).length,t[u].removed+=Object.keys(m.removed).length,t[u].changed+=Object.keys(m.changed).length,l+=Kr(m)}}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(p=>`${p}(${this.traces.get(p).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=L.dirname(this.outputPath);K.existsSync(l)||K.mkdirSync(l,{recursive:!0});const c=K.openSync(this.outputPath,"w");try{K.writeSync(c,`{
|
|
302
|
-
"meta": `),K.writeSync(c,JSON.stringify(o,null,2)),K.writeSync(c,`,
|
|
303
|
-
"summary": `),K.writeSync(c,JSON.stringify(i,null,2)),K.writeSync(c,`,
|
|
304
|
-
"entities": {`);let p=!0;for(const[u,m]of this.traces)p||K.writeSync(c,","),K.writeSync(c,`
|
|
305
|
-
${JSON.stringify(u)}: `),K.writeSync(c,JSON.stringify(m,null,2)),p=!1;K.writeSync(c,`
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
`),this.log(`flush: wrote trace to ${this.outputPath}`)}finally{K.closeSync(c)}}clear(){this.traces.clear(),this.currentEntity=null,this.currentStage=null}static loadTrace(t){const r=K.readFileSync(t,"utf-8"),s=JSON.parse(r),a=new Ho({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,c]of this.traces){let p=0;for(let u=1;u<c.stages.length;u++){const m=c.stages[u],f=`${((a=c.stages[u-1])==null?void 0:a.stage)??"start"}→${m.stage}`;if(t[f]||(t[f]={added:0,removed:0,changed:0}),(o=m.diffFromPrevious)!=null&&o.signatureSchema){const g=m.diffFromPrevious.signatureSchema;t[f].added+=Object.keys(g.added).length,t[f].removed+=Object.keys(g.removed).length,t[f].changed+=Object.keys(g.changed).length,p+=Kr(g)}if((i=m.diffFromPrevious)!=null&&i.returnValueSchema){const g=m.diffFromPrevious.returnValueSchema;t[f].added+=Object.keys(g.added).length,t[f].removed+=Object.keys(g.removed).length,t[f].changed+=Object.keys(g.changed).length,p+=Kr(g)}}r.set(l,p)}const s=[...r.entries()].sort((l,c)=>c[1]-l[1]).slice(0,10).map(([l,c])=>({name:l,totalChanges:c}));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 c=(o=l.data.signatureSchema)==null?void 0:o[r],p=(i=l.data.returnValueSchema)==null?void 0:i[r],u=c??p;u!==void 0&&a.push({stage:l.stage,value:u})}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,c]of Object.entries(i.data.signatureSchema??{}))o.test(l)&&a.push({stage:i.stage,path:l,type:c,schemaType:"signature"});for(const[l,c]of Object.entries(i.data.returnValueSchema??{}))o.test(l)&&a.push({stage:i.stage,path:l,type:c,schemaType:"returnValue"});for(const[l,c]of Object.entries(i.data.dependencySchemas??{}))for(const[p,u]of Object.entries(c))for(const[m,h]of Object.entries(u.returnValueSchema??{}))o.test(m)&&a.push({stage:i.stage,path:`${l}/${p}::${m}`,type:h,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 c=r.stages.length-1;c>=0;c--)if(Object.keys(r.stages[c].data.dependencySchemas??{}).length>0){s=r.stages[c];break}if(!s)return[];const a=new Set(["length","toString","valueOf","constructor"]),o=new Map,i=(c,p)=>{const u=c.match(/\.([a-zA-Z_][a-zA-Z0-9_]*)(\[\])?$/);if(!u)return;const m=u[1],h=u[2]==="[]";if(a.has(m))return;const f=m+(h?"[]":"");o.has(f)||o.set(f,[]),o.get(f).push({path:c,type:p})};for(const[,c]of Object.entries(s.data.dependencySchemas??{}))for(const[,p]of Object.entries(c))for(const[u,m]of Object.entries(p.returnValueSchema??{}))i(u,m);const l=[];for(const[c,p]of o)new Set(p.map(m=>m.type.replace(/ \| undefined/g,"").replace(/ \| null/g,""))).size>1&&l.push({propertyName:c,paths:p.map(m=>({...m,stage:s.stage}))});return l.sort((c,p)=>{const u=new Set(c.paths.map(h=>h.type)).size;return new Set(p.paths.map(h=>h.type)).size-u}),l}getStageDiffSummary(t,r,s){const a=this.traces.get(t);if(!a)return null;const o=a.stages.find(h=>h.stage===r),i=a.stages.find(h=>h.stage===s);if(!o||!i)return null;const l={added:[],removed:[],typeChanged:[]},c=o.data.returnValueSchema??{},p=i.data.returnValueSchema??{},u=new Set(Object.keys(c)),m=new Set(Object.keys(p));for(const h of m)u.has(h)?c[h]!==p[h]&&l.typeChanged.push({path:h,from:c[h],to:p[h]}):l.added.push(`${h}: ${p[h]}`);for(const h of u)m.has(h)||l.removed.push(`${h}: ${c[h]}`);return l}traceSchemaTransform(t,r,s,a,o){if(!this.enabled)return a(s),s;const i={...s};a(s);const l=ln(i,s);for(const[c,p]of Object.entries(l.added))this.operation(t,{operation:r,path:c,before:void 0,after:p,context:{...o,changeType:"added"}});for(const[c,p]of Object.entries(l.removed))this.operation(t,{operation:r,path:c,before:p,after:void 0,context:{...o,changeType:"removed"}});for(const[c,{from:p,to:u}]of Object.entries(l.changed))this.operation(t,{operation:r,path:c,before:p,after:u,context:{...o,changeType:"changed"}});return s}traceSchemaTransformResult(t,r,s,a,o){if(!this.enabled)return;const i=ln(s,a);for(const[l,c]of Object.entries(i.added))this.operation(t,{operation:r,path:l,before:void 0,after:c,context:{...o,changeType:"added"}});for(const[l,c]of Object.entries(i.removed))this.operation(t,{operation:r,path:l,before:c,after:void 0,context:{...o,changeType:"removed"}});for(const[l,{from:c,to:p}]of Object.entries(i.changed))this.operation(t,{operation:r,path:l,before:c,after:p,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 c=s[i][l];(o==="signature"||o==="both")&&c.signatureSchema&&a(c.signatureSchema),(o==="returnValue"||o==="both")&&c.returnValueSchema&&a(c.returnValueSchema)}return}for(const i in s)for(const l in s[i]){const c=s[i][l],p={filePath:i,dependencyName:l};(o==="signature"||o==="both")&&c.signatureSchema&&this.traceSchemaTransform(t,r,c.signatureSchema,a,{...p,schemaType:"signature"}),(o==="returnValue"||o==="both")&&c.returnValueSchema&&this.traceSchemaTransform(t,r,c.returnValueSchema,a,{...p,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 c in s[l]){const p=s[l][c];o[l][c]={sig:{...p.signatureSchema||{}},rv:{...p.returnValueSchema||{}}}}}a();for(const l in s)for(const c in s[l]){const p=s[l][c],u=(i=o[l])==null?void 0:i[c],m={filePath:l,dependencyName:c};if(p.signatureSchema){const h=(u==null?void 0:u.sig)||{},f=ln(h,p.signatureSchema);for(const[g,y]of Object.entries(f.added))this.operation(t,{operation:r,path:g,before:void 0,after:y,context:{...m,schemaType:"signature",changeType:"added"}});for(const[g,{from:y,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:g,before:y,after:x,context:{...m,schemaType:"signature",changeType:"changed"}})}if(p.returnValueSchema){const h=(u==null?void 0:u.rv)||{},f=ln(h,p.returnValueSchema);for(const[g,y]of Object.entries(f.added))this.operation(t,{operation:r,path:g,before:void 0,after:y,context:{...m,schemaType:"returnValue",changeType:"added"}});for(const[g,{from:y,to:x}]of Object.entries(f.changed))this.operation(t,{operation:r,path:g,before:y,after:x,context:{...m,schemaType:"returnValue",changeType:"changed"}})}}}}function Yx(){const e=process.env.CODEYAM_TRACE_TRANSFORMS;return e==="1"||e==="true"}const Qi=new Ho({enabled:Yx(),outputPath:"/tmp/codeyam/transform-trace.json"});process.on("beforeExit",()=>{Qi.isEnabled()&&Qi.flush()});function wd(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 Sp.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),wd(e)}return null}}function Ux({description:e,existingScenarios:t,scenariosDataStructure:r,flowSelections:s}){let a="";return s&&s.length>0&&(a=`
|
|
309
|
-
User-selected Execution Flow Values:
|
|
310
|
-
The user has specifically requested these values be used in the scenario:
|
|
311
|
-
${s.map(o=>` - ${o.path}: ${o.value}${o.isCustom?" (custom value)":""}`).join(`
|
|
312
|
-
`)}
|
|
313
|
-
|
|
314
|
-
IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
|
|
315
|
-
`),`Mock Scenario Data Structure:
|
|
316
|
-
\`\`\`
|
|
317
|
-
${JSON.stringify(r,null,2)}
|
|
318
|
-
\`\`\`
|
|
319
|
-
Existing Mock Scenario Data:
|
|
320
|
-
\`\`\`
|
|
321
|
-
${JSON.stringify(t,null,2)}
|
|
322
|
-
\`\`\`
|
|
323
|
-
${a}
|
|
324
|
-
New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
|
|
325
|
-
`}function Wx({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}){const o=s.find(i=>i.name===Ps);return`Mock Scenario Data Structure:
|
|
326
|
-
\`\`\`
|
|
327
|
-
${JSON.stringify({props:a.arguments,dataVariables:a.dataForMocks},null,2)}
|
|
328
|
-
\`\`\`
|
|
329
|
-
|
|
330
|
-
Existing Mock Scenario Data:
|
|
331
|
-
\`\`\`
|
|
332
|
-
${JSON.stringify(s.map(i=>({name:i.name,data:ur(o.metadata.data,i.metadata.data)})),null,2)}
|
|
333
|
-
\`\`\`
|
|
334
|
-
|
|
335
|
-
Mock Scenario that should be edited: "${t}"
|
|
336
|
-
${r?`The portion of the data that should be edited:
|
|
337
|
-
\`\`\`
|
|
338
|
-
${JSON.stringify(r,null,2)}
|
|
339
|
-
\`\`\``:""}
|
|
340
|
-
|
|
341
|
-
How this data should be changed: "${e}"
|
|
342
|
-
`}async function Jx({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,flowSelections:o,model:i}){const l=t?Wx({description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a}):Ux({description:e,existingScenarios:s,scenariosDataStructure:a,flowSelections:o}),c=await Va({type:"guessScenarioDataFromDescription",systemMessage:t?Vx(r):Hx,prompt:l,model:i??Uy});await lx({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:t,editingMockData:r,existingScenarios:s,scenariosDataStructure:a,model:i},...c.stats});const{completion:p}=c;return p?wd(p):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const Hx=`
|
|
343
|
-
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.
|
|
344
|
-
|
|
345
|
-
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.
|
|
346
|
-
|
|
347
|
-
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.
|
|
348
|
-
|
|
349
|
-
You must respond with valid JSON following this format of this TS type definition:
|
|
350
|
-
\`\`\`
|
|
351
|
-
export type ScenarioData = {
|
|
352
|
-
name: string;
|
|
353
|
-
description: string;
|
|
354
|
-
data: {
|
|
355
|
-
mockData: { [key: string]: unknown };
|
|
356
|
-
argumentsData: { [key: string]: unknown };
|
|
357
|
-
};
|
|
358
|
-
};
|
|
359
|
-
|
|
360
|
-
\`\`\`
|
|
361
|
-
`,Vx=e=>`
|
|
362
|
-
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.
|
|
363
|
-
|
|
364
|
-
Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
|
|
365
|
-
${e?`
|
|
366
|
-
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.`:""}
|
|
367
|
-
|
|
368
|
-
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.
|
|
369
|
-
|
|
370
|
-
You must respond with valid JSON following this type definition:
|
|
371
|
-
\`\`\`
|
|
372
|
-
{
|
|
373
|
-
data: {
|
|
374
|
-
mockData: { [key: string]: unknown };
|
|
375
|
-
argumentsData: { [key: string]: unknown };
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
\`\`\`
|
|
379
|
-
`;async function Gx({request:e}){if(e.method!=="POST")return X({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 X({error:"Missing required field: description or flowSelections"},{status:400});const c=await Jx({description:r||"",existingScenarios:s??[],scenariosDataStructure:a,editingMockName:o,editingMockData:i,flowSelections:l}),p=(c==null?void 0:c.data)||c;return X({success:!0,data:p})}catch(t){return console.error("[Generate Scenario Data API] Error:",t),X({error:"Failed to generate scenario data",details:t instanceof Error?t.message:String(t)},{status:500})}}const Kx=Object.freeze(Object.defineProperty({__proto__:null,action:Gx},Symbol.toStringTag,{value:"Module"}));function qx(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(m=>m.date>=o),l=new Set(i.map(m=>m.commitSha).filter(Boolean)),c=new Map;for(const m of i)if(m.scenarioScreenshots)for(const h of m.scenarioScreenshots){c.has(h.name)||c.set(h.name,[]);const f=c.get(h.name);f.some(g=>g.path===h.path)||f.push({path:h.path,time:m.time})}for(const m of c.values())m.sort((h,f)=>h.time.localeCompare(f.time));const p=[],u=new Map;for(const[m,h]of c){const f=m.indexOf(" - ");if(f!==-1){const g=m.slice(0,f);u.has(g)||u.set(g,[]),u.get(g).push({name:m,screenshots:h})}else p.push({name:m,screenshots:h})}return{commitCount:l.size,entryCount:i.length,appScenarios:p,componentGroups:u,totalScenarios:c.size}}function Qx(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 Zx(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 Xx(e,t){const r=e.replace(/[^a-zA-Z0-9_\-]/g,"_");return`${t.toISOString().replace(/:/g,"-").replace(/\.\d+Z$/,"")}_${r}.png`}function eb(e){const{title:t,timeStr:r,type:s,description:a,allScenarioNames:o,screenshot:i,scenarioScreenshots:l,commitSha:c,commitMessage:p,featureName:u,userPrompt:m}=e,h=["","---","",`### ${t}`,`**Time:** ${r}`,`**Type:** ${s}`];if(u&&h.push(`**Feature:** ${u}`),m&&h.push(`**Prompt:** ${m}`),o.length>0&&h.push(`**Scenarios:** ${o.join(", ")}`),h.push(""),h.push(a),i&&(h.push(""),h.push(``)),l.length>0){h.push(""),h.push("**Scenario Screenshots:**");for(const f of l)h.push(""),h.push(``)}return c&&p&&(h.push(""),h.push(`**Commit:** \`${c}\` — ${p}`)),h.push(""),h.join(`
|
|
380
|
-
`)}function tb(e,t){return e.findIndex(r=>r.time===t)}function nb(e){return!!e.commitSha}function rb(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 sb(e,t,r,s){const a=`
|
|
381
|
-
**Commit:** \`${r}\` — ${s||"no message"}
|
|
382
|
-
`,o=`### ${t}`,i=e.lastIndexOf(o);if(i===-1)return null;const l=e.indexOf(`
|
|
383
|
-
---
|
|
384
|
-
`,i+1),c=l!==-1?l:e.length;return e.slice(0,c)+a+e.slice(c)}async function ab(e){console.log(`[editorScenarioLookup] Looking up screenshots for ${e.length} scenarios: ${e.join(", ")}`);try{const t=await Fe();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up scenarios"),[];const{project:r}=await Re(t),a=await Te().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(c=>({name:c.name,screenshot_path:c.screenshot_path,id:c.id})));const o=a.filter(c=>!c.screenshot_path);o.length>0&&console.warn(`[editorScenarioLookup] ${o.length} scenarios have no screenshot_path:`,o.map(c=>c.name));const i=a.filter(c=>c.screenshot_path),l=vt(i,c=>c.name).map(c=>({name:c.name,screenshotPath:c.screenshot_path,scenarioId:c.id,componentName:c.component_name||null,pageFilePath:c.page_file_path||null,url:c.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 ob(e){console.log(`[editorScenarioLookup] Looking up screenshots by entity names: ${e.join(", ")}`);try{const t=await Fe();if(!t)return[];const{project:r}=await Re(t),a=await Te().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(p=>{const u=nn({componentName:p.component_name,pageFilePath:p.page_file_path,url:p.url});return o.has(u)}).filter(p=>p.screenshot_path),c=vt(l,p=>p.name).map(p=>({name:p.name,screenshotPath:p.screenshot_path,scenarioId:p.id,componentName:p.component_name||null,pageFilePath:p.page_file_path||null,url:p.url||null}));return console.log(`[editorScenarioLookup] Found ${c.length} scenarios for ${e.length} entities`),c}catch(t){return console.error("[editorScenarioLookup] Failed to look up entity screenshots:",t),[]}}async function vd(e){console.log("[editorScenarioLookup] Looking up session scenario screenshots",e?`(after ${e})`:"(all session)");try{const t=await Fe();if(!t)return console.warn("[editorScenarioLookup] No project slug found — cannot look up session scenarios"),[];const{project:r}=await Re(t),s=Te(),a=Ne()||process.cwd();let o=null;const i=L.join(a,".codeyam","editor-step.json");try{const h=K.readFileSync(i,"utf8");o=JSON.parse(h).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,c=Ar(l),p=await s.selectFrom("editor_scenarios").select(["name","screenshot_path","id","component_name","page_file_path","url"]).where("project_id","=",r.id).where("created_at",">=",c).orderBy("created_at","asc").execute();console.log(`[editorScenarioLookup] Query returned ${p.length} scenarios since ${l}`);const u=p.filter(h=>h.screenshot_path),m=vt(u,h=>h.name).map(h=>({name:h.name,screenshotPath:h.screenshot_path,scenarioId:h.id,componentName:h.component_name||null,pageFilePath:h.page_file_path||null,url:h.url||null}));return console.log(`[editorScenarioLookup] Found ${m.length} session scenarios with screenshots`),m}catch(t){return console.error("[editorScenarioLookup] Failed to look up session scenario screenshots:",t),[]}}async function Ga(e,t,r){const s=L.join(t,".codeyam","journal","screenshots");await Ae.mkdir(s,{recursive:!0});const a=[];for(const o of e){const i=L.join(t,".codeyam","editor-scenarios",o.screenshotPath),l=Xx(o.name,r),c=L.join(s,l);console.log(`[editorScenarioLookup] Copying scenario screenshot: "${o.name}" from ${i} → ${c}`);try{await Ae.access(i),await Ae.copyFile(i,c),a.push({name:o.name,path:`screenshots/${l}`,componentName:o.componentName,url:o.url}),console.log(`[editorScenarioLookup] Successfully copied screenshot for "${o.name}"`)}catch(p){console.warn(`[editorScenarioLookup] Scenario screenshot not found: ${i}`,p instanceof Error?p.message:p)}}return console.log(`[editorScenarioLookup] Scenario screenshot summary: ${a.length} scenarios have screenshots embedded`),a}async function ib({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(),c=L.join(l,".codeyam","journal"),p=L.join(c,"index.json");console.log(`[editor-journal-update] Updating entry with time="${r}"`);let u={entries:[]};try{const y=await Ae.readFile(p,"utf8");u=JSON.parse(y)}catch{return new Response(JSON.stringify({error:"No journal index found"}),{status:404,headers:{"Content-Type":"application/json"}})}const m=tb(u.entries,r);if(m===-1)return new Response(JSON.stringify({error:`No journal entry found with time "${r}"`}),{status:404,headers:{"Content-Type":"application/json"}});const h=u.entries[m];if(nb(h))return console.log(`[editor-journal-update] Rejected: entry "${h.title}" already committed (${h.commitSha}). Create a new entry instead.`),new Response(JSON.stringify({error:`Journal entry already committed (${h.commitSha}). Create a new entry via POST /api/editor-journal-entry instead of updating.`}),{status:409,headers:{"Content-Type":"application/json"}});let f,g;if(i){const y=await vd();y.length>0&&(f=y.map(x=>x.name),g=await Ga(y,l,new Date))}if(rb(h,{commitSha:s,commitMessage:a,description:o,scenarios:f,scenarioScreenshots:g}),u.entries[m]=h,await Ae.writeFile(p,JSON.stringify(u,null,2),"utf8"),console.log("[editor-journal-update] Updated index.json"),s)try{const y=h.date,x=L.join(c,`${y}.md`);let w="";try{w=await Ae.readFile(x,"utf8")}catch{}if(w){const b=sb(w,h.title,s,a||null);b&&(await Ae.writeFile(x,b,"utf8"),console.log(`[editor-journal-update] Appended commit line to ${x}`))}}catch(y){console.warn("[editor-journal-update] Failed to update markdown:",y)}return bt.notifyChange("journal"),console.log(`[editor-journal-update] Done: updated entry "${h.title}"`),new Response(JSON.stringify({success:!0,entry:h}),{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 lb=Object.freeze(Object.defineProperty({__proto__:null,action:ib},Symbol.toStringTag,{value:"Module"}));async function cb({request:e}){var t;try{const r=process.env.CODEYAM_ROOT_PATH||process.cwd(),s=await rd(r);let a=0;const o={};for(const[c,p]of Object.entries(s))p.errors.length>0&&(o[c]=p,a+=p.errors.length);const i=x0(),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 db=Object.freeze(Object.defineProperty({__proto__:null,loader:cb},Symbol.toStringTag,{value:"Module"}));async function ub({request:e}){try{const r=(await wn()||[]).filter(i=>i.analyses&&i.analyses.length>0).map(i=>{var g;const l=i.analyses[0],c=l.scenarios||[],p=!((g=l.status)!=null&&g.finishedAt),u=i.entityType||"visual",h=u==="library"||u==="functionCall"?c.some(y=>{var x;return!!((x=y.metadata)!=null&&x.executionResult)}):c.some(y=>{var x,w,b,v;return((w=(x=y.metadata)==null?void 0:x.screenshotPaths)==null?void 0:w[0])&&!((b=y.metadata)!=null&&b.noScreenshotSaved)&&!((v=y.metadata)!=null&&v.sameAsDefault)}),f=c.length;return{name:i.name,entityType:u,filePath:i.filePath||"",hasScreenshot:h,isAnalyzing:p,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 pb=Object.freeze(Object.defineProperty({__proto__:null,loader:ub},Symbol.toStringTag,{value:"Module"}));async function mb({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:c,commitMessage:p}=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 u=process.env.CODEYAM_ROOT_PATH||process.cwd(),m=L.join(u,".codeyam","journal");await Ae.mkdir(m,{recursive:!0});const h=new Date,f=h.toISOString().split("T")[0],g=h.toISOString();let y=o||[];const x=L.join(m,"index.json");let w={entries:[]};try{const P=await Ae.readFile(x,"utf8");w=JSON.parse(P)}catch{}let b;i&&w.entries.length>0&&(b=w.entries[w.entries.length-1].time);const v=i?await vd(b):o&&o.length>0?await ab(o):[];i&&v.length>0&&(y=v.map(P=>P.name));const N=await Ga(v,u,h);let C;try{const P=Ne()||process.cwd(),H=await Fe();if(H){const{project:W}=await Re(H),J=await Te().selectFrom("editor_scenarios").select(["name","component_name","component_path","page_file_path","url","display_name"]).where("project_id","=",W.id).orderBy("created_at","asc").execute(),z=vt(J,B=>`${B.name}::${B.url||"/"}`).map(B=>({componentName:B.component_name||null,componentPath:B.component_path||null,pageFilePath:B.page_file_path??null,url:B.url??null,displayName:B.display_name??null})),A=await Gn({projectRoot:P,scenarioInputs:z});Object.keys(A.entityChangeStatus).length>0&&(C=A.entityChangeStatus)}}catch{}if(C&&Object.keys(C).length>0){const P=new Set(v.map(W=>W.name)),H=Object.entries(C).filter(([,W])=>W.status==="impacted").map(([W])=>W);if(H.length>0){const W=[],F=new Set(v.map(J=>nn(J)));for(const J of H)F.has(J)||W.push(J);if(W.length>0)try{const J=await ob(W);if(J.length>0){const Y=await Ga(J.filter(z=>!P.has(z.name)),u,h);N.push(...Y),y.push(...Y.map(z=>z.name))}}catch{}}}let E=N,k=y;if(!i&&C&&Object.keys(C).length>0){E=cg(N,C);const P=new Set(E.map(H=>H.name));k=y.filter(H=>P.has(H))}const _=Yo(u),S=Uo(u);let j;try{const P=Vn();P.length>0&&(j=P.filter(H=>H.status!=="deleted").map(H=>({path:H.path,status:H.status})))}catch{}const $=L.join(m,`${f}.md`);let T="";try{T=await Ae.readFile($,"utf8")}catch{T=`# Development Journal — ${f}
|
|
385
|
-
`}const R=eb({title:r,timeStr:g,type:s,description:a,allScenarioNames:k,screenshot:l||null,scenarioScreenshots:E,commitSha:c||null,commitMessage:p||null,featureName:_,userPrompt:S});await Ae.writeFile($,T+R,"utf8"),console.log(`[editor-journal-entry] Written daily markdown: ${$}`);const I={date:f,time:g,title:r,type:s,description:a,scenarios:k,screenshot:l||null,scenarioScreenshots:E,commitSha:c||null,commitMessage:p||null,entityChangeStatus:C,featureName:_,userPrompt:S,modifiedFiles:j};w.entries.push(I),await Ae.writeFile(x,JSON.stringify(w,null,2),"utf8"),console.log(`[editor-journal-entry] Updated index.json (now ${w.entries.length} entries)`);try{await Ae.unlink(L.join(u,"editor-user-prompt.txt"))}catch{}return bt.notifyChange("journal"),console.log(`[editor-journal-entry] Done: title="${r}", scenarioScreenshotsEmbedded=${E.length}`),new Response(JSON.stringify({success:!0,entry:I,scenarioScreenshotsFound:E.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 hb=Object.freeze(Object.defineProperty({__proto__:null,action:mb},Symbol.toStringTag,{value:"Module"}));function fb({request:e}){const t={"Content-Type":"application/json","Access-Control-Allow-Origin":"*"};try{const r=Ne()||process.cwd();let o=new URL(e.url).searchParams.get("scenarioId");if(!o){const c=L.join(r,".codeyam","active-scenario.json");if(!K.existsSync(c))return new Response(JSON.stringify({}),{headers:t});o=JSON.parse(K.readFileSync(c,"utf-8")).scenarioId||null}if(!o)return new Response(JSON.stringify({}),{headers:t});const i=L.join(r,".codeyam","editor-scenarios",`${o}.json`);if(!K.existsSync(i))return new Response(JSON.stringify({}),{headers:t});const l=K.readFileSync(i,"utf-8");return new Response(l,{headers:t})}catch{return new Response(JSON.stringify({}),{headers:t})}}const gb=Object.freeze(Object.defineProperty({__proto__:null,loader:fb},Symbol.toStringTag,{value:"Module"}));async function yb(e,t){const r=Ne();if(!r)return{entityCalls:[],analysisCalls:[]};const s=L.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(w=>w.endsWith(".json")),c=`${e}_`,p=t?`${t}_`:null,u=[],m=[];for(const w of l)w.startsWith(c)||p&&w.startsWith(p)?u.push(w):m.push(w);const h=u.map(async w=>{try{const b=L.join(s,w),v=await Ae.readFile(b,"utf-8");return JSON.parse(v)}catch{return null}}),f=m.map(async w=>{try{const b=L.join(s,w),v=await Ae.readFile(b,"utf-8"),N=JSON.parse(v);return N.object_id===e||t&&N.object_id===t?N:null}catch{return null}}),[g,y]=await Promise.all([Promise.all(h),Promise.all(f)]),x=[...g,...y].filter(w=>w!==null);for(const w of x)w.object_id===e?a.push(w):t&&w.object_id===t&&o.push(w);a.sort((w,b)=>b.created_at-w.created_at),o.sort((w,b)=>b.created_at-w.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:a,analysisCalls:o}}async function xb({params:e,request:t}){const{entitySha:r}=e;if(!r)return X({error:"Entity SHA is required"},{status:400});const a=new URL(t.url).searchParams.get("analysisId")||void 0,o=await yb(r,a);return X(o)}const bb=Object.freeze(Object.defineProperty({__proto__:null,loader:xb},Symbol.toStringTag,{value:"Module"}));function wb(){try{const e=Ne()||process.cwd(),t=ee.join(e,".codeyam","config.json");if(!ue.existsSync(t))return Response.json({projectTitle:null,projectDescription:null,defaultScreenSize:null,screenSizes:null});const r=JSON.parse(ue.readFileSync(t,"utf8"));return Response.json({projectTitle:r.projectTitle||null,projectDescription:r.projectDescription||null,defaultScreenSize:r.defaultScreenSize||null,screenSizes:r.screenSizes||null})}catch{return Response.json({projectTitle:null,projectDescription:null,defaultScreenSize:null,screenSizes:null})}}async function vb({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ne()||process.cwd(),r=ee.join(t,".codeyam","config.json");if(!ue.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(ue.readFileSync(r,"utf8"));return 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),ue.writeFileSync(r,JSON.stringify(a,null,2)),s.defaultScreenSize&&!s.skipBroadcast&&Lo(s.defaultScreenSize),bt.notifyChange("unknown"),new Response(JSON.stringify({success:!0,projectTitle:a.projectTitle||null,projectDescription:a.projectDescription||null,defaultScreenSize:a.defaultScreenSize||null,screenSizes:a.screenSizes||null}),{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 Nb=Object.freeze(Object.defineProperty({__proto__:null,action:vb,loader:wb},Symbol.toStringTag,{value:"Module"}));function Sb(e){try{const t=L.join(e,"package.json"),r=JSON.parse(K.readFileSync(t,"utf8")),s={...r.dependencies,...r.devDependencies};return s.vitest?"vitest":s.jest?"jest":null}catch{return null}}function Cb(e,t){var i;const s=JSON.parse(t).testResults||[],a=[];for(const l of s)for(const c of l.assertionResults||[]){const p=c.ancestorTitles||[],u=c.title||c.fullName||"unknown",m=p.length>0?`${p.join(" > ")} > ${u}`:u;a.push({title:u,fullName:m,status:c.status==="passed"?"passed":c.status==="failed"?"failed":"skipped",duration:c.duration,failureMessages:(i=c.failureMessages)!=null&&i.length?c.failureMessages:void 0})}const o=a.some(l=>l.status==="failed");return{testFilePath:e,status:o?"failed":"passed",testCases:a}}async function Nd(e,t){const r=Sb(e);if(!r)return{testFilePath:t,status:"error",testCases:[],errorMessage:"No test runner found (install vitest or jest)"};const s=L.isAbsolute(t)?t:L.join(e,t);if(!K.existsSync(s))return{testFilePath:t,status:"error",testCases:[],errorMessage:"Test file not found"};const a=L.join(so.tmpdir(),`codeyam-test-result-${Date.now()}.json`);return new Promise(o=>{var m;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 c=St(l,i,{cwd:e,stdio:"pipe",env:{...process.env,NODE_ENV:"test"}});let p="";(m=c.stderr)==null||m.on("data",h=>{p+=h.toString()});const u=setTimeout(()=>{c.kill("SIGTERM"),o({testFilePath:t,status:"error",testCases:[],errorMessage:"Test timed out after 30 seconds"})},3e4);c.on("close",()=>{clearTimeout(u);try{const h=K.readFileSync(a,"utf8");K.unlinkSync(a),o(Cb(t,h))}catch{o({testFilePath:t,status:"error",testCases:[],errorMessage:p.trim().slice(0,500)||"Test runner failed to produce output"})}}),c.on("error",h=>{clearTimeout(u),o({testFilePath:t,status:"error",testCases:[],errorMessage:`Failed to spawn test runner: ${h.message}`})})})}async function _b({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=Ne()||process.cwd();try{const a=await Nd(s,r);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 kb=Object.freeze(Object.defineProperty({__proto__:null,loader:_b},Symbol.toStringTag,{value:"Module"}));function Zi(e,t){var r,s;try{return((s=(r=$e(`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 Eb(e,t,r,s){const a=Bn.createHash("sha256");return a.update(`${e}:${t}:${r}:${s}`),a.digest("hex").substring(0,16)}function Sd(){const e=Ne();if(!e)throw new Error("No project root found");const t=ee.join(e,".codeyam","cache","branch-entity-diff");return ue.existsSync(t)||ue.mkdirSync(t,{recursive:!0}),t}function Ab(e){try{const t=Sd(),r=ee.join(t,`${e}.json`);if(!ue.existsSync(r))return null;const s=ue.readFileSync(r,"utf8");return JSON.parse(s)}catch(t){return console.error("Failed to read cache:",t),null}}function Pb(e,t){try{const r=Sd(),s=ee.join(r,`${e}.json`);ue.writeFileSync(s,JSON.stringify(t,null,2))}catch(r){console.error("Failed to write cache:",r)}}function jb(e,t,r){const s=ms(t,e),a=ms(r,e),o=new Map(s.map(u=>[u.name,u])),i=new Map(a.map(u=>[u.name,u])),l=[],c=[],p=[];for(const[u,m]of i){const h=o.get(u);h?h.sha!==m.sha&&c.push({name:u,baseSha:h.sha,compareSha:m.sha,entityType:m.entityType}):l.push(m)}for(const[u,m]of o)i.has(u)||p.push(m);return{filePath:e,newEntities:l,modifiedEntities:c,deletedEntities:p}}function Tb(e,t){const r=Ne();if(!r)throw new Error("No project root found");const s=Zi(e,r),a=Zi(t,r);if(!s||!a)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${t}`);const o=Eb(e,t,s,a),i=Ab(o);if(i)return console.log(`Using cached branch entity diff: ${o}`),i;const l=ld(e,t),c=[];for(const u of l)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const m=rs(u.path,e,t),h=ms(m.oldContent,u.path);c.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:h})}else if(u.status==="added"){const m=rs(u.path,e,t),h=ms(m.newContent,u.path);c.push({filePath:u.path,newEntities:h,modifiedEntities:[],deletedEntities:[]})}else{const m=rs(u.path,e,t),h=jb(u.path,m.oldContent,m.newContent);(h.newEntities.length>0||h.modifiedEntities.length>0||h.deletedEntities.length>0)&&c.push(h)}const p={baseBranch:e,compareBranch:t,baseCommitSha:s,compareCommitSha:a,fileComparisons:c,cacheKey:o,computedAt:new Date().toISOString()};return Pb(o,p),p}function Mb({request:e}){try{const t=new URL(e.url),r=t.searchParams.get("base"),s=t.searchParams.get("compare");if(!r||!s)return X({error:"Missing required parameters: base and compare"},{status:400});const a=Tb(r,s);return X(a)}catch(t){return console.error("Failed to compute branch entity diff:",t),X({error:"Failed to compute branch entity diff",details:t instanceof Error?t.message:String(t)},{status:500})}}const $b=Object.freeze(Object.defineProperty({__proto__:null,loader:Mb},Symbol.toStringTag,{value:"Module"}));async function Ib({request:e}){if(e.method!=="POST")return X({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 X({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=Ne();if(!i)return X({error:"Project root not found"},{status:500});const l=L.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),c=JSON.stringify({url:r,scenarioId:s,projectId:a,projectRoot:i,viewportWidth:o}),p=await new Promise(h=>{const f=L.join(i,".codeyam","db.sqlite3"),g=St("npx",["tsx",l,c],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let y="",x="";g.stdout.on("data",w=>{const b=w.toString();y+=b;const v=b.trim().split(`
|
|
386
|
-
`);for(const N of v)N.includes("[Capture]")&&console.log(N)}),g.stderr.on("data",w=>{const b=w.toString();x+=b,console.error("[Capture:Error]",b.trim())}),g.on("close",w=>{h(w===0?{success:!0,output:y}:{success:!1,output:y,error:x||`Process exited with code ${w}`})}),g.on("error",w=>{console.error("[Capture] Failed to spawn child process:",w),h({success:!1,output:"",error:w.message})})});if(!p.success)return X({error:"Failed to capture screenshot",details:p.error},{status:500});const u=p.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return X({error:"Failed to parse capture result"},{status:500});const m=JSON.parse(u[1]);return X(m)}catch(t){return console.error("[Capture] Error:",t),X({error:"Failed to capture screenshot",details:t instanceof Error?t.message:String(t)},{status:500})}}const Rb=Object.freeze(Object.defineProperty({__proto__:null,action:Ib},Symbol.toStringTag,{value:"Module"}));function Db(e){const t=e||process.cwd();try{return $e("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 Ob(e){const t=e||process.cwd();try{return $e("git rev-parse --git-dir",{cwd:t,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),!0}catch{return!1}}function Fb(e){if(Ob(e))return!1;$e("git init",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]});try{$e('git config user.email "codeyam@local"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),$e('git config user.name "CodeYam"',{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}catch{}return!0}function Lb(e){$e("git add -A",{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]})}function zb(e,t){return $e(`git commit -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Db(e)}function Bb(e){return/^[0-9a-f]{7,40}$/i.test(e)}function Yb(e,t){try{return $e(`git cat-file -t ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"}),!0}catch{return!1}}function Ub(e,t){try{return{stashed:!$e(`git stash push -m ${JSON.stringify(t)}`,{cwd:e,encoding:"utf8",stdio:"pipe"}).includes("No local changes")}}catch{return{stashed:!1}}}function Wb(e,t){$e(`git checkout ${t}`,{cwd:e,encoding:"utf8",stdio:"pipe"})}async function Jb({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(!Bb(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}`),!Yb(s,r))return new Response(JSON.stringify({success:!1,error:`Commit ${r} not found`}),{status:400,headers:{"Content-Type":"application/json"}});const{stashed:a}=Ub(s,"codeyam: auto-stash before time travel");a&&console.log("[editor-load-commit] Stashed uncommitted changes");try{Wb(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 Hb=Object.freeze(Object.defineProperty({__proto__:null,action:Jb},Symbol.toStringTag,{value:"Module"}));async function Vb(e,t,r){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${t}`),await ze();const s=await Yt({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const a=Te(),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 Un(e,g=>{if(g){if(g.readyToBeCaptured=!0,g.scenarios)for(const y of g.scenarios)delete y.finishedAt,delete y.startedAt,delete y.screenshotStartedAt,delete y.screenshotFinishedAt,delete y.interactiveStartedAt,delete y.interactiveFinishedAt,delete y.error,delete y.errorStack;delete g.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const c=Ne();if(!c)throw new Error("Project root not found");const p=L.join(c,".codeyam","config.json"),u=JSON.parse(K.readFileSync(p,"utf8")),{projectSlug:m}=u;if(!m)throw new Error("Project slug not found in config");const{jobId:h}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:m,analysisId:e,defaultWidth:t});return console.log(`[recapture] Recapture job queued with ID: ${h}`),{jobId:h}}async function Gb(e,t,r){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${t}`),await ze();const s=await Yt({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=(u=s.scenarios)==null?void 0:u.find(m=>m.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 Un(e,m=>{if(m&&(m.readyToBeCaptured=!0,delete m.finishedAt,m.scenarios)){const h=m.scenarios.find(f=>f.name===a.name);h&&(delete h.finishedAt,delete h.startedAt,delete h.error,delete h.errorStack,delete h.screenshotStartedAt,delete h.screenshotFinishedAt,delete h.interactiveStartedAt,delete h.interactiveFinishedAt)}}),console.log(`[recapture] Cleared errors and marked scenario ${a.name} for recapture`);const o=Ne();if(!o)throw new Error("Project root not found");const i=L.join(o,".codeyam","config.json"),l=JSON.parse(K.readFileSync(i,"utf8")),{projectSlug:c}=l;if(!c)throw new Error("Project slug not found in config");const{jobId:p}=r.enqueue({type:"recapture",commitSha:s.commit.sha,projectSlug:c,analysisId:e,scenarioId:t});return console.log(`[recapture] Scenario recapture job queued with ID: ${p}`),{jobId:p}}async function Kb({request:e,context:t}){if(e.method!=="POST")return X({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Ut()),!r)return X({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a||!o)return X({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${a}, scenario ${o}`);const i=await Gb(a,o,r);return console.log("[API] Scenario recapture queued",i),X({success:!0,message:"Scenario recapture queued",...i})}catch(s){return console.log("[API] Error during scenario recapture:",s),X({error:"Failed to recapture scenario",details:s instanceof Error?s.message:String(s)},{status:500})}}const qb=Object.freeze(Object.defineProperty({__proto__:null,action:Kb},Symbol.toStringTag,{value:"Module"}));async function Ka(e){try{return await Pe.stat(e),!0}catch{return!1}}async function Cd(){try{const e=Ne();if(!e)return null;const t=ee.join(e,".codeyam","config.json");return JSON.parse(await Pe.readFile(t,"utf-8")).projectSlug||null}catch{return null}}function Qb(){return`/private/tmp/claude-501/-${(Ne()||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}/tasks`}const ss="/tmp/claude-rule-markers",Zb=/<system-reminder>[\s\S]*?<\/system-reminder>/g,Xi=2e3;function Xb(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 ew=["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 tw(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 nw(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(`
|
|
387
|
-
###`);return a!==-1&&(s=s.slice(0,a).trim()),s||void 0}function rw(e){for(const t of e){if(t.type!=="user_prompt")continue;const r=(t.text||"").toLowerCase();for(const s of ew)if(r.includes(s))return!0}return!1}function sw(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 aw(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 ow(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 c=(o.message||{}).content,p=o.timestamp||"";if(i==="user"){if(typeof c=="string")t.push({type:"user_prompt",text:c,timestamp:p,agent_id:String(o.agentId||o.session_id||"unknown"),slug:String(o.slug||"")});else if(Array.isArray(c)){for(const u of c)if(typeof u=="object"&&u!==null&&u.type==="tool_result"){const m=u,h=String(m.tool_use_id||"");let f=m.content;const g=!!m.is_error;typeof f=="string"&&(f=f.replace(Zb,"").trim()),t.push({type:"tool_result",tool_use_id:h,tool_name:r[h]||"unknown",content:typeof f=="string"?f:JSON.stringify(f),is_error:g,timestamp:p})}}}else if(i==="assistant"&&Array.isArray(c))for(const u of c){if(typeof u!="object"||u===null)continue;const m=u;if(m.type==="text"){const h=String(m.text||"").trim();h&&t.push({type:"assistant_text",text:h,timestamp:p})}else if(m.type==="tool_use"){const h=String(m.id||""),f=String(m.name||"unknown"),g=m.input||{};r[h]=f,t.push({type:"tool_call",tool_use_id:h,name:f,input:g,timestamp:p})}}}return t}function iw(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 jn=20;async function el(e){const r=(await Pe.readFile(e.filePath,"utf-8")).split(`
|
|
388
|
-
`),s=ow(r);if(s.length===0)return null;const a=s.find(v=>v.type==="user_prompt"),o=e.stem,i=sw(r);let l=(a==null?void 0:a.slug)||"",c=(a==null?void 0:a.timestamp)||"";c||(c=new Date(e.mtime).toISOString());let p;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 v=e.filePath.replace(/\.log$/,".context");if(await Ka(v))try{p=await Pe.readFile(v,"utf-8")}catch{}}const u=s.filter(v=>v.type==="tool_call").length,m=s.filter(v=>v.type==="assistant_text").length,h=s.filter(v=>v.type==="tool_result"&&v.is_error&&v.content!=="Sibling tool call errored"),f=h.length,g=h.map(v=>{const N=v.content||"Unknown error";return N.length>150?N.slice(0,150)+"...":N});for(const v of s)v.type==="tool_call"&&v.name&&v.input&&(v.summary=Xb(v.name,v.input));for(const v of s)v.type==="tool_result"&&v.content&&v.content.length>Xi&&(v.truncated=!0,v.fullLength=v.content.length,v.content=v.content.slice(0,Xi));const y=tw(s),x=rw(s),w=nw(p),b=aw(r);return{id:o,slug:l,timestamp:c,model:i,sourceFile:e.filePath,stats:{toolCalls:u,textBlocks:m,errors:f,errorMessages:g},entries:s,context:p,conversationSnippet:w,ruleChanges:y,hasConfusion:x,sessionResult:b}}async function lw(){const e=Qb(),t=ss,r=[];if(await Ka(e)){const i=await Pe.readdir(e);for(const l of i)if(l.endsWith(".output")){const c=ee.join(e,l),p=await Pe.stat(c);r.push({filePath:c,stem:l.replace(".output",""),mtime:p.mtimeMs})}}const s=new Set,a=await Cd(),o=[];a&&o.push(ee.join(t,a)),o.push(t);for(const i of o){if(!await Ka(i))continue;const l=await Pe.readdir(i);for(const c of l){if(!c.endsWith(".log")||s.has(c))continue;s.add(c);const p=ee.join(i,c),u=await Pe.stat(p);r.push({filePath:p,stem:c.replace(".log",""),mtime:u.mtimeMs})}}return r.sort((i,l)=>l.mtime-i.mtime),r}async function cw({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 lw();if(!s){const u=o.length,m=(a-1)*jn,h=o.slice(m,m+jn),f=[];for(const g of h){const y=await el(g);y&&f.push(y)}return Response.json({agents:f,total:u,page:a,pageSize:jn})}const i=[];for(const u of o){const m=await el(u);if(!m)continue;(m.id.toLowerCase().includes(s)||m.slug.toLowerCase().includes(s)||m.entries.some(f=>iw(f,s)))&&i.push(m)}const l=i.length,c=(a-1)*jn,p=i.slice(c,c+jn);return Response.json({agents:p,total:l,page:a,pageSize:jn})}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 dw=Object.freeze(Object.defineProperty({__proto__:null,loader:cw},Symbol.toStringTag,{value:"Module"})),_d="__codeyam_editor_dev_server__",tl=30;function Vo(){return globalThis[_d]??null}function kd(e){globalThis[_d]=e}function qr(e,t){const r=[ee.join(e,".next","dev","lock"),ee.join(e,"node_modules",".vite","deps","_lock")];for(const s of r)try{ue.existsSync(s)&&(ue.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=$e(`lsof -ti:${t}`,{encoding:"utf8"}).trim();if(s){const a=process.pid,o=s.split(`
|
|
389
|
-
`).filter(i=>i&&parseInt(i,10)!==a);if(o.length>0){for(const i of o)try{$e(`kill ${i}`)}catch{}console.log(`[editor-dev-server] Killed orphaned process(es) on port ${t}: ${o.join(", ")}`)}}}catch{}}function uw({request:e}){const t=Vo();return t?new Response(JSON.stringify({status:t.status,url:t.url,proxyUrl:qc(),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 pw({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"?qa():r==="stop"?nl():r==="restart"?(nl(),await new Promise(s=>setTimeout(s,1e3)),qa()):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 mw(){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(ue.existsSync(s))return s;return console.warn("[editor-dev-server] codeyam-preload.mjs not found, SSR fetch interception disabled"),null}function qa(e=!1){var E,k;const t=Vo();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=Ne()||process.cwd(),s=parseInt(process.env.CODEYAM_PORT||"3111",10),{proxyPort:a,devServerPort:o}=Yc(s),i=l0(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:c,env:p}=i;qr(r,o),qr(r,3e3),qr(r,3001),qr(r,5173),console.log(`[editor-dev-server] Starting: ${l} ${c.join(" ")} in ${r}`);const u=mw(),m=u?`--import ${u}`:"",{NODE_OPTIONS:h,PORT:f,CODEYAM_PORT:g,...y}=process.env,x={};try{const _=ee.join(r,".codeyam","config.json"),S=JSON.parse(ue.readFileSync(_,"utf-8"));for(const j of S.environmentVariables||[])j.key&&j.value!==void 0&&(x[j.key]=j.value)}catch{}const w=St(l,c,{cwd:r,stdio:["ignore","pipe","pipe"],env:{...y,...x,FORCE_COLOR:"1",BROWSER:"none",...m?{NODE_OPTIONS:m}:{},CODEYAM_PROXY_URL:`http://localhost:${a}`,...p},detached:!0});w.unref();const b=e?((t==null?void 0:t.retryCount)??0)+1:0,v={process:w,url:null,status:"starting",errorMessage:null,stderrBuffer:[],pid:w.pid||0,startedAt:Date.now(),retryCount:b};kd(v);const N=(_,S)=>{const j=_.toString(),$=j.split(`
|
|
390
|
-
`).filter(T=>T.trim());if($.length>0&&(v.stderrBuffer.push(...$),v.stderrBuffer.length>tl&&(v.stderrBuffer=v.stderrBuffer.slice(-tl))),v.status==="starting"){const T=d0(j);T&&(v.url=T,v.status="running",console.log(`[editor-dev-server] URL detected: ${v.url}`),Wa({port:a,targetUrl:v.url}).then(()=>Yi()))}};(E=w.stdout)==null||E.on("data",_=>N(_)),(k=w.stderr)==null||k.on("data",_=>N(_));const C=parseInt(p.PORT||"0",10);return C>0&&(async()=>{if(await new Promise(S=>setTimeout(S,1e4)),v.status!=="starting")return;console.log(`[editor-dev-server] Stdout detection timed out, polling port ${C}...`);const _=await p0(C,{intervalMs:2e3,maxAttempts:15});_&&v.status==="starting"&&(v.url=_,v.status="running",console.log(`[editor-dev-server] URL detected via polling: ${v.url}`),Wa({port:a,targetUrl:v.url}).then(()=>Yi()))})(),w.on("exit",_=>{console.log(`[editor-dev-server] Process exited with code ${_}`);const S=Date.now()-v.startedAt,j=v.status==="running",$=m0({exitCode:_??null,uptime:S,retryCount:v.retryCount,wasRunning:j});if($.action==="retry")console.log(`[editor-dev-server] Quick failure (${S}ms), auto-retrying...`),v.status="stopped",qa(!0);else if($.action==="error"){v.status="error";const T=v.stderrBuffer.length>0?v.stderrBuffer.join(`
|
|
391
|
-
`):"",R=j?`Dev server exited with code ${_}`:`Dev server exited (code ${_}) before it started serving`;v.errorMessage=T?`${R}
|
|
392
|
-
|
|
393
|
-
${T}`:R,console.error(`[editor-dev-server] Server failed: ${v.errorMessage}`)}else v.status="stopped"}),w.on("error",_=>{console.error("[editor-dev-server] Process error:",_),v.status="error",v.errorMessage=_.message}),new Response(JSON.stringify({status:"starting",pid:w.pid,message:`Starting ${l} ${c.join(" ")}`}),{headers:{"Content-Type":"application/json"}})}function nl(){const e=Vo();if(!e||e.status==="stopped")return new Response(JSON.stringify({status:"stopped",message:"No server to stop"}),{headers:{"Content-Type":"application/json"}});ed();try{e.process.pid&&process.kill(-e.process.pid,"SIGTERM")}catch{try{e.process.kill("SIGTERM")}catch{}}return e.status="stopped",kd(null),new Response(JSON.stringify({status:"stopped",message:"Dev server stopped"}),{headers:{"Content-Type":"application/json"}})}const hw=Object.freeze(Object.defineProperty({__proto__:null,action:pw,loader:uw},Symbol.toStringTag,{value:"Module"}));async function fw({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=Is(r);try{return await dr(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 gw({params:e}){const{projectSlug:t}=e;if(!t)return new Response("Project slug is required",{status:400});const r=Is(t);try{if(!xt(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 Ra(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 yw=Object.freeze(Object.defineProperty({__proto__:null,action:fw,loader:gw},Symbol.toStringTag,{value:"Module"}));function xw({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return Response.json({error:"Missing path parameter"},{status:400});const s=Ne()||process.cwd(),a=L.resolve(s,r);if(!a.startsWith(s+L.sep)&&a!==s)return Response.json({error:"Path outside project root"},{status:403});const o=cd(r,s);return Response.json(o)}const bw=Object.freeze(Object.defineProperty({__proto__:null,loader:xw},Symbol.toStringTag,{value:"Module"}));async function ww(){const e=await Fe();if(!e)return Response.json({error:"No project configured"},{status:400});const{project:t}=await Re(e),r=Te(),s=process.env.CODEYAM_PORT||"3111",a=Ne()||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=vt(o,p=>`${p.name}::${p.url||"/"}`);let l={};try{const p=i.map(m=>({componentName:m.component_name||null,componentPath:m.component_path||null,pageFilePath:m.page_file_path??null,url:m.url??null,displayName:m.display_name??null}));l=(await Gn({projectRoot:a,scenarioInputs:p})).entityChangeStatus}catch{}const c=i.map(p=>{const u=p,m=nn({componentName:p.component_name,pageFilePath:u.page_file_path,url:u.url}),h=m?l[m]:void 0;return{id:p.id,name:p.name,componentName:p.component_name||null,type:p.type||null,changeStatus:(h==null?void 0:h.status)||null,screenshotPath:p.screenshot_path||null,link:`http://localhost:${s}/editor?scenario=${p.id}&ref=link`}});return Response.json({scenarios:c})}const vw=Object.freeze(Object.defineProperty({__proto__:null,loader:ww},Symbol.toStringTag,{value:"Module"}));async function Nw(e,t){var o,i,l,c,p,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${t}`),await ze();const r=await Yt({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(m=>m.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:((c=(l=(i=s.metadata)==null?void 0:i.data)==null?void 0:l.argumentsData)==null?void 0:c[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${r.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(p=s.metadata)==null?void 0:p.data)==null?void 0:u.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 Sw({request:e}){if(e.method!=="POST")return X({error:"Method not allowed"},{status:405});try{const t=await e.formData(),r=t.get("analysisId"),s=t.get("scenarioId");if(!r||!s)return X({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${r}, scenario ${s}`);const a=await Nw(r,s);return console.log("[API] Function execution completed successfully"),X({success:!0,result:a})}catch(t){return console.log("[API] Error during function execution:",t),X({success:!1,error:"Failed to execute function",details:t instanceof Error?t.message:String(t)},{status:500})}}const Cw=Object.freeze(Object.defineProperty({__proto__:null,action:Sw},Symbol.toStringTag,{value:"Module"}));function _w({request:e}){return X({status:"ok"})}async function kw({request:e,context:t}){if(e.method!=="POST")return X({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Ut()),!r)return console.error("[Interactive Mode API] Queue not initialized"),X({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 X({error:"Missing required fields: action and analysisId"},{status:400});if(a!=="start"&&a!=="stop")return X({error:'Invalid action. Must be "start" or "stop"'},{status:400});const l=await Fe();if(console.log("[Interactive Mode API] projectSlug:",l),!l)return X({error:"Project not initialized"},{status:500});if(a==="start"){const c=await r.enqueue({type:"interactive-start",analysisId:o,scenarioId:i,projectSlug:l});return X({success:!0,action:"start",message:"Interactive mode starting...",jobId:c})}else{const c=await r.enqueue({type:"interactive-stop",analysisId:o,projectSlug:l});return X({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:c})}}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),X({error:"Failed to control interactive mode",details:a},{status:500})}}const Ew=Object.freeze(Object.defineProperty({__proto__:null,action:kw,loader:_w},Symbol.toStringTag,{value:"Module"}));async function Aw({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=Ne();if(a)for(const o of s){const i=ee.join(a,".codeyam","captures","screenshots",o);try{await Pe.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 Zm({ids:[r]});try{await Te().deleteFrom("editor_scenarios").where("id","=",r).execute()}catch{}try{const a=Ne()||process.cwd();z0(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 Pw=Object.freeze(Object.defineProperty({__proto__:null,action:Aw},Symbol.toStringTag,{value:"Module"}));class jw extends _r{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 Qa="__codeyam_dev_mode_event_emitter__";if(!globalThis[Qa]){const e=new jw;e.setMaxListeners(20),globalThis[Qa]=e}const rl=globalThis[Qa];function Tw({request:e}){const t=new ReadableStream({start(r){const s=new TextEncoder;r.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
394
|
-
|
|
395
|
-
`));let a=!1;const o=()=>{if(!a){a=!0,rl.off("event",i),clearInterval(l);try{r.close()}catch{}}},i=c=>{try{r.enqueue(s.encode(`data: ${JSON.stringify(c)}
|
|
396
|
-
|
|
397
|
-
`))}catch{o()}};rl.on("event",i);const l=setInterval(()=>{try{r.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
398
|
-
|
|
399
|
-
`))}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 Mw=Object.freeze(Object.defineProperty({__proto__:null,loader:Tw},Symbol.toStringTag,{value:"Module"})),vr="/tmp/codeyam",Za=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",Ed=500,$w=Ed*1024*1024;function pn(e,t){try{return $e(`git ${e}`,{cwd:t,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function as(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Ad(e){return pn("config user.email",e)}function Iw(e){const t=L.join(e,".codeyam","debug-report.md");if(!K.existsSync(t))return null;try{return K.readFileSync(t,"utf8")}catch{return null}}function Rw(e,t=20){const r=L.join(vr,"local-dev",e,"codeyam","log.txt");if(!K.existsSync(r))return[];try{return K.readFileSync(r,"utf8").split(`
|
|
400
|
-
`).filter(i=>i.includes("CodeYam Log Level 1")).slice(-t)}catch{return[]}}async function Dw(e){try{const t=await fetch(`${Za}/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 Ow(e,t){try{$e(`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 Fw(e){const{projectRoot:t,projectSlug:r,outputPath:s,metadata:a,screenshot:o,onProgress:i}=e,l=i||(()=>{}),c=Date.now(),p=L.join(vr,`delta-staging-${c}`),u=L.join(p,"delta");K.mkdirSync(u,{recursive:!0});try{const m=pn("diff --binary HEAD",t)||"";K.writeFileSync(L.join(u,"tracked.patch"),m?m+`
|
|
401
|
-
`:"");const h=pn("ls-files --others --exclude-standard",t);if(h){const x=L.join(u,"untracked");K.mkdirSync(x,{recursive:!0});for(const w of h.split(`
|
|
402
|
-
`).filter(Boolean)){const b=L.join(t,w),v=L.join(x,w);if(K.existsSync(b)){const N=L.dirname(v);K.mkdirSync(N,{recursive:!0}),K.statSync(b).isFile()&&K.copyFileSync(b,v)}}}const f=L.join(t,".codeyam");if(K.existsSync(f)){const x=L.join(u,"codeyam");K.cpSync(f,x,{recursive:!0})}K.writeFileSync(L.join(u,"meta.json"),JSON.stringify(a,null,2));const g=L.join(vr,"local-dev",r,"codeyam","log.txt");K.existsSync(g)?K.copyFileSync(g,L.join(u,"codeyam-log.txt")):K.writeFileSync(L.join(u,"codeyam-log.txt"),`# Log file not found
|
|
403
|
-
`);const y=L.join(t,".codeyam","debug-report.md");K.existsSync(y)&&(K.copyFileSync(y,L.join(u,"debug-report.md")),l("Debug report included")),o&&o.length>0&&(K.writeFileSync(L.join(u,"screenshot.jpg"),o),l(`Screenshot included (${as(o.length)})`));try{$e(`tar -czf "${s}" -C "${p}" delta`,{stdio:"pipe"})}catch(x){throw new Error(`tar failed: ${x.message}`)}}finally{K.rmSync(p,{recursive:!0,force:!0})}}async function Lw(e){const{projectRoot:t,projectSlug:r,feedback:s,screenshot:a,onProgress:o}=e,i=o||(()=>{});i("Gathering metadata...");const l=pn("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 c=pn("rev-parse --abbrev-ref HEAD",t)||"unknown",p=pn("status --porcelain",t),u=pn("remote get-url origin",t),m=p!==null&&p.length>0,h=kc(r),f=Iw(t);let g=s;f&&(g={...s||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam-diagnose workflow"));const y={timestamp:new Date().toISOString(),projectSlug:r,git:{sha:l,branch:c,isDirty:m,remoteUrl:u},versions:{cli:h.cliVersion,webserver:h.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:g},x=Date.now(),w=L.join(vr,`base-${l}-${x}.tar.gz`),b=L.join(vr,`delta-${r}-${x}.tar.gz`);i("Checking for existing base...");const v=await Dw(l);let N=null;v?i("Server already has base, skipping..."):(i("Generating base archive..."),Ow(t,w),N=K.statSync(w).size,i(`Base archive: ${as(N)}`)),i("Generating delta archive..."),Fw({projectRoot:t,projectSlug:r,outputPath:b,metadata:y,screenshot:a,onProgress:o});const E=K.statSync(b).size;i(`Delta archive: ${as(E)}`);const k=(N||0)+E;if(k>$w)throw K.existsSync(w)&&K.unlinkSync(w),K.unlinkSync(b),new Error(`Bundle too large: ${as(k)} (max: ${Ed} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:v?null:w,deltaPath:b,metadata:y,baseSha:l,baseSize:N,deltaSize:E}}async function zw(e){const{basePath:t,deltaPath:r,projectSlug:s,metadata:a,baseSha:o,deltaSize:i,onProgress:l}=e,c=l||(()=>{}),p=K.statSync(r),u=t?K.statSync(t):null,m=p.size+((u==null?void 0:u.size)||0);c("Requesting upload URLs...");const h=await fetch(`${Za}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:s,fileSizeBytes:m,baseSha:o,needsBaseUpload:t!==null,deltaSizeBytes:i,metadata:{timestamp:a.timestamp,git:a.git,versions:a.versions,system:a.system,feedback:a.feedback}})});if(!h.ok){const v=await h.json();throw new Error(v.error||`Server returned ${h.status}`)}const{reportId:f,deltaUploadUrl:g,baseUploadUrl:y}=await h.json(),x=[];if(t&&y){c("Uploading base...");const v=K.readFileSync(t);x.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(N=>{if(!N.ok)throw new Error(`Base upload failed: ${N.status}`)}))}c("Uploading delta...");const w=K.readFileSync(r);x.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:w}).then(v=>{if(!v.ok)throw new Error(`Delta upload failed: ${v.status}`)})),await Promise.all(x),c("Confirming upload...");const b=await fetch(`${Za}/api/reports/confirm-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reportId:f})});if(!b.ok){const v=await b.json();throw new Error(v.error||`Confirm failed: ${b.status}`)}return t&&K.existsSync(t)&&K.unlinkSync(t),K.unlinkSync(r),{bundleId:f}}async function Bw({request:e}){if(e.method!=="POST")return X({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"),c=t.get("analysisId"),p=t.get("currentUrl"),u=t.get("entityName"),m=t.get("entityType"),h=t.get("scenarioName"),f=t.get("errorMessage"),g=t.get("screenshot");let y=s||void 0;!y&&u&&(h?y=`Issue on ${u} scenario "${h}"`:y=`Issue on ${u}`);let x;if(g&&g.size>0){const k=await g.arrayBuffer();x=Buffer.from(k),console.log(`[Bundle] Screenshot received: ${g.size} bytes`)}const w=Ne();if(!w)return X({error:"Project root not found"},{status:500});const b=await Fe();if(!b)return X({error:"Project slug not found"},{status:500});const v={issueType:r||"other",description:y,email:a||void 0,source:o||"navbar",entitySha:i||void 0,scenarioId:l||void 0,analysisId:c||void 0,currentUrl:p||void 0,recentActivity:Rw(b,20),entityName:u||void 0,entityType:m||void 0,scenarioName:h||void 0,errorMessage:f||void 0};console.log(`[Bundle] Generating bundle for ${b}...`),console.log(`[Bundle] Context: ${v.source}, issue: ${v.issueType}`);const N=await Lw({projectRoot:w,projectSlug:b,feedback:v,screenshot:x,onProgress:k=>{console.log(`[Bundle] ${k}`)}}),C=(N.baseSize||0)+N.deltaSize;console.log(`[Bundle] Archives created: delta=${N.deltaSize} bytes${N.basePath?`, base=${N.baseSize} bytes`:" (base reused)"}`);const E=await zw({basePath:N.basePath,deltaPath:N.deltaPath,projectSlug:b,metadata:N.metadata,baseSha:N.baseSha,deltaSize:N.deltaSize,onProgress:k=>{console.log(`[Bundle] ${k}`)}});return console.log(`[Bundle] Upload complete: ${E.bundleId}`),X({success:!0,reportId:E.bundleId,size:C})}catch(t){return console.error("[Bundle] Error:",t),X({error:t.message||"Failed to generate bundle"},{status:500})}}function Yw(){const e=Ne(),t=e?Ad(e):null;return X({defaultEmail:t})}const Uw=Object.freeze(Object.defineProperty({__proto__:null,action:Bw,loader:Yw},Symbol.toStringTag,{value:"Module"}));async function Ww({request:e}){try{const r=new URL(e.url).searchParams.get("date"),s=process.env.CODEYAM_ROOT_PATH||process.cwd(),a=L.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 Jw=Object.freeze(Object.defineProperty({__proto__:null,loader:Ww},Symbol.toStringTag,{value:"Module"}));function Pd(e){if(!K.existsSync(e))return et.Unknown;try{const t=JSON.parse(K.readFileSync(e,"utf8")),r={...t.dependencies,...t.devDependencies};return r.next?et.Next:r["@remix-run/node"]||r["@remix-run/react"]||r["react-router"]?et.Remix:r["react-scripts"]?et.CRA:r.expo?et.Expo:r.vite?et.Vite:et.Unknown}catch{return et.Unknown}}function Hw(e,t){let r=e;const s=L.resolve(t);for(;;){const a=L.resolve(r);if(K.existsSync(L.join(a,"pnpm-lock.yaml")))return"pnpm";if(K.existsSync(L.join(a,"yarn.lock")))return"yarn";if(K.existsSync(L.join(a,"package-lock.json")))return"npm";if(a===s)break;const o=L.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 Vw(e){const t=/cd\s+([^\s;&|]+)\s*(?:&&|;)/,r=e.match(t);return r?r[1]:null}function Gw(e){const t=L.join(e,"package.json");if(!K.existsSync(t))return{isWebApp:!1};if(Pd(t)===et.Unknown)return{isWebApp:!1};try{const a=JSON.parse(K.readFileSync(t,"utf8")).scripts||{},o=["remix","react-router","next dev","vite","react-scripts","webpack-dev-server","parcel","expo"],l=Object.keys(a).filter(c=>["dev","start","serve","build"].some(p=>c.includes(p))).filter(c=>o.some(p=>a[c].includes(p)));if(l.length===0)return{isWebApp:!1};for(const c of l){const p=a[c],u=Vw(p);if(u){const m=L.join(e,u);if(K.existsSync(m)&&K.statSync(m).isDirectory())return{isWebApp:!0,actualPath:m}}}return{isWebApp:!0}}catch{return{isWebApp:!1}}}function jd(e,t=e,r=0,s=3){if(r>s)return[];const a=[],o=Gw(t);if(o.isWebApp){const l=o.actualPath||t,c=L.relative(e,l);return a.push(c||"."),a}const i=["node_modules",".git",".next","dist","build",".cache","coverage",".codeyam"];try{const l=K.readdirSync(t,{withFileTypes:!0});for(const c of l)if(c.isDirectory()&&!i.includes(c.name)){const p=L.join(t,c.name);a.push(...jd(e,p,r+1,s))}}catch{}return a}function Kw(e){const t=jd(e);return t.length===0?[]:t.map(s=>{const a=L.join(e,s),o=L.join(a,"package.json"),i=Pd(o),l=Hw(a,e);let c;if(i===et.Remix||i===et.Next){const m=L.join(a,"app");K.existsSync(m)&&K.statSync(m).isDirectory()&&(c="app")}const p=qw(s,e),u=p?{command:"sh",args:["-c",`${l} run ${p} -- --port $PORT`]}:void 0;return{path:s,framework:i,packageManager:l,appDirectory:c,startCommand:u}})}function qw(e,t){const r=L.join(t,e),s=L.join(r,"package.json");if(!K.existsSync(s))return null;try{const o=JSON.parse(K.readFileSync(s,"utf8")).scripts||{},i=["dev","start","serve"];for(const l of i)if(o[l])return l;return null}catch{return null}}function Qw(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 Zw({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Ne()||process.cwd(),r=ee.join(t,".codeyam","config.json");let s=[];try{s=Kw(t)}catch{}if(ue.existsSync(r)){const i=JSON.parse(ue.readFileSync(r,"utf8")),l=i.webapps||[];i.webapps=Qw(s,l),s=i.webapps,ue.writeFileSync(r,JSON.stringify(i,null,2))}const a=await Fe();if(a)try{await Dn({projectSlug:a,metadataUpdate:{webapps:s}})}catch{}let o=!1;if(s.length>0)try{const i=process.env.CODEYAM_PORT||"3111",c=await(await fetch(`http://localhost:${i}/api/editor-dev-server`)).json();(c.status==="stopped"||c.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 Xw=Object.freeze(Object.defineProperty({__proto__:null,action:Zw},Symbol.toStringTag,{value:"Module"}));async function ev({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=await e.json(),r=Ne()||process.cwd();if(t.action==="clear"){xg(r);try{K.unlinkSync(L.join(r,".codeyam","claude-session-id.txt"))}catch{}return new Response(JSON.stringify({success:!0,message:"Editor state 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 tv=Object.freeze(Object.defineProperty({__proto__:null,action:ev},Symbol.toStringTag,{value:"Module"}));function hn(){const e=process.memoryUsage(),t=_p.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(Da.totalmem()/1024/1024),freeMemory:Math.round(Da.freemem()/1024/1024)}}}function nv(){const e=hn();console.log(`
|
|
404
|
-
[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 rv(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=hn();global.gc();const t=hn(),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 sv(){const e=hn(),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 av({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=rv(),a=hn();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=nv();return Response.json({success:!0,stats:s})}case"leaks":{const s=sv(),a=hn();return Response.json({success:!0,leakCheck:s,stats:a})}default:{const s=hn();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 ov=Object.freeze(Object.defineProperty({__proto__:null,loader:av},Symbol.toStringTag,{value:"Module"})),Qr=io(oo);async function iv({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=lv(o),l=i?await cv(o):null;return{pid:o,isRunning:i,processName:l}}));return Response.json({processes:a})}function lv(e){try{return process.kill(e,0),!0}catch{return!1}}async function cv(e){if(process.platform==="win32")try{const{stdout:r}=await Qr(`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 Qr(`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 Qr(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:s}=await Qr(`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 dv=Object.freeze(Object.defineProperty({__proto__:null,loader:iv},Symbol.toStringTag,{value:"Module"})),uv=_s(import.meta.url),pv=L.dirname(uv);function mv({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const t=Fs(),r=Ne()||(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=L.join(pv,"..","..","..","..","webserver","bootstrap.js"),o=L.join(r,".codeyam","logs");K.existsSync(o)||K.mkdirSync(o,{recursive:!0});const i=K.openSync(L.join(o,"background-server.log"),"a"),l=K.openSync(L.join(o,"background-server-error.log"),"a"),c=new Date().toISOString();K.appendFileSync(L.join(o,"background-server.log"),`
|
|
405
|
-
[${c}] Server restart requested via dashboard
|
|
406
|
-
`),No();const p=St("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"}});p.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${p.pid})`);const u=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),u}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 hv=Object.freeze(Object.defineProperty({__proto__:null,action:mv},Symbol.toStringTag,{value:"Module"}));async function fv({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,c)=>{var m,h,f,g,y;const p=(h=(m=l.metadata)==null?void 0:m.data)==null?void 0:h.argumentsData,u=Array.isArray(p)&&p.length>0?JSON.stringify(p[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${c}: ${l.name}`,{id:l.id,projectId:l.projectId,analysisId:l.analysisId,hasMetadata:!!l.metadata,hasData:!!((f=l.metadata)!=null&&f.data),mockDataKeys:(y=(g=l.metadata)==null?void 0:g.data)!=null&&y.mockData?Object.keys(l.metadata.data.mockData):[],argumentsDataLength:Array.isArray(p)?p.length:"not-array",argumentsDataPreview:u})});const a=s.map(l=>({...l,projectId:l.projectId||r.projectId,analysisId:l.analysisId||r.id})),o=await hh(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,c)=>{var u,m;const p=(m=(u=l.metadata)==null?void 0:u.data)==null?void 0:m.argumentsData;console.log(`[API] Saved scenario ${c}: ${l.name}`,{id:l.id,argumentsDataLength:Array.isArray(p)?p.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 gv=Object.freeze(Object.defineProperty({__proto__:null,action:fv},Symbol.toStringTag,{value:"Module"})),yv=()=>[{title:"Agent Transcripts - CodeYam"},{name:"description",content:"View background agent transcripts and tool call history"}];async function xv({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),c=await(await fetch(i.toString())).json();if(c.error)return X({agents:[],error:c.error,search:r,page:1,totalPages:1});const p=c.total??(c.agents||[]).length,u=c.pageSize??20;return X({agents:c.agents||[],error:null,search:r,page:c.page??parseInt(s,10),totalPages:Math.max(1,Math.ceil(p/u))})}catch(t){return console.error("Failed to load agent transcripts:",t),X({agents:[],error:"Failed to load agent transcripts",search:"",page:1,totalPages:1})}}function bv(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 wv(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 vv(e){return e.includes("opus")?"Opus":e.includes("sonnet")?"Sonnet":e.includes("haiku")?"Haiku":e}function os({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 Nv({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)+"..."),d("div",{children:[d("span",{className:"text-[#f4a261] font-bold",children:[t,":"]})," ",n("span",{className:"text-gray-700",children:s})]},t)})})}function Sv({content:e,truncated:t,fullLength:r}){const[s,a]=M(!1);return d("div",{children:[d("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 Cv({entry:e,pairedResult:t}){const[r,s]=M(!1),a=bv(e.timestamp||"");return e.type==="user_prompt"?d("div",{className:"my-2",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(os,{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"?d("div",{className:"my-2",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(os,{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"?d("div",{className:"my-2",children:[d("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(wt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}):n(Xt,{className:"w-3 h-3 text-gray-400 flex-shrink-0"}),n(os,{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&&d("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(Nv,{input:e.input||{}}),t&&d("div",{className:"mt-3 pt-3 border-t border-gray-200",children:[d("div",{className:"text-[11px] font-bold uppercase tracking-wide text-[#2a9d8f] mb-1",children:["Result",t.is_error?" (Error)":"",":"]}),n(Sv,{content:t.content||"",truncated:t.truncated,fullLength:t.fullLength})]})]})]}):(e.type==="tool_result",null)}function _v({context:e}){const[t,r]=M(!1);return d("div",{className:"my-2",children:[d("button",{onClick:()=>r(!t),className:"flex items-center gap-2 mb-1 cursor-pointer hover:opacity-80",children:[t?n(wt,{className:"w-3 h-3 text-gray-400"}):n(Xt,{className:"w-3 h-3 text-gray-400"}),n(os,{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 kv({snippet:e}){const[t,r]=M(!1),s=e.split(`
|
|
407
|
-
`).filter(l=>l.trim()),a=s.slice(0,4),o=s.length>4,i=t?s:a;return d("div",{className:"my-2 bg-blue-50 border border-blue-200 rounded-md p-3",children:[d("div",{className:"flex items-center gap-2 mb-2",children:[n(Ju,{className:"w-3.5 h-3.5 text-blue-600"}),n("span",{className:"text-xs font-bold text-blue-800",children:"Source Conversation"}),d("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,c)=>{const p=l.match(/^\[(\w+)\]:\s*(.*)/);if(!p)return null;const[,u,m]=p,h=u==="user";return d("div",{className:"text-xs",children:[d("span",{className:`font-bold ${h?"text-blue-700":"text-gray-500"}`,children:[h?"User":"Assistant",":"]})," ",n("span",{className:"text-gray-700",children:m.length>200?m.slice(0,200)+"...":m})]},c)})}),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 Ev({change:e}){const[t,r]=M(!1),s=e.action==="created"?!!e.content:e.action==="modified"?!!(e.oldString||e.newString):!1;return d("li",{children:[n("button",{onClick:()=>s&&r(!t),className:`text-left w-full ${s?"hover:text-green-900 cursor-pointer":""}`,children:d("span",{className:"inline-flex items-center gap-1",children:[s&&(t?n(wt,{className:"w-3 h-3 inline flex-shrink-0"}):n(Xt,{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"&&d("div",{className:"mt-1 mb-2 ml-4 space-y-1",children:[e.oldString&&d("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&&d("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 Av({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 d("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:"}),d("ul",{className:"text-xs space-y-0.5 font-mono",children:[r.map((i,l)=>n(Ev,{change:i},l)),t.length>0&&d("li",{children:["Touched timestamps on ",t.length," rule",t.length!==1?"s":""]})]})]})}function Pv({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=c=>c>=6e4?`${(c/6e4).toFixed(1)}m`:`${(c/1e3).toFixed(1)}s`,l=c=>c>=1e3?`${(c/1e3).toFixed(1)}k`:String(c);return d("div",{className:`my-2 border rounded-md p-3 ${r}`,children:[d("div",{className:`text-xs font-bold mb-1 ${s}`,children:["Session Result: ",o]}),d("div",{className:`text-xs ${a} font-mono space-y-0.5`,children:[d("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5",children:[e.duration_ms!=null&&d("span",{children:["Duration: ",i(e.duration_ms)]}),e.duration_api_ms!=null&&d("span",{children:["API time: ",i(e.duration_api_ms)]}),e.num_turns!=null&&d("span",{children:["Turns: ",e.num_turns]}),e.total_cost_usd!=null&&d("span",{children:["Cost: $",e.total_cost_usd.toFixed(4)]})]}),e.usage&&d("div",{className:"flex flex-wrap gap-x-4 gap-y-0.5 mt-1",children:[e.usage.input_tokens!=null&&d("span",{children:["Input: ",l(e.usage.input_tokens)]}),e.usage.output_tokens!=null&&d("span",{children:["Output: ",l(e.usage.output_tokens)]}),e.usage.cache_read_input_tokens!=null&&d("span",{children:["Cache read: ",l(e.usage.cache_read_input_tokens)]}),e.usage.cache_creation_input_tokens!=null&&d("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((c,p)=>n("div",{className:"text-red-700 break-words",children:c},p))})]})]})}function jv({agent:e,defaultOpen:t,isAdmin:r}){var C,E,k;const[s,a]=M(t),[o,i]=M(!1),[l,c]=M(null),[p,u]=M(!1),m=ae(()=>{const _={};for(const S of e.entries)S.type==="tool_result"&&S.tool_use_id&&(_[S.tool_use_id]=S);return _},[e.entries]),h=ae(()=>{const _=new Set;for(const S of e.entries)S.type==="tool_call"&&S.tool_use_id&&m[S.tool_use_id]&&_.add(S.tool_use_id);return _},[e.entries,m]),f=_=>{_.stopPropagation(),i(!0),c(null),fetch("/api/save-fixture",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:e.id})}).then(S=>S.json()).then(S=>{S.success?c(`Saved to ${S.fixturePath}`):c(`Error: ${S.error}`)}).catch(S=>{c(`Error: ${S instanceof Error?S.message:String(S)}`)}).finally(()=>{i(!1)})},g=(e.ruleChanges||[]).filter(_=>_.action!=="touched"),y=g.filter(_=>_.action==="created"),x=g.filter(_=>_.action==="modified"),w=(e.ruleChanges||[]).filter(_=>_.action==="touched"),b=g.length>0,v=w.length>0,N=b||v;return d("div",{className:`bg-white border rounded-lg overflow-hidden mb-4 ${e.stats.errors>0?"border-red-300":y.length>0?"border-green-300":x.length>0?"border-amber-300":"border-gray-200"}`,children:[d("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(wt,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}):n(Xt,{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:vv(e.model)}),y.length>0&&d("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(ls,{className:"w-3 h-3"}),y.length," rule",y.length!==1?"s":""," ","created"]}),x.length>0&&d("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(ls,{className:"w-3 h-3"}),x.length," rule",x.length!==1?"s":""," ","modified"]}),!b&&v&&d("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:[w.length," timestamp",w.length!==1?"s":""," ","touched"]}),e.stats.errors>0&&d("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(is,{className:"w-3 h-3 flex-shrink-0"}),e.stats.errors," ",e.stats.errors===1?"Error":"Errors"]}),d("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&&d(xe,{children:[" · ",e.sessionResult.duration_ms>=6e4?`${(e.sessionResult.duration_ms/6e4).toFixed(1)}m`:`${(e.sessionResult.duration_ms/1e3).toFixed(1)}s`]}),((E=e.sessionResult)==null?void 0:E.total_cost_usd)!=null&&d(xe,{children:[" · ","$",e.sessionResult.total_cost_usd.toFixed(2)]})]}),d("span",{className:"text-[11px] text-gray-400 font-mono ml-auto flex items-center gap-2",children:[wv(e.timestamp),r&&b&&d("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(Wu,{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&&d("div",{className:"px-4 pb-4 border-t border-gray-100",children:[e.sourceFile&&d("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:_=>{_.stopPropagation(),navigator.clipboard.writeText(e.sourceFile),u(!0),setTimeout(()=>u(!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:p?n(Nt,{className:"w-3.5 h-3.5 text-green-500"}):n(Et,{className:"w-3.5 h-3.5"})})]}),e.sessionResult&&n(Pv,{result:e.sessionResult}),e.stats.errors>0&&((k=e.stats.errorMessages)==null?void 0:k.length)>0&&d("div",{className:"my-2 bg-red-50 border border-red-200 rounded-md p-3",children:[d("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((_,S)=>n("li",{className:"break-words",children:_},S))})]}),e.conversationSnippet&&n(kv,{snippet:e.conversationSnippet}),N&&n(Av,{changes:e.ruleChanges}),e.context&&n(_v,{context:e.context}),e.entries.map((_,S)=>{if(_.type==="tool_result"&&_.tool_use_id&&h.has(_.tool_use_id))return null;const j=_.type==="tool_call"&&_.tool_use_id?m[_.tool_use_id]:void 0;return n(Cv,{entry:_,pairedResult:j},`${e.id}-${S}`)})]})]})}function Pa(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 Tv=Qe(function(){const{agents:t,error:r,search:s,page:a,totalPages:o}=tt(),i=Pt(),l=vu("root"),c=(l==null?void 0:l.isAdmin)??!1,[p,u]=M(s),[m,h]=M(!1),[f,g]=M(0);jt({source:"agent-transcripts-page"});const y=w=>{w.preventDefault(),window.location.href=Pa(1,p)},x=()=>{h(!m),g(w=>w+1)};return r?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("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:d("div",{className:"px-20 py-12 font-sans",children:[d("div",{className:"mb-8",children:[d("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(Yu,{className:"w-5 h-5"})}),n(cs,{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"})]}),d("div",{className:"flex items-center gap-4 mb-6",children:[d("form",{onSubmit:y,className:"relative flex-1 max-w-md",children:[n(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),n("input",{type:"text",value:p,onChange:w=>u(w.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:m?"Collapse All":"Expand All"})]}),d("div",{className:"text-sm text-gray-500 mb-4",children:["Page ",a," of ",o,s&&d("span",{children:[" ","matching “",s,"”",n(Ce,{to:"/agent-transcripts",className:"text-[#005C75] hover:underline ml-2",children:"Clear"})]})]}),t.length===0?d("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(cs,{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(w=>n(jv,{agent:w,defaultOpen:m,isAdmin:c},w.id))},f),o>1&&d("div",{className:"flex items-center justify-center gap-3 mt-8",children:[d("a",{href:a>1?Pa(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(Uu,{className:"w-4 h-4"}),"Prev"]}),d("span",{className:"text-sm text-gray-500 font-mono",children:[a," / ",o]}),d("a",{href:a<o?Pa(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(Xt,{className:"w-4 h-4"})]})]})]})})}),Mv=Object.freeze(Object.defineProperty({__proto__:null,default:Tv,loader:xv,meta:yv},Symbol.toStringTag,{value:"Module"}));async function $v({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=Fb(s);a&&console.log("[editor-commit] Initialized new git repository"),Lb(s),console.log("[editor-commit] Staged all changes");const o=zb(s,r);console.log(`[editor-commit] Created commit: ${o}`);try{const{broadcastHideResults:i}=await Promise.resolve().then(()=>Y0);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 Iv=Object.freeze(Object.defineProperty({__proto__:null,action:$v},Symbol.toStringTag,{value:"Module"}));async function Rv(){const e=Ne()||process.cwd(),t=L.join(e,".codeyam","glossary.json");let r;try{const S=K.readFileSync(t,"utf8");r=_o(JSON.parse(S))}catch{return Response.json({components:[],functions:[],summary:{totalComponents:0,componentsOk:0,componentsMissing:0,componentsWithErrors:0,totalFunctions:0,functionsOk:0,functionsMissing:0,functionsFailing:0,functionsNameMismatch:0,allPassing:!0}})}if(r.length===0)return Response.json({components:[],functions:[],summary:{totalComponents:0,componentsOk:0,componentsMissing:0,componentsWithErrors:0,totalFunctions:0,functionsOk:0,functionsMissing:0,functionsFailing:0,functionsNameMismatch:0,allPassing:!0}});const s=L.join(e,".codeyam","editor-step.json");let a=null;try{const S=K.readFileSync(s,"utf8");a=JSON.parse(S).featureStartedAt||null}catch{}let o;const i=await Fe();if(i)try{const{project:S}=await Re(i),$=await Te().selectFrom("editor_scenarios").select(["name","component_name","component_path","page_file_path","url","display_name"]).where("project_id","=",S.id).orderBy("created_at","asc").execute(),R=vt($,P=>`${P.name}::${P.url||"/"}`).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})),I=await Gn({projectRoot:e,scenarioInputs:R});Object.keys(I.entityChangeStatus).length>0&&(o=I.entityChangeStatus)}catch{}const l=ky({featureStartedAt:a,entityChangeStatus:o});a=l.featureStartedAt,o=l.entityChangeStatus;const c=Ey(r,o),{components:p,functions:u}=Cy(c);let m={},h={};if(i)try{const{project:S}=await Re(i),j=Te();m=await Wi(j,S.id,a);const $=await Ji(j,S.id,a);for(const[T,R]of Object.entries($)){const I=c.find(P=>P.filePath===T);I&&(m[I.name]=(m[I.name]||0)+R)}if(a&&o){const T=await Wi(j,S.id,null),R=await Ji(j,S.id,null);h={...T};for(const[I,P]of Object.entries(R)){const H=c.find(W=>W.filePath===I);H&&(h[H.name]=(h[H.name]||0)+P)}}}catch{}const f={};try{const S=process.env.CODEYAM_ROOT_PATH||process.cwd(),j=await rd(S);for(const[,$]of Object.entries(j)){if($.errors.length===0)continue;const T=$.scenarioName,R=T.indexOf(" - "),I=R>=0?T.slice(0,R):T;I&&(f[I]||(f[I]=[]),f[I].push(...$.errors))}}catch{}const g={};for(const S of u)S.testFile&&(g[S.testFile]=K.existsSync(L.join(e,S.testFile)));const y={};for(const S of u)if(!(!S.testFile||!g[S.testFile]))try{const j=await Nd(e,S.testFile),$=j.status==="passed",T=j.testCases.some(R=>R.fullName.startsWith(S.name));y[S.testFile]={passing:$,hasEntityNameDescribe:T,...j.status==="error"&&j.errorMessage?{errorMessage:j.errorMessage}:{}}}catch(j){y[S.testFile]={passing:!1,hasEntityNameDescribe:!1,errorMessage:j.message||"Unknown test runner error"}}const x=new Set(r.map(S=>S.filePath)),w=[];if(i)try{const{project:S}=await Re(i),$=await Te().selectFrom("editor_scenarios").select(["component_name","component_path","page_file_path"]).where("project_id","=",S.id).execute(),T=new Map;for(const R of $){const I=R,P=I.component_path||I.page_file_path;if(!P)continue;const H=T.get(P);H?H.count++:T.set(P,{name:I.component_name||L.basename(P,L.extname(P)),count:1})}for(const[R,I]of T)x.has(R)||w.push({name:I.name,filePath:R,scenarioCount:I.count})}catch{}const b=_y({components:p,functions:u,scenarioCounts:m,testFileExistence:g,testResults:y,clientErrors:f,totalScenarioCounts:h,entityChangeStatus:o});b.missingFromGlossary=w,w.length>0&&(b.summary.allPassing=!1,b.summary.missingFromGlossary=w.length);let v=[];if(i)try{const{project:S}=await Re(i),j=Te();v=await Ay(j,S.id,a)}catch{}if(b.incompleteEntities=v,v.length>0){b.summary.allPassing=!1,b.summary.incompleteEntities=v.length;const S=v.filter(j=>j.preExisting).length;S>0&&(b.summary.preExistingIncompleteEntities=S)}let N=[];if(i)try{const{project:S}=await Re(i),j=Te();N=await Py(j,S.id,a)}catch{}b.miscategorizedScenarios=N,N.length>0&&(b.summary.allPassing=!1,b.summary.miscategorizedScenarios=N.length);let C=[];if(i)try{const{project:S}=await Re(i),j=Te();C=await jy(j,S.id,a)}catch{}b.unassociatedScenarios=C,C.length>0&&(b.summary.allPassing=!1,b.summary.unassociatedScenarios=C.length);let E=[];if(i&&o&&Object.keys(o).length>0)try{const{project:S}=await Re(i),$=await Te().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","=",S.id).execute(),T=a?Ar(a):null,R=$.map(I=>({name:I.name,entityName:nn({componentName:I.component_name,pageFilePath:I.page_file_path,url:I.url}),updatedInSession:T?ko({created_at:I.created_at,updated_at:I.updated_at},T):!1}));E=hd({scenarios:R,entityChangeStatus:o})}catch{}b.scenariosNeedingRecapture=E,E.length>0&&(b.summary.allPassing=!1,b.summary.scenariosNeedingRecapture=E.length);const k=[],_=Ty(r);for(const[S,j]of _)k.push({name:S,filePaths:j.map($=>$.filePath)});return b.duplicateNames=k,Response.json(b)}const Dv=Object.freeze(Object.defineProperty({__proto__:null,loader:Rv},Symbol.toStringTag,{value:"Module"}));async function Ov({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(!sl(r))return Response.json({error:"Process not running",pid:r},{status:404});try{process.kill(r,s)}catch(u){return Response.json({error:"Failed to kill process",pid:r,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,l=500,c=Date.now();let p=!0;for(;p&&Date.now()-c<i;)await new Promise(u=>setTimeout(u,l)),p=sl(r);if(p){console.warn(`Process ${r} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(r,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${r}:`,u)}}if(a)try{await Kt({commitSha:a,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${r} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:r,signal:s,message:`Process ${r} killed successfully`,waitedMs:Date.now()-c})}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 sl(e){try{return process.kill(e,0),!0}catch{return!1}}const Fv=Object.freeze(Object.defineProperty({__proto__:null,action:Ov},Symbol.toStringTag,{value:"Module"})),Lv=_s(import.meta.url),zv=ee.dirname(Lv),Bv=ee.resolve(zv,"../../../../src/utils/ruleReflection/__tests__/fixtures/captured");function Yv(e){const t=[],r=new Set;for(const s of e.split(`
|
|
408
|
-
`)){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 c=l;if(c.type!=="tool_use")continue;const p=String(c.name||""),u=c.input||{};if(p==="Write"||p==="Edit"){const m=String(u.file_path||"");if(m.includes(".claude/rules/")){const h=m.replace(/^.*?(\.claude\/rules\/)/,"$1"),f=`${p}:${h}`;r.has(f)||(r.add(f),t.push({action:p==="Write"?"created":"modified",filePath:h}))}}else if(p==="Bash"){const m=String(u.command||"");if(m.includes("codeyam memory touch")){const h=`touch:${m}`;r.has(h)||(r.add(h),t.push({action:"touched",filePath:m}))}}}}return t}async function Uv({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 Cd(),a=s?ee.join(ss,s):null;let o=a?ee.join(a,`${r}.log`):"";if((!o||!xt(o))&&(o=ee.join(ss,`${r}.log`)),!xt(o))return Response.json({error:`Log file not found: ${r}.log`},{status:404});const i=await Ra(o,"utf-8");let l=a?ee.join(a,`${r}.context`):"";(!l||!xt(l))&&(l=ee.join(ss,`${r}.context`));let c=null;if(xt(l))try{c=await Ra(l,"utf-8")}catch{}const p=Yv(i),m=c?["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=>c.toLowerCase().includes(x)):!1,h=r.endsWith("-stale")?"-stale":r.endsWith("-conversation")?"-conv":r.endsWith("-interruption")?"-int":"",f=r.slice(0,8)+h,g=ee.join(Bv,f);await mp(g,{recursive:!0}),await dr(ee.join(g,"agent-log.jsonl"),i),c&&await dr(ee.join(g,"context.md"),c),await dr(ee.join(g,"rule-changes.json"),JSON.stringify(p,null,2)),await dr(ee.join(g,"metadata.json"),JSON.stringify({sessionId:r,capturedAt:new Date().toISOString(),hasConfusion:m,ruleChangeCount:p.length},null,2));const y=ee.relative(process.cwd(),g);return console.log(`[api.save-fixture] Saved fixture to ${y}`),Response.json({success:!0,fixturePath:y})}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 Wv=Object.freeze(Object.defineProperty({__proto__:null,action:Uv},Symbol.toStringTag,{value:"Module"}));async function Jv({params:e}){const t=e["*"];if(!t)return new Response("Screenshot path is required",{status:400});const r=Ne();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 Pe.access(s);const a=await Pe.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 Hv=Object.freeze(Object.defineProperty({__proto__:null,loader:Jv},Symbol.toStringTag,{value:"Module"})),al={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 Go({type:e,className:t=""}){const r=al[e]||al.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 Vv={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 Zr({variant:e,pid:t,label:r,className:s=""}){const a=Vv[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 ol=!1;function Gv(){if(ol)return;const e=document.createElement("style");e.textContent=`
|
|
409
|
-
@keyframes strongPulse {
|
|
410
|
-
0%, 100% { opacity: 0.2; }
|
|
411
|
-
50% { opacity: 1; }
|
|
412
|
-
}
|
|
413
|
-
`,document.head.appendChild(e),ol=!0}function Ko({size:e="medium",className:t=""}){typeof document<"u"&&Gv();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 d("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 Kv=()=>[{title:"Activity - CodeYam"},{name:"description",content:"View analysis activity and queue status"}];async function qv({request:e,context:t,params:r}){var J,Y,z,A,B,G,q,Q;let s=t.analysisQueue;s||(s=await Ut());const a=new URL(e.url),o=parseInt(a.searchParams.get("page")||"1",10),i=20,l=r.tab||"current";if(!s)return X({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 c=s.getState(),p=await Fe();let u=null;if(p&&((J=c==null?void 0:c.currentlyExecuting)!=null&&J.commitSha)){const{project:U,branch:D}=await Re(p),O=await hs({projectId:U.id,branchId:D.id,shas:[c.currentlyExecuting.commitSha]});u=O&&O.length>0?O[0]:null}else u=await Wn();const m=async U=>{const D=await xn(U);if(!D)return null;const{getAnalysesForEntity:O}=await Promise.resolve().then(()=>Dh),V=await O(U,!1);return{...D,analyses:V||[]}},h=await Promise.all(((c==null?void 0:c.jobs)||[]).map(async U=>{const D=[];if(U.entityShas&&U.entityShas.length>0){const O=U.entityShas.map(ne=>m(ne)),V=await Promise.all(O);D.push(...V.filter(ne=>ne!==null))}return{...U,entities:D}}));let f=null;if(c!=null&&c.currentlyExecuting){const U=c.currentlyExecuting,D=[];if(U.entityShas&&U.entityShas.length>0){const O=U.entityShas.map(ne=>m(ne)),V=await Promise.all(O);D.push(...V.filter(ne=>ne!==null))}f={...U,entities:D}}const g=f?h.filter(U=>U.id!==f.id):h,y=((z=(Y=u==null?void 0:u.metadata)==null?void 0:Y.currentRun)==null?void 0:z.currentEntityShas)||[],w=(await Promise.all(y.map(U=>m(U)))).filter(U=>U!==null),b=[];if(p)try{const{project:U,branch:D}=await Re(p),O=await hs({projectId:U.id,branchId:D.id,limit:100});for(const V of O){const ne=((A=V.metadata)==null?void 0:A.historicalRuns)||[];b.push(...ne)}}catch(U){console.error("[activity.tsx] Failed to load historical runs from commits:",U)}const v=[...b].sort((U,D)=>{const O=U.lastCaptureAt||U.analysisCompletedAt||U.archivedAt||U.createdAt||"";return(D.lastCaptureAt||D.analysisCompletedAt||D.archivedAt||D.createdAt||"").localeCompare(O)}),N=(o-1)*i,C=N+i,E=v.slice(N,C),k=Math.ceil(v.length/i),_=await Promise.all(E.map(async U=>{const D=U.currentEntityShas||[];if(D.length===0)return{...U,entities:[]};const O=await Promise.all(D.map(V=>m(V)));return{...U,entities:O.filter(V=>V!==null)}})),S=!!f,j=g.length,$=v.filter(U=>{const D=!!U.failedAt,O=U.readyToBeCaptured,V=U.capturesCompleted??0,ne=O===void 0?!0:O===0||V>=O;return!D&&!!U.analysisCompletedAt&&ne}),T=new Set(((B=f==null?void 0:f.entities)==null?void 0:B.map(U=>U.sha))||[]),R=$.filter(U=>!(U.currentEntityShas||[]).some(O=>T.has(O))),P=(await Promise.all(R.slice(0,3).map(async U=>{const D=U.currentEntityShas||[];if(D.length===0)return{run:U,entities:[]};const O=await Promise.all(D.map(V=>m(V)));return{run:U,entities:O.filter(V=>V!==null)}}))).flatMap(({run:U,entities:D})=>D.map(O=>({...O,runId:U.id,completedAt:U.lastCaptureAt||U.analysisCompletedAt||U.archivedAt||U.createdAt})));let H=[],W=null,F=null;if((q=(G=u==null?void 0:u.metadata)==null?void 0:G.currentRun)!=null&&q.analysisCompletedAt&&w.length>0){const U=w[0].sha;W=w[0];const D=await js(U);D&&D.length>0&&D[0].scenarios&&(H=D[0].scenarios,F=D[0].status)}return X({state:{...c,jobs:g,currentlyExecuting:f},currentRun:(Q=u==null?void 0:u.metadata)==null?void 0:Q.currentRun,historicalRuns:_,totalHistoricalRuns:v.length,currentPage:o,totalPages:k,projectSlug:p,commitSha:u==null?void 0:u.sha,queueJobs:g,currentlyExecuting:f,currentEntities:w,tab:l,hasCurrentActivity:S,queuedCount:j,recentCompletedEntities:P,hasMoreCompletedRuns:R.length>3,currentEntityScenarios:H,currentEntityForScenarios:W,currentAnalysisStatus:F})}function Qv({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(Ce,{to:o.id==="current"?"/activity":`/activity/${o.id}`,className:`
|
|
414
|
-
relative pb-4 px-2 text-sm transition-colors cursor-pointer
|
|
415
|
-
${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
|
|
416
|
-
`,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:d("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:`
|
|
417
|
-
inline-block w-2 h-2 rounded-full
|
|
418
|
-
${i?"":"bg-gray-400"}
|
|
419
|
-
`,style:i?{backgroundColor:"#005C75"}:{}})]})},o.id)})})})}function Zv({currentlyExecuting:e,currentRun:t,state:r,projectSlug:s,commitSha:a,onShowLogs:o,recentCompletedEntities:i,hasMoreCompletedRuns:l,currentEntityScenarios:c,currentEntityForScenarios:p,currentAnalysisStatus:u}){var I,P,H,W;const[m,h]=M({}),[f,g]=M({isKilling:!1,current:0,total:0}),y=Lt(),x=!!e,w=(e==null?void 0:e.entities)||[],b=!!(t!=null&&t.analysisCompletedAt),v=b&&!!(t!=null&&t.capturePid),N=!b,C=x,E=c||[],{lastLine:k}=zt(s,C);re(()=>{if(!t)return;const F=[t.analyzerPid,t.capturePid].filter(A=>!!A);if(F.length===0)return;let J=!0;const Y=async()=>{try{const B=await(await fetch(`/api/process-status?pids=${F.join(",")}`)).json();if(B.processes&&J){const G={};B.processes.forEach(q=>{G[q.pid]={isRunning:q.isRunning,processName:q.processName}}),h(G)}}catch(A){J&&console.error("Failed to fetch process statuses:",A)}};Y();const z=setInterval(()=>void Y(),5e3);return()=>{J=!1,clearInterval(z)}},[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid]);const[_,S]=M(!1),[j,$]=M(!1);re(()=>{w.length<=3&&_&&S(!1)},[w.length,_]),re(()=>{i.length<=3&&j&&$(!1)},[i.length,j]);const T=_?w:w.slice(0,3),R=w.length>3;return d("div",{className:"flex flex-col gap-[45px]",children:[C?d("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[d("div",{className:"flex items-center gap-2 mb-[15px]",children:[n(kt,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),n("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:v?"Capturing...":"Analyzing..."})]}),T.map(F=>d("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:[d("div",{className:"flex items-center gap-3",children:[n("div",{children:n(dt,{type:F.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col gap-[1px]",children:[d("div",{className:"flex items-center gap-[14px]",children:[n(Ce,{to:`/entity/${F.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:F.name}),F.entityType&&n(Go,{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&&!_&&d("button",{onClick:()=>S(!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:["+",w.length-3," more"," ",w.length-3===1?"entity":"entities"]}),_&&R&&n("button",{onClick:()=>S(!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"}),v&&E&&E.length>0&&p&&n("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:E.map(F=>{var q,Q,U,D;if(!F.id)return null;const J=(Q=(q=F.metadata)==null?void 0:q.screenshotPaths)==null?void 0:Q[0],Y=(U=F.metadata)==null?void 0:U.noScreenshotSaved,z=J&&!Y,A=(D=u==null?void 0:u.scenarios)==null?void 0:D.find(O=>O.name===F.name),G=A&&A.screenshotStartedAt&&!A.screenshotFinishedAt||!z&&!Y;return n(Ce,{to:`/entity/${p.sha}/scenarios/${F.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:G?"#f9f9f9":void 0,borderColor:G?"#efefef":"#ccc"},children:z?n(rt,{screenshotPath:J,alt:F.name,className:"w-full h-full object-contain bg-gray-100"}):G?n("div",{className:"w-full h-full flex items-center justify-center",children:n(Ko,{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)})}),k&&n("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:k}),n("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((t==null?void 0:t.analyzerPid)||(t==null?void 0:t.capturePid))&&d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center gap-2",children:[d("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(t==null?void 0:t.analyzerPid)&&n(Zr,{variant:"analyzer",pid:t.analyzerPid}),(t==null?void 0:t.analyzerPid)&&(N||((I=m[t.analyzerPid])==null?void 0:I.isRunning))&&n(Zr,{variant:"running"}),(t==null?void 0:t.capturePid)&&n(Zr,{variant:"capture",pid:t.capturePid}),(t==null?void 0:t.capturePid)&&(v||((P=m[t.capturePid])==null?void 0:P.isRunning))&&n(Zr,{variant:"running"})]}),(((H=m[t==null?void 0:t.analyzerPid])==null?void 0:H.isRunning)||((W=m[t==null?void 0:t.capturePid])==null?void 0:W.isRunning))&&n("button",{onClick:()=>{const F=[t==null?void 0:t.analyzerPid,t==null?void 0:t.capturePid].filter(z=>{var A;return!!z&&((A=m[z])==null?void 0:A.isRunning)});if(F.length===0)return;const J=F.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${J})?`))return;g({isKilling:!0,current:1,total:F.length}),(async()=>{for(let z=0;z<F.length;z++){const A=F[z];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:A,commitSha:a||""})})}catch(B){console.error(`Failed to kill process ${A}:`,B)}z<F.length-1&&g({isKilling:!0,current:z+2,total:F.length})}g({isKilling:!1,current:0,total:0}),y.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"})]})]}):d("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:[d("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(Wl,{size:24,style:{color:"#005C75"}})}),d("div",{children:[n("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),d("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",n(Ce,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",n(Ce,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),d(Ce,{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&&d("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"}),d("div",{className:"flex flex-col gap-4",children:[(j?i:i.slice(0,3)).map(F=>{var z;const J=(z=F.analyses)==null?void 0:z[0],Y=(J==null?void 0:J.scenarios)||[];return J==null||J.status,n("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:d("div",{className:"flex flex-col gap-[15px]",children:[d("div",{className:"flex items-center",children:[n("div",{className:"flex-shrink-0",children:n(dt,{type:F.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[d("div",{className:"flex items-center gap-[5px]",children:[n(Ce,{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:A=>{A.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:A=>{A.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),n("div",{className:"border-t border-gray-200 mx-[-15px]"}),Y.length>0?n("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:Y.map(A=>{var Q,U,D;if(!A.id)return null;const B=(U=(Q=A.metadata)==null?void 0:Q.screenshotPaths)==null?void 0:U[0],G=(D=A.metadata)==null?void 0:D.noScreenshotSaved,q=B&&!G;return d("div",{className:"shrink-0 flex flex-col gap-2",children:[n(Ce,{to:`/entity/${F.sha}/scenarios/${A.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:q?"#f3f4f6":"#FAFAFA",borderColor:q?"#d1d5db":"#BCCDD3",borderStyle:q?"solid":"dashed"},onMouseEnter:O=>{q&&(O.currentTarget.style.borderColor="#005C75",O.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:O=>{O.currentTarget.style.borderColor=q?"#d1d5db":"#BCCDD3",O.currentTarget.style.boxShadow="none"},children:q?n(rt,{screenshotPath:B,alt:A.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:A.name})]},A.id)})}):n("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},F.sha)}),i.length>3&&!j&&d("button",{onClick:()=>$(!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"]}),j&&i.length>3&&n("button",{onClick:()=>$(!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 Xv({queueJobs:e,state:t,currentRun:r}){if(!e||e.length===0)return d("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:[d("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(Hu,{size:24,style:{color:"#005C75"}})}),d("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."})]})]}),d(Ce,{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]=M(null),[o,i]=M(null),[l,c]=M(null),[p,u]=M(!1),[m,h]=M(!1),[f,g]=M(new Set),y=Lt();re(()=>{e.length<=3&&m&&h(!1)},[e.length,m]);const x=E=>{a(E)},w=(E,k)=>{E.preventDefault(),i(k)},b=async(E,k)=>{if(E.preventDefault(),!s){i(null);return}const _=e.findIndex($=>$.id===s);if(_===-1){a(null),i(null);return}if(_===k){a(null),i(null);return}const S=_<k?"down":"up",j=Math.abs(k-_);u(!0);try{for(let $=0;$<j;$++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:s,direction:S})});y.revalidate()}catch($){console.error("Failed to reorder job:",$)}finally{u(!1),a(null),i(null)}},v=()=>{p||(a(null),i(null))},N=async E=>{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:E})}),window.location.reload()}catch(k){console.error("Failed to cancel job:",k)}},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(E){console.error("Failed to cancel jobs:",E)}};return d("div",{children:[d("div",{className:"flex items-center justify-between mb-4",children:[d("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"})]}),d("div",{className:"flex flex-col gap-3",children:[(m?e:e.slice(0,3)).map(E=>{var R,I,P,H;const k=e.findIndex(W=>W.id===E.id),_=l===k,S=s===E.id,j=o===k,$=f.has(E.id),T=((R=E.entities)==null?void 0:R.length)>0?$?E.entities:E.entities.slice(0,3):[];return d("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:S||p?.5:1,transform:j&&s!==null&&!S?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:p?"not-allowed":S?"grabbing":"grab"},onMouseEnter:()=>c(k),onMouseLeave:()=>c(null),draggable:!p,onDragStart:W=>{x(E.id),W.dataTransfer.effectAllowed="move"},onDragOver:W=>w(W,k),onDrop:W=>void b(W,k),onDragEnd:v,children:[d("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[n(Vu,{size:16,style:{color:"#005C75"}}),d("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",k+1]})]}),d("div",{className:"flex flex-col gap-2 mt-8",children:[T.length>0?d(xe,{children:[T.map(W=>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:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{children:n(dt,{type:W.entityType||"other",size:"large"})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(Ce,{to:`/entity/${W.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:W.name}),W.entityType&&n(Go,{type:W.entityType})]}),n("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:W.filePath})]})]})})},W.sha)),((I=E.entities)==null?void 0:I.length)>3&&n("button",{onClick:()=>{g(W=>{const F=new Set(W);return F.has(E.id)?F.delete(E.id):F.add(E.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:$?"Show less":`+${E.entities.length-3} more ${E.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:d("div",{className:"flex items-center gap-3 flex-1",children:[n("div",{style:{transform:"scale(1.0)"},children:n(ds,{size:18,style:{color:"#8e8e8e"}})}),d("div",{className:"flex-1",children:[n("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((P=E.entityNames)==null?void 0:P[0])||(E.type==="analysis"?"Analysis Job":E.type==="recapture"?"Recapture Job":E.type==="debug-setup"?"Debug Setup":E.type.charAt(0).toUpperCase()+E.type.slice(1))}),n("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((H=E.filePaths)==null?void 0:H[0])||(E.filePaths&&E.filePaths.length>1?`${E.filePaths.length} files`:E.entityShas&&E.entityShas.length>0?`${E.entityShas.length} ${E.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),d("div",{className:"flex items-center justify-end gap-2 mt-1",children:[_&&n("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:n(Gu,{size:20})}),n("button",{onClick:()=>void N(E.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"})]})]})]},E.id)}),e.length>3&&!m&&d("button",{onClick:()=>h(!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"]}),m&&e.length>3&&n("button",{onClick:()=>h(!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 eN({historicalRuns:e,totalHistoricalRuns:t,currentPage:r,totalPages:s,tab:a,onShowLogs:o}){if(t===0)return d("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:[d("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(Ku,{size:24,style:{color:"#005C75"}})}),d("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."})]})]}),d(Ce,{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]=M(!1),c=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(m=>{c.push({...m,runCreatedAt:u.createdAt})})});const p=i?c:c.slice(0,3);return d("div",{className:"flex flex-col gap-4",children:[p.map(u=>{var g;const m=(g=u.analyses)==null?void 0:g[0],h=(m==null?void 0:m.scenarios)||[],f=!u.isUncommitted;return d("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[d("div",{className:"flex items-start justify-between mb-3",children:[d("div",{className:"flex items-start gap-3 flex-1",children:[n("div",{children:n(dt,{type:u.entityType||"other",size:"large"})}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(Ce,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.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:u.filePath,children:u.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"})]}),h.length>0&&d("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[h.slice(0,8).map(y=>{var v,N,C;if(!y.id)return null;const x=(N=(v=y.metadata)==null?void 0:v.screenshotPaths)==null?void 0:N[0],w=(C=y.metadata)==null?void 0:C.noScreenshotSaved,b=x&&!w;return n(Ce,{to:`/entity/${u.sha}/scenarios/${y.id}`,className:"border rounded overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"120px",height:"80px",borderColor:b?"#ccc":"#BCCDD3",borderStyle:b?"solid":"dashed"},children:b?n(rt,{screenshotPath:x,alt:y.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"})},y.id)}),h.length>8&&d("div",{className:"flex items-center justify-center flex-shrink-0",style:{width:"120px",height:"80px",fontSize:"12px",color:"#646464"},children:["+",h.length-8," more"]})]})]},`${u.sha}-${u.runCreatedAt}`)}),c.length>3&&!i&&d("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:["+",c.length-3," more"," ",c.length-3===1?"entity":"entities"]}),i&&c.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 tN=Qe(function(){const t=tt(),r=Bl(),[s,a]=M(!1);jt({source:"activity-page"});const o=r.tab||"current";return t?d("div",{className:"px-20 py-12",children:[d("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(Qv,{activeTab:o,hasCurrentActivity:t.hasCurrentActivity,queuedCount:t.queuedCount,historicCount:t.totalHistoricalRuns}),o==="current"&&n(Zv,{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(Xv,{queueJobs:t.queueJobs,state:t.state,currentRun:t.currentRun}),o==="historic"&&n(eN,{historicalRuns:t.historicalRuns,totalHistoricalRuns:t.totalHistoricalRuns,currentPage:t.currentPage,totalPages:t.totalPages,tab:o,onShowLogs:()=>a(!0)}),s&&t.projectSlug&&n(qt,{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..."})})})}),nN=Object.freeze(Object.defineProperty({__proto__:null,default:tN,loader:qv,meta:Kv},Symbol.toStringTag,{value:"Module"}));async function Td(e,t,r){var N,C;await ze();const s=await Yt({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=Ne();if(!a)throw new Error("Project root not found");const o=L.join(a,".codeyam","config.json"),i=JSON.parse(K.readFileSync(o,"utf8")),{projectSlug:l}=i;if(!l)throw new Error("Project slug not found in config");const c=Is(l);try{K.writeFileSync(c,"","utf8")}catch{}const{project:p}=await Re(l),u=((N=p.metadata)==null?void 0:N.packageManager)||"npm",m=3112,h=At(l),f=((C=p.metadata)==null?void 0:C.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${l}`);const g=i.environmentVariables||[],y=Km({filePath:s.filePath,webapps:f,environmentVariables:g,port:m,packageManager:u});await Un(e,E=>{if(E&&(E.readyToBeCaptured=!0,E.scenarios))for(const k of E.scenarios)(!t||k.name===t)&&(delete k.screenshotStartedAt,delete k.screenshotFinishedAt,delete k.interactiveStartedAt,delete k.interactiveFinishedAt,delete k.error,delete k.errorStack)});const{jobId:x}=r.enqueue({type:"debug-setup",commitSha:s.commit.sha,projectSlug:l,analysisId:e,scenarioId:t,prepOnly:!0}),w=y.startCommand,b={title:"Debug Setup In Progress",sections:[{heading:"Status",items:[{content:"Setting up debug environment... This may take a minute."},{label:"Project Path",content:h}]},{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 ${h}`,isCode:!0},{label:"2. Start the development server (copy & paste this exact command)",content:w,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${m}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:x,analysisId:e,scenarioId:t,projectPath:h,projectSlug:l,port:m,packageManager:u,framework:y.framework,instructions:b}}async function rN({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 X({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 Ut()),!o)return X({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:s,scenarioId:a});try{const i=await Td(s,a,o);return X({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),X({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function sN({request:e,context:t}){if(e.method!=="POST")return X({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Ut()),!r)return X({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("scenarioId");if(!a)return X({error:"Missing required field: analysisId"},{status:400});const i=await Td(a,o,r);return X({...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),X({error:"Failed to setup debug environment",details:a},{status:500})}}const aN=Object.freeze(Object.defineProperty({__proto__:null,action:sN,loader:rN},Symbol.toStringTag,{value:"Module"}));function oN({request:e}){const r=new URL(e.url).searchParams.get("path");if(!r)return new Response("Missing path parameter",{status:400});const s=Ne()||process.cwd(),a=L.resolve(s,r);if(!a.startsWith(s+L.sep)&&a!==s)return new Response("Path outside project root",{status:403});try{const o=K.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 iN=Object.freeze(Object.defineProperty({__proto__:null,loader:oN},Symbol.toStringTag,{value:"Module"})),lN=process.env.LABS_UNLOCK_SALT||"codeyam-labs-default-salt";function Md(e){const t=gp("sha256",lN);return t.update(e),`CY-${t.digest("hex").slice(0,16)}`}function cN(e,t){return t===Md(e)}async function dN({request:e}){if(e.method!=="POST")return X({error:"Method not allowed"},{status:405});try{const r=(await e.formData()).get("unlockCode");if(!r)return X({success:!1,error:"Unlock code is required"},{status:400});const s=await Fe();return s?cN(s,r)?(await Dn({projectSlug:s,metadataUpdate:{labs:{accessGranted:!0,simulations:!0}}}),X({success:!0})):X({success:!1,error:"Invalid unlock code"},{status:400}):X({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("[Labs Unlock] Error:",t),X({success:!1,error:"Failed to validate unlock code. Please try again."},{status:500})}}const uN=Object.freeze(Object.defineProperty({__proto__:null,action:dN},Symbol.toStringTag,{value:"Module"}));async function pN({request:e,context:t}){if(e.method!=="POST")return X({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Ut()),!r)return X({error:"Queue not initialized"},{status:500});try{const s=await e.formData(),a=s.get("analysisId"),o=s.get("defaultWidth");if(!a||!o)return X({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(o,10);if(isNaN(i)||i<320||i>3840)return X({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 Vb(a,i,r);return console.log("[API] Recapture queued",l),X({success:!0,message:"Recapture queued",...l})}catch(s){return console.log("[API] Error during recapture:",s),X({error:"Failed to recapture screenshots",details:s instanceof Error?s.message:String(s)},{status:500})}}const mN=Object.freeze(Object.defineProperty({__proto__:null,action:pN},Symbol.toStringTag,{value:"Module"}));function hN(e){if(e.length===0)throw new Error("paths array must not be empty");return e.map(fN).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 fN(e){const r=e.replace(/\/+$/,"").split("/");for(;r.length>0;){const s=r[r.length-1];if(gN(s))r.pop();else break}return r.join("/")}function gN(e){return!!(e.includes("*")||/\.\w+$/.test(e))}function yN({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=hN(r),a=s?`.claude/rules/${s}/`:".claude/rules/";return Response.json({result:a})}const xN=Object.freeze(Object.defineProperty({__proto__:null,loader:yN},Symbol.toStringTag,{value:"Module"}));function bN(e,t){var i,l,c,p,u;const r=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,s=e.analyses&&e.analyses.length>0&&e.analyses.some(m=>m.scenarios&&m.scenarios.length>0);if(!r){const m=!!((l=e.metadata)!=null&&l.previousVersionWithAnalyses),h=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return m||h?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=!!((c=e.metadata)!=null&&c.previousCommittedSha);if(!!((p=e.metadata)!=null&&p.previousVersionWithAnalyses)||a){const m=s&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return s&&!m?{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 wN(e){return bN(e).hasOutdatedSimulations}function Ks(e,t,r,s,a){var W,F,J,Y,z,A,B,G;const o=(W=t==null?void 0:t.scenarios)==null?void 0:W.find(q=>q.name===e.name),i=!!(o!=null&&o.startedAt),l=!!(o!=null&&o.screenshotStartedAt),c=!!(o!=null&&o.screenshotFinishedAt),p=!!(o!=null&&o.finishedAt),u=1800*1e3,m=l&&!c&&(o==null?void 0:o.screenshotStartedAt)&&Date.now()-new Date(o.screenshotStartedAt).getTime()>u,h=!!((J=(F=e.metadata)==null?void 0:F.screenshotPaths)!=null&&J[0])||!!((Y=e.metadata)!=null&&Y.executionResult),f=l&&!c,g=o==null?void 0:o.error,y=(A=(z=e.metadata)==null?void 0:z.executionResult)==null?void 0:A.error,x=[];if(t!=null&&t.errors&&t.errors.length>0)for(const q of t.errors)x.push({source:`${q.phase} phase`,message:q.message});if(t!=null&&t.steps)for(const q of t.steps)q.error&&x.push({source:q.name,message:q.error});const w=!h&&!g&&!y&&x.length>0,b=!!(g||y||m||w),v=m?"Capture timed out after 30 minutes":(typeof g=="string"?g:null)||(y==null?void 0:y.message)||(w?`Analysis error: ${x[0].message}`:null),N=m?"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)||(y==null?void 0:y.stack)||null,E=(s&&a?a.jobs.some(q=>{var Q;return((Q=q.entityShas)==null?void 0:Q.includes(s))||q.type==="analysis"&&q.entityShas&&q.entityShas.length===0})||((G=(B=a.currentlyExecuting)==null?void 0:B.entityShas)==null?void 0:G.includes(s)):!1)&&!i&&!b||!!(o!=null&&o.analyzing)&&!i&&!b,k=i&&!l&&!p&&!b,_=(E||k||f)&&!b,S=(E||k)&&r===!1&&!h;let j;S?j="crashed":b?j="error":h||p?j="completed":f?j="capturing":k?j="starting":E?j="queued":j="pending";let $="📷",T="pending",R=!1,I=`Not captured: ${e.name}`;const P="border-gray-300",H=b||S?"bg-red-50":"bg-white";return b||S?($="⚠️",T="error",I=`Error: ${S?"Analysis process crashed":v||"Unknown error"}`):E?($="⋯",T="queued",I=`Queued: ${e.name}`):k?($="⋯",T="starting",R=!0,I=`Starting server for ${e.name}...`):f&&!b?($="⋯",T="capturing",R=!0,I=`Capturing ${e.name}...`):h&&($="✓",T="completed",I=e.name),{hasError:b||S,errorMessage:S?"Analysis process crashed":v,errorStack:S?"Process terminated unexpectedly before completing analysis":N,isCapturing:f,isCaptured:h,hasCrashed:S,isAnalyzing:_,isQueued:E,isServerStarting:k,status:j,icon:$,iconType:T,shouldSpin:R,title:I,borderColor:P,bgColor:H}}function $d({scenario:e,entitySha:t,size:r="medium",showBorder:s=!0,isOutdated:a=!1}){var N,C,E,k,_,S;const o=Ks(e,void 0,void 0,t,void 0),i=(N=e.metadata)==null?void 0:N.executionResult,l=!!i,p=(((E=(C=e.metadata)==null?void 0:C.data)==null?void 0:E.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,m=((_=(k=i==null?void 0:i.sideEffects)==null?void 0:k.consoleOutput)==null?void 0:_.length)||0,h=((S=i==null?void 0:i.timing)==null?void 0:S.duration)||0;let f=0;p>0&&f++,p>2&&f++,u&&f++,m>0&&f++,f=Math.min(3,f);const g=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"},w=s?`border-2 ${x.border}`:"",b=Array.from({length:3},(j,$)=>n("div",{className:`w-1 h-1 rounded-full ${$<f?x.icon.replace("text-","bg-"):"bg-gray-300"}`},$)),v=o.hasError?`Error: ${o.errorMessage||"Unknown error"}`:l?`${e.name}
|
|
420
|
-
${p} args → ${u?"value":"void"}${m>0?` (${m} logs)`:""}
|
|
421
|
-
${h}ms`:`Not executed: ${e.name}`;return d(Ce,{to:`/entity/${t}/scenarios/${e.id}`,className:`relative ${g.width} ${g.height} ${w} rounded ${x.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:v,onClick:j=>j.stopPropagation(),children:[n("div",{className:`${x.icon} ${g.iconSize} font-mono font-bold`,children:o.hasError?"⚠":l?"ƒ":"○"}),l&&!o.hasError&&d("div",{className:`flex items-center gap-0.5 ${g.textSize} ${x.badge} px-1 rounded`,children:[n("span",{children:p}),n("span",{children:"→"}),n("span",{children:u?"✓":"∅"})]}),l&&!o.hasError&&r==="medium"&&n("div",{className:"flex gap-0.5 mt-0.5",children:b}),l&&!o.hasError&&h>100&&r==="medium"&&n("div",{className:`absolute top-0.5 right-0.5 ${g.textSize} ${x.badge} px-1 rounded`,children:h>1e3?`${Math.round(h/1e3)}s`:`${h}ms`}),l&&!o.hasError&&m>0&&r==="medium"&&d("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",m]})]})}function Xa({size:e=24,className:t=""}){return d("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 il({scenario:e,entity:t,analysisStatus:r,queueState:s,processIsRunning:a,size:o="medium",cacheBuster:i,className:l="",viewMode:c}){var y,x;if(t.entityType==="library")return n($d,{scenario:e,entitySha:t.sha,size:o==="small"?"small":"medium"});const u=Ks(e,r,a,t.sha,s),m=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"},h=`relative ${m.containerClass} ${l}`,f=()=>{const w=`/entity/${t.sha}/scenarios/${e.id}`;return c?`${w}/${c}`:w};if(u.isCaptured){const w=(x=(y=e.metadata)==null?void 0:y.screenshotPaths)==null?void 0:x[0];return n(Ce,{to:f(),className:`${h} overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center hover:scale-105 hover:shadow-md`,children:n(rt,{screenshotPath:w,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const g=()=>{const w={size:o==="small"?16:o==="large"?24:20,strokeWidth:2},b=n(Ko,{size:o});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return b;switch(u.iconType){case"starting":case"capturing":return b;case"error":return d("div",{className:"flex flex-col items-center justify-center gap-1",children:[n(Xa,{size:24}),n("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return n(qu,{...w});default:return b}};return n(Ce,{to:f(),className:`${h} ${u.bgColor} flex flex-col items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:u.title,children:n("div",{className:m.iconSize,children:g()})})}const Tn=70;function vN({scenarios:e,hiddenScenarios:t=[],analysis:r,selectedScenario:s,entitySha:a,cacheBuster:o,activeTab:i,entityType:l,entity:c,queueState:p,processIsRunning:u,isEntityAnalyzing:m,areScenariosStale:h,viewMode:f,setViewMode:g,isBreakdownView:y}){var R,I,P,H,W,F;const x=ge(null),[w,b]=M(new Set),[v,N]=M(!1);re(()=>{x.current&&i==="scenarios"&&x.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[s==null?void 0:s.id,i]);const C=J=>`/entity/${a}/scenarios/${J}`,E=J=>{b(Y=>{const z=new Set(Y);return z.has(J)?z.delete(J):z.add(J),z})},k=(J,Y=2)=>{const A=J.split(`
|
|
422
|
-
`).slice(0,Y).join(" ").trim();return A.length>Tn?A.substring(0,Tn-3):(J.split(`
|
|
423
|
-
`).length>Y||J.length>A.length,A)},_=ae(()=>{var Y;if(!((Y=r==null?void 0:r.metadata)!=null&&Y.executionFlows)||!(r!=null&&r.scenarios))return null;const J=r.scenarios.filter(z=>{var A;return!((A=z.metadata)!=null&&A.sameAsDefault)});return Wo(r.metadata.executionFlows,J)},[r]),S=(_==null?void 0:_.totalFlows)||0,j=(_==null?void 0:_.coveredFlows)||0,$=(_==null?void 0:_.coveragePercentage)||0;(R=c==null?void 0:c.metadata)!=null&&R.defaultWidth||(I=r==null?void 0:r.metadata)!=null&&I.defaultWidth;const T=(P=r==null?void 0:r.status)!=null&&P.finishedAt?new Date(r.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return d("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[r&&e.length>0&&d("div",{className:"flex flex-col gap-2",children:[n("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),d("div",{className:"grid grid-cols-2 gap-2",children:[d(Ce,{to:y?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((H=e[0])==null?void 0:H.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:[d("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round($),"%"]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),d(Ce,{to:y?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((W=e[0])==null?void 0:W.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:[d("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[j,"/",S]}),n("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),d(Ce,{to:y?`/entity/${a}/scenarios/${(s==null?void 0:s.id)||((F=e[0])==null?void 0:F.id)}`:`/entity/${a}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${y?"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"}),y?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"})})]})]}),c&&c.filePath&&n("div",{children:n(Ce,{to:`/entity/${a}/create-scenario`,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] no-underline flex items-center justify-center gap-1",children:"+ Create New Scenario"})}),e.length>0&&d("div",{className:"py-3 flex items-center justify-between",children:[d("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),T&&n("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:T})]}),m&&(h||e.length===0)?d("div",{className:"",children:[d("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[d("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((J,Y)=>{const z=!y&&(s==null?void 0:s.id)===J.id,A=w.has(J.id||"");return J.id?d(Ce,{to:C(J.id),ref:z?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${z?"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(il,{scenario:J,entity:{sha:a,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:p,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),d("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${A?"":"line-clamp-1"}`,children:J.name}),J.description&&n("div",{className:"mt-2",children:d("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[A?J.description:k(J.description),!A&&J.description.length>Tn&&d(xe,{children:["...",n("button",{onClick:B=>{B.preventDefault(),B.stopPropagation(),E(J.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),A&&J.description.length>Tn&&n("button",{onClick:B=>{B.preventDefault(),B.stopPropagation(),E(J.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},Y):null})})}),t.length>0&&!(m&&h)&&d("div",{className:"border-t border-[#e1e1e1] pt-3",children:[d("button",{onClick:()=>N(!v),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 ${v?"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,")"]}),v&&d("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((J,Y)=>{const z=!y&&(s==null?void 0:s.id)===J.id,A=w.has(J.id||"");return J.id?d(Ce,{to:`/entity/${a}/scenarios/${J.id}`,ref:z?x:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${z?"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(il,{scenario:J,entity:{sha:a,entityType:l},analysisStatus:r==null?void 0:r.status,queueState:p,processIsRunning:u,size:"large",cacheBuster:o,viewMode:f})}),d("div",{className:"px-3 py-3",children:[n("div",{className:`text-xs font-semibold text-[#343434] ${A?"":"line-clamp-1"}`,children:J.name}),J.description&&n("div",{className:"mt-2",children:d("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[A?J.description:k(J.description),!A&&J.description.length>Tn&&d(xe,{children:["...",n("button",{onClick:B=>{B.preventDefault(),B.stopPropagation(),E(J.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),A&&J.description.length>Tn&&n("button",{onClick:B=>{B.preventDefault(),B.stopPropagation(),E(J.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},Y):null})})]})]})]})}function NN({scenario:e,entitySha:t,onApply:r,onSave:s,onEditMockData:a,onDelete:o,isApplying:i=!1,isSaving:l=!1,saveMessage:c=null,showDeleteConfirm:p=!1,onShowDeleteConfirm:u,isDeleting:m=!1,deleteError:h=null}){const[f,g]=M(""),y=async()=>{await r(f)},x=async w=>{await s(f,w),w||g("")};return d("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[d("div",{className:"border-b border-[#e1e1e1] pb-3",children:[d("div",{className:"flex items-start justify-between mb-2",children:[n("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),n(Ce,{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})]}),d("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[d("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:w=>g(w.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}),d("button",{onClick:()=>void y(),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&&d("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"}),d("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"})]}),c&&n("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${c.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:c}),c==="Recapture successful"&&n("div",{children:n(Ce,{to:`/entity/${t}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),d("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&&d(xe,{children:[p?d("div",{className:"flex flex-col gap-1",children:[d("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),d("div",{className:"flex gap-1",children:[n("button",{onClick:()=>void o(),disabled:m,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:m?"Deleting...":"Yes, Delete"}),n("button",{onClick:()=>u==null?void 0:u(!1),disabled:m,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:()=>u==null?void 0:u(!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"}),h&&n("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:h})]})]})]})}function SN({scenario:e,analysis:t,entity:r}){var i,l,c;const s=((i=e.metadata)==null?void 0:i.executionResult)||null,a=((c=(l=e.metadata)==null?void 0:l.data)==null?void 0:c.argumentsData)||[],o=p=>{var g,y,x;if(!p)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],m=((g=p.sideEffects)==null?void 0:g.consoleOutput)||[];m.length>0&&(u.push(`Console Output: ${m.length} log ${m.length===1?"entry":"entries"} captured`),m.forEach(w=>{u.push(` [${w.level.toUpperCase()}] ${w.args.join(" ")}`)}));const h=((y=p.sideEffects)==null?void 0:y.fileWrites)||[];h.length>0&&(u.push(`
|
|
424
|
-
File System Operations: ${h.length} ${h.length===1?"operation":"operations"} detected`),h.forEach(w=>{u.push(` ${w.operation}: ${w.path}${w.size?` (${w.size} bytes)`:""}`)}));const f=((x=p.sideEffects)==null?void 0:x.apiCalls)||[];return f.length>0&&(u.push(`
|
|
425
|
-
API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(w=>{u.push(` ${w.method} ${w.url}${w.status?` → ${w.status}`:""}${w.duration?` (${w.duration}ms)`:""}`)})),p.error&&u.push(`
|
|
426
|
-
Error: ${p.error.name||"Error"}: ${p.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
|
|
427
|
-
`)};return d("div",{className:"flex w-full h-full gap-0",children:[d("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)})})]}),d("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"})})]}),d("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 cn={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function Xr({scenarioId:e,analysisId:t}){const[r,s]=M(!1),[a,o]=M(!1),[i,l]=M(null),[c,p]=M(!1),u=e||t;if(!u)return null;const m=`/codeyam-diagnose ${u}`,h=async()=>{o(!0);try{const{default:g}=await import("html2canvas-pro"),x=(await g(document.body,{scale:.5})).toDataURL("image/jpeg",.8);l(x),s(!0)}catch(g){console.error("Screenshot capture failed:",g),s(!0)}finally{o(!1)}},f=()=>{s(!1),l(null)};return d(xe,{children:[d("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:cn.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:cn.subtext},children:"Simply run this command in Claude Code:"}),d("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:cn.commandBoxBg,borderColor:cn.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:cn.commandBoxText},children:m}),n("button",{onClick:g=>{g.stopPropagation(),navigator.clipboard.writeText(m),p(!0),setTimeout(()=>p(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:c?"#22c55e":cn.commandBoxText},title:c?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:c?n(Nt,{size:14}):n(Et,{size:14})})]}),d("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 h(),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:cn.link},children:a?"capturing...":"please do so here"}),"."]})]}),n(Zl,{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 ll=1440,es=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],Dt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function Id({selectedScenario:e,analysis:t,entity:r,viewMode:s,cacheBuster:a,hasScenarios:o,isAnalyzing:i=!1,projectSlug:l,hasAnApiKey:c=!0,processIsRunning:p,queueState:u}){var V,ne,ie,we,le,ce,ve,Ee,he,Z,Se;const m=Ue(),[h,f]=M(!1),[g,y]=M(!1),[x,w]=M({name:"Desktop",width:ll,height:900}),[b,v]=M(ll),[N,C]=M(1),{customSizes:E,addCustomSize:k,removeCustomSize:_}=Ls(l),S=ae(()=>[...es,...E],[E]),j=(fe,se)=>{v(fe);const pe=S.find(_e=>_e.width===fe&&_e.height===se);w({name:(pe==null?void 0:pe.name)||"Custom",width:fe,height:se})},$=fe=>{v(fe.width),w({name:fe.name,width:fe.width,height:fe.height})},T=fe=>{k(fe,x.width,x.height??900),y(!1),w(se=>({...se,name:fe}))},R=(fe,se)=>{v(fe);const pe=S.find(_e=>_e.width===fe&&_e.height===se);w(_e=>({name:(pe==null?void 0:pe.name)||"Custom",width:fe,height:_e.height}))},I=(ne=(V=e==null?void 0:e.metadata)==null?void 0:V.screenshotPaths)==null?void 0:ne[0],P=ae(()=>e?Ks(e,t==null?void 0:t.status,p,r==null?void 0:r.sha,u):null,[e,t==null?void 0:t.status,p,r==null?void 0:r.sha,u]),H=ae(()=>{var se,pe;const fe=[];if((se=t==null?void 0:t.status)!=null&&se.errors&&t.status.errors.length>0)for(const _e of t.status.errors)fe.push({source:`${_e.phase} phase`,message:_e.message,stack:_e.stack});if((pe=t==null?void 0:t.status)!=null&&pe.steps)for(const _e of t.status.steps)_e.error&&fe.push({source:_e.name,message:_e.error,stack:_e.errorStack});return fe},[(ie=t==null?void 0:t.status)==null?void 0:ie.errors,(we=t==null?void 0:t.status)==null?void 0:we.steps]),W=(P==null?void 0:P.errorMessage)||null,F=(P==null?void 0:P.errorStack)||null,{interactiveServerUrl:J,isStarting:Y,isLoading:z,showIframe:A,iframeKey:B,onIframeLoad:G}=vn({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"}),q=ae(()=>J||null,[J]),Q=!i&&o&&e&&!((ce=(le=e.metadata)==null?void 0:le.screenshotPaths)!=null&&ce[0])&&((Ee=(ve=t==null?void 0:t.status)==null?void 0:ve.scenarios)==null?void 0:Ee.some(fe=>fe.name===e.name&&fe.screenshotStartedAt&&!fe.screenshotFinishedAt)),{lastLine:U}=zt(l,i||s==="interactive"||Q||!1);if(!e){if(i&&r)return d(xe,{children:[n("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:d("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."}),U&&n("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:U}),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"})]})}),h&&l&&n(qt,{projectSlug:l,onClose:()=>f(!1)})]});if(!o&&r&&!i){if(H.length>0){const fe=H.length===1?((he=H[0])==null?void 0:he.message)||"An error occurred during analysis.":`${H.length} errors occurred during analysis.`;return d(xe,{children:[n("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:d("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded",style:{backgroundColor:Dt.background,border:`2px solid ${Dt.border}`},role:"alert",children:d("div",{className:"flex items-center gap-3",children:[n(Xa,{size:24,className:"shrink-0"}),n("div",{className:"flex-1 min-w-0",children:d("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:Dt.text},children:[n("span",{className:"font-semibold",children:"Analysis Error."})," ",fe," ",n("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:Dt.link},children:"See logs"})," ","for details."]})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Xr,{analysisId:t==null?void 0:t.id})})]})}),h&&l&&n(qt,{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:d("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:()=>{m.submit({entitySha:r.sha,filePath:r.filePath},{method:"post",action:"/api/analyze"})},disabled:m.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:m.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 d(xe,{children:[n("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
|
|
428
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
429
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
430
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
431
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
432
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||Q&&!I)&&!W&&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:d("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[d("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 ${((Z=t==null?void 0:t.scenarios)==null?void 0:Z.length)||0} scenario${((Se=t==null?void 0:t.scenarios)==null?void 0:Se.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${r==null?void 0:r.entityType} entity...`}),e&&d("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),U&&n("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:d("div",{className:"flex items-start gap-3",children:[n("span",{className:"text-xl shrink-0",children:"📝"}),d("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:U,children:U})]})]})}),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"&&(I||W)||s==="interactive"&&(q||Y)||s==="data"?d(xe,{children:[W&&!I&&n("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:d("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[n("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:Dt.background,border:`2px solid ${Dt.border}`,maxHeight:"50vh"},role:"alert",children:d("div",{className:"flex flex-col gap-3",children:[d("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:Dt.text},children:[n(Xa,{size:24,className:"shrink-0"}),n("div",{children:"Capture Error"})]}),d("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:Dt.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:Dt.text},children:W})})]})}),n("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:n(Xr,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})}),s==="interactive"?d("div",{className:"flex-1 flex flex-col min-h-0",children:[q&&d("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(Lg,{presets:[...es],customSizes:E,currentWidth:x.width,currentHeight:x.height??900,scale:N,onSizeChange:j,onSaveCustomSize:()=>y(!0),onRemoveCustomSize:_}),e&&r&&d(Ce,{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"]})]}),q&&n("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:n("div",{style:{maxWidth:`${es[es.length-1].width}px`,width:"100%"},children:n(So,{currentViewportWidth:b,currentPresetName:x.name,onDevicePresetClick:$,devicePresets:S})})}),n(Us,{scenarioId:e.id,scenarioName:e.name,iframeUrl:q,isStarting:Y,isLoading:z,showIframe:A,iframeKey:B,onIframeLoad:G,onScaleChange:C,onDimensionChange:R,projectSlug:l,defaultWidth:x.width,defaultHeight:x.height})]}):s==="data"?n("div",{className:"flex-1 min-h-0",children:n(SN,{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:`${b}px`},children:(I||!W)&&n(rt,{screenshotPath:I,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&&!I?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:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),d("div",{className:"flex-1",children:[n("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),d("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."]}),U&&d("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:U})]}),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"})]})]})})}):W?d("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!c&&n("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:d("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[d("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"})]}),d("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."}),d("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(Ce,{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:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),d("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."}),d("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:W})})]}),F&&d("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(Xr,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})]}):H.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:d("div",{className:"flex items-start gap-4 mb-6",children:[n("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),d("div",{className:"flex-1 min-w-0",children:[n(AnalysisErrorDisplay,{errors:H,title:"Analysis Error",description:H.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${H.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(Xr,{scenarioId:e==null?void 0:e.id,analysisId:t==null?void 0:t.id})})]})]})})}):d("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"})]})})})}),h&&l&&n(qt,{projectSlug:l,onClose:()=>f(!1)}),g&&n(Co,{width:x.width,height:x.height??900,onSave:T,onCancel:()=>y(!1)})]})}function CN({analysis:e,entitySha:t}){Lt();const[r,s]=M(e);re(()=>{s(e)},[e]);const[a,o]=M(null),i=ae(()=>{var m;if(!((m=r==null?void 0:r.metadata)!=null&&m.executionFlows)||!(r!=null&&r.scenarios))return null;const u=r.scenarios.filter(h=>{var f;return!((f=h.metadata)!=null&&f.sameAsDefault)});return Wo(r.metadata.executionFlows,u)},[r]),l=ae(()=>i?cy(i):[],[i]),c=ae(()=>r!=null&&r.scenarios?r.scenarios.filter(u=>{var m;return!((m=u.metadata)!=null&&m.sameAsDefault)}):[],[r]),p=u=>{var h;const m=((h=u.metadata)==null?void 0:h.coveredFlows)||[];return i?i.executionFlows.filter(f=>m.includes(f.id)):[]};return r?!i||i.executionFlows.length===0?n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:d("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:d("div",{className:"p-6 space-y-6",children:[d("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"}),d("div",{className:"grid grid-cols-4 gap-4 text-center",children:[d("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:c.length}),n("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[n("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),n("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[d("div",{className:"text-2xl font-bold text-gray-900",children:[i.coveredFlows,"/",i.totalFlows]}),n("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),d("div",{className:"bg-gray-50 rounded-lg p-3",children:[d("div",{className:`text-2xl font-bold ${i.coveragePercentage===100?"text-green-600":i.coveragePercentage>=50?"text-amber-600":"text-red-600"}`,children:[i.coveragePercentage.toFixed(0),"%"]}),n("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),d("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:d("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",c.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:c.length===0?d("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",n(Ce,{to:`/entity/${t}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):c.map(u=>{var f,g,y;const m=(g=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0],h=p(u);return d("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(rt,{screenshotPath:m,alt:u.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),d("div",{className:"flex-1 min-w-0",children:[n("div",{className:"flex items-start justify-between gap-2",children:d("div",{children:[n(Ce,{to:`/entity/${t}/scenarios/${u.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:u.name}),((y=u.metadata)==null?void 0:y.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:u.description}),h.length>0&&n("div",{className:"flex flex-wrap gap-1 mt-2",children:h.map(x=>n("span",{className:`text-xs px-1.5 py-0.5 rounded ${x.isError?"bg-red-50 text-red-700":x.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:x.name},x.id))})]})]},u.id)})}),n("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:d(Ce,{to:`/entity/${t}/create-scenario`,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 no-underline",children:[n("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),l.length>0&&d("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[d("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[l.length," uncovered execution flow",l.length>1?"s":""," — consider adding scenarios to cover these"]}),d("div",{className:"flex flex-wrap gap-1",children:[l.slice(0,10).map(u=>d("span",{className:`text-xs px-2 py-0.5 rounded ${u.impact==="high"?"bg-red-100 text-red-700":"bg-amber-100 text-amber-700"}`,children:[u.name,u.impact==="high"&&" (high impact)"]},u.id)),l.length>10&&d("span",{className:"text-xs text-amber-600",children:["+",l.length-10," more"]})]})]}),d("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:d("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",i.executionFlows.length,")"]})}),n("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const m=a===u.id,h=u.usedInScenarios.length>0;return d("div",{children:[n("button",{onClick:()=>o(m?null:u.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:d("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?"▼":"▶"}),d("div",{className:"flex-1",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[n("span",{className:"font-medium text-sm text-gray-900",children:u.name}),h?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"}),u.blocksOtherFlows&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),u.impact==="high"&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),u.isError&&n("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),u.description&&n("p",{className:"text-sm text-gray-600 mt-1 m-0",children:u.description})]})]})}),m&&d("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[u.requiredValues.length>0&&d("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:u.requiredValues.map((f,g)=>d("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:f.attributePath}),n("span",{className:"text-gray-400",children:f.comparison}),n("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:f.value})]},g))})]}),h&&d("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:u.usedInScenarios.map(f=>n("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:f.name},f.id))})]}),u.codeSnippet&&d("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:u.codeSnippet})})]})]})]},u.id)})})]})]})}):n("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:d("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 cl({hasIndirectBadge:e,onAnalyze:t}){return d(xe,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:d("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"})]})}),d("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 _N({entity:e,history:t}){const[r,s]=M("entity"),[a,o]=M(new Set),i=t.filter(u=>u.analyses.length>0).length,l=ae(()=>{const u=new Map;return t.forEach(m=>{m.analyses.forEach(h=>{(h.scenarios??[]).filter(g=>{var y;return!((y=g.metadata)!=null&&y.sameAsDefault)}).forEach(g=>{u.has(g.name)||u.set(g.name,[]),u.get(g.name).push({version:m,analysis:h,scenario:g})})})}),Array.from(u.entries()).map(([m,h])=>{var f;return{name:m,description:((f=h[0])==null?void 0:f.scenario.description)||"",versions:h.sort((g,y)=>{const x=new Date(g.analysis.createdAt||0).getTime();return new Date(y.analysis.createdAt||0).getTime()-x})}})},[t]),c=l.length,p=u=>{o(m=>{const h=new Set(m);return h.has(u)?h.delete(u):h.add(u),h})};return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:d("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[n("div",{className:"mb-8",children:d("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[d("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})]}),d("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:c})]})]})}),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"?d("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((u,m)=>d("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]"}),d("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:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center gap-3",children:[u.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"}),d(Ce,{to:`/entity/${u.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:u.sha.substring(0,8)})]})]}),n("span",{className:"text-xs font-medium text-[#8e8e8e] leading-[22px]",children:u.createdAt&&new Date(u.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})})]})}),u.analyses.length>0?n("div",{children:u.analyses.map((h,f)=>{var y;const g=(h.scenarios??[]).filter(x=>{var w;return!((w=x.metadata)!=null&&w.sameAsDefault)});return n("div",{children:g.length===0?n(cl,{hasIndirectBadge:h.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):d(xe,{children:[n("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:d("div",{className:"flex items-center justify-end gap-2",children:[h.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"}),d("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[g.length," scenario",g.length!==1?"s":""]})]})}),((y=h.metadata)==null?void 0:y.scenarioChangesOverview)&&n("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:d("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[d("span",{className:"font-medium",children:["What Changed:"," "]}),h.metadata.scenarioChangesOverview]})}),g.length>0&&n("div",{className:"p-5 bg-white",children:n("div",{className:"flex gap-4 flex-wrap",children:g.map((x,w)=>{var N,C;const b=(C=(N=x.metadata)==null?void 0:N.screenshotPaths)==null?void 0:C[0],v=`${x.name}-${w}`;return d(Ce,{to:`/entity/${u.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:b?n(rt,{screenshotPath:b,alt:x.name,className:"max-w-full max-h-full object-contain rounded-sm"}):d("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})})]},v)})})})]})},h.id||f)})}):n(cl,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.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((u,m)=>{const h=a.has(u.name),f=h?u.versions:u.versions.slice(0,1),g=u.versions.length-1,y=u.versions[0];return y==null||y.version.sha,e==null||e.sha,d("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]"}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("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:u.name}),u.description&&n("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),d("div",{className:"p-5 bg-white",children:[f.map((x,w)=>{var k,_;const{version:b,analysis:v,scenario:N}=x,C=(_=(k=N.metadata)==null?void 0:k.screenshotPaths)==null?void 0:_[0],E=w===0;return d("div",{className:`flex gap-5 items-start ${E?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[n(Ce,{to:`/entity/${b.sha}/scenarios/${N.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(rt,{screenshotPath:C,alt:N.name,className:"max-w-full max-h-full object-contain rounded-sm"}):d("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"})]})}),d("div",{className:"flex-1 flex flex-col gap-2",children:[d("div",{className:"flex items-center gap-2 flex-wrap",children:[b.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"}),E&&u.versions.length>1&&d("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#e0e9ec] text-[#005c75] rounded text-xs font-medium leading-5",children:[u.versions.length," versions"]})]}),d(Ce,{to:`/entity/${b.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:b.sha.substring(0,8)})]}),v.createdAt&&d("p",{className:"text-xs font-medium text-[#8e8e8e] m-0 leading-[22px]",children:["Captured:"," ",new Date(v.createdAt).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1})]}),v.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"})]})]},`${b.sha}-${w}`)}),g>0&&d("button",{onClick:()=>p(u.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 ${h?"rotate-180":""}`,children:n("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),h?"Hide":`${g} previous version${g!==1?"s":""}`]})]})]})]},u.name)})})]})})}function dl({entity:e,analysisInfo:t,from:r}){const s=Ue(),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(Ce,{to:`/entity/${e.sha}${r?`?from=${r}`:""}`,className:"block group cursor-pointer",children:d("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(rt,{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(dt,{type:e.entityType})})}),d("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-1",children:[n(dt,{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&&d("div",{className:"flex items-center gap-2 mt-2",children:[d("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"?d(xe,{children:[d("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"?d("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"})]}):d(xe,{children:[d("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 ul=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 kN({importedEntities:e,importingEntities:t}){const[r]=Ln(),s=r.get("from"),a=Ue(),o=a.state!=="idle",i=e.length>0,l=t.length>0,c=h=>h.filter(f=>f.entityType==="visual"||f.entityType==="library"),p=h=>{const f=c(h);f.length!==0&&a.submit({entityShas:f.map(g=>g.sha).join(",")},{method:"post",action:"/api/analyze"})},u=c(e).length>0,m=c(t).length>0;return n("div",{className:"max-w-[1400px] mx-auto",children:d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-6 py-4 flex items-start justify-between",children:[d("div",{children:[d("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."})]}),u&&n("button",{onClick:()=>p(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(h=>n(dl,{entity:h,analysisInfo:ul(h),from:s},h.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."})})]}),d("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[d("div",{className:"px-6 py-4 flex items-start justify-between",children:[d("div",{children:[d("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."})]}),m&&n("button",{onClick:()=>p(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(h=>n(dl,{entity:h,analysisInfo:ul(h),from:s},h.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 EN({relatedEntities:e}){return n("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:n(kN,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function AN({data:e,defaultExpanded:t=!1,maxDepth:r=3}){return n("div",{className:"font-mono text-sm",children:n(Nr,{data:e,depth:0,defaultExpanded:t,maxDepth:r})})}function Nr({data:e,depth:t,defaultExpanded:r,maxDepth:s,objectKey:a,showInlineToggle:o=!1}){const[i,l]=M(r||t<2);if(re(()=>{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 c=typeof e;if(c==="string")return d("span",{className:"text-green-600",children:['"',e,'"']});if(c==="number")return n("span",{className:"text-blue-600",children:e});if(c==="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:"[]"}):d("span",{children:[d("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:[d("span",{children:[i?"▼":"▶"," ","["]}),!i&&d("span",{children:[e.length,"]"]})]}),i?d(xe,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((p,u)=>n("div",{className:"py-0.5",children:n(Nr,{data:p,depth:t+1,defaultExpanded:r,maxDepth:s})},u))}),n("div",{className:"text-gray-600",children:"]"})]}):null]});if(c==="object"){const p=Object.keys(e);if(p.length===0)return n("span",{className:"text-gray-600",children:"{}"});const u=h=>h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,m=h=>Array.isArray(h)&&h.length>0;return d("span",{children:[d("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:[d("span",{children:[i?"▼":"▶"," ","{"]}),!i&&d("span",{children:[p.length,"}"]})]}),i?d(xe,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:p.map(h=>{const f=e[h],g=u(f),y=m(f);return n("div",{className:"py-0.5",children:g?n(qo,{propertyKey:h,value:f,depth:t,defaultExpanded:r,maxDepth:s}):y?n(Qo,{propertyKey:h,value:f,depth:t,defaultExpanded:r,maxDepth:s}):d(xe,{children:[d("span",{className:"text-orange-600",children:[h,": "]}),n(Nr,{data:f,depth:t+1,defaultExpanded:r,maxDepth:s})]})},h)})}),n("div",{className:"text-gray-600",children:"}"})]}):null]})}return n("span",{className:"text-gray-500",children:String(e)})}function qo({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=M(s||r<2),l=Object.keys(t);return re(()=>{i(s||r<2)},[s,r]),d(xe,{children:[d("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?"▼":"▶"}),d("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"{"}),!o&&d("span",{className:"text-gray-600",children:[l.length,"}"]})]}),o&&d(xe,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:l.map(c=>{const p=t[c],u=p!==null&&typeof p=="object"&&!Array.isArray(p)&&Object.keys(p).length>0,m=Array.isArray(p)&&p.length>0;return n("div",{className:"py-0.5",children:u?n(qo,{propertyKey:c,value:p,depth:r+1,defaultExpanded:s,maxDepth:a}):m?n(Qo,{propertyKey:c,value:p,depth:r+1,defaultExpanded:s,maxDepth:a}):d(xe,{children:[d("span",{className:"text-orange-600",children:[c,": "]}),n(Nr,{data:p,depth:r+2,defaultExpanded:s,maxDepth:a})]})},c)})}),n("div",{className:"text-gray-600",children:"}"})]})]})}function Qo({propertyKey:e,value:t,depth:r,defaultExpanded:s,maxDepth:a}){const[o,i]=M(s||r<2);return re(()=>{i(s||r<2)},[s,r]),d(xe,{children:[d("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?"▼":"▶"}),d("span",{className:"text-orange-600",children:[e,": "]}),n("span",{className:"text-gray-600 ml-0.5",children:"["}),!o&&d("span",{className:"text-gray-600",children:[t.length,"]"]})]}),o&&d(xe,{children:[n("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:t.map((l,c)=>{const p=l!==null&&typeof l=="object"&&!Array.isArray(l)&&Object.keys(l).length>0,u=Array.isArray(l)&&l.length>0;return n("div",{className:"py-0.5",children:p?n(qo,{propertyKey:c.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:a}):u?n(Qo,{propertyKey:c.toString(),value:l,depth:r+1,defaultExpanded:s,maxDepth:a}):n(Nr,{data:l,depth:r+2,defaultExpanded:s,maxDepth:a})},c)})}),n("div",{className:"text-gray-600",children:"]"})]})]})}function ja({label:e,count:t,isActive:r,onClick:s,badgeColorActive:a,badgeTextActive:o}){return d("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 pl({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 ml({call:e,scenarioName:t}){const[r,s]=M(!1),[a,o]=M("system"),i=h=>new Date(h).toLocaleString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),l=h=>h?`$${h.toFixed(4)}`:null,c=(h,f)=>{if(!h&&!f)return null;const g=[];return h&&g.push(`${h.toLocaleString()} in`),f&&g.push(`${f.toLocaleString()} out`),g.join(" / ")},p=ae(()=>{var h,f,g,y,x;try{const w=JSON.parse(e.response);return(g=(f=(h=w.choices)==null?void 0:h[0])==null?void 0:f.message)!=null&&g.content?w.choices[0].message.content:(x=(y=w.content)==null?void 0:y[0])!=null&&x.text?w.content[0].text:e.response}catch{return e.response}},[e.response]),u=ae(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),m=ae(()=>{var h;if(t)return t;try{const f=JSON.parse(e.props);return((h=f==null?void 0:f.scenario)==null?void 0:h.name)||null}catch{return null}},[e.props,t]);return d("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:d("div",{className:"flex items-start justify-between gap-4",children:[d("div",{className:"flex-1 min-w-0",children:[d("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}),m&&n("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:m}),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"})]}),d("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[n("span",{children:i(e.created_at)}),c(e.input_tokens,e.output_tokens)&&n("span",{children:c(e.input_tokens,e.output_tokens)}),l(e.cost)&&n("span",{className:"text-[#005c75] font-medium",children:l(e.cost)})]}),d("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&&d("div",{className:"border-t border-[#e1e1e1]",children:[d("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&&d("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"&&d("div",{children:[e.error&&d("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:p})]}),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:u})]}),e.error&&!a&&n("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:d("p",{className:"text-xs text-[#dc2626] m-0",children:[n("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const hl=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function PN({entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a}){var v,N,C,E,k,_,S,j,$;const[o,i]=M("entity"),[l,c]=M("analysis"),[p,u]=M(r.length>0?{scenarioId:r[0].id||r[0].name}:null),[m,h]=M("entity"),{entityLlmCalls:f,scenarioLlmCalls:g,totalLlmCalls:y}=ae(()=>{if(!a)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const T=[...a.entityCalls,...a.analysisCalls],R=T.filter(P=>P.object_type==="entity"||hl.includes(P.prompt_type)),I=T.filter(P=>P.object_type!=="entity"&&!hl.includes(P.prompt_type));return R.sort((P,H)=>H.created_at-P.created_at),I.sort((P,H)=>H.created_at-P.created_at),{entityLlmCalls:R,scenarioLlmCalls:I,totalLlmCalls:T.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:(v=e==null?void 0:e.metadata)==null?void 0:v.isolatedDataStructure,description:"Entity's own data structure without dependencies"},{id:"mergedDataStructure",title:"Merged Data Structure",data:(N=t==null?void 0:t.metadata)==null?void 0:N.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(E=(C=e==null?void 0:e.metadata)==null?void 0:C.isolatedDataStructure)==null?void 0:E.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(k=t==null?void 0:t.metadata)==null?void 0:k.executionFlows,description:"Distinct outcomes/behaviors this component can produce"},{id:"importedExports",title:"Imported Dependencies",data:{"Internal Dependencies":(_=e==null?void 0:e.metadata)==null?void 0:_.importedExports,"External Dependencies":(S=e==null?void 0:e.metadata)==null?void 0:S.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(j=t==null?void 0:t.metadata)==null?void 0:j.scenariosDataStructure,description:"Structure template used across all scenarios"}],w=x.filter(T=>T.data!==void 0&&T.data!==null).length;let b=null;if(o==="entity"){const T=x.find(R=>R.id===l);T&&T.data!==void 0&&T.data!==null&&(b={title:T.title,description:T.description,data:T.data})}else if(o==="scenarios"&&p){const T=r.find(R=>(R.id||R.name)===p.scenarioId);T&&(b={title:T.name,description:T.description||"Scenario data and configuration",data:T.metadata})}return d("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[n("div",{className:"mb-6 shrink-0",children:d("div",{className:"flex border-b border-gray-200 relative",children:[n(ja,{label:"Entity",isActive:o==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),n(ja,{label:"Scenarios",count:r.length,isActive:o==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),n(ja,{label:"LLM Calls",count:y,isActive:o==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),(($=t==null?void 0:t.metadata)==null?void 0:$.analyzerVersion)&&d("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"?d("div",{className:"flex-1 min-h-0",children:[d("div",{className:"flex gap-4 mb-4",children:[d("button",{onClick:()=>h("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),d("button",{onClick:()=>h("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${m==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",g.length,")"]})]}),n("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:m==="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(T=>n(ml,{call:T},T.id)):g.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"})}):g.map(T=>n(ml,{call:T},T.id))})]}):d("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"?d(xe,{children:[n("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),w===0?n("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):n("nav",{className:"space-y-1",children:x.map(T=>{const R=T.data!==void 0&&T.data!==null;return n(pl,{label:T.title,isActive:l===T.id,onClick:()=>c(T.id),disabled:!R},T.id)})})]}):d(xe,{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(T=>{const R=T.id||T.name,I=(p==null?void 0:p.scenarioId)===R;return n(pl,{label:T.name,isActive:I,onClick:()=>u({scenarioId:R})},R)})})]})}),n("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:b?n(jN,{title:b.title,description:b.description,data:b.data}):o==="scenarios"&&r.length===0?n(fl,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:s}):o==="entity"?n(fl,{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 fl({title:e,description:t,onAnalyze:r}){return d("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 jN({title:e,description:t,data:r}){const[s,a]=M(!0);return d(xe,{children:[d("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})]}),d("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[d("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(mt,{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(AN,{data:r,defaultExpanded:s,maxDepth:99})}):n("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function TN({entity:e,analysis:t,scenarios:r,onAnalyze:s}){const a=Ue();return re(()=>{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(PN,{entity:e,analysis:t,scenarios:r,onAnalyze:s,llmCalls:a.data})})}const MN={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},$N={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},IN=2e3,RN=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 DN({entity:e,entityCode:t}){const r=Sr(),s=ge(null);return re(()=>{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 c=l.style.backgroundColor;l.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{l.style.backgroundColor=c},2e3)}},300)},[r.hash,t]),n("div",{ref:s,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:d("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[d("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[d("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(mt,{content:t,label:"Copy Code",duration:IN,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(kp,{language:RN(e==null?void 0:e.filePath),style:Ep,showLineNumbers:!0,customStyle:MN,lineNumberStyle:$N,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"})})]})})}const ON=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function FN({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 LN({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),c=l[0]||"scenarios",p=l[1]||null,u=l[2]||null,m=r.analysisQueue,h=m?m.getState():{paused:!1,jobs:[]},[f,g,y,x]=await Promise.all([xn(s),Fe(),Wn(),Fh(Ne()||process.cwd())]),w=f?await Ts(f):null,b=f?await mc(f.sha):null;let v={importedEntities:[],importingEntities:[]},N=null,C=[];f&&(v=await hc(f),N=await fc(f),C=await yc(f));const E=!!(f&&C.length>0&&C[0].sha!==f.sha),k=C.length>0?C[0].sha:null,_=!!(C.length>0&&C[0].analyses&&C[0].analyses.length>0),S=f?await gc(f):!1;return X({entity:f??void 0,analysis:w??void 0,currentEntityAnalysis:b??void 0,projectSlug:g,from:o,relatedEntities:v,entityCode:N??void 0,hasNewerVersion:E,newestEntitySha:k,newestVersionHasAnalysis:_,fileModifiedSinceEntity:S,history:C,tab:c,scenarioId:p,viewModeFromUrl:u,currentCommit:y,hasAnApiKey:x,queueState:h})}const zN=Qe(function(){var Rr,Dr,Or,Qn,Fr,kn,Zn,Lr,Xn,zr,er,tr,Br,$t,Yr;const t=tt(),a=(Bl()["*"]||"").split("/").filter(Boolean),o=a[0]||"scenarios",i=a[1]||null,l=a[2]||null,c=t.entity,p=t.analysis,u=t.currentEntityAnalysis,m=u||p,h=t.projectSlug;t.from;const f=t.relatedEntities,g=t.entityCode,y=t.hasNewerVersion,x=t.newestEntitySha,w=t.newestVersionHasAnalysis,b=t.fileModifiedSinceEntity,v=t.history,N=t.currentCommit,C=t.hasAnApiKey,E=t.queueState;(Rr=m==null?void 0:m.status)==null||Rr.errors;const k=(m==null?void 0:m.scenarios)||[],_=k.filter(ye=>{var Me;return!((Me=ye.metadata)!=null&&Me.sameAsDefault)}),S=k.filter(ye=>{var Me;return(Me=ye.metadata)==null?void 0:Me.sameAsDefault}),j=Pt(),$=ge(null);re(()=>{$.current===null&&($.current=window.history.length)},[]);const T=()=>{if(typeof window>"u")return;const ye=window.history.state;if(ye===null||(ye==null?void 0:ye.idx)===void 0||(ye==null?void 0:ye.idx)===0)j("/");else{const Me=window.history.length,Xe=$.current;if(Xe!==null&&Me>Xe){const Ye=Me-Xe+1;j(-Ye)}else j(-1)}},R=!!E.currentlyExecuting,I=o,P=(Dr=N==null?void 0:N.metadata)==null?void 0:Dr.currentRun,H=!!(P!=null&&P.createdAt)&&!(P!=null&&P.analysisCompletedAt),W=!!(c!=null&&c.sha&&((Or=P==null?void 0:P.currentEntityShas)!=null&&Or.includes(c.sha))),F=!!(c!=null&&c.sha&&((Fr=(Qn=E.currentlyExecuting)==null?void 0:Qn.entityShas)!=null&&Fr.includes(c.sha))),J=!!(c!=null&&c.sha&&((kn=E.jobs)!=null&&kn.some(ye=>{var Me;return(Me=ye.entityShas)==null?void 0:Me.includes(c.sha)}))),Y=W||F||J,z=Y&&((Zn=m==null?void 0:m.status)==null?void 0:Zn.finishedAt)!=null&&_.length>0&&m.entitySha!==(c==null?void 0:c.sha),A=ae(()=>{if(I!=="scenarios")return null;if(i){const ye=_.find(Me=>Me.id===i);if(ye)return ye}return _.length>0&&!Y?_[0]:null},[I,i,_,Y]),B=((zr=(Xn=(Lr=A==null?void 0:A.metadata)==null?void 0:Lr.executionResult)==null?void 0:Xn.error)==null?void 0:zr.message)||((Br=(tr=(er=m==null?void 0:m.status)==null?void 0:er.errors)==null?void 0:tr[0])==null?void 0:Br.message);jt({source:A?"scenario-page":"entity-page",entitySha:c==null?void 0:c.sha,scenarioId:A==null?void 0:A.id,analysisId:m==null?void 0:m.id,entityName:c==null?void 0:c.name,entityType:c==null?void 0:c.entityType,scenarioName:A==null?void 0:A.name,errorMessage:B});const[G,q]=M(()=>l&&l!=="edit"?l:(c==null?void 0:c.entityType)==="library"?"data":"screenshot");re(()=>{l&&l!==G&&l!=="edit"&&q(l)},[l]);const Q=l==="edit",[U,D]=M(!1),[O,V]=M(!1),[ne,ie]=M(null),[we,le]=M(!1),[ce,ve]=M(!1),[Ee,he]=M(null),[Z,Se]=M(null),[fe,se]=M(0),{interactiveServerUrl:pe,isStarting:_e,isLoading:Le,showIframe:de,iframeKey:We,onIframeLoad:Je}=vn({analysisId:m==null?void 0:m.id,scenarioId:A==null?void 0:A.id,scenarioName:A==null?void 0:A.name,projectSlug:h,enabled:Q&&!!A,refreshTrigger:fe}),[Ie,Wt]=M(!1),[Xs,ea]=M(""),[Ze,Jt]=M(!1),[Kn,Nn]=M(Date.now()),[nt,st]=M(!1),ht=Ue(),Mt=Ue(),at=Ue(),He=Lt(),ta=E.jobs.some(ye=>{var Me;return(c==null?void 0:c.sha)&&((Me=ye.entityShas)==null?void 0:Me.includes(c.sha))||ye.type==="analysis"&&ye.commitSha===(N==null?void 0:N.sha)&&ye.entityShas&&ye.entityShas.length===0}),Ht=Y,jr=(($t=c==null?void 0:c.metadata)==null?void 0:$t.defaultWidth)||((Yr=m==null?void 0:m.metadata)==null?void 0:Yr.defaultWidth)||1440,na=Math.round(jr*(900/1440));ht.state==="submitting"||ht.state,ae(()=>{var ye;return!!((ye=A==null?void 0:A.metadata)!=null&&ye.interactiveExamplePath)},[A]);const{isCompleted:Sn}=zt(h,Ze);re(()=>{ht.state==="idle"&&ht.data&&(ht.data.success?setTimeout(()=>{Nn(Date.now()),He.revalidate(),Jt(!1)},1500):ht.data.error&&(Jt(!1),alert(`Recapture failed: ${ht.data.error}`)))},[ht.state,ht.data,He]),re(()=>{Ze&&Sn&&setTimeout(()=>{Nn(Date.now()),He.revalidate(),Jt(!1)},1500)},[Ze,Sn,He]),re(()=>{Mt.state==="idle"&&Mt.data&&(Mt.data.success?setTimeout(()=>{Nn(Date.now()),He.revalidate(),Jt(!1)},1500):Mt.data.error&&(Jt(!1),alert(`Recapture failed: ${Mt.data.error}`)))},[Mt.state,Mt.data,He]);const Cn=()=>{c&&(y&&x&&x!==c.sha?(j(`/entity/${x}/scenarios`),setTimeout(()=>{at.submit({entitySha:x,filePath:c.filePath||""},{method:"post",action:"/api/analyze"})},100)):at.submit({entitySha:c.sha,filePath:c.filePath||""},{method:"post",action:"/api/analyze"}))};re(()=>{at.state==="idle"&&at.data&&(at.data.success?He.revalidate():at.data.error&&alert(`Analysis failed: ${at.data.error}`))},[at.state,at.data,c==null?void 0:c.sha,He]),re(()=>{const ye=setTimeout(()=>{He.revalidate()},500);return()=>clearTimeout(ye)},[]),re(()=>{if(H||Ht){const ye=setInterval(()=>{He.revalidate()},3e3);return()=>clearInterval(ye)}},[H,Ht,He]);const ra=(ye,Me)=>ye==="scenarios"?`/entity/${c==null?void 0:c.sha}/scenarios`:`/entity/${c==null?void 0:c.sha}/${ye}`,Tr=(ye,Me)=>`/entity/${c==null?void 0:c.sha}/scenarios/${ye}/${Me}`,Mr=ye=>{q(ye),A!=null&&A.id&&(ye==="interactive"?j(`/entity/${c==null?void 0:c.sha}/scenarios/${A.id}/fullscreen`,{replace:!0}):j(Tr(A.id,ye),{replace:!0}))},_n=async ye=>{var Me,Xe;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:ye,hasSelectedScenario:!!A,hasAnalysis:!!m}),!A||!m){const Ye="Error: No scenario or analysis available";console.error("[EntityDetail]",Ye),ie(Ye);return}D(!0),ie(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:ye,scenarioId:A.id,scenarioName:A.name,currentData:A.data});try{const Ye=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:ye,existingScenarios:m.scenarios,scenariosDataStructure:(Me=m.metadata)==null?void 0:Me.scenariosDataStructure,editingMockName:A.name,editingMockData:Z||((Xe=A.metadata)==null?void 0:Xe.data)})}),ot=await Ye.json();if(!Ye.ok||!ot.success)throw new Error(ot.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",ot.data),Se(ot.data);const It=(m.scenarios||[]).map(Ge=>Ge.id===A.id?{...Ge,metadata:{...Ge.metadata,data:ot.data}}:Ge),gt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:It})}),it=await gt.json();if(!gt.ok||!it.success)throw console.error("[EntityDetail] Temp save failed:",it),new Error(it.error||"Failed to apply preview");if(ie("Generating preview. Capturing screenshot..."),pe){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:pe});const Ge=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:pe,scenarioId:A.id,projectId:m.projectId,viewportWidth:1440})}),rn=await Ge.json();!Ge.ok||!rn.success?(console.error("[EntityDetail] Direct capture failed:",rn),ie("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),ie('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Ge=new FormData;Ge.append("analysisId",m.id||""),Ge.append("scenarioId",A.id||"");const rn=await fetch("/api/recapture-scenario",{method:"POST",body:Ge}),En=await rn.json();!rn.ok||!En.success?(console.warn("[EntityDetail] Recapture failed:",En.error),ie("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",En.jobId),ie('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}se(Ge=>Ge+1),He.revalidate()}catch(Ye){console.error("Error applying changes:",Ye),ie(`Error: ${Ye instanceof Error?Ye.message:String(Ye)}`)}finally{D(!1)}},sa=async(ye,Me)=>{var Xe;if(!A||!m){ie("Error: No scenario or analysis available");return}V(!0),ie(null),console.log("[EntityDetail] Saving scenario to database",{description:ye,saveAsNew:Me});try{const Ye=Z||((Xe=A.metadata)==null?void 0:Xe.data);let ot;if(Me){const it={...A,id:`${A.name}-${Date.now()}`,name:`${A.name} (Copy)`,metadata:{...A.metadata,data:Ye},description:ye||A.description};ot=[...m.scenarios||[],it]}else ot=(m.scenarios||[]).map(it=>it.id===A.id?{...it,metadata:{...it.metadata,data:Ye},description:ye||it.description}:it);const It=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:m,scenarios:ot})}),gt=await It.json();if(!It.ok||!gt.success)throw new Error(gt.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),ie(Me?"New scenario created successfully":"Scenario saved successfully"),Se(null),He.revalidate()}catch(Ye){console.error("Error saving scenario:",Ye),ie(`Error: ${Ye instanceof Error?Ye.message:String(Ye)}`)}finally{V(!1)}},$r=()=>{A!=null&&A.id&&(c!=null&&c.sha)&&j(`/entity/${c.sha}/scenarios/${A.id}/dev`)},Ir=async()=>{var ye;if(!(A!=null&&A.id)){he("Cannot delete scenario without ID");return}le(!0),he(null);try{const Me=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:A.id,screenshotPaths:((ye=A.metadata)==null?void 0:ye.screenshotPaths)||[]})}),Xe=await Me.json();if(!Me.ok||!Xe.success)throw new Error(Xe.error||"Failed to delete scenario");j(`/entity/${c==null?void 0:c.sha}/scenarios`)}catch(Me){console.error("[EntityDetail] Error deleting scenario:",Me),he(Me instanceof Error?Me.message:"Failed to delete scenario"),ve(!1)}finally{le(!1)}},ft=m&&c&&m.entitySha!==c.sha,qn=c?wN(c):!1;return n(Ys,{children:d("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:d("div",{className:"flex items-end h-full px-6 gap-6",children:[d("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[n("button",{onClick:T,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:c==null?void 0:c.name}),n("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:c==null?void 0:c.filePath,children:c==null?void 0:c.filePath})]}),n("div",{className:"flex items-end gap-8 shrink-0",children:[{id:"scenarios",label:"Scenarios",count:_.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(ye=>n(Ce,{to:ra(ye.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${I===ye.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:I===ye.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:d("span",{className:"flex items-center gap-2",children:[ye.label,ye.count!==void 0&&ye.count>0&&n("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${I===ye.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:ye.count})]})},ye.id))})]})}),(y||ft&&!u||b&&qn)&&!Y&&!ta&&n("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:d("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:ft&&!y?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),n("span",{className:"text-sm",style:{color:"#714A25"},children:y?"You are viewing an older version. A newer version is available.":ft?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),y&&x&&w?n(Ce,{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:ye=>{ye.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:ye=>{ye.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):n("button",{onClick:Cn,disabled:at.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:ye=>{at.state==="idle"&&(ye.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:ye=>{at.state==="idle"&&(ye.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),d("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[I==="scenarios"&&d(xe,{children:[Q&&A?n(NN,{scenario:A,entitySha:(c==null?void 0:c.sha)||"",onApply:_n,onSave:sa,onEditMockData:$r,onDelete:Ir,isApplying:U,isSaving:O,saveMessage:ne,showDeleteConfirm:ce,onShowDeleteConfirm:ve,isDeleting:we,deleteError:Ee}):n(vN,{scenarios:_,hiddenScenarios:S,analysis:m,selectedScenario:A,entitySha:(c==null?void 0:c.sha)||"",cacheBuster:Kn,activeTab:I,entityType:c==null?void 0:c.entityType,entity:c,queueState:E,processIsRunning:R,isEntityAnalyzing:Y,areScenariosStale:z,viewMode:G,setViewMode:Mr,isBreakdownView:i==="breakdown"}),i==="breakdown"?n(CN,{analysis:m??null,entitySha:(c==null?void 0:c.sha)||""}):Q&&A?n(Us,{scenarioId:A.id||A.name,scenarioName:A.name,iframeUrl:pe,isStarting:_e,isLoading:Le,showIframe:de,iframeKey:We,onIframeLoad:Je,projectSlug:h,defaultWidth:1440,defaultHeight:900}):d("div",{className:"flex flex-col flex-1 min-h-0",children:[A&&d("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-xs font-semibold text-[#343434]",children:A.name}),d("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[jr," × ",na]})]}),d("div",{className:"flex items-center gap-2",children:[n(Ce,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${A.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"}),d("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"]}),d(Ce,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${A.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:[d("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"]}),d(Ce,{to:`/entity/${c==null?void 0:c.sha}/scenarios/${A.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(Id,{selectedScenario:A,analysis:m,entity:c,viewMode:G,cacheBuster:Kn,hasScenarios:_.length>0,isAnalyzing:Ht,projectSlug:h,hasAnApiKey:C,processIsRunning:R,queueState:E})]})]}),I==="related"&&n(EN,{relatedEntities:f}),I==="data"&&n(TN,{entity:c,analysis:m,scenarios:_,onAnalyze:Cn}),I==="code"&&n(DN,{entity:c,entityCode:g}),I==="history"&&n(_N,{entity:c,history:v})]}),nt&&h&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>st(!1),children:d("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:ye=>ye.stopPropagation(),children:[d("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:()=>st(!1),children:"×"})]}),n("div",{className:"flex-1 overflow-hidden",children:n(qt,{projectSlug:h,onClose:()=>st(!1)})})]})})]})})}),BN=Object.freeze(Object.defineProperty({__proto__:null,default:zN,loader:LN,meta:ON,shouldRevalidate:FN},Symbol.toStringTag,{value:"Module"}));async function YN(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 ze();const i=Ne();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const l=ee.join(i,".codeyam","config.json"),c=JSON.parse(await Pe.readFile(l,"utf8")),{projectSlug:p,branchId:u}=c;if(!p||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${p}, Branch: ${u}`);const m=Is(p);try{await Pe.writeFile(m,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:h,branch:f}=await Re(p);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const g=await qe({shas:t});if(!g||g.length===0)throw new Error(`No entities found for SHAs: ${t.join(", ")}`);let y=r;if((!y||y.length===0)&&(y=[...new Set(g.map(b=>b.filePath).filter(b=>!!b))],console.log(`[analyzeEntities] Found ${y.length} unique files`)),!y||y.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${y.length} files...`);const x=await $h(h,f,y);console.log(`[analyzeEntities] Created commit ${x.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await Kt({commitSha:x.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:t.length,analysesCompleted:0,capturesCompleted:0,createdAt:new Date().toISOString()},updateCallback:b=>{if(!b)return;const v=b.currentRun;if(v&&v.id&&v.archivedAt)return;v&&(v.analysesCompleted&&v.analysesCompleted>0||v.capturesCompleted&&v.capturesCompleted>0)&&Hh(b)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:w}=o.enqueue({type:"analysis",commitSha:x.sha,projectSlug:p,filePaths:y,entityShas:t,entityNames:g.map(b=>b.name),...s?{context:s}:{},...a?{scenarioCount:a}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${w} for ${t.length} entities`),{jobId:w}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function UN({request:e,context:t}){if(e.method!=="POST")return X({error:"Method not allowed"},{status:405});let r=t.analysisQueue;if(r||(r=await Ut()),!r)return X({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"),c=s.get("scenarioCount");let p;if(o)p=o.split(",").filter(Boolean);else if(a)p=[a];else return X({error:"Missing required field: entitySha or entityShas"},{status:400});if(p.length===0)return X({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${p.length} entity(ies)`);const u=await qe({shas:p}),h=[...new Set(u.map(g=>g.filePath).filter(g=>!!g))].length,{jobId:f}=await YN({entityShas:p,filePaths:i?[i]:void 0,context:l||void 0,scenarioCount:c?parseInt(c,10):void 0,queue:r});return console.log(`[API] Analysis queued with job ID: ${f}`),X({success:!0,message:`Analysis queued for ${p.length} entity(ies)`,entityCount:p.length,fileCount:h,jobId:f})}catch(s){return console.error("[API] Error starting analysis:",s),X({error:"Failed to start analysis",details:s.message},{status:500})}}const WN=Object.freeze(Object.defineProperty({__proto__:null,action:UN},Symbol.toStringTag,{value:"Module"}));function JN(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:d("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:d("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 Rd(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,c=o.toString().padStart(2,"0");return`Today, ${l}:${c} ${i}`}return t.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function yt(e,t=[],r=!1){var u,m;if(t.some(h=>{var f,g;return!!((f=h.entityShas)!=null&&f.includes(e.sha)||(g=h.entities)!=null&&g.some(y=>y.sha===e.sha))}))return r?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const a=e.analyses[0];if(!(((u=a.status)==null?void 0:u.scenarios)&&a.status.scenarios.length>0&&a.status.scenarios.some(h=>h.screenshotFinishedAt||h.finishedAt))||a.entitySha!==e.sha)return"not-analyzed";const i=a.createdAt?new Date(a.createdAt).getTime():0,l=(m=e.metadata)!=null&&m.editedAt?new Date(e.metadata.editedAt).getTime():0,c=a.scenarios||[],p=c.some(h=>{var f,g,y;return((g=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0])||((y=h.metadata)==null?void 0:y.executionResult)});return i>=l?c.length>0&&p?c.every(f=>{var g,y,x;return((y=(g=f.metadata)==null?void 0:g.screenshotPaths)==null?void 0:y[0])||((x=f.metadata)==null?void 0:x.executionResult)})?"up-to-date":"incomplete":c.length>0?"incomplete":"not-analyzed":"out-of-date"}const HN=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function VN({request:e,context:t}){try{const r=t.analysisQueue,s=r?r.getState():{paused:!1,jobs:[]},a=await wn();return X({entities:a||[],queueState:s})}catch(r){return console.error("Failed to load simulations:",r),X({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const GN=Qe(function(){const t=tt(),r=t.entities,s=t.queueState;jt({source:"simulations-page"});const[a,o]=M(""),[i,l]=M("visual"),c=ae(()=>{const y=[];return r.forEach(x=>{var b;const w=(b=x.analyses)==null?void 0:b[0];if(w!=null&&w.scenarios){const v=w.scenarios.filter(N=>{var C;return!((C=N.metadata)!=null&&C.sameAsDefault)}).map(N=>{var $,T,R,I,P;const C=(T=($=N.metadata)==null?void 0:$.screenshotPaths)==null?void 0:T[0],E=(R=N.metadata)==null?void 0:R.noScreenshotSaved,k=C&&!E,_=(P=(I=w.status)==null?void 0:I.scenarios)==null?void 0:P.find(H=>H.name===N.name),S=_&&_.screenshotStartedAt&&!_.screenshotFinishedAt;let j;return k?j="completed":S?j="capturing":j="error",{scenarioName:N.name,scenarioDescription:N.description||"",screenshotPath:C||"",scenarioId:N.id,state:j}}).filter(N=>N.state==="completed"||N.state==="capturing");v.length>0&&y.push({entity:x,screenshots:v,createdAt:w.createdAt||""})}}),y.sort((x,w)=>new Date(w.createdAt).getTime()-new Date(x.createdAt).getTime()),y},[r]),p=ae(()=>r.filter(y=>{var b,v;const x=(b=y.analyses)==null?void 0:b[0];return!((v=x==null?void 0:x.scenarios)==null?void 0:v.some(N=>{var C,E;return(E=(C=N.metadata)==null?void 0:C.screenshotPaths)==null?void 0:E[0]}))}),[r]),u=ae(()=>c.filter(({entity:y})=>{const x=!a||y.name.toLowerCase().includes(a.toLowerCase()),w=i==="all"||y.entityType===i;return x&&w}),[c,a,i]),m=ae(()=>p.filter(y=>{const x=!a||y.name.toLowerCase().includes(a.toLowerCase()),w=i==="all"||y.entityType===i;return x&&w}),[p,a,i]),h=oe(y=>{o(y.target.value)},[]),f=oe(y=>{l(y.target.value)},[]),g=c.length>0;return n("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:d("div",{className:"px-20 py-12",children:[d("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."})]}),!g&&n("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:d("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."})]})}),d("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"}),d("div",{className:"flex gap-3",children:[d("div",{className:"relative",children:[d("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(wt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"flex-1 relative",children:[n(Cr,{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:h})]})]})]}),g&&u.length>0&&n("div",{className:"mb-2",children:d("div",{className:"flex items-center py-3",children:[d("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?"entity":"entities"]}),d("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:d("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:"|"}),d("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((y,{screenshots:x})=>y+x.length,0)})," ","scenarios"]})]})}),d("div",{className:"flex flex-col gap-3",children:[g&&(u.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(xe,{children:u.map(({entity:y,screenshots:x})=>n(KN,{entity:y,screenshots:x,queueJobs:(s==null?void 0:s.jobs)||[]},y.sha))})),!g&&(m.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."}):m.map(y=>n(qN,{entity:y},y.sha)))]})]})})});function KN({entity:e,screenshots:t,queueJobs:r}){var f,g,y;const s=Pt(),a=Ue(),[o,i]=M(!1),l=t.length||(((y=(g=(f=e.analyses)==null?void 0:f[0])==null?void 0:g.scenarios)==null?void 0:y.length)??0),c=x=>{s(`/entity/${e.sha}/scenarios/${x}?from=simulations`)},p=()=>{i(!0),a.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};re(()=>{a.state==="idle"&&o&&i(!1)},[a.state,o]);const u=yt(e,r),m=JN(u),h=u==="out-of-date";return n("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:d("div",{className:"flex flex-col",children:[d("div",{className:"flex items-center px-[15px] py-[15px]",children:[n("div",{className:"flex-shrink-0",children:n(dt,{type:e.entityType||"other",size:"large"})}),d("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[d("div",{className:"flex items-center gap-[5px]",children:[d(Ce,{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:m.bgColor,color:m.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:m.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"}),d("div",{className:"flex-shrink-0 flex items-center gap-2",children:[h&&n(xe,{children:o||a.state!=="idle"?d("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[n(kt,{size:14,className:"animate-spin",style:{color:"#be185d"}}),n("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):n("button",{onClick:p,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=>d("div",{className:"shrink-0 flex flex-col gap-2",children:[n("button",{onClick:()=>c(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:w=>{x.state==="completed"&&(w.currentTarget.style.borderColor="#005C75",w.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:w=>{w.currentTarget.style.borderColor=x.state==="capturing"?"#efefef":"#d1d5db",w.currentTarget.style.boxShadow="none"},children:x.state==="completed"?n(rt,{screenshotPath:x.screenshotPath,alt:x.scenarioName,className:"max-w-full max-h-full object-contain"}):x.state==="capturing"?n(Ko,{size:"medium"}):null})}),d("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:d("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&&d(xe,{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 qN({entity:e}){const t=Ue(),[r,s]=M(!1),a=()=>{s(!0),t.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return re(()=>{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:d("div",{className:"px-5 py-4 flex items-center",children:[d("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[n(dt,{type:e.entityType}),d("div",{className:"min-w-0",children:[d("div",{className:"flex items-center gap-3 mb-0.5",children:[n(Ce,{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:Rd(e.createdAt||null)}),n("div",{className:"w-24 flex justify-end",children:r||t.state!=="idle"?d("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(kt,{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 QN=Object.freeze(Object.defineProperty({__proto__:null,default:GN,loader:VN,meta:HN},Symbol.toStringTag,{value:"Module"}));function ZN({request:e,context:t}){const r=t.dbNotifier||bt;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"})}
|
|
433
|
-
|
|
434
|
-
`)),Math.random().toString(36).substring(7);let i=!1;const l=()=>{if(!i){i=!0,r.off("change",c),clearInterval(p);try{a.close()}catch{}}},c=u=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
|
|
435
|
-
|
|
436
|
-
`))}catch{l()}};r.on("change",c);const p=setInterval(()=>{try{a.enqueue(o.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
437
|
-
|
|
438
|
-
`))}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 XN=Object.freeze(Object.defineProperty({__proto__:null,loader:ZN},Symbol.toStringTag,{value:"Module"}));function eS(){return new Response(JSON.stringify({status:"ok",version:bo,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const tS=Object.freeze(Object.defineProperty({__proto__:null,loader:eS},Symbol.toStringTag,{value:"Module"}));function Zo(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(`
|
|
439
|
-
`).filter(p=>p.trim().startsWith("-")).map(p=>p.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean):l&&(o.paths=l[1].split(",").map(p=>p.replace(/['"]/g,"").trim()).filter(Boolean));const c=s.match(/^category:\s*(.+)$/m);return c&&(o.category=c[1].replace(/['"]/g,"").trim()),{frontmatter:o,body:a}}async function qs(e,t=""){const r=[];try{const s=await Pe.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){const i=await qs(ee.join(e,a.name),o);r.push(...i)}else a.isFile()&&a.name.endsWith(".md")&&r.push(o)}}catch{}return r}async function Pr(e){const t=await qs(e),r=[];for(const s of t){const a=ee.join(e,s);try{const o=await Pe.readFile(a,"utf-8"),{frontmatter:i,body:l}=Zo(o);r.push({filePath:s,absolutePath:a,frontmatter:i,body:l})}catch{}}return r}function Dd(e){const t=ee.posix.dirname(e.filePath);return!t||t==="."?null:`${t}/**`}function Od(e,t){if(t.frontmatter.paths&&t.frontmatter.paths.length>0)return t.frontmatter.paths.some(s=>Oa(e,s,{matchBase:!0}));const r=Dd(t);return r?Oa(e,r,{matchBase:!0}):!1}function nS(e,t){return(!e.frontmatter.paths||e.frontmatter.paths.length===0)&&!Dd(e)?[]:t.filter(r=>Od(r,e))}const rS=new Set(["node_modules",".git","dist",".codeyam",".claude","build","coverage"]);async function Xo(e){const t=[];async function r(s,a){try{const o=await Ae.readdir(s,{withFileTypes:!0});for(const i of o){const l=L.join(s,i.name),c=a?`${a}/${i.name}`:i.name;i.isDirectory()&&rS.has(i.name)||(i.isDirectory()?await r(l,c):i.isFile()&&t.push(c))}}catch{}}return await r(e,""),t}const sS="codeyam-rule-state.json",Ta=1;function Fd(e){const t=e.replace(/^category:\s*.+$\n?/m,"");return Bn.createHash("sha256").update(t).digest("hex")}function Ld(e){return ee.join(e,".claude",sS)}async function zd(e){const t=Ld(e);try{const r=await Pe.readFile(t,"utf-8"),s=JSON.parse(r);return s.version!==Ta?(console.warn(`[ruleState] Unknown version ${s.version}, using empty state`),{version:Ta,rules:{}}):s}catch{return{version:Ta,rules:{}}}}async function Bd(e,t){const r=Ld(e),s=ee.dirname(r);await Pe.mkdir(s,{recursive:!0}),await Pe.writeFile(r,JSON.stringify(t,null,2)+`
|
|
440
|
-
`,"utf-8")}async function ei(e,t){const r=await zd(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 Pe.readFile(a.absolutePath,"utf-8"),i=Fd(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 Bd(e,r),r}async function gl(e,t,r,s){const a=await zd(e);if(r){const o=ee.join(e,".claude","rules"),i=ee.join(o,t),l=await Pe.readFile(i,"utf-8"),c=Fd(l);a.rules[t]?(a.rules[t].reviewed=!0,a.rules[t].contentHash=c):a.rules[t]={contentHash:c,reviewed:!0}}else a.rules[t]&&(a.rules[t].reviewed=!1);await Bd(e,a)}function ti(e,t){var r;return((r=e.rules[t])==null?void 0:r.reviewed)??!1}async function Yd(e,t=""){const r=[],s=await Pe.readdir(e,{withFileTypes:!0});for(const a of s){const o=t?`${t}/${a.name}`:a.name;a.isDirectory()?r.push(...await Yd(ee.join(e,a.name),o)):a.name.endsWith(".md")&&r.push(o)}return r}function bs(e){if(!e||e==="(diff not available)")return!1;const t=e.split(`
|
|
441
|
-
`).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 aS({request:e}){const t=Ne();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 iS(t,a);if(s==="reviewed-status")return cS(t,a);if(s==="audit")return dS(t,a);if(s==="source-files")return uS(t);if(s==="rule-coverage")return pS(t,a);if(s==="rule-diff"){const o=r.searchParams.get("filePath");return o?lS(t,o):Response.json({error:"Missing required parameter: filePath"},{status:400})}if(s==="rules-for-path"){const o=r.searchParams.get("path");return o?mS(a,o):Response.json({error:"Missing required parameter: path"},{status:400})}try{const o=await qs(a),i=[];for(const u of o){const m=ee.join(a,u);try{const h=await Pe.readFile(m,"utf-8"),f=await Pe.stat(m),{frontmatter:g,body:y}=Zo(h);i.push({filePath:u,content:h,frontmatter:g,body:y,lastModified:f.mtime.toISOString()})}catch{}}i.sort((u,m)=>new Date(m.lastModified).getTime()-new Date(u.lastModified).getTime());let l=i.length>0;if(!l)try{await Pe.access(ee.join(t,".claude","codeyam-rule-state.json")),l=!0}catch{}const c=await Pr(a),p={};if(c.length>0){const u=await ei(t,c);for(const m of c)p[m.filePath]=ti(u,m.filePath)}return Response.json({memories:i,memoryInitialized:l,reviewedStatus:p})}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 oS(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(`
|
|
442
|
-
`).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],c=o[1];let p=[i];if(i.endsWith("/")&&l==="?"){const u=ee.join(e,i);try{p=(await Yd(u)).map(h=>i+h)}catch{continue}}for(const u of p){if(u.endsWith("/"))continue;const m=u.replace(".claude/rules/","");let h="modified";l==="A"||l==="?"?h="added":l==="D"||c==="D"?h="deleted":(l==="M"||c==="M")&&(h="modified");let f="";try{if(h==="deleted")f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(h==="added"&&l==="?"){const g=`${e}/${u}`;try{const y=await Pe.readFile(g,"utf-8");f=`diff --git a/${u} b/${u}
|
|
443
|
-
new file mode 100644
|
|
444
|
-
--- /dev/null
|
|
445
|
-
+++ b/${u}
|
|
446
|
-
@@ -0,0 +1,${y.split(`
|
|
447
|
-
`).length} @@
|
|
448
|
-
${y.split(`
|
|
449
|
-
`).map(x=>"+"+x).join(`
|
|
450
|
-
`)}`}catch{f="(content not available)"}}else f=t(`git diff HEAD -- "${u}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});f.length>5e3&&(f=f.substring(0,5e3)+`
|
|
451
|
-
... (truncated)`)}catch{f="(diff not available)"}h==="modified"&&bs(f)||r.push({filePath:m,changeType:h,diff:f})}}}catch{}return r}async function iS(e,t){try{const{execSync:r}=await import("child_process"),s=[],a=await Pr(t),o={};if(a.length>0){const u=await ei(e,a);for(const m of a)o[m.filePath]=ti(u,m.filePath)}const l=(await oS(e,r)).filter(u=>!o[u.filePath]);l.length>0&&s.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:l});const p=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(`
|
|
452
|
-
`).filter(Boolean).slice(0,20);for(const u of p){const[m,h,...f]=u.split("|"),g=f.join("|");if(!m||!h)continue;const y=r(`git diff-tree --no-commit-id --name-status -r ${m} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),x=[];for(const w of y.split(`
|
|
453
|
-
`).filter(Boolean)){const[b,v]=w.split(" ");if(!v||!v.startsWith(".claude/rules/"))continue;const N=v.replace(".claude/rules/","");let C="modified";if(b==="A"?C="added":b==="D"&&(C="deleted"),o[N])continue;let E="";try{E=r(`git show ${m} --format="" -- "${v}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),E.length>5e3&&(E=E.substring(0,5e3)+`
|
|
454
|
-
... (truncated)`)}catch{E="(diff not available)"}C==="modified"&&bs(E)||x.push({filePath:N,changeType:C,diff:E})}x.length>0&&s.push({commitHash:m.substring(0,8),date:h,message:g,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 lS(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(bs(i))return Response.json({diff:null});const y=i.length>5e3?i.substring(0,5e3)+`
|
|
455
|
-
... (truncated)`:i;return Response.json({diff:{diff:y,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 y=ee.join(e,s);try{const x=await Pe.readFile(y,"utf-8"),w=`diff --git a/${s} b/${s}
|
|
456
|
-
new file mode 100644
|
|
457
|
-
--- /dev/null
|
|
458
|
-
+++ b/${s}
|
|
459
|
-
@@ -0,0 +1,${x.split(`
|
|
460
|
-
`).length} @@
|
|
461
|
-
${x.split(`
|
|
462
|
-
`).map(b=>"+"+b).join(`
|
|
463
|
-
`)}`;return Response.json({diff:{diff:w.length>5e3?w.substring(0,5e3)+`
|
|
464
|
-
... (truncated)`:w,commitMessage:"New file (untracked)",date:new Date().toISOString(),isUncommitted:!0,commitCount:0}})}catch{}}const p=r(`git log -1 --format="%H|%aI|%s" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}).trim();if(!p)return Response.json({diff:null});const[u,m,...h]=p.split("|"),f=h.join("|");if(!u||!m)return Response.json({diff:null});let g=r(`git show ${u} --format="" -- "${s}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});return g.trim()?bs(g)?Response.json({diff:null}):(g.length>5e3&&(g=g.substring(0,5e3)+`
|
|
465
|
-
... (truncated)`),Response.json({diff:{diff:g,commitMessage:f,date:m,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 cS(e,t){try{const r=await Pr(t),s={};if(r.length>0){const a=await ei(e,r);for(const o of r)s[o.filePath]=ti(a,o.filePath)}return Response.json({reviewedStatus:s})}catch(r){return console.error("[API] Error getting reviewed status:",r),Response.json({reviewedStatus:{}})}}async function dS(e,t){try{const r=await Pr(t),s=await Xo(e),a=[];for(const o of s){const i=r.filter(l=>Od(o,l));if(i.length>0){const l=i.reduce((c,p)=>c+p.body.length,0);a.push({filePath:o,matchingRules:i.map(c=>({filePath:c.filePath,patterns:c.frontmatter.paths||[],bodyLength:c.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 uS(e){try{const t=await Xo(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 pS(e,t){try{const[r,s]=await Promise.all([Pr(t),Xo(e)]),a={};for(const o of r)a[o.filePath]=nS(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 mS(e,t){try{const r=await qs(e),s=[];for(const o of r){const i=ee.join(e,o);try{const l=await Pe.readFile(i,"utf-8"),c=await Pe.stat(i),{frontmatter:p,body:u}=Zo(l);p.paths&&p.paths.some(m=>Oa(t,m,{matchBase:!0}))&&s.push({filePath:o,content:l,frontmatter:p,body:u,lastModified:c.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 hS({request:e}){const t=Ne();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 gl(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 gl(t,o,!1),console.log(`[API] Rule marked as unreviewed: ${o}`),Response.json({success:!0,message:"Rule marked as unreviewed",filePath:o});const c=ee.normalize(o);if(c.includes("..")||ee.isAbsolute(c))return Response.json({error:"Invalid file path"},{status:400});const p=ee.join(r,c);switch(a){case"create":case"update":return i?(await Pe.mkdir(ee.dirname(p),{recursive:!0}),await Pe.writeFile(p,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 Pe.unlink(p),console.log(`[API] Memory deleted: ${o}`);const u=ee.dirname(p);try{(await Pe.readdir(u)).length===0&&u!==r&&await Pe.rmdir(u)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(u){if(u.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw u}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 fS=Object.freeze(Object.defineProperty({__proto__:null,action:hS,loader:aS},Symbol.toStringTag,{value:"Module"}));async function gS({request:e,context:t}){var o;let r=t.analysisQueue;if(r||(r=await Ut()),!r)return X({error:"Queue not initialized"},{status:500});const s=new URL(e.url),a=s.searchParams.get("queryType");if(!a)return X({error:"Missing queryType parameter for GET request"},{status:400});if(a==="job"){const i=s.searchParams.get("jobId");if(!i)return X({error:"Missing jobId parameter for job query"},{status:400});const l=r.getState();if(((o=l.currentlyExecuting)==null?void 0:o.id)===i)return X({jobId:i,status:"running",job:l.currentlyExecuting});const c=l.jobs.find(u=>u.id===i);if(c){const u=l.jobs.indexOf(c);return X({jobId:i,status:"queued",position:u,job:c})}const p=r.getJobResult(i);return p?X({jobId:i,status:p.status==="error"?"failed":"completed",error:p.error}):X({jobId:i,status:"completed"})}if(a==="full"){const i=r.getState(),l=await Promise.all(i.jobs.map(async p=>{const u=[];if(p.entityShas&&p.entityShas.length>0){const m=p.entityShas.map(f=>xn(f)),h=await Promise.all(m);u.push(...h.filter(f=>f!==null))}return{id:p.id,type:p.type,commitSha:p.commitSha,projectSlug:p.projectSlug,queuedAt:p.queuedAt,entities:u,filePaths:p.filePaths}}));let c;if(i.currentlyExecuting){const p=i.currentlyExecuting,u=[];if(p.entityShas&&p.entityShas.length>0){const m=p.entityShas.map(f=>xn(f)),h=await Promise.all(m);u.push(...h.filter(f=>f!==null))}c={id:p.id,type:p.type,commitSha:p.commitSha,projectSlug:p.projectSlug,queuedAt:p.queuedAt,entities:u,filePaths:p.filePaths}}return X({state:{...i,jobsWithEntities:l,currentlyExecutingWithEntities:c}})}return X({error:"Unknown queryType"},{status:400})}async function yS({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 Ut(),console.log("[Queue API] Using global queue")),!r)return console.error("[Queue API] ERROR: Queue not initialized in context"),X({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(c=>{console.error(`[Queue API] Job ${i} failed:`,c)}),X({jobId:i,status:"queued"})}if(a==="resume")return r.resume(),X({status:"resumed"});if(a==="pause")return r.pause(),X({status:"paused"});if(a==="remove"){const{jobId:i}=o;return i?r.removeJob(i)?X({status:"removed",jobId:i}):X({error:"Job not found in queue"},{status:404}):X({error:"Missing jobId parameter"},{status:400})}if(a==="clear"){const i=r.clearQueue();return X({status:"cleared",count:i})}if(a==="reorder"){const{jobId:i,direction:l}=o;return!i||!l?X({error:"Missing jobId or direction parameter"},{status:400}):l!=="up"&&l!=="down"?X({error:'Invalid direction: must be "up" or "down"'},{status:400}):r.reorderJob(i,l)?X({status:"reordered",jobId:i,direction:l}):X({error:"Could not reorder job (not found or at boundary)"},{status:400})}return X({error:"Unknown action"},{status:400})}const xS=Object.freeze(Object.defineProperty({__proto__:null,action:yS,loader:gS},Symbol.toStringTag,{value:"Module"})),bS=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],wS=Qe(function(){return Ue(),n(Ys,{children:d("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:d("div",{className:"flex items-center h-full px-6 gap-6",children:[d("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"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[d("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"})]}),d("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:d("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[d("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"})]}),d("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"})]})}),d("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(Id,{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})]})]})})}),vS=Object.freeze(Object.defineProperty({__proto__:null,default:wS,meta:bS},Symbol.toStringTag,{value:"Module"})),NS=()=>[{title:"Settings - CodeYam"},{name:"description",content:"Configure project settings"}];async function SS({request:e}){var t,r;try{const s=await Ms();if(!s)return X({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Project configuration not found"});let a=!1;try{const c=await Fe();if(c){const{project:p}=await Re(c);a=((r=(t=p.metadata)==null?void 0:t.labs)==null?void 0:r.simulations)===!0}}catch{}const o=Ne()||process.cwd(),i=await $s(o),l=kc(s.projectSlug);return X({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),X({config:null,secrets:null,versionInfo:null,simulationsEnabled:!1,error:"Failed to load configuration"})}}function CS(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 _S({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"),c=t.get("memorySettings");let p;if(r)try{p=JSON.parse(r)}catch{return X({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let u;if(s)try{u=JSON.parse(s)}catch{return X({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let m;l&&(m=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 h;if(c)try{h=JSON.parse(c)}catch{return X({success:!1,error:"Invalid memorySettings JSON format",requiresRestart:!1},{status:400})}let f;if(u){const x=await Ms();x!=null&&x.webapps&&(f=x.webapps.map((w,b)=>{if(u[b]!==void 0){const v=CS(u[b]);return{...w,startCommand:v}}return w}))}if(!await xc({universalMocks:p,pathsToIgnore:m,webapps:f,memory:h}))return X({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let y=!1;if(a!==void 0||o!==void 0||i!==void 0){const x=Ne()||process.cwd(),w=await $s(x);y=a!==void 0&&a!==(w.GROQ_API_KEY||"")||o!==void 0&&o!==(w.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(w.OPENAI_API_KEY||""),await Oh(x,{...w,GROQ_API_KEY:a||void 0,ANTHROPIC_API_KEY:o||void 0,OPENAI_API_KEY:i||void 0},!0)}return X({success:!0,error:null,requiresRestart:y})}catch(t){return console.log("[Settings Action] Failed to save config:",t),X({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function yl(e){if(!e)return"";const t=[e.command];return e.args&&e.args.length>0&&t.push(...e.args),t.join(" ")}function xl({mock:e,onSave:t,onCancel:r}){const[s,a]=M(e.entityName),[o,i]=M(e.filePath),[l,c]=M(e.content);return d("div",{className:"space-y-3",children:[d("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:u=>a(u.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"})]}),d("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:u=>i(u.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"})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:l,onChange:u=>c(u.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' }"})]}),d("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 kS(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const ES=Qe(function(){var Ee,he,Z,Se,fe;const{config:t,secrets:r,versionInfo:s,simulationsEnabled:a,error:o}=tt(),i=Nu(),l=Ue(),c=Lt(),[p,u]=M(a?"project-metadata":"memory");jt({source:"settings-page"});const[m,h]=M((t==null?void 0:t.universalMocks)||[]),[f,g]=M(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[y,x]=M(((t==null?void 0:t.pathsToIgnore)||[]).join(", ")),[w,b]=M((r==null?void 0:r.GROQ_API_KEY)||""),[v,N]=M((r==null?void 0:r.ANTHROPIC_API_KEY)||""),[C,E]=M((r==null?void 0:r.OPENAI_API_KEY)||""),[k,_]=M(!1),[S,j]=M(!1),[$,T]=M(!1),[R,I]=M(!1),[P,H]=M(!1),[W,F]=M(!1),[J,Y]=M(null),[z,A]=M(!1),[B,G]=M({}),[q,Q]=M(((Ee=t==null?void 0:t.memory)==null?void 0:Ee.conversationReflection)??!0),[U,D]=M(((he=t==null?void 0:t.memory)==null?void 0:he.ruleMaintenance)??!0),[O,V]=M(((Z=t==null?void 0:t.memory)==null?void 0:Z.promptModel)??"haiku");re(()=>{var se,pe,_e,Le;if(t){h(t.universalMocks||[]);const de=(t.pathsToIgnore||[]).join(", ");g(de),x(de);const We={};(se=t.webapps)==null||se.forEach((Je,Ie)=>{Je.startCommand&&(We[Ie]=yl(Je.startCommand))}),G(We),Q(((pe=t.memory)==null?void 0:pe.conversationReflection)??!0),D(((_e=t.memory)==null?void 0:_e.ruleMaintenance)??!0),V(((Le=t.memory)==null?void 0:Le.promptModel)??"haiku")}r&&(b(r.GROQ_API_KEY||""),N(r.ANTHROPIC_API_KEY||""),E(r.OPENAI_API_KEY||""))},[t,r]),re(()=>{if(i!=null&&i.success){I(!0);const se=setTimeout(()=>I(!1),3e3);return()=>clearTimeout(se)}},[i]),re(()=>{if(l.state==="idle"&&l.data&&!W){console.log("[Settings] Fetcher data:",l.data);const se=l.data;if(se.success){console.log("[Settings] Save successful, revalidating..."),I(!0),F(!0),(f!==y||se.requiresRestart)&&H(!0),c.revalidate();const pe=setTimeout(()=>{I(!1),F(!1)},3e3);return()=>clearTimeout(pe)}}},[l.state,l.data,W,c,f,y]);const ne=se=>{se.preventDefault();const pe=new FormData(se.currentTarget);pe.set("universalMocks",JSON.stringify(m)),pe.set("startCommands",JSON.stringify(B)),pe.set("memorySettings",JSON.stringify({conversationReflection:q,ruleMaintenance:U,promptModel:O})),console.log("[Settings] Submitting form data:",{universalMocks:pe.get("universalMocks"),startCommands:pe.get("startCommands"),openAiApiKey:pe.get("openAiApiKey")?"***":"(empty)"}),l.submit(pe,{method:"post"})},ie=se=>{h([...m,se]),A(!1)},we=(se,pe)=>{const _e=[...m];_e[se]=pe,h(_e),Y(null)},le=se=>{h(m.filter((pe,_e)=>_e!==se))};if(o)return d("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 ce=[{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?ce:ce.filter(se=>se.id==="memory");return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 pt-8 pb-12 font-sans",children:[d("div",{className:"mb-8 flex justify-between items-start",children:[d("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||P||(i==null?void 0:i.error)||l.data&&typeof l.data=="object"&&"error"in l.data)&&d("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!"}),P&&d("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:"}),d("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(mt,{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 se=l.data;return typeof se.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:se.error}):null}return null})()]}),d("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(se=>n("li",{children:n("button",{type:"button",onClick:()=>u(se.id),className:`w-full text-left px-3 lg:px-0 py-2.5 text-sm transition-colors cursor-pointer whitespace-nowrap ${p===se.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:se.label})},se.id))})}),n("div",{className:"flex-1 min-w-0 -mt-2",children:d("form",{id:"settings-form",onSubmit:ne,className:"space-y-6",children:[p==="project-metadata"&&d("div",{children:[n("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),d("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((se,pe)=>{var _e;return n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:se.path==="."?"Root":se.path})]}),se.appDirectory&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:se.appDirectory})]}),d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:se.framework})]}),se.startCommand&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",d("span",{className:"text-gray-900 font-mono text-xs",children:[se.startCommand.command," ",(_e=se.startCommand.args)==null?void 0:_e.join(" ")]})]})]})},pe)})}):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`."})]})]}),p==="ai-provider"&&d("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."}),d("div",{className:"space-y-6",children:[d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("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."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("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"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),d("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"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:k?"text":"password",id:"groqApiKey",name:"groqApiKey",value:w,onChange:se=>b(se.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:()=>_(!k),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:k?"Hide":"Show"})]})]})]}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("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."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("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"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),d("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"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:S?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:v,onChange:se=>N(se.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:()=>j(!S),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:S?"Hide":"Show"})]})]})]}),d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[n("div",{className:"flex items-start justify-between mb-3",children:d("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."}),d("div",{className:"flex flex-wrap gap-2 text-xs",children:[d("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"]}),d("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[n("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),d("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"]})]})]})}),d("div",{className:"mt-4",children:[n("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),d("div",{className:"relative",children:[n("input",{type:$?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:C,onChange:se=>E(se.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:()=>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:$?"Hide":"Show"})]})]})]})]})]}),p==="commands"&&d("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((se,pe)=>d("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[d("div",{className:"mb-4",children:[n("div",{className:"text-base font-semibold text-gray-900 mb-1",children:se.path==="."?"Root":se.path}),n("div",{className:"text-sm text-gray-600",children:se.framework})]}),d("div",{children:[n("label",{htmlFor:`startCommand-${pe}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),n("input",{type:"text",id:`startCommand-${pe}`,name:`startCommand-${pe}`,value:B[pe]||"",onChange:_e=>G({...B,[pe]:_e.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"})]})]},pe))}):n("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),p==="paths-to-ignore"&&d("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:se=>g(se.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"}),d("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"})]})]}),p==="universal-mocks"&&d("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"}),m.length===0?d("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:()=>A(!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:m.map((se,pe)=>n("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:J===pe?n(xl,{mock:se,onSave:_e=>we(pe,_e),onCancel:()=>Y(null)}):n(xe,{children:d("div",{className:"flex justify-between items-start mb-2",children:[d("div",{className:"flex-1",children:[n("div",{className:"font-medium text-gray-800 mb-1",children:se.entityName}),n("div",{className:"text-sm text-gray-600 mb-2",children:se.filePath}),n("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:se.content})]}),d("div",{className:"flex gap-2 ml-3",children:[n("button",{type:"button",onClick:()=>Y(pe),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:()=>le(pe),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},pe))}),m.length>0&&n("button",{type:"button",onClick:()=>A(!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"})]}),p==="memory"&&d("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."}),d("div",{className:"space-y-6",children:[n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:d("div",{className:"flex items-start justify-between",children:[d("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":q,onClick:()=>Q(!q),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 ${q?"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 ${q?"translate-x-5":"translate-x-0"}`})})]})}),n("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:d("div",{className:"flex items-start justify-between",children:[d("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":U,onClick:()=>D(!U),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 ${U?"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 ${U?"translate-x-5":"translate-x-0"}`})})]})}),d("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(se=>d("label",{className:`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${O===se.value?"border-[#005C75] bg-[#005C75]/5":"border-gray-200 hover:border-gray-300"}`,children:[n("input",{type:"radio",name:"promptModel",value:se.value,checked:O===se.value,onChange:()=>V(se.value),className:"mt-1 accent-[#005C75]"}),d("div",{children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-gray-900",children:se.label}),se.badge&&n("span",{className:"px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:se.badge})]}),n("p",{className:"text-sm text-gray-600 mt-0.5",children:se.description})]})]},se.value))})]})]})]}),p==="current-configuration"&&d("div",{className:"space-y-6",children:[t&&d("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:d("div",{className:"space-y-2 text-sm",children:[t.projectSlug&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",n("span",{className:"text-gray-900",children:t.projectSlug})]}),t.packageManager&&d("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&&d("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((se,pe)=>n("div",{className:"p-4 bg-white border border-gray-200 rounded",children:d("div",{className:"space-y-2 text-sm",children:[d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Path:"})," ",n("span",{className:"text-gray-900",children:se.path==="."?"Root":se.path})]}),se.appDirectory&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",n("span",{className:"text-gray-900",children:se.appDirectory})]}),d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",n("span",{className:"text-gray-900",children:se.framework})]}),se.startCommand&&d("div",{children:[n("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",n("span",{className:"text-gray-900 font-mono text-xs",children:yl(se.startCommand)})]})]})},pe))})]})]}),s&&d("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:d("div",{className:"space-y-2 text-sm",children:[s.webserverVersion&&d("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&&d("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||((Se=s.templateVersion.gitCommit)==null?void 0:Se.slice(0,7))||"unknown"}),s.templateVersion.buildTimestamp&&d("span",{className:"text-gray-500 ml-2",children:["(built"," ",kS(s.templateVersion.buildTimestamp),")"]})]}),s.cachedAnalyzerVersion&&d("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||((fe=s.cachedAnalyzerVersion.gitCommit)==null?void 0:fe.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)&&d("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"})]})]})})]})]})]})})]}),z&&n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:d("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(xl,{mock:{entityName:"",filePath:"",content:""},onSave:ie,onCancel:()=>A(!1)})]})})]})})}),AS=Object.freeze(Object.defineProperty({__proto__:null,action:_S,default:ES,loader:SS,meta:NS},Symbol.toStringTag,{value:"Module"}));async function PS({params:e}){const t=e["*"];if(!t)return new Response("Static path is required",{status:400});const r=Ne();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 Pe.access(o);let i=await Pe.readFile(o);const l=ee.extname(o).toLowerCase();let c="application/octet-stream";if(l===".html"){c="text/html";let p=i.toString("utf-8");const u=p.match(/<script>(window\.__remixContext\s*=\s*\{[\s\S]*?\});?<\/script>/i);if(u)try{const h=u[1].match(/=\s*(\{[\s\S]*\})/);if(h){const f=JSON.parse(h[1]);f.isSpaMode=!0,f.future&&(f.future.v3_lazyRouteDiscovery=!1);const g=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;p=p.replace(u[0],g)}}catch(m){console.error("[Static] Failed to parse Remix context:",m)}i=Buffer.from(p,"utf-8")}else l===".js"||l===".mjs"?c="application/javascript":l===".css"?c="text/css":l===".json"?c="application/json":l===".png"?c="image/png":l===".jpg"||l===".jpeg"?c="image/jpeg":l===".svg"?c="image/svg+xml":l===".woff"?c="font/woff":l===".woff2"?c="font/woff2":l===".ttf"&&(c="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":c,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const jS=Object.freeze(Object.defineProperty({__proto__:null,loader:PS},Symbol.toStringTag,{value:"Module"}));function TS(e,t,r=10){var c;const s=new Map,a=p=>p.entityType==="visual"||p.entityType==="library";for(const p of e)a(p)&&s.set(p.sha,{entity:p,depth:0});const o=new Map;for(const p of t){const u=(c=p.metadata)==null?void 0:c.importedBy;if(u)for(const m of Object.keys(u))for(const h of Object.keys(u[m])){const{shas:f}=u[m][h];for(const g of f)o.has(p.sha)||o.set(p.sha,new Set),o.get(p.sha).add(g)}}const i=[],l=new Set;for(const p of e)i.push({sha:p.sha,depth:0}),l.add(p.sha);for(;i.length>0;){const{sha:p,depth:u}=i.shift();if(u>=r)continue;const m=o.get(p);if(m)for(const h of m){if(l.has(h))continue;l.add(h);const f=t.find(g=>g.sha===h);if(f){if(a(f)){const g=u+1,y=s.get(h);(!y||g<y.depth)&&s.set(h,{entity:f,depth:g})}i.push({sha:h,depth:u+1})}}}return Array.from(s.values()).sort((p,u)=>p.depth!==u.depth?p.depth-u.depth:p.entity.name.localeCompare(u.entity.name))}function ws(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 p,u;const l=((p=o.metadata)==null?void 0:p.editedAt)||o.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(l)});r.push(a[0])}return r}function Ud(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(c=>c.filePath===a.path||a.status==="renamed"&&a.oldPath&&c.filePath===a.oldPath),i=o.filter(c=>{var p,u;return s.has(c.filePath)&&((p=c.metadata)==null?void 0:p.isUncommitted)&&!((u=c.metadata)!=null&&u.isSuperseded)}),l=ws(i);r.set(a.path,{status:a,entities:o,editedEntities:l})}return r}function MS(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(c=>c.filePath===o.path||o.status==="renamed"&&o.oldPath&&c.filePath===o.oldPath),l=ws(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(p=>(p.filePath===o.path||o.status==="renamed"&&o.oldPath&&p.filePath===o.oldPath)&&i.has(p.name)):[],c=ws(l);s.set(o.path,{status:o,entities:c})}}return s}function $S(e,t){const r=new Map,s=Wd(e,t);for(const a of s){const i=TS([a],t).filter(({depth:l})=>l>0);r.set(a.sha,i)}return r}function Wd(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 ws(s)}function IS({recentSimulations:e}){const t=ae(()=>{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 d("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:d("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?d(xe,{children:[n("div",{className:"space-y-6 mb-5",children:t.map(r=>d("div",{children:[d("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(yr,{size:16,style:{color:"#8B5CF6"}})}),n(Ce,{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(Ce,{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(rt,{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(Ce,{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 →"})]}):d("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(yr,{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."}),d("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",n(Ce,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",n(Ce,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const RS="/assets/codeyam-name-logo-CvKwUgHo.svg",DS=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function OS({request:e,context:t}){var r,s,a,o,i;try{const l=await Fe();if(l){const{project:R}=await Re(l),I=((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)||I)return Su("/memory")}const c=t.analysisQueue,p=c?c.getState():{paused:!1,jobs:[]},[u,m]=await Promise.all([wn(),Wn()]),h=Vn(),f=u?Ud(h,u):new Map,g=Array.from(f.entries()).sort((R,I)=>R[0].localeCompare(I[0])),y=(u==null?void 0:u.length)||0,x=(u==null?void 0:u.filter(R=>R.entityType==="visual").length)||0,w=(u==null?void 0:u.filter(R=>R.entityType==="library").length)||0,b=u?Wd(h,u):[],v=b.length,N=(u==null?void 0:u.filter(R=>(R.analyses??[]).filter(I=>I.scenarios&&I.scenarios.length>0).length>0).length)||0,C=(u==null?void 0:u.reduce((R,I)=>{var H,W,F;const P=((F=(W=(H=I.analyses)==null?void 0:H[0])==null?void 0:W.scenarios)==null?void 0:F.length)||0;return R+P},0))||0,E=(u==null?void 0:u.reduce((R,I)=>{var W,F;const H=(((F=(W=I.analyses)==null?void 0:W[0])==null?void 0:F.scenarios)||[]).filter(J=>{var Y,z;return(z=(Y=J.metadata)==null?void 0:Y.screenshotPaths)==null?void 0:z[0]}).length;return R+H},0))||0,k=[];u==null||u.forEach(R=>{var P;const I=(P=R.analyses)==null?void 0:P[0];I!=null&&I.scenarios&&I.scenarios.filter(W=>{var F;return!((F=W.metadata)!=null&&F.sameAsDefault)}).forEach(W=>{var J,Y;const F=(Y=(J=W.metadata)==null?void 0:J.screenshotPaths)==null?void 0:Y[0];F&&k.push({entitySha:R.sha,entityName:R.name,scenarioId:W.id,scenarioName:W.name,screenshotPath:F,createdAt:I.createdAt||""})})}),k.sort((R,I)=>new Date(I.createdAt).getTime()-new Date(R.createdAt).getTime());const _=k.slice(0,16),S=(u==null?void 0:u.filter(R=>R.entityType==="visual").filter(R=>{var H,W;const I=(H=R.analyses)==null?void 0:H[0];return!((W=I==null?void 0:I.scenarios)==null?void 0:W.some(F=>{var J,Y;return(Y=(J=F.metadata)==null?void 0:J.screenshotPaths)==null?void 0:Y[0]}))}).slice(0,8))||[],j=(o=m==null?void 0:m.metadata)==null?void 0:o.currentRun,$=((i=j==null?void 0:j.currentEntityShas)==null?void 0:i.length)||0,T=p.jobs.length||0;return X({stats:{totalEntities:y,visualEntities:x,libraryEntities:w,uncommittedEntities:v,entitiesWithAnalyses:N,totalScenarios:C,capturedScreenshots:E,currentlyAnalyzing:$,filesOnQueue:T},uncommittedFiles:g,uncommittedEntitiesList:b,recentSimulations:_,visualEntitiesForSimulation:S,projectSlug:l,queueState:p,currentCommit:m})}catch(l){return console.error("Failed to load dashboard data:",l),X({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 FS=Qe(function(){var J,Y;const{stats:t,uncommittedFiles:r,uncommittedEntitiesList:s,recentSimulations:a,visualEntitiesForSimulation:o,projectSlug:i,queueState:l,currentCommit:c}=tt(),p=Ue(),u=Lt(),{showToast:m}=mo();jt({source:"dashboard"});const[h,f]=M(new Set),[g,y]=M(null),[x,w]=M(!1),[b,v]=M(!1),{lastLine:N,isCompleted:C}=zt(i,!!g),{simulatingEntity:E,scenarios:k,scenarioStatuses:_,allScenariosCaptured:S}=ae(()=>{var D,O;const z={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!g)return z;const A=o==null?void 0:o.find(V=>V.sha===g);if(!A)return z;const B=(D=A.analyses)==null?void 0:D[0],G=(B==null?void 0:B.scenarios)||[],q=((O=B==null?void 0:B.status)==null?void 0:O.scenarios)||[],Q=q.filter(V=>V.screenshotFinishedAt).length,U=G.length>0&&Q===G.length;return{simulatingEntity:A,scenarios:G,scenarioStatuses:q,allScenariosCaptured:U}},[g,o]);re(()=>{(C||S)&&y(null)},[C,S]);const j=(J=c==null?void 0:c.metadata)==null?void 0:J.currentRun,$=new Set((j==null?void 0:j.currentEntityShas)||[]),T=new Set(l.jobs.flatMap(z=>z.entityShas||[])),R=new Set(((Y=l.currentlyExecuting)==null?void 0:Y.entityShas)||[]),I=s.filter(z=>z.entityType==="visual"||z.entityType==="library"),P=I.filter(z=>!$.has(z.sha)&&!T.has(z.sha)&&!R.has(z.sha)),H=()=>{if(P.length===0){m("All entities are already queued or analyzing","info",3e3);return}const z=P.map(A=>A.sha);v(!0),m(`Starting analysis for ${P.length} entities...`,"info",3e3),p.submit({entityShas:z.join(",")},{method:"post",action:"/api/analyze"})};re(()=>{if(p.state==="idle"&&p.data){const z=p.data;z.success?(console.log("[Analyze All] Success:",z.message),m(`Analysis started for ${z.entityCount} entities in ${z.fileCount} files. Watch the logs for progress.`,"success",6e3),v(!1)):z.error&&(console.error("[Analyze All] Error:",z.error),m(`Error: ${z.error}`,"error",8e3),v(!1))}},[p.state,p.data,m]);const W=z=>{f(A=>{const B=new Set(A);return B.has(z)?B.delete(z):B.add(z),B})},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:d("div",{className:"px-20 pt-8 pb-12",children:[d("header",{className:"mb-8 flex justify-between items-center",children:[d("div",{className:"flex items-center gap-4",children:[n("img",{src:RS,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,z=>z.toUpperCase()):"Project"})]}),u.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((z,A)=>n(Ce,{to:z.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 ${z.color}`},children:d("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[d("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[d("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:z.label}),d("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:d("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[z.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:z.color},children:"View All →"})]}),d("div",{className:"flex flex-col gap-2",children:[d("div",{className:"flex items-center gap-3",children:[d("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${z.color}15`},children:[z.iconType==="folder"&&n(Qu,{size:20,style:{color:z.color}}),z.iconType==="check"&&n(no,{size:20,style:{color:z.color}}),z.iconType==="image"&&n(yr,{size:20,style:{color:z.color}}),z.iconType==="code-xml"&&n(Zu,{size:20,style:{color:z.color}})]}),n("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:z.value.toLocaleString("en-US")})]}),n("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:z.color},children:"View All →"})]})]})},A))}),d("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[d("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[d("div",{className:"flex justify-between items-start mb-5",children:[d("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"})]}),I.length>0&&n("button",{onClick:H,disabled:p.state!=="idle"||b||P.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:z=>z.currentTarget.style.backgroundColor="#004560",onMouseLeave:z=>z.currentTarget.style.backgroundColor="#005C75",children:p.state!=="idle"||b?"Starting analysis...":P.length===0?"All Queued":"Analyze All"})]}),r.length>0?n("div",{className:"flex flex-col gap-3",children:r.map(([z,A])=>{const B=h.has(z),G=A.editedEntities||[];return d("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:()=>W(z),role:"button",tabIndex:0,children:d("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:B?"▼":"▶"}),d("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[d("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"})})})]}),d("div",{className:"flex-1 min-w-0",children:[n("span",{className:"font-normal text-gray-900 text-sm block truncate",children:z}),d("span",{className:"text-xs text-gray-500",children:[G.length," entit",G.length!==1?"ies":"y"]})]})]})}),B&&n("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:G.length>0?G.map(q=>{const Q=$.has(q.sha),U=T.has(q.sha)||R.has(q.sha);return d(Ce,{to:`/entity/${q.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:D=>D.currentTarget.style.borderColor="#005C75",onMouseLeave:D=>D.currentTarget.style.borderColor="inherit",children:[d("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:q.entityType==="visual"?"#8B5CF615":q.entityType==="library"?"#6366F1":"#EC4899"},children:[q.entityType==="visual"&&n(yr,{size:16,style:{color:"#8B5CF6"}}),q.entityType==="library"&&n(Ul,{size:16,className:"text-white"}),q.entityType==="other"&&n(Xu,{size:16,className:"text-white"})]}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2 mb-0.5",children:[n("div",{className:"font-semibold text-gray-900 text-sm",children:q.name}),q.entityType==="visual"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),q.entityType==="library"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),q.entityType==="other"&&n("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),q.description&&n("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:q.description})]}),d("div",{className:"flex items-center gap-2 shrink-0",children:[Q&&d("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(kt,{size:14,className:"animate-spin"}),"Analyzing..."]}),!Q&&U&&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&&!U&&n("button",{onClick:D=>{D.preventDefault(),D.stopPropagation(),m(`Starting analysis for ${q.name}...`,"info",3e3),p.submit({entityShas:q.sha},{method:"post",action:"/api/analyze"})},disabled:p.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:D=>D.currentTarget.style.backgroundColor="#004560",onMouseLeave:D=>D.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},q.sha)}):n("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},z)})}):d("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:d("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."})]})]}),!g&&n(IS,{recentSimulations:a}),g&&d("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[n("div",{className:"flex justify-between items-start mb-5",children:d("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"})]})}),g&&d("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[E&&n("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:d("div",{className:"flex items-center gap-3",children:[n("span",{className:"text-[32px] leading-none",children:n(dt,{type:"visual"})}),d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",E.name]}),n("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:E.filePath})]})]})}),S?d("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:"✅"}),d("span",{children:["Complete (",k.length," scenario",k.length!==1?"s":"",")"]})]}):N?d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(kt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:N,children:N}),i&&n("button",{onClick:()=>w(!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"})]}):p.state!=="idle"?d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(kt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):d("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[n(kt,{size:18,className:"animate-spin shrink-0"}),n("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),k.length>0&&n("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:k.slice(0,8).map((z,A)=>{var O,V,ne;const B=(O=E==null?void 0:E.analyses)==null?void 0:O[0],G=Ks(z,B==null?void 0:B.status,void 0,g||void 0,void 0),q=(ne=(V=z.metadata)==null?void 0:V.screenshotPaths)==null?void 0:ne[0],Q=G.isCaptured,U=G.status==="capturing"||G.status==="starting",D=G.hasError;return Q?n(Ce,{to:`/entity/${g}`,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(rt,{screenshotPath:q,alt:z.name,title:z.name,className:"max-w-full max-h-full object-contain object-center"})},A):D?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:G.errorMessage||"Capture error",children:n("span",{className:"text-red-500",children:"⚠️"})},A):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:`${U?"Capturing":"Pending"} ${z.name}...`,children:n("span",{className:U?"animate-pulse":"text-gray-400",children:U?"⋯":"⏹️"})},A)})})]})]})]}),x&&i&&n(qt,{projectSlug:i,onClose:()=>w(!1)})]})})}),LS=Object.freeze(Object.defineProperty({__proto__:null,default:FS,loader:OS,meta:DS},Symbol.toStringTag,{value:"Module"}));function Jd({content:e,className:t}){const r=e.trim().replace(/^#+ .+$/m,"").trim();return n(Pp,{remarkPlugins:[jp],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(xe,{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 Hd(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 Vd(e){let t=e.memories.length;for(const r of e.children.values())t+=Vd(r);return t}function Qs(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 gr(e){return Math.round(e/3.5)}function In(e){const t=new Date(e),r=new Date;if(t.toDateString()===r.toDateString()){const c=r.getTime()-t.getTime(),p=Math.floor(c/(1e3*60)),u=Math.floor(c/(1e3*60*60));return p<3?"Just now":p<60?`${p}min ago`:u===1?"1h ago":`${u}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 zS({rule:e,onEdit:t,onDelete:r,onView:s,isReviewed:a,onToggleReviewed:o,changeType:i,isUncommitted:l,changeDate:c,diff:p,isFadingOut:u,showLeftBorder:m}){const[h,f]=M(!1),[g,y]=M(!1),x=ae(()=>Qs(e.body,e.filePath),[e.body,e.filePath]),w=gr(e.body.length),b=h?"#3e3e3e":l?"#d97706":"#c7c7c7",v=`rounded-lg border overflow-hidden transition-all ease-in-out ${l?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,N={...u&&{opacity:0,maxHeight:0,paddingTop:0,paddingBottom:0,marginBottom:0,borderWidth:0,transitionDuration:"600ms"}};return d("div",{className:v,style:N,children:[n("div",{className:`p-4 cursor-pointer ${l?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>s?s(e):f(!h),children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"flex items-center gap-3",children:[n("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:h?"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:b})})}),d("div",{className:"flex-1",children:[d("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"}),d("span",{className:"text-xs text-gray-400",children:["~",w.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&&d(xe,{children:[e.frontmatter.paths.slice(0,2).map((C,E)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:C},E)),e.frontmatter.paths.length>2&&d("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-2," more"]})]})})]})]}),d("div",{className:"flex items-center gap-3 flex-shrink-0",children:[c&&n("span",{className:"text-xs text-gray-400",children:In(c)}),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"})})})]})]})}),h&&d("div",{className:`border-t ${l?"border-amber-200":"border-gray-100"}`,children:[d("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"&&p&&d("button",{onClick:C=>{C.stopPropagation(),y(!g)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${g?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(cs,{className:"w-3 h-3"}),g?"Hide Diff":"Show Diff"]})}),i!=="deleted"&&d("div",{className:"flex items-center gap-2",children:[d("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(ep,{className:"w-3 h-3"}),"Edit"]}),d("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(tp,{className:"w-3 h-3"}),"Delete"]})]})]}),g&&p&&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:p.split(`
|
|
466
|
-
`).map((C,E)=>{let k="";return C.startsWith("+")&&!C.startsWith("+++")?k="text-green-400":C.startsWith("-")&&!C.startsWith("---")?k="text-red-400":C.startsWith("@@")&&(k="text-cyan-400"),n("div",{className:k,children:C},E)})}),d("div",{className:"mx-4 mb-3",children:[n("div",{className:"text-xs text-gray-500 mb-1.5 font-medium",children:"Edit with Claude:"}),d("div",{className:"flex items-center gap-2",children:[d("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(mt,{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&&d("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,E)=>n("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-600 rounded font-mono text-xs",children:C},E))})]}),!g&&n("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[500px] overflow-auto bg-white border-gray-200",children:n(Jd,{content:e.body})})]})]})}function BS(){return new Date().toISOString().split(".")[0]+"",`---
|
|
467
|
-
paths:
|
|
468
|
-
- '**/*.ts'
|
|
469
|
-
---
|
|
470
|
-
|
|
471
|
-
## Title
|
|
472
|
-
|
|
473
|
-
Description here.
|
|
474
|
-
`}function YS({rule:e,onSave:t,onCancel:r}){const[s,a]=M(e?`.claude/rules/${e.filePath}`:""),[o,i]=M((e==null?void 0:e.content)||BS()),[l,c]=M(!!e),[p,u]=M(!1),m=!e;return d("div",{className:"p-6",children:[d("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(zn,{className:"w-5 h-5"})})]}),m&&d("div",{className:"mb-6",children:[n("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:d("div",{className:"flex items-start gap-3",children:[n(cs,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),d("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:"}),d("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"),u(!0),setTimeout(()=>u(!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:p?n(Nt,{className:"w-4 h-4 text-green-500"}):n(Et,{className:"w-4 h-4"})})]})]})]})}),d("button",{onClick:()=>c(!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||!m)&&d("div",{className:"space-y-4",children:[d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),d("div",{className:"relative",children:[n("input",{type:"text",value:s,onChange:h=>a(h.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(Et,{className:"w-4 h-4"})})]})]}),e&&d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Ask Claude for help editing:"}),d("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(Et,{className:"w-4 h-4"})})]})]}),d("div",{children:[n("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),n("textarea",{value:o,onChange:h=>i(h.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"})]}),d("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 US({memories:e,selectedPath:t,onSelectPath:r,expandedFolders:s,onToggleFolder:a}){const o=ae(()=>Hd(e),[e]),i=(p,u,m)=>{if(p.target.closest(".chevron-toggle")){m&&a(u||"root");return}const f=u||null;r(t===f?null:f),m&&!s.has(u||"root")&&a(u||"root")},l=p=>{r(t===p?null:p)},c=(p,u=0)=>{const m=s.has(p.path||"root"),h=Vd(p),f=p.children.size>0,g=p.name==="root"?"(root)":p.name,y=p.memories.length>0||f,x=p.path||"",w=t===x||t===null&&x==="";return d("div",{children:[d("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${w?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${u*12+8}px`},onClick:b=>i(b,p.path,y),children:[y&&n("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:b=>{b.stopPropagation(),a(p.path||"root")},children:n(Xt,{className:`w-3 h-3 text-gray-500 transition-transform ${m?"rotate-90":""}`})}),!y&&n("div",{className:"w-3"}),n(Jl,{className:"w-3.5 h-3.5 text-[#005C75]"}),n("span",{className:`text-xs font-mono font-semibold ${w?"text-[#005C75]":""}`,style:{color:"#005C75"},children:g}),d("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[h," rules"]})]}),m&&d("div",{className:"relative",children:[(p.memories.length>0||f)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${u*12+8+6}px`}}),p.memories.length>0&&n("div",{style:{paddingLeft:`${(u+1)*12+8}px`},children:p.memories.map(b=>{var N;const v=t===b.filePath;return n("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${v?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>l(b.filePath),children:n("span",{className:"text-xs",children:(N=b.filePath.split("/").pop())==null?void 0:N.replace(".md","")})},b.filePath)})}),f&&n("div",{children:Array.from(p.children.values()).sort((b,v)=>b.name.localeCompare(v.name)).map(b=>c(b,u+1))})]})]},p.path||"root")};return n("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:c(o)})}function WS({memories:e,onEdit:t,onDelete:r,expandedFolders:s,onToggleFolder:a,reviewedStatus:o,onMarkReviewed:i,onMarkUnreviewed:l,onViewRule:c}){const[p,u]=M({});re(()=>{u({})},[o]);const m=ae(()=>({...o,...p}),[o,p]),h=ae(()=>Hd(e),[e]),f=(y,x,w)=>{u(b=>({...b,[y]:!w})),w?l(y):i(y,x)},g=(y,x=0)=>{const w=s.has(y.path||"root"),b=y.children.size>0,v=y.name==="root"?"root":y.name,N=y.memories.length>0||b;return d("div",{children:[d("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:()=>N&&a(y.path||"root"),children:[N&&n(Xt,{className:`w-4 h-4 text-gray-500 transition-transform ${w?"rotate-90":""}`}),!N&&n("div",{className:"w-4"}),n(Jl,{className:"w-4 h-4 text-[#005C75]"}),n("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:v})]}),w&&d("div",{className:"ml-10 space-y-4 relative",children:[(y.memories.length>0||b)&&n("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),y.memories.length>0&&n("div",{className:"space-y-2",children:y.memories.map(C=>n(zS,{rule:C,onEdit:t,onDelete:r,onView:c,isReviewed:m[C.filePath]??!1,onToggleReviewed:f},C.filePath))}),b&&n("div",{className:"space-y-4",children:Array.from(y.children.values()).sort((C,E)=>C.name.localeCompare(E.name)).map(C=>g(C,x+1))})]})]},y.path||"root")};return n("div",{children:g(h)})}function JS({memories:e,reviewedStatus:t,onViewRule:r,refreshKey:s}){const[a,o]=M("unreviewed"),[i,l]=M("by-date"),[c,p]=M(null),[u,m]=M(!0),[h,f]=M(new Map),g=ge(t),y=ge([]);re(()=>()=>{y.current.forEach(clearTimeout)},[]),re(()=>{(async()=>{m(!0);try{const E=await(await fetch("/api/memory?action=rule-coverage")).json();p(E.coverage??null)}catch{p(null)}finally{m(!1)}})()},[s]),re(()=>{const N=g.current,C=[];for(const[E,k]of Object.entries(t))k&&!N[E]&&C.push(E);g.current=t,C.length!==0&&(f(E=>{const k=new Map(E);return C.forEach(_=>k.set(_,"approved")),k}),y.current.push(setTimeout(()=>{f(E=>{const k=new Map(E);return C.forEach(_=>k.set(_,"fading")),k})},1500)),y.current.push(setTimeout(()=>{f(E=>{const k=new Map(E);return C.forEach(_=>k.delete(_)),k})},2500)))},[t]);const x=ae(()=>{const N=[...e];return i==="by-impact"&&c!==null?N.sort((C,E)=>{const k=c[C.filePath]??0,_=c[E.filePath]??0;return _!==k?_-k:new Date(E.lastModified).getTime()-new Date(C.lastModified).getTime()}):N.sort((C,E)=>new Date(E.lastModified).getTime()-new Date(C.lastModified).getTime()),N},[e,i,c]),w=ae(()=>x.filter(N=>!t[N.filePath]).length,[x,t]),b=ae(()=>a==="unreviewed"?x.filter(N=>!t[N.filePath]||h.has(N.filePath)):x,[x,a,t,h]),v=!u&&c!==null;return d("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:[d("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"}),d("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"}}),d("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="unreviewed"?600:400,color:a==="unreviewed"?"#005C75":"#626262"},children:["Unreviewed Rules (",w,")"]})]}),d("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"}}),d("span",{className:"text-[12px] leading-5",style:{fontFamily:"Sora",fontWeight:a==="all"?600:400,color:a==="all"?"#005C75":"#626262"},children:["All (",x.length,")"]})]})]}),d("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"}),d("button",{onClick:()=>v&&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 ${v?"cursor-pointer hover:text-gray-600":"cursor-default"} ${i==="by-impact"?"text-[#005C75]":"text-gray-400"}`,children:["Src Files",i==="by-impact"&&n(wt,{className:"w-3 h-3"})]}),d("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(wt,{className:"w-3 h-3"})]}),d("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",d("span",{className:"relative group",children:[n(Ia,{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:b.map(N=>{const C=t[N.filePath]??!1,E=h.get(N.filePath),k=Qs(N.body,N.filePath),_=(c==null?void 0:c[N.filePath])??0;return n("div",{className:`border-b border-gray-50 transition-all ${E==="fading"?"duration-1000":"duration-300"}`,style:{opacity:E==="fading"?0:1},children:d("div",{className:`grid grid-cols-[1fr_90px_80px_100px] px-5 py-2.5 items-center cursor-pointer transition-colors duration-300 ${E==="approved"?"bg-[#f0fdf4]":"hover:bg-gray-50"}`,onClick:()=>r(N),children:[n("div",{className:"flex items-center gap-2 min-w-0",children:n("span",{className:"text-sm text-gray-900 truncate",children:k})}),n("span",{className:"text-xs text-center",children:u?n("span",{className:"inline-block w-6 h-3 bg-gray-100 rounded animate-pulse"}):c!==null?n("span",{className:_>0?"text-gray-700 font-medium":"text-gray-300",children:_}):n("span",{className:"text-gray-300",children:"—"})}),n("span",{className:"text-xs text-gray-500 text-center",children:In(N.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"})})})})]})},N.filePath)})}),b.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 HS(e,t){const r=t.map(s=>`- \`${s}\``).join(`
|
|
475
|
-
`);return`Please audit the following Claude Rules that apply to the file \`${e}\`:
|
|
476
|
-
|
|
477
|
-
${r}
|
|
478
|
-
|
|
479
|
-
Please review these rules in conjunction with one another as they all apply to this file.
|
|
480
|
-
|
|
481
|
-
Review each rule with the other rules in mind:
|
|
482
|
-
- Necessary: Is this rule really necessary to avoid confusion in future work sessions?
|
|
483
|
-
- Efficiency: Are the rules concise and well-structured?
|
|
484
|
-
- Effectiveness: Does the rules provide clear, actionable guidance?
|
|
485
|
-
- Context window impact: Can the rules be shortened without losing important information?
|
|
486
|
-
- Overlap: Is there any redundant information across the rules that can be consolidated?
|
|
487
|
-
- Duplication: Are there any rules that are nearly identical that can be merged or removed?
|
|
488
|
-
|
|
489
|
-
Remember that documenting past confusion isn't helpul unless that confusion will likely happen again.
|
|
490
|
-
|
|
491
|
-
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 VS({filePath:e,rulePaths:t,onClose:r}){const[s,a]=M(!1),o=HS(e,t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:d("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(zn,{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?d(xe,{children:[n(Nt,{className:"w-4 h-4"}),"Copied!"]}):d(xe,{children:[n(Et,{className:"w-4 h-4"}),"Copy Prompt"]})})})]})})}function GS({refreshKey:e,reviewedStatus:t,memories:r,onViewRule:s}){const[a,o]=M("unreviewed"),[i,l]=M(null),[c,p]=M(""),[u,m]=M(0),[h,f]=M(!1),[g,y]=M(null),[x,w]=M(null),b=ge(null),v=ge(null),[N,C]=M({topPaths:[],totalFilesWithCoverage:0,allSourceFiles:[]}),[E,k]=M(!0);re(()=>{(async()=>{k(!0);try{const W=await(await fetch("/api/memory?action=audit")).json();C({topPaths:W.topPaths||[],totalFilesWithCoverage:W.totalFilesWithCoverage||0,allSourceFiles:W.allSourceFiles||[]})}catch(H){console.error("Failed to load audit data:",H)}finally{k(!1)}})()},[e]);const _=ae(()=>a==="all"?N.topPaths:N.topPaths.filter(P=>P.matchingRules.some(H=>!t[H.filePath])),[N.topPaths,a,t]);ae(()=>N.topPaths.filter(P=>P.matchingRules.some(H=>!t[H.filePath])).length,[N.topPaths,t]);const S=P=>P.split("/").pop()||P,j=ae(()=>{const P=new Map;for(const H of N.topPaths)P.set(H.filePath,H);return P},[N.topPaths]),$=ae(()=>{if(!c.trim())return[];const P=c.toLowerCase(),H=[],W=[];for(const F of N.allSourceFiles){const J=F.toLowerCase();if(!J.includes(P))continue;const Y=j.get(F)||{filePath:F,matchingRules:[],totalTextLength:0};J.startsWith(P)?H.push(Y):W.push(Y)}return H.sort((F,J)=>F.filePath.localeCompare(J.filePath)),W.sort((F,J)=>F.filePath.localeCompare(J.filePath)),[...H,...W].slice(0,8)},[c,N.allSourceFiles,j]),T=oe(P=>{var H;y(P),l(P.filePath),p(P.filePath),f(!1),(H=b.current)==null||H.blur()},[]),R=oe(()=>{var P;p(""),y(null),l(null),(P=b.current)==null||P.focus()},[]),I=oe(P=>{var H;!h||$.length===0||(P.key==="ArrowDown"?(P.preventDefault(),m(W=>Math.min(W+1,$.length-1))):P.key==="ArrowUp"?(P.preventDefault(),m(W=>Math.max(W-1,0))):P.key==="Enter"?(P.preventDefault(),T($[u])):P.key==="Escape"&&(f(!1),(H=b.current)==null||H.blur()))},[h,$,u,T]);return re(()=>{m(0)},[$]),d("div",{className:"bg-white rounded-lg border border-gray-200 flex flex-col",children:[d("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"})}),d("div",{className:"relative flex-1 max-w-[300px]",children:[n(Cr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400"}),n("input",{ref:b,type:"text",value:c,onChange:P=>{p(P.target.value),f(!0)},onFocus:()=>{c.trim()&&f(!0)},onBlur:()=>{setTimeout(()=>f(!1),200)},onKeyDown:I,placeholder:"Search files...",className:`w-full pl-8 ${c?"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`}),c&&n("button",{type:"button",onMouseDown:P=>{P.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"})})}),h&&$.length>0&&n("div",{ref:v,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:$.map((P,H)=>d("div",{onMouseDown:W=>{W.preventDefault(),T(P)},onMouseEnter:()=>m(H),className:`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm ${H===u?"bg-[#f0f9ff]":"hover:bg-gray-50"}`,children:[n(ds,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-gray-700 truncate",title:P.filePath,children:(()=>{const W=P.filePath.toLowerCase().indexOf(c.toLowerCase());if(W===-1)return P.filePath;const F=P.filePath.slice(0,W),J=P.filePath.slice(W,W+c.length),Y=P.filePath.slice(W+c.length);return d(xe,{children:[F,n("span",{className:"font-semibold text-[#005C75]",children:J}),Y]})})()}),d("span",{className:"text-xs text-gray-400 ml-auto flex-shrink-0",children:[P.matchingRules.length," rule",P.matchingRules.length!==1?"s":""]})]},P.filePath))})]}),n("div",{className:"flex-1"}),d("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"})]}),d("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"})]})]}),d("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"}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Rules",d("span",{className:"relative group",children:[n(Ia,{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"})]})]}),d("span",{className:"text-[11px] uppercase tracking-wider text-gray-400 font-medium flex items-center justify-center gap-1 whitespace-nowrap",children:["Unreviewed Tokens",d("span",{className:"relative group",children:[n(Ia,{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"})]})]})]}),E&&n("div",{className:"px-5 py-6",children:d("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"})]})}),!E&&(_.length>0||g)&&n("div",{className:"max-h-[400px] overflow-y-auto",children:(g?[g,..._.filter(H=>H.filePath!==g.filePath)].slice(0,8):_.slice(0,8)).map((P,H)=>{const W=P.matchingRules.length,F=P.matchingRules.filter(G=>!t[G.filePath]),J=F.length,Y=F.reduce((G,q)=>G+q.bodyLength,0),z=J>0,A=i===P.filePath,B=(g==null?void 0:g.filePath)===P.filePath;return d("div",{children:[d("div",{onClick:()=>l(A?null:P.filePath),className:`grid grid-cols-[1fr_140px_150px] px-5 py-2.5 items-center border-b border-gray-50 cursor-pointer ${B?"bg-[#f0f9ff] hover:bg-[#e0f2fe]":"hover:bg-gray-50"}`,children:[d("div",{className:"flex items-center gap-2 min-w-0",children:[A?n(wt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}):n(Xt,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n(ds,{className:"w-3.5 h-3.5 text-gray-400 flex-shrink-0"}),n("span",{className:"text-sm text-gray-900 truncate",title:P.filePath,children:B?P.filePath:S(P.filePath)})]}),d("span",{className:"text-sm text-center",children:[n("span",{className:z?"font-semibold text-[#1A5276]":"text-gray-400",children:J}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:W})]}),d("span",{className:"text-sm text-center",children:[n("span",{className:z?"font-semibold text-[#1A5276]":"text-gray-400",children:gr(Y).toLocaleString()}),n("span",{className:"text-gray-300",children:" / "}),n("span",{className:"text-gray-500",children:gr(P.totalTextLength).toLocaleString()})]})]}),A&&d("div",{className:"bg-gray-50 border-b border-gray-100",children:[P.matchingRules.map(G=>{const q=r.find(U=>U.filePath===G.filePath),Q=t[G.filePath]??!1;return d("div",{onClick:U=>{U.stopPropagation(),q&&s(q)},className:"flex items-center gap-2 px-5 pl-12 py-2 hover:bg-gray-100 cursor-pointer",children:[n(ls,{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:q?Qs(q.body,q.filePath):G.filePath}),d("span",{className:"text-xs text-gray-400 flex-shrink-0",children:[gr(G.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"})})})]},G.filePath)}),d("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:G=>{G.stopPropagation(),w({filePath:P.filePath,rulePaths:P.matchingRules.map(q=>q.filePath)})},className:"px-3 py-1 text-xs font-medium text-[#005C75] border border-[#005C75] rounded hover:bg-[#f0f9ff] cursor-pointer",children:"Prompt"})]})]})]},P.filePath)})}),!E&&_.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(VS,{filePath:x.filePath,rulePaths:x.rulePaths,onClose:()=>w(null)})]})}function KS({rule:e,changeInfo:t,isReviewed:r,onApprove:s,onEdit:a,onDelete:o,onClose:i}){const l=Qs(e.body,e.filePath),c=gr(e.body.length),p=e.frontmatter.category,u=`.claude/rules/${e.filePath}`,[m,h]=M(null),f=(t==null?void 0:t.changeType)==="added"||m!=null&&m.commitCount!=null&&m.commitCount<=1&&!(m.commitCount===1&&m.isUncommitted);return re(()=>{h(null),fetch(`/api/memory?action=rule-diff&filePath=${encodeURIComponent(e.filePath)}`).then(g=>g.json()).then(g=>{g.diff&&h(g.diff)}).catch(()=>{})},[e.filePath]),re(()=>{const g=y=>{y.key==="Escape"&&i()};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[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:d("div",{className:"rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",style:{backgroundColor:"#F8F7F6"},onClick:g=>g.stopPropagation(),children:[n("div",{className:"px-6 pt-5 pb-4",children:d("div",{className:"flex items-start justify-between",children:[d("div",{className:"min-w-0 flex-1",children:[d("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&&d(xe,{children:[n("span",{className:"text-xs text-gray-400 flex-shrink-0",children:In(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})]})]}),p&&d("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:p})]}),d("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:u}),n(mt,{content:u,icon:!0,iconSize:12,className:"p-0.5 rounded text-gray-400 hover:text-gray-600 transition-colors",ariaLabel:"Copy file path"})]}),d("div",{className:"text-[11px] text-gray-400 uppercase tracking-wider font-medium",children:["TOKENS: ~",c.toLocaleString()]})]}),d("div",{className:"flex items-center gap-2 flex-shrink-0 ml-4",children:[d("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(Nt,{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(zn,{className:"w-5 h-5"})})]})]})}),e.frontmatter.paths&&e.frontmatter.paths.length>0&&d("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((g,y)=>{const x=g.split("/"),w=x.pop()||g,b=x.length>0?x.join("/")+"/":"";return d("div",{className:"flex items-center gap-2 text-[13px] font-mono",children:[n(ds,{className:"w-4 h-4 text-[#005C75] flex-shrink-0"}),d("span",{children:[b&&n("span",{className:"text-gray-500",children:b}),n("span",{className:"font-bold text-gray-900",children:w})]})]},y)})})]}),f?n("div",{className:"px-6 pb-4",children:d("div",{className:"text-[13px] text-gray-500",children:["Created"," ",t!=null&&t.date?In(t.date):m!=null&&m.date?In(m.date):"recently"]})}):m&&n("div",{className:"px-6 pb-4",children:d("details",{children:[d("summary",{className:"text-[13px] text-gray-700 font-semibold cursor-pointer",children:["Recent change: ",m.commitMessage," —"," ",In(m.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:m.diff.split(`
|
|
492
|
-
`).map((g,y)=>{let x="";return g.startsWith("+")&&!g.startsWith("+++")?x="text-green-400":g.startsWith("-")&&!g.startsWith("---")?x="text-red-400":g.startsWith("@@")&&(x="text-cyan-400"),n("div",{className:x,children:g},y)})})]})}),d("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(Jd,{content:e.body})})]})]})})}function qS(){return d("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 QS(){return d("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 ZS(){return n("div",{className:"bg-[#f9f9f9] min-h-screen",children:d("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans max-w-3xl mx-auto",children:[d("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."})]}),d("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"}),d("ol",{className:"space-y-5",children:[d("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"})]}),d("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"}),d("div",{children:[d("div",{className:"flex items-center gap-2 pt-0.5",children:[n("span",{className:"text-[14px] font-medium text-gray-900",children:"Run"}),n(bl,{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."})]})]}),d("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"}),d("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."})]})]})]})]}),d("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"}),d("div",{className:"relative",children:[n("div",{className:"absolute left-[15px] top-8 bottom-4",style:{borderLeft:"2px dotted #B0BEC5"}}),d("div",{className:"space-y-6",children:[d("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"})}),d("div",{children:[d("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."})]})]}),d("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"})}),d("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."})]})]}),d("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"})}),d("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."})]})]})]})]})]}),d("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(bl,{value:"/codeyam-memory"}),n("span",{className:"text-white text-[15px] font-medium",children:"in Claude Code to get started"})]})]})})}function bl({value:e}){const[t,r]=M(!1);return d("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(Nt,{className:"w-3.5 h-3.5 text-green-400"}):d("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 ts({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:d("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}),d("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 XS({searchFilter:e,onSearchChange:t,onCreateNew:r,onLearnMore:s,reviewCounts:a}){return d("div",{className:"mb-8",children:[d("div",{className:"flex flex-wrap items-center justify-between gap-4 mb-6",children:[d("div",{children:[d("div",{className:"flex items-center gap-3 mb-2",children:[n(qS,{}),n("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),d("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."})]})]}),d("div",{className:"flex items-center gap-3",children:[d("div",{className:"relative",children:[n(Cr,{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"})]}),d("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(ro,{className:"w-4 h-4"}),"New Rule"]})]})]}),d("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[n(ts,{label:"Total Rules",count:a.total,icon:n(QS,{}),bgColor:"#EDF1F3",iconBgColor:"#E0E9EC",textColor:"#005C75"}),n(ts,{label:"Unreviewed",count:a.unreviewed,icon:n(np,{className:"w-5 h-5 text-[#1A5276]"}),bgColor:"#E9F0FB",iconBgColor:"#DBE9FF",textColor:"#1A5276"}),n(ts,{label:"Reviewed",count:a.reviewed,icon:n(Nt,{className:"w-5 h-5 text-[#1B7A4A]"}),bgColor:"#EAFBEF",iconBgColor:"#D4EDDB",textColor:"#1B7A4A"}),n(ts,{label:"Stale",count:a.stale,icon:n(Wl,{className:"w-5 h-5 text-[#5B21B6]"}),bgColor:"#EDE9FB",iconBgColor:"#DDD6FE",textColor:"#5B21B6"})]})]})}function eC({onClose:e,onCreateNew:t}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("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(zn,{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?"}),d("div",{className:"text-gray-600 text-[15px] space-y-3 mb-6",children:[d("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:d("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(ro,{className:"w-4 h-4"}),"New Rule"]})})]})})}function tC({rule:e,onConfirm:t,onCancel:r}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:d("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?"}),d("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."]}),d("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 wl="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!",vl="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function Nl({text:e}){const[t,r]=M(!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?d(xe,{children:[n(Nt,{className:"w-4 h-4"}),"Copied!"]}):d(xe,{children:[n(Et,{className:"w-4 h-4"}),"Copy Prompt"]})})}function nC({onClose:e}){return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("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(zn,{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:wl,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(Nl,{text:wl})}),d("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:vl,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(Nl,{text:vl})})]})]})})}function rC(){const[e,t]=M(!1);return d(xe,{children:[d("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(nC,{onClose:()=>t(!1)})]})}function sC(e){return`Can you help me review my unreviewed rules? The following rules in \`.claude/rules\` have not been reviewed yet:
|
|
493
|
-
|
|
494
|
-
${e.map(r=>`- \`.claude/rules/${r}\``).join(`
|
|
495
|
-
`)}
|
|
496
|
-
|
|
497
|
-
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 Sl="Can you mark all of these rules as reviewed in `.claude/codeyam-rule-state.json`?";function Cl({text:e}){const[t,r]=M(!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?d(xe,{children:[n(Nt,{className:"w-4 h-4"}),"Copied!"]}):d(xe,{children:[n(Et,{className:"w-4 h-4"}),"Copy Prompt"]})})}function aC({onClose:e,unreviewedRulePaths:t}){const r=sC(t);return n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:d("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(zn,{className:"w-6 h-6"})}),n("h2",{className:"text-xl font-bold mb-2",children:"Audit Unreviewed Rules"}),d("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(Cl,{text:r})}),d("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:Sl,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(Cl,{text:Sl})})]})]})})}function oC({unreviewedRulePaths:e}){const[t,r]=M(!1);return e.length===0?d("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."})]}):d(xe,{children:[d("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"}),d("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(aC,{onClose:()=>r(!1),unreviewedRulePaths:e})]})}const iC=()=>[{title:"Memory - CodeYam"},{name:"description",content:"Manage Claude Memory documentation"}];async function lC({request:e}){try{const r=await(await fetch(new URL("/api/memory",e.url).toString())).json();return r.error?X({memories:[],reviewedStatus:{},memoryInitialized:r.memoryInitialized??!1,error:r.error}):r.memoryInitialized??!1?X({memories:r.memories||[],reviewedStatus:r.reviewedStatus||{},memoryInitialized:!0,error:null}):X({memories:[],reviewedStatus:{},memoryInitialized:!1,error:null})}catch(t){return console.error("Failed to load memories:",t),X({memories:[],reviewedStatus:{},memoryInitialized:!1,error:"Failed to load memories"})}}const cC=Qe(function(){const{memories:t,reviewedStatus:r,memoryInitialized:s,error:a}=tt(),o=Ue(),i=Lt(),[l,c]=M(""),[p,u]=M(null),[m,h]=M(new Set(["root"])),[f,g]=M(null),[y,x]=M(!1),[w,b]=M(null),[v,N]=M(0),[C,E]=M(!1),[k,_]=M(null),[S,j]=M(null),[$,T]=M({}),R=U=>{h(D=>{const O=new Set(D);return O.has(U)?O.delete(U):O.add(U),O})};jt({source:"memory-page"});const I=ae(()=>({...r,...$}),[r,$]),P=ge(o.state);re(()=>{const U=P.current==="loading"||P.current==="submitting",D=o.state==="idle";U&&D&&o.data&&(i.revalidate(),g(null),x(!1),N(O=>O+1)),P.current=o.state},[o.state,o.data,i]),re(()=>{T(U=>{const D={};for(const[O,V]of Object.entries(U))r[O]!==V&&(D[O]=V);return Object.keys(D).length===Object.keys(U).length?U:D})},[r]);const H=(U,D)=>{T(O=>({...O,[U]:!0})),o.submit({action:"mark-reviewed",filePath:U,lastModified:D},{method:"POST",action:"/api/memory",encType:"application/json"})},W=U=>{T(D=>({...D,[U]:!1})),o.submit({action:"mark-unreviewed",filePath:U},{method:"POST",action:"/api/memory",encType:"application/json"})},F=(U,D)=>{_(U),j(D??null)},J=ae(()=>{let U=t;if(l.trim()){const D=l.toLowerCase();U=U.filter(O=>{var ne;return(((ne=O.filePath.split("/").pop())==null?void 0:ne.replace(".md",""))||"").toLowerCase().includes(D)||O.body.toLowerCase().includes(D)})}return U},[t,l]),Y=ae(()=>p?J.some(D=>D.filePath===p)?J.filter(D=>D.filePath===p):J.filter(D=>D.filePath.startsWith(p+"/")||D.filePath===p):J,[J,p]),z=(U,D)=>{const O=f?"update":"create";o.submit({action:O,filePath:U,content:D},{method:"POST",action:"/api/memory",encType:"application/json"})},A=U=>{o.submit({action:"delete",filePath:U.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),b(null)},B=ae(()=>{const U=t.filter(D=>I[D.filePath]).length;return{total:t.length,reviewed:U,unreviewed:t.length-U,stale:0}},[t,I]),G=ae(()=>{const U=new Set(["root"]);for(const D of J){const O=D.filePath.split("/");O.pop();let V="";for(const ne of O)V=V?`${V}/${ne}`:ne,U.add(V)}return U},[J]),q=G.size===m.size&&[...G].every(U=>m.has(U)),Q=()=>{h(q?new Set(["root"]):new Set(G))};return a?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("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:d("div",{className:"px-6 sm:px-12 lg:px-20 py-8 lg:py-12 font-sans",children:[n(XS,{searchFilter:l,onSearchChange:c,onCreateNew:()=>x(!0),onLearnMore:()=>E(!0),reviewCounts:B}),(y||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),g(null)},children:n("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:U=>U.stopPropagation(),children:n(YS,{rule:f,onSave:z,onCancel:()=>{x(!1),g(null)}})})}),d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(JS,{memories:J,reviewedStatus:I,onViewRule:F,refreshKey:v}),n(GS,{onEditRule:g,onDeleteRule:b,refreshKey:v,reviewedStatus:I,onMarkReviewed:H,onMarkUnreviewed:W,memories:t,onViewRule:F})]}),d("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 mb-8",children:[n(oC,{unreviewedRulePaths:t.filter(U=>!I[U.filePath]).map(U=>U.filePath)}),n(rC,{})]}),d("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:G.size>1&&n("button",{onClick:Q,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:q?"Collapse All":"Expand All"})})]}),d("div",{className:"flex gap-6",children:[n("div",{className:"hidden lg:block w-80 flex-shrink-0",children:n(US,{memories:J,selectedPath:p,onSelectPath:u,expandedFolders:m,onToggleFolder:R})}),n("div",{className:"flex-1 min-w-0",children:t.length===0?d("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[n(rp,{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"}),d("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."]}),d("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(ro,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):d("div",{children:[p&&d("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:p||"(root)"}),n("button",{onClick:()=>u(null),className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),n(WS,{memories:Y,onEdit:g,onDelete:b,expandedFolders:m,onToggleFolder:R,reviewedStatus:I,onMarkReviewed:H,onMarkUnreviewed:W,onViewRule:F})]})})]}),n("div",{className:"mt-8 mb-8",children:n(Ce,{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:d("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:d("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"})]})}),d("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"})]})]})})}),k&&!f&&(()=>{const U=t.find(D=>D.filePath===k.filePath)??k;return n(KS,{rule:U,changeInfo:S??void 0,isReviewed:I[U.filePath]??!1,onApprove:()=>{I[U.filePath]??!1?W(U.filePath):H(U.filePath,U.lastModified),_(null)},onEdit:()=>{g(U)},onDelete:()=>{b(U),_(null)},onClose:()=>_(null)})})(),C&&n(eC,{onClose:()=>E(!1),onCreateNew:()=>{E(!1),x(!0)}}),w&&n(tC,{rule:w,onConfirm:A,onCancel:()=>b(null)})]})}):n(ZS,{})}),dC=Object.freeze(Object.defineProperty({__proto__:null,default:cC,loader:lC,meta:iC},Symbol.toStringTag,{value:"Module"}));function Ma(e){return`${e.filePath||""}::${e.name}`}function Gd(e,t){const r=Ue(),{showToast:s}=mo(),[a,o]=M(new Map);re(()=>{if(r.state==="idle"&&r.data){const h=r.data;h!=null&&h.error&&s(`Error: ${h.error}`,"error",6e3)}},[r.state,r.data,s]),re(()=>{var f;if(a.size===0)return;const h=new Set;(f=t==null?void 0:t.jobs)==null||f.forEach(g=>{var y;(y=g.entityShas)==null||y.forEach(x=>{a.forEach((w,b)=>{w===x&&h.add(b)})})}),e==null||e.forEach(g=>{a.forEach((y,x)=>{y===g&&h.add(x)})}),h.size>0&&o(g=>{const y=new Map(g);return h.forEach(x=>y.delete(x)),y})},[t,e,a]);const i=oe(h=>{console.log("Generate analysis clicked for entity:",h.sha,h.name);const f=Ma(h);o(y=>new Map(y).set(f,h.sha));const g=new FormData;g.append("entitySha",h.sha),g.append("filePath",h.filePath||""),r.submit(g,{method:"post",action:"/api/analyze"})},[r]),l=oe(h=>{const f=h.filter(x=>x.entityType==="visual"||x.entityType==="library");console.log("Generate analysis for all entities:",f.length),o(x=>{const w=new Map(x);return f.forEach(b=>w.set(Ma(b),b.sha)),w});const g=f.map(x=>x.sha).join(","),y=new FormData;y.append("entityShas",g),r.submit(y,{method:"post",action:"/api/analyze"})},[r]),c=oe(h=>(e==null?void 0:e.includes(h))??!1,[e]),p=oe(h=>{const f=Ma(h);return a.has(f)},[a]),u=oe(h=>{var f;return((f=t==null?void 0:t.jobs)==null?void 0:f.some(g=>{var y;return(y=g.entityShas)==null?void 0:y.includes(h)}))??!1},[t]),m=ae(()=>Array.from(a.keys()),[a]);return{isAnalyzing:r.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:l,isEntityBeingAnalyzed:c,isEntityPending:p,isEntityInQueue:u,pendingEntityKeys:m}}function ni({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:d("div",{className:"flex justify-between items-center px-3 py-2",children:[d("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[n("span",{className:"w-4"}),n("span",{children:"FILE"})]}),d("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"})}),d("div",{className:"flex gap-4 items-center",children:[n("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),d("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 uC({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 d("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 ri({filePath:e,isExpanded:t,onToggle:r,fileStatus:s,simulationPreviews:a,entityCount:o,state:i,lastModified:l,actionButton:c,uncommittedCount:p,children:u,isNotAnalyzable:m=!1,isUncommitted:h=!1}){return d("div",{className:"bg-white overflow-hidden",style:t?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[d("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${m?"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:[d("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(ec,{filePath:e}),s&&n(uC,{status:typeof s=="string"?s:s.status,variant:"full"}),h&&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"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(h||i==="out-of-date")&&d("div",{className:"flex gap-1.5 items-center",children:[h&&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"&&!h&&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}),d("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:d("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:Rd(l)}),n("div",{style:{width:"127px"},className:"flex justify-center",children:c})]})]})]}),t&&u&&n("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function si({entities:e,maxPreviews:t=3}){var s,a,o,i,l;const r=[];for(const c of e){if(r.length>=t)break;const p=((a=(s=c.analyses)==null?void 0:s[0])==null?void 0:a.scenarios)||[];if(c.entityType==="library"){const u=p.find(m=>{var h,f;return((h=m.metadata)==null?void 0:h.executionResult)||((f=m.metadata)==null?void 0:f.error)});u&&r.push({type:"library",scenario:u,entitySha:c.sha})}else if(c.entityType==="visual"){const u=p.find(m=>{var h,f;return(f=(h=m.metadata)==null?void 0:h.screenshotPaths)==null?void 0:f[0]});if(u){const m=(i=(o=u.metadata)==null?void 0:o.screenshotPaths)==null?void 0:i[0],h=!!((l=u.metadata)!=null&&l.error);m&&r.push({type:"screenshot",screenshot:m,hasError:h,scenario:u,entitySha:c.sha})}}}return r.length===0?n("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):n(xe,{children:r.map((c,p)=>{if(c.type==="screenshot"&&c.screenshot){const u=c.hasError?"border-red-400":"border-gray-200";return d(Ce,{to:c.scenario?`/entity/${c.entitySha}/scenarios/${c.scenario.id}`:`/entity/${c.entitySha}`,className:`relative w-[50px] h-[38px] border ${u} rounded overflow-hidden bg-gray-50 shrink-0 flex items-center justify-center cursor-pointer transition-all hover:scale-105 hover:shadow-md`,onClick:m=>m.stopPropagation(),children:[n(rt,{screenshotPath:c.screenshot,alt:`Preview ${p+1}`,className:"max-w-full max-h-full object-contain object-center"}),c.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(is,{size:12,color:"white"})})]},`screenshot-${p}`)}return c.type==="library"&&c.scenario&&c.entitySha?n($d,{scenario:c.scenario,entitySha:c.entitySha,size:"small",showBorder:!0},`library-${p}`):null})})}function ai({entity:e,isActivelyAnalyzing:t,isQueued:r,onGenerateSimulation:s}){var u,m;const a=t||r?[{entityShas:[e.sha]}]:[],o=yt(e,a,t),i=e.entityType==="visual"||e.entityType==="library",l=i&&(o==="not-analyzed"||o==="out-of-date")&&!t&&!r,p=(((m=(u=e.analyses)==null?void 0:u[0])==null?void 0:m.scenarios)||[]).filter(h=>{var f,g;return(g=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:g[0]});return d("div",{className:"bg-white rounded-lg",children:[d(Ce,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[d("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(dt,{type:"type"})})}):n(dt,{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(Go,{type:e.entityType||"other"})]}),d("div",{className:"flex items-center gap-3 shrink-0",children:[n("div",{style:{width:"160px"}}),d("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"?d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[d("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"?d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("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:h=>{h.preventDefault(),h.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:h=>{h.preventDefault(),h.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"})})]})]})]}),p.length>0&&n("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:p.map((h,f)=>{var y,x;const g=(x=(y=h.metadata)==null?void 0:y.screenshotPaths)==null?void 0:x[0];return g?n(Ce,{to:`/entity/${e.sha}?scenario=${h.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:w=>w.stopPropagation(),children:n(rt,{screenshotPath:g,alt:h.name,className:"max-w-full max-h-full object-contain object-center"})},h.id):null})})]})}function pC({entities:e,page:t,itemsPerPage:r=50,currentRun:s,filter:a,entityType:o,queueState:i,isEntityPending:l,pendingEntityKeys:c,onGenerateSimulation:p,onGenerateAllSimulations:u,totalFilesCount:m,totalEntitiesCount:h,uncommittedFilesCount:f,showOnlyUncommitted:g,onToggleUncommitted:y}){const[x,w]=Ln(),[b,v]=M(new Set),[N,C]=M(""),[E,k]=M(!1),[_,S]=M("all"),[j,$]=M("desc"),T=o||"all",R=ae(()=>{let A=e;return T!=="all"&&(A=A.filter(B=>B.entityType===T)),a==="analyzed"&&(A=A.filter(B=>B.analyses&&B.analyses.length>0)),A},[e,T,a]),I=ae(()=>{const A=new Map,B=new Map,G=new Map;R.forEach(D=>{var ne,ie;const O=`${D.filePath}::${D.name}`,V=B.get(O);if(!V)B.set(O,D),G.set(O,[]);else{const we=((ne=V.metadata)==null?void 0:ne.editedAt)||V.createdAt||"",le=((ie=D.metadata)==null?void 0:ie.editedAt)||D.createdAt||"";let ce=!1;if(le>we)ce=!0;else if(le===we){const ve=V.createdAt||"";ce=(D.createdAt||"")>ve}ce?(G.get(O).push(V),B.set(O,D)):G.get(O).push(D)}}),B.forEach((D,O)=>{var ne;if(!(D.analyses&&D.analyses.length>0)&&((ne=D.metadata)!=null&&ne.previousVersionWithAnalyses)){const we=(G.get(O)||[]).find(le=>{var ce;return le.sha===((ce=D.metadata)==null?void 0:ce.previousVersionWithAnalyses)});we&&we.analyses&&we.analyses.length>0&&(D.analyses=we.analyses)}}),Array.from(B.values()).sort((D,O)=>{var ie,we,le,ce;const V=!((ie=D.metadata)!=null&&ie.notExported)&&!((we=D.metadata)!=null&&we.namedExport),ne=!((le=O.metadata)!=null&&le.notExported)&&!((ce=O.metadata)!=null&&ce.namedExport);return V&&!ne?-1:!V&&ne?1:0}).forEach(D=>{var we,le,ce,ve,Ee;const O=D.filePath??"No File Path";A.has(O)||A.set(O,{filePath:O,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const V=A.get(O);V.entities.push(D),V.totalCount++,(we=D.metadata)!=null&&we.isUncommitted&&V.uncommittedCount++;const ne=((ve=(ce=(le=D.analyses)==null?void 0:le[0])==null?void 0:ce.scenarios)==null?void 0:ve.length)||0;V.simulationCount+=ne;const ie=((Ee=D.metadata)==null?void 0:Ee.editedAt)||D.updatedAt;ie&&(!V.lastUpdated||new Date(ie)>new Date(V.lastUpdated))&&(V.lastUpdated=ie)});const q=(i==null?void 0:i.jobs)||[],Q=D=>{const O=`${D.filePath||""}::${D.name}`;return(c==null?void 0:c.includes(O))||!1};A.forEach(D=>{const O=D.entities.map(V=>Q(V)?"queued":yt(V,q));O.includes("analyzing")||O.includes("queued")?D.state="analyzing":O.includes("incomplete")?D.state="incomplete":O.includes("out-of-date")?D.state="out-of-date":O.includes("not-analyzed")?D.state="not-analyzed":D.state="up-to-date"}),A.forEach(D=>{var O,V,ne,ie,we;for(const le of D.entities){if(D.previewScreenshots.length+D.previewLibraryScenarios.length>=3)break;const ve=((V=(O=le.analyses)==null?void 0:O[0])==null?void 0:V.scenarios)||[];if(le.entityType==="library"){const Ee=ve.find(he=>{var Z,Se;return((Z=he.metadata)==null?void 0:Z.executionResult)||((Se=he.metadata)==null?void 0:Se.error)});Ee&&D.previewLibraryScenarios.push({scenario:Ee,entitySha:le.sha})}else{const Ee=ve.find(he=>{var Z,Se;return(Se=(Z=he.metadata)==null?void 0:Z.screenshotPaths)==null?void 0:Se[0]});if(Ee){const he=(ie=(ne=Ee.metadata)==null?void 0:ne.screenshotPaths)==null?void 0:ie[0],Z=!!((we=Ee.metadata)!=null&&we.error);he&&!D.previewScreenshots.includes(he)&&(D.previewScreenshots.push(he),D.previewScreenshotErrors.push(Z))}}}});const U=Array.from(A.values());return U.sort((D,O)=>{if(a==="analyzed"){const ie=Math.max(...D.entities.filter(le=>{var ce,ve;return(ve=(ce=le.analyses)==null?void 0:ce[0])==null?void 0:ve.createdAt}).map(le=>new Date(le.analyses[0].createdAt).getTime()),0),we=Math.max(...O.entities.filter(le=>{var ce,ve;return(ve=(ce=le.analyses)==null?void 0:ce[0])==null?void 0:ve.createdAt}).map(le=>new Date(le.analyses[0].createdAt).getTime()),0);return j==="desc"?we-ie:ie-we}if(D.uncommittedCount>0&&O.uncommittedCount===0)return-1;if(D.uncommittedCount===0&&O.uncommittedCount>0)return 1;const V=D.lastUpdated?new Date(D.lastUpdated).getTime():0,ne=O.lastUpdated?new Date(O.lastUpdated).getTime():0;return j==="desc"?ne-V:V-ne}),U},[R,a,j,i,c]),P=ae(()=>{let A=I;if(_!=="all"&&(A=A.filter(B=>B.state===_)),N.trim()){const B=N.toLowerCase();A=A.filter(G=>G.filePath.toLowerCase().includes(B))}return A},[I,N,_]),H=(t-1)*r,W=H+r,F=P.slice(H,W),J=Math.ceil(P.length/r),Y=A=>{v(B=>{const G=new Set(B);return G.has(A)?G.delete(A):G.add(A),G})},z=()=>{$(A=>A==="desc"?"asc":"desc")};return d("div",{children:[d("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"}),d("div",{className:"flex gap-3",children:[d("div",{className:"relative w-[130px]",children:[d("select",{value:T,onChange:A=>{const B=A.target.value,G=new URLSearchParams(x);B==="all"?G.delete("entityType"):G.set("entityType",B),G.set("page","1"),w(G)},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(wt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"relative w-[130px]",children:[d("select",{value:_,onChange:A=>S(A.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(wt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),d("div",{className:"flex-1 relative",children:[n(Cr,{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:N,onChange:A=>C(A.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"})]})]})]}),m!==void 0&&h!==void 0&&f!==void 0&&n("div",{className:"mb-3",children:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center",children:[d("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?"file":"files"]}),d("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:d("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:"|"}),d("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((A,B)=>A+B.totalCount,0)})," ",P.reduce((A,B)=>A+B.totalCount,0)===1?"entity":"entities"]}),n("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),g?d("button",{onClick:y,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:[P.filter(A=>A.uncommittedCount>0).length," ","uncommitted"," ",P.filter(A=>A.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"})})]}):d("button",{onClick:y,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&&d("div",{className:"flex gap-6",children:[d("button",{onClick:()=>{v(new Set(F.map(A=>A.filePath))),k(!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(Hl,{className:"w-3.5 h-3.5"}),"Expand All"]}),d("button",{onClick:()=>{v(new Set),k(!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(Vl,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),n(ni,{showActions:!0,sortOrder:j,onSortChange:z}),n("div",{className:"flex flex-col gap-[3px]",children:F.map(A=>{const B=b.has(A.filePath),q=A.entities.filter(O=>(O.entityType==="visual"||O.entityType==="library")&&(yt(O,(i==null?void 0:i.jobs)||[])==="not-analyzed"||yt(O,(i==null?void 0:i.jobs)||[])==="out-of-date"||yt(O,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,Q=O=>{var V;return((V=s==null?void 0:s.currentEntityShas)==null?void 0:V.includes(O))||!1},U=O=>{var V;return l!=null&&l(O)?!0:((V=i==null?void 0:i.jobs)==null?void 0:V.some(ne=>{var ie;return(ie=ne.entityShas)==null?void 0:ie.includes(O.sha)}))||!1},D=O=>{p==null||p(O)};return n(ri,{filePath:A.filePath,isExpanded:B,onToggle:()=>Y(A.filePath),simulationPreviews:n(si,{entities:A.entities,maxPreviews:1}),entityCount:A.totalCount,state:A.state,lastModified:A.lastUpdated,uncommittedCount:A.uncommittedCount,isUncommitted:A.uncommittedCount>0,actionButton:q?n("button",{onClick:O=>{O.stopPropagation();const V=A.entities.filter(ne=>(ne.entityType==="visual"||ne.entityType==="library")&&(yt(ne,(i==null?void 0:i.jobs)||[])==="not-analyzed"||yt(ne,(i==null?void 0:i.jobs)||[])==="out-of-date"||yt(ne,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(V)},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:A.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:A.entities.sort((O,V)=>{var ce,ve,Ee,he;const ne=!((ce=O.metadata)!=null&&ce.notExported)&&!((ve=O.metadata)!=null&&ve.namedExport),ie=!((Ee=V.metadata)!=null&&Ee.notExported)&&!((he=V.metadata)!=null&&he.namedExport);if(ne&&!ie)return-1;if(!ne&&ie)return 1;const we=O.entityType==="visual"||O.entityType==="library",le=V.entityType==="visual"||V.entityType==="library";return we&&!le?-1:!we&&le?1:O.name.localeCompare(V.name)}).map(O=>n(ai,{entity:O,isActivelyAnalyzing:Q(O.sha),isQueued:U(O),onGenerateSimulation:D},O.sha))},A.filePath)})}),J>1&&d("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"}),d("span",{children:["Page ",t," of ",J]}),t<J&&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 mC=()=>[{title:"Files & Entities - CodeYam"},{name:"description",content:"Browse your codebase files and entities"}];async function hC({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:[]},[c,p]=await Promise.all([wn(),Wn()]);return X({entities:c,currentCommit:p,page:s,filter:a,entityType:o,queueState:l})}catch(r){return console.error("Failed to load entities:",r),X({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const fC=Qe(function(){var N,C,E;const{entities:t,currentCommit:r,page:s,filter:a,entityType:o,queueState:i,error:l}=tt();Lt();const[c,p]=Ln(),[u,m]=M(!1);jt({source:"files-page"});const{handleGenerateSimulation:h,handleGenerateAllSimulations:f,isEntityPending:g,pendingEntityKeys:y}=Gd((C=(N=r==null?void 0:r.metadata)==null?void 0:N.currentRun)==null?void 0:C.currentEntityShas,i),x=t||[],w=ae(()=>{const k=new Set([]);for(const _ of x)k.add(_.filePath??"No File Path");return Array.from(k)},[x]),b=ae(()=>{let k=x;return u&&(k=k.filter(_=>{var S;return(S=_.metadata)==null?void 0:S.isUncommitted})),k.sort((_,S)=>{var j,$,T,R,I,P;return(j=_.metadata)!=null&&j.isUncommitted&&!(($=S.metadata)!=null&&$.isUncommitted)?-1:!((T=_.metadata)!=null&&T.isUncommitted)&&((R=S.metadata)!=null&&R.isUncommitted)?1:new Date(((I=S.metadata)==null?void 0:I.editedAt)||0).getTime()-new Date(((P=_.metadata)==null?void 0:P.editedAt)||0).getTime()})},[x,u]),v=ae(()=>{var _;const k=new Set([]);for(const S of x)(_=S.metadata)!=null&&_.isUncommitted&&k.add(S.filePath??"No File Path");return Array.from(k)},[x]);return l?n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("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:d("div",{className:"px-20 py-12 font-sans",children:[d("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:d("div",{className:"max-w-md mx-auto",children:[n("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),d("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:d("div",{className:"px-20 py-12 font-sans",children:[d("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(pC,{entities:b,page:s,itemsPerPage:50,currentRun:(E=r==null?void 0:r.metadata)==null?void 0:E.currentRun,filter:a,entityType:o,queueState:i,isEntityPending:g,pendingEntityKeys:y,onGenerateSimulation:h,onGenerateAllSimulations:f,totalFilesCount:w.length,totalEntitiesCount:x.length,uncommittedFilesCount:v.length,showOnlyUncommitted:u,onToggleUncommitted:()=>m(!u)})]})})}),gC=Object.freeze(Object.defineProperty({__proto__:null,default:fC,loader:hC,meta:mC},Symbol.toStringTag,{value:"Module"})),yC=()=>[{title:"Labs - CodeYam"},{name:"description",content:"Experimental features"}];async function xC({request:e}){var t;try{const r=await Fe();if(!r)return X({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Project not found"});const{project:s}=await Re(r),a=Ne()||process.cwd(),o=Ad(a)||"";let i="";try{const c=await Ms();if(c!=null&&c.webapps&&Array.isArray(c.webapps)){const p=c.webapps.map(u=>u.framework).filter(Boolean);p.length>0&&(i=p.join(", "))}}catch{}const l=Md(r);return X({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),X({labs:null,projectSlug:null,defaultEmail:"",detectedTechStack:"",unlockCode:null,error:"Failed to load labs configuration"})}}async function bC({request:e}){try{const t=await e.formData(),r=t.get("feature"),s=t.get("enabled")==="true";if(!r)return X({success:!1,error:"Missing feature name"},{status:400});const a=await Fe();return a?(r==="clearAccess"?await Dn({projectSlug:a,metadataUpdate:{labs:{accessGranted:!1,simulations:!1}}}):await Dn({projectSlug:a,metadataUpdate:{labs:{[r]:s}}}),X({success:!0,error:null})):X({success:!1,error:"Project not found"},{status:404})}catch(t){return console.error("Failed to update labs config:",t),X({success:!1,error:"Failed to save labs configuration"},{status:500})}}const wC=[{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}],_l="https://docs.google.com/forms/d/e/1FAIpQLSfopqQOQsjY9S4Ns0l3xDLzGl7iYNpKa2Wn2Xzmtxj8CR1sMA/viewform",vC=[{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 NC({onClose:e}){const t=ge(null),r=ge(0);return re(()=>{const s=t.current;if(!s)return;const a=100,o=2e3,i=500;let l=null,c=!1;const p=()=>{r.current=Date.now(),!l&&!c&&(l=setInterval(()=>{const u=Date.now()-r.current,m=s.scrollTop>a,h=u>o;m&&h&&(s.scrollTo({top:0,behavior:"smooth"}),c=!0,l&&(clearInterval(l),l=null))},i))};return s.addEventListener("scroll",p,{passive:!0}),()=>{s.removeEventListener("scroll",p),l&&clearInterval(l)}},[]),d("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"}),d("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:"×"}),d("div",{ref:t,className:"overflow-y-auto max-h-[90vh] p-4 md:p-6",children:[d("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:`${_l}?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:d("div",{className:"text-center",children:[n("div",{className:"mb-4",children:"Loading form..."}),d("div",{className:"text-sm",children:["If this takes too long,"," ",n("a",{href:_l,target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:text-blue-800 underline",children:"open the form directly"})]})]})})})})]})]})]})}function SC({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 d("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:c=>{c.target===c.currentTarget&&e()},children:[n("div",{className:"absolute inset-0 bg-black/50"}),d("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."}),d(s.Form,{method:"post",action:"/api/labs-unlock",className:"space-y-4",children:[n("input",{type:"text",name:"unlockCode",value:t,onChange:c=>r(c.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 CC=Qe(function(){const{labs:t,unlockCode:r,error:s}=tt(),a=Ue(),o=Ue(),i=Ue(),[l,c]=M(""),[p,u]=M(!1),[m,h]=M(!1);jt({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:d("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?d("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"})}),d("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:wC.map(g=>{var w;const y=(t==null?void 0:t[g.id])??g.defaultEnabled,x=o.state==="submitting"&&((w=o.formData)==null?void 0:w.get("feature"))===g.id;return n("div",{className:"border border-cygray-30 rounded-xl p-5 sm:p-8 bg-white",children:d("div",{className:"flex items-center justify-between gap-4",children:[d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-3 mb-3",children:[n("h3",{className:"text-lg font-semibold text-cyblack-100 m-0",children:g.name}),n("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${y?"bg-primary-100/15 text-primary-100":"bg-cygray-20 text-cygray-50"}`,children:y?"Enabled":"Disabled"})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed m-0",children:g.description})]}),d(o.Form,{method:"post",children:[n("input",{type:"hidden",name:"feature",value:g.id}),n("input",{type:"hidden",name:"enabled",value:String(!y)}),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 ${y?"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 ${y?"translate-x-6":"translate-x-0"}`})})]})]})},g.id)})}),r&&n("div",{className:"px-6 sm:px-12 pt-12",children:d("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."}),d("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}),d(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"})]})]})]})})]}):d("div",{className:"bg-cygray-10 min-h-screen font-sans",children:[p&&n(NC,{onClose:()=>u(!1)}),m&&n(SC,{onClose:()=>h(!1),unlockCodeInput:l,setUnlockCodeInput:c,unlockFetcher:a}),d("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"}),d("div",{className:"flex flex-wrap items-center gap-3",children:[n("button",{onClick:()=>h(!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:()=>u(!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"})]})]}),d("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."}),d("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:()=>u(!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"})}),d("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:vC.map(g=>d("div",{className:"border border-cygray-30 bg-white p-5 sm:p-8 rounded-lg",children:[d("h4",{className:"text-base font-semibold text-cyblack-100 mb-1",children:[g.title," ",d("span",{className:"font-normal text-primary-100 font-serif italic",children:["(",g.status,")"]})]}),n("p",{className:"text-sm text-cygray-50 leading-relaxed mt-3 mb-0",children:g.desc})]},g.title))})]}),n("div",{className:"px-6 sm:px-12 py-16",children:d("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:()=>u(!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."})]})})]})}),_C=Object.freeze(Object.defineProperty({__proto__:null,action:bC,default:CC,loader:xC,meta:yC},Symbol.toStringTag,{value:"Module"}));function kC(e,t,r){const[s,a]=M(()=>new Set),[o,i]=M(()=>new Set),l=ge([]),c=ge([]);return re(()=>{(t.length!==l.current.length||t.some((y,x)=>y!==l.current[x]))&&(l.current=t,a(y=>{const x=new Set;return t.forEach(w=>{y.has(w)&&x.add(w)}),x}))},[t]),re(()=>{(r.length!==c.current.length||r.some((y,x)=>y!==c.current[x]))&&(c.current=r,i(y=>{const x=new Set;return r.forEach(w=>{y.has(w)&&x.add(w)}),x}))},[r]),{expandedUncommitted:s,expandedBranch:o,setExpandedUncommitted:a,setExpandedBranch:i,toggleFile:(g,y,x)=>{x(w=>{const b=new Set(w);return b.has(g)?b.delete(g):b.add(g),b})},expandAllUncommitted:()=>{a(new Set(t))},collapseAllUncommitted:()=>{a(new Set)},expandAllBranch:()=>{i(new Set(r))},collapseAllBranch:()=>{i(new Set)}}}function EC(e,t,r){const[s,a]=M(null),[o,i]=M(null),l=Ue();re(()=>{var m,h;((m=l.data)==null?void 0:m.oldContent)!==void 0&&((h=l.data)==null?void 0:h.newContent)!==void 0&&i({oldContent:l.data.oldContent,newContent:l.data.newContent,fileName:l.data.fileName})},[l.data]);const c=m=>{a({type:"file",path:m}),i(null);const h=new FormData;h.append("actionType","getDiff"),h.append("filePath",m),h.append("diffType","branch"),h.append("baseBranch",e),h.append("currentBranch",t||""),l.submit(h,{method:"post"})},p=(m,h)=>{a({type:"entity",path:m,entitySha:h}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",m),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",t||""),f.append("entitySha",h),l.submit(f,{method:"post"})},u=()=>{a(null),i(null)};return{diffView:s,diffContent:o,isLoading:l.state==="loading"||l.state==="submitting",handleShowFileDiff:c,handleShowEntityDiff:p,handleCloseDiff:u}}function AC({diffView:e,diffContent:t,isLoading:r,entities:s,onClose:a}){var p;const[o,i]=M(!1),[l,c]=M(!1);return re(()=>{c(!0)},[]),n("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:d("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[d("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[d("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&&d("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((p=s.find(u=>u.sha===e.entitySha))==null?void 0:p.name)||e.entitySha]})]}),d("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(Tp,{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 PC({files:e,currentBranch:t,defaultBranch:r,baseBranch:s,allBranches:a,expandedFiles:o,isEntityBeingAnalyzed:i,isEntityQueued:l,sortOrder:c,onToggleFile:p,onBranchChange:u,onGenerateSimulation:m,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const x=e.flatMap(([v,{entities:N}])=>{const C=N.filter(E=>i(E.sha)||l(E)).map(E=>E.sha);return C.length>0?[{entityShas:C}]:[]}),w=v=>{const N=v.map(C=>yt(C,x));return N.includes("analyzing")||N.includes("queued")?"analyzing":N.includes("out-of-date")?"out-of-date":N.includes("not-analyzed")?"not-analyzed":"up-to-date"},b=ae(()=>[...e].sort((v,N)=>{const C=v[1].entities.reduce((S,j)=>{var T;const $=((T=j.metadata)==null?void 0:T.editedAt)||j.updatedAt;return $?S?new Date($)>new Date(S)?$:S:$:S},null),E=N[1].entities.reduce((S,j)=>{var T;const $=((T=j.metadata)==null?void 0:T.editedAt)||j.updatedAt;return $?S?new Date($)>new Date(S)?$:S:$:S},null);if(!C&&!E)return 0;if(!C)return 1;if(!E)return-1;const k=new Date(C).getTime(),_=new Date(E).getTime();return c==="desc"?_-k:k-_}),[e,c]);return n("div",{children:e.length>0?d("div",{children:[n(ni,{showActions:!0,sortOrder:c,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([v,{status:N,entities:C,isUncommitted:E}])=>{const k=o.has(v),_=w(C),S=C.reduce((R,I)=>{var H;const P=((H=I.metadata)==null?void 0:H.editedAt)||I.updatedAt;return P?R?new Date(P)>new Date(R)?P:R:P:R},null),$=C.filter(R=>R.entityType==="visual"||R.entityType==="library").length===0;let T;return $?T=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):_==="analyzing"?T=d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("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..."]}):_==="up-to-date"?T=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"}):_==="out-of-date"?T=n("button",{onClick:R=>{R.stopPropagation(),C.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!i(I.sha)&&!l(I)).forEach(I=>m(I))},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"}):_==="not-analyzed"&&(T=n("button",{onClick:R=>{R.stopPropagation(),C.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!i(I.sha)&&!l(I)).forEach(I=>m(I))},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(ri,{filePath:v,isExpanded:k,onToggle:()=>p(v),fileStatus:N,isUncommitted:E,simulationPreviews:n(si,{entities:C,maxPreviews:1}),entityCount:C.length,state:_,lastModified:S,isNotAnalyzable:$,actionButton:T,children:C.sort((R,I)=>{const P=R.entityType==="visual"||R.entityType==="library",H=I.entityType==="visual"||I.entityType==="library";return P&&!H?-1:!P&&H?1:0}).map(R=>n(ai,{entity:R,isActivelyAnalyzing:i(R.sha),isQueued:l(R),onGenerateSimulation:m},R.sha))},v)})})]}):d("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 jC({files:e,entityImpactMap:t,expandedFiles:r,isEntityBeingAnalyzed:s,isEntityQueued:a,projectSlug:o,baseBranch:i,currentBranch:l,sortOrder:c,onToggleFile:p,onShowFileDiff:u,onGenerateSimulation:m,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}){const x=ae(()=>{const v=[];return e.forEach(([N,{editedEntities:C}])=>{const E=C.filter(k=>s(k.sha)||a(k)).map(k=>k.sha);E.length>0&&v.push({entityShas:E})}),v},[e,s,a]),w=ae(()=>{const v=new Map;return e.forEach(([N,{editedEntities:C}])=>{const E=C.map(j=>yt(j,x));let k;E.includes("analyzing")||E.includes("queued")?k="analyzing":E.includes("out-of-date")?k="out-of-date":E.includes("not-analyzed")?k="not-analyzed":k="up-to-date";const _=C.reduce((j,$)=>{var R;const T=((R=$.metadata)==null?void 0:R.editedAt)||$.updatedAt;return T&&(!j||new Date(T)>new Date(j))?T:j},null),S=C.filter(j=>j.entityType==="visual"||j.entityType==="library").length;v.set(N,{state:k,lastModified:_,analyzableCount:S})}),v},[e,x]),b=ae(()=>[...e].sort((v,N)=>{const C=w.get(v[0]),E=w.get(N[0]),k=C==null?void 0:C.lastModified,_=E==null?void 0:E.lastModified;if(!k&&!_)return 0;if(!k)return 1;if(!_)return-1;const S=new Date(k).getTime(),j=new Date(_).getTime();return c==="desc"?j-S:S-j}),[e,w,c]);return e.length===0?d("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."})]}):d("div",{children:[n(ni,{showActions:!0,sortOrder:c,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:g,analyzeAllText:y}),n("div",{className:"flex flex-col gap-[3px]",children:b.map(([v,{status:N,editedEntities:C}])=>{const E=r.has(v),k=w.get(v),{state:_,lastModified:S,analyzableCount:j}=k,$=j===0;let T;return $?T=n("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):_==="analyzing"?T=d("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[d("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..."]}):_==="up-to-date"?T=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"}):_==="out-of-date"?T=n("button",{onClick:R=>{R.stopPropagation(),C.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!s(I.sha)&&!a(I)).forEach(I=>m(I))},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"}):_==="not-analyzed"&&(T=n("button",{onClick:R=>{R.stopPropagation(),C.filter(I=>(I.entityType==="visual"||I.entityType==="library")&&!s(I.sha)&&!a(I)).forEach(I=>m(I))},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(ri,{filePath:v,isExpanded:E,onToggle:()=>p(v),fileStatus:N,simulationPreviews:n(si,{entities:C,maxPreviews:1}),entityCount:C.length,state:_,lastModified:S,isNotAnalyzable:$,isUncommitted:!0,actionButton:T,children:C.sort((R,I)=>{const P=R.entityType==="visual"||R.entityType==="library",H=I.entityType==="visual"||I.entityType==="library";return P&&!H?-1:!P&&H?1:0}).map(R=>n(ai,{entity:R,isActivelyAnalyzing:s(R.sha),isQueued:a(R),onGenerateSimulation:m},R.sha))},v)})})]})}function TC({activeTab:e,onTabChange:t,uncommittedCount:r,branchCount:s}){return n("div",{className:"border-b border-gray-200",children:d("nav",{className:"flex gap-8 items-center",children:[d("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:[d("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"})]}),d("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:[d("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 MC=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function $C({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 c;return a==="branch"?c=rs(s,o,i):c=X0(s),X({...c,entitySha:l})}return X({error:"Unknown action"},{status:400})}async function IC({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,c,p]=await Promise.all([wn(),Wn(),Fe()]),u=Vn(),m=K0(),h=q0(),f=Q0(),g=a||m,y=s||h;let x=[];return g&&g!==y&&(x=ld(y,g)),X({entities:l||[],gitStatus:u,currentBranch:g,actualCurrentBranch:m,defaultBranch:h,allBranches:f,baseBranch:y,branchDiff:x,currentCommit:c,projectSlug:p,queueState:i})}catch(r){return console.error("Failed to load git data:",r),X({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 RC=Qe(function(){var _e,Le;const{entities:t,gitStatus:r,currentBranch:s,actualCurrentBranch:a,defaultBranch:o,allBranches:i,baseBranch:l,branchDiff:c,currentCommit:p,projectSlug:u,queueState:m}=tt();jt({source:"git-page"});const[h,f]=Ln(),[g,y]=M(null),[x,w]=M("desc"),[b,v]=M("branch"),N=h.get("expanded")==="true",C=()=>{w(de=>de==="desc"?"asc":"desc")},E=Ue(),k=E.data;re(()=>{s&&l&&s!==l&&E.state==="idle"&&!k&&E.load(`/api/branch-entity-diff?base=${encodeURIComponent(l)}&compare=${encodeURIComponent(s)}`)},[s,l,E,k]);const _=ae(()=>{const de=Ud(r,t);return Array.from(de.entries()).sort((We,Je)=>We[0].localeCompare(Je[0]))},[r,t]),S=ae(()=>{const de=MS(c,t,k);return Array.from(de.entries()).sort((We,Je)=>We[0].localeCompare(Je[0]))},[c,t,k]),j=ae(()=>$S(r,t),[r,t]),$=ae(()=>b==="uncommitted"?_:S,[b,_,S]),T=ae(()=>$.map(([de])=>de),[$]),{expandedUncommitted:R,setExpandedUncommitted:I,toggleFile:P,expandAllUncommitted:H,collapseAllUncommitted:W}=kC(N,T,[]),{diffView:F,diffContent:J,isLoading:Y,handleShowFileDiff:z,handleCloseDiff:A}=EC(l,s),B=(_e=p==null?void 0:p.metadata)==null?void 0:_e.currentRun,G=new Set((B==null?void 0:B.currentEntityShas)||[]),q=new Set(m.jobs.flatMap(de=>de.entityShas||[])),Q=new Set(((Le=m.currentlyExecuting)==null?void 0:Le.entityShas)||[]),{isAnalyzing:U,handleGenerateSimulation:D,handleGenerateAllSimulations:O,isEntityBeingAnalyzed:V,isEntityPending:ne}=Gd(B==null?void 0:B.currentEntityShas,m),ie=de=>ne(de)||q.has(de.sha)||Q.has(de.sha),we=de=>{de===(a||s)?h.delete("viewBranch"):h.set("viewBranch",de),f(h)},le=de=>{de===o?h.delete("compare"):h.set("compare",de),f(h)},ce=()=>{const We=$.flatMap(([Je,Ie])=>Ie.editedEntities||Ie.entities||[]).filter(Je=>!G.has(Je.sha)&&!q.has(Je.sha)&&!Q.has(Je.sha)&&!ne(Je));O(We)},ve=_.length,Ee=S.length,he=$.flatMap(([de,We])=>We.editedEntities||We.entities||[]),Z=he.filter(de=>de.entityType==="visual"||de.entityType==="library"),Se=Z.length>0&&Z.every(de=>G.has(de.sha)),fe=Z.length>0&&!Se&&Z.every(de=>q.has(de.sha)||Q.has(de.sha)),se=U||Se||fe,pe=Se?"Analyzing...":fe?"Queued...":U?"Analyzing...":"Analyze All";return n("div",{className:"bg-[#F8F7F6] min-h-screen",children:d("div",{className:"px-20 py-12",children:[d("div",{className:"mb-8",children:[n("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),d("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(TC,{activeTab:b,onTabChange:v,uncommittedCount:ve,branchCount:Ee})}),s&&b==="branch"&&n("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:s===o?d("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",n("span",{className:"text-cyblack-75",children:o}),"."]}):d("div",{className:"flex gap-6 items-center",children:[d("div",{className:"shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?d("div",{className:"relative w-50",children:[n("select",{value:s,onChange:de=>we(de.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(de=>n("option",{value:de,children:de},de))}),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})]}),d("div",{className:"flex-shrink-0",children:[n("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),d("div",{className:"relative w-[200px]",children:[n("select",{value:l,onChange:de=>le(de.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(de=>de!==s).map(de=>n("option",{value:de,children:de},de))}),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:d("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:d("div",{className:"flex items-center justify-between",children:[d("div",{className:"flex items-center",children:[d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[n("span",{style:{color:"#000000"},children:$.length})," ","modified ",$.length===1?"file":"files"]}),d("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:d("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:"|"}),d("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[n("span",{style:{color:"#000000"},children:he.length})," ",he.length===1?"entity":"entities"]})]}),$.length>0&&d("div",{className:"flex gap-6",children:[d("button",{onClick:H,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(Hl,{className:"w-3.5 h-3.5"}),"Expand All"]}),d("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(Vl,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),d("div",{className:"overflow-hidden",children:[b==="branch"&&s&&n(PC,{files:S,currentBranch:s,defaultBranch:o,baseBranch:l,allBranches:i,expandedFiles:R,isEntityBeingAnalyzed:V,isEntityQueued:ie,sortOrder:x,onToggleFile:de=>P(de,R,I),onBranchChange:le,onGenerateSimulation:D,onSortChange:C,onAnalyzeAll:ce,analyzeAllDisabled:se,analyzeAllText:pe}),b==="uncommitted"&&n(jC,{files:_,entityImpactMap:j,expandedFiles:R,isEntityBeingAnalyzed:V,isEntityQueued:ie,projectSlug:u,baseBranch:l,currentBranch:s,sortOrder:x,onToggleFile:de=>P(de,R,I),onShowFileDiff:z,onGenerateSimulation:D,onSortChange:C,onAnalyzeAll:ce,analyzeAllDisabled:se,analyzeAllText:pe})]}),F&&n(AC,{diffView:F,diffContent:J,isLoading:Y,entities:t,onClose:A}),g&&u&&n(qt,{projectSlug:u,onClose:()=>y(null)})]})})}),DC=Object.freeze(Object.defineProperty({__proto__:null,action:$C,default:RC,loader:IC,meta:MC},Symbol.toStringTag,{value:"Module"})),vs=[{name:"Desktop",width:1440,height:900},{name:"Laptop",width:1024,height:768},{name:"Tablet",width:768,height:1024},{name:"Mobile",width:375,height:667}];function OC(e){if(!e)return vs;const t=Object.entries(e).map(([s,a])=>({name:s,width:a.width,height:a.height})),r=new Set(t.map(s=>s.name));return[...t,...vs.filter(s=>!r.has(s.name))]}function FC({featureName:e,editorStep:t,editorStepLabel:r,onContinue:s}){const a=oe(o=>{o.key==="Enter"&&(o.preventDefault(),s())},[s]);return re(()=>(window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)),[a]),n("div",{className:"flex items-center justify-center h-full bg-[#1e1e1e] text-[#d4d4d4]",children:d("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:"Resume Previous Session?"}),n("p",{className:"text-sm text-[#999] mb-4",children:"An editor session is still in progress:"}),d("div",{className:"bg-[#1e1e1e] rounded p-3 mb-5 text-sm",children:[e&&d("div",{className:"mb-1",children:[n("span",{className:"text-[#999]",children:"Feature:"})," ",n("span",{className:"text-white",children:e})]}),t!=null&&r&&d("div",{children:[n("span",{className:"text-[#999]",children:"Step:"})," ",d("span",{className:"text-white",children:[t," (",r,")"]})]})]}),n("button",{onClick:s,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:"Continue Session"})]})})}const LC={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"},zC={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."},BC={1:"Survey",2:"App Scenarios",3:"Component Scenarios",4:"Preview",5:"Discuss",6:"Decompose",7:"Extract",8:"Recapture",9:"Journal",10:"Present"},YC={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."},UC=18,WC=10;function JC({projectTitle:e,featureName:t,editorStep:r,editorStepLabel:s,migrationMode:a}){const[o,i]=M(!1),[l,c]=M(null),p=ge(null);re(()=>{if(!o)return;const w=b=>{p.current&&!p.current.contains(b.target)&&i(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[o]);const u=t&&r!=null,m=a==="active",h=m?BC:LC,f=m?YC:zC,g=m?WC:UC,y=u?s||h[r]||"?":null;return d("div",{className:"h-8 shrink-0 flex items-center justify-between px-3 bg-[#2a2a2a] border-b border-[#333] text-xs select-none",children:[d("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"})]}),u&&d("div",{className:"relative",ref:p,children:[d("button",{onClick:()=>i(w=>!w),className:"flex items-center gap-1.5 text-[#ccc] hover:text-white transition-colors cursor-pointer",children:[n("span",{className:"text-[#555]",children:"::"}),d("span",{children:["Step ",r,d("span",{className:"text-[#888]",children:[" / ",g]}),":"," ",y]}),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:g},(w,b)=>b+1).map(w=>{const b=w===r,v=w<r,N=l===w,C=f[w];return d("div",{onClick:()=>c(N?null:w),className:"cursor-pointer",children:[d("div",{className:`w-full px-3 py-1 flex items-center gap-2 text-left transition-colors hover:bg-[#383838] ${b?"text-green-400 font-medium":v?"text-[#ccc]":"text-[#999]"}`,children:[d("span",{className:"w-5 text-right tabular-nums shrink-0",children:[w,"."]}),n("span",{className:"flex-1",children:h[w]||`Step ${w}`}),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 ${N?"rotate-180":""}`,children:n("path",{d:"M2 4l3 3 3-3"})})]}),N&&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})})]},w)})})]})]})}function oi(e){const[t,r]=M(null),[s,a]=M(!1),o=oe(()=>{e&&(a(!0),fetch(`/api/editor-test-results?testFile=${encodeURIComponent(e)}`).then(i=>i.json()).then(i=>{r(i),a(!1)}).catch(()=>{r({testFilePath:e,status:"error",testCases:[],errorMessage:"Failed to fetch test results"}),a(!1)}))},[e]);return{results:t,isRunning:s,runTests:o}}function Zs({scenarioId:e,updatedAt:t,alt:r,className:s="",imgClassName:a=""}){const[o,i]=M(!1),l=`/api/editor-scenario-image/${e}.png${t?`?v=${encodeURIComponent(t)}`:""}`;return re(()=>{i(!1)},[e]),o?n("div",{className:`flex items-center justify-center ${s}`,children:n("span",{className:"text-[8px] text-gray-500",children:"No img"})}):n("div",{className:s,children:n("img",{src:l,alt:r,className:a,loading:"lazy",onError:()=>i(!0)})})}function ir({scenarioId:e,updatedAt:t,hasScreenshot:r,imgSrc:s,name:a,isActive:o,onSelect:i}){return d("button",{onClick:i,className:"flex flex-col items-center gap-1 cursor-pointer group",title:a,children:[n("div",{className:`w-32 h-32 rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] ${o?"border-[#005c75] ring-1 ring-[#005c75]":"border-transparent hover:border-[#4d4d4d]"}`,children:e&&r?n(Zs,{scenarioId:e,updatedAt:t,alt:a,className:"w-full h-full",imgClassName:"w-full h-full object-contain"}):!e&&s?n("img",{src:s,alt:a,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"})})}),n("span",{className:`text-[10px] leading-tight text-center truncate w-32 ${o?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:a})]})}function $a({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=oi(e);if(s&&!r)return d("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(!r)return null;if(r.status==="error")return n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-red-400",children:r.errorMessage})});const o=t?r.testCases.filter(c=>c.fullName.startsWith(t)):r.testCases,i=o.length>0?o:r.testCases;if(i.length===0)return null;const l=t?`${t} > `:"";return d("div",{className:"px-2 pt-1 space-y-0.5",children:[i.map(c=>{var u;const p=l&&c.fullName.startsWith(l)?c.fullName.slice(l.length):c.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[c.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):c.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] ${c.status==="passed"?"text-green-400":c.status==="failed"?"text-red-400":"text-gray-500"}`,children:p})]}),c.status==="failed"&&((u=c.failureMessages)==null?void 0:u.map((m,h)=>n("div",{className:"pl-4 text-[9px] text-red-300/70 truncate max-w-full",title:m,children:m.split(`
|
|
498
|
-
`)[0]},h)))]},c.fullName)}),n("button",{onClick:a,disabled:s,className:"mt-1 text-[10px] text-[#00a0c4] hover:text-[#00c4ee] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}function dn({filePath:e}){return e?d("div",{className:"flex items-center gap-1 px-2 mt-0.5",children:[d("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(mt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function HC({scenarios:e,projectRoot:t,activeScenarioId:r,onScenarioSelect:s,zoomComponent:a,focusedEntity:o,onZoomChange:i,analyzedEntities:l=[],glossaryFunctions:c=[],activeAnalyzedScenarioId:p,onAnalyzedScenarioSelect:u,entityImports:m,pageFilePaths:h={}}){const{pageGroups:f,componentGroups:g}=ae(()=>{var j;const k=new Map,_=new Map;for(const $ of e)if($.componentName){const T=_.get($.componentName)||[];T.push($),_.set($.componentName,T)}else if(zs($.url)){const T=(j=$.url)==null?void 0:j.match(/[?&]c=([^&]+)/),R=T?decodeURIComponent(T[1]):"Isolated",I=_.get(R)||[];I.push($),_.set(R,I)}else{const T=$.pageFilePath?Tt(Ct($.pageFilePath)):ut($.url),R=k.get(T)||[];R.push($),k.set(T,R)}const S=new Map([..._.entries()].sort(([$],[T])=>$.localeCompare(T)));return{pageGroups:k,componentGroups:S}},[e]),y=ae(()=>{const k=new Set((l||[]).filter(S=>S.entityType==="visual").map(S=>S.name)),_=new Map;for(const[S,j]of g)k.has(S)||_.set(S,j);return _},[g,l]),{visualEntities:x,libraryEntities:w}=ae(()=>{const k=l.filter(S=>S.entityType==="visual").sort((S,j)=>S.name.localeCompare(j.name)),_=l.filter(S=>S.entityType==="library"||S.entityType==="functionCall").sort((S,j)=>S.name.localeCompare(j.name));return{visualEntities:k,libraryEntities:_}},[l]),b=ae(()=>{const k=new Set(w.map(_=>_.name));return c.filter(_=>!k.has(_.name)).sort((_,S)=>_.name.localeCompare(S.name))},[c,w]),v=l.some(k=>k.isAnalyzing),N=ge(null),C=ge(0),E=oe(()=>{N.current&&(C.current=N.current.scrollTop)},[]);if(re(()=>{N.current&&C.current>0&&(N.current.scrollTop=C.current)}),e.length===0&&l.length===0&&b.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:d("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 k=o.name,_=o.filePath,S=o.sha,j=e.filter(P=>P.componentName===k||P.componentPath===_||!P.componentName&&(P.pageFilePath===_||S&&P.entitySha===S)),$=new Set((m==null?void 0:m[k])||[]),T=$.size>0,R=T?x.filter(P=>$.has(P.name)):[],I=T?w.filter(P=>$.has(P.name)):[];return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-1",children:[d("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:j.length===0?n("div",{className:"px-3 py-2 text-xs text-gray-500",children:"No scenarios for this component"}):j.map(P=>n(ir,{scenarioId:P.id,updatedAt:P.updatedAt,hasScreenshot:!!P.screenshotPath,name:P.name,isActive:P.id===r,onSelect:()=>s(P)},P.id))}),R.length>0&&d("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"})}),R.map(P=>d("div",{className:"mt-2",children:[n("div",{className:"flex items-center gap-2 px-2 py-1",children:n("button",{onClick:()=>i(P.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:P.name})}),n(dn,{filePath:P.filePath,projectRoot:t}),(P.scenarios.length>0||P.pendingScenarios.length>0)&&n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:P.scenarios.map(H=>n(ir,{imgSrc:H.screenshotPath?`/api/screenshot/${H.screenshotPath}`:null,name:H.name,isActive:H.id===p,onSelect:()=>u==null?void 0:u({analysisId:P.analysisId,scenarioId:H.id,scenarioName:H.name,entitySha:P.sha,entityName:P.name})},H.id))})]},P.sha))]}),I.length>0&&d("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"})}),I.map(P=>d("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:P.name})}),n(dn,{filePath:P.filePath,projectRoot:t}),P.testFile&&n($a,{testFile:P.testFile,entityName:P.name})]},P.sha))]})]})})}return n("div",{ref:N,onScroll:E,className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-3",children:[f.size>0&&d("div",{children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"})}),[...f.entries()].sort(([k],[_])=>k==="Home"?-1:_==="Home"?1:k.localeCompare(_)).map(([k,_])=>{var S,j;return d("div",{className:"px-2 pt-1",children:[n("div",{className:"py-0.5",children:n("span",{className:"text-[11px] font-medium text-gray-400",children:k})}),(((S=_[0])==null?void 0:S.pageFilePath)||h[k])&&n(dn,{filePath:((j=_[0])==null?void 0:j.pageFilePath)||h[k],projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 pt-1",children:_.map($=>n(ir,{scenarioId:$.id,updatedAt:$.updatedAt,hasScreenshot:!!$.screenshotPath,name:$.name,isActive:$.id===r&&!p,onSelect:()=>s($)},$.id))})]},k)})]}),y.size>0&&d("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"})}),[...y.entries()].map(([k,_])=>{var S;return d("div",{className:"mt-2",children:[n("div",{className:"flex items-center justify-between px-2 py-1",children:n("button",{onClick:()=>i(k),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:k})}),((S=_[0])==null?void 0:S.componentPath)&&n(dn,{filePath:_[0].componentPath,projectRoot:t}),n("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:_.map(j=>n(ir,{scenarioId:j.id,updatedAt:j.updatedAt,hasScreenshot:!!j.screenshotPath,name:j.name,isActive:j.id===r&&!p,onSelect:()=>s(j)},j.id))})]},k)})]}),x.length>0&&d("div",{className:"pt-2 mt-1 border-t border-[#3d3d3d]",children:[d("div",{className:"px-2 py-1",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),v&&e.length===0&&l.every(k=>k.scenarioCount===0)&&n("span",{className:"ml-2 text-[10px] text-gray-500",children:"— Entities are being analyzed..."})]}),x.map(k=>d("div",{className:"mt-2",children:[d("div",{className:"flex items-center gap-2 px-2 py-1",children:[n("button",{onClick:()=>i(k.name),className:"text-[11px] font-medium text-gray-400 truncate cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:k.name}),k.isAnalyzing&&k.scenarioCount===0&&d("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(dn,{filePath:k.filePath,projectRoot:t}),(k.scenarios.length>0||k.pendingScenarios.length>0)&&d("div",{className:"flex flex-wrap gap-2 px-2 pt-1",children:[k.scenarios.map(_=>n(ir,{imgSrc:_.screenshotPath?`/api/screenshot/${_.screenshotPath}`:null,name:_.name,isActive:_.id===p,onSelect:()=>u==null?void 0:u({analysisId:k.analysisId,scenarioId:_.id,scenarioName:_.name,entitySha:k.sha,entityName:k.name})},_.id)),k.pendingScenarios.map(_=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:_,children:_},_))]})]},k.sha))]}),(w.length>0||b.length>0)&&d("div",{className:`pt-2 mt-1 ${x.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"})}),w.map(k=>d("div",{className:"mt-2",children:[d("div",{className:"px-2 py-1",children:[n("span",{className:"text-[11px] font-medium text-gray-300",children:k.name}),k.isAnalyzing&&k.scenarioCount===0&&d("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(dn,{filePath:k.filePath,projectRoot:t}),k.testFile?n($a,{testFile:k.testFile,entityName:k.name}):n("div",{className:"px-2 pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},k.sha)),b.map(k=>d("div",{className:"mt-2",children:[n("div",{className:"px-2 py-1",children:n("span",{className:"text-[11px] font-medium text-gray-300",children:k.name})}),n(dn,{filePath:k.filePath,projectRoot:t}),n($a,{testFile:k.testFile,entityName:k.name})]},k.name))]})]})})}const kl=120;function Kd({text:e,theme:t}){const[r,s]=M(!1),a=e.length>kl,o=a&&!r?e.slice(0,kl)+"…":e,i=t==="light";return d("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"}),d("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…"})]})]})}function El({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 VC({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=oi(e);if(s&&!r)return d("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(!r)return null;if(r.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-400",children:r.errorMessage})});const o=t?r.testCases.filter(c=>c.fullName.startsWith(t)):r.testCases,i=o.length>0?o:r.testCases;if(i.length===0)return null;const l=t?`${t} > `:"";return d("div",{className:"pt-1 space-y-0.5",children:[i.map(c=>{var u;const p=l&&c.fullName.startsWith(l)?c.fullName.slice(l.length):c.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[c.status==="passed"?n("span",{className:"text-green-400 text-[10px]",children:"✓"}):c.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] ${c.status==="passed"?"text-green-400":c.status==="failed"?"text-red-400":"text-gray-500"}`,children:p})]}),c.status==="failed"&&((u=c.failureMessages)==null?void 0:u.map((m,h)=>n("div",{className:"pl-4 text-[9px] text-red-400/70 truncate max-w-full",title:m,children:m.split(`
|
|
499
|
-
`)[0]},h)))]},c.fullName)}),n("button",{onClick:a,disabled:s,className:"mt-1 text-[10px] text-[#00a0c4] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}const GC={added:"text-green-400",untracked:"text-green-400",modified:"text-blue-400",renamed:"text-purple-400"};function KC({files:e}){return d("div",{className:"border-t border-[#3d3d3d] pt-2 mt-1",children:[d("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=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${GC[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 qC={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 QC(e){try{return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function ZC(e){try{return new Date(e+"T00:00:00").toLocaleDateString([],{weekday:"long",month:"long",day:"numeric"})}catch{return e}}const XC=[{value:"1d",label:"1 Day"},{value:"3d",label:"3 Days"},{value:"7d",label:"1 Week"},{value:"30d",label:"1 Month"}];function e1({entries:e,onScreenshotClick:t}){const[r,s]=M(!1),[a,o]=M("7d"),i=ae(()=>qx(e,a),[e,a]);return d("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[d("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&&d("div",{className:"px-3 pb-3 space-y-3 border-t border-[#3d3d3d]",children:[n("div",{className:"flex gap-1 pt-2.5",children:XC.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))}),d("div",{className:"flex items-center gap-3 text-[11px] text-gray-400",children:[d("span",{children:[n("span",{className:"text-white font-medium",children:i.commitCount})," ",i.commitCount===1?"commit":"commits"]}),n("span",{className:"text-[#3d3d3d]",children:"|"}),d("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:"|"}),d("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."}):d("div",{className:"space-y-3",children:[i.appScenarios.length>0&&d("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(Al,{scenario:l,onScreenshotClick:t},l.name))]}),i.componentGroups.size>0&&d("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],[c])=>l.localeCompare(c)).map(([l,c])=>d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:l}),c.map(p=>n(Al,{scenario:p,onScreenshotClick:t},p.name))]},l))]})]})]})]})}function Al({scenario:e,onScreenshotClick:t}){const r=e.name.indexOf(" - "),s=r!==-1?e.name.slice(r+3):e.name;return d("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)=>d("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 t1({isActive:e,onScreenshotClick:t,glossaryFunctions:r=[]}){const[s,a]=M([]),[o,i]=M(!0),[l,c]=M(new Set),p=oe(h=>{c(f=>{const g=new Set(f);return g.has(h)?g.delete(h):g.add(h),g})},[]),u=oe(async()=>{try{const h=await fetch("/api/editor-journal");if(h.ok){const f=await h.json();a(f.entries||[])}}catch{}finally{i(!1)}},[]);if(re(()=>{u()},[u]),re(()=>{e&&u()},[e,u]),re(()=>{if(!e)return;const h=setInterval(()=>void u(),5e3);return()=>clearInterval(h)},[e,u]),o)return n("div",{className:"flex-1 flex items-center justify-center",children:n("span",{className:"text-gray-500 text-sm",children:"Loading journal..."})});if(s.length===0)return n("div",{className:"flex-1 flex items-center justify-center",children:d("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=Qx(s);return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-3 space-y-4",children:[n(e1,{entries:s,onScreenshotClick:t}),[...m.entries()].map(([h,f])=>d("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:ZC(h)})}),n("div",{className:"space-y-2",children:f.map((g,y)=>{const x=qC[g.type]||{label:g.type,color:"bg-gray-600"},w=`${g.time}-${y}`,b=l.has(w);return d("div",{className:"bg-[#2d2d2d] rounded-lg overflow-hidden",children:[d("div",{className:`p-3 space-y-2 ${b?"":"max-h-[300px] overflow-y-auto"}`,children:[n("div",{className:"flex items-start gap-2 cursor-pointer",onClick:()=>p(w),children:d("div",{className:"flex-1 min-w-0",children:[d("div",{className:"flex items-center gap-2",children:[n("span",{className:"text-sm font-medium text-white truncate",children:g.title}),n("span",{className:`${x.color} text-white text-[9px] font-bold px-1.5 py-0.5 rounded uppercase tracking-wider shrink-0`,children:x.label})]}),n("span",{className:"text-[10px] text-gray-500",children:QC(g.time)}),g.featureName&&n("span",{className:"text-[10px] text-gray-500 italic truncate",title:g.featureName,children:g.featureName})]})}),g.userPrompt&&n(Kd,{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 v=Zx(g.scenarioScreenshots),N=g.entityChangeStatus,C=v.filter(([j])=>j==="App").flatMap(([,j])=>j),E=v.filter(([j])=>j!=="App"),k=new Map;for(const j of C){const $=j,T=$.pageFilePath?Tt(Ct($.pageFilePath)):ut($.url??null),R=k.get(T)||[];R.push(j),k.set(T,R)}const _=[...k.entries()],S=j=>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/${j.path.replace("screenshots/","")}`,commitSha:g.commitSha,commitMessage:g.commitMessage,scenarioName:j.name}),children:n("img",{src:`/api/editor-journal-image/${j.path.replace("screenshots/","")}`,alt:j.name,title:j.name,className:"max-w-full max-h-full object-contain",loading:"lazy"})},j.path);return d("div",{className:"space-y-2",children:[_.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),_.map(([j,$])=>d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:j}),(N==null?void 0:N[j])&&n(El,{status:N[j]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:$.map(S)})]},j))]}),E.length>0&&d("div",{className:"space-y-1.5",children:[n("span",{className:"text-[10px] font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),E.map(([j,$])=>d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] font-medium text-gray-400",children:j}),(N==null?void 0:N[j])&&n(El,{status:N[j]})]}),n("div",{className:"flex flex-wrap gap-1 mt-0.5",children:$.map(S)})]},j))]})]})})(),r.length>0&&d("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(v=>d("div",{children:[n("span",{className:"text-[11px] font-medium text-gray-200",children:v.name}),n("span",{className:"text-[9px] text-gray-500 truncate block",children:v.filePath}),v.testFile?n(VC,{testFile:v.testFile,entityName:v.name}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-500",children:"No test file"})})]},v.name))})]}),g.commitSha&&d("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})]}),b&&g.modifiedFiles&&g.modifiedFiles.length>0&&n(KC,{files:g.modifiedFiles})]}),d("button",{onClick:()=>p(w),className:"w-full py-1.5 text-[10px] text-gray-500 hover:text-gray-300 border-t border-[#3d3d3d] transition-colors cursor-pointer",children:["——— ",b?"Collapse":"Expand"," ———"]})]},w)})})]},h))]})})}function n1({prompt:e,height:t=300,onClose:r}){const s=ge(null),a=ge(null),o=ge(null),i=ge(!1),l=ge(e);return re(()=>{const c=s.current;if(!c)return;let p=!1,u=null;async function m(){const[h,f]=await Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit")]);if(p)return;{let k=document.getElementById("xterm-css");k||(k=document.createElement("style"),k.id="xterm-css",document.head.appendChild(k)),k.textContent=`
|
|
500
|
-
.xterm { cursor: text; position: relative; user-select: none; -ms-user-select: none; -webkit-user-select: none; }
|
|
501
|
-
.xterm.focus, .xterm:focus { outline: none; }
|
|
502
|
-
.xterm .xterm-helpers { position: absolute; top: 0; z-index: 5; }
|
|
503
|
-
.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; }
|
|
504
|
-
.xterm .composition-view { background: #000; color: #FFF; display: none; position: absolute; white-space: nowrap; z-index: 1; }
|
|
505
|
-
.xterm .composition-view.active { display: block; }
|
|
506
|
-
.xterm .xterm-viewport { background-color: #000; overflow-y: scroll; cursor: default; position: absolute; right: 0; left: 0; top: 0; bottom: 0; }
|
|
507
|
-
.xterm .xterm-screen { position: relative; }
|
|
508
|
-
.xterm .xterm-screen canvas { position: absolute; left: 0; top: 0; }
|
|
509
|
-
.xterm .xterm-scroll-area { visibility: hidden; }
|
|
510
|
-
.xterm-char-measure-element { display: inline-block; visibility: hidden; position: absolute; top: 0; left: -9999em; line-height: normal; }
|
|
511
|
-
.xterm.enable-mouse-events { cursor: default; }
|
|
512
|
-
.xterm.xterm-cursor-pointer, .xterm .xterm-cursor-pointer { cursor: pointer; }
|
|
513
|
-
.xterm.column-select.focus { cursor: crosshair; }
|
|
514
|
-
.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; }
|
|
515
|
-
.xterm .xterm-accessibility-tree:not(.debug) *::selection { color: transparent; }
|
|
516
|
-
.xterm .xterm-accessibility-tree { user-select: text; white-space: pre; }
|
|
517
|
-
.xterm .live-region { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; }
|
|
518
|
-
.xterm-dim { opacity: 1 !important; }
|
|
519
|
-
.xterm-underline-1 { text-decoration: underline; }
|
|
520
|
-
.xterm-underline-2 { text-decoration: double underline; }
|
|
521
|
-
.xterm-underline-3 { text-decoration: wavy underline; }
|
|
522
|
-
.xterm-underline-4 { text-decoration: dotted underline; }
|
|
523
|
-
.xterm-underline-5 { text-decoration: dashed underline; }
|
|
524
|
-
.xterm-overline { text-decoration: overline; }
|
|
525
|
-
.xterm-strikethrough { text-decoration: line-through; }
|
|
526
|
-
.xterm-screen .xterm-decoration-container .xterm-decoration { z-index: 6; position: absolute; }
|
|
527
|
-
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { z-index: 7; }
|
|
528
|
-
.xterm-decoration-overview-ruler { z-index: 8; position: absolute; top: 0; right: 0; pointer-events: none; }
|
|
529
|
-
.xterm-decoration-top { z-index: 2; position: relative; }
|
|
530
|
-
`}const g=new h.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}),y=new f.FitAddon;g.loadAddon(y),g.open(c),requestAnimationFrame(()=>{try{y.fit()}catch{}}),o.current=g;let x=null;try{const k=await fetch("/api/editor-scenario-prompt",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:l.current})});k.ok&&(x=(await k.json()).promptFile)}catch{}if(p)return;const w=window.location.protocol==="https:"?"wss:":"ws:",b=window.location.host,v=new URLSearchParams;v.set("entityName","inline-claude");const N=`${w}//${b}/ws/terminal?${v.toString()}`,C=new WebSocket(N);a.current=C,C.onopen=()=>{C.send(JSON.stringify({type:"resize",cols:g.cols,rows:g.rows}))};let E=!1;C.onmessage=k=>{try{const _=JSON.parse(k.data);if(_.type==="session-id"&&!E){E=!0,setTimeout(()=>{const S=x?`claude "Read the file at '${x.replace(/'/g,"'\\''")}' for your instructions."`:"claude";C.send(JSON.stringify({type:"input",data:S+"\r"}))},300);return}if(_.type==="output"&&_.data){g.write(_.data);return}}catch{g.write(k.data)}},C.onclose=()=>{i.current||g.write(`\r
|
|
531
|
-
\x1B[90m--- Session ended ---\x1B[0m\r
|
|
532
|
-
`)},C.onerror=()=>{g.write(`\r
|
|
533
|
-
\x1B[31mConnection error\x1B[0m\r
|
|
534
|
-
`)},g.onData(k=>{C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:"input",data:k}))}),u=new ResizeObserver(()=>{try{y.fit(),C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:"resize",cols:g.cols,rows:g.rows}))}catch{}}),u.observe(c)}return m(),()=>{var h,f;p=!0,i.current=!0,u==null||u.disconnect(),((h=a.current)==null?void 0:h.readyState)===WebSocket.OPEN&&a.current.close(),(f=o.current)==null||f.dispose()}},[]),d("div",{className:"border-t border-[#2d2d2d]",children:[d("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:s,style:{height:t,background:"#1a1a1a",padding:"4px 0",position:"relative",overflow:"hidden"}})]})}const Pl=()=>n("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",className:"text-gray-500 shrink-0",children:n("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})});function r1(e,t){if(e.length<=t)return e;const r=t-2;return[e[0],"ellipsis",...e.slice(e.length-r)]}function jl({items:e,onNavigate:t}){if(e.length===0)return null;const r=r1(e,4);return n("nav",{className:"flex items-center gap-1 text-xs min-w-0",children:r.map((s,a)=>{if(s==="ellipsis")return d("span",{className:"flex items-center gap-1",children:[n(Pl,{}),n("span",{className:"text-gray-500",children:"..."})]},"ellipsis");const o=a===r.length-1;return d("span",{className:"flex items-center gap-1 min-w-0",children:[a>0&&n(Pl,{}),o?n("span",{className:"text-white font-medium truncate",children:s.name}):n("button",{onClick:()=>t(s.componentName,s.entitySha),className:"text-gray-400 hover:text-white transition-colors cursor-pointer bg-transparent border-none p-0 truncate",children:s.name})]},s.componentName||"app")})})}function qd(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(zs(i.url)){const l=(a=i.url)==null?void 0:a.match(/[?&]c=([^&]+)/),c=l?decodeURIComponent(l[1]):"Isolated",p=r.get(c)||[];p.push(i),r.set(c,p)}else{const l=i.displayName||((o=i.pageFilePath)!=null&&o.startsWith("app/")?Tt(Ct(i.pageFilePath)):ut(i.url)),c=t.get(l)||[];c.push(i),t.set(l,c)}const s=new Map([...r.entries()].sort(([i],[l])=>i.localeCompare(l)));return{pageGroups:t,componentGroups:s}}function s1(e,t){var s,a;const r=new Map;for(const[o,i]of e){const l=(s=i.find(c=>c.entitySha))==null?void 0:s.entitySha;l&&r.set(o,l)}for(const[o,i]of t){const l=(a=i.find(c=>c.entitySha))==null?void 0:a.entitySha;l&&r.set(o,l)}return r}function a1(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 o1(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 i1(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 l1(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 Tl={new:0,edited:1,impacted:2};function Ml({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 $l({filePath:e}){const[t,r]=M(null),[s,a]=M(!0),[o,i]=M(null);return re(()=>{import("react-diff-viewer-continued").then(l=>{i(()=>l.default)})},[]),re(()=>{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 Il({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?d(xe,{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=>d("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?d(xe,{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=>d("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 Rl({scenarioId:e,name:t,isActive:r,onSelect:s,updatedAt:a}){const o=ge(null);return re(()=>{r&&o.current&&o.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[r]),d("button",{ref:o,onClick:s,className:"flex flex-col items-center gap-1.5 cursor-pointer group",title:t,children:[n("div",{className:`w-32 h-32 rounded-lg overflow-hidden border-2 transition-all ${r?"border-[#0ea5e9] ring-2 ring-[#0ea5e9]/40 shadow-lg shadow-[#0ea5e9]/20":"border-gray-200 hover:border-gray-400 shadow-sm"}`,children:n(Zs,{scenarioId:e,updatedAt:a,alt:t,className:"w-full h-full bg-white",imgClassName:"w-full h-full object-contain bg-white"})}),n("span",{className:`text-[11px] leading-tight text-center truncate w-32 font-medium ${r?"text-gray-900":"text-gray-600 group-hover:text-gray-900"}`,children:t})]})}function c1({filePath:e}){return e?d("div",{className:"flex items-center gap-1 mt-0.5",children:[d("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(mt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-400 hover:text-gray-600 transition-colors"})]}):null}function eo({testFile:e,entityName:t}){const{results:r,isRunning:s,runTests:a}=oi(e);if(s&&!r)return d("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(!r)return null;if(r.status==="error")return n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-red-500",children:r.errorMessage})});const o=t?r.testCases.filter(c=>c.fullName.startsWith(t)):r.testCases,i=o.length>0?o:r.testCases;if(i.length===0)return null;const l=t?`${t} > `:"";return d("div",{className:"pt-1 space-y-0.5",children:[i.map(c=>{var u;const p=l&&c.fullName.startsWith(l)?c.fullName.slice(l.length):c.fullName;return d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[c.status==="passed"?n("span",{className:"text-green-600 text-[10px]",children:"✓"}):c.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] ${c.status==="passed"?"text-green-600":c.status==="failed"?"text-red-500":"text-gray-400"}`,children:p})]}),c.status==="failed"&&((u=c.failureMessages)==null?void 0:u.map((m,h)=>n("div",{className:"pl-4 text-[9px] text-red-400 truncate max-w-full",title:m,children:m.split(`
|
|
535
|
-
`)[0]},h)))]},c.fullName)}),n("button",{onClick:a,disabled:s,className:"mt-1 text-[10px] text-[#0ea5e9] hover:text-[#38bdf8] transition-colors cursor-pointer disabled:opacity-50 bg-transparent border-none p-0",children:s?"Running...":"Re-run"})]})}function Dl(e){const t=e.indexOf(" - ");return t!==-1?e.slice(t+3):e}function Ol(e,t){return!t||Object.keys(t).length===0?e:[...e].sort(([r],[s])=>{var l,c;const a=((l=t[r])==null?void 0:l.status)||"impacted",o=((c=t[s])==null?void 0:c.status)||"impacted",i=(Tl[a]??2)-(Tl[o]??2);return i!==0?i:r.localeCompare(s)})}function d1({scenarios:e,allScenarios:t=[],glossaryFunctions:r=[],projectRoot:s,activeScenarioId:a,onScenarioSelect:o,onClose:i,entityChangeStatus:l={},modifiedFiles:c=[],featureName:p,userPrompt:u}){const m=ae(()=>{if(t.length===0||Object.keys(l).length===0)return e;const S=new Set(e.map($=>$.id)),j=t.filter($=>{var R,I;if(S.has($.id))return!1;const T=$.componentName||$.displayName||((R=$.pageFilePath)!=null&&R.startsWith("app/")?Tt(Ct($.pageFilePath)):ut($.url));return((I=l[T])==null?void 0:I.status)==="impacted"});return j.length===0?e:[...e,...j]},[e,t,l]),h=ae(()=>Object.entries(l).filter(([,S])=>S.status==="new"||S.status==="edited").map(([S,j])=>({name:S,status:j.status})),[l]),[f,g]=M(null),y=oe(S=>{g(j=>j===S?null:S)},[]),{pageGroups:x,componentGroups:w}=ae(()=>qd(m),[m]),b=ae(()=>Ol([...x.entries()],l),[x,l]),v=ae(()=>Ol([...w.entries()],l),[w,l]),N=b,C=v,E=ae(()=>lg(r,l),[r,l]),k=ae(()=>{const S=[];for(const[,j]of N)S.push(...j);for(const[,j]of C)S.push(...j);return S},[N,C]),_=ge(!1);return re(()=>{_.current||k.length!==0&&(_.current=!0,o(k[0]))},[k,o]),re(()=>{if(k.length===0)return;const S=j=>{if(j.key!=="ArrowLeft"&&j.key!=="ArrowRight")return;const $=j.target,T=$==null?void 0:$.tagName;if(T==="INPUT"||T==="SELECT"||T==="TEXTAREA"&&!$.classList.contains("xterm-helper-textarea"))return;j.preventDefault();const R=k.findIndex(P=>P.id===a);let I;j.key==="ArrowLeft"?I=R<=0?k.length-1:R-1:I=R>=k.length-1?0:R+1,o(k[I])};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[k,a,o]),m.length===0&&r.length===0?d("div",{className:"h-full bg-white flex items-center justify-center relative",children:[n("button",{onClick:i,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"})]}):d("div",{className:"h-full bg-white flex flex-col overflow-hidden",children:[d("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-gray-200 shrink-0",children:[d("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:i,className:"text-gray-400 hover:text-gray-700 text-lg leading-none cursor-pointer bg-transparent border-none shrink-0",title:"Close results",children:"×"})]}),u&&n(Kd,{text:u,theme:"light"}),n("div",{className:"flex-1 overflow-auto p-4",children:d("div",{className:"space-y-5",children:[N.length>0&&d("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:N.map(([S,j])=>{var I;const $=l[S],T=f===S,R=(I=j[0])==null?void 0:I.componentPath;return d("div",{children:[d("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:S}),$&&n(Ml,{status:$,onClick:()=>y(S)})]}),T&&($==null?void 0:$.status)==="edited"&&R&&n($l,{filePath:R}),T&&($==null?void 0:$.status)==="impacted"&&n(Il,{impactedBy:$.impactedBy,changedEntities:h}),n("div",{className:"flex flex-wrap gap-3",children:j.map(P=>n(Rl,{scenarioId:P.id,name:Dl(P.name),isActive:P.id===a,onSelect:()=>o(P),updatedAt:P.updatedAt},P.id))})]},S)})})]}),C.length>0&&d("div",{className:N.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:C.map(([S,j])=>{var I;const $=l[S],T=f===S,R=(I=j[0])==null?void 0:I.componentPath;return d("div",{children:[d("div",{className:"mb-1.5 flex items-center gap-2",children:[n("span",{className:"text-[11px] font-medium text-gray-600",children:S}),$&&n(Ml,{status:$,onClick:()=>y(S)})]}),T&&($==null?void 0:$.status)==="edited"&&R&&n($l,{filePath:R}),T&&($==null?void 0:$.status)==="impacted"&&n(Il,{impactedBy:$.impactedBy,changedEntities:h}),n("div",{className:"flex flex-wrap gap-3",children:j.map(P=>n(Rl,{scenarioId:P.id,name:Dl(P.name),isActive:P.id===a,onSelect:()=>o(P),updatedAt:P.updatedAt},P.id))})]},S)})})]}),E.length>0&&d("div",{className:N.length>0||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:"Functions"})}),n("div",{className:"space-y-2 pl-1",children:E.map(S=>d("div",{children:[n("div",{className:"flex items-center gap-2",children:n("span",{className:"text-[11px] font-medium text-gray-700",children:S.name})}),n(c1,{filePath:S.filePath,projectRoot:s}),S.testFile?n(eo,{testFile:S.testFile,entityName:S.name}):n("div",{className:"pt-1",children:n("span",{className:"text-[10px] text-gray-400",children:"No test file"})})]},S.name))})]}),c.length>0&&d("div",{className:N.length>0||C.length>0||E.length>0?"pt-3 border-t border-gray-200":"",children:[n("div",{className:"mb-2",children:d("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:["Modified Files (",c.length,")"]})}),n("div",{className:"space-y-0.5 pl-1 max-h-[200px] overflow-auto",children:c.map(S=>d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:`text-[9px] font-bold uppercase w-[14px] text-center ${S.status==="added"||S.status==="untracked"?"text-green-600":S.status==="modified"?"text-blue-600":S.status==="renamed"?"text-purple-600":"text-gray-400"}`,children:S.status==="added"||S.status==="untracked"?"A":S.status==="modified"?"M":S.status==="renamed"?"R":"?"}),n("span",{className:"text-[10px] text-gray-500 truncate font-mono",children:S.path})]},S.path))})]})]})})]})}function u1(e,t,r,s){var c;const a=s.length>0?s.map(p=>`- "${p.name}" (ID: ${p.id})${p.url?` — URL: ${p.url}`:""}`).join(`
|
|
536
|
-
`):"(no scenarios yet)",o=t.endsWith("/page.tsx")||t.endsWith("/page.js"),i=((c=s.find(p=>p.url))==null?void 0:c.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(`
|
|
537
|
-
`)}function Qd(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(`
|
|
538
|
-
`)}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(`
|
|
539
|
-
`)}function Fl({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(`
|
|
540
|
-
`):[`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:","",Qd(e,t),"","Step 3: Reload the editor page in the browser and verify the scenarios appear."].join(`
|
|
541
|
-
`);return n(mt,{content:a,label:"Copy Fix Prompt",copiedLabel:"Copied!",className:"text-[9px] text-amber-400 hover:text-amber-300 bg-transparent border border-amber-400/30 rounded px-1.5 py-0.5 cursor-pointer transition-colors ml-2"})}function p1({brokenEntities:e}){if(e.length===0)return null;const t=e.reduce((o,i)=>o+i.scenarios.length,0),r=e.filter(o=>o.reason==="incomplete"),s=e.filter(o=>o.reason==="missing"),a=[`${e.length} entities are missing data in the CodeYam database. ${t} 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:","",...r.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:","",...r.map(o=>{var l,c;const i=((l=o.scenarios[0])==null?void 0:l.componentPath)||((c=o.scenarios[0])==null?void 0:c.pageFilePath)||"FILL_IN_PATH";return`- "${o.name}" (filePath: "${i}")`}),"",'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","",...s.length>0?["## Step 3: Fix missing entity associations","",...s.map(o=>Qd(o.name,o.scenarios)),""]:[],`## Step ${s.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(`
|
|
542
|
-
`);return d("div",{className:"mb-3 p-2 rounded border border-amber-400/30 bg-amber-400/5",children:[d("p",{className:"text-[10px] text-amber-400/80 m-0 leading-relaxed",children:[e.length," ",e.length===1?"entity is":"entities are"," missing data (",t," hidden scenario",t!==1?"s":"","). Copy this prompt into Claude to fix them all at once."]}),n("div",{className:"mt-1.5",children:n(mt,{content:a,label:"Copy Fix All Prompt",copiedLabel:"Copied!",className:"text-[9px] text-amber-400 hover:text-amber-300 bg-transparent border border-amber-400/30 rounded px-1.5 py-0.5 cursor-pointer transition-colors"})})]})}function m1({scenarios:e,entityName:t,entityFilePath:r,entityType:s,onSwitchToBuild:a,onScenarioSelect:o}){const[i,l]=M(!1),[c,p]=M(null),[u,m]=M(""),[h,f]=M(!1),[g,y]=M(null),[x,w]=M(!1),b=oe(async N=>{if(!(!u.trim()||h)){f(!0);try{(await fetch("/api/editor-rename-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:N,name:u.trim()})})).ok&&p(null)}catch{}finally{f(!1)}}},[u,h]),v=oe(async N=>{if(confirm(`Delete scenario "${N.name}"?`)){y(N.id);try{const C=N.screenshotPaths?Object.values(N.screenshotPaths):N.screenshotPath?[N.screenshotPath]:[];await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:N.id,screenshotPaths:C})})}catch{}finally{y(null)}}},[]);return i?d("div",{className:"border border-[#3d3d3d] rounded-lg overflow-hidden",children:[d("div",{className:"flex items-center justify-between px-3 py-2 bg-[#1e1e1e]",children:[n("span",{className:"text-xs font-medium text-gray-400",children:"Edit Scenarios"}),n("button",{onClick:()=>{l(!1),p(null)},className:"text-gray-500 hover:text-gray-300 text-xs bg-transparent border-none cursor-pointer",children:"Close"})]}),n("div",{className:"divide-y divide-[#2d2d2d]",children:e.map(N=>d("div",{className:"px-3 py-2 flex items-center gap-2 hover:bg-[#252525] cursor-pointer transition-colors",style:{opacity:g===N.id?.4:1},onClick:()=>{c!==N.id&&o(N)},children:[N.screenshotPath?n(Zs,{scenarioId:N.id,updatedAt:N.updatedAt,alt:"",className:"rounded w-[40px] h-[40px] shrink-0 overflow-hidden",imgClassName:"w-full h-full object-cover"}):n("div",{className:"rounded bg-[#1e1e1e]",style:{width:40,height:40,flexShrink:0}}),c===N.id?d("form",{className:"flex-1 flex items-center gap-1.5 min-w-0",onSubmit:C=>{C.preventDefault(),b(N.id)},children:[n("input",{type:"text",value:u,onChange:C=>m(C.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:h}),n("button",{type:"submit",disabled:h||!u.trim(),className:"px-2 py-1 text-[10px] bg-[#005c75] text-white rounded hover:bg-[#004d63] disabled:opacity-40 cursor-pointer border-none",children:h?"...":"Save"}),n("button",{type:"button",onClick:()=>p(null),className:"px-2 py-1 text-[10px] text-gray-400 hover:text-white cursor-pointer bg-transparent border-none",children:"Cancel"})]}):d(xe,{children:[n("span",{className:"flex-1 text-xs text-gray-300 truncate min-w-0",children:N.name}),n("button",{onClick:C=>{C.stopPropagation(),p(N.id),m(N.name)},className:"text-[10px] text-gray-500 hover:text-gray-300 cursor-pointer bg-transparent border-none px-1",title:"Rename",children:"Rename"}),n("button",{onClick:C=>{C.stopPropagation(),v(N)},disabled:g===N.id,className:"text-[10px] text-red-400/60 hover:text-red-400 cursor-pointer bg-transparent border-none px-1",title:"Delete",children:"Delete"})]})]},N.id))}),x?n(n1,{prompt:u1(t,r,s,e),height:500,onClose:()=>w(!1)}):n("div",{className:"px-3 py-2.5 bg-[#1e1e1e] border-t border-[#2d2d2d] flex justify-center",children:n("button",{onClick:()=>w(!0),className:"px-5 py-2 text-xs font-medium text-white cursor-pointer bg-[#005c75] hover:bg-[#004d63] border-none rounded-md transition-colors",children:"Modify with Claude"})})]}):n("div",{className:"flex justify-center",children:n("button",{onClick:()=>l(!0),className:"px-5 py-2 text-xs font-medium text-gray-300 hover:text-white transition-colors cursor-pointer bg-[#2a2a2a] hover:bg-[#333] border border-[#4a4a4a] hover:border-[#666] rounded-md",children:"Edit Scenarios"})})}function Mn({scenarioId:e,updatedAt:t,hasScreenshot:r,imgSrc:s,name:a,isActive:o,onSelect:i}){return d("button",{onClick:i,className:"flex flex-col items-center gap-1 cursor-pointer group w-full",title:a,children:[n("div",{className:`w-full aspect-square rounded overflow-hidden border-2 transition-all bg-[#1a1a1a] ${o?"border-[#005c75] ring-1 ring-[#005c75]":"border-transparent hover:border-[#4d4d4d]"}`,children:e&&r?n(Zs,{scenarioId:e,updatedAt:t,alt:a,className:"w-full h-full",imgClassName:"w-full h-full object-contain"}):!e&&s?n("img",{src:s,alt:a,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"})})}),n("span",{className:`text-[10px] leading-tight text-center truncate w-full ${o?"text-white":"text-gray-500 group-hover:text-gray-300"}`,children:a})]})}function lr({filePath:e}){return e?d("div",{className:"flex items-center gap-1 mt-0.5",children:[d("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(mt,{content:e,icon:!0,iconSize:10,className:"shrink-0 text-gray-500 hover:text-gray-300 transition-colors"})]}):null}function h1({hasProject:e,scenarios:t,analyzedEntities:r,allEntities:s=[],glossaryFunctions:a=[],glossaryEntries:o=[],projectRoot:i,activeScenarioId:l,onScenarioSelect:c,onAnalyzedScenarioSelect:p,onSwitchToBuild:u,zoomComponent:m,focusedEntity:h,onZoomChange:f,entityImports:g,pageFilePaths:y={},projectTitle:x,projectDescription:w,migrationMode:b="none",migrationState:v,onStartMigration:N,breadcrumbItems:C=[]}){var z;const{pageGroups:E,componentGroups:k}=ae(()=>qd(t),[t]),_=ae(()=>s1(E,k),[E,k]),S=ae(()=>new Set(r.map(A=>A.sha)),[r]),j=ae(()=>a1(g||{}),[g]),$=oe(A=>o1(A,S,s,j),[S,s,j]),T=ae(()=>{const A=new Map;for(const B of s)A.set(B.sha,B.name);return A},[s]),R=ae(()=>i1(E,k,_,$),[E,k,_,$]),I=ae(()=>r.filter(A=>A.entityType==="visual").sort((A,B)=>A.name.localeCompare(B.name)),[r]),P=ae(()=>{const A=new Map;for(const B of a)A.set(B.name,B);return A},[a]),H=ge(null),W=ge(0),F=oe(()=>{H.current&&(W.current=H.current.scrollTop)},[]);re(()=>{H.current&&W.current>0&&(H.current.scrollTop=W.current)});const J=(h==null?void 0:h.sha)??"overview";if(!e)return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"flex flex-col items-center gap-4",children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:"Ready to build something?"}),n("button",{onClick:u,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(b==="candidate")return n("div",{className:"flex-1 flex items-center justify-center",children:d("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 font-['IBM_Plex_Sans'] m-0",children:"Migrate Your Project"}),n("p",{className:"text-sm text-gray-400 m-0 font-['IBM_Plex_Sans'] 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:N,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:u,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(b==="active"&&v){const A=v.pages||[],B=A.filter(Q=>Q.status==="complete").length,G=A.length,q=G>0?Math.round(B/G*100):0;return d("div",{className:"flex-1 flex flex-col overflow-auto p-4",children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0 mb-3",children:"Project Migration"}),d("div",{className:"mb-4",children:[n("div",{className:"flex items-center gap-2 mb-1",children:d("span",{className:"text-xs text-gray-400 font-['IBM_Plex_Sans']",children:[B,"/",G," pages (",q,"%)"]})}),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:`${q}%`}})})]}),n("div",{className:"space-y-1.5",children:A.map((Q,U)=>{const D=Q.status==="complete"?"✓":Q.status==="in-progress"?"→":"○",O=Q.status==="complete"?"text-green-400":Q.status==="in-progress"?"text-cyan-400":"text-gray-600";return d("div",{className:"flex items-center gap-2",children:[n("span",{className:`text-xs ${O} w-3 text-center`,children:D}),n("span",{className:`text-xs font-['IBM_Plex_Sans'] ${Q.status==="in-progress"?"text-white font-medium":Q.status==="complete"?"text-gray-400":"text-gray-600"}`,children:Q.name}),n("span",{className:"text-[10px] text-gray-600",children:Q.route}),Q.status==="complete"&&d("span",{className:"text-[10px] text-gray-600",children:[(Q.extractedComponents||[]).length,"c"," ",(Q.extractedFunctions||[]).length,"f"," ",Q.scenarioCount||0,"s"]})]},U)})}),(v.sharedComponents||[]).length>0&&d("div",{className:"mt-4",children:[n("h3",{className:"text-xs font-medium text-gray-400 font-['IBM_Plex_Sans'] mb-1.5",children:"Shared Components"}),(v.sharedComponents||[]).map((Q,U)=>d("div",{className:"text-[10px] text-gray-500 mb-0.5",children:[Q.name," ",d("span",{className:"text-gray-600",children:["— used in: ",(Q.usedInPages||[]).join(", ")]})]},U))]}),n("div",{className:"mt-4",children:n("button",{onClick:u,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"})})]})}if(!(t.length>0||I.length>0))return n("div",{className:"flex-1 flex items-center justify-center",children:d("div",{className:"flex flex-col items-center gap-4 px-8 text-center",children:[x?d(xe,{children:[n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:x}),w&&n("p",{className:"text-sm text-gray-400 m-0 font-['IBM_Plex_Sans'] leading-relaxed",children:w})]}):n("h2",{className:"text-lg font-medium text-white font-['IBM_Plex_Sans'] m-0",children:"Your project is ready"}),n("p",{className:"text-sm text-gray-400 m-0 font-['IBM_Plex_Sans'] leading-relaxed",children:"Describe what you want to build in the Chat and your pages and components will appear here."}),n("button",{onClick:u,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(h){const A=h.filePath,B=h.name,G=r.some(Z=>Z.sha===h.sha||Z.filePath===A),q=!!((z=g==null?void 0:g[B])!=null&&z.length);if(!G&&!q){t.some(fe=>fe.componentName===B&&fe.entitySha===h.sha);const Z=t.filter(fe=>fe.entitySha===h.sha),Se=[`The "${h.displayName}" entity (${A}) 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 "${B}" to the glossary if it's not already there:`,` Check: cat .codeyam/glossary.json | grep "${B}"`,"",` If not found, add an entry with name "${B}" and filePath "${A}" 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(`
|
|
543
|
-
`);return n("div",{ref:H,onScroll:F,className:"flex-1 overflow-auto",children:d("div",{className:"p-4 space-y-3",children:[n(jl,{items:C,onNavigate:f}),n("h2",{className:"text-sm font-semibold text-white m-0 font-['IBM_Plex_Sans'] uppercase tracking-wider",children:h.displayName}),A&&n(lr,{filePath:A,projectRoot:i}),d("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(mt,{content:Se,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:Z.map(fe=>n(Mn,{scenarioId:fe.id,updatedAt:fe.updatedAt,hasScreenshot:!!fe.screenshotPath,name:fe.name,isActive:fe.id===l,onSelect:()=>c(fe)},fe.id))})]})},J)}const Q=h.sha,U=t.filter(Z=>!Z.componentName&&(Z.pageFilePath===A||Q&&Z.entitySha===Q)),D=t.filter(Z=>Z.componentName===B||Z.componentPath===A),O=I.find(Z=>Z.filePath===A||Z.name===B),V=P.get(B)||a.find(Z=>Z.filePath===A),ne=[...U,...D],ie=new Set((g==null?void 0:g[B])||[]),we=q?[...k.entries()].filter(([Z])=>ie.has(Z)):[],le=q?I.filter(Z=>ie.has(Z.name)&&!we.some(([Se])=>Se===Z.name)):[],ce=q?o.filter(Z=>ie.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})):[],ve=we.length>0||le.length>0,Ee=ce.length>0,he=ve||Ee;return n("div",{className:"flex-1 overflow-auto",children:d("div",{className:"p-4 space-y-3",children:[n(jl,{items:C,onNavigate:f}),d("div",{children:[n("h2",{className:"text-sm font-semibold text-white m-0 font-['IBM_Plex_Sans'] uppercase tracking-wider",children:h.displayName}),h.filePath&&n(lr,{filePath:h.filePath,projectRoot:i})]}),ne.length>0&&n("div",{className:"grid grid-cols-3 gap-2",children:ne.map(Z=>n(Mn,{scenarioId:Z.id,updatedAt:Z.updatedAt,hasScreenshot:!!Z.screenshotPath,name:Z.name,isActive:Z.id===l,onSelect:()=>c(Z)},Z.id))}),O&&(O.scenarios.length>0||O.pendingScenarios.length>0)&&d("div",{className:"grid grid-cols-3 gap-2",children:[O.scenarios.map(Z=>n(Mn,{imgSrc:Z.screenshotPath?`/api/screenshot/${Z.screenshotPath}`:null,name:Z.name,isActive:!1,onSelect:()=>p({analysisId:O.analysisId,scenarioId:Z.id,scenarioName:Z.name,entitySha:O.sha,entityName:O.name})},Z.id)),O.pendingScenarios.map(Z=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:Z,children:Z},Z))]}),V&&V.testFile&&d("div",{children:[d("div",{className:"flex items-center gap-1.5",children:[n("span",{className:"text-[10px] text-gray-500",children:"Tests:"}),n(lr,{filePath:V.testFile,projectRoot:i})]}),n(eo,{testFile:V.testFile,entityName:B})]}),ne.length===0&&!O&&!V&&n("div",{className:"text-xs text-gray-500",children:"No scenarios for this entity"}),ne.length>0&&n(m1,{scenarios:ne,entityName:h.displayName,entityFilePath:h.filePath,entityType:h.entityType,onSwitchToBuild:u,onScenarioSelect:c}),he&&d("div",{className:"pt-3 mt-2 border-t border-[#3d3d3d] space-y-3",children:[ve&&d("div",{children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Components"}),we.map(([Z,Se])=>n("div",{className:"mt-3",children:_.has(Z)?d(xe,{children:[n("div",{className:"py-1",children:n("button",{onClick:()=>f(Z,_.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})}),Se.length>0&&n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:Se.map(fe=>n(Mn,{scenarioId:fe.id,updatedAt:fe.updatedAt,hasScreenshot:!!fe.screenshotPath,name:fe.name,isActive:fe.id===l,onSelect:()=>c(fe)},fe.id))})]}):d("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(Fl,{name:Z,scenarios:Se})})]})},Z)),le.map(Z=>d("div",{className:"mt-3",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>f(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)&&d("div",{className:"grid grid-cols-3 gap-2 pt-1",children:[Z.scenarios.map(Se=>n(Mn,{imgSrc:Se.screenshotPath?`/api/screenshot/${Se.screenshotPath}`:null,name:Se.name,isActive:!1,onSelect:()=>p({analysisId:Z.analysisId,scenarioId:Se.id,scenarioName:Se.name,entitySha:Z.sha,entityName:Z.name})},Se.id)),Z.pendingScenarios.map(Se=>n("div",{className:"px-2.5 py-1 bg-[#2a2a2a] text-gray-400 text-[10px] rounded-full",title:Se,children:Se},Se))]})]},Z.sha))]}),Ee&&d("div",{children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Functions"}),ce.map(Z=>d("div",{className:"mt-2",children:[n("div",{className:"py-1",children:n("button",{onClick:()=>f(Z.name,_.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(lr,{filePath:Z.filePath,projectRoot:i}),Z.testFile&&d("div",{className:"mt-0.5",children:[d("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(eo,{testFile:Z.testFile,entityName:Z.name})]})]},Z.name))]})]})]})})}return n("div",{ref:H,onScroll:F,className:"flex-1 overflow-auto",children:d("div",{className:"p-4 space-y-4",children:[x&&d("div",{children:[n("h2",{className:"text-base font-semibold text-white m-0 font-['IBM_Plex_Sans']",children:x}),w&&n("p",{className:"text-xs text-gray-400 m-0 mt-1 font-['IBM_Plex_Sans'] leading-relaxed",children:w})]}),R.length>1&&n(p1,{brokenEntities:R}),E.size>0&&d("div",{children:[d("div",{className:"flex items-center justify-between",children:[n("span",{className:"text-xs font-semibold text-gray-500 uppercase tracking-wider",children:"Application"}),n("button",{onClick:u,className:"px-2.5 py-1 text-[10px] font-medium text-gray-400 bg-[#2a2a2a] border border-[#4d4d4d] rounded hover:bg-[#333] hover:text-white hover:border-[#005c75] transition-colors cursor-pointer",children:"+ New Page"})]}),d("p",{className:"text-[11px] text-gray-500 m-0 mt-1.5 font-['IBM_Plex_Sans'] leading-relaxed",children:["Select a page scenario below and switch to"," ",n("button",{onClick:u,className:"text-[#00a0c4] hover:text-[#00c4eb] bg-transparent border-none p-0 cursor-pointer underline font-inherit text-inherit",children:"Build"})," ","to change or enhance an existing page or"," ",n("button",{onClick:u,className:"text-[#00a0c4] hover:text-[#00c4eb] bg-transparent border-none p-0 cursor-pointer underline font-inherit text-inherit",children:"create a new page"})]}),[...E.entries()].sort(([A],[B])=>A==="Home"?-1:B==="Home"?1:A.localeCompare(B)).map(([A,B])=>{var G,q;return n("div",{className:"mt-2",children:_.has(A)&&$(_.get(A))?d(xe,{children:[n("div",{className:"py-1",children:(()=>{const Q=_.get(A),D=(Q?T.get(Q):void 0)||A;return n("button",{onClick:()=>f(A,_.get(A)),className:"text-[11px] font-medium text-gray-400 cursor-pointer hover:text-white transition-colors bg-transparent border-none p-0",children:D})})()}),(((G=B[0])==null?void 0:G.pageFilePath)||y[A])&&n(lr,{filePath:((q=B[0])==null?void 0:q.pageFilePath)||y[A],projectRoot:i}),n("div",{className:"grid grid-cols-3 gap-2 pt-1",children:B.map(Q=>n(Mn,{scenarioId:Q.id,updatedAt:Q.updatedAt,hasScreenshot:!!Q.screenshotPath,name:Q.name,isActive:Q.id===l,onSelect:()=>c(Q)},Q.id))})]}):d("div",{className:"py-2",children:[n("span",{className:"text-[11px] font-medium text-gray-500",children:(()=>{const Q=_.get(A);return Q&&T.get(Q)||A})()}),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 page. Please copy and paste this prompt into Claude to ask Claude to fix the data."}),n("div",{className:"mt-1.5",children:n(Fl,{name:A,scenarios:B,reason:_.has(A)?"incomplete":"missing"})})]})},A)})]})]})},J)}const f1=[{key:"app",label:"App"},{key:"build",label:"Build"},{key:"data",label:"Structure"},{key:"journal",label:"Journal"}];function g1({activeTab:e,onTabChange:t,buildIdle:r}){return d("div",{className:"bg-[#3d3d3d] h-10 flex items-center px-3 gap-3 shrink-0 z-20 border-b border-[#2d2d2d]",children:[d("div",{className:"flex items-center gap-2 shrink-0",children:[n("img",{src:Es,alt:"CodeYam",className:"h-5 brightness-0 invert"}),n("span",{className:"text-white font-medium text-xs whitespace-nowrap",children:"Codeyam Editor"})]}),n("div",{className:"flex-1"}),n("div",{className:"flex items-center gap-2 shrink-0",children:n("div",{className:"flex items-center gap-0.5 bg-[#4a3232] rounded-lg p-0.5",children:f1.map(s=>d("button",{onClick:()=>t(s.key),className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors cursor-pointer ${e===s.key?"bg-[#7a4444] text-white":"text-gray-300 hover:text-white"}`,children:[s.label,s.key==="build"&&r&&e!=="build"&&n("span",{className:"ml-1 inline-block w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"})]},s.key))})})]})}function y1({onMouseDown:e,onDoubleClick:t,isDragging:r}){return d("div",{className:"shrink-0 relative flex items-center justify-center cursor-col-resize group",style:{width:12},onMouseDown:e,onDoubleClick:t,children:[n("div",{className:"absolute inset-y-0 left-1/2 -translate-x-1/2",style:{width:r?3:1,backgroundColor:r?"#3b82f6":"#3d3d3d",transition:"width 100ms, background-color 100ms"}}),!r&&n("div",{className:"absolute inset-0 bg-blue-500/0 group-hover:bg-blue-500/20 transition-colors pointer-events-none"}),d("div",{className:"relative z-10 flex flex-col gap-[3px] opacity-0 group-hover:opacity-100 transition-opacity",style:r?{opacity:1}:void 0,children:[n("div",{className:"w-2 h-px bg-gray-400"}),n("div",{className:"w-2 h-px bg-gray-400"}),n("div",{className:"w-2 h-px bg-gray-400"})]})]})}const Ll=300,ns=150;function x1(e){const[t,r]=M(null),[s,a]=M(!1),o=ge(0),i=ge(null);re(()=>{e.current&&r(Math.round(e.current.offsetWidth*.5))},[e]);const l=oe(()=>{var x;return((x=e.current)==null?void 0:x.offsetWidth)??(typeof window<"u"?window.innerWidth:1024)},[e]),c=oe(x=>{x.preventDefault(),a(!0)},[]),p=oe(()=>{r(Math.round(l()*.5))},[l]),u=oe(()=>{r(x=>(x&&x>0&&(i.current=x),0))},[]),m=oe(()=>{const x=i.current;i.current=null,r(x&&x>=Ll?x:Math.round(l()*.5))},[l]),h=oe(()=>{r(Math.round(l()*.5))},[l]);re(()=>{if(!s)return;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const x=b=>{cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{var S;const v=(S=e.current)==null?void 0:S.getBoundingClientRect(),N=(v==null?void 0:v.left)??0,E=((v==null?void 0:v.width)??window.innerWidth)-ns,k=b.clientX-N,_=Math.min(Math.max(k,Ll),E);r(_)})},w=b=>{var k;cancelAnimationFrame(o.current),a(!1);const v=(k=e.current)==null?void 0:k.getBoundingClientRect(),N=(v==null?void 0:v.left)??0,C=(v==null?void 0:v.width)??window.innerWidth,E=b.clientX-N;E<ns?r(0):C-E<ns&&r(C)};return document.addEventListener("mousemove",x),document.addEventListener("mouseup",w),()=>{cancelAnimationFrame(o.current),document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",w),document.body.style.cursor="",document.body.style.userSelect=""}},[s,e]),re(()=>{const x=()=>{r(w=>{if(w===null||w===0)return w;const b=l();return w>=b?b:Math.min(w,b-ns)})};if(!(typeof window>"u"))return window.addEventListener("resize",x),()=>window.removeEventListener("resize",x)},[l]);const f=l(),g=t===0,y=t!==null&&t>=f;return{editorWidth:t,isDragging:s,isEditorCollapsed:g,isPreviewCollapsed:y,handleMouseDown:c,handleDoubleClick:p,collapseEditor:u,expandEditor:m,expandPreview:h}}function b1({preview:e,onDismiss:t,onLoadCommit:r}){return d("div",{className:"flex flex-col items-center gap-6 max-w-[700px] w-full",children:[d("div",{className:"text-center",children:[n("h2",{className:"text-lg font-semibold text-[#333] m-0 font-['IBM_Plex_Sans']",children:"Journal Screenshot"}),n("p",{className:"text-sm text-[#888] mt-1 m-0 font-['IBM_Plex_Sans']",children:"This is a snapshot from a previous version — not a live preview"})]}),n("div",{className:"rounded-lg overflow-hidden border-2 border-[#ccc] shadow-md max-w-full w-fit",children:n("img",{src:e.screenshotUrl,alt:e.scenarioName,className:"max-w-full h-auto block"})}),d("div",{className:"flex items-center gap-2 text-sm text-[#666]",children:[e.commitSha&&n("span",{className:"font-mono text-xs text-[#00a0c4] bg-[#00a0c4]/15 px-2 py-0.5 rounded",children:e.commitSha.slice(0,7)}),d("span",{className:"truncate",children:[e.scenarioName,e.commitMessage&&` — ${e.commitMessage}`]})]}),n("div",{className:"flex items-center gap-3",children:e.commitSha&&r&&n(w1,{commitSha:e.commitSha,onLoadCommit:r})})]})}function w1({commitSha:e,onLoadCommit:t}){const[r,s]=M(!1),[a,o]=M(null);return d(xe,{children:[n("button",{onClick:()=>{s(!0),o(null),t(e).then(i=>{i.success||o(i.error||"Failed to load commit")}).catch(i=>{o(i instanceof Error?i.message:"Network error")}).finally(()=>s(!1))},disabled:r,className:"bg-[#005c75] hover:bg-[#004d63] disabled:opacity-50 text-white text-sm font-medium px-4 py-1.5 rounded transition-colors cursor-pointer",children:r?"Reverting...":"Revert to this code and load this version"}),a&&n("div",{className:"bg-red-50 border border-red-200 rounded px-4 py-2 text-sm text-red-600 w-full text-center",children:a})]})}function v1({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,onStateChange:o}){const{interactiveServerUrl:i,isStarting:l,isLoading:c}=vn({analysisId:e,scenarioId:t,scenarioName:r,entityName:s,projectSlug:a,enabled:!0});return re(()=>{o(i,l||c)},[i,l,c,o]),null}function N1({onSaveToCurrent:e,onSaveAsNew:t,onDismiss:r,isSaving:s,scenarioName:a}){return d("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?d(xe,{children:["Data modified in “",a,"”."]}):"Data modified."}),d("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:d("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 S1(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 C1(e){const[t,r]=M({url:null,proxyUrl:null,isStarting:!1,error:null,canStartServer:!0,autoStartAttempted:!1}),s=ge(t);s.current=t,re(()=>{let i=!1,l=null;const c=async()=>{try{const p=await fetch("/api/editor-dev-server");if(i)return;const u=await p.json(),m=S1(s.current,u),{shouldAutoStart:h,...f}=m;if(r(f),h&&!(e!=null&&e.skipAutoStart))try{const g=await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"start"})});if(i)return;g.ok?r(y=>({...y,isStarting:!0})):r(y=>({...y,canStartServer:!1}))}catch{}}catch{}};return c(),l=setInterval(()=>void c(),2e3),()=>{i=!0,l&&clearInterval(l)}},[t.url]);const a=oe(()=>{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=oe(()=>{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 _1(e){const t=ge(null),r=ge(null);re(()=>{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,c=(64-l)/2;i.drawImage(a,c,c,l,l);const p=12,u=64-p-1,m=p+1;i.beginPath(),i.arc(u,m,p,0,2*Math.PI),i.fillStyle="#ef4444",i.fill(),s.href=o.toDataURL("image/png")},a.src=t.current},[e]),re(()=>()=>{if(typeof document>"u")return;const s=document.querySelector('link[rel="icon"]');s&&t.current&&(s.href=t.current)},[])}function k1(e){if(!e||typeof e!="object")return[];for(const t of Object.values(e))if(Array.isArray(t))return t;return[]}function E1(e){return L.join(e,".codeyam","migration-state.json")}function Zd(e){const t=E1(e);try{const r=K.readFileSync(t,"utf8"),s=JSON.parse(r);return A1(s)}catch{return null}}function A1(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 P1(e,t){if(!K.existsSync(L.join(e,"package.json"))||t!=null&&t.hasEditorScenarios)return!1;const r=L.join(e,".codeyam","glossary.json");if(K.existsSync(r))try{const o=JSON.parse(K.readFileSync(r,"utf8"));if((Array.isArray(o)?o:k1(o)).length>0)return!1}catch{}const s=L.join(e,".codeyam","editor-step.json");if(K.existsSync(s))try{const o=JSON.parse(K.readFileSync(s,"utf8"));if(o.feature||o.scaffolded)return!1}catch{}const a=Zd(e);return(a==null?void 0:a.status)!=="complete"}function j1(e){const t=L.join(e,".codeyam","editor-step.json");try{const r=K.readFileSync(t,"utf8");return!!JSON.parse(r).migration}catch{return!1}}function T1({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 M1=()=>[{title:"Editor - CodeYam"},{name:"description",content:"CodeYam Code + Data Editor"}];function $1(e){const t=new URL(e).pathname.match(/\/editor\/entity\/([^/]+)/);return t?t[1]:null}async function I1({request:e}){var H;const t=await Fe();let r=!1,s=[],a=[];const o=Ne()||process.cwd();let i={map:{},allFiles:[]};try{i=Bo(o)}catch{}let l=[];try{l=Vn()}catch{}if(t){const{project:W}=await Re(t);r=((H=W.metadata)==null?void 0:H.editorMode)??!1;try{const F=Te();try{const A=await F.selectFrom("editor_scenarios").select(["id","url"]).where("project_id","=",W.id).where("component_name","is",null).where("page_file_path","is",null).execute();if(A.length>0){const{allFiles:B}=i;for(const G of A){const q=G;if(!q.url)continue;const Q=$c(q.url,B);Q&&await F.updateTable("editor_scenarios").set({page_file_path:Q}).where("id","=",q.id).execute()}}}catch(A){console.warn("[editor] page_file_path backfill failed (non-fatal):",A instanceof Error?A.message:A)}const J=await F.selectFrom("editor_scenarios").selectAll().where("project_id","=",W.id).orderBy("created_at","asc").execute(),Y=A=>{const B=A;let G=null,q=null;try{B.dimensions&&(G=JSON.parse(B.dimensions))}catch{}try{B.screenshot_paths&&(q=JSON.parse(B.screenshot_paths))}catch{}return{id:A.id,name:A.name,description:A.description||"",componentName:A.component_name||null,componentPath:A.component_path||null,screenshotPath:A.screenshot_path||null,url:B.url||null,type:B.type||null,viewportWidth:B.viewport_width||null,viewportHeight:B.viewport_height||null,dimensions:G,screenshotPaths:q,pageFilePath:B.page_file_path||null,entitySha:B.entity_sha||null,displayName:B.display_name||null,updatedAt:B.updated_at||null}};a=vt(J,A=>`${A.name}::${A.url||"/"}`).map(Y);const z=ud(o);if(z){const A=Ar(z),B=J.filter(G=>ko(G,A));s=vt(B,G=>`${G.name}::${G.url||"/"}`).map(Y)}else s=a}catch{}}const c=[...new Set(a.map(W=>W.componentName).filter(W=>W!==null))];let p=[];try{const W=L.join(o,".codeyam","glossary.json");if(K.existsSync(W)){const F=K.readFileSync(W,"utf8");p=JSON.parse(F)}}catch{}const u=mg(p);let m=[],h=[];try{const W=await wn()||[];m=W.map(F=>({sha:F.sha,name:F.name,entityType:F.entityType||"visual",filePath:F.filePath||""})),h=hg(W,p)}catch{}let f=[];try{if(m.length>0){const W=m.map(F=>F.sha);await ze(),f=await qe({shas:W})||[]}}catch{}let g={};try{if(f.length>0){const W=new Set([...h.map(F=>F.name),...m.map(F=>F.name),...c,...p.map(F=>F.name)]);g=fg(f,W)}}catch{}const y=i.map,x=i.allFiles;if(Object.keys(y).length>0&&f.length>0&&(g=gg(g,y,f)),x.length>0&&f.length>0){const W=new Map;for(const F of f)F.filePath&&W.set(F.filePath,F.name);for(const F of x){const J=Tt(Ct(F));if(g[J])continue;const Y=W.get(F);Y&&g[Y]&&(g[J]=g[Y])}}let w={};try{w=(await Gn({projectRoot:o,scenarioInputs:a,glossaryInputs:u,precomputedPageFilePaths:i,precomputedGitFiles:l,precomputedEntities:f})).entityChangeStatus}catch{}const b=l.filter(W=>W.status!=="deleted").map(W=>({path:W.path,status:W.status})),v=Yo(o),N=Uo(o),C=pd(o),E=md(o);let k=null,_=null,S=null,j=null;try{const W=L.join(o,".codeyam","config.json");if(K.existsSync(W)){const F=JSON.parse(K.readFileSync(W,"utf8"));k=F.projectTitle||null,_=F.projectDescription||null,S=F.defaultScreenSize||null,j=F.screenSizes||null}}catch{}const $=$1(e.url);let T=null,R=null;if($&&t)try{await ze();const W=await qe({}),F=W==null?void 0:W.find(J=>J.sha===$);if(F){const J=F.name,Y=F.filePath||"",z=F.entityType||"visual";R={name:J,filePath:Y,entityType:z,displayName:J};const A=W==null?void 0:W.find(B=>B.name===F.name&&B.filePath===F.filePath&&B.sha!==$&&B.createdAt&&F.createdAt&&B.createdAt>F.createdAt);A&&(T=A.sha)}}catch{}let I="none",P=null;try{if(P=Zd(projRoot),(P==null?void 0:P.status)==="complete")I="complete";else if((P==null?void 0:P.status)==="in-progress"||(P==null?void 0:P.status)==="surveyed")I="active";else if(j1(projRoot))I="active";else if(t){const W=a.length>0;P1(projRoot,{hasEditorScenarios:W})&&(I="candidate")}}catch{}return X({projectSlug:t,projectRoot:Ne(),hasProject:!!t,editorMode:r,scenarios:s,allScenarios:a,components:c,analyzedEntities:h,allEntities:m,glossaryFunctions:u,glossaryEntries:p,entityImports:g,pageFilePaths:y,entityChangeStatus:w,modifiedFiles:b,featureName:v,userPrompt:N,projectTitle:k,projectDescription:_,defaultScreenSize:S,screenSizes:j,editorStep:(C==null?void 0:C.step)??null,editorStepLabel:(C==null?void 0:C.label)??null,claudeSessionId:E,focusedEntitySha:$,newerEntitySha:T,focusedEntity:R,migrationMode:I,migrationState:P})}class R1 extends Au{constructor(){super(...arguments);Rt(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:d("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)&&d("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 D1=Qe(function(){var ui;const{projectSlug:t,projectRoot:r,hasProject:s,scenarios:a,allScenarios:o,analyzedEntities:i,allEntities:l,glossaryFunctions:c,glossaryEntries:p,entityImports:u,pageFilePaths:m,entityChangeStatus:h,modifiedFiles:f,featureName:g,userPrompt:y,projectTitle:x,projectDescription:w,defaultScreenSize:b,screenSizes:v,editorStep:N,editorStepLabel:C,claudeSessionId:E,focusedEntitySha:k,newerEntitySha:_,focusedEntity:S,migrationMode:j,migrationState:$}=tt(),[T,R]=Ln(),I=Pt(),P=ge(null),H=ge(null),W=ge(null),F=ge(null),[J,Y]=M(k);re(()=>{Y(k)},[k]);const z=ae(()=>l1(J,l),[J,l,o]),A=(z==null?void 0:z.displayName)??void 0,B=T.get("scenario")||void 0,[G,q]=M(()=>A?[A]:[]),Q=ge(null),U=ge([]),D=ge(null);re(()=>{var Ve;const te=B||((Ve=Di(o))==null?void 0:Ve.id);if(!Eg(te,Q.current))return;const be=o.find(lt=>lt.id===te);if(!be)return;Q.current=te;const je=Na(be,U.current,D.current);je&&Wt(je);const Be=Qt(be.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Be,scenarioId:be.id,scenarioName:be.name,scenarioType:be.type})}).catch(()=>{})},[B,o]),re(()=>{const te=new BroadcastChannel("codeyam-editor");return te.onmessage=be=>{var je;if(((je=be.data)==null?void 0:je.type)==="switch-scenario"&&be.data.scenarioId){const Be=be.data.scenarioId,Ve=o.find(Pn=>Pn.id===Be);if(!Ve)return;Q.current=Be;const lt=new URLSearchParams(T);lt.set("scenario",Be),lt.delete("zoom"),R(lt),Z(null),fe(null),Le(null),gt(!0);const rr=Qt(Ve.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:rr,scenarioId:Be,scenarioType:Ve.type})}).then(()=>{Ee(!1),Xe(Pn=>Pn+1)}).catch(()=>{gt(!1)})}},()=>te.close()},[T,R,o]),re(()=>{if(T.get("ref")!=="link"||!B)return;const te=new BroadcastChannel("codeyam-editor");te.postMessage({type:"switch-scenario",scenarioId:B}),te.close(),window.close()},[]);const{devServerUrl:O,proxyUrl:V,isStarting:ne,error:ie,canStartServer:we,retryServer:le,startServer:ce}=C1({skipAutoStart:j==="candidate"||j==="active"}),[ve,Ee]=M(!1),[he,Z]=M(null),[Se,fe]=M(null),[se,pe]=M(!1),[_e,Le]=M(null),de=oe(async te=>{const je=await(await fetch("/api/editor-load-commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commitSha:te})})).json();return je.success&&(Le(null),Ee(!1)),je},[]),We=oe((te,be)=>{fe(je=>(te&&te!==je&&Ee(!1),te)),!be&&te&&Ee(!0),pe(be)},[]),Je=oe(te=>{Le(null),Z(je=>(je&&je.analysisId===te.analysisId||(fe(null),Xe(Ve=>Ve+1)),te)),pe(!0),Ee(!1);const be=new URLSearchParams(T);be.delete("scenario"),be.delete("zoom"),R(be)},[T,R]),[Ie,Wt]=M(b?{name:b.name,width:b.width,height:b.height}:{name:"Desktop",width:1440,height:900}),[Xs,ea]=M(!1),[Ze,Jt]=M(!1),Kn=b?{name:b.name,width:b.width,height:b.height}:null;D.current=Kn;const Nn=Sr(),nt=ae(()=>{const te=Nn.pathname.split("/").filter(Boolean),be=te[te.length-1];return be==="build"||be==="journal"?be:be==="structure"?"data":"app"},[Nn.pathname]),st=oe(te=>{Y(null),q([]);const be=te==="app"?"":`/${te==="data"?"structure":te}`,je=T.get("scenario"),Be=je?`?scenario=${je}`:"";I(`/editor${be}${Be}`)},[I,T]),ht=oe(()=>{st("build"),He(!0)},[st]),Mt=oe(()=>{st("build"),He(!0),setTimeout(()=>{var te;(te=P.current)==null||te.sendInput("codeyam editor migrate")},300)},[st]),[at,He]=M(nt==="build"),ta=!!(g&&N),[Ht,jr]=M(ta?"pending":"no-session");re(()=>{Ht==="pending"&&(st("build"),He(!0))},[Ht,st]);const na=oe(()=>{jr("continue")},[]),[Sn,Cn]=M(!1),[ra,Tr]=M(!1),Mr=ge(!1),_n=ge(0),sa=oe(te=>{Cn(te),te&&!Mr.current&&(Tr(!1),_n.current=Date.now()),te||(_n.current=0),Mr.current=te},[]);_1(Sn);const{editorWidth:$r,isDragging:Ir,isEditorCollapsed:ft,isPreviewCollapsed:qn,handleMouseDown:Rr,handleDoubleClick:Dr,collapseEditor:Or,expandEditor:Qn,expandPreview:Fr}=x1(F),[kn,Zn]=M(!1),Lr=oe(()=>{Zn(!0),st("build"),He(!0)},[st]),Xn=oe(()=>{Zn(!1)},[]),zr=oe(te=>{Wt(te),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:te,skipBroadcast:!0})})},[]),[er,tr]=M($n);re(()=>{const te=eg();tr(te),te.systemNotification&&typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},[]);const Br=oe(te=>{tr(te),tg(te)},[]);re(()=>{if(nt==="build"){Cn(!1);const te=setTimeout(()=>{var be,je;(be=P.current)==null||be.scrollToBottom(),(je=P.current)==null||je.focus()},50);return()=>clearTimeout(te)}},[nt]),re(()=>{function te(){!document.hidden&&nt==="build"&&Cn(!1)}return document.addEventListener("visibilitychange",te),()=>document.removeEventListener("visibilitychange",te)},[nt]);const[$t,Yr]=M(null);re(()=>{const te=W.current;if(!te)return;const be=new ResizeObserver(je=>{const Be=je[0];Be&&Yr({width:Be.contentRect.width,height:Be.contentRect.height})});return be.observe(te),()=>be.disconnect()},[]);const ye=ae(()=>$t?Ag($t,Ie):1,[$t,Ie]),[Me,Xe]=M(0),[Ye,ot]=M(null),[It,gt]=M(!1),[it,Ge]=M(!1),[rn,En]=M(!1),aa=ge(0);re(()=>{Me>0&&(aa.current=Date.now()+3e3)},[Me]);const Xd=oe(()=>{if(Date.now()<aa.current)return;const te=_n.current;te===0||Date.now()-te<5e3||Ge(!0)},[]);re(()=>{const te=be=>{var je;if(((je=be.data)==null?void 0:je.type)==="codeyam-localstorage-changed"){if(Date.now()<aa.current)return;const Be=_n.current;if(Be===0||Date.now()-Be<5e3)return;Ge(!0)}};return window.addEventListener("message",te),()=>window.removeEventListener("message",te)},[]);const ii=oe(async te=>{En(!0);try{let be;const je=H.current;je!=null&&je.contentWindow&&(be=await new Promise(lt=>{const rr=setTimeout(()=>lt(void 0),2e3),Pn=pi=>{var mi;((mi=pi.data)==null?void 0:mi.type)==="codeyam-localstorage-state"&&(clearTimeout(rr),window.removeEventListener("message",Pn),lt(pi.data.data))};window.addEventListener("message",Pn),je.contentWindow.postMessage({type:"codeyam-get-localstorage"},"*")}));const Ve=await(await fetch("/api/editor-save-seed-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:te,localStorage:be})})).json();Ve.success?Ge(!1):console.error("[editor] Save seed state failed:",Ve.error)}catch(be){console.error("[editor] Save seed state error:",be)}finally{En(!1)}},[]),eu=oe((te,be)=>{if(ot(te||null),be){const je=new URLSearchParams(T);je.set("scenario",be),Q.current=be,R(je);const Be=o.find(Ve=>Ve.id===be);if(Be){const Ve=Na(Be,U.current,D.current);Ve&&Wt(Ve)}}Le(null),Ee(!1),Xe(je=>je+1)},[T,R,o]),{customSizes:oa,addCustomSize:tu,removeCustomSize:nu}=Ls(t),ia=ae(()=>OC(v),[v]),la=ae(()=>[...ia,...oa],[ia,oa]);U.current=la;const li=ae(()=>{const te=new Map;for(const be of l){te.set(be.name,be.sha);const je=Tt(Ct(be.filePath));je!==be.name&&te.set(je,be.sha)}return te},[l]),ru=ae(()=>{const te=[{name:"App"}];for(const be of G)te.push({name:be,componentName:be,entitySha:li.get(be)});return te},[G,li]),ci=oe((te,be)=>{if(!te){q([]),Y(null);const lt=T.get("scenario"),rr=lt?`?scenario=${lt}`:"";I(`/editor${rr}`);return}if(!be){console.error(`[editor] No entity SHA for "${te}" — entity missing from database`);return}const je=G.indexOf(te);je>=0?q(G.slice(0,je+1)):q([...G,te]);const Be=o.find(lt=>lt.entitySha===be);Y(be);const Ve=Be?`?scenario=${Be.id}`:"";I(`/editor/entity/${be}${Ve}`)},[I,o,G,T]),nr=oe(te=>{Z(null),fe(null),Le(null),ot(null);const be=Na(te,la,Kn);be&&Wt(be),Q.current=te.id;const je=new URLSearchParams(T);je.set("scenario",te.id),R(je),gt(!0),Ge(!1);const Be=Qt(te.name);fetch("/api/editor-switch-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioSlug:Be,scenarioId:te.id,scenarioType:te.type,skipBroadcast:!0})}).then(()=>{Ee(!1),Xe(Ve=>Ve+1)}).catch(()=>{gt(!1)})},[T,R,la]),su=oe(te=>{if(!te.commitSha){const be=o.find(je=>je.name===te.scenarioName);if(be){nr(be);return}}Le(te)},[o,nr]),au=te=>{const be={name:te.name,width:te.width,height:te.height};Wt(be),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:be,skipBroadcast:!0})})},ou=(te,be,je)=>{tu(te,be,je)},iu=te=>{Wt(te),fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultScreenSize:te,skipBroadcast:!0})})},di=()=>{he||Ee(!0),gt(!1)},An=ae(()=>kg({activeAnalyzedScenario:!!he,analyzedPreviewUrl:Se,activeScenarioId:B||null,scenarios:o,proxyUrl:V,devServerUrl:O,zoomComponent:A||null}),[V,O,A,B,o,he,Se]),ca=ae(()=>{const te=Lc(An,Ye);if(!te)return null;const be=te.includes("?")?"&":"?";return`${te}${be}__cb=${Me}`},[An,Ye,Me]),lu=ae(()=>({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:c==null?void 0:c.length,entityChangeStatusKeys:h?Object.keys(h):[],featureName:g}),[t,s,a,o,i,c,h,g]);return d(xe,{children:[n(R1,{loaderSnapshot:lu,children:d("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[he&&n(v1,{analysisId:he.analysisId,scenarioId:he.scenarioId,scenarioName:he.scenarioName,entityName:he.entityName,projectSlug:t,onStateChange:We},he.analysisId),d("div",{ref:F,className:"flex-1 flex min-h-0",children:[ft&&n("div",{className:"shrink-0 flex items-center justify-center cursor-pointer hover:bg-[#3d3d3d] transition-colors",style:{width:8,backgroundColor:"#2d2d2d"},onClick:Qn,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"})})}),d("aside",{className:"bg-[#1e1e1e] shrink-0 flex flex-col overflow-hidden",style:{...ft?{display:"none"}:$r!==null?{width:`${$r}px`}:{width:"50%"}},children:[_&&z&&d("div",{className:"px-3 py-2 text-xs flex items-center justify-between",style:{background:"#2a1f00",borderBottom:"1px solid #3d2e00",color:"#f0c040"},children:[d("span",{children:["Viewing an older version of"," ",n("strong",{children:z.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(g1,{activeTab:nt,onTabChange:te=>{st(te),te==="build"&&He(!0),fetch("/api/telemetry-page-view",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({route:`/editor/${te}`})}).catch(()=>{})},buildIdle:Sn}),d("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:[Sn&&nt!=="build"&&!ra&&d("div",{className:"absolute top-3 left-1/2 -translate-x-1/2 z-50 animate-[slideDown_0.3s_ease-out]",children:[n("style",{children:`
|
|
544
|
-
@keyframes slideDown {
|
|
545
|
-
from { transform: translate(-50%, -100%); opacity: 0; }
|
|
546
|
-
to { transform: translate(-50%, 0); opacity: 1; }
|
|
547
|
-
}
|
|
548
|
-
`}),d("div",{className:"flex items-center gap-1 bg-amber-50 border-2 border-amber-300 rounded-lg shadow-lg",children:[d("button",{onClick:()=>{st("build"),He(!0)},className:"flex items-center gap-2 px-4 py-2 cursor-pointer hover:bg-amber-100 transition-colors rounded-l-md",children:[n("span",{className:"inline-block w-2 h-2 rounded-full bg-amber-400 animate-pulse"}),n("span",{className:"text-sm font-medium text-amber-900",children:"Claude is waiting for you"}),n("span",{className:"text-xs text-amber-600 ml-1",children:"Go to Build"})]}),n("button",{onClick:te=>{te.stopPropagation(),Tr(!0)},className:"px-2 py-2 cursor-pointer hover:bg-amber-100 transition-colors rounded-r-md text-amber-400 hover:text-amber-600","aria-label":"Dismiss",children:n("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:n("path",{d:"M3 3l8 8M11 3l-8 8"})})})]})]}),at&&d("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:nt==="build"?"visible":"hidden"},children:[n(JC,{projectTitle:x,featureName:g,editorStep:N,editorStepLabel:C,migrationMode:j}),n("div",{className:"flex-1 min-h-0",style:kn?{flex:"1 1 50%"}:void 0,children:Ht==="pending"?n(FC,{featureName:g,editorStep:N,editorStepLabel:C,onContinue:na}):n(Mc,{ref:P,entityName:"Editor",projectSlug:t,entityFilePath:null,scenarioName:null,onRefreshPreview:eu,onShowResults:Lr,onHideResults:Xn,onSetViewport:zr,onDataMutationForwarded:Xd,editorMode:!0,onIdleChange:sa,notificationSettings:er,buildTabActive:nt==="build",claudeStartMode:Ht==="continue"?"resume":"fresh",claudeSessionId:E,resultsOpen:kn})}),kn&&n("div",{style:{flex:"1 1 50%"},className:"min-h-0 border-t-2 border-gray-300",children:n(d1,{scenarios:a,allScenarios:o,glossaryFunctions:c,projectRoot:r,activeScenarioId:B,onScenarioSelect:nr,onClose:Xn,entityChangeStatus:h,modifiedFiles:f,featureName:g,userPrompt:y})})]}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:nt==="app"?"visible":"hidden"},children:n(h1,{hasProject:s,scenarios:o,analyzedEntities:i,allEntities:l,glossaryFunctions:c,glossaryEntries:p,projectRoot:r,activeScenarioId:B,onScenarioSelect:nr,onAnalyzedScenarioSelect:Je,onSwitchToBuild:ht,zoomComponent:A,focusedEntity:z,onZoomChange:ci,entityImports:u,pageFilePaths:m,projectTitle:x,projectDescription:w,breadcrumbItems:ru,migrationMode:j,migrationState:$,onStartMigration:Mt})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:nt==="data"?"visible":"hidden"},children:n(HC,{scenarios:o,projectRoot:r,activeScenarioId:B,onScenarioSelect:nr,zoomComponent:A,focusedEntity:z,onZoomChange:ci,analyzedEntities:[],glossaryFunctions:c,activeAnalyzedScenarioId:he==null?void 0:he.scenarioId,onAnalyzedScenarioSelect:Je,entityImports:u,pageFilePaths:m})}),n("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:nt==="journal"?"visible":"hidden"},children:n(t1,{isActive:nt==="journal",onScreenshotClick:su,glossaryFunctions:c})})]}),n(Tc,{serverUrl:O,isStarting:ne,projectSlug:t,devServerError:ie,onStartServer:we?ce:void 0,notificationSettings:er,onChangeNotificationSettings:Br})]}),!ft&&!qn&&n(y1,{onMouseDown:Rr,onDoubleClick:Dr,isDragging:Ir}),qn&&n("div",{className:"shrink-0 flex items-center justify-center cursor-pointer hover:bg-[#3d3d3d] transition-colors",style:{width:8,backgroundColor:"#2d2d2d"},onClick:Fr,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"})})}),d("div",{className:"flex-1 flex flex-col min-w-0",style:{...qn?{display:"none"}:void 0,...Ir?{pointerEvents:"none"}:void 0},children:[d("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:()=>{ft?(Qn(),setTimeout(()=>{var te;return(te=P.current)==null?void 0:te.focus()},50)):Or()},className:`p-1.5 rounded transition-colors cursor-pointer ${ft?"text-white bg-[#666] hover:bg-[#777]":"text-gray-500 hover:text-gray-300"}`,title:ft?"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:ft?d(xe,{children:[n("path",{d:"M13 17l5-5-5-5"}),n("path",{d:"M6 17l5-5-5-5"})]}):d(xe,{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:d("div",{className:"flex items-center gap-1 pointer-events-auto",children:[vs.map(te=>d("button",{onClick:()=>{Ze&&Jt(!1),au(te)},className:`p-1.5 rounded transition-colors cursor-pointer ${!Ze&&Ie.name===te.name?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:`${te.name} (${te.width}×${te.height})`,children:[te.name==="Desktop"&&d("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"})]}),te.name==="Laptop"&&d("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"})]}),te.name==="Tablet"&&d("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"})]}),te.name==="Mobile"&&d("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"})]})]},te.name)),d("div",{className:"relative",children:[d("button",{onClick:()=>{Ze||ea(te=>!te)},className:`flex items-center gap-1.5 px-2 py-1 rounded transition-colors ${Ze?"":"cursor-pointer"} ${Ze||Xs||!vs.some(te=>te.name===Ie.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:Ze&&$t?`${Math.round($t.width)} × ${Math.round($t.height)}`:`${Ie.width} × ${Ie.height??900}`})]}),Xs&&n(Gf,{currentWidth:Ie.width,currentHeight:Ie.height??900,devicePresets:ia,customSizes:oa,onApply:iu,onSave:ou,onRemove:nu,onClose:()=>ea(!1)})]}),n("button",{onClick:()=>{Jt(te=>!te)},className:`p-1.5 rounded transition-colors cursor-pointer ${Ze?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:Ze?"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:Ze?d(xe,{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"})]}):d(xe,{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 te=ca||An;te&&window.open(te,"_blank")},className:"p-1.5 rounded text-gray-500 hover:text-gray-300 transition-colors cursor-pointer",title:"Open preview in new window",children:d("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"})]})})]})})]}),it&&n(N1,{onSaveToCurrent:()=>void ii("overwrite"),onSaveAsNew:()=>void ii("new"),onDismiss:()=>Ge(!1),isSaving:rn,scenarioName:(ui=o.find(te=>{var be;return te.id===(B||((be=Di(o))==null?void 0:be.id))}))==null?void 0:ui.name}),n("div",{ref:W,className:`flex-1 flex overflow-hidden ${Ze?"":"items-center justify-center p-8"}`,style:Ze?{backgroundColor:"#fff"}:_e?{backgroundColor:"#f5f0e8",backgroundImage:"repeating-linear-gradient(0deg, transparent, transparent 19px, #e8e0d0 19px, #e8e0d0 20px), repeating-linear-gradient(90deg, transparent, transparent 19px, #e8e0d0 19px, #e8e0d0 20px)"}:{backgroundImage:`
|
|
549
|
-
linear-gradient(45deg, #333 25%, transparent 25%),
|
|
550
|
-
linear-gradient(-45deg, #333 25%, transparent 25%),
|
|
551
|
-
linear-gradient(45deg, transparent 75%, #333 75%),
|
|
552
|
-
linear-gradient(-45deg, transparent 75%, #333 75%)
|
|
553
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#2d2d2d"},children:_e?n(b1,{preview:_e,onDismiss:()=>Le(null),onLoadCommit:de}):An?Ze?d("div",{className:"relative w-full h-full bg-white",children:[!ve&&!It&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("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(Ft,{})}),d("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"})]})]})}),It&&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:d("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:H,src:ca||An,className:"w-full h-full border-none",title:"Editor preview",onLoad:di,style:{opacity:ve?1:0}},Me)]}):n("div",{style:{width:`${Ie.width*ye}px`,height:`${(Ie.height??900)*ye}px`},children:d("div",{className:"relative bg-white origin-top-left",style:{width:`${Ie.width}px`,height:`${Ie.height??900}px`,transform:ye<1?`scale(${ye})`:void 0},children:[!ve&&!It&&n("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:d("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(Ft,{})}),d("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"})]})]})}),It&&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:d("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:H,src:ca||An,className:"w-full h-full border-none",title:"Editor preview",onLoad:di,style:{opacity:ve?1:0}},Me)]})}):n("div",{className:"bg-[#2a2a2a] rounded-lg flex flex-col items-center justify-center",style:{width:`${Ie.width*ye}px`,height:`${(Ie.height??900)*ye}px`},children:ie?d("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:ie}),n("button",{onClick:le,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"})]}):ne||se?d(xe,{children:[n("div",{className:"mb-4",children:n(Ft,{})}),d("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:se?"Starting Interactive Mode":"Starting Dev Server"}),n("p",{className:"text-sm text-gray-400 leading-5 m-0 font-['IBM_Plex_Sans']",children:se?"Loading component preview...":"Your dev server is starting up..."})]})]}):d("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(zl,{})]})}),O1=Object.freeze(Object.defineProperty({__proto__:null,default:D1,loader:I1,meta:M1,shouldRevalidate:T1},Symbol.toStringTag,{value:"Module"})),F1=Qe(function(){return null}),cr=Object.freeze(Object.defineProperty({__proto__:null,default:F1},Symbol.toStringTag,{value:"Module"})),J2={entry:{module:"/assets/entry.client-SuW9syRS.js",imports:["/assets/jsx-runtime-D_zvdyIk.js","/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/index-CWV9XZiG.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-BxUQigda.js",imports:["/assets/jsx-runtime-D_zvdyIk.js","/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/index-CWV9XZiG.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/ReportIssueModal-C2PLkej3.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/loader-circle-De-7qQ2u.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/book-open-CL-lMgHh.js","/assets/useToast-5HR2j9ZE.js","/assets/useLastLogLine-BNd5hYuW.js","/assets/LogViewer-CM5zg40N.js","/assets/EntityTypeIcon-CD7lGABo.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/chevron-down-GmAjGS9-.js","/assets/circle-check-DFcQkN5j.js","/assets/CopyButton-CLe80MMu.js","/assets/triangle-alert-DqJ0j69l.js","/assets/copy-C6iF61Xs.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-C6eeL24i.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/Spinner-D0LgAaSa.js","/assets/useLastLogLine-BNd5hYuW.js","/assets/ViewportInspectBar-BA_Ry-rs.js","/assets/useCustomSizes-DhXHbEjP.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/InlineSpinner-CgTNOhnu.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-KTQuL0aj.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/Spinner-D0LgAaSa.js","/assets/useLastLogLine-BNd5hYuW.js","/assets/ViewportInspectBar-BA_Ry-rs.js","/assets/useCustomSizes-DhXHbEjP.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/InlineSpinner-CgTNOhnu.js","/assets/editorPreview-oepecPae.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/preload-helper-ckwbz45p.js"],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/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-CAoXLsQr.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/InteractivePreview-CKeQT5Ty.js","/assets/Spinner-D0LgAaSa.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-BNd5hYuW.js","/assets/InlineSpinner-CgTNOhnu.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-DQM8E7L4.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/InteractivePreview-CKeQT5Ty.js","/assets/Spinner-D0LgAaSa.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-BNd5hYuW.js","/assets/InlineSpinner-CgTNOhnu.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-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-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-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.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-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-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-Bg3e7q4S.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/terminal-CrplD4b1.js","/assets/search-BdBb5aqc.js","/assets/chevron-down-GmAjGS9-.js","/assets/book-open-CL-lMgHh.js","/assets/triangle-alert-DqJ0j69l.js","/assets/copy-C6iF61Xs.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-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)-BOARiB-g.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/LogViewer-CM5zg40N.js","/assets/useLastLogLine-BNd5hYuW.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/EntityTypeIcon-CD7lGABo.js","/assets/EntityTypeBadge-CQgyEGV-.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/LoadingDots-By5zI316.js","/assets/loader-circle-De-7qQ2u.js","/assets/pause-CFxEKL1u.js","/assets/createLucideIcon-4ImjHTVC.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._-Blfy9UlN.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useLastLogLine-BNd5hYuW.js","/assets/Spinner-D0LgAaSa.js","/assets/InteractivePreview-CKeQT5Ty.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/LibraryFunctionPreview-D3s1MFkb.js","/assets/LoadingDots-By5zI316.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-DUMfcNVK.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-CD7lGABo.js","/assets/CopyButton-CLe80MMu.js","/assets/LogViewer-CM5zg40N.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/preload-helper-ckwbz45p.js","/assets/InlineSpinner-CgTNOhnu.js","/assets/ViewportInspectBar-BA_Ry-rs.js","/assets/useCustomSizes-DhXHbEjP.js","/assets/ReportIssueModal-C2PLkej3.js","/assets/circle-check-DFcQkN5j.js","/assets/triangle-alert-DqJ0j69l.js","/assets/copy-C6iF61Xs.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-DSCdE99u.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/LoadingDots-By5zI316.js","/assets/EntityTypeIcon-CD7lGABo.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/chevron-down-GmAjGS9-.js","/assets/search-BdBb5aqc.js","/assets/loader-circle-De-7qQ2u.js","/assets/createLucideIcon-4ImjHTVC.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-C8y4mmyv.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/ScenarioViewer-DUMfcNVK.js","/assets/InteractivePreview-CKeQT5Ty.js","/assets/ViewportInspectBar-BA_Ry-rs.js","/assets/useCustomSizes-DhXHbEjP.js","/assets/LogViewer-CM5zg40N.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/useLastLogLine-BNd5hYuW.js","/assets/Spinner-D0LgAaSa.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-C2PLkej3.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/circle-check-DFcQkN5j.js","/assets/triangle-alert-DqJ0j69l.js","/assets/copy-C6iF61Xs.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/InlineSpinner-CgTNOhnu.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-DdE-Untf.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/CopyButton-CLe80MMu.js","/assets/copy-C6iF61Xs.js","/assets/createLucideIcon-4ImjHTVC.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-BAWd-Xjf.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useLastLogLine-BNd5hYuW.js","/assets/useToast-5HR2j9ZE.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/LogViewer-CM5zg40N.js","/assets/EntityTypeIcon-CD7lGABo.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/circle-check-DFcQkN5j.js","/assets/loader-circle-De-7qQ2u.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-Cx2xEx7s.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/terminal-CrplD4b1.js","/assets/copy-C6iF61Xs.js","/assets/CopyButton-CLe80MMu.js","/assets/chevron-down-GmAjGS9-.js","/assets/search-BdBb5aqc.js","/assets/pause-CFxEKL1u.js","/assets/book-open-CL-lMgHh.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-D-xGrg29.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/EntityItem-Crt_KN_U.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/chevron-down-GmAjGS9-.js","/assets/search-BdBb5aqc.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/useToast-5HR2j9ZE.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/LibraryFunctionPreview-D3s1MFkb.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DqJ0j69l.js","/assets/EntityTypeIcon-CD7lGABo.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-B_IX45ih.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.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-Bq_fbXP5.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useReportContext-Cy5Qg_UR.js","/assets/EntityItem-Crt_KN_U.js","/assets/LogViewer-CM5zg40N.js","/assets/index-DE3jI_dv.js","/assets/fileTableUtils-Daa96Fr1.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/useToast-5HR2j9ZE.js","/assets/TruncatedFilePath-CK7-NaPZ.js","/assets/SafeScreenshot-DanvyBPb.js","/assets/LibraryFunctionPreview-D3s1MFkb.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-DqJ0j69l.js","/assets/EntityTypeIcon-CD7lGABo.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)-DII1pg_z.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js","/assets/jsx-runtime-D_zvdyIk.js","/assets/useCustomSizes-DhXHbEjP.js","/assets/editorPreview-oepecPae.js","/assets/CopyButton-CLe80MMu.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/Spinner-D0LgAaSa.js","/assets/copy-C6iF61Xs.js","/assets/createLucideIcon-4ImjHTVC.js","/assets/useLastLogLine-BNd5hYuW.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-Gbk_i5Js.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.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-Gbk_i5Js.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.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-Gbk_i5Js.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0},"editor-tab-journal":{id:"editor-tab-journal",parentId:"routes/editor.entity.($sha)",path:"journal",index:void 0,caseSensitive:void 0,hasAction:!1,hasLoader:!1,hasClientAction:!1,hasClientLoader:!1,hasClientMiddleware:!1,hasDefaultExport:!0,hasErrorBoundary:!1,module:"/assets/editor._tab-Gbk_i5Js.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.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-Gbk_i5Js.js",imports:["/assets/chunk-JZWAC4HX-BAdwhyCx.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-cdf2c0a7.js",version:"cdf2c0a7",sri:void 0},H2="build/client",V2="/",G2={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,unstable_trailingSlashAwareDataRequests:!1,unstable_previewServerPrerendering:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},K2=!0,q2=!1,Q2=[],Z2={mode:"lazy",manifestPath:"/__manifest"},X2="/",e5={module:$p},t5={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:Hf},"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:Zf},"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:Tg},"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:$g},"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:t0},"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:ry},"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:iy},"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:hy},"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:yy},"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:by},"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:vy},"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:Iy},"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:Dy},"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:Fy},"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:zy},"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:Yy},"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:Kx},"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:lb},"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:db},"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:pb},"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:hb},"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:gb},"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:bb},"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:Nb},"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:kb},"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:$b},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:Rb},"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:Hb},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:qb},"routes/api.agent-transcripts":{id:"routes/api.agent-transcripts",parentId:"root",path:"api/agent-transcripts",index:void 0,caseSensitive:void 0,module:dw},"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:hw},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:yw},"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:bw},"routes/api.editor-scenarios":{id:"routes/api.editor-scenarios",parentId:"root",path:"api/editor-scenarios",index:void 0,caseSensitive:void 0,module:vw},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Cw},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:Ew},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:Pw},"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:Mw},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:Uw},"routes/api.editor-journal":{id:"routes/api.editor-journal",parentId:"root",path:"api/editor-journal",index:void 0,caseSensitive:void 0,module:Jw},"routes/api.editor-refresh":{id:"routes/api.editor-refresh",parentId:"root",path:"api/editor-refresh",index:void 0,caseSensitive:void 0,module:Xw},"routes/api.editor-session":{id:"routes/api.editor-session",parentId:"root",path:"api/editor-session",index:void 0,caseSensitive:void 0,module:tv},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:ov},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:dv},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:hv},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:gv},"routes/agent-transcripts":{id:"routes/agent-transcripts",parentId:"root",path:"agent-transcripts",index:void 0,caseSensitive:void 0,module:Mv},"routes/api.editor-commit":{id:"routes/api.editor-commit",parentId:"root",path:"api/editor-commit",index:void 0,caseSensitive:void 0,module:Iv},"routes/api.editor-audit":{id:"routes/api.editor-audit",parentId:"root",path:"api/editor-audit",index:void 0,caseSensitive:void 0,module:Dv},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:Fv},"routes/api.save-fixture":{id:"routes/api.save-fixture",parentId:"root",path:"api/save-fixture",index:void 0,caseSensitive:void 0,module:Wv},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:Hv},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:nN},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:aN},"routes/api.editor-file":{id:"routes/api.editor-file",parentId:"root",path:"api/editor-file",index:void 0,caseSensitive:void 0,module:iN},"routes/api.labs-unlock":{id:"routes/api.labs-unlock",parentId:"root",path:"api/labs-unlock",index:void 0,caseSensitive:void 0,module:uN},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:mN},"routes/api.rule-path":{id:"routes/api.rule-path",parentId:"root",path:"api/rule-path",index:void 0,caseSensitive:void 0,module:xN},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:BN},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:WN},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:QN},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:XN},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:tS},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:fS},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:xS},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:vS},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:AS},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:jS},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:LS},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:dC},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:gC},"routes/labs":{id:"routes/labs",parentId:"root",path:"labs",index:void 0,caseSensitive:void 0,module:_C},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:DC},"routes/editor.entity.($sha)":{id:"routes/editor.entity.($sha)",parentId:"root",path:"editor",index:void 0,caseSensitive:void 0,module:O1},"editor-tab-index":{id:"editor-tab-index",parentId:"routes/editor.entity.($sha)",path:void 0,index:!0,caseSensitive:void 0,module:cr},"editor-tab-build":{id:"editor-tab-build",parentId:"routes/editor.entity.($sha)",path:"build",index:void 0,caseSensitive:void 0,module:cr},"editor-tab-structure":{id:"editor-tab-structure",parentId:"routes/editor.entity.($sha)",path:"structure",index:void 0,caseSensitive:void 0,module:cr},"editor-tab-journal":{id:"editor-tab-journal",parentId:"routes/editor.entity.($sha)",path:"journal",index:void 0,caseSensitive:void 0,module:cr},"editor-tab-entity":{id:"editor-tab-entity",parentId:"routes/editor.entity.($sha)",path:"entity/:sha",index:void 0,caseSensitive:void 0,module:cr}},n5=!1;export{_m as $,wh as A,yh as B,Sh as C,hh as D,Te as E,Fm as F,Lm as G,bn as H,$2 as I,rm as J,am as K,om as L,im as M,nc as N,cm as O,dm as P,rc as Q,pm as R,mm as S,Am as T,sc as U,ym as V,bm as W,wm as X,vm as Y,Sm as Z,Cm as _,qp as a,km as a0,tm as a1,nm as a2,Em as a3,ps as a4,jm as a5,Tm as a6,Mm as a7,$m as a8,Rm as a9,q2 as aA,Q2 as aB,Z2 as aC,X2 as aD,e5 as aE,t5 as aF,n5 as aG,J2 as aH,Im as aa,F2 as ab,bo as ac,L2 as ad,B2 as ae,z2 as af,O2 as ag,W2 as ah,Re as ai,Rh as aj,$h as ak,Hh as al,Is as am,I2 as an,dc as ao,Ah as ap,Ph as aq,Kw as ar,U2 as as,tn as at,R2 as au,D2 as av,H2 as aw,V2 as ax,G2 as ay,K2 as az,gn as b,fn as c,Bt as d,kr as e,ho as f,As as g,tc as h,Gp as i,Zm as j,Xm as k,Zt as l,Yt as m,go as n,ih as o,hs as p,qe as q,ic as r,lc as s,yo as t,Kt as u,cc as v,Un as w,Dn as x,qm as y,ki as z};
|