@codeyam/codeyam-cli 0.1.0-staging.323686 → 0.1.0-staging.483fdc2
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 +2 -2
- package/analyzer-template/packages/ai/index.ts +6 -1
- package/analyzer-template/packages/ai/src/lib/analyzeScope.ts +39 -17
- package/analyzer-template/packages/ai/src/lib/astScopes/astScopeAnalyzer.ts +67 -9
- package/analyzer-template/packages/ai/src/lib/astScopes/processExpression.ts +308 -50
- package/analyzer-template/packages/ai/src/lib/astScopes/types.ts +15 -6
- package/analyzer-template/packages/ai/src/lib/dataStructure/ScopeDataStructure.ts +664 -242
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.ts +16 -3
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.ts +6 -4
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.ts +20 -1
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.ts +35 -13
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.ts +160 -0
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.ts +40 -30
- package/analyzer-template/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.ts +289 -83
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarioData.ts +269 -1
- package/analyzer-template/packages/ai/src/lib/generateEntityScenarios.ts +9 -5
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +11 -3
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionalEffects.ts +1 -1
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromConditionals.ts +297 -7
- package/analyzer-template/packages/ai/src/lib/generateExecutionFlowsFromJsxUsages.ts +1 -1
- package/analyzer-template/packages/ai/src/lib/mergeStatements.ts +90 -96
- package/analyzer-template/packages/ai/src/lib/promptGenerators/gatherAttributesMap.ts +10 -7
- package/analyzer-template/packages/ai/src/lib/resolvePathToControllable.ts +25 -13
- package/analyzer-template/packages/ai/src/lib/worker/SerializableDataStructure.ts +4 -3
- package/analyzer-template/packages/analyze/src/lib/FileAnalyzer.ts +65 -59
- package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +113 -26
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.ts +19 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.ts +19 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getAllExports.ts +11 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.ts +8 -0
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.ts +49 -1
- package/analyzer-template/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.ts +2 -1
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.ts +20 -6
- package/analyzer-template/packages/analyze/src/lib/files/analyze/analyzeEntities.ts +14 -4
- package/analyzer-template/packages/analyze/src/lib/files/analyze/gatherEntityMap.ts +4 -2
- package/analyzer-template/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.ts +0 -3
- package/analyzer-template/packages/analyze/src/lib/files/analyzeRemixRoute.ts +4 -5
- package/analyzer-template/packages/analyze/src/lib/files/getImportedExports.ts +14 -12
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.ts +57 -13
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.ts +29 -0
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateDataStructure.ts +35 -4
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +117 -9
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.ts +199 -17
- package/analyzer-template/packages/analyze/src/lib/files/scenarios/propagateArrayItemSchemas.ts +474 -0
- package/analyzer-template/packages/analyze/src/lib/files/setImportedExports.ts +2 -1
- package/analyzer-template/packages/analyze/src/lib/utils/getFileByPath.ts +19 -0
- package/analyzer-template/packages/aws/package.json +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts +5 -5
- package/analyzer-template/packages/github/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
- package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
- package/analyzer-template/packages/github/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
- package/analyzer-template/packages/github/package.json +1 -1
- package/analyzer-template/packages/types/src/types/ScenariosDataStructure.ts +6 -5
- package/analyzer-template/packages/types/src/types/ScopeAnalysis.ts +6 -1
- package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts +5 -5
- package/analyzer-template/packages/utils/dist/types/src/types/ScenariosDataStructure.d.ts.map +1 -1
- package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts +6 -1
- package/analyzer-template/packages/utils/dist/types/src/types/ScopeAnalysis.d.ts.map +1 -1
- package/analyzer-template/project/constructMockCode.ts +54 -9
- package/analyzer-template/project/writeMockDataTsx.ts +73 -2
- package/background/src/lib/virtualized/project/constructMockCode.js +45 -3
- package/background/src/lib/virtualized/project/constructMockCode.js.map +1 -1
- package/background/src/lib/virtualized/project/writeMockDataTsx.js +71 -2
- package/background/src/lib/virtualized/project/writeMockDataTsx.js.map +1 -1
- package/codeyam-cli/scripts/apply-setup.js +146 -0
- package/codeyam-cli/scripts/apply-setup.js.map +1 -1
- package/codeyam-cli/src/commands/debug.js +7 -5
- package/codeyam-cli/src/commands/debug.js.map +1 -1
- package/codeyam-cli/src/utils/install-skills.js +22 -0
- package/codeyam-cli/src/utils/install-skills.js.map +1 -1
- package/codeyam-cli/src/utils/reviewedRules.js +92 -0
- package/codeyam-cli/src/utils/reviewedRules.js.map +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-CX9f-5xM.css +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/{manifest-7522edd4.js → manifest-bba56ec1.js} +1 -1
- package/codeyam-cli/src/webserver/build/client/assets/memory-DuTFSyJ2.js +92 -0
- package/codeyam-cli/src/webserver/build/client/assets/{root-eVAaavTS.js → root-DTfSQARG.js} +6 -6
- package/codeyam-cli/src/webserver/build/server/assets/{index-DVzYx8PN.js → index-TD1f-DHV.js} +1 -1
- package/codeyam-cli/src/webserver/build/server/assets/server-build-BQ-1XyEa.js +258 -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/templates/codeyam:memory.md +174 -233
- package/codeyam-cli/templates/codeyam:new-rule.md +41 -2
- package/codeyam-cli/templates/rule-reflection-hook.py +161 -0
- package/codeyam-cli/templates/rules-instructions.md +126 -0
- package/package.json +1 -1
- package/packages/ai/index.js +2 -1
- package/packages/ai/index.js.map +1 -1
- package/packages/ai/src/lib/analyzeScope.js +29 -12
- package/packages/ai/src/lib/analyzeScope.js.map +1 -1
- package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js +54 -8
- package/packages/ai/src/lib/astScopes/astScopeAnalyzer.js.map +1 -1
- package/packages/ai/src/lib/astScopes/processExpression.js +239 -43
- package/packages/ai/src/lib/astScopes/processExpression.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js +503 -165
- package/packages/ai/src/lib/dataStructure/ScopeDataStructure.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js +13 -3
- package/packages/ai/src/lib/dataStructure/helpers/BatchSchemaProcessor.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js +6 -4
- package/packages/ai/src/lib/dataStructure/helpers/ScopeTreeManager.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js +22 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanKnownObjectFunctions.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js +34 -9
- package/packages/ai/src/lib/dataStructure/helpers/cleanNonObjectFunctions.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js +159 -0
- package/packages/ai/src/lib/dataStructure/helpers/convertTypeAnnotationsToValues.js.map +1 -0
- package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js +37 -20
- package/packages/ai/src/lib/dataStructure/helpers/deduplicateFunctionSchemas.js.map +1 -1
- package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js +237 -73
- package/packages/ai/src/lib/dataStructure/helpers/fillInSchemaGapsAndUnknowns.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarioData.js +195 -1
- package/packages/ai/src/lib/generateEntityScenarioData.js.map +1 -1
- package/packages/ai/src/lib/generateEntityScenarios.js +7 -1
- package/packages/ai/src/lib/generateEntityScenarios.js.map +1 -1
- package/packages/ai/src/lib/generateExecutionFlows.js +10 -2
- package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -1
- package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js +209 -3
- package/packages/ai/src/lib/generateExecutionFlowsFromConditionals.js.map +1 -1
- package/packages/ai/src/lib/mergeStatements.js +70 -51
- package/packages/ai/src/lib/mergeStatements.js.map +1 -1
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js +10 -4
- package/packages/ai/src/lib/promptGenerators/gatherAttributesMap.js.map +1 -1
- package/packages/ai/src/lib/resolvePathToControllable.js +24 -14
- package/packages/ai/src/lib/resolvePathToControllable.js.map +1 -1
- package/packages/ai/src/lib/worker/SerializableDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/FileAnalyzer.js +60 -36
- package/packages/analyze/src/lib/FileAnalyzer.js.map +1 -1
- package/packages/analyze/src/lib/ProjectAnalyzer.js +96 -26
- package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js +14 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getAllDeclaredEntityNodes.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js +14 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getAllEntityNodes.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js +6 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getAllExports.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js +6 -0
- package/packages/analyze/src/lib/asts/sourceFiles/getImportsAnalysis.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js +39 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getResolvedModule.js.map +1 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js +2 -1
- package/packages/analyze/src/lib/asts/sourceFiles/getSourceFilesForAllImports.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js +13 -5
- package/packages/analyze/src/lib/files/analyze/analyzeEntities/prepareDataStructures.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js +14 -4
- package/packages/analyze/src/lib/files/analyze/analyzeEntities.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js +2 -1
- package/packages/analyze/src/lib/files/analyze/gatherEntityMap.js.map +1 -1
- package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js +0 -3
- package/packages/analyze/src/lib/files/analyze/validateDependencyAnalyses.js.map +1 -1
- package/packages/analyze/src/lib/files/analyzeRemixRoute.js +3 -2
- package/packages/analyze/src/lib/files/analyzeRemixRoute.js.map +1 -1
- package/packages/analyze/src/lib/files/getImportedExports.js +11 -7
- package/packages/analyze/src/lib/files/getImportedExports.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js +52 -10
- package/packages/analyze/src/lib/files/scenarios/enrichArrayTypesFromChildSignatures.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js +25 -8
- package/packages/analyze/src/lib/files/scenarios/gatherDataForMocks.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js +34 -4
- package/packages/analyze/src/lib/files/scenarios/generateDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +56 -8
- package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -1
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js +168 -9
- package/packages/analyze/src/lib/files/scenarios/mergeInDependentDataStructure.js.map +1 -1
- package/packages/analyze/src/lib/files/setImportedExports.js +2 -1
- package/packages/analyze/src/lib/files/setImportedExports.js.map +1 -1
- package/packages/analyze/src/lib/utils/getFileByPath.js +12 -0
- package/packages/analyze/src/lib/utils/getFileByPath.js.map +1 -0
- package/codeyam-cli/src/webserver/build/client/assets/globals-D3yhhV8x.css +0 -1
- package/codeyam-cli/src/webserver/build/client/assets/memory-yxFcrxBX.js +0 -92
- package/codeyam-cli/src/webserver/build/server/assets/server-build-4Cr0uToj.js +0 -257
|
@@ -1,257 +0,0 @@
|
|
|
1
|
-
var Rs=Object.defineProperty;var ya=e=>{throw TypeError(e)};var Ds=(e,r,n)=>r in e?Rs(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n;var ar=(e,r,n)=>Ds(e,typeof r!="symbol"?r+"":r,n),Ls=(e,r,n)=>r.has(e)||ya("Cannot "+n);var xa=(e,r,n)=>(Ls(e,r,"read from private field"),n?n.call(e):r.get(e)),ba=(e,r,n)=>r.has(e)?ya("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,n);import{jsx as t,jsxs as l,Fragment as le}from"react/jsx-runtime";import{PassThrough as Fs}from"node:stream";import{createReadableStreamFromReadable as Os}from"@react-router/node";import{ServerRouter as zs,useFetcher as Ae,useLocation as Er,useNavigate as Mt,Link as oe,UNSAFE_withComponentProps as Oe,Meta as Ys,Links as Bs,ScrollRestoration as Us,Scripts as Ws,useLoaderData as We,useRevalidator as rt,Outlet as Hs,data as G,useSearchParams as Jt,useParams as ao,useActionData as qs}from"react-router";import{isbot as Gs}from"isbot";import{renderToPipeableStream as Js}from"react-dom/server";import{useState as M,useEffect as re,useCallback as se,createContext as bn,useContext as Ar,useRef as Ee,useMemo as ne}from"react";import{Settings as wa,CheckCircle2 as wn,Bug as oo,AlertTriangle as cn,Check as so,Copy as vn,Loader2 as Ze,HomeIcon as Vs,GitCommitIcon as va,File as Qs,RefreshCw as Ks,BookOpen as Zs,SettingsIcon as Xs,PanelsTopLeftIcon as ei,ComponentIcon as ti,FileText as Ca,Code as Na,Box as ri,List as ni,BarChart3 as ai,Tag as oi,Image as Ut,Code2 as io,Activity as qr,ChevronDown as Wt,CircleEqual as si,Pause as ii,ListTodo as li,PauseCircle as ci,FileCode as lo,GripVertical as di,Ban as ui,CheckCircle as hi,Search as Cn,FolderOpen as mi,CodeXml as pi,Zap as fi,Plus as Sa,FolderTree as gi,Filter as yi,X as co,Terminal as uo,Pencil as ho,ArrowLeft as xi,ChevronRight as Nn,Trash2 as bi,Folder as mo,ChevronsUpDown as po,ChevronsDownUp as fo}from"lucide-react";import"fetch-retry";import wi from"better-sqlite3";import{Pool as vi}from"pg";import*as K from"fs";import Nt,{existsSync as Ci}from"fs";import*as ee from"path";import he from"path";import{OperationNodeTransformer as Ni,Kysely as go,ParseJSONResultsPlugin as Si,SqliteDialect as Ei,PostgresDialect as Ai,sql as Qe}from"kysely";import*as ki from"kysely/helpers/sqlite";import*as Pi from"kysely/helpers/postgres";import _e from"typescript";import*as Ie from"fs/promises";import xe,{writeFile as _i,readFile as Mi}from"fs/promises";import*as Ti from"os";import dn from"os";import Ii from"prompts";import mr from"chalk";import*as $i from"crypto";import Sn,{randomUUID as Vt}from"crypto";import{execSync as Me,spawn as kr,exec as En}from"child_process";import{fileURLToPath as An}from"url";import{promisify as kn}from"util";import ji from"dotenv";import Ri,{EventEmitter as Di}from"events";import{v4 as Li}from"uuid";import Fi from"openai";import Oi from"p-queue";import Ea from"p-retry";import{DynamoDBClient as Pr,PutItemCommand as zi}from"@aws-sdk/client-dynamodb";import{LRUCache as Pn}from"lru-cache";import"pluralize";import"piscina";import Yi from"json5";import{marshall as Bi}from"@aws-sdk/util-dynamodb";import Ui from"v8";import{Prism as Wi}from"react-syntax-highlighter";import{vscDarkPlus as Hi}from"react-syntax-highlighter/dist/cjs/styles/prism/index.js";import{randomUUID as qi}from"node:crypto";import{minimatch as yo}from"minimatch";import xo from"react-markdown";import bo from"remark-gfm";import Gi from"react-diff-viewer-continued";const wo=5e3;function Ji(e,r,n,a,o){return e.method.toUpperCase()==="HEAD"?new Response(null,{status:r,headers:n}):new Promise((s,i)=>{let c=!1,d=e.headers.get("user-agent"),m=d&&Gs(d)||a.isSpaMode?"onAllReady":"onShellReady",u=setTimeout(()=>h(),wo+1e3);const{pipe:p,abort:h}=Js(t(zs,{context:a,url:e.url}),{[m](){c=!0;const f=new Fs({final(g){clearTimeout(u),u=void 0,g()}}),y=Os(f);n.set("Content-Type","text/html"),p(f),s(new Response(y,{headers:n,status:r}))},onShellError(f){i(f)},onError(f){r=500,c&&console.error(f)}})})}const Vi=Object.freeze(Object.defineProperty({__proto__:null,default:Ji,streamTimeout:wo},Symbol.toStringTag,{value:"Module"}));function Qi({id:e,selected:r,onClick:n,icon:a,name:o}){const[s,i]=M(!1);re(()=>{i(!0)},[]);const c=se(()=>{n==null||n(e)},[n,e]);return l("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
|
-
${r?"text-[#CBF3FA]":"text-[#568B94] hover:text-[#CBF3FA]"}
|
|
5
|
-
`,onClick:c,children:[t("div",{className:`${r?"bg-[#CBF3FA] text-[#022A35]":""} w-9 h-9 rounded-lg flex items-center justify-center transition-colors`,children:s&&a}),t("span",{className:`text-[10px] font-normal text-center leading-tight ${r?"text-[#CBF3FA]":""}`,style:r?{color:"#CBF3FA !important"}:void 0,children:o})]})}const vo="/assets/cy-logo-cli-CCKUIm0S.svg";function Ki(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 Zi({content:e,className:r=""}){const[n,a]=M(!1),o=se(()=>{navigator.clipboard.writeText(e).then(()=>{a(!0),setTimeout(()=>a(!1),2e3)}).catch(s=>{console.error("Failed to copy:",s)})},[e]);return t("button",{onClick:o,className:`cursor-pointer flex items-center gap-1 ${r}`,disabled:n,"aria-label":n?"Copied to clipboard":"Copy to clipboard",children:n?l(le,{children:[t(so,{size:14}),"Copied"]}):l(le,{children:[t(vn,{size:14}),"Copy"]})})}function Co({isOpen:e,onClose:r,context:n,defaultEmail:a="",screenshotDataUrl:o}){const[s,i]=M(""),[c,d]=M(a),[m,u]=M(!1),[p,h]=M(!1),[f,y]=M(null),[g,w]=M(null),x=Ae(),b=x.state!=="idle",v=!!(n.scenarioId||n.analysisId),C=n.analysisId||n.scenarioId||"",E=()=>{const $=`/codeyam:diagnose ${C}`;return s.trim()?`${$} ${s.trim()}`:$};if(x.data&&!p&&!g){const $=x.data;$.success&&$.reportId?(h(!0),y($.reportId)):$.error&&w($.error)}const N=async()=>{w(null);const $=new FormData;if($.append("issueType","other"),$.append("description",s),$.append("email",c),$.append("source",n.source),$.append("entitySha",n.entitySha||""),$.append("scenarioId",n.scenarioId||""),$.append("analysisId",n.analysisId||""),$.append("currentUrl",n.currentUrl),$.append("entityName",n.entityName||""),$.append("entityType",n.entityType||""),$.append("scenarioName",n.scenarioName||""),$.append("errorMessage",n.errorMessage||""),o)try{const I=await(await fetch(o)).blob();$.append("screenshot",I,"screenshot.jpg")}catch(D){console.error("Failed to convert screenshot:",D)}x.submit($,{method:"post",action:"/api/generate-report",encType:"multipart/form-data"})},A=()=>{i(""),u(!1),h(!1),y(null),w(null),r()},_=$=>{$.key==="Escape"&&A()};return e?t("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",onKeyDown:_,children:l("div",{className:"bg-white rounded-lg max-w-lg w-full p-6 shadow-xl max-h-[90vh] overflow-y-auto",children:[l("div",{className:"flex items-center justify-between mb-6",children:[l("div",{className:"flex items-center gap-3",children:[b?t("div",{className:"animate-spin",children:t(wa,{size:24,style:{strokeWidth:1.5}})}):p?t(wn,{size:24,style:{color:"#10B981",strokeWidth:1.5}}):t(oo,{size:24,style:{color:"#005C75",strokeWidth:1.5}}),t("h2",{className:"text-xl font-semibold text-gray-900",children:p?"Report Submitted":"Report Issue"})]}),t("button",{onClick:A,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:t("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),p?l("div",{children:[l("div",{className:"mb-6 p-4 bg-green-50 rounded-lg border border-green-200",children:[t("p",{className:"text-sm text-green-800 font-medium mb-1",children:"Thank you for your feedback!"}),l("p",{className:"text-xs text-green-700",children:["Report ID:"," ",t("code",{className:"bg-green-100 px-1 rounded",children:f})]})]}),t("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."}),t("div",{className:"flex justify-end",children:t("button",{onClick:A,className:"px-4 py-2 bg-[#005c75] text-white text-sm font-medium rounded-md hover:bg-[#004a5c] transition-colors cursor-pointer",children:"Done"})})]}):l("div",{children:[l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[l("div",{className:"flex items-center justify-between",children:[t("div",{className:"text-sm font-medium text-gray-900",title:`${n.source}${n.entitySha?` • Entity: ${n.entitySha}`:""}${n.scenarioId?` • Scenario: ${n.scenarioId}`:""}${n.analysisId?` • Analysis: ${n.analysisId}`:""}`,children:Ki(n)}),t("button",{type:"button",onClick:()=>u(!m),className:"text-xs text-gray-500 hover:text-gray-700 underline cursor-pointer",children:m?"Hide":"Details"})]}),m&&l("div",{className:"mt-2 pt-2 border-t border-gray-200 text-xs text-gray-600 space-y-1 break-all",children:[l("div",{children:[t("span",{className:"text-gray-400",children:"Source:"})," ",n.source]}),l("div",{children:[t("span",{className:"text-gray-400",children:"URL:"})," ",n.currentUrl]}),n.entitySha&&l("div",{children:[t("span",{className:"text-gray-400",children:"Entity:"})," ",t("code",{className:"bg-gray-100 px-1 rounded",children:n.entitySha})]}),n.scenarioId&&l("div",{children:[t("span",{className:"text-gray-400",children:"Scenario:"})," ",t("code",{className:"bg-gray-100 px-1 rounded",children:n.scenarioId})]}),n.analysisId&&l("div",{children:[t("span",{className:"text-gray-400",children:"Analysis:"})," ",t("code",{className:"bg-gray-100 px-1 rounded",children:n.analysisId})]})]})]}),o&&l("div",{className:"mb-4 p-3 bg-gray-50 rounded-lg border border-gray-200",children:[t("div",{className:"text-xs text-gray-500 mb-2",children:"Screenshot (will be included in report)"}),t("img",{src:o,alt:"Page screenshot",className:"w-full max-h-[150px] object-contain rounded border border-gray-300"})]}),l("div",{className:"mb-4",children:[t("label",{htmlFor:"description",className:"block text-sm font-medium text-gray-700 mb-2",children:"What happened?"}),t("textarea",{id:"description",value:s,onChange:$=>i($.target.value),placeholder:"Optional: Describe what you expected vs what happened...",rows:3,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75] resize-none"})]}),v&&l(le,{children:[l("div",{className:"mb-4 p-4 bg-purple-50 rounded-lg border border-purple-200",children:[l("div",{className:"flex items-center gap-2 mb-2",children:[t("span",{className:"text-lg",children:"🔧"}),t("h3",{className:"text-sm font-semibold text-purple-900",children:"Diagnose & Fix (Recommended)"})]}),t("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."}),l("div",{className:"relative",children:[t("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:E()}),t(Zi,{content:E(),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"})]})]}),l("div",{className:"relative my-5",children:[t("div",{className:"absolute inset-0 flex items-center",children:t("div",{className:"w-full border-t border-gray-300"})}),t("div",{className:"relative flex justify-center",children:t("span",{className:"bg-white px-3 text-xs text-gray-500 uppercase",children:"or"})})]})]}),l("div",{className:v?"opacity-75":"",children:[v&&l("div",{className:"flex items-center gap-2 mb-3",children:[t("span",{className:"text-lg",children:"📤"}),t("h3",{className:"text-sm font-semibold text-gray-700",children:"Quick Report"}),t("span",{className:"text-xs text-gray-500",children:"(won't investigate locally)"})]}),l("div",{className:"mb-4",children:[t("label",{htmlFor:"email",className:"block text-sm font-medium text-gray-700 mb-2",children:"Your email"}),t("input",{id:"email",type:"email",value:c,onChange:$=>d($.target.value),placeholder:"you@example.com",className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-[#005c75] focus:border-[#005c75]"})]}),l("div",{className:"mb-4 p-3 bg-amber-50 rounded-lg border border-amber-200 flex gap-2",children:[t(cn,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#D97706"}}),l("div",{className:"text-xs text-amber-800",children:[t("p",{className:"font-medium mb-1",children:"Source code will be uploaded"}),t("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&&t("div",{className:"mb-4 text-center",children:t("p",{className:"text-sm text-gray-600",children:x.formData?"Uploading report...":"Creating archive..."})}),g&&l("div",{className:"mb-4 p-3 bg-red-50 rounded-lg border border-red-200 flex gap-2",children:[t(cn,{size:16,className:"flex-shrink-0 mt-0.5",style:{color:"#DC2626"}}),l("div",{className:"text-xs text-red-800",children:[t("p",{className:"font-medium mb-1",children:"Upload failed"}),t("p",{children:g})]})]}),l("div",{className:"flex gap-3 justify-end",children:[t("button",{onClick:A,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"}),t("button",{onClick:()=>void N(),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?l(le,{children:[t("div",{className:"animate-spin",children:t(wa,{size:16,style:{strokeWidth:1.5}})}),"Submitting..."]}):g?"Try Again":"Submit Report"})]})]})]})]})}):null}const Aa={source:"navbar"},_n=bn(void 0);function Xi({children:e}){const[r,n]=M(Aa),a=se(s=>{n(s)},[]),o=se(()=>{n(Aa)},[]);return t(_n.Provider,{value:{contextData:r,setContextData:a,resetContextData:o},children:e})}function mt(e){const r=Ar(_n),n=Ee(r);re(()=>{if(n.current)return n.current.setContextData(e),()=>{var a;(a=n.current)==null||a.resetContextData()}},[e.source,e.entitySha,e.scenarioId,e.analysisId,e.entityName,e.entityType,e.scenarioName,e.errorMessage])}function el(){const e=Ar(_n),r=Er();return e?{source:e.contextData.source,entitySha:e.contextData.entitySha,scenarioId:e.contextData.scenarioId,analysisId:e.contextData.analysisId,currentUrl:r.pathname,entityName:e.contextData.entityName,entityType:e.contextData.entityType,scenarioName:e.contextData.scenarioName,errorMessage:e.contextData.errorMessage}:{source:"navbar",currentUrl:r.pathname}}function tl(){var b;const e=Er(),r=Mt(),[n,a]=M(),[o,s]=M(!1),[i,c]=M(!1),[d,m]=M(null),u=Ae();re(()=>{u.state==="idle"&&!u.data&&u.load("/api/generate-report")},[u]);const p=((b=u.data)==null?void 0:b.defaultEmail)||"",h={width:"20px",height:"20px",strokeWidth:1.5},f=[{id:"dashboard",icon:t(Vs,{style:h}),link:"/",name:"Dashboard"},{id:"simulations",icon:l("svg",{width:"20",height:"20",viewBox:"0 0 18 18",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:h,children:[t("path",{d:"M9 12.75V15.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),t("path",{d:"M6 15.75H12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),t("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"}),t("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"}),t("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"},{id:"git",icon:t(va,{style:h}),link:"/git",name:"Git"},{id:"files",icon:t(Qs,{style:h}),link:"/files",name:"Files"},{id:"activity",icon:t(Ks,{style:h}),link:"/activity",name:"Activity"},{id:"memory",icon:t(Zs,{style:h}),link:"/memory",name:"Memory"},{id:"settings",icon:t(Xs,{style:h}),link:"/settings",name:"Settings"},{id:"commits",icon:t(va,{style:h}),link:"/commits",name:"Commits",hidden:!0},{id:"pages",icon:t(ei,{style:h}),link:"/pages",name:"Pages",hidden:!0},{id:"components",icon:t(ti,{style:h}),link:"/components",name:"Components",hidden:!0}],y=se(v=>{const C=f.find(E=>E.id===v);C!=null&&C.link&&r(C.link),a(E=>E===v?void 0:v)},[f,r]);re(()=>{const v={dashboard:["/","/home"],git:["git"],commits:["commits"],simulations:["simulations"],activity:["activity"],memory:["memory"],files:["files"],settings:["settings"],pages:["pages"],components:["components"]};for(const[C,E]of Object.entries(v))if(E.some(N=>N==="/"?e.pathname==="/":e.pathname.includes(N))){a(C);return}a(void 0)},[e]);const g=async()=>{c(!0);try{const{default:v}=await import("html2canvas-pro"),E=(await v(document.body)).toDataURL("image/jpeg",.8);m(E),s(!0)}catch(v){console.error("Screenshot capture failed:",v),s(!0)}finally{c(!1)}},w=()=>{s(!1),m(null)},x=el();return l(le,{children:[l("div",{id:"sidebar",className:"relative w-full h-screen bg-[#051C22] flex flex-col justify-between py-3",children:[l("div",{className:"w-full flex flex-col items-center",children:[t("div",{className:"py-3 mt-2 mb-4",children:t(oe,{to:"/",className:"flex items-center justify-center cursor-pointer",children:t("img",{src:vo,alt:"CodeYam",className:"h-6"})})}),f.filter(v=>!v.hidden).map(v=>t(Qi,{id:v.id,selected:v.id===n,onClick:y,icon:v.icon,name:v.name},`sidebar-button-${v.id}`))]}),t("div",{className:"w-full flex flex-col items-center pb-2",children:l("button",{onClick:()=>void g(),disabled:i,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:[t("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center",children:i?t(Ze,{style:{width:"20px",height:"20px",strokeWidth:1.5},className:"animate-spin"}):t(oo,{style:{width:"20px",height:"20px",strokeWidth:1.5}})}),t("span",{className:"text-[9px] font-normal text-center leading-tight whitespace-pre-line",children:i?"Capturing...":`Report
|
|
6
|
-
Bug`})]})})]}),o&&t(Co,{isOpen:!0,onClose:w,context:x,defaultEmail:p,screenshotDataUrl:d??void 0})]})}const No=bn(void 0);function rl({children:e}){const[r,n]=M([]),a=se((s,i="info",c=5e3)=>{const m={id:`toast-${Date.now()}-${Math.random()}`,message:s,type:i,duration:c};n(u=>[...u,m])},[]),o=se(s=>{n(i=>i.filter(c=>c.id!==s))},[]);return t(No.Provider,{value:{toasts:r,showToast:a,closeToast:o},children:e})}function Mn(){const e=Ar(No);if(!e)throw new Error("useToast must be used within a ToastProvider");return e}function nl({toast:e,onClose:r}){re(()=>{const o=e.duration||5e3;if(o>0){const s=setTimeout(()=>{r(e.id)},o);return()=>clearTimeout(s)}},[e.id,e.duration,r]);const n={success:"✅",error:"❌",info:"ℹ️",warning:"⚠️"};return l("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:[t("span",{className:"text-2xl",children:n[e.type]}),t("p",{className:"flex-1 text-sm font-medium m-0",children:e.message}),t("button",{onClick:()=>r(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 al({toasts:e,onClose:r}){return e.length===0?null:l("div",{className:"fixed top-4 right-4 z-10000 flex flex-col gap-2",children:[t("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(n=>t(nl,{toast:n,onClose:r},n.id))]})}function pt(e,r){const[n,a]=M(""),[o,s]=M(!1),[i,c]=M(null),[d,m]=M(!1);re(()=>{r&&(m(!1),s(!1),c(null))},[r]),re(()=>{if(!e||!r){r||a("");return}const p=async()=>{try{const f=await fetch(`/api/logs/${e}`);if(f.ok){const g=(await f.text()).trim().split(`
|
|
18
|
-
`).filter(b=>b.length>0);if(g.length<3){s(!1),m(!1),c(null),a("");return}const w=g.filter(b=>b.includes("CodeYam Log Level 1"));if(w.length>0){const b=w[w.length-1];a(b.replace(/.*CodeYam Log Level 1: /,""))}const x=g.find(b=>b.includes("$$INTERACTIVE_SERVER_URL$$:"));if(x){const b=x.split("$$INTERACTIVE_SERVER_URL$$:")[1].trim();c(b),m(!0)}g.some(b=>b.includes("CodeYam: Exiting start.js"))&&s(!0)}}catch{}};p().catch(()=>{});const h=setInterval(()=>{p().catch(()=>{})},2e3);return()=>clearInterval(h)},[e,r]);const u=se(()=>{a(""),s(!1),c(null),m(!1)},[]);return{lastLine:n,interactiveUrl:i,isCompleted:o,resetLogs:u}}function dt({projectSlug:e,onClose:r}){const[n,a]=M("Loading logs..."),[o,s]=M(!0),[i,c]=M(!0),[d,m]=M("all"),u=Ee(null);return re(()=>{const p=async()=>{try{const h=await fetch(`/api/logs/${e}`);if(h.ok){const f=await h.text();if(d==="all")a(f);else{const y=f.trim().split(`
|
|
19
|
-
`).filter(g=>{if(g.length===0)return!1;const w=g.match(/^.*CodeYam Log Level (\d+):/);return!!w&&Number(w[1])<=d});a(y.map(g=>g.replace(/^.*CodeYam Log Level \d+:\s*/,"")).join(`
|
|
20
|
-
`))}i&&u.current&&setTimeout(()=>{var y;(y=u.current)==null||y.scrollTo({top:u.current.scrollHeight,behavior:"smooth"})},100)}else a(`Error: ${h.status} - ${await h.text()}`)}catch(h){a(`Error fetching logs: ${h.message}`)}};if(p().catch(()=>{}),o){const h=setInterval(()=>{p().catch(()=>{})},2e3);return()=>clearInterval(h)}},[e,o,i,d]),re(()=>{const p=h=>{h.key==="Escape"&&r()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r]),t("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-9999 p-5",onClick:r,children:l("div",{className:"bg-[#1e1e1e] rounded-lg shadow-2xl flex flex-col max-w-[1200px] w-full max-h-[90vh] overflow-hidden",onClick:p=>p.stopPropagation(),children:[l("div",{className:"flex justify-between items-center px-5 py-4 border-b border-[#333] bg-[#252525]",children:[l("h3",{className:"m-0 text-lg font-semibold text-white",children:["Analysis Logs - ",e]}),l("div",{className:"flex items-center gap-4",children:[l("label",{className:"flex items-center gap-2 text-sm text-[#ccc] select-none",children:[t("span",{children:"Log Level:"}),l("select",{value:d,onChange:p=>m(p.target.value==="all"?"all":Number(p.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:[t("option",{value:"1",children:"1"}),t("option",{value:"2",children:"2"}),t("option",{value:"3",children:"3"}),t("option",{value:"4",children:"4"}),t("option",{value:"all",children:"All"})]})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[t("input",{type:"checkbox",checked:o,onChange:p=>s(p.target.checked),className:"cursor-pointer"}),t("span",{className:"group-hover:text-white",children:"Auto-refresh"})]}),l("label",{className:"flex items-center gap-1.5 text-sm text-[#ccc] cursor-pointer select-none group",children:[t("input",{type:"checkbox",checked:i,onChange:p=>c(p.target.checked),className:"cursor-pointer"}),t("span",{className:"group-hover:text-white",children:"Auto-scroll"})]}),t("button",{onClick:r,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:"✕"})]})]}),t("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:n})]})})}function Ue({type:e,size:r="default"}){const n={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"}},a=n[e]||n.other,o=r==="large"?18:14,s=r==="large"?32:18,i=()=>{switch(e){case"library":return t(io,{size:o,color:a.iconColor});case"visual":return t(Ut,{size:o,color:a.iconColor});case"type":return t(oi,{size:o,color:a.iconColor});case"data":return t(ai,{size:o,color:a.iconColor});case"index":return t(ni,{size:o,color:a.iconColor});case"functionCall":return t(Na,{size:o,color:a.iconColor});case"class":return t(ri,{size:o,color:a.iconColor});case"method":return t(Na,{size:o,color:a.iconColor});case"other":return t(Ca,{size:o,color:a.iconColor});default:return t(Ca,{size:o,color:a.iconColor})}};return t("span",{className:`flex items-center justify-center rounded ${a.bgColor}`,style:{width:`${s}px`,height:`${s}px`},children:i()})}function So({filePath:e,maxLength:r=60,className:n,style:a}){const s=((c,d)=>{if(c.length<=d)return c;const m="...",u=d-m.length,p=Math.ceil(u*.4),h=Math.floor(u*.6),f=c.slice(0,p),y=c.slice(-h),g=f.lastIndexOf("/"),w=y.indexOf("/"),x=g>p*.5?f.slice(0,g+1):f,b=w!==-1&&w<h*.5?y.slice(w):y;return`${x}${m}${b}`})(e,r),i=s!==e;return t("span",{className:n||"font-normal text-gray-900 text-[14px] select-text cursor-text",style:{...a,display:"inline-block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i?e:void 0,children:s})}function Gr({entity:e,nameSize:r="11px",pathSize:n="10px",pathMaxLength:a=50,showScenarioCount:o=!1,scenarioCount:s=0,additionalContent:i}){return l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"flex items-center gap-1",children:[t(Ue,{type:e.entityType||"other"}),l(oe,{to:`/entity/${e.sha}`,className:"hover:underline shrink-0 cursor-pointer",style:{fontSize:r,fontWeight:500,color:"#000",whiteSpace:"nowrap"},children:[e.name,o&&s>0&&` (${s})`]}),t(So,{filePath:e.filePath,maxLength:a,style:{fontSize:n,color:"#8E8E8E"}})]}),i]})}const Jr={fontSize:"9px",color:"#005C75",fontStyle:"italic"};function ol({currentRun:e,projectSlug:r,currentEntities:n=[],isAnalysisStarting:a=!1,queuedJobCount:o=0,queueJobs:s=[],currentlyExecuting:i=null,historicalRuns:c=[]}){var L,z,O;const[d,m]=M(!1),[u,p]=M(!1),[h,f]=M(null),[y,g]=M(new Set),[w,x]=M(new Set),[b,v]=M(!1),C=!!i||s.length>0,E=!!i,N=(i==null?void 0:i.entities)||n,A=!!(e!=null&&e.analysisCompletedAt),_=(e==null?void 0:e.readyToBeCaptured)??0,$=(e==null?void 0:e.capturesCompleted)??0;e!=null&&e.captureCompletedAt||A&&(_===0||$>=_);const D=(e==null?void 0:e.currentEntityShas)&&e.currentEntityShas.length>0,I=C,{lastLine:k}=pt(r,I),T=E||s.length>0,j=new Set(((L=i==null?void 0:i.entities)==null?void 0:L.map(F=>F.sha))||[]),P=c.filter(F=>!(F.currentEntityShas||[]).some(S=>j.has(S))),B=(()=>{const R=Date.now()-1440*60*1e3;if(e!=null&&e.createdAt&&D){const S=e.analysisCompletedAt||e.createdAt;if(new Date(S).getTime()>R)return!0}if(P.length>0){const S=P[0],H=S.analysisCompletedAt||S.archivedAt||S.createdAt;if(H&&new Date(H).getTime()>R)return!0}return!1})();return re(()=>{const F=(i==null?void 0:i.id)||null;C&&!u&&F!==h&&p(!0),!C&&h!==null&&f(null)},[C,i==null?void 0:i.id,u,h]),l(le,{children:[l("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&&l("div",{onClick:()=>{p(!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:[T?t(Ze,{size:16,className:"animate-spin",style:{color:"#005C75"}}):t("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:t(qr,{size:16,style:{color:"#005C75"}})}),t("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:T?"Analyzing...":"Activity: No Activity Yet"}),T&&t("button",{onClick:F=>{F.stopPropagation(),m(!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&&l("div",{children:[l("div",{className:"flex items-center justify-between px-3 py-2",children:[l("div",{className:"flex items-center gap-2",children:[T?t(Ze,{size:16,className:"animate-spin",style:{color:"#005C75"}}):t("div",{className:"flex items-center justify-center rounded",style:{backgroundColor:"#E0E9EC",width:"20px",height:"20px"},children:t(qr,{size:16,style:{color:"#005C75"}})}),t("span",{style:{fontSize:"12px",fontWeight:500,color:"#343434"},children:T?"Analyzing...":"Activity"})]}),l("div",{className:"flex items-center gap-2",children:[t("button",{onClick:()=>m(!0),className:"px-2 py-1 rounded transition-colors cursor-pointer",style:{backgroundColor:"#E0E9EC",color:"#005C75",fontSize:"10px",fontWeight:600},children:"View Logs"}),t("button",{onClick:()=>{p(!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:t(Wt,{size:16,style:{color:"#646464"}})})]})]}),t("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),l("div",{className:"px-3 pt-2 pb-3 space-y-3",children:[T&&i&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[t(qr,{size:12,style:{color:"#005C75"}}),t("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Current Activity"})]}),t("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:N.length>0?l("div",{className:"space-y-1.5",children:[(b?N:N.slice(0,3)).map(F=>t(Gr,{entity:F,nameSize:"11px",pathSize:"10px",pathMaxLength:150},F.sha)),N.length>3&&t("button",{onClick:()=>v(F=>!F),className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Jr,"aria-label":b?"Show fewer entities":`Show ${N.length-3} more entities`,children:b?"Show less":`+${N.length-3} more`}),k&&t("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:k})]}):l("div",{children:[i.entityNames&&i.entityNames.length>0?l("div",{className:"space-y-0.5",children:[i.entityNames.slice(0,5).map((F,R)=>t("div",{style:{fontSize:"11px",color:"#343434"},children:F},R)),i.entityNames.length>5&&l("div",{className:"italic",style:{fontSize:"10px",color:"#666"},children:["+",i.entityNames.length-5," ","more"]})]}):l("div",{style:{fontSize:"11px",color:"#343434"},children:["Analyzing"," ",((z=i.entityShas)==null?void 0:z.length)||0," ",((O=i.entityShas)==null?void 0:O.length)===1?"entity":"entities","..."]}),k&&t("div",{style:{fontSize:"10px",color:"#005C75",marginTop:"4px"},children:k})]})})]}),s.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[t(si,{size:12,style:{color:"#005C75"}}),t("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Queued Activity"})]}),t("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:s.map(F=>{var H,q;const R=y.has(F.id),S=R?F.entities:F.entities.slice(0,3);return t("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:F.entities.length>0?l("div",{className:"space-y-1.5",children:[S.map(J=>t(Gr,{entity:J,nameSize:"10px",pathSize:"9px",pathMaxLength:120},J.sha)),F.entities.length>3&&t("button",{onClick:()=>{g(J=>{const ae=new Set(J);return ae.has(F.id)?ae.delete(F.id):ae.add(F.id),ae})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Jr,"aria-label":R?"Show fewer entities":`Show ${F.entities.length-3} more entities`,children:R?"Show less":`+${F.entities.length-3} more`})]}):l("div",{style:{fontSize:"10px",color:"#343434"},children:[F.type==="analysis"&&t(le,{children:F.entityNames&&F.entityNames.length>0?l("div",{className:"space-y-0.5",children:[F.entityNames.slice(0,5).map((J,ae)=>t("div",{children:J},ae)),F.entityNames.length>5&&l("div",{className:"italic",children:["+",F.entityNames.length-5," more"]})]}):`Analyzing ${((H=F.entityShas)==null?void 0:H.length)||0} ${((q=F.entityShas)==null?void 0:q.length)===1?"entity":"entities"}`}),F.type==="recapture"&&"Recapturing scenario",F.type==="debug-setup"&&"Setting up debug environment"]})},F.id)})})]}),B&&P.length>0&&l("div",{children:[l("div",{className:"flex items-center gap-1.5 mb-2",children:[t(wn,{size:12,style:{color:"#005C75"}}),t("h4",{style:{fontSize:"11px",fontWeight:600,color:"#343434"},children:"Recently Completed"})]}),t("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:P.slice(0,3).map((F,R)=>{const S=F.entities||[],H=F.analysisCompletedAt||F.archivedAt||F.createdAt||"",q=(()=>{if(!H)return"";const Y=Date.now()-new Date(H).getTime(),U=Math.floor(Y/6e4),Q=Math.floor(Y/36e5);return Q>0?`${Q}h ago`:U>0?`${U}m ago`:"just now"})(),J=w.has(R),V=(J?S:S.slice(0,3)).map(Y=>{var U,Q,W;return{...Y,scenarioCount:((W=(Q=(U=Y.analyses)==null?void 0:U[0])==null?void 0:Q.scenarios)==null?void 0:W.length)||0}});return t("div",{className:"rounded p-2",style:{backgroundColor:"#f5f5f5"},children:S.length>0&&l("div",{className:"space-y-1.5",children:[V.map((Y,U)=>l("div",{className:"flex items-start justify-between gap-2",children:[t("div",{className:"flex-1 min-w-0",children:t(Gr,{entity:Y,nameSize:"10px",pathSize:"9px",pathMaxLength:100,showScenarioCount:!0,scenarioCount:Y.scenarioCount})}),U===0&&q&&t("div",{style:{fontSize:"9px",color:"#8E8E8E",whiteSpace:"nowrap",paddingTop:"2px"},children:q})]},Y.sha)),S.length>3&&t("button",{onClick:()=>{x(Y=>{const U=new Set(Y);return U.has(R)?U.delete(R):U.add(R),U})},className:"cursor-pointer bg-transparent border-none p-0 hover:underline",style:Jr,"aria-label":J?"Show fewer entities":`Show ${S.length-3} more entities`,children:J?"Show less":`+${S.length-3} more`})]})},R)})})]})]}),t("div",{style:{height:"1px",backgroundColor:"#E0E9EC",margin:"0 12px"}}),t("div",{className:"px-3 pb-2",children:t(oe,{to:"/activity",className:"text-xs font-medium hover:underline cursor-pointer",style:{color:"#005C75"},children:"View All Activity →"})})]})]}),d&&r&&t(dt,{projectSlug:r,onClose:()=>m(!1)})]})}function He(e){return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,n===null?void 0:n]))}function Qt(e){const{file_id:r,project_id:n,commit_id:a,file_path:o,entity_type:s,entity_branches:i,analyses:c,commit:d,created_at:m,updated_at:u,...p}=e,h=(i??[]).map(g=>g.branch_id),f=c?c.map(nt):void 0,y=d?St(d):void 0;return He({...p,fileId:r,projectId:n,commitId:a,filePath:o,entityType:s,commit:y,analyses:f,branchIds:h,createdAt:m,updatedAt:u})}function Tn(e){return He({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 In(e){const{branches:r,files:n,analyzed_at:a,content_changed_at:o,created_at:s,updated_at:i,github_token:c,configuration:d,team_id:m,...u}=e;return He({...u,branches:r?r.map(Pt):void 0,files:n?n.map(Tn):void 0,analyzedAt:a,contentChangedAt:o,createdAt:s,updatedAt:i})}function sl(e){const{id:r,project_id:n,user_id:a,scenario_id:o,thumbs_up:s,user:i}=e,c=i?{username:i.github_username,avatarUrl:i.github_user.avatar_url}:void 0;return He({id:r,projectId:n,userId:a,scenarioId:o,thumbsUp:!!s,user:c})}function il(e){const{id:r,project_id:n,user_id:a,scenario_id:o,text:s,created_at:i,updated_at:c,user:d}=e,m=d?{username:d.github_username,avatarUrl:d.github_user.avatar_url}:void 0;return He({id:r,projectId:n,userId:a,scenarioId:o,text:s,createdAt:i,updatedAt:c,user:m})}function Eo(e){const{project_id:r,analysis_id:n,previous_version_id:a,analysis:o,user_scenarios:s,scenario_comments:i,approved:c,...d}=e,m=o?nt(o):void 0,u=s?s.map(sl):void 0,p=i?i.map(il):void 0;return He({...d,projectId:r,analysisId:n,previousVersionId:a,analysis:m,userScenarios:u,comments:p})}function ll(e){return He({id:e.id,analysisId:e.analysis_id,entitySha:e.entity_sha,branchId:e.branch_id,active:!!e.active,analysis:e.analysis?nt(e.analysis):void 0,entity:e.entity?Qt(e.entity):void 0,branch:e.branch?Pt(e.branch):void 0,createdAt:e.created_at})}function nt(e){const{project_id:r,commit_id:n,file_id:a,file_path:o,entity_sha:s,entity_type:i,entity_name:c,previous_analysis_id:d,file:m,entity:u,commit:p,project:h,scenarios:f,analysis_branches:y,dependency_analyzed_tree_sha:g,analyzed_tree_sha:w,branch_commit_sha:x,committed_at:b,completed_at:v,created_at:C,updated_at:E,indirect:N,...A}=e,_=u?Qt(u):void 0,$=m?Tn(m):void 0,D=h?In(h):void 0,I=p?St(p):void 0,k=f?f.map(Eo):void 0,T=y?y.map(ll):void 0,j=T?T.map(P=>P.branch):void 0;return He({...A,projectId:r,commitId:n,fileId:a,filePath:o,entitySha:s,entityType:i,entityName:c,previousAnalysisId:d,entity:_,file:$,commit:I,project:D,scenarios:k,analysisBranches:T,branches:j,dependencyAnalyzedTreeSha:g,analyzedTreeSha:w,branchCommitSha:x,committedAt:b,completedAt:v,createdAt:C,updatedAt:E,indirect:!!N})}function $n(e){return He({id:e.id,commitId:e.commit_id,branchId:e.branch_id,active:!!e.active,commit:e.commit?St(e.commit):void 0,branch:e.branch?Pt(e.branch):void 0})}function cl(e){const{project_id:r,commit_id:n,created_at:a,updated_at:o,success:s,...i}=e;return He({...i,projectId:r,commitId:n,createdAt:a,updatedAt:o,success:!!s})}function St(e){const{project_id:r,branch_id:n,branch:a,background_jobs:o,merged_branch_id:s,mergedBranch:i,ai_message:c,html_url:d,author:m,analyses:u,entities:p,commit_branches:h,committed_at:f,analyzed_at:y,...g}=e,w=a?Pt(a):void 0,x=i?Pt(i):void 0,b=(o==null?void 0:o.length)>0?cl(o[o.length-1]):void 0,v=(u??[]).map(nt),C=(p??[]).map(Qt),E=(h==null?void 0:h.length)>0?h.map($n):void 0;return m&&(m.username=m.preferredUsername??m.username),He({...g,projectId:r,branchId:n,branch:w,backgroundJob:b,mergedBranchId:s,mergedBranch:x,aiMessage:c,htmlUrl:d,author:m,analyses:v,entities:C,commitBranches:E,committedAt:f,analyzedAt:y})}function Pt(e){const{project_id:r,content_changed_at:n,commits:a,analysis_branches:o,active_at:s,created_at:i,updated_at:c,primary:d,...m}=e,u=a?a.map(St):void 0,p=o?o.flatMap(h=>nt(h.analysis)):void 0;return He({...m,projectId:r,contentChangedAt:n,commits:u,analyses:p,activeAt:s,createdAt:i,updatedAt:c,primary:!!d})}var Sr;class dl{constructor(){ba(this,Sr,new ul)}transformQuery(r){return xa(this,Sr).transformNode(r.node)}transformResult(r){return Promise.resolve(r.result)}}Sr=new WeakMap;class ul extends Ni{transformValue(r){return{...super.transformValue(r),value:typeof r.value=="boolean"?r.value?1:0:r.value}}transformPrimitiveValueList(r){return{...r,values:r.values.map(n=>typeof n=="boolean"?n?1:0:n)}}}const X=()=>null,hl={analyzed_at:X(),configuration:X(),content_changed_at:X(),created_at:X(),description:X(),github_token:X(),id:X(),metadata:X(),name:X(),path:X(),slug:X(),team_id:X(),updated_at:X()},ml=Object.keys(hl),pl={active:X(),analysis_id:X(),branch_id:X(),created_at:X(),entity_sha:X(),id:X()},fl=Object.keys(pl),gl={active_at:X(),content_changed_at:X(),created_at:X(),id:X(),metadata:X(),name:X(),primary:X(),project_id:X(),ref:X(),sha:X(),updated_at:X()},Ao=Object.keys(gl),yl={ai_message:X(),analyzed_at:X(),author_github_username:X(),branch_id:X(),committed_at:X(),created_at:X(),files:X(),html_url:X(),id:X(),merged_branch_id:X(),message:X(),metadata:X(),project_id:X(),sha:X(),title:X(),url:X()},ko=Object.keys(yl);ko.filter(e=>e!=="files");const xl={commit_id:X(),created_at:X(),description:X(),documentation:X(),entity_type:X(),file_id:X(),file_path:X(),metadata:X(),name:X(),project_id:X(),quality:X(),sha:X(),updated_at:X()},Po=Object.keys(xl),bl={active:X(),branch_id:X(),entity_sha:X()},wl=Object.keys(bl),vl={created_at:X(),deleted:X(),id:X(),metadata:X(),name:X(),path:X(),project_id:X(),updated_at:X()},Cl=Object.keys(vl),Nl={analysis_id:X(),approved:X(),created_at:X(),description:X(),id:X(),metadata:X(),name:X(),previous_version_id:X(),project_id:X()},pr=Object.keys(Nl),Sl=!!Et("ENABLE_QUERY_LOGGING"),El=!!Et("ENABLE_QUERY_ERROR_LOGGING");Et("USE_LOCAL_POSTGRESQL_FOR_TESTING");let or;function ve(){if(!or){const e=Mo();if(e==="sqlite")or=Al();else if(e==="postgresql")or=kl();else throw new Error(`Unknown database type: ${e}`)}return or}function Al(e){if(e||(e=Et("SQLITE_PATH")),e===":memory:"||e==="memory")throw new Error("In-memory SQLite not supported in getDatabase(). Use getDatabaseForTesting() instead.");const r=K.existsSync(e),n=ee.dirname(e);if(!K.existsSync(n))K.mkdirSync(n,{recursive:!0,mode:493});else try{K.chmodSync(n,493)}catch(o){console.warn(`Warning: Could not set permissions on database directory: ${o.message}`)}const a=new wi(e,{readonly:!1,fileMustExist:!1});if(a.pragma("journal_mode = WAL"),a.pragma("synchronous = FULL"),!process.env.CLAUDE_CODE_MODE)try{const o=a.prepare("SELECT COUNT(*) as count FROM sqlite_master WHERE type='table' AND name='projects'").get();r&&o.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(o){console.error("CodeYam DB ERROR: Failed to verify database schema:",o)}return new go({dialect:new Ei({database:a}),plugins:[new Si,new dl],log:_o})}function kl(){const e=_l();console.log(`CodeYam: Using PostgreSQL database at: ${e}`);const r=new vi({connectionString:e,max:3,idleTimeoutMillis:1e4});return r.on("error",(n,a)=>{console.error("CodeYam: Unexpected error on idle PostgreSQL client",n)}),new go({dialect:new Ai({pool:r}),log:_o})}let Vr=null;function At(){return Vr||(Vr=Pl(Mo())),Vr}function _o(e){e.level==="error"?El&&console.error("Query failed : ",{durationMs:e.queryDurationMillis,error:e.error,sql:e.query.sql,params:e.query.parameters}):Sl&&console.log("Query executed : ",{durationMs:e.queryDurationMillis,sql:e.query.sql,params:e.query.parameters})}function Pl(e){if(e==="sqlite")return ki;if(e==="postgresql")return Pi;throw new Error(`Unknown database type: ${e}`)}function Mo(){if(Et("SQLITE_PATH"))return"sqlite";if(Et("POSTGRESQL_URL"))return"postgresql";throw new Error("No database configuration found. Set SQLITE_PATH for SQLite or POSTGRESQL_URL for PostgreSQL")}function _l(){const e=Et("POSTGRESQL_URL");if(!e)throw new Error("No PostgreSQL connection string found. Set POSTGRESQL_URL environment variable.");return e}function Et(e){var r;return typeof window<"u"?(r=window.env)==null?void 0:r[e]:process.env[e]}var Kt=(e=>(e.Remix="Remix",e.CodeYam="CodeYam",e.CRA="CRA",e.Next="Next",e.NextPages="NextPages",e.Unknown="Unknown",e))(Kt||{});const _r="Default Scenario";let Ml="<main>";function Tl(){return Ml}function ka(e,...r){fe(`CodeYam Log Level ${e}: ${r[0]}`,...r.slice(1))}function fe(...e){const r=Tl(),n=e.map(o=>{if(o)return typeof o=="string"?o:o instanceof Error?`${o.name}: ${o.message}
|
|
21
|
-
${o.stack}`:typeof o=="object"?Il(o):String(o)}).filter(Boolean).join(`
|
|
22
|
-
`),a=`${r} ${n}`;if(!process.env.CODEYAM_ECS_TASK_ARN){console.log(a+`
|
|
23
|
-
`);return}console.log(a.replace(/\n/g,"\r"))}function Il(e,r=2){function n(a,o=new WeakMap){return a===null||typeof a!="object"?a:o.has(a)?`"[Circular: ${a.constructor.name}]"`:(o.set(a,!0),Array.isArray(a)?`[${a.map(c=>{const d=n(c,o);return typeof c=="string"?`"${d}"`:d}).join(",")}]`:`{${Object.entries(a).map(([i,c])=>{let d;return typeof c>"u"?null:(typeof c=="function"?d=`"(function: ${c.name||"anonymous"})"`:c instanceof Date?d=`"${c.toISOString()}"`:typeof c=="object"&&c!==null?d=n(c,o):typeof c=="string"?d=`"${c.replace(/"/g,'\\"')}"`:d=JSON.stringify(c),`"${i.replace(/"/g,'\\"')}":${d}`)}).filter(Boolean).join(",")}}`)}try{return JSON.stringify(e,null,r)}catch(a){const o=n(e);if(!r)return o;try{return JSON.stringify(JSON.parse(n(e)),null,r)}catch(s){return console.log("CodeYam Error: error stringifying object to provide proper spacing",{error:s,pureStringifyError:a,serialized:o}),o}}}function fr(e,r){try{let n=function(s){var i,c;if(_e.isFunctionDeclaration(s)&&Ft(s)){const d=((i=s.name)==null?void 0:i.text)||"default",m=s.getText(a),u=Qr(s);o.push({name:d,code:m,sha:xt(r,d,m),entityType:"function",isDefault:u})}else if(_e.isClassDeclaration(s)&&Ft(s)){const d=((c=s.name)==null?void 0:c.text)||"default",m=s.getText(a),u=Qr(s),p=m.includes("React.")||m.includes("jsx")||m.includes("tsx");o.push({name:d,code:m,sha:xt(r,d,m),entityType:p?"component":"class",isDefault:u})}else if(_e.isInterfaceDeclaration(s)&&Ft(s)){const d=s.name.text,m=s.getText(a);o.push({name:d,code:m,sha:xt(r,d,m),entityType:"interface",isDefault:!1})}else if(_e.isTypeAliasDeclaration(s)&&Ft(s)){const d=s.name.text,m=s.getText(a);o.push({name:d,code:m,sha:xt(r,d,m),entityType:"type",isDefault:!1})}else if(_e.isVariableStatement(s)&&Ft(s)){const d=Qr(s);s.declarationList.declarations.forEach(m=>{var u;if(_e.isIdentifier(m.name)){const p=m.name.text,h=s.getText(a),f=((u=m.initializer)==null?void 0:u.getText(a))||"",y=(r.endsWith(".tsx")||r.endsWith(".jsx"))&&f.includes("=>")&&(f.includes("<")||f.includes("React."));o.push({name:p,code:h,sha:xt(r,p,h),entityType:y?"component":"variable",isDefault:d})}})}else if(_e.isExportAssignment(s)){const d=s.getText(a);o.push({name:"default",code:d,sha:xt(r,"default",d),entityType:"unknown",isDefault:!0})}else if(_e.isExportDeclaration(s)&&s.exportClause&&_e.isNamedExports(s.exportClause)){const d=s.getText(a);for(const m of s.exportClause.elements){const u=m.name.text;o.push({name:u,code:d,sha:xt(r,u,d),entityType:"unknown",isDefault:!1})}}_e.forEachChild(s,n)};const a=_e.createSourceFile(r,e,_e.ScriptTarget.Latest,!0),o=[];return n(a),o}catch(n){return console.error(`Failed to extract entities from ${r}:`,n),[]}}function Ft(e){if(!_e.canHaveModifiers(e))return!1;const r=_e.getModifiers(e);return r?r.some(n=>n.kind===_e.SyntaxKind.ExportKeyword):!1}function Qr(e){if(!_e.canHaveModifiers(e))return!1;const r=_e.getModifiers(e);return r?r.some(n=>n.kind===_e.SyntaxKind.DefaultKeyword):!1}function xt(e,r,n){const a=Sn.createHash("sha256");return a.update(`${e}:${r}:${n}`),a.digest("hex").substring(0,40)}function $l(e){var m;const{webapp:r,port:n,environmentVariables:a,packageManager:o}=e,s=r==null?void 0:r.startCommand;if(!s)return`${o} ${o==="npm"?"run ":""}dev`;const i=((m=s.args)==null?void 0:m.map(u=>u.replace(/\$PORT/g,String(n))))??[],c=[];for(const u of a)if(u.key&&u.value!==void 0){const p=String(u.value).replace(/'/g,"'\\''");c.push(`${u.key}='${p}'`)}if(s.env)for(const[u,p]of Object.entries(s.env)){const f=String(p).replace(/\$PORT/g,String(n)).replace(/'/g,"'\\''");c.push(`${u}='${f}'`)}const d=c.length>0?c.join(" ")+" ":"";return s.command==="sh"&&i[0]==="-c"&&i[1]?`${d}sh -c "${i[1]}"`:`${d}${s.command} ${i.join(" ")}`}function jl(e,r){if(!r||r.length===0)return;if(r.length===1)return r[0];const n=ee.normalize(e),a=[...r].sort((o,s)=>{var i,c;return(((i=s.path)==null?void 0:i.length)??0)-(((c=o.path)==null?void 0:c.length)??0)});for(const o of a){const s=ee.normalize(o.path??".");if(s==="."||n.startsWith(s+ee.sep)||n===s)return o}return r[0]}function Rl(e){const{filePath:r,webapps:n,environmentVariables:a,port:o,packageManager:s}=e;if(!n||n.length===0)throw new Error("No webapps configured. Please run CodeYam init again.");const i=jl(r,n);if(!i)throw new Error("Could not find webapp for file path: "+r);const c=$l({webapp:i,port:o,environmentVariables:a,packageManager:s});return{webapp:i,webappPath:i.path??".",framework:i.framework,packageManager:i.packageManager??s,startCommand:c,url:`http://localhost:${o}/static/codeyam-sample`}}function Mr(e,r,n=[]){const a=Array.isArray(r)?r:[r];return o=>o.columns(a).doUpdateSet(s=>{const i=Object.keys(e).filter(c=>c!==r&&!n.includes(c));return Object.fromEntries(i.map(c=>[c,s.ref(`excluded.${c}`)]))})}function Dl(e){const{jsonObjectFrom:r}=At();return r(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 Ll({ids:e,analysisId:r}){const n=ve();try{let a=n.deleteFrom("scenarios");if(e){if(e.length===0)return;a=a.where("id","in",e)}else if(r)a=a.where("analysis_id","=",r);else throw fe("CodeYam Error: No deletion criteria provided",null,{ids:e,analysisId:r}),new Error("No deletion criteria provided for scenarios");await a.execute()}catch(a){throw fe("CodeYam Error: Database error deleting scenarios",a,{ids:e,analysisId:r}),a}}function Fl(...e){try{const r=Sn.createHash("sha256");for(const n of e)r.update(n);return r.digest("hex")}catch(r){throw console.log("CodeYam Error: Error generating sha",e),r}}function Kr(e,r){return r.map(n=>Ol(e,n))}function Ol(e,r){return Qe` ${Qe.ref(e)}.${Qe.ref(r)}`.as(r)}function zl(e,r,n){return r.map(a=>Yl(e,a,n))}function Yl(e,r,n){return Qe` ${Qe.ref(e)}.${Qe.ref(r)}`.as(`_cy_${n}:${r}`)}function Bl(e,...r){const n={};for(const[a,o]of Object.entries(e)){const s=a.match(/^_cy_(.+?):(.+)$/);if(s){const[,i,c]=s;if(r.includes(i)){n[i]||(n[i]={}),n[i][c]=o;continue}console.warn(`CodeYam Warning: Unrecognized prefix in key '${a}'`);continue}n[a]=o}return n}const Ul=50;function Wl(e,r){return e.length<=r?[e]:Array.from({length:Math.ceil(e.length/r)},(n,a)=>e.slice(a*r,a*r+r))}function Pa({projectId:e,ids:r,fileIds:n,entityName:a,entityShas:o,commitIds:s,branchCommitSha:i,limit:c,excludeMetadata:d}){const m=ve(),{jsonObjectFrom:u,jsonArrayFrom:p}=At();let h=d?m.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"]):m.selectFrom("analyses").selectAll("analyses");if(e&&(h=h.where("project_id","=",e)),r){if(r.length===0)return null;h=h.where("id","in",r)}if(n){if(n.length===0)return null;h=h.where("file_id","in",n)}if(s){if(s.length===0)return null;h=h.where("commit_id","in",s)}return a&&(h=h.where("entity_name","=",a)),o&&(h=h.where("entity_sha","in",o)),i&&(h=h.where("branch_commit_sha","=",i)),c&&(h=h.limit(c)),d?m.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[p(f.selectFrom("scenarios").select(Kr("scenarios",pr)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),p(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")]):m.with("filtered_analyses",()=>h).selectFrom("filtered_analyses").selectAll("filtered_analyses").select(f=>[u(f.selectFrom("entities").select(Kr("entities",Po)).whereRef("entities.sha","=","filtered_analyses.entity_sha").limit(1)).as("entity"),p(f.selectFrom("scenarios").select(Kr("scenarios",pr)).whereRef("scenarios.analysis_id","=","filtered_analyses.id")).as("scenarios"),p(f.selectFrom("analysis_branches").select(["id","branch_id"]).whereRef("analysis_branches.analysis_id","=","filtered_analyses.id")).as("analysis_branches")])}async function ut(e){const{ids:r,fileIds:n,entityShas:a,commitIds:o}=e;try{const i=Object.entries({id:{arr:r,key:"ids"},file_id:{arr:n,key:"fileIds"},entity_sha:{arr:a,key:"entityShas"},commit_id:{arr:o,key:"commitIds"}}).find(([d,{arr:m}])=>(m==null?void 0:m.length)>0);let c=[];if(i){const[d,{arr:m,key:u}]=i,p=Wl(m,Ul),h=[];for(let f=0;f<p.length;f++){const y=p[f],w=await Pa({...e,[u]:y}).execute();w&&h.push(...w)}c=h}else{const m=await Pa(e).execute();if(!m||m.length===0)return fe("CodeYam: No analyses found",null,e),null;c=m}return c.length===0?null:c.map(nt)}catch(s){return fe("CodeYam Error: Database error in loadAnalyses",s,e),null}}function Hl(e,r){const{jsonArrayFrom:n,jsonObjectFrom:a}=At();let o=e.selectFrom("analysis_branches").select(fl).select(s=>a(s.selectFrom("branches").select(Ao).whereRef("id","=","analysis_branches.branch_id")).as("branch"));return r&&(o=r(o)),n(o)}async function at({id:e,analysisBranchId:r,projectId:n,fileId:a,commitId:o,entityName:s,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:p,includeBranches:h}){const f=ve(),y=Date.now();try{let g=f.selectFrom("analyses").selectAll("analyses");e&&(g=g.where("id","=",e)),n&&(g=g.where("project_id","=",n)),i?g=g.where("dependency_analyzed_tree_sha","=",i):c?g=g.where("analyzed_tree_sha","=",c):a&&(g=g.where("file_id","=",a)),s&&(g=g.where("entity_name","=",s)),o?g=g.where("commit_id","=",o):g=g.orderBy("created_at","desc").limit(1),r&&(g=g.innerJoin("analysis_branches","analyses.id","analysis_branches.analysis_id").where("analysis_branches.id","=",r));const{jsonObjectFrom:w,jsonArrayFrom:x}=At();g=g.select(C=>{const E=[];return E.push(w(C.selectFrom("entities").select(Po).whereRef("entities.sha","=","analyses.entity_sha")).as("entity")),d&&E.push(w(C.selectFrom("files").select(Cl).whereRef("files.id","=","analyses.file_id")).as("file")),m&&E.push(w(C.selectFrom("projects").select(ml).whereRef("projects.id","=","analyses.project_id")).as("project")),p&&E.push(x(C.selectFrom("scenarios").select(pr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")),h&&E.push(Hl(C,N=>N.whereRef("analysis_branches.analysis_id","=","analyses.id")).as("analysis_branches")),u&&E.push(w(C.selectFrom("commits").select(ko).select(N=>Dl(N).as("author")).whereRef("commits.id","=","analyses.commit_id")).as("commit")),E});const b=await g.executeTakeFirst(),v=Date.now()-y;if(!b)return fe("CodeYam Error: Analysis not found",null,{id:e,analysisBranchId:r,projectId:n,fileId:a,commitId:o,entityName:s,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:p,includeBranches:h}),null;if(v>100&&u){const C=b.commit,E=C!=null&&C.files?JSON.stringify(C.files).length:0;console.log(`CodeYam DEBUG: [CommitFilesTiming] loadAnalysis took ${v}ms (files: ${Math.round(E/1024)}KB)`,{id:b.id,entityName:b.entity_name})}return nt(b)}catch(g){return fe("CodeYam Error: Database error loading analysis",g,{id:e,analysisBranchId:r,projectId:n,fileId:a,commitId:o,entityName:s,dependencyAnalyzedTreeSha:i,analyzedTreeSha:c,includeFile:d,includeProject:m,includeCommitAndBranch:u,includeScenarios:p,includeBranches:h}),null}}async function To({projectId:e,ids:r,names:n,includeInactive:a}){const o=ve();try{let s=o.selectFrom("branches").selectAll("branches").where("project_id","=",e);if(r){if(r.length===0)return[];s=s.where("id","in",r)}if(n){if(n.length===0)return[];s=s.where("name","in",n)}return a||(s=s.where("active_at","is not",null)),(await s.execute()).map(Pt)}catch(s){return fe("CodeYam Error: Database error loading branches",s,{projectId:e,ids:r,names:n,includeInactive:a}),[]}}async function ql({projectId:e,commitId:r,branchId:n,active:a,includeBranches:o}){const s=ve();try{let i=s.selectFrom("commit_branches").selectAll("commit_branches").innerJoin("branches","commit_branches.branch_id","branches.id").$if(o,m=>m.select(zl("branches",Ao,"branch"))).where("branches.project_id","=",e);r&&(i=i.where("commit_branches.commit_id","=",r)),n&&(i=i.where("commit_branches.branch_id","=",n)),a!==void 0&&(i=i.where("commit_branches.active","=",a));const c=await i.execute();return!c||c.length===0?null:c.map(m=>Bl(m,"branch")).map($n)}catch(i){return fe("CodeYam Error: Error loading commit branches",i,{projectId:e,commitId:r,branchId:n,active:a,includeBranches:o}),null}}async function Gl(e){if(e.length===0)return new Map;const r=ve();try{const n=await r.selectFrom("commits").select(["id","branch_id","merged_branch_id"]).where("id","in",e).execute(),a=new Set;if(n.forEach(s=>{s.branch_id&&a.add(s.branch_id),s.merged_branch_id&&a.add(s.merged_branch_id)}),a.size===0)return new Map;const o=await r.selectFrom("branches").selectAll().where("id","in",Array.from(a)).execute();return new Map(o.map(s=>[s.id,s]))}catch(n){return fe("CodeYam Error: Loading branches for commits",n,{commitIds:e}),new Map}}async function Jl(e){if(e.length===0)return new Map;const r=ve(),{jsonObjectFrom:n,jsonArrayFrom:a}=At();try{const o=await r.selectFrom("analyses").selectAll("analyses").select(i=>[n(i.selectFrom("files").select(["id","name","path"]).whereRef("files.id","=","analyses.file_id")).as("file"),a(i.selectFrom("scenarios").select(pr).whereRef("scenarios.analysis_id","=","analyses.id")).as("scenarios")]).where("commit_id","in",e).execute(),s=new Map;return o.forEach(i=>{const c=s.get(i.commit_id)||[];c.push(i),s.set(i.commit_id,c)}),s}catch(o){return fe("CodeYam Error: Loading analyses for commits",o,{commitIds:e}),new Map}}async function Vl(e){if(e.length===0)return new Map;const r=ve();try{const n=await r.selectFrom("entities").selectAll().where("commit_id","in",e).execute(),a=new Map;return n.forEach(o=>{const s=a.get(o.commit_id)||[];s.push(o),a.set(o.commit_id,s)}),a}catch(n){return fe("CodeYam Error: Loading entities for commits",n,{commitIds:e}),new Map}}async function gr({projectId:e,branchId:r,ids:n,shas:a,fileNames:o,limit:s=10,skipRelations:i=!1}){if(!e&&!n)throw new Error("Must provide projectId or ids");const c=ve(),{jsonObjectFrom:d}=At(),m=Date.now();try{let u=c.selectFrom("commits").selectAll("commits").select(b=>[d(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)),n){if(n.length===0)return[];u=u.where("id","in",n)}if(a){if(a.length===0)return[];u=u.where("sha","in",a)}if(o&&o.length>0){const b=Qe.join(o.map(v=>Qe`${v}`),Qe`, `);u=u.where(Qe`
|
|
24
|
-
EXISTS (
|
|
25
|
-
SELECT 1
|
|
26
|
-
FROM json_each(${Qe.ref("commits.files")}) AS f
|
|
27
|
-
WHERE json_extract(f.value, '$.fileName') IN (${b})
|
|
28
|
-
)
|
|
29
|
-
`)}r&&(u=u.where("branch_id","=",r));const p=await u.orderBy("committed_at","desc").limit(s).execute(),h=Date.now()-m;if(!p||p.length===0)return[];if(h>100){const b=p.reduce((v,C)=>v+(C.files?JSON.stringify(C.files).length:0),0);console.log(`CodeYam DEBUG: [CommitFilesTiming] loadCommits took ${h}ms (${p.length} commits, totalFiles: ${Math.round(b/1024)}KB)`)}if(i)return p.map(v=>({...v,branch:void 0,mergedBranch:void 0,analyses:[],entities:[]})).map(St);const f=p.map(b=>b.id),[y,g,w]=await Promise.all([Gl(f),Jl(f),Vl(f)]);return p.map(b=>{const v=b.branch_id?y.get(b.branch_id):void 0,C=b.merged_branch_id?y.get(b.merged_branch_id):void 0,E=g.get(b.id)||[],N=w.get(b.id)||[];return{...b,branch:v,mergedBranch:C,analyses:E,entities:N}}).map(St)}catch(u){return fe("CodeYam Error: Database error loading commits",u,{projectId:e,branchId:r,ids:n,shas:a,limit:s}),[]}}async function ht({projectId:e,branchId:r,fileIds:n,filePaths:a,names:o,shas:s,excludeMetadata:i}){if(n&&n.length==0||a&&a.length==0||o&&o.length==0||s&&s.length==0)return[];if(s&&s.length>50){const d=[];for(let m=0;m<s.length;m+=50){const u=s.slice(m,m+50),p=await ht({projectId:e,branchId:r,fileIds:n,filePaths:a,names:o,shas:u,excludeMetadata:i});p&&d.push(...p)}return d}const c=ve();try{const u=await(i?c.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"]):c.selectFrom("entities").selectAll("entities")).$if(!!r,p=>p.innerJoin("entity_branches","entity_branches.entity_sha","entities.sha").where("entity_branches.branch_id","=",r)).$if(!!e,p=>p.where("entities.project_id","=",e)).$if(!!s,p=>p.where("entities.sha","in",s)).$if(!!a,p=>p.where("entities.file_path","in",a)).$if(!!o,p=>p.where("entities.name","in",o)).$if(!!n,p=>p.where("entities.file_id","in",n)).execute();return!u||u.length===0?(console.log("Load Entities: No entities found",{projectId:e,fileIds:n,filePaths:a,shas:s}),null):u.map(Qt)}catch(d){return console.log("Load Entities: Error occurred",d,{projectId:e,fileIds:n,filePaths:a,shas:s}),null}}function Ql(e,r){const{jsonArrayFrom:n}=At();let a=e.selectFrom("entity_branches").select(wl);return r&&(a=r(a)),n(a)}async function Io({projectId:e,sha:r}){const n=ve();try{const a=await n.selectFrom("entities").innerJoin("files","entities.file_id","files.id").selectAll("entities").select(o=>Ql(o,s=>s.whereRef("entity_branches.entity_sha","=","entities.sha")).as("entity_branches")).where("files.project_id","=",e).where("entities.sha","=",r).executeTakeFirst();return a?Qt(a):(process.env.CODEYAM_E2E_BASELINE_MODE!=="true"&&fe("CodeYam Error: Load Entity: Entity not found",null,{projectId:e,sha:r}),null)}catch(a){return fe("CodeYam Error: Load Entity: Database error",a,{projectId:e,sha:r}),null}}const Zr=1e3;async function $o({projectId:e,filePaths:r,fileIds:n,fileNames:a}){if(r&&r.length>50){const c=[];for(let d=0;d<r.length;d+=50){const m=r.slice(d,d+50),u=await $o({projectId:e,filePaths:m,fileIds:n,fileNames:a});u&&c.push(...u)}return c}const o=ve(),s=[];let i=0;try{for(;;){let c=o.selectFrom("files").selectAll().where("project_id","=",e).limit(Zr).offset(i);if(r){if(r.length===0)return[];c=c.where("path","in",r)}if(n){if(n.length===0)return[];c=c.where("id","in",n)}if(a){if(a.length===0)return[];c=c.where("name","in",a)}const d=await c.execute();if(!d||d.length===0||(s.push(...d),d.length<Zr))break;i+=Zr}return s==null?void 0:s.map(Tn)}catch(c){return console.log("CodeYam Error: Error loading project files in loadFiles",c),null}}async function Kl({id:e,slug:r,withBranches:n,withFiles:a,silent:o}){try{let i=ve().selectFrom("projects").selectAll();if(e)i=i.where("id","=",e);else if(r)i=i.where("slug","=",r);else throw new Error("Either id or slug must be provided");const c=await i.executeTakeFirst();if(!c)return o||console.log("CodeYam Error: Error loading project",{id:e,slug:r,withBranches:n,withFiles:a}),null;const d=In(c);return a&&(d.files=await $o({projectId:d.id})),n&&(d.branches=await To({projectId:d.id,includeInactive:!1})),d}catch(s){return o||console.log("CodeYam Error: Error loading project",s),null}}function yr(e,r){const n={...e};for(const a in r){const o=r[a],s=e[a];o!=null&&typeof o=="object"&&!Array.isArray(o)&&s!==void 0&&s!==null&&typeof s=="object"&&!Array.isArray(s)?n[a]=yr(s,o):o!==void 0&&(n[a]=o)}return n}async function ct({commitId:e,commitSha:r,metadataUpdate:n,runStatusUpdate:a,archiveCurrentRun:o,updateCallback:s}){try{return await ve().transaction().execute(async i=>{var u,p;const c=await i.selectFrom("commits").select(["id","metadata"]).$if(!!e,h=>h.where("id","=",e)).$if(!!r,h=>h.where("sha","=",r)).executeTakeFirst();if(!c)return fe(`CodeYam Error: updateCommitMetadata(): Commit ${e} not found`),null;const d=c.metadata||{};if(a)a.lastUpdatedAt??(a.lastUpdatedAt=new Date().toISOString()),a.currentEntityShas!==void 0&&(console.log("[updateCommitMetadata] Updating currentRun.currentEntityShas"),console.log(`[updateCommitMetadata] Commit SHA: ${r}`),console.log("[updateCommitMetadata] Previous entity SHAs:",(u=d.currentRun)==null?void 0:u.currentEntityShas),console.log("[updateCommitMetadata] New entity SHAs:",a.currentEntityShas),console.log("[updateCommitMetadata] Archive flag:",o)),n=yr(n??{},{currentRun:a});else if(!n&&!s)return d;const m=n?yr(d,n):d;if(o&&m.currentRun){console.log("[updateCommitMetadata] ========================================"),console.log("[updateCommitMetadata] ARCHIVING CURRENT RUN"),console.log(`[updateCommitMetadata] Commit SHA: ${r}`),console.log("[updateCommitMetadata] Current run entity SHAs:",m.currentRun.currentEntityShas),console.log(`[updateCommitMetadata] Current run PIDs: analyzer=${m.currentRun.analyzerPid}, capture=${m.currentRun.capturePid}`),console.log(`[updateCommitMetadata] Current run completed: analyses=${m.currentRun.analysesCompleted}, captures=${m.currentRun.capturesCompleted}`),console.log(`[updateCommitMetadata] Historical runs before archiving: ${((p=m.historicalRuns)==null?void 0:p.length)||0}`);const h={...m.currentRun,archivedAt:new Date().toISOString()};console.log("[updateCommitMetadata] Run to archive:",JSON.stringify(h,null,2)),m.historicalRuns=[...m.historicalRuns||[],h],console.log(`[updateCommitMetadata] Historical runs after archiving: ${m.historicalRuns.length}`),console.log("[updateCommitMetadata] All historical runs:",JSON.stringify(m.historicalRuns.map(f=>({entityShas:f.currentEntityShas,archivedAt:f.archivedAt,completed:{analyses:f.analysesCompleted,captures:f.capturesCompleted}})),null,2)),console.log("[updateCommitMetadata] ========================================")}s&&await s(m);try{return await i.updateTable("commits").set({metadata:JSON.stringify(m)}).where("id","=",c.id).returning(["id"]).executeTakeFirst()?m:(fe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`),d)}catch(h){return fe(`CodeYam Error: updateCommitMetadata(): Failed to update commit ${e}`,h),d}})}catch(i){return fe(`CodeYam Error: updateCommitMetadata(): Transaction failed for commit ${e}`,i),null}}async function jo(e,r,n="analysis"){try{return await ve().transaction().execute(async a=>{const o=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!o)return fe(`CodeYam Error: updateFreshAnalysisMetadata(): Analysis ${e} not found (source: ${n})`,null,{analysisId:e,source:n}),null;const s=nt(o);return r(s.metadata,s),await a.updateTable("analyses").set({metadata:JSON.stringify(s.metadata)}).where("id","=",e).returningAll().executeTakeFirst()?s.metadata:(fe(`CodeYam Error: updateFreshAnalysisMetadata(): Failed to update analysis ${e} (source: ${n})`,null,{analysisId:e,source:n}),null)})}catch(a){return fe(`CodeYam Error: updateFreshAnalysisMetadata(): Transaction failed for analysis ${e} (source: ${n})`,a,{analysisId:e,source:n}),null}}async function Tt(e,r,n="capture"){try{return await ve().transaction().execute(async a=>{const o=await a.selectFrom("analyses").selectAll().where("id","=",e).executeTakeFirst();if(!o)return fe(`CodeYam Error: updateFreshAnalysisStatus(): Analysis ${e} not found (source: ${n})`,null,{analysisId:e,source:n}),null;const s=nt(o);return r(s.status,s),await a.updateTable("analyses").set({status:JSON.stringify(s.status)}).where("id","=",e).returningAll().executeTakeFirst()?s.status:(fe(`CodeYam Error: updateFreshAnalysisStatus(): Failed to update analysis ${e} (source: ${n})`,null,{analysisId:e,source:n}),null)})}catch(a){return fe(`CodeYam Error: updateFreshAnalysisStatus(): Transaction failed for analysis ${e} (source: ${n})`,a,{analysisId:e,source:n}),null}}async function Zl({projectId:e,projectSlug:r,metadataUpdate:n,updateCallback:a}){if(!e&&!r)throw new Error("Either projectId or projectSlug must be provided");try{return await ve().transaction().execute(async o=>{const s=await o.selectFrom("projects").selectAll().$if(!!e,d=>d.where("id","=",e)).$if(!!r,d=>d.where("slug","=",r)).executeTakeFirst();if(!s)return fe(`CodeYam Error: updateProjectMetadata(): Project ${e} not found`),null;const i=s.metadata||{};if(!n&&!a)return i;const c=n?yr(i,n):i;a&&await a(c,In(s));try{return await o.updateTable("projects").set({metadata:JSON.stringify(c)}).where("id","=",s.id).returningAll().executeTakeFirst()?c:(fe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`),null)}catch(d){return fe(`CodeYam Error: updateProjectMetadata(): Failed to update project ${e}`,d),null}})}catch(o){return fe(`CodeYam Error: updateProjectMetadata(): Transaction failed for project ${e}`,o),null}}function Xl(e){const{id:r,projectId:n,analysisId:a,previousVersionId:o,analysis:s,metadata:i,data:c,...d}=e;return delete d.userScenarios,delete d.comments,"created_at"in d&&delete d.created_at,{...d,id:r??Vt(),metadata:i?JSON.stringify(i):null,project_id:n,analysis_id:a,previous_version_id:o}}async function ec(e){if(e.length===0)return[];const r=ve(),n=e.map(Xl);try{return(await r.insertInto("scenarios").values(n).onConflict(Mr(n[0],"id",["created_at"])).returningAll().execute()).map(Eo)}catch(a){return fe("CodeYam Error: Database error upserting scenarios",a,{scenarioCount:e.length}),null}}function tc(e){const{id:r,commitId:n,branchId:a,...o}=e;return delete o.commit,delete o.branch,{...o,id:r??Vt(),commit_id:n,branch_id:a}}async function _a(e){if(e.length===0)return[];const r=ve(),n=e.map(tc);try{return(await r.insertInto("commit_branches").values(n).onConflict(Mr(n[0],"id",["created_at"])).returningAll().execute()).map($n)}catch(a){return fe("CodeYam Error: Database error upserting commit branches",a,{commitBranchCount:e.length,commitBranchIds:e.map(o=>o.id)}),[]}}async function rc(e,r){const n=ve(),a={username:e,avatar_url:r};try{return await n.insertInto("github_users").values(a).onConflict(Mr(a,"username",[])).returningAll().executeTakeFirst()||null}catch(o){return fe("CodeYam Error: Error upserting github user",o,{username:e,avatarUrl:r}),null}}function nc(e,r){const{id:n,projectId:a,branchId:o,mergedBranchId:s,aiMessage:i,htmlUrl:c,analyzedAt:d,committedAt:m,author:u,metadata:p,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:n??Vt(),project_id:a??String(r),metadata:p?JSON.stringify(p):void 0,files:h?JSON.stringify(h):void 0,branch_id:o,merged_branch_id:s,author_github_username:u==null?void 0:u.username,html_url:c,ai_message:i,analyzed_at:d,committed_at:m}}async function ac({projectId:e,commits:r}){const n=ve();try{const a=r.reduce((i,c)=>{const{author:d}=c;return d!=null&&d.username&&(d!=null&&d.avatarUrl)&&(i[d.username]=d.avatarUrl),i},{});for(const i in a)await rc(i,a[i]);const o=r.map(i=>nc(i,e));return(await n.insertInto("commits").values(o).onConflict(Mr(o[0],"id",["created_at"])).returningAll().execute()).map(St)}catch(a){return fe("CodeYam Error: Error saving commits",a,{projectId:e,commitCount:r.length,commitIds:r.map(o=>o.id).filter(Boolean)}),[]}}const xr=ee.join(Ti.homedir(),".codeyam","secrets.json"),br=ee.join(process.cwd(),".codeyam","secrets.json");async function ft(){let e={};try{if(K.existsSync(br)){const s=await Ie.readFile(br,"utf8");e=JSON.parse(s)}}catch{console.warn(mr.yellow("⚠ Could not read project secrets file, trying home directory"))}if(!e.OPENAI_API_KEY&&!e.ANTHROPIC_API_KEY)try{if(K.existsSync(xr)){const s=await Ie.readFile(xr,"utf8");e={...JSON.parse(s),...e}}}catch{console.warn(mr.yellow("⚠ Could not read home secrets file, falling back to environment variables"))}const r={},n=e.OPENAI_API_KEY||process.env.OPENAI_API_KEY;n&&(r.OPENAI_API_KEY=n);const a=e.ANTHROPIC_API_KEY||process.env.ANTHROPIC_API_KEY;a&&(r.ANTHROPIC_API_KEY=a);const o=e.GROQ_API_KEY||process.env.GROQ_API_KEY;return o&&(r.GROQ_API_KEY=o),r}async function oc(e,r=!0){const n=r?xr:br,a=ee.dirname(n);await Ie.mkdir(a,{recursive:!0}),await Ie.writeFile(n,JSON.stringify(e,null,2)),await Ie.chmod(n,384)}function sc(e=!0){return e?xr:br}async function Ma(){const e=await ft(),r=[];for(const n of r)e[n];return{isValid:!0,missing:[],secrets:e}}async function ic(e){console.log(),console.log(mr.blue("ℹ Configuration needed")),console.log();const r={};for(const n of e)switch(n){case"OPENAI_API_KEY":const a=await Ii({type:"password",name:"key",message:"OpenAI API Key",validate:o=>o&&!o.startsWith("sk-")?"OpenAI API key should start with sk-":!0});a.key&&(r.OPENAI_API_KEY=a.key);break}return r}async function lc(e=!0){const r=await Ma();if(r.isValid)return r.secrets;const n=await ic(r.missing),o={...await ft(),...n};await oc(o,e);const s=sc(e);return console.log(mr.green(`✓ Configuration saved to ${s}`)),(await Ma()).secrets}function Ro(e=process.cwd()){let r=ee.resolve(e);const n=ee.parse(r).root;for(;r!==n;){const o=ee.join(r,".codeyam","config.json");if(K.existsSync(o))return r;r=ee.dirname(r)}const a=ee.join(n,".codeyam","config.json");return K.existsSync(a)?n:null}let Do=Ro();function pe(){return Do}function cc(e){Do=e}function Lo(e){const r={...e};for(const n in e)if(n.includes(".")){const a=n.replace(/\./g,"");r[a]=e[n]}return r}const dc={"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>`};Lo(dc);const uc={"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>`};Lo(uc);function Ot(e,r,n=new WeakSet){if(!r)return e;if(!e)return r;try{if(typeof r=="object"&&r!==null){if(n.has(r))throw new Error("Circular reference detected during deep merge");n.add(r)}if(Array.isArray(r)){const o=Array.isArray(e)?e:[],s=[];for(let i=0;i<r.length;i++){const c=r[i];c&&typeof c=="object"&&!Array.isArray(c)||Array.isArray(c)?s[i]=Ot(o[i],c,n):s[i]=c}return s}const a={...e};for(const o in r)if(r[o]===null)a[o]=null;else if(Array.isArray(r[o])){const s=Array.isArray(e[o])?e[o]:[];a[o]=[];for(let i=0;i<r[o].length;i++){const c=r[o][i];typeof c=="object"&&c!==null?a[o][i]=Ot(s[i],c,n):a[o][i]=c}}else typeof r[o]=="object"&&r[o]!==null?a[o]=Ot(a[o]??{},r[o],n):a[o]=r[o];return a}catch(a){throw console.log("CodeYam: Error merging data",e,r),a}}async function hc({projectId:e,commit:r,branch:n}){var c,d,m,u,p,h,f;let a;const o={commitId:r.id,branchId:n.id,active:!0},s=await ql({projectId:e,commitId:r.id,includeBranches:!0});if(s&&s.length>0){a=(c=s.sort((g,w)=>{var x,b,v,C;return(((b=(x=g.branch.metadata)==null?void 0:x.permanent)==null?void 0:b.order)??999)-(((C=(v=w.branch.metadata)==null?void 0:v.permanent)==null?void 0:C.order)??999)})[0])==null?void 0:c.branch,a&&((m=(d=n.metadata)==null?void 0:d.permanent)==null?void 0:m.order)!==void 0&&(((p=(u=n.metadata)==null?void 0:u.permanent)==null?void 0:p.order)<=((f=(h=a.metadata)==null?void 0:h.permanent)==null?void 0:f.order)?a=n:o.active=!1);const y=s.filter(g=>g.active&&g.branch.id!==a.id||!g.active&&g.branch.id===a.id);y.length>0&&await _a(y.map(g=>({...g,active:g.branchId===a.id})))}(s==null?void 0:s.find(y=>y.branchId===o.branchId))||await _a([o])}function gt(){if(process.env.SQLITE_PATH)return process.env.SQLITE_PATH;const e=pe();if(!e)throw new Error("Could not find project root. Please run this command inside a CodeYam project.");return he.join(e,".codeyam","db.sqlite3")}async function $e(){const e=await lc();process.env.SQLITE_PATH=gt(),e.OPENAI_API_KEY&&(process.env.OPENAI_API_KEY=e.OPENAI_API_KEY)}async function Fe(e){await $e();const r=await Kl({slug:e});if(!r)throw new Error(`Project with slug "${e}" not found in database`);const n=await To({projectId:r.id,names:["_local"]}),a=n==null?void 0:n[0];if(!a)throw new Error(`Local development branch not found for project "${e}". Please run "codeyam init" to set up local analysis.`);return{project:r,branch:a}}async function mc(e,r,n){await $e();const a=pe(),o=Fl(`${e.slug}-local-${Date.now()}-${Math.random()}`),s=n.map(d=>{let m="";if(a)try{if(m=Me(`git diff HEAD -- "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10}),!m)try{const u=Me(`cat "${d}"`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]});if(u){const p=u.split(`
|
|
30
|
-
`);m=`@@ -0,0 +1,${p.length} @@
|
|
31
|
-
${p.map(h=>`+${h}`).join(`
|
|
32
|
-
`)}`}}catch{}}catch{}return{fileName:d,status:"modified",patch:m}}),i={sha:o,projectId:e.id,branchId:r.id,message:`Local analysis: ${n.join(", ")} at ${new Date().toISOString()}`,url:`local://codeyam/${e.slug}/${o}`,htmlUrl:`local://codeyam/${e.slug}/${o}`,author:{username:"local-dev",avatarUrl:"https://github.com/identicons/local-dev.png"},committedAt:new Date().toISOString(),parents:[],files:s,metadata:{baseline:!1,receivedAt:new Date().toISOString()}},c=await ac({projectId:e.id,commits:[i]});if(!c||c.length===0)throw new Error("Failed to create fake commit");return await hc({projectId:e.id,commit:c[0],branch:r}),c[0]}async function Zt(){await $e();const e=await ht({excludeMetadata:!0});if(!e||e.length===0)return[];const r=e.filter(d=>{var m;return!((m=d.metadata)!=null&&m.isSuperseded)}),n=r.map(d=>d.sha),a=r.map(d=>{var m;return(m=d.metadata)==null?void 0:m.previousVersionWithAnalyses}).filter(d=>!!d),o=[...new Set([...n,...a])],s=await ut({entityShas:o,excludeMetadata:!0}),i=new Map;if(s)for(const d of s)i.has(d.entitySha)||i.set(d.entitySha,[]),i.get(d.entitySha).push(d);return r.map(d=>{var p;const m=i.get(d.sha)||[];if(m.length>0)return{...d,analyses:m};const u=(p=d.metadata)==null?void 0:p.previousVersionWithAnalyses;if(u){const h=i.get(u)||[];return{...d,analyses:h}}return{...d,analyses:[]}})}async function Tr(e,r){await $e();const n=await ut({entityShas:[e],limit:1});if(n&&n.length>0&&r){const a=await Io({projectId:n[0].projectId,sha:e});if(a)for(const o of n)o.entity=a}return n||[]}async function jn(e){if(await $e(),e.name&&e.projectId){const n=await ut({projectId:e.projectId,entityName:e.name,limit:10});if(n&&n.length>0){const a=n.filter(s=>{const i=s.scenarios&&s.scenarios.length>0,c=!e.filePath||s.filePath===e.filePath;return i&&c});if(a.length>0)return a.sort((s,i)=>{const c=new Date(s.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),a[0];const o=n.filter(s=>s.scenarios&&s.scenarios.length>0);if(o.length>0)return o.sort((s,i)=>{const c=new Date(s.createdAt||0).getTime();return new Date(i.createdAt||0).getTime()-c}),o[0]}}const r=await ut({entityShas:[e.sha],limit:1});return r&&r.length>0?r[0]:null}async function Fo(e){await $e();const r=await ut({entityShas:[e],limit:1});return(r==null?void 0:r[0])??null}async function _t(e){await $e();const r=await ze();if(!r)return null;const{project:n}=await Fe(r);return await Io({projectId:n.id,sha:e})}async function Oo(e){var a,o,s,i,c,d,m,u;await $e();const r=[],n=[];if((a=e.metadata)!=null&&a.importedExports&&e.metadata.importedExports.length>0){const p=e.metadata.importedExports;for(const h of p){if(!h.filePath||!h.name)continue;const f=await ht({projectId:e.projectId,filePaths:[h.filePath],names:[h.name]});if(f&&f.length>0){const y=f[0],g=await ut({entityShas:[y.sha],limit:1});let w,x,b;if(g&&g.length>0&&g[0].scenarios){const v=g[0],C=v.scenarios||[],E=C.length,N=C.find(_=>{var $,D;return(D=($=_.metadata)==null?void 0:$.screenshotPaths)==null?void 0:D[0]});N&&(w=(s=(o=N.metadata)==null?void 0:o.screenshotPaths)==null?void 0:s[0],x=N.name),b={status:((i=y.metadata)==null?void 0:i.previousVersionWithAnalyses)||v.entitySha!==y.sha?"out_of_date":"up_to_date",scenarioCount:E,timestamp:v.createdAt?new Date(v.createdAt).toLocaleDateString("en-US",{month:"2-digit",day:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"}):void 0}}else b={status:"not_analyzed"};r.push({...y,screenshotPath:w,scenarioName:x,analysisStatus:b})}}}if((c=e.metadata)!=null&&c.importedBy){const p=[];for(const h in e.metadata.importedBy)for(const f in e.metadata.importedBy[h]){const y=e.metadata.importedBy[h][f];y.shas&&p.push(...y.shas)}if(p.length>0){const h=await ht({projectId:e.projectId,shas:p});if(h)for(const f of h){const y=await ut({entityShas:[f.sha],limit:1});let g,w,x;if(y&&y.length>0&&y[0].scenarios){const b=y[0],v=b.scenarios||[],C=v.length,E=v.find(A=>{var _,$;return($=(_=A.metadata)==null?void 0:_.screenshotPaths)==null?void 0:$[0]});E&&(g=(m=(d=E.metadata)==null?void 0:d.screenshotPaths)==null?void 0:m[0],w=E.name),x={status:((u=f.metadata)==null?void 0:u.previousVersionWithAnalyses)||b.entitySha!==f.sha?"out_of_date":"up_to_date",scenarioCount:C,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 x={status:"not_analyzed"};n.push({...f,screenshotPath:g,scenarioName:w,analysisStatus:x})}}}return{importedEntities:r,importingEntities:n}}async function ze(){try{const e=pe();if(!e)return null;const r=he.join(e,".codeyam","config.json");return JSON.parse(await xe.readFile(r,"utf8")).projectSlug||null}catch(e){return console.error("[getProjectSlug] Error:",e),null}}async function It(){await $e();try{const e=await ze();if(!e)return null;const{project:r,branch:n}=await Fe(e),a=await gr({projectId:r.id,branchId:n.id,limit:1,skipRelations:!0});return a&&a.length>0?a[0]:null}catch(e){return console.error("[getCurrentCommit] Error:",e),null}}async function Rn(){try{const e=pe();if(!e)return null;const r=he.join(e,".codeyam","config.json");return JSON.parse(await xe.readFile(r,"utf8"))}catch(e){return console.error("[getProjectConfig] Error:",e),null}}async function zo(e){try{const r=pe();if(!r)return console.error("[getEntityCodeFromFilesystem] No project root found"),null;if(!e.filePath)return console.error("[getEntityCodeFromFilesystem] Entity has no filePath"),null;const n=he.join(r,e.filePath);return await xe.readFile(n,"utf8")}catch(r){return console.error("[getEntityCodeFromFilesystem] Error reading file:",r),null}}async function Yo(e){try{const r=pe();if(!r||!e.filePath)return!1;const n=he.join(r,e.filePath),o=(await xe.stat(n)).mtime.getTime(),s=e.updatedAt||e.createdAt;if(!s)return!1;const i=new Date(s).getTime();return o>i+1e3}catch{return!1}}async function Bo(e){if(await $e(),!e.filePath||!e.name||!e.projectId)return console.error("[getEntityHistory] Entity missing required fields (filePath, name, or projectId)"),[];const r=await ht({projectId:e.projectId,filePaths:[e.filePath],names:[e.name]});if(!r||r.length===0)return[];const n=r.map(i=>i.sha),a=await ut({entityShas:n}),o=new Map;if(a)for(const i of a)o.has(i.entitySha)||o.set(i.entitySha,[]),o.get(i.entitySha).push(i);for(const[i,c]of o.entries())c.sort((d,m)=>{const u=new Date(d.createdAt||0).getTime();return new Date(m.createdAt||0).getTime()-u});const s=r.map(i=>({...i,analyses:o.get(i.sha)||[]}));return s.sort((i,c)=>{var u,p;const d=((u=i.analyses[0])==null?void 0:u.createdAt)||i.createdAt||"",m=((p=c.analyses[0])==null?void 0:p.createdAt)||c.createdAt||"";return new Date(m).getTime()-new Date(d).getTime()}),s}async function Uo(e){try{const r=pe();if(!r)return console.error("[updateProjectConfig] No project root found"),!1;const n=he.join(r,".codeyam","config.json"),a=await xe.readFile(n,"utf8"),o=JSON.parse(a),s={...o,...e},i=JSON.stringify(s,null,2);if(await xe.writeFile(n,i,"utf8"),o.projectSlug){const c={};e.universalMocks!==void 0&&(c.universalMocks=e.universalMocks),e.pathsToIgnore!==void 0&&(c.pathsToIgnore=e.pathsToIgnore),e.webapps!==void 0&&(c.webapps=e.webapps),await Zl({projectSlug:o.projectSlug,metadataUpdate:c})}return!0}catch(r){return console.error("[updateProjectConfig] Error:",r),!1}}const pc=Object.freeze(Object.defineProperty({__proto__:null,getAllEntities:Zt,getAnalysesForEntity:Tr,getAnalysisForExactEntitySha:Fo,getCurrentCommit:It,getEntityBySha:_t,getEntityCodeFromFilesystem:zo,getEntityHistory:Bo,getLatestAnalysisForEntity:jn,getProjectConfig:Rn,getProjectSlug:ze,getRelatedEntities:Oo,hasFileBeenModifiedSinceEntity:Yo,updateProjectConfig:Uo},Symbol.toStringTag,{value:"Module"})),Wo="secrets.json";function Ho(e){return he.join(e,".codeyam",Wo)}function qo(){return he.join(dn.homedir(),".codeyam",Wo)}async function Ir(e){let r={};try{const n=qo(),a=await xe.readFile(n,"utf-8");r=JSON.parse(a)}catch{}try{const n=Ho(e),a=await xe.readFile(n,"utf-8"),o=JSON.parse(a);r={...r,...o}}catch{}return r}async function fc(e,r,n=!0){const a=n?qo():Ho(e),o=he.dirname(a);await xe.mkdir(o,{recursive:!0}),await xe.writeFile(a,JSON.stringify(r,null,2)+`
|
|
33
|
-
`,"utf-8")}async function gc(e){const r=await Ir(e);return!!(r.ANTHROPIC_API_KEY&&r.ANTHROPIC_API_KEY.length>0)||!!(r.OPENAI_API_KEY&&r.OPENAI_API_KEY.length>0)||!!(r.GROQ_API_KEY&&r.GROQ_API_KEY.length>0)||!!(r.OPENROUTER_API_KEY&&r.OPENROUTER_API_KEY.length>0)}async function yc({sourcePath:e,destinationPath:r,excludes:n=[],keepExisting:a=!1,silent:o=!1,extraArgs:s=[]}){return new Promise((i,c)=>{const d=e.endsWith("/")?e:`${e}/`,m=r.endsWith("/")?r:`${r}/`,u=["-a"];a||u.push("--delete","--force"),u.push(...s);for(const f of n)u.push(`--exclude=${f}`);u.push(d,m);const p=Date.now(),h=kr("rsync",u);h.on("exit",f=>{if(f===0){if(!o){const y=((Date.now()-p)/1e3).toFixed(1);console.log(`Directory synced from ${e} to ${r} [Time: ${y}s]`)}i()}else c(new Error(`rsync failed with exit code ${f}`))}),h.on("error",f=>{o||console.log("Error occurred:",f),c(f)})})}const xc=kn(En);async function bc(e){return new Promise(r=>setTimeout(r,e))}function wc(e){try{return process.kill(e,0),!0}catch{return!1}}async function Go(e){try{const{stdout:r}=await xc(`ps -A -o pid=,ppid= | awk '$2 == ${e} { print $1 }'`),n=r.trim().split(`
|
|
34
|
-
`).filter(o=>o.trim()).map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o)),a=[...n];for(const o of n){const s=await Go(o);a.push(...s)}return a}catch{return[]}}function Ta(e,r,n){try{process.kill(e,r)}catch(a){n==null||n(`Error sending ${r} to process ${e}: ${a}`)}}async function vc(e,r,n){const a=await Go(e);for(const o of a.reverse())await Ta(o,r,n);await Ta(e,r,n)}async function Ht(e,r=console.log,n=1){if(e==process.pid)throw new Error(`Eek! killProcess(${e}) called on self!`);let a=0;async function o(s,i){await vc(e,s,r);for(let c=0;c<i;c++)if(await bc(1e3),a+=1e3,!await wc(e))return r(`Process tree ${e} successfully killed with ${s} after ${a/1e3} seconds.`),!0;return r(`Process tree still running after ${s}...`),!1}if(await o("SIGINT",5)||await o("SIGTERM",5))return!0;for(let s=0;s<n;s++)if(await o("SIGKILL",2))return!0;return console.warn(`CodeYam Warning: Completely failed to kill process tree ${e} after ${a/1e3} seconds.`),!1}function Cc(e){const r=new Date().toISOString();e.currentRun&&(e.currentRun.archivedAt=r,e.historicalRuns??(e.historicalRuns=[]),e.historicalRuns.push(e.currentRun)),e.currentRun={id:qi(),createdAt:r}}ji.config({quiet:!0});var Jo=(e=>(e.Server="server",e.Analyzer="analyzer",e.Capture="capture",e.Controller="controller",e.Worker="worker",e.Project="project",e.Other="other",e))(Jo||{});class Nc extends Ri{constructor(){super(...arguments),this.processes=new Map}register(r){const n=Li(),{process:a,type:o,name:s,metadata:i,parentId:c}=r,d={id:n,type:o,name:s,pid:a.pid,state:"running",startedAt:Date.now(),metadata:i,parentId:c,children:[]};if(this.processes.set(n,{info:d,process:a}),c){const p=this.processes.get(c);p&&(p.info.children=p.info.children||[],p.info.children.push(n))}const m=(p,h)=>{this.handleProcessExit(n,p,h)},u=p=>{this.handleProcessError(n,p)};return a.on("exit",m),a.on("error",u),a.__cleanup=()=>{a.removeListener("exit",m),a.removeListener("error",u)},this.emit("processStarted",d),n}unregister(r){const n=this.processes.get(r);return n?(n.process.__cleanup&&n.process.__cleanup(),this.processes.delete(r),!0):!1}getInfo(r){const n=this.processes.get(r);return n?{...n.info}:null}listAll(){return Array.from(this.processes.values()).map(r=>({...r.info}))}listByType(r){return this.listAll().filter(n=>n.type===r)}listByState(r){return this.listAll().filter(n=>n.state===r)}findByName(r){return this.listAll().filter(n=>n.name===r)}async shutdown(r,n={}){const a=this.processes.get(r);if(!a)throw new Error(`Process not found: ${r}`);const{info:o,process:s}=a;if(o.state==="completed"||o.state==="failed"||o.state==="killed")return;if(n.shutdownChildren&&o.children&&o.children.length>0&&await Promise.all(o.children.map(c=>this.shutdown(c,n))),s.pid)try{await Ht(s.pid,c=>console.log(`[Process ${r}] ${c}`))}catch(c){console.warn(`Error killing process ${r}:`,c)}await new Promise(c=>setTimeout(c,100)),o.state==="running"&&(o.state="killed",o.endedAt=Date.now());const i=s.__cleanup;i&&i()}async shutdownByType(r,n={}){const a=this.listByType(r);await Promise.all(a.map(o=>this.shutdown(o.id,n)))}async shutdownAll(r={}){const n=this.listAll();await Promise.all(n.map(a=>this.shutdown(a.id,r)))}cleanupCompleted(r={}){const{retentionMs:n=6e4}=r,a=Date.now();for(const[o,s]of this.processes.entries()){const{info:i}=s;if((i.state==="completed"||i.state==="failed"||i.state==="killed")&&i.endedAt&&a-i.endedAt>n){const c=s.process.__cleanup;c&&c(),this.processes.delete(o)}}}handleProcessExit(r,n,a){const o=this.processes.get(r);if(!o)return;const{info:s}=o;s.endedAt=Date.now(),s.exitCode=n,s.signal=a,n===0?s.state="completed":a?s.state="killed":s.state="failed",this.emit("processExited",s)}handleProcessError(r,n){const a=this.processes.get(r);if(!a)return;const{info:o}=a;o.endedAt=Date.now(),o.state="failed",o.metadata={...o.metadata,error:n.message},this.emit("processExited",o)}}let Xr=null;function Sc(){return Xr||(Xr=new Nc),Xr}const Ec={stdoutToConsole:!0,stdoutToFile:!0,stderrToConsole:!0,stderrToFile:!0};function Ac({command:e,args:r,workingDir:n,outputOptions:a=Ec,processName:o,env:s}){const i={...process.env,...s||{},CODEYAM_PROCESS_NAME:`codeyam-${o}`},c=kr(e,r,{cwd:n,env:i});return Sc().register({process:c,type:Jo.Other,name:o,metadata:{command:e,args:r,workingDir:n}}),{promise:new Promise(u=>{const p=f=>{const y=he.join(n,"log.txt");K.appendFile(y,f,g=>{g&&console.log("Error writing to log file:",g)})},h=(f,y="")=>{const g=new Date().toLocaleString();return f.split(`
|
|
35
|
-
`).map(x=>x.trim()?`[${g}]${y} ${x}`:x).join(`
|
|
36
|
-
`)};c.stdout.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=h(y);a.stdoutToConsole&&console.log(g),a.stdoutToFile&&p(g+`
|
|
37
|
-
`),a.stdoutCallback&&a.stdoutCallback(y)}),c.stderr.on("data",function(f){const y=(f==null?void 0:f.toString())??"",g=h(y,"<STDERR>");a.stderrToConsole&&console.error(g),a.stderrToFile&&p(g+`
|
|
38
|
-
`),a.stderrCallback&&a.stderrCallback(y)}),c.on("exit",function(f){u(f)})}),process:c}}function kc(e){const r=[];return Object.keys(e).forEach(n=>{const a=e[n];a!==void 0&&(typeof a=="boolean"?a&&r.push(`--${n}`):a!==null&&r.push(`--${n}`,String(a)))}),r}function Pc({absoluteCodeyamRootPath:e,startEnv:r,startArgs:n,outputOptions:a}){const o=Object.entries(r).map(([i,c])=>`${i}=${c}`).join(`
|
|
39
|
-
`);K.writeFileSync(`${e}/.env`,o);const s=kc(n);return Ac({command:"node",args:["--enable-source-maps","./dist/project/start.js",...s],workingDir:e,outputOptions:a,processName:"analyzer",env:r})}const _c="/tmp/codeyam/local-dev";function Vo(e){return ee.join(_c,e)}function Qo(e){return ee.join(Vo(e),"codeyam")}function ot(e){return ee.join(Vo(e),"project")}function $r(e){return ee.join(Qo(e),"log.txt")}const Mc=[".sync-metadata.json","__codeyamMocks__"];async function Tc(e,r={}){const{port:n,silent:a=!0}=r,o=ot(e);if(n)try{Me(`lsof -ti:${n} | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}try{Me(`lsof +D "${o}" 2>/dev/null | grep node | awk '{print $2}' | xargs kill -9 2>/dev/null || true`,{stdio:a?"ignore":"inherit"})}catch{}await new Promise(s=>setTimeout(s,500))}async function Ic(e,r={}){const{killProcesses:n=!0,port:a,silent:o=!0}=r,s=ot(e),i=[],c=[];if(!K.existsSync(s))return{removed:i,errors:c};n&&await Tc(e,{port:a,silent:o});for(const d of Mc){const m=ee.join(s,d);if(K.existsSync(m))try{(await Ie.stat(m)).isDirectory()?await Ie.rm(m,{recursive:!0,force:!0}):await Ie.unlink(m),i.push(d)}catch(u){c.push(`${d}: ${u instanceof Error?u.message:String(u)}`)}}return{removed:i,errors:c}}const $c=ee.dirname(An(import.meta.url));function jc(e){let r=e;for(;r!==ee.dirname(r);){const n=ee.join(r,"package.json");if(K.existsSync(n))try{if(JSON.parse(K.readFileSync(n,"utf8")).name==="@codeyam/codeyam-cli")return r}catch{}r=ee.dirname(r)}throw new Error("Could not find @codeyam/codeyam-cli package root")}function Dn(){const e=jc($c);return ee.join(e,"analyzer-template")}function $t(e){return Qo(e)}async function Ia(e){const r=Dn(),n=$t(e);if(!K.existsSync(r))throw new Error(`Analyzer template not found at ${r}. Did the build process complete successfully?`);await Ie.mkdir(ee.dirname(n),{recursive:!0}),await yc({sourcePath:r,destinationPath:n,silent:!0})}function jt(e,r,n,a){const o=$t(e);if(!K.existsSync(o))throw new Error(`Analyzer not found at ${o}. The analyzer template may not be initialized. Try running 'codeyam init' or contact support if the issue persists.`);const s=void 0;return Pc({absoluteCodeyamRootPath:o,startEnv:r,startArgs:n,outputOptions:{stdoutToConsole:!1,stdoutToFile:!0,stdoutCallback:s,stderrToConsole:!1,stderrToFile:!0,stderrCallback:s}})}function Rc(e){const r=Dn(),n=$t(e),a=ee.join(r,".build-info.json"),o=ee.join(n,".build-info.json");if(!K.existsSync(a))return{isFresh:!1,reason:"Template build marker missing - template may be corrupted"};if(!K.existsSync(n))return{isFresh:!1,reason:"Cached analyzer does not exist"};if(!K.existsSync(o))return{isFresh:!1,reason:"Cached analyzer build marker missing - was created with old version"};try{const s=JSON.parse(K.readFileSync(a,"utf8")),i=JSON.parse(K.readFileSync(o,"utf8"));return s.buildTime>i.buildTime?{isFresh:!1,reason:`Template is newer (${s.buildTimestamp}) than cached version (${i.buildTimestamp})`}:{isFresh:!0}}catch(s){return{isFresh:!1,reason:`Error reading build markers: ${s.message}`}}}async function Xt(e,r){const n=$t(e);if(!K.existsSync(n)){r.update("Creating analyzer..."),await Ia(e);return}const a=Rc(e);a.isFresh||(r.update(`Updating analyzer (${a.reason})...`),await Ia(e))}async function Ln(e){await Ic(e,{killProcesses:!1})}const Dc=ee.dirname(An(import.meta.url));function Ko(){let e=Dc;for(;e!==ee.dirname(e);){const r=ee.join(e,"package.json");if(K.existsSync(r))try{if(JSON.parse(K.readFileSync(r,"utf8")).name==="@codeyam/codeyam-cli")return e}catch{}e=ee.dirname(e)}return null}function Bt(e){if(!K.existsSync(e))return null;try{return JSON.parse(K.readFileSync(e,"utf8"))}catch{return null}}function Lc(){const e=Ko();if(e){const r=[ee.join(e,"src/webserver/build-info.json"),ee.join(e,"codeyam-cli/src/webserver/build-info.json")];for(const n of r){const a=Bt(n);if(a!=null&&a.semanticVersion)return a.semanticVersion}}return"unknown"}const Fn=Lc();function Zo(e){const r=Ko();let n=null;if(r){const d=[ee.join(r,"src/webserver/build-info.json"),ee.join(r,"codeyam-cli/src/webserver/build-info.json")];for(const m of d)if(n=Bt(m),n)break}const a=Dn(),o=ee.join(a,".build-info.json"),s=Bt(o);let i=null;if(e){const d=$t(e),m=ee.join(d,".build-info.json");i=Bt(m)}let c=!1;return s&&i?c=s.buildTime>i.buildTime:s&&!i&&e&&(c=!0),{cliVersion:Fn,webserverVersion:n,templateVersion:s,cachedAnalyzerVersion:i,isCacheStale:c}}function jr(e){const r=$t(e),n=ee.join(r,".build-info.json"),a=Bt(n);return(a==null?void 0:a.version)??null}function Xo(){const e=pe();return e?ee.join(e,".codeyam","server.json"):null}function es(){const e=Xo();if(!e||!K.existsSync(e))return null;try{const r=K.readFileSync(e,"utf8");return JSON.parse(r)}catch{return null}}function Fc(){const e=Xo();if(e)try{K.unlinkSync(e)}catch{}}const Oc="/assets/globals-D3yhhV8x.css";function zc({text:e,subtext:r,linkText:n,linkTo:a}){const[o,s]=M(!1);return o?null:t("div",{className:"bg-blue-100 border rounded border-blue-800 shadow-sm mx-6 mt-6",children:l("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3 flex-1",children:[t("div",{className:"shrink-0",children:t("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:t("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"})})}),l("div",{className:"flex-1",children:[t("p",{className:"text-sm font-medium text-blue-900",children:e}),t("p",{className:"text-xs text-blue-700 mt-0.5",children:r})]}),t(oe,{to:a,className:"shrink-0 px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded hover:bg-blue-700 transition-colors",children:n})]}),t("button",{type:"button",onClick:()=>s(!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:t("svg",{className:"w-5 h-5",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",viewBox:"0 0 24 24",stroke:"currentColor",children:t("path",{d:"M6 18L18 6M6 6l12 12"})})})]})})}function Yc({serverVersion:e}){const[r,n]=M("stale"),[a,o]=M(null),s=async()=>{n("restarting"),o(null);try{if(!(await fetch("/api/restart-server",{method:"POST"})).ok)throw new Error("Failed to restart server");n("reconnecting");let c=0;const d=30,m=1e3,u=async()=>{try{if((await fetch("/api/health")).ok){window.location.reload();return}}catch{}c++,c<d?setTimeout(()=>void u(),m):(o("Server took too long to restart. Please refresh manually."),n("stale"))};setTimeout(()=>void u(),500)}catch(i){o(i instanceof Error?i.message:"Failed to restart server"),n("stale")}};return t("div",{className:"bg-amber-100 border rounded border-amber-700 shadow-sm mx-6 mt-6",children:t("div",{className:"max-w-7xl mx-auto px-4 py-3 flex items-center justify-between",children:l("div",{className:"flex items-center gap-3 flex-1",children:[t("div",{className:"shrink-0",children:t("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:t("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"})})}),l("div",{className:"flex-1",children:[r==="stale"&&l(le,{children:[t("p",{className:"text-sm font-medium text-amber-900",children:"Dashboard server is out of date"}),l("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."]}),a&&t("p",{className:"text-xs text-red-600 mt-1",children:a})]}),r==="restarting"&&l(le,{children:[t("p",{className:"text-sm font-medium text-amber-900",children:"Restarting server..."}),t("p",{className:"text-xs text-amber-700 mt-0.5",children:"Please wait while the server restarts."})]}),r==="reconnecting"&&l(le,{children:[t("p",{className:"text-sm font-medium text-amber-900",children:"Reconnecting..."}),t("p",{className:"text-xs text-amber-700 mt-0.5",children:"Waiting for the server to come back online."})]})]}),r==="stale"&&t("button",{type:"button",onClick:()=>void s(),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"}),(r==="restarting"||r==="reconnecting")&&l("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 text-amber-700 text-sm",children:[l("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("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"})]}),r==="restarting"?"Stopping...":"Reconnecting..."]})]})})})}function wr(e){return ee.join(e,".codeyam","queue.json")}function zt(e){const r=wr(e);if(!K.existsSync(r))return{paused:!1,jobs:[]};try{const n=K.readFileSync(r,"utf8");return JSON.parse(n)}catch(n){return console.error("Failed to load queue state:",n),{paused:!1,jobs:[]}}}function Bc(e,r){const n=wr(e),a=ee.dirname(n);K.existsSync(a)||K.mkdirSync(a,{recursive:!0});try{K.writeFileSync(n,JSON.stringify(r,null,2),"utf8")}catch(o){throw console.error("Failed to save queue state:",o),o}}async function Uc(e,r,n){console.log(`[Queue] Executing job ${e.id} (${e.type})`);try{if(e.type==="analysis")await Wc(e,r,n);else if(e.type==="baseline")await Hc(e,r,n);else if(e.type==="recapture")await qc(e,r,n);else if(e.type==="capture-only")await Gc(e,r,n);else if(e.type==="debug-setup")await Jc(e,r,n);else if(e.type==="interactive-start")await Vc(e,r,n);else if(e.type==="interactive-stop")await Qc(e,r,n);else throw new Error(`Unknown job type: ${e.type}`);console.log(`[Queue] Job ${e.id} completed successfully`)}catch(a){throw console.error(`[Queue] Job ${e.id} failed:`,a),a}}async function Wc(e,r,n){var g,w,x,b;const{projectSlug:a,commitSha:o,entityShas:s}=e;if(!o)throw new Error("Analysis job missing commitSha");const i=s||[],{project:c}=await Fe(a);await Ln(a),await Xt(a,{update:v=>console.log(`[Queue] ${v}`)});const d=jr(a),m={...await ft(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:o,CODEYAM_LOCAL_PROJECT_PATH:r,SQLITE_PATH:gt(),...i.length>0?{ENTITY_SHAS:i.join(",")}:{},...e.onlyDataStructure?{ONLY_DATA_STRUCTURE:"true"}:{},...d?{ANALYZER_VERSION:d}:{}},u=(w=(g=c.metadata)==null?void 0:g.webapps)==null?void 0:w[0];if(!u)throw new Error("No webapps found in project metadata");const p=e.onlyDataStructure,h={packageManager:((x=c.metadata)==null?void 0:x.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:0,noServer:!0,framework:u.framework,...p?{}:{orchestrateCapture:"local-sequential"}},f=jt(a,m,h),y=v=>{try{return process.kill(v,0),!0}catch{return!1}};await ct({commitSha:o,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}}),n==null||n.notifyChange("commit");try{try{const v=new Promise((C,E)=>setTimeout(()=>E(new Error("Analysis timed out after 60 minutes")),36e5));await Promise.race([f.promise,v]),await ct({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),n==null||n.notifyChange("commit"),await ct({commitSha:o,runStatusUpdate:{currentEntityShas:[]}}),n==null||n.notifyChange("commit"),await new Promise(C=>setTimeout(C,2e3))}finally{if(f.process.pid)try{y(f.process.pid)&&await Ht(f.process.pid,()=>{})}catch{}}}catch(v){if(console.error(`[Queue] Analysis job ${e.id} failed:`,v),f.process.pid&&y(f.process.pid))try{await Ht(f.process.pid,()=>{})}catch{}try{await ct({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:v instanceof Error?v.message:String(v)}}),n==null||n.notifyChange("commit")}catch(C){console.error("[Queue] Failed to update commit metadata after job failure:",C)}throw v}}async function Hc(e,r,n){var h,f,y;const{projectSlug:a,commitSha:o}=e;if(!o)throw new Error("Baseline job missing commitSha");console.log(`[Queue] Starting baseline analysis for ${a}`);const{project:s}=await Fe(a);await Ln(a),await Xt(a,{update:g=>console.log(`[Queue] ${g}`)});const i=jr(a),c={...await ft(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",BRANCH_COMMIT_SHA:o,CODEYAM_LOCAL_PROJECT_PATH:r,SQLITE_PATH:gt(),...i?{ANALYZER_VERSION:i}:{}},d=(f=(h=s.metadata)==null?void 0:h.webapps)==null?void 0:f[0];if(!d)throw new Error("No webapps found in project metadata");const m={packageManager:((y=s.metadata)==null?void 0:y.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:0,noServer:!0,framework:d.framework,orchestrateCapture:"local-sequential"},u=jt(a,c,m),p=g=>{try{return process.kill(g,0),!0}catch{return!1}};await ct({commitSha:o,runStatusUpdate:{createdAt:new Date().toISOString(),analyzerPid:u.process.pid}}),n==null||n.notifyChange("commit");try{const g=new Promise((w,x)=>setTimeout(()=>x(new Error("Baseline timed out after 4 hours")),144e5));await Promise.race([u.promise,g]),await ct({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0},archiveCurrentRun:!0}),n==null||n.notifyChange("commit"),console.log(`[Queue] Baseline completed for ${a}`),await new Promise(w=>setTimeout(w,2e3))}finally{if(u.process.pid)try{p(u.process.pid)&&await Ht(u.process.pid,()=>{})}catch{}}}async function qc(e,r,n){var f,y,g,w;const{projectSlug:a,analysisId:o,scenarioId:s,defaultWidth:i}=e;if(!o)throw new Error("Recapture job missing analysisId");const c=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${o} not found`);if(i){const{getDatabase:x}=await import("./index-DVzYx8PN.js"),b=x(),v=await b.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let C={};v!=null&&v.metadata&&(typeof v.metadata=="string"?C=JSON.parse(v.metadata):C=v.metadata),C.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",c.entitySha).execute()}await Tt(o,x=>{if(x.readyToBeCaptured=!0,x.scenarios)for(const b of x.scenarios)(!s||b.name===s)&&(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 x.finishedAt});const{project:d}=await Fe(a);await Xt(a,{update:x=>console.log(`[Queue] ${x}`)});const m=jr(a),u={...await ft(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:r,SQLITE_PATH:gt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,...s?{SCENARIO_IDS:s}:{},...m?{ANALYZER_VERSION:m}:{}},p={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!0,framework:((w=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:w.framework)??Kt.Next,orchestrateCapture:"local-sequential"},h=jt(a,u,p);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function Gc(e,r,n){var f,y,g,w;const{projectSlug:a,analysisId:o,scenarioId:s,defaultWidth:i}=e;if(!o)throw new Error("Capture-only job missing analysisId");const c=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!c||!c.commit)throw new Error(`Analysis ${o} not found`);if(i){const{getDatabase:x}=await import("./index-DVzYx8PN.js"),b=x(),v=await b.selectFrom("entities").select(["metadata"]).where("sha","=",c.entitySha).executeTakeFirst();let C={};v!=null&&v.metadata&&(typeof v.metadata=="string"?C=JSON.parse(v.metadata):C=v.metadata),C.defaultWidth=i,await b.updateTable("entities").set({metadata:JSON.stringify(C)}).where("sha","=",c.entitySha).execute()}await Tt(o,x=>{if(x.readyToBeCaptured=!0,x.scenarios)for(const b of x.scenarios)(!s||b.name===s)&&(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 x.finishedAt});const{project:d}=await Fe(a);await Xt(a,{update:x=>console.log(`[Queue] ${x}`)});const m=jr(a);console.log("[Queue] executeCaptureOnlyJob: Setting CAPTURE_ONLY=true for capture without file regeneration");const u={...await ft(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:c.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:r,SQLITE_PATH:gt(),READY_TO_BE_CAPTURED:"true",CAPTURE_ONLY:"true",ANALYSIS_IDS:o,...s?{SCENARIO_IDS:s}:{},...m?{ANALYZER_VERSION:m}:{}},p={packageManager:((f=d.metadata)==null?void 0:f.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!0,fast:!0,framework:((w=(g=(y=d.metadata)==null?void 0:y.webapps)==null?void 0:g[0])==null?void 0:w.framework)??Kt.Next,orchestrateCapture:"local-sequential"},h=jt(a,u,p);try{await h.promise}finally{try{h.process.kill("SIGTERM")}catch{}}}async function Jc(e,r,n){var h,f,y,g;const{projectSlug:a,analysisId:o,scenarioId:s}=e;if(!o)throw new Error("Debug setup job missing analysisId");const i=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${o} not found`);const{project:c}=await Fe(a);await Ln(a),await Xt(a,{update:w=>console.log(`[Queue] ${w}`)});const d={...await ft(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:r,SQLITE_PATH:gt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,PREP_ONLY:"true"};s&&(d.SCENARIO_IDS=s);const m={packageManager:((h=c.metadata)==null?void 0:h.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!1,framework:((g=(y=(f=c.metadata)==null?void 0:f.webapps)==null?void 0:y[0])==null?void 0:g.framework)||Kt.Next},p=await jt(a,d,m).promise;if(p!==0)throw new Error(`Prep process exited with code ${p}`)}async function Vc(e,r,n){var p,h,f,y;const{projectSlug:a,analysisId:o,scenarioId:s}=e;if(!o)throw new Error("Interactive start job missing analysisId");const i=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!i||!i.commit)throw new Error(`Analysis ${o} not found`);const{project:c}=await Fe(a),d={...await ft(),PROJECT_SLUG:a,USE_WORKER_THREADS:"true",COMMIT_SHA:i.commit.sha,CODEYAM_LOCAL_PROJECT_PATH:r,SQLITE_PATH:gt(),READY_TO_BE_CAPTURED:"true",ANALYSIS_IDS:o,INTERACTIVE_MODE:"true"};s&&(d.SCENARIO_IDS=s);const m={packageManager:((p=c.metadata)==null?void 0:p.packageManager)||"npm",absoluteProjectRootPath:ot(a),port:void 0,noServer:!1,framework:((y=(f=(h=c.metadata)==null?void 0:h.webapps)==null?void 0:f[0])==null?void 0:y.framework)||Kt.Next};await Tt(o,g=>{g.readyToBeCaptured=!0});const u=jt(a,d,m);await jo(o,g=>{g.interactiveMode={pid:u.process.pid,startedAt:new Date().toISOString(),jobId:e.id}}),console.log(`[Queue] Interactive mode started for analysis ${o}, PID: ${u.process.pid}`)}async function Qc(e,r,n){var d;const{projectSlug:a,analysisId:o}=e;if(!o)throw new Error("Interactive stop job missing analysisId");const s=await at({id:o,includeScenarios:!0,includeCommitAndBranch:!0});if(!s)throw new Error(`Analysis ${o} not found`);const i=(d=s.metadata)==null?void 0:d.interactiveMode;if(!(i!=null&&i.pid)){console.log(`[Queue] No interactive mode process found for analysis ${o}`);return}const c=i.pid;console.log(`[Queue] Stopping interactive mode for analysis ${o}, killing PID: ${c}`);try{try{process.kill(c,0)}catch{console.log(`[Queue] Process ${c} already exited`);return}await Ht(c,()=>{}),console.log(`[Queue] Successfully killed interactive mode process ${c}`)}catch(m){throw console.error(`[Queue] Failed to kill process ${c}:`,m),m}finally{await jo(o,m=>{m.interactiveMode=null})}}class Kc{constructor(r,n){this.processing=!1,this.completionCallbacks=new Map,this.completedJobs=new Map,this.projectRoot=r,this.state={paused:!1,jobs:[]},n&&(typeof n=="function"?this.notifier={notifyChange:()=>n()}:this.notifier=n)}start(){this.state=zt(this.projectRoot),this.state.jobs.length>0?(this.state.currentlyExecuting&&(console.log(`[Queue] Clearing stale currentlyExecuting job from previous session: ${this.state.currentlyExecuting.id}`),this.state.currentlyExecuting=void 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(r){const n=r.commitSha||Vt(),a={...r,id:n,queuedAt:new Date().toISOString()};this.state.jobs.push(a),this.save(),console.log(`[Queue] Enqueued job ${n} (${a.type})`);const o=new Promise((s,i)=>{this.completionCallbacks.set(n,c=>{c?i(c):s()})});return this.state.paused||this.processNext().catch(s=>{console.error("[Queue] ERROR in processNext():",s)}),{jobId:n,completion:o}}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(r){return this.completedJobs.get(r)}removeJob(r){const n=this.state.jobs.length;this.state.jobs=this.state.jobs.filter(o=>o.id!==r);const a=this.state.jobs.length<n;if(a){console.log(`[Queue] Removed job ${r}`),this.save();const o=this.completionCallbacks.get(r);o&&(setImmediate(()=>o(new Error("Job cancelled by user"))),this.completionCallbacks.delete(r))}else console.log(`[Queue] Job ${r} not found in queue`);return a}clearQueue(){const r=this.state.jobs.length;return r===0?0:(this.state.jobs.forEach(n=>{const a=this.completionCallbacks.get(n.id);a&&(setImmediate(()=>a(new Error("Job cancelled by user"))),this.completionCallbacks.delete(n.id))}),this.state.jobs=[],console.log(`[Queue] Cleared ${r} jobs`),this.save(),r)}reorderJob(r,n){const a=this.state.jobs.findIndex(i=>i.id===r);if(a===-1)return console.log(`[Queue] Job ${r} not found in queue`),!1;const o=n==="up"?a-1:a+1;if(o<0||o>=this.state.jobs.length)return console.log(`[Queue] Cannot move job ${r} ${n}: at boundary`),!1;const s=this.state.jobs[a];return this.state.jobs[a]=this.state.jobs[o],this.state.jobs[o]=s,console.log(`[Queue] Moved job ${r} ${n} (position ${a} -> ${o})`),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 r=this.state.jobs[0];console.log(`[Queue] Starting job ${r.id} (${r.type})`);try{this.state.currentlyExecuting=this.state.jobs.shift(),this.save(),await Uc(r,this.projectRoot,this.notifier),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(r.id,{id:r.id,status:"success",completedAt:new Date().toISOString()});const n=this.completionCallbacks.get(r.id);n&&(n(),this.completionCallbacks.delete(r.id)),console.log(`[Queue] Job ${r.id} completed successfully`)}catch(n){console.error(`[Queue] Job ${r.id} failed:`,n),this.state.currentlyExecuting=void 0,this.save(),this.completedJobs.set(r.id,{id:r.id,status:"error",error:(n==null?void 0:n.message)||"Unknown error",completedAt:new Date().toISOString()});const a=this.completionCallbacks.get(r.id);a&&(a(n),this.completionCallbacks.delete(r.id))}finally{this.processing=!1,!this.state.paused&&this.state.jobs.length>0&&setImmediate(()=>void this.processNext())}}save(){Bc(this.projectRoot,this.state),this.notifier&&this.notifier.notifyChange("queue")}}class Zc{constructor(r,n,a=100){this.watcher=null,this.debounceTimer=null,this.projectRoot=r,this.onChange=n,this.debounceMs=a}start(){const r=wr(this.projectRoot);if(!K.existsSync(r)){console.log("[QueueFileWatcher] Queue file does not exist yet, will start watching when created"),this.watchDirectory();return}this.watchFile(r)}watchDirectory(){const r=wr(this.projectRoot),n=r.substring(0,r.lastIndexOf("/"));try{this.watcher=K.watch(n,(a,o)=>{o==="queue.json"&&(this.stop(),this.watchFile(r),this.notifyChange())}),console.log("[QueueFileWatcher] Watching .codeyam directory for queue.json creation")}catch(a){console.error("[QueueFileWatcher] Failed to watch directory:",a)}}watchFile(r){try{this.watcher=K.watch(r,n=>{n==="change"&&this.notifyChange()}),console.log("[QueueFileWatcher] Watching queue.json for changes")}catch(n){console.error("[QueueFileWatcher] Failed to watch queue file:",n)}}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 Xc{constructor(r,n,a){this.fileWatcher=null,this.serverInfo=r,this.projectRoot=n,this.onStateChange=a,this.cachedState=zt(n)}start(){this.cachedState=zt(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 Zc(this.projectRoot,()=>{console.log("[ProxyQueue] Detected queue.json change from background server"),this.refreshState()}),this.fileWatcher.start()}enqueue(r){let n,a;const o=new Promise((i,c)=>{n=i,a=c}),s=`proxy-${Date.now()}-${Math.random().toString(36).slice(2)}`;return this.enqueueRemote(r).then(i=>{console.log(`[ProxyQueue] Job enqueued on background server: ${i.jobId}`),this.refreshState(),n()}).catch(i=>{console.error("[ProxyQueue] Failed to enqueue job:",i),a(i)}),{jobId:s,completion:o}}async enqueueRemote(r){const n=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"enqueue",...r})});if(!n.ok){const a=await n.text();throw new Error(`Failed to enqueue: ${n.status} ${a}`)}return n.json()}resume(){console.log("[ProxyQueue] Sending resume command to background server"),this.sendAction("resume").catch(r=>{console.error("[ProxyQueue] Failed to resume:",r)})}pause(){console.log("[ProxyQueue] Sending pause command to background server"),this.sendAction("pause").catch(r=>{console.error("[ProxyQueue] Failed to pause:",r)})}async sendAction(r){const n=await fetch(`${this.serverInfo.url}/api/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:r})});if(!n.ok){const a=await n.text();throw new Error(`Failed to ${r}: ${n.status} ${a}`)}this.refreshState()}getState(){return this.cachedState=zt(this.projectRoot),{...this.cachedState}}refreshState(){this.cachedState=zt(this.projectRoot),this.onStateChange&&this.onStateChange()}async isServerAlive(){try{const r=new AbortController,n=setTimeout(()=>r.abort(),2e3),a=await fetch(`${this.serverInfo.url}/api/health`,{signal:r.signal});return clearTimeout(n),a.ok}catch{return!1}}getServerInfo(){return{...this.serverInfo}}stop(){this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null)}}function ed(e){const r=ee.join(e,".codeyam","server.json");if(!K.existsSync(r))return null;try{const n=K.readFileSync(r,"utf8");return JSON.parse(n)}catch{return null}}function td(e){try{return process.kill(e,0),!0}catch{return!1}}async function rd(e){try{const r=new AbortController,n=setTimeout(()=>r.abort(),2e3),a=await fetch(`${e}/api/health`,{signal:r.signal});return clearTimeout(n),a.ok}catch{return!1}}async function nd(e){const r=ed(e);return!r||!td(r.pid)||!await rd(r.url)?null:{url:r.url,port:r.port,pid:r.pid}}class ad extends Di{constructor(){super();ar(this,"watcher",null);ar(this,"dbPath",null);ar(this,"isWatching",!1);this.setMaxListeners(20)}async start(){if(!this.isWatching)try{this.dbPath=gt();const{default:n}=await import("chokidar"),a=[this.dbPath,`${this.dbPath}-wal`,`${this.dbPath}-shm`];this.watcher=n.watch(a,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:1e3}),this.watcher.on("change",o=>{const s=Date.now(),i=new Date(s).toISOString();console.log("[dbNotifier] ========================================"),console.log(`[dbNotifier] Database file changed: ${o}`),console.log(`[dbNotifier] Timestamp: ${i} (${s})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:"unknown",timestamp:s})}).on("error",o=>{console.error("Database watcher error:",o),this.emit("error",o)}),this.isWatching=!0}catch(n){console.error("Failed to start database watcher:",n),this.emit("error",n)}}notifyChange(n="unknown"){const a=Date.now(),o=new Date(a).toISOString();console.log("[dbNotifier] ========================================"),console.log("[dbNotifier] Manual notification triggered"),console.log(`[dbNotifier] Change type: ${n}`),console.log(`[dbNotifier] Timestamp: ${o} (${a})`),console.log(`[dbNotifier] Listeners count: ${this.listenerCount("change")}`),console.log("[dbNotifier] ========================================"),this.emit("change",{type:n,timestamp:a})}stop(){this.watcher&&(this.watcher.close(),this.watcher=null,this.isWatching=!1,console.log("Database watcher stopped"))}}const un=new ad;let vt=null,Yt=null;async function od(){if(!vt){if(Yt){await Yt;return}Yt=(async()=>{try{const e=process.env.CODEYAM_ROOT_PATH||Ro()||process.cwd();cc(e),console.log(`[GlobalQueue] Project root: ${e}`);const r=await nd(e);if(r){console.log(`[GlobalQueue] Detected background server at ${r.url} (PID: ${r.pid})`),console.log("[GlobalQueue] Using proxy queue");const n=new Xc(r,e,()=>{un.notifyChange("unknown")});await n.start(),vt=n}else{console.log("[GlobalQueue] No background server detected, using local queue");const n=new Kc(e,un);await n.start(),vt=n}console.log("[GlobalQueue] Queue initialized")}catch(e){throw console.error("[GlobalQueue] Failed to initialize queue:",e),e}})(),await Yt}}async function st(){return vt||await od(),vt}function sd(){return vt||(Yt&&console.warn("[GlobalQueue] Queue still initializing, loader may see empty state"),null)}const id=()=>[{rel:"stylesheet",href:Oc},{rel:"icon",type:"image/x-icon",href:"/favicon.ico"}];async function ld({request:e,context:r}){var n,a,o,s,i,c,d;try{const m=pe()||process.cwd(),[u,p]=await Promise.all([ze(),Ir(m)]);if(!u)throw new Error("Project slug not found");const{project:h,branch:f}=await Fe(u),y=await gr({projectId:h.id,branchId:f.id,limit:20,skipRelations:!0}),g=y.length>0?y[0]:null,w=r.analysisQueue||sd(),x=w==null?void 0:w.getState(),b=async L=>{if(!L||L.length===0)return[];const z=Math.min(Math.max(L.length*2e3,1e4),6e4),O=new Promise(R=>setTimeout(()=>{console.warn(`[Loader] Entity fetch timeout after ${z}ms for ${L.length} entities`),R([])},z)),F=ht({shas:L,excludeMetadata:!0}).then(R=>R||[]);return Promise.race([F,O])},v=await Promise.all(((x==null?void 0:x.jobs)||[]).map(async L=>{var O;const z=await b(L.entityShas||[]);return z.length===0&&((O=L.entityShas)!=null&&O.length)&&console.warn("[Loader] Entity fetch timeout/failed for job",L.id),{...L,entities:z}}));let C=null;if(x!=null&&x.currentlyExecuting){const L=x.currentlyExecuting,z=await b(L.entityShas||[]);z.length===0&&((n=L.entityShas)!=null&&n.length)&&console.warn("[Loader] Entity fetch timeout/failed for currentlyExecuting",L.id),C={...L,entities:z}}const E=C?v.filter(L=>L.id!==C.id):v;let N=((o=(a=g==null?void 0:g.metadata)==null?void 0:a.currentRun)==null?void 0:o.currentEntityShas)||[];if(N.length===0){const L=((s=g==null?void 0:g.metadata)==null?void 0:s.historicalRuns)||[];if(L.length>0){const O=[...L].sort((F,R)=>{const S=F.archivedAt||F.createdAt||"";return(R.archivedAt||R.createdAt||"").localeCompare(S)})[0];if(O){const F=O.analysisCompletedAt||O.createdAt;if(F){const R=new Date(F).getTime(),H=Date.now()-1440*60*1e3;R>H&&(N=O.currentEntityShas||[])}}}}const A=await b(N),_=[];p.ANTHROPIC_API_KEY&&_.push("ANTHROPIC_API_KEY"),p.GROQ_API_KEY&&_.push("GROQ_API_KEY"),p.OPENAI_API_KEY&&_.push("OPENAI_API_KEY"),p.OPENROUTER_API_KEY&&_.push("OPENROUTER_API_KEY");const $=[];for(const L of y){const z=((i=L.metadata)==null?void 0:i.historicalRuns)||[];for(const O of z){const F=O.currentEntityShas||[];if(F.length>0){const R=await b(F);$.push({...O,entities:R})}else $.push(O)}}const D=$.sort((L,z)=>{const O=L.archivedAt||L.analysisCompletedAt||L.createdAt||"";return(z.archivedAt||z.analysisCompletedAt||z.createdAt||"").localeCompare(O)}),I=new Set(((c=C==null?void 0:C.entities)==null?void 0:c.map(L=>L.sha))||[]),k=D.filter(L=>!(L.currentEntityShas||[]).some(O=>I.has(O))),T=es(),j=(T==null?void 0:T.cliVersion)??"unknown",P=j!=="unknown"&&j!==Fn,B={currentRun:(d=g==null?void 0:g.metadata)==null?void 0:d.currentRun,projectSlug:u,currentEntities:A,availableAPIKeys:_,queuedJobCount:E.length,queueJobs:E,currentlyExecuting:C,historicalRuns:k,isServerOutOfDate:P,serverVersion:j};return G(B)}catch(m){return console.error("Failed to load root data:",m),G({currentRun:void 0,projectSlug:null,currentEntities:[],availableAPIKeys:[],queuedJobCount:0,queueJobs:[],currentlyExecuting:null,historicalRuns:[],isServerOutOfDate:!1,serverVersion:"unknown"})}}function cd(){const{currentRun:e,projectSlug:r,currentEntities:n,availableAPIKeys:a,queuedJobCount:o,queueJobs:s,currentlyExecuting:i,historicalRuns:c,isServerOutOfDate:d,serverVersion:m}=We(),{toasts:u,closeToast:p}=Mn(),h=rt(),f=Ee(h),y=Er();re(()=>{f.current=h},[h]);const g=y.pathname.startsWith("/entity/")&&y.pathname.includes("/edit/")||y.pathname.startsWith("/dev/"),w=y.pathname.includes("/fullscreen");return re(()=>{const x=new EventSource("/api/events");let b=null,v=0;const C=2e3;return x.addEventListener("message",E=>{const N=JSON.parse(E.data);if(N.type==="queue")f.current.revalidate(),v=Date.now();else if(N.type==="db-change"||N.type==="unknown"){const A=Date.now(),_=A-v;_<C?(b&&clearTimeout(b),b=setTimeout(()=>{f.current.revalidate(),v=Date.now(),b=null},C-_)):(f.current.revalidate(),v=A)}}),x.addEventListener("error",E=>{console.error("SSE connection error:",E)}),()=>{b&&clearTimeout(b),x.close()}},[]),l(le,{children:[l("div",{className:`min-h-screen ${g?"":"grid"} bg-cygray-10`,style:g?void 0:{gridTemplateColumns:"65px minmax(900px, 1fr)"},children:[!g&&t(tl,{}),l("div",{className:"max-h-screen overflow-auto bg-cygray-10",children:[d&&t(Yc,{serverVersion:m}),a.length===0&&t(zc,{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"}),t(Hs,{})]})]}),t(al,{toasts:u,onClose:p}),!w&&t(ol,{currentRun:e,projectSlug:r,currentEntities:n,isAnalysisStarting:!1,queuedJobCount:o,queueJobs:s,currentlyExecuting:i,historicalRuns:c})]})}const dd=Oe(function(){return l("html",{lang:"en",children:[l("head",{children:[t("meta",{charSet:"utf-8"}),t("meta",{name:"viewport",content:"width=device-width,initial-scale=1"}),t(Ys,{}),t(Bs,{})]}),l("body",{children:[t(rl,{children:t(Xi,{children:t(cd,{})})}),t(Us,{}),t(Ws,{})]})]})}),ud=Object.freeze(Object.defineProperty({__proto__:null,default:dd,links:id,loader:ld},Symbol.toStringTag,{value:"Module"}));function $a(e){const r=e.replace(/[^a-zA-Z0-9_]+/g,"_");return r.slice(0,1).toUpperCase()+r.slice(1)}function er({analysisId:e,scenarioId:r,scenarioName:n,projectSlug:a,enabled:o=!0,refreshTrigger:s=0}){const i=Ae(),[c,d]=M(null),[m,u]=M(!1),[p,h]=M(!1),[f,y]=M(!1),g=Ee(!1),w=Ee(null),x=Ee(null),[b,v]=M(0),[C,E]=M(0),N=Ee(null),A=Ee(!1),{interactiveUrl:_,resetLogs:$}=pt(a,o),D=Ee(r),I=Ee(s);re(()=>{I.current!==s&&(I.current=s,c&&(console.log("[useInteractiveMode] Manual refresh triggered"),h(!0),y(!1),v(0),E(T=>T+1),A.current=!1,N.current&&(clearTimeout(N.current),N.current=null)))},[s,c]),re(()=>{if(D.current!==r&&(D.current=r,w.current&&x.current&&n)){const T=$a(x.current),j=$a(n),P=w.current.replace(T,j);d(P),h(!0),y(!1),v(0),E(B=>B+1),A.current=!1,N.current&&(clearTimeout(N.current),N.current=null);return}},[r,n]),re(()=>{if(_){const T=_+"?width=600px";w.current=T,n&&(x.current=n),d(T),u(!1),h(!0)}},[_]),re(()=>{const T=j=>{j.data.type==="codeyam-resize"&&(A.current||(A.current=!0,N.current&&(clearTimeout(N.current),N.current=null),v(0),y(!0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{h(!1)})})))};return window.addEventListener("message",T),()=>window.removeEventListener("message",T)},[]);const k=()=>{A.current=!1,N.current&&clearTimeout(N.current);const T=500*Math.pow(2,b);N.current=setTimeout(()=>{A.current||(b<2?(v(j=>j+1),E(j=>j+1),h(!0)):(console.error("[useInteractiveMode] Interactive mode failed to load after 3 attempts - showing iframe anyway"),y(!0),h(!1)))},T)};return re(()=>{o&&!g.current&&r&&e&&(g.current=!0,u(!0),y(!1),d(null),(async()=>{if(a)try{await fetch(`/api/logs/${a}`,{method:"DELETE"})}catch(j){console.error("[useInteractiveMode] Failed to clear log file:",j)}$(),i.submit({action:"start",analysisId:e,scenarioId:r},{method:"post",action:"/api/interactive-mode"})})())},[o,r,e,$,a]),re(()=>{const T=e,j=()=>{if(g.current&&T){const B=new URLSearchParams({action:"stop",analysisId:T});console.log("[useInteractiveMode] Sending stop request via sendBeacon");const L=navigator.sendBeacon("/api/interactive-mode",B);console.log("[useInteractiveMode] sendBeacon result:",L),L||(console.log("[useInteractiveMode] sendBeacon failed, using fetch fallback"),fetch("/api/interactive-mode",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:B,keepalive:!0}).catch(z=>console.error("Failed to stop interactive mode:",z)))}},P=()=>{j()};return window.addEventListener("beforeunload",P),()=>{window.removeEventListener("beforeunload",P),console.log("[useInteractiveMode] Cleanup running:",{hasStarted:g.current,analysisId:T}),j()}},[e]),{interactiveServerUrl:c,isStarting:m,isLoading:p,showIframe:f,iframeKey:C,onIframeLoad:k}}const sr=10,hd=1024;function ts({currentViewportWidth:e,currentPresetName:r,onDevicePresetClick:n,devicePresets:a,onHoverChange:o,hideLabel:s=!1,lightMode:i=!1}){const[c,d]=M(null),m=Ee(null),u=ne(()=>[...a].sort((b,v)=>b.width-v.width),[a]),{fittingPresets:p,overflowPresets:h}=ne(()=>{const b=[],v=[];for(const C of u)C.width<=hd?b.push(C):v.push(C);return v.sort((C,E)=>E.width-C.width),{fittingPresets:b,overflowPresets:v}},[u]),f=se(b=>{if(!m.current)return null;const v=m.current.getBoundingClientRect(),C=b-v.left,E=v.width,N=E/2,_=(p.length>0?p[p.length-1].width:0)/2,$=N-_,D=N+_,I=h.length>0?(h.length-1)*sr:0;if(h.length>0){if(C<$){if(C<=I){const T=Math.min(Math.floor(C/sr),h.length-1);return h[T]}return h[h.length-1]}if(C>D){const T=E-C;if(T<=I){const j=Math.min(Math.floor(T/sr),h.length-1);return h[j]}return h[h.length-1]}}const k=Math.abs(C-N);for(let T=p.length-1;T>=0;T--){const j=p[T],P=p[T-1],B=j.width/2,L=P?P.width/2:0;if(k<=B&&k>=L)return j}return p[0]||h[h.length-1]||null},[p,h]),y=se(b=>{const v=f(b.clientX);d(v),o==null||o(v)},[f,o]),g=se(()=>{d(null),o==null||o(null)},[o]),w=se(b=>{const v=f(b.clientX);v&&n(v)},[f,n]),x=c||{name:r,width:e};return l("div",{ref:m,className:"relative h-6 shrink-0 overflow-hidden cursor-pointer",onMouseMove:y,onMouseLeave:g,onClick:w,children:[c&&t("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:t("div",{className:"h-full transition-all duration-100 bg-[#005C75]",style:{width:`${c.width}px`}})}),t("div",{className:"absolute inset-0 pointer-events-none",children:p.map(b=>{const v=b.width===e,C=(c==null?void 0:c.name)===b.name,E=b.width/2;return l("div",{children:[t("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% - ${E}px)`},children:t("div",{className:`w-0.5 h-full transition-colors duration-75 ${v||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),t("div",{className:"absolute top-0 bottom-0",style:{left:`calc(50% + ${E}px)`},children:t("div",{className:`w-0.5 h-full transition-colors duration-75 ${v||C?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),t("div",{className:"absolute inset-0 pointer-events-none",children:h.map((b,v)=>{const C=v*sr,E=b.width===e,N=(c==null?void 0:c.name)===b.name;return l("div",{children:[t("div",{className:"absolute top-0 bottom-0",style:{left:`${C}px`},children:t("div",{className:`w-0.5 h-full transition-colors duration-75 ${E||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})}),t("div",{className:"absolute top-0 bottom-0",style:{right:`${C}px`},children:t("div",{className:`w-0.5 h-full transition-colors duration-75 ${E||N?i?"bg-gray-900":"bg-white":i?"bg-[rgba(0,0,0,0.2)]":"bg-[rgba(255,255,255,0.3)]"}`})})]},b.name)})}),!s&&t("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:l("div",{className:`text-[10px] px-2 py-0.5 rounded shadow-sm whitespace-nowrap transition-colors ${c?"bg-[#005c75] text-white":"bg-white/90 text-[#005c75] border border-[rgba(0,92,117,0.25)]"}`,children:[x.name," - ",x.width,"px"]})})]})}function rs({width:e,height:r,onSave:n,onCancel:a}){const[o,s]=M(""),[i,c]=M(""),d=()=>{const u=o.trim();if(!u){c("Please enter a name for this custom size");return}n(u)};return t("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:l("div",{className:"bg-white rounded-lg max-w-md w-full p-6 shadow-xl",children:[l("div",{className:"flex items-center justify-between mb-6",children:[t("h2",{className:"text-xl font-semibold text-gray-900",children:"Save Custom Size"}),t("button",{onClick:a,className:"text-gray-400 hover:text-gray-600 transition-colors cursor-pointer","aria-label":"Close",children:t("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),l("div",{className:"mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200",children:[t("div",{className:"text-sm text-gray-500 mb-1",children:"Dimensions"}),l("div",{className:"text-lg font-medium text-gray-900",children:[e,"px × ",r,"px"]})]}),l("div",{className:"mb-6",children:[t("label",{htmlFor:"custom-size-name",className:"block text-sm font-medium text-gray-700 mb-2",children:"Name"}),t("input",{id:"custom-size-name",type:"text",value:o,onChange:u=>{s(u.target.value),c("")},onKeyDown:u=>{u.key==="Enter"&&o.trim()&&d(),u.key==="Escape"&&a()},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&&t("p",{className:"mt-1 text-sm text-red-600",children:i})]}),l("div",{className:"flex gap-3 justify-end",children:[t("button",{onClick:a,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 cursor-pointer",children:"Cancel"}),t("button",{onClick:d,disabled:!o.trim(),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 cursor-pointer disabled:bg-gray-300 disabled:cursor-not-allowed",children:"Save"})]})]})})}function ns(e){const[r,n]=M([]),a=e?`codeyam-custom-sizes-${e}`:null;re(()=>{if(!a||typeof window>"u"){n([]);return}try{const c=localStorage.getItem(a);if(c){const d=JSON.parse(c);Array.isArray(d)&&n(d)}}catch(c){console.error("[useCustomSizes] Failed to load custom sizes:",c),n([])}},[a]);const o=se(c=>{if(!(!a||typeof window>"u"))try{localStorage.setItem(a,JSON.stringify(c))}catch(d){console.error("[useCustomSizes] Failed to save custom sizes:",d)}},[a]),s=se((c,d,m)=>{n(u=>{const p=u.findIndex(y=>y.name===c),h={name:c,width:d,height:m};let f;return p>=0?(f=[...u],f[p]=h):f=[...u,h],o(f),f})},[o]),i=se(c=>{n(d=>{const m=d.filter(u=>u.name!==c);return o(m),m})},[o]);return{customSizes:r,addCustomSize:s,removeCustomSize:i}}function vr(){return l("div",{className:"spinner-container",children:[t("span",{className:"loader"}),t("style",{children:`
|
|
40
|
-
.loader {
|
|
41
|
-
width: 48px;
|
|
42
|
-
height: 48px;
|
|
43
|
-
border: 3px solid rgba(0, 92, 117, 0.2);
|
|
44
|
-
border-radius: 50%;
|
|
45
|
-
display: inline-block;
|
|
46
|
-
position: relative;
|
|
47
|
-
box-sizing: border-box;
|
|
48
|
-
animation: rotation 1s linear infinite;
|
|
49
|
-
}
|
|
50
|
-
.loader::after {
|
|
51
|
-
content: '';
|
|
52
|
-
box-sizing: border-box;
|
|
53
|
-
position: absolute;
|
|
54
|
-
left: 50%;
|
|
55
|
-
top: 50%;
|
|
56
|
-
transform: translate(-50%, -50%);
|
|
57
|
-
width: 56px;
|
|
58
|
-
height: 56px;
|
|
59
|
-
border-radius: 50%;
|
|
60
|
-
border: 3px solid;
|
|
61
|
-
border-color: #005c75 transparent;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
@keyframes rotation {
|
|
65
|
-
0% {
|
|
66
|
-
transform: rotate(0deg);
|
|
67
|
-
}
|
|
68
|
-
100% {
|
|
69
|
-
transform: rotate(360deg);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
`})]})}const ja=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],md=80;function Cr(){const[e,r]=M(0);return re(()=>{const n=setInterval(()=>{r(a=>(a+1)%ja.length)},md);return()=>clearInterval(n)},[]),t("span",{className:"inline-block mr-2",children:ja[e]})}async function pd({params:e}){var c;const{sha:r,scenarioId:n}=e;if(!r||!n)throw G("Invalid parameters",{status:400});const a=await _t(r);if(!a)throw G("Entity not found",{status:404});const o=await jn(a),s=((c=o==null?void 0:o.scenarios)==null?void 0:c.find(d=>d.id===n))||null;if(!s)throw G("Scenario not found",{status:404});const i=await ze();return G({entity:a,scenario:s,analysis:o,projectSlug:i})}const en=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],fd=Oe(function(){const{entity:r,scenario:n,analysis:a,projectSlug:o}=We(),s=Mt(),[i]=Jt(),[c,d]=M(null),[m,u]=M(1440),[p,h]=M({name:"Desktop",width:1440,height:900}),[f,y]=M(!1),[g,w]=M(null),{customSizes:x,addCustomSize:b}=ns(o),v=ne(()=>[...en,...x],[x]),{interactiveServerUrl:C,isStarting:E,isLoading:N,showIframe:A,iframeKey:_,onIframeLoad:$}=er({analysisId:a==null?void 0:a.id,scenarioId:n==null?void 0:n.id,scenarioName:n==null?void 0:n.name,projectSlug:o,enabled:!0}),{lastLine:D}=pt(o,E||N),I=()=>{s(`/entity/${r.sha}`)},k=(q,J)=>{u(q);const ae=v.find(Y=>Y.width===q&&Y.height===J);d(ae||null),h({name:(ae==null?void 0:ae.name)||"Custom",width:q,height:J})},T=q=>{d(q),u(q.width),h({name:q.name,width:q.width,height:q.height})},j=q=>{b(q,p.width,p.height??900),y(!1),h(J=>({...J,name:q}))},P=((a==null?void 0:a.scenarios)||[]).filter(q=>{var J;return!((J=q.metadata)!=null&&J.sameAsDefault)}),B=P.findIndex(q=>q.id===(n==null?void 0:n.id)),L=B+1,z=P.length,O=B>0,F=B<P.length-1,R=()=>{if(O){const q=P[B-1],J=encodeURIComponent(`/entity/${r.sha}/scenarios/${q.id}/fullscreen`);s(`/entity/${r.sha}/scenarios/${q.id}/fullscreen?from=${J}`)}},S=()=>{if(F){const q=P[B+1],J=encodeURIComponent(`/entity/${r.sha}/scenarios/${q.id}/fullscreen`);s(`/entity/${r.sha}/scenarios/${q.id}/fullscreen?from=${J}`)}},H=E||N||!A;return l("div",{className:"fixed inset-0 bg-[#2d2d2d] flex flex-col",children:[l("div",{className:"bg-[#3d3d3d] h-12 flex items-center px-4 gap-4 shrink-0 z-20",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[t("img",{src:vo,alt:"CodeYam",className:"h-6 brightness-0 invert"}),t("span",{className:"text-white font-medium text-sm whitespace-nowrap",children:r.name}),l("div",{className:"flex items-center gap-2 shrink-0",children:[t("button",{onClick:R,disabled:!O,className:`${O?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Previous scenario",children:t("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:t("path",{d:"M12.5 15L7.5 10L12.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:"text-gray-400 text-sm",children:[L,"/",z]}),t("button",{onClick:S,disabled:!F,className:`${F?"text-white hover:text-gray-300":"text-gray-600 cursor-not-allowed"} transition-colors`,"aria-label":"Next scenario",children:t("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:t("path",{d:"M7.5 15L12.5 10L7.5 5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),l("div",{className:"flex items-center gap-2 ml-2 min-w-0",children:[t("span",{className:"text-white font-semibold text-xs whitespace-nowrap shrink-0",children:n==null?void 0:n.name}),(n==null?void 0:n.description)&&l("div",{className:"relative group min-w-0",children:[t("span",{className:"text-gray-400 text-xs truncate block",children:n.description}),t("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:n.description})]})]})]}),t("button",{onClick:I,className:"text-white hover:text-gray-300 transition-colors ml-4","aria-label":"Close fullscreen",children:t("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:t("path",{d:"M15 5L5 15M5 5L15 15",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})})]}),l("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:[t("div",{className:"absolute inset-0 flex justify-center",children:t("div",{style:{maxWidth:`${en[en.length-1].width}px`,width:"100%"},children:t(ts,{currentViewportWidth:m,currentPresetName:p.name,onDevicePresetClick:T,devicePresets:v,hideLabel:!0,onHoverChange:w,lightMode:!0})})}),l("div",{className:"relative z-10 flex items-center gap-2",children:[l("div",{className:"relative w-28 h-5",children:[l("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:[t("span",{className:"leading-none",children:(g==null?void 0:g.name)||p.name}),t("svg",{width:"10",height:"10",viewBox:"0 0 12 12",fill:"none",className:"shrink-0",children:t("path",{d:"M3 4.5L6 7.5L9 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l("select",{value:p.name,onChange:q=>{const J=v.find(ae=>ae.name===q.target.value);J&&T(J)},className:"relative w-full h-full opacity-0 cursor-pointer",children:[v.map(q=>t("option",{value:q.name,children:q.name},q.name)),p.name==="Custom"&&t("option",{value:"Custom",children:"Custom"})]})]}),t("input",{type:"number",value:p.width,onChange:q=>{const J=parseInt(q.target.value,10);!isNaN(J)&&J>0&&k(J,p.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"}),t("span",{className:"text-gray-400 text-xs h-5 flex items-center leading-none",children:"×"}),t("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:p.height??900}),p.name==="Custom"&&t("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"})]})]}),t("div",{className:"flex-1 flex items-center justify-center overflow-auto p-8",style:{backgroundImage:`
|
|
73
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
74
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
75
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
76
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
77
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:C?l("div",{className:"relative bg-white w-full h-full",style:{maxWidth:`${p.width}px`,maxHeight:`${p.height}px`},children:[H&&t("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[t("div",{className:"mb-4",children:t(vr,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[t("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),t("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),D&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[t(Cr,{}),D]})]})]})}),t("iframe",{src:C,className:"w-full h-full border-none",title:`Interactive preview: ${n==null?void 0:n.name}`,onLoad:$,style:{opacity:A?1:0}},_)]}):l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[t("div",{className:"mb-4",children:t(vr,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[t("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),t("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),D&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[t(Cr,{}),D]})]})]})}),f&&t(rs,{width:p.width,height:p.height??900,onSave:j,onCancel:()=>y(!1)})]})}),gd=Object.freeze(Object.defineProperty({__proto__:null,default:fd,loader:pd},Symbol.toStringTag,{value:"Module"})),as=bn({dimensions:{height:720,width:1200},updateDimensions:()=>{},iframeRef:{current:null},scale:1,updateScale:()=>{},maxWidth:1200,updateMaxWidth:()=>{}}),On=()=>{const e=Ar(as);if(!e)throw new Error("useWebContainer must be used within a WebContainerProvider");return e},Rr=({children:e})=>{const[r,n]=M({height:720,width:1200}),[a,o]=M(1),[s,i]=M(1200),c=Ee(null),d=se(({height:p,width:h})=>{n(f=>({height:p??f.height,width:h??f.width}))},[]),m=se(p=>{o(p)},[]),u=se(p=>{i(p)},[]);return t(as.Provider,{value:{dimensions:r,updateDimensions:d,iframeRef:c,scale:a,updateScale:m,maxWidth:s,updateMaxWidth:u},children:e})},yd=typeof window<"u";function xd(){const[e,r]=M(null);return re(()=>{import("react-resizable").then(n=>{r(()=>n.ResizableBox)}),Promise.resolve({ })},[]),e}const bd=1200,wd=720,Ra=30,vd=({id:e,scenarioName:r,iframeUrl:n,defaultWidth:a=1440,defaultHeight:o=900,onDataOverride:s,onIframeLoad:i,onScaleChange:c,onDimensionChange:d})=>{const m=xd(),[u,p]=M(!1),[h,f]=M(!1),[y,g]=M(bd),[w,x]=M(wd),[b,v]=M(null),[C,E]=M(null),{dimensions:N,updateDimensions:A,iframeRef:_,updateScale:$,updateMaxWidth:D}=On(),I=ne(()=>Math.min(1,y/N.width),[y,N.width]),k=C!==null?C:I;re(()=>{u||($(k),c==null||c(k))},[k,$,c,u]),re(()=>{D(y)},[y,D]);const T=se(()=>{p(!0),E(I)},[I]),j=se(()=>{p(!1),E(null)},[]),P=se((F,R)=>{const S=C!==null?C:1,H=Math.round(R.size.width/S);A({width:H}),d==null||d(H,N.height)},[A,C,d,N.height]),B=se(()=>{setTimeout(()=>{f(!0)},100),i&&i()},[i]);re(()=>{const F=R=>{if(R.data.type==="codeyam-resize"){if(r&&R.data.name!==r||N.height===R.data.height||R.data.height===0)return;A({height:R.data.height})}};return window.addEventListener("message",F),()=>{window.removeEventListener("message",F)}},[_,r,a,N,A]),re(()=>{h&&s&&s(_.current)},[h,s,_]),re(()=>{if(!r)return;const F=setInterval(()=>{var R,S;(S=(R=_==null?void 0:_.current)==null?void 0:R.contentWindow)==null||S.postMessage({type:"codeyam-respond",name:r},"*")},1e3);return()=>clearInterval(F)},[r,_]),re(()=>{const F=()=>{const R=document.getElementById("scenario-container");if(!R)return;const S=R.getBoundingClientRect(),H=R.clientWidth-Ra*2,q=window.innerHeight-S.top-Ra*2,J=Math.max(q,400),ae=window.innerHeight-S.top;g(H),x(J),v(ae)};return F(),window.addEventListener("resize",F),()=>window.removeEventListener("resize",F)},[]),re(()=>{A({width:a,height:o})},[a,o,A]);const L=ne(()=>N.width*k,[N.width,k]),z=ne(()=>{const F=N.height,R=F*k;return F&&F!==720&&F!==900&&R<w?R:w},[N.height,w,k]),O=se(()=>{window.history.back()},[]);return!yd||!m?t("div",{className:"relative bg-gray-100 w-full h-full flex items-center justify-center",children:t("p",{className:"text-gray-500",children:"Loading interactive view..."})}):l("div",{id:"scenario-container",className:"relative bg-gray-100 w-full flex items-center justify-center",style:b?{height:`${b}px`}:{},children:[u&&t("div",{className:"fixed inset-0 z-50 bg-transparent"}),t("style",{children:`
|
|
78
|
-
.react-resizable-handle-e {
|
|
79
|
-
display: flex !important;
|
|
80
|
-
align-items: center !important;
|
|
81
|
-
justify-content: center !important;
|
|
82
|
-
width: 6px !important;
|
|
83
|
-
height: 48px !important;
|
|
84
|
-
right: -8px !important;
|
|
85
|
-
top: 50% !important;
|
|
86
|
-
transform: translateY(-50%) !important;
|
|
87
|
-
cursor: ew-resize !important;
|
|
88
|
-
background: #d1d5db !important;
|
|
89
|
-
border-radius: 3px !important;
|
|
90
|
-
opacity: 0 !important;
|
|
91
|
-
transition: all 0.2s ease !important;
|
|
92
|
-
}
|
|
93
|
-
.react-resizable-handle-e:hover {
|
|
94
|
-
opacity: 0.8 !important;
|
|
95
|
-
background: #9ca3af !important;
|
|
96
|
-
}
|
|
97
|
-
.react-resizable:hover .react-resizable-handle-e {
|
|
98
|
-
opacity: 0.4 !important;
|
|
99
|
-
}
|
|
100
|
-
`}),t(m,{width:L,height:z,minConstraints:[300,200],maxConstraints:[y,w],className:"relative bg-white rounded-lg shadow-md",resizeHandles:["e"],onResizeStart:T,onResizeStop:j,onResize:P,children:t("div",{className:"overflow-auto",style:{width:`${L}px`,height:`${z}px`},children:t("div",{style:{width:`${N.width}px`,height:`${N.height}px`,transform:`scale(${k})`,transformOrigin:"top left"},children:n?t("iframe",{ref:_,className:"w-full h-full rounded-lg",src:n,onLoad:B,sandbox:"allow-scripts allow-same-origin"}):l("p",{className:"w-full h-full flex flex-col gap-3 items-center justify-center",children:[t("span",{className:"text-xl font-light",children:"Oops! Looks like this scenario is not available yet. Please check back later."}),t("span",{className:"text-blue-600 cursor-pointer",onClick:O,children:"Go back"})]})})})},`resizable-box-${e}`)]})};function Cd({presets:e,customSizes:r,currentWidth:n,currentHeight:a,scale:o,onSizeChange:s,onSaveCustomSize:i,onRemoveCustomSize:c,className:d=""}){const[m,u]=M(!1),[p,h]=M(String(n)),[f,y]=M(String(a)),[g,w]=M(!1),[x,b]=M(!1),v=Ee(null);re(()=>{g||h(String(n))},[n,g]),re(()=>{x||y(String(a))},[a,x]),re(()=>{const k=T=>{v.current&&!v.current.contains(T.target)&&u(!1)};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[]);const C=ne(()=>{const k=e.find(j=>j.width===n&&j.height===a);if(k)return k.name;const T=r.find(j=>j.width===n&&j.height===a);return T?T.name:"Custom"},[e,r,n,a]),E=C==="Custom",N=k=>{s(k.width,k.height),u(!1)},A=k=>{const T=k.target.value;h(T);const j=parseInt(T,10);!isNaN(j)&&j>0&&s(j,a)},_=k=>{const T=k.target.value;y(T);const j=parseInt(T,10);!isNaN(j)&&j>0&&s(n,j)},$=()=>{w(!1);const k=parseInt(p,10);(isNaN(k)||k<=0)&&h(String(n))},D=()=>{b(!1);const k=parseInt(f,10);(isNaN(k)||k<=0)&&y(String(a))},I=k=>{(k.key==="Enter"||k.key==="Escape")&&k.target.blur()};return l("div",{className:`flex items-center gap-3 ${d}`,children:[l("div",{className:"relative",ref:v,children:[l("button",{onClick:()=>u(!m),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:[t("span",{children:C}),t("svg",{className:`w-4 h-4 transition-transform ${m?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),m&&t("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:l("div",{className:"py-1",children:[e.length>0&&l(le,{children:[t("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Presets"}),e.map(k=>l("button",{onClick:()=>N(k),className:`w-full text-left px-3 py-2 text-sm hover:bg-gray-100 flex justify-between items-center gap-4 whitespace-nowrap ${C===k.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[t("span",{children:k.name}),l("span",{className:"text-xs text-gray-500",children:[k.width," x ",k.height]})]},k.name))]}),r.length>0&&l(le,{children:[t("div",{className:"border-t border-gray-100 my-1"}),t("div",{className:"px-3 py-1 text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap",children:"Custom"}),[...r].sort((k,T)=>k.width-T.width).map(k=>l("div",{className:`flex items-center gap-1 hover:bg-gray-100 ${C===k.name?"bg-[#f0f7f9] text-[#005c75]":"text-gray-700"}`,children:[l("button",{onClick:()=>N(k),className:"flex-1 text-left px-3 py-2 text-sm flex justify-between items-center gap-4 whitespace-nowrap cursor-pointer",children:[t("span",{children:k.name}),l("span",{className:"text-xs text-gray-500",children:[k.width," x ",k.height]})]}),c&&t("button",{onClick:T=>{T.stopPropagation(),C===k.name&&e.length>0&&s(e[0].width,e[0].height),c(k.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:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},k.name))]})]})})]}),l("div",{className:"flex items-center gap-1 text-sm",children:[l("div",{className:"flex items-center",children:[t("input",{type:"text",value:p,onChange:A,onFocus:()=>w(!0),onBlur:$,onKeyDown:I,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]"}),t("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"})]}),t("span",{className:"text-gray-400 mx-1",children:"×"}),l("div",{className:"flex items-center",children:[t("input",{type:"text",value:f,onChange:_,onFocus:()=>b(!0),onBlur:D,onKeyDown:I,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]"}),t("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"})]}),o!==void 0&&o<1&&l("span",{className:"text-xs text-gray-500 ml-1",children:["(",Math.round(o*100),"%)"]})]}),E&&t("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 tn(e,r,n){if(Array.isArray(e)){if(!isNaN(parseInt(r)))return e[parseInt(r)];for(const a of e)if(a.name===r||a.title===r||a.id===r)return a}return e[r]}function hn(e){return e&&(typeof e=="object"||Array.isArray(e))}function Nd(e){return Array.isArray(e)?e.length:void 0}function Sd(e){const{data:r,structure:n}=e;if(!(!r&&!n)){if(Array.isArray(n))return Array.isArray(r)?r.map((a,o)=>o.toString()):[];if(typeof n=="object")return[...new Set([...Object.keys(r),...Object.keys(n)])].sort((o,s)=>{const i=hn(r[o]),c=hn(r[s]);return i&&!c?1:!i&&c?-1:o.localeCompare(s)});if(typeof r=="object")return Object.keys(r).sort((o,s)=>o.localeCompare(s))}}function Ed({scenarioFormData:e,handleInputChange:r}){return l("div",{className:"p-3 flex flex-col gap-3",children:[l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[t("label",{htmlFor:"name",className:"text-sm font-medium text-gray-700",children:"Name"}),t("input",{type:"text",id:"name",placeholder:"Name",name:"name",value:e.name,onChange:r,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"})]}),l("div",{className:"grid w-full gap-1.5 pt-2",children:[t("label",{htmlFor:"description",className:"text-sm font-medium text-gray-700",children:"Description"}),t("textarea",{placeholder:"Type your message here.",id:"description",name:"description",value:e.description,onChange:r,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]"})]}),t("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 Ad({path:e,namedPath:r,isArray:n,count:a,onClick:o}){const s=se(()=>{o&&o(e)},[o,e]);return l("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:s,children:[l("div",{className:"flex items-center gap-3",children:[n&&t("svg",{className:"w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})}),l("div",{className:"capitalize font-medium text-gray-900",children:[r[r.length-1],a!==void 0&&` (${a})`]})]}),l("div",{className:"flex items-center gap-3",children:[n&&t("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:t("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"})}),t("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]})]})}var os=(e=>(e.STRING="string",e.NUMBER="number",e.BOOLEAN="boolean",e.UNION="union",e.OBJECT="object",e.ARRAY="array",e))(os||{});const kd=({name:e,value:r,options:n,onChange:a})=>{const o=se(s=>{a({target:{name:e,value:s.target.value}})},[e,a]);return t("select",{name:e,value:r,onChange:o,className:"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",children:n.map((s,i)=>t("option",{value:s.trim(),children:s.trim()},i))})},Pd=({name:e,value:r,onChange:n})=>{const a=se(o=>{const s=o.target.checked;n({target:{name:e,value:s}})},[e,n]);return t("label",{className:"flex items-center gap-2 cursor-pointer",children:t("input",{type:"checkbox",name:e,checked:r,onChange:a,className:`w-10 h-6 rounded-full appearance-none cursor-pointer transition-colors relative
|
|
101
|
-
bg-gray-300 checked:bg-blue-600
|
|
102
|
-
after:content-[''] after:absolute after:top-1 after:left-1 after:w-4 after:h-4
|
|
103
|
-
after:bg-white after:rounded-full after:transition-transform
|
|
104
|
-
checked:after:translate-x-4`})})};function _d({dataType:e,path:r,value:n,onChange:a}){const o=ne(()=>r[r.length-1],[r]),s=ne(()=>r.join("-"),[r]),i=se(d=>{a(r,d.target.value)},[a,r]),c=se(d=>{a(r,d.target.value)},[a,r]);return l("div",{className:"grid w-full max-w-sm items-center gap-1.5",children:[t("label",{htmlFor:s,className:"capitalize text-sm font-medium text-gray-700",children:o==="~~codeyam-code~~"?"Dynamic Field":o}),e.includes("|")?t(kd,{name:s,value:n,options:e.split("|"),onChange:i}):e===os.BOOLEAN?t(Pd,{name:s,value:n??!1,onChange:c}):t("input",{id:s,name:s,type:"text",value:JSON.stringify(n??"").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-${s}`)]})}function Md({analysis:e,scenarioName:r,dataItem:n,onResult:a,onGenerateData:o}){const[s,i]=M(!1),[c,d]=M(""),m=se(async()=>{if(!o){console.error("onGenerateData prop is required for AI data generation");return}i(!0);try{const p=e.scenarios.find(w=>w.name===r);if(!p)throw new Error("Scenario not found");const h=e.scenarios.find(w=>w.name===_r),f=await o(c,n);if(!f){console.error("Error getting AI guess for scenario data"),i(!1);return}const y=(w,x)=>{const b=Object.assign({},w);return g(w)&&g(x)&&Object.keys(x).forEach(v=>{g(x[v])?v in w?b[v]=y(w[v],x[v]):Object.assign(b,{[v]:x[v]}):Object.assign(b,{[v]:x[v]})}),b},g=w=>w&&typeof w=="object"&&!Array.isArray(w);p.metadata.data=y(y((h==null?void 0:h.metadata.data)||{},p.metadata.data),f.data||{}),a(p),i(!1),d("")}catch(p){console.error("Error generating AI data:",p),i(!1)}},[e,c,n,r,a,o]),u=se(p=>{d(p.target.value)},[]);return l("div",{className:"w-full p-3 flex flex-col gap-2 rounded-lg border-2 border-blue-200 text-sm bg-blue-50",children:[t("div",{className:"font-medium text-gray-700",children:"Describe the data changes to the AI"}),t("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:c}),t("button",{type:"button",disabled:s,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 ${c.length>0?"flex":"hidden peer-focus-within:flex"} items-center justify-center gap-2`,onClick:()=>void m(),children:s?l(le,{children:[l("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:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("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 Td({namedPath:e,path:r,last:n,onClick:a}){const o=se(()=>a(n?r.slice(0,-1):r),[n,r,a]);return t("div",{className:"capitalize cursor-pointer hover:text-blue-600 transition-colors",onClick:o,children:e[e.length-1]})}function Id({dataItem:e,onClick:r}){const n=se(()=>r([]),[r]),a=ne(()=>e.namedPath.length>=2?e.namedPath.length-2:0,[e]);return l("div",{className:"text-sm flex items-center gap-2 py-3 px-2 border-b border-t border-gray-300 bg-gray-50",children:[t("svg",{className:"w-4 h-4 cursor-pointer hover:text-blue-600",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",onClick:n,children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})}),e.namedPath.length>2&&l("div",{className:"flex items-center gap-1",children:[t("div",{children:"..."}),t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]}),e.namedPath.slice(a).map((o,s)=>l("div",{className:"flex items-center gap-1",children:[t(Td,{namedPath:e.namedPath.slice(0,s+a+1),path:e.path.slice(0,s+a+1),last:s+a===e.namedPath.length-1,onClick:r}),s+a<e.namedPath.length-1&&t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})]},`path-${o}-${s+a}`))]})}function Da({analysis:e,scenarioName:r,dataItem:n,onClick:a,onChange:o,onAIResult:s,onGenerateData:i,saveFeedback:c}){const d=ne(()=>n.data,[n]),m=ne(()=>Sd(n),[n]);return l("div",{className:"w-full flex flex-col gap-6 px-3 mt-3",children:[n.path.length>0&&t(Id,{dataItem:n,onClick:a}),l("div",{className:"flex flex-col gap-3",children:[t(Md,{analysis:e,scenarioName:r,dataItem:n,onResult:s,onGenerateData:i}),m==null?void 0:m.map((u,p)=>{var f;if(hn(d[u])){let y=u;isNaN(Number(u))||(y=d[u].name??d[u].title??d[u].id??`${n.path[n.path.length-1].replace(/s$/,"")} ${parseInt(u)+1}`);const g=[...n.path,u],w=[...n.namedPath,y];return t(Ad,{path:g,namedPath:w,isArray:Array.isArray(d),count:Nd(d[u]),onClick:a},`data-${u}-${p}`)}if(u==="id")return null;const h=[...n.path,u];return t(_d,{dataType:((f=n.structure)==null?void 0:f[u])??"string",path:h,value:d[u],onChange:o},`InputField-${h.join("-")}`)})]}),t("input",{type:"hidden",name:"recapture",id:"recapture-input",value:"false"}),l("div",{className:"flex gap-2",children:[t("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="false")},disabled:c==null?void 0:c.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:c!=null&&c.isSaving?"Saving...":"Save Changes"}),t("button",{type:"submit",onClick:()=>{const u=document.getElementById("recapture-input");u&&(u.value="true")},disabled:c==null?void 0:c.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"})]}),(c==null?void 0:c.message)&&!(c!=null&&c.isSaving)&&t("div",{className:`mt-3 p-3 rounded-md text-sm font-medium ${c.isError?"bg-red-50 text-red-700 border border-red-200":"bg-green-50 text-green-700 border border-green-200"}`,children:c.message})]})}function La({title:e,children:r,defaultOpen:n=!1,borderT:a=!1,borderB:o=!1}){const[s,i]=M(n),c=[];return a&&c.push("border-t"),o&&c.push("border-b"),l("div",{className:`${c.join(" ")} border-gray-300`,children:[l("button",{type:"button",onClick:()=>i(!s),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:[t("span",{children:e}),t("svg",{className:`transition-transform ${s?"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:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),s&&t("div",{className:"px-4 py-3",children:r})]})}const $d=({currentScenario:e,defaultScenario:r,dataStructure:n,analysis:a,shouldCreateNewScenario:o,onSave:s,onNavigate:i,iframeRef:c,onGenerateData:d,saveFeedback:m})=>{const u=se((A,_)=>{const $=Object.assign({},A),D=I=>I&&typeof I=="object"&&!Array.isArray(I);return D(A)&&D(_)&&Object.keys(_).forEach(I=>{D(_[I])?I in A?$[I]=u(A[I],_[I]):Object.assign($,{[I]:_[I]}):Object.assign($,{[I]:_[I]})}),$},[]),[p,h]=M({name:e.name,description:e.description,data:u(r.metadata.data,e.metadata.data)}),[f,y]=M(null),g=ne(()=>({...p.data}),[p]),w=ne(()=>({...g.mockData?{"Retrieved Data":g.mockData}:{},...g.argumentsData?{"Function Arguments":g.argumentsData}:{}}),[g]),x=ne(()=>{const A={...n.arguments?{"Function Arguments":n.arguments}:{},...n.dataForMocks?{"Retrieved Data":n.dataForMocks}:{}};return Object.keys(A).reduce((_,$)=>{if($.includes(".")){const[D,I]=$.split(".");_[D]||(_[D]={}),_[D][I]=A[$]}else _[$]=A[$];return _},{})},[n]),b=se(async A=>{A.preventDefault();const _=A.target.querySelector('input[name="recapture"]'),$=(_==null?void 0:_.value)==="true",D={mockData:p.data.mockData??{},argumentsData:p.data.argumentsData??[]};console.log("[ScenarioEditor] Saving scenario data:",{scenarioName:p.name,shouldRecapture:$,dataToSave:D,rawFormData:p.data,iframePayload:{arguments:g.argumentsData??[],...g.mockData??{}}}),console.log("[ScenarioEditor] Full dataToSave JSON:",JSON.stringify(D,null,2).substring(0,1e3));const I=a==null?void 0:a.scenarios.map(k=>!o&&k.name===e.name?{...k,name:p.name,description:p.description,metadata:{...k.metadata,data:D}}:k);o&&I.push({name:p.name,description:p.description,metadata:{data:D,interactiveExamplePath:a==null?void 0:a.scenarios[0].metadata.interactiveExamplePath}}),console.log("[ScenarioEditor] Updated scenarios to save:",I),s&&await s(I,{recapture:$}),i&&i(p.name)},[a,e.name,p,g,o,s,i]),v=se(A=>{h(_=>({..._,[A.target.name]:A.target.value}))},[]),C=se(A=>{y(_=>{if(!_)return null;for(const $ of[{arguments:A.metadata.data.argumentsData},A.metadata.data.mockData]){let D=$;for(const I of _.path)if(D=tn(D,I),!D)break;D&&(_.data=D)}return{..._}}),h({name:A.name,description:A.description,data:A.metadata.data})},[]),E=se((A,_)=>{h($=>{for(const D of[{"Function Arguments":$.data.argumentsData},{"Retrieved Data":$.data.mockData}]){let I=D;for(const k of A.slice(0,-1))if(I=tn(I,k),!I)break;if(I){const k=I[A[A.length-1]];y(T=>T?(T.namedPath[T.namedPath.length-1]===k&&(T.namedPath[T.namedPath.length-1]=_.toString()),T.data[A[A.length-1]]=_,{...T}):null),I[A[A.length-1]]=_}}return{...$}})},[]),N=se(A=>{var I,k,T;if(A.length===0){y(null);return}let _=w;const $=[];let D=x;for(const j of A){if($.push(isNaN(parseInt(j))?j:((I=_[j])==null?void 0:I.name)??((k=_[j])==null?void 0:k.title)??((T=_[j])==null?void 0:T.id)??j),_=tn(_,j),!_){console.log("Data not found",_,j),y(null);return}Array.isArray(D)?D=D[0]:D=D[j]}y({path:A,namedPath:$,data:_,structure:D})},[w,x]);return re(()=>{const A=_=>{var $;_.data.type==="codeyam-log"&&(($=_.data.data)!=null&&$.includes("Error"))&&console.error("[ScenarioEditor] Error from iframe:",_.data.data)};return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},[]),re(()=>{var A;if((A=c==null?void 0:c.current)!=null&&A.contentWindow){const _={arguments:g.argumentsData??[],...g.mockData??{}},$={type:"codeyam-override-data",name:e.name,data:JSON.stringify(_)};console.log("[ScenarioEditor] → SENDING codeyam-override-data:",{type:$.type,name:$.name,dataPreview:JSON.stringify(_).substring(0,200)+"...",fullData:_}),c.current.contentWindow.postMessage($,"*")}},[g,e,c]),t("form",{method:"post",onSubmit:A=>void b(A),children:f?t(Da,{analysis:a,scenarioName:p.name,dataItem:f,onClick:N,onChange:E,onAIResult:C,onGenerateData:d,saveFeedback:m}):l(le,{children:[t(La,{title:"Edit Name and Description",borderT:!0,children:t(Ed,{scenarioFormData:p,handleInputChange:v})}),e.metadata.data&&t(La,{title:"Edit Scenario Data",defaultOpen:!0,borderT:!0,borderB:!0,children:t(Da,{analysis:a,scenarioName:p.name,dataItem:{path:[],namedPath:[],data:w,structure:x},onClick:N,onChange:E,onAIResult:C,onGenerateData:d,saveFeedback:m})})]})})};function Dr({scenarioId:e,scenarioName:r,iframeUrl:n,isStarting:a,isLoading:o,showIframe:s,iframeKey:i,onIframeLoad:c,onScaleChange:d,onDimensionChange:m,projectSlug:u,defaultWidth:p=1440,defaultHeight:h=900,retryCount:f=0}){const{lastLine:y}=pt(u??null,a||o);return n?l("div",{className:"flex-1 min-h-0 relative",style:{background:"transparent"},children:[t("div",{style:{opacity:s?1:0,background:"transparent"},children:t(vd,{id:e,scenarioName:r,iframeUrl:n,defaultWidth:p,defaultHeight:h,onIframeLoad:c,onScaleChange:d,onDimensionChange:m},i)}),!s&&(a||o)&&t("div",{className:"absolute inset-0 flex items-center justify-center z-10",children:l("div",{className:"flex flex-col items-center justify-center gap-6 bg-white rounded-lg p-8 shadow-sm w-[500px] h-[300px]",children:[t("div",{className:"mb-4",children:t(vr,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[t("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),t("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[t(Cr,{}),y]})]})]})})]}):t("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center",children:l("div",{className:"flex flex-col items-center justify-center gap-6 w-[500px] h-[300px] bg-white rounded-lg p-8 shadow-sm",children:[t("div",{className:"mb-4",children:t(vr,{})}),l("div",{className:"flex flex-col gap-3 text-center",children:[t("h2",{className:"text-xl font-medium text-black leading-[28px] m-0 font-['IBM_Plex_Sans']",children:"Starting Interactive Mode"}),t("p",{className:"text-sm text-[#666] leading-5 m-0 font-['IBM_Plex_Sans']",children:"Setting up a sandboxed environment for your component"}),y&&l("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 mt-3 font-['IBM_Plex_Mono'] uppercase",children:[t(Cr,{}),y]})]})]})})}const jd=({data:e})=>[{title:e!=null&&e.scenario?`Edit ${e.scenario.name} - CodeYam`:"Edit Scenario - CodeYam"},{name:"description",content:"Edit scenario data"}];async function Rd({params:e}){var d,m;const{sha:r,scenarioId:n}=e;if(!r)throw new Response("Entity SHA is required",{status:400});if(!n)throw new Response("Scenario ID is required",{status:400});const a=await Tr(r,!0),o=a&&a.length>0?a[0]:null;if(!o)throw new Response("Analysis not found",{status:404});const s=(d=o.scenarios)==null?void 0:d.find(u=>u.id===n);if(!s)throw new Response("Scenario not found",{status:404});const i=(m=o.scenarios)==null?void 0:m.find(u=>u.name===_r),c=await ze();return G({analysis:o,scenario:s,defaultScenario:i||s,entitySha:r,projectSlug:c})}function Dd(){var j,P,B;const e=We(),r=e.analysis,n=e.scenario,a=e.defaultScenario,o=e.entitySha,s=e.projectSlug,i=Mt(),{iframeRef:c}=On(),[d,m]=M(!1),[u,p]=M(null),[h,f]=M(null),[y,g]=M(!1),[w,x]=M(!1),[b,v]=M(null),{interactiveServerUrl:C,isStarting:E,isLoading:N,showIframe:A,iframeKey:_,onIframeLoad:$}=er({analysisId:r==null?void 0:r.id,scenarioId:n==null?void 0:n.id,scenarioName:n==null?void 0:n.name,projectSlug:s,enabled:!0}),D=se(async(L,z)=>{m(!0),p(null),f(null),console.log("[EditScenario] Starting save with options:",z),console.log("[EditScenario] Scenarios to save:",L);try{const O={analysis:r,scenarios:L};console.log("[EditScenario] Sending to /api/save-scenarios:",{analysisId:r.id,scenarioCount:L.length,scenarioNames:L.map(S=>S.name)});const F=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(O)}),R=await F.json();if(console.log("[EditScenario] API response:",R),!F.ok||!R.success)throw new Error(R.error||"Failed to save scenarios");if(console.log("[EditScenario] Scenarios saved successfully"),z!=null&&z.recapture&&n.id&&C){console.log("[EditScenario] ========== DIRECT CAPTURE START =========="),console.log("[EditScenario] Taking screenshot from running server",{scenarioId:n.id,projectId:r.projectId,serverUrl:C}),p("Changes saved. Capturing screenshot...");const S={serverUrl:C,scenarioId:n.id,projectId:r.projectId,viewportWidth:1440};console.log("[EditScenario] Capture request body:",S);const H=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});console.log("[EditScenario] Capture response status:",H.status);const q=await H.json();if(console.log("[EditScenario] Capture response body:",q),!H.ok||!q.success)throw console.error("[EditScenario] Capture failed:",q),new Error(q.error||"Failed to capture screenshot");console.log("[EditScenario] Screenshot captured successfully:",q),console.log("[EditScenario] ========== DIRECT CAPTURE COMPLETE =========="),p("Recapture successful")}else if(z!=null&&z.recapture&&!C){console.log("[EditScenario] No running server, using queued recapture");const S=new FormData;S.append("analysisId",r.id||""),S.append("scenarioId",n.id||"");const H=await fetch("/api/recapture-scenario",{method:"POST",body:S}),q=await H.json();if(!H.ok||!q.success)throw new Error(q.error||"Failed to trigger recapture");console.log("Recapture queued:",q),f(q.jobId),p("Changes saved. Screenshot recapture queued.")}else p("Changes saved successfully.")}catch(O){console.error("Error saving scenarios:",O),p(`Error: ${O instanceof Error?O.message:String(O)}`)}finally{m(!1)}},[r,n.id,C]),I=se(L=>{},[]),k=se(async(L,z)=>{var R;const O=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:L,existingScenarios:r.scenarios,scenariosDataStructure:(R=r.metadata)==null?void 0:R.scenariosDataStructure,editingMockName:n.name,editingMockData:z==null?void 0:z.data})}),F=await O.json();if(!O.ok||!F.success)throw new Error(F.error||"Failed to generate scenario data");return F.data},[r,n.name]),T=se(async()=>{var L;if(!n.id){v("Cannot delete scenario without ID");return}g(!0),v(null);try{const z=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:n.id,screenshotPaths:((L=n.metadata)==null?void 0:L.screenshotPaths)||[]})}),O=await z.json();if(!z.ok||!O.success)throw new Error(O.error||"Failed to delete scenario");i(`/entity/${o}`)}catch(z){console.error("[EditScenario] Error deleting scenario:",z),v(z instanceof Error?z.message:"Failed to delete scenario"),x(!1)}finally{g(!1)}},[n.id,(j=n.metadata)==null?void 0:j.screenshotPaths,o,i]);return l("div",{className:"h-screen bg-gray-50 flex flex-col",children:[l("header",{className:"bg-white border-b border-gray-200 px-8 py-6 shrink-0",children:[t("div",{className:"mb-4",children:l(oe,{to:`/entity/${o}`,className:"text-blue-600 no-underline text-sm font-medium transition-colors hover:text-blue-700 hover:underline",children:["← Back to ",(P=r.entity)==null?void 0:P.name]})}),l("h1",{className:"text-[32px] font-bold text-gray-900 m-0 mb-3",children:["Edit Scenario: ",n.name]}),n.description&&t("p",{className:"text-gray-600 text-[15px] leading-relaxed m-0",children:n.description})]}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[l("aside",{className:"w-[400px] bg-white border-r border-gray-200 overflow-y-auto shrink-0",children:[t($d,{currentScenario:n,defaultScenario:a,dataStructure:((B=r.metadata)==null?void 0:B.scenariosDataStructure)||{},analysis:r,shouldCreateNewScenario:!1,onSave:D,onNavigate:I,iframeRef:c,onGenerateData:k,saveFeedback:{isSaving:d,message:u,isError:(u==null?void 0:u.startsWith("Error"))??!1}}),u==="Recapture successful"&&t("div",{className:"px-4 pb-4",children:t(oe,{to:`/entity/${o}`,className:"text-blue-600 hover:text-blue-700 hover:underline text-sm",children:"View updated screenshot on entity page →"})}),l("div",{className:"border-t border-gray-200 p-4 mt-4",children:[t("div",{className:"text-sm text-gray-600 mb-3",children:"Permanently remove this scenario and its screenshots."}),w?l("div",{className:"space-y-3",children:[l("div",{className:"text-sm text-red-600 font-medium",children:['Are you sure you want to delete "',n.name,'"?']}),l("div",{className:"flex gap-2",children:[t("button",{onClick:()=>void T(),disabled:y,className:"flex-1 px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors",children:y?"Deleting...":"Yes, Delete"}),t("button",{onClick:()=>x(!1),disabled:y,className:"flex-1 px-4 py-2 bg-gray-100 text-gray-700 border border-gray-300 rounded-md text-sm font-medium hover:bg-gray-200 disabled:opacity-50 transition-colors",children:"Cancel"})]})]}):t("button",{onClick:()=>x(!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&&t("div",{className:"mt-3 text-sm text-red-600 bg-red-50 px-3 py-2 rounded-md",children:b})]})]}),t("main",{className:"flex-1 bg-gray-100 overflow-auto flex flex-col min-w-0",children:t(Dr,{scenarioId:n.id||n.name,scenarioName:n.name,iframeUrl:C,isStarting:E,isLoading:N,showIframe:A,iframeKey:_,onIframeLoad:$,projectSlug:s,defaultWidth:1440,defaultHeight:900})})]})]})}const Ld=Oe(function(){return t(Rr,{children:t(Dd,{})})}),Fd=Object.freeze(Object.defineProperty({__proto__:null,default:Ld,loader:Rd,meta:jd},Symbol.toStringTag,{value:"Module"}));function Od({executionFlows:e,selections:r,onChange:n,disabled:a=!1}){const o=se(i=>r.some(c=>c.flowId===i),[r]),s=se(i=>{o(i.id)?n(r.filter(c=>c.flowId!==i.id)):n([...r,{flowId:i.id,flowName:i.name}])},[r,n,o]);return e.length===0?t("div",{className:"text-sm text-gray-500 py-2",children:"No execution flows found."}):t("div",{className:"space-y-3",children:e.map(i=>{const c=o(i.id),d=i.usedInScenarios.length>0;return l("div",{className:"border-b border-gray-100 pb-3 last:border-0 last:pb-0",children:[l("label",{className:"flex items-start gap-2 cursor-pointer",children:[t("input",{type:"checkbox",checked:c,onChange:()=>s(i),disabled:a,className:"mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[t("span",{className:"font-mono text-sm font-medium text-gray-900",children:i.name}),!d&&t("span",{className:"text-xs px-1.5 py-0.5 bg-amber-100 text-amber-700 rounded",children:"uncovered"}),i.blocksOtherFlows&&t("span",{className:"text-xs px-1.5 py-0.5 bg-purple-100 text-purple-700 rounded",children:"blocking"}),i.impact==="high"&&t("span",{className:"text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"high impact"})]}),i.description&&t("p",{className:"text-xs text-gray-500 mt-0.5 m-0",children:i.description})]})]}),c&&i.requiredValues.length>0&&l("div",{className:"ml-6 mt-2 p-2 bg-gray-50 rounded text-xs",children:[t("span",{className:"text-gray-700 font-medium",children:"Required values:"}),t("ul",{className:"m-0 mt-1 pl-4 space-y-0.5",children:i.requiredValues.map((m,u)=>l("li",{className:"text-gray-600",children:[t("code",{className:"bg-gray-100 px-1 rounded",children:m.attributePath})," ",t("span",{className:"text-gray-400",children:m.comparison})," ",t("code",{className:"bg-gray-100 px-1 rounded",children:m.value})]},u))})]})]},i.id)})})}function zn(e,r){const n=(e||[]).map(d=>({...d,usedInScenarios:[]})),a=new Map;n.forEach(d=>{a.set(d.id,d)});const o=[];r.forEach(d=>{var u;const m=((u=d.metadata)==null?void 0:u.coveredFlows)||[];m.forEach(p=>{const h=a.get(p);h&&h.usedInScenarios.push({id:d.id||"",name:d.name})}),o.push({scenario:d,coveredFlowIds:m})});const s=n.length,i=n.filter(d=>d.usedInScenarios.length>0).length,c=s>0?i/s*100:0;return{executionFlows:n,totalFlows:s,coveredFlows:i,coveragePercentage:c,scenariosWithFlows:o}}function zd(e){return e.executionFlows.filter(r=>r.usedInScenarios.length===0)}const Yd=({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 Bd({params:e}){var i;const{sha:r}=e;if(!r)throw new Response("Entity SHA is required",{status:400});const n=await Tr(r,!0),a=n&&n.length>0?n[0]:null;if(!a)throw new Response("Analysis not found",{status:404});const o=(i=a.scenarios)==null?void 0:i.find(c=>c.name===_r);if(!o)throw new Response("Default scenario not found",{status:404});const s=await ze();return G({analysis:a,defaultScenario:o,entity:a.entity,entitySha:r,projectSlug:s})}function Ud(){var O;const{analysis:e,defaultScenario:r,entity:n,entitySha:a,projectSlug:o}=We(),s=Mt(),{iframeRef:i}=On(),[c,d]=M(""),[m,u]=M(400),[p,h]=M(!1),[f,y]=M(!1),[g,w]=M(!1),[x,b]=M(null),[v,C]=M(null),[E,N]=M([]),A=ne(()=>{var R;return!((R=e==null?void 0:e.metadata)!=null&&R.executionFlows)||!(e!=null&&e.scenarios)?[]:zn(e.metadata.executionFlows,e.scenarios).executionFlows},[e]),{interactiveServerUrl:_,isStarting:$,isLoading:D,showIframe:I,iframeKey:k,onIframeLoad:T}=er({analysisId:e==null?void 0:e.id,scenarioId:r==null?void 0:r.id,scenarioName:r==null?void 0:r.name,projectSlug:o,enabled:!0}),j=se(async()=>{var F,R,S,H;if(!c.trim()&&E.length===0){b("Please describe how you want to change the scenario or select execution flows");return}y(!0),b(null),C("Generating scenario with AI...");try{const q=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:c,existingScenarios:e.scenarios,scenariosDataStructure:(F=e.metadata)==null?void 0:F.scenariosDataStructure,flowSelections:E.length>0?E:void 0})}),J=await q.json();if(!q.ok||!J.success)throw new Error(J.error||"Failed to generate scenario data");console.log("[CreateScenario] AI generated scenario:",J.data);const ae=J.data;if(!ae.name||!ae.data)throw new Error("AI response missing required fields (name or data)");C("Saving new scenario..."),w(!0);const V={name:ae.name,description:ae.description||c,metadata:{data:ae.data,interactiveExamplePath:(R=r.metadata)==null?void 0:R.interactiveExamplePath}},Y=[...e.scenarios||[],V],U=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:e,scenarios:Y})}),Q=await U.json();if(!U.ok||!Q.success)throw new Error(Q.error||"Failed to save scenario");console.log("[CreateScenario] Scenario saved:",Q);const W=(H=(S=Q.analysis)==null?void 0:S.scenarios)==null?void 0:H.find(Z=>Z.name===ae.name);if(!(W!=null&&W.id)){console.warn("[CreateScenario] Could not find saved scenario ID, navigating to entity page"),C("Scenario created! Redirecting..."),setTimeout(()=>void s(`/entity/${a}`),1e3);return}if(_){C("Capturing screenshot...");const Z=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:_,scenarioId:W.id,projectId:e.projectId,viewportWidth:1440})}),de=await Z.json();!Z.ok||!de.success?(console.error("[CreateScenario] Capture failed:",de),C("Scenario created! (Screenshot capture failed)")):C("Scenario created and captured!")}else C("Scenario created!");setTimeout(()=>{s(`/entity/${a}/scenarios/${W.id}`)},1e3)}catch(q){console.error("[CreateScenario] Error:",q),b(q instanceof Error?q.message:String(q)),C(null)}finally{y(!1),w(!1)}},[c,E,e,r,a,_,s]),P=f||g,B=se(()=>{h(!0)},[]),L=se(F=>{if(!p)return;const R=F.clientX;R>=250&&R<=600&&u(R)},[p]),z=se(()=>{h(!1)},[]);return re(()=>(p?(document.addEventListener("mousemove",L),document.addEventListener("mouseup",z)):(document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",z)),()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",z)}),[p,L,z]),l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[t("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-end h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[t("button",{onClick:()=>void s(`/entity/${a}`),className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:t("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:t("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),t("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:n==null?void 0:n.name}),t("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:n==null?void 0:n.filePath,children:n==null?void 0:n.filePath})]}),l("div",{className:"flex items-end gap-8 shrink-0",children:[t(oe,{to:`/entity/${a}/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:l("span",{className:"flex items-center gap-2",children:["Scenarios",t("span",{className:"inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full bg-[#cbf3fa] text-[#005c75]",children:((O=e==null?void 0:e.scenarios)==null?void 0:O.length)||0})]})}),t(oe,{to:`/entity/${a}/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"}),t(oe,{to:`/entity/${a}/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"}),t(oe,{to:`/entity/${a}/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"}),t(oe,{to:`/entity/${a}/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"})]})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0 relative",children:[l("aside",{className:"bg-white border-r border-gray-200 overflow-y-auto shrink-0 p-6 flex flex-col",style:{width:`${m}px`},children:[l("div",{className:"mb-6",children:[t("h2",{className:"text-lg font-semibold text-gray-900 mb-2",children:"Default Scenario Preview"}),t("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."})]}),A.length>0&&l("details",{className:"mb-4 border border-gray-200 rounded-lg",children:[l("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"," ",E.length>0&&l("span",{className:"text-blue-600",children:["(",E.length," selected)"]})]}),t("div",{className:"px-3 pb-3 pt-1 border-t border-gray-100",children:t(Od,{executionFlows:A,selections:E,onChange:N,disabled:P})})]}),l("div",{className:"mb-4",children:[t("label",{htmlFor:"prompt",className:"block text-sm font-medium text-gray-700 mb-2",children:"Describe your scenario"}),t("textarea",{id:"prompt",value:c,onChange:F=>d(F.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})]}),l("div",{className:"space-y-2",children:[t("button",{onClick:()=>void j(),disabled:P||!c.trim()&&E.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&&t("div",{className:"text-xs text-blue-600 bg-blue-50 px-2 py-1.5 rounded",children:v}),x&&t("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1.5 rounded",children:x})]})]}),l("div",{onMouseDown:B,style:{width:"20px",position:"absolute",top:0,left:`${m-10}px`,bottom:0,cursor:"col-resize",touchAction:"none",userSelect:"none",zIndex:100,pointerEvents:"auto"},children:[t("div",{style:{position:"absolute",left:"10px",top:0,bottom:0,width:"1px",background:p?"#005c75":"rgba(0,0,0,0.1)",transition:"background 0.15s ease"}}),t("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"}})]}),t("main",{className:"flex-1 overflow-auto flex items-center justify-center min-w-0",style:{backgroundImage:`
|
|
105
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
106
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
107
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
108
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
109
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:t(Dr,{scenarioId:r.id||r.name,scenarioName:r.name,iframeUrl:_,isStarting:$,isLoading:D,showIframe:I,iframeKey:k,onIframeLoad:T,projectSlug:o,defaultWidth:1440,defaultHeight:900})})]})]})}const Wd=Oe(function(){return t(Rr,{children:t(Ud,{})})}),Hd=Object.freeze(Object.defineProperty({__proto__:null,default:Wd,loader:Bd,meta:Yd},Symbol.toStringTag,{value:"Module"}));var ie;(e=>{(r=>{r.OPENAI_GPT5_1="openai/gpt-5.1",r.OPENAI_GPT5="openai/gpt-5",r.OPENAI_GPT5_MINI="openai/gpt-5-mini",r.OPENAI_GPT5_NANO="openai/gpt-5-nano",r.OPENAI_GPT4_1="openai/gpt-4.1",r.OPENAI_GPT4_1_MINI="openai/gpt-4.1-mini",r.OPENAI_GPT4_O="openai/gpt-4o",r.OPENAI_GPT4_O_MINI="openai/gpt-4o-mini",r.OPENAI_GPT_OSS_120B_GROQ="openai/gpt-oss-120b-groq",r.OPENAI_GPT_OSS_120B_DEEPINFRA="openai/gpt-oss-120b-deepinfra",r.QWEN3_235B_INSTRUCT_DEEPINFRA="qwen/qwen3-235b-instruct-deepinfra",r.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA="qwen/qwen3-coder-480b-instruct-deepinfra",r.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA="google/gemini-2.5-pro-deepinfra",r.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA="google/gemini-2.5-flash-deepinfra",r.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER="google/gemini-2.5-flash-lite-openrouter",r.META_LLAMA_4_MAVERICK_OPENROUTER="meta-llama/llama-4-maverick-openrouter",r.DEEPSEEK_V3_1_TERMINUS_OPENROUTER="deepseek/v3.1-terminus-openrouter",r.ANTHROPIC_CLAUDE_4_5_HAIKU="anthropic/claude-4.5-haiku",r.ANTHROPIC_CLAUDE_4_5_SONNET="anthropic/claude-4.5-sonnet",r.ANTHROPIC_CLAUDE_4_5_OPUS="anthropic/claude-4.5-opus",r.PHIND_CODELLAMA="phind/codellama",r.GOOGLE_GEMINI_PRO="google/gemini-pro",r.GOOGLE_PALM_2_CODE_CHAT_32K="google/palm-2-code-chat-32k",r.META_CODELLAMA_34B_INSTRUCT="meta-llama/codellama-34b-instruct",r.OPENAI_GPT4_PREVIEW="openai/gpt-4-preview"})(e.Model||(e.Model={}))})(ie||(ie={}));function ss(e,r){return e?Object.values(ie.Model).includes(e)?e:(console.warn(`Invalid model in environment variable: ${e}. Falling back to ${r}`),r):r}const is=ss(process.env.DEFAULT_SMALLER_MODEL,ie.Model.OPENAI_GPT4_1_MINI),qd=ss(process.env.DEFAULT_LARGER_MODEL,ie.Model.OPENAI_GPT4_1),Ke={name:"OpenAI",baseURL:"https://api.openai.com/v1",apiKeyEnvVar:"OPENAI_API_KEY"},rn={name:"OpenRouter",baseURL:"https://openrouter.ai/api/v1",apiKeyEnvVar:"OPENROUTER_API_KEY"},Gd={name:"Groq",baseURL:"https://api.groq.com/openai/v1",apiKeyEnvVar:"GROQ_API_KEY"},nn={name:"Anthropic",baseURL:"https://api.anthropic.com/v1/",apiKeyEnvVar:"ANTHROPIC_API_KEY"},it={name:"DeepInfra",baseURL:"https://api.deepinfra.com/v1/",apiKeyEnvVar:"DEEPINFRA_API_KEY"},Jd={[ie.Model.OPENAI_GPT5_1]:{id:ie.Model.OPENAI_GPT5_1,provider:Ke,apiModelName:"gpt-5.1",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"none"},[ie.Model.OPENAI_GPT5]:{id:ie.Model.OPENAI_GPT5,provider:Ke,apiModelName:"gpt-5",maxCompletionTokens:128e3,pricing:{input:1.25,output:10},reasoningEffort:"minimal"},[ie.Model.OPENAI_GPT5_MINI]:{id:ie.Model.OPENAI_GPT5_MINI,provider:Ke,apiModelName:"gpt-5-mini",maxCompletionTokens:128e3,pricing:{input:.25,output:2},reasoningEffort:"minimal"},[ie.Model.OPENAI_GPT5_NANO]:{id:ie.Model.OPENAI_GPT5_NANO,provider:Ke,apiModelName:"gpt-5-nano",maxCompletionTokens:128e3,pricing:{input:.05,output:.4},reasoningEffort:"minimal"},[ie.Model.OPENAI_GPT4_1]:{id:ie.Model.OPENAI_GPT4_1,provider:Ke,apiModelName:"gpt-4.1",maxCompletionTokens:32768,pricing:{input:2,output:8}},[ie.Model.OPENAI_GPT4_1_MINI]:{id:ie.Model.OPENAI_GPT4_1_MINI,provider:Ke,apiModelName:"gpt-4.1-mini",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ie.Model.OPENAI_GPT4_O]:{id:ie.Model.OPENAI_GPT4_O,provider:Ke,apiModelName:"gpt-4o",maxCompletionTokens:16384,pricing:{input:2.5,output:10}},[ie.Model.OPENAI_GPT4_O_MINI]:{id:ie.Model.OPENAI_GPT4_O_MINI,provider:Ke,apiModelName:"gpt-4o-mini",maxCompletionTokens:16384,pricing:{input:.15,output:.6}},[ie.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER]:{id:ie.Model.GOOGLE_GEMINI_2_5_FLASH_LITE_OPENROUTER,provider:rn,apiModelName:"google/gemini-2.5-flash-lite",maxCompletionTokens:1048576,pricing:{input:.1,output:.4},reasoningEffort:"minimal"},[ie.Model.META_LLAMA_4_MAVERICK_OPENROUTER]:{id:ie.Model.META_LLAMA_4_MAVERICK_OPENROUTER,provider:rn,apiModelName:"meta-llama/llama-4-maverick",maxCompletionTokens:1048576,pricing:{input:.15,output:.6},reasoningEffort:"minimal"},[ie.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER]:{id:ie.Model.DEEPSEEK_V3_1_TERMINUS_OPENROUTER,provider:rn,apiModelName:"deepseek/deepseek-v3.1-terminus",maxCompletionTokens:163840,pricing:{input:.23,output:.9},reasoningEffort:"minimal"},[ie.Model.OPENAI_GPT_OSS_120B_GROQ]:{id:ie.Model.OPENAI_GPT_OSS_120B_GROQ,provider:Gd,apiModelName:"openai/gpt-oss-120b",maxCompletionTokens:131072,pricing:{input:.15,output:.75},reasoningEffort:"low"},[ie.Model.OPENAI_GPT_OSS_120B_DEEPINFRA]:{id:ie.Model.OPENAI_GPT_OSS_120B_DEEPINFRA,provider:it,apiModelName:"openai/gpt-oss-120b-Turbo",maxCompletionTokens:32768,pricing:{input:.15,output:.6},reasoningEffort:"low"},[ie.Model.QWEN3_235B_INSTRUCT_DEEPINFRA]:{id:ie.Model.QWEN3_235B_INSTRUCT_DEEPINFRA,provider:it,apiModelName:"Qwen/Qwen3-235B-A22B-Instruct-2507",maxCompletionTokens:32768,pricing:{input:.09,output:.57}},[ie.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA]:{id:ie.Model.QWEN3_CODER_480B_INSTRUCT_DEEPINFRA,provider:it,apiModelName:"Qwen/Qwen3-Coder-480B-A35B-Instruct",maxCompletionTokens:32768,pricing:{input:.4,output:1.6}},[ie.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA]:{id:ie.Model.GOOGLE_GEMINI_2_5_PRO_DEEPINFRA,provider:it,apiModelName:"google/gemini-2.5-pro",maxCompletionTokens:1048576,pricing:{input:1.25,output:10},reasoningEffort:"low"},[ie.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA]:{id:ie.Model.GOOGLE_GEMINI_2_5_FLASH_DEEPINFRA,provider:it,apiModelName:"google/gemini-2.5-flash",maxCompletionTokens:1048576,pricing:{input:.3,output:2.5},reasoningEffort:"low"},[ie.Model.ANTHROPIC_CLAUDE_4_5_HAIKU]:{id:ie.Model.ANTHROPIC_CLAUDE_4_5_HAIKU,provider:nn,apiModelName:"claude-haiku-4-5",maxCompletionTokens:2e5,pricing:{input:1,output:5}},[ie.Model.ANTHROPIC_CLAUDE_4_5_SONNET]:{id:ie.Model.ANTHROPIC_CLAUDE_4_5_SONNET,provider:nn,apiModelName:"claude-sonnet-4-5",maxCompletionTokens:2e5,pricing:{input:3,output:15}},[ie.Model.ANTHROPIC_CLAUDE_4_5_OPUS]:{id:ie.Model.ANTHROPIC_CLAUDE_4_5_OPUS,provider:nn,apiModelName:"claude-opus-4-5",maxCompletionTokens:2e5,pricing:{input:5,output:25}},[ie.Model.PHIND_CODELLAMA]:{id:ie.Model.PHIND_CODELLAMA,provider:Ke,apiModelName:"phind-codellama",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ie.Model.GOOGLE_GEMINI_PRO]:{id:ie.Model.GOOGLE_GEMINI_PRO,provider:it,apiModelName:"google/gemini-pro",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ie.Model.GOOGLE_PALM_2_CODE_CHAT_32K]:{id:ie.Model.GOOGLE_PALM_2_CODE_CHAT_32K,provider:it,apiModelName:"google/palm-2-code-chat-32k",maxCompletionTokens:32768,pricing:{input:0,output:0}},[ie.Model.META_CODELLAMA_34B_INSTRUCT]:{id:ie.Model.META_CODELLAMA_34B_INSTRUCT,provider:it,apiModelName:"meta-llama/codellama-34b-instruct",maxCompletionTokens:16384,pricing:{input:0,output:0}},[ie.Model.OPENAI_GPT4_PREVIEW]:{id:ie.Model.OPENAI_GPT4_PREVIEW,provider:Ke,apiModelName:"gpt-4-preview",maxCompletionTokens:128e3,pricing:{input:0,output:0}}};function Lr(e){const r=Jd[e];if(!r)throw new Error(`Unknown model: ${e}`);return r}function Vd(e){return Lr(e).maxCompletionTokens}function Qd(e){return Lr(e).pricing}const Fa=1e6;function Kd({model:e,usage:r}){const n=Qd(e);return n?r.prompt_tokens*(n.input/Fa)+r.completion_tokens*(n.output/Fa):null}function Zd({chatRequest:e,chatCompletion:r,model:n}){if("error"in r&&r.error)return{model:n,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(r,null,2),error:JSON.stringify(r.error)};const a=r.usage||{prompt_tokens:0,completion_tokens:0},o=Kd({model:n,usage:a});return{model:n,prompt_type:e.type,system_message:e.messages.system,prompt_text:e.messages.prompt,response:JSON.stringify(r,null,2),input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,cost:o?Math.round(o*1e5)/1e5:void 0}}function Xd({messages:{system:e,prompt:r},model:n,responseType:a,jsonSchema:o}){const s=n??is,i=Lr(s);Vd(s);const c=[];return e&&c.push({role:"system",content:e}),c.push({role:"user",content:[{type:"text",text:r}]}),{messages:c,model:i.apiModelName,response_format:a==="json_schema"&&o?{type:"json_schema",json_schema:{name:o.name,schema:o.schema,strict:o.strict!==!1}}:{type:a&&a=="text"?"text":"json_object"},...i.reasoningEffort&&{reasoning_effort:i.reasoningEffort}}}const mn="/tmp/codeyam-e2e-tracking";let an,on;function eu(){return an===void 0&&(an=process.env.CODEYAM_E2E_TRACK_DATA==="true"),an}function tu(){return on===void 0&&(on=!process.env.CODEYAM_LLM_FIXTURES_DIR),on}function ru(){K.existsSync(mn)||K.mkdirSync(mn,{recursive:!0})}function nu(e){const r=JSON.stringify(e,null,0);return $i.createHash("md5").update(r).digest("hex")}function au(e,r,n){return[e].join("_")+".json"}function ls(e,r,n,a){if(!eu())return;ru();const o=au(e),s=ee.join(mn,o),i=nu(r);if(tu()){const c={timestamp:Date.now(),checkpoint:e,entityName:n,scenarioName:a,dataHash:i,data:r};K.writeFileSync(s,JSON.stringify(c,null,2)),console.log(`[E2E Tracking] First run - saved snapshot: ${e} hash=${i.substring(0,8)}`)}else if(K.existsSync(s)){const c=JSON.parse(K.readFileSync(s,"utf-8")),d={matches:i===c.dataHash,firstRunHash:c.dataHash};if(d.matches)console.log(`[E2E Tracking] Match at ${e} hash=${i.substring(0,8)}`);else{d.differences=pn(c.data,r),console.log(`[E2E Tracking] MISMATCH at ${e}`),console.log(` First run hash: ${c.dataHash}`),console.log(` Second run hash: ${i}`);const m=s.replace(".json","_DIFF.json");K.writeFileSync(m,JSON.stringify({checkpoint:e,entityName:n,scenarioName:a,firstRun:c.data,secondRun:r,differences:d.differences},null,2)),console.log(` Diff saved to: ${m}`)}}else console.log(`[E2E Tracking] No first-run snapshot found for: ${e}`)}function pn(e,r,n=""){const a=[];if(typeof e!=typeof r)return a.push(`${n||"root"}: type mismatch (${typeof e} vs ${typeof r})`),a;if(e===null||r===null)return e!==r&&a.push(`${n||"root"}: ${JSON.stringify(e)} vs ${JSON.stringify(r)}`),a;if(Array.isArray(e)&&Array.isArray(r)){e.length!==r.length&&a.push(`${n||"root"}: array length ${e.length} vs ${r.length}`);const o=Math.max(e.length,r.length);for(let s=0;s<o;s++)a.push(...pn(e[s],r[s],`${n}[${s}]`));return a}if(typeof e=="object"&&typeof r=="object"){const o=Object.keys(e),s=Object.keys(r),i=Array.from(new Set([...o,...s]));for(const c of i){const d=e[c],m=r[c];c in e?c in r?a.push(...pn(d,m,`${n?n+".":""}${c}`)):a.push(`${n?n+".":""}${c}: missing in second run`):a.push(`${n?n+".":""}${c}: missing in first run`)}return a}if(e!==r){const o=JSON.stringify(e),s=JSON.stringify(r);o.length<100&&s.length<100?a.push(`${n||"root"}: ${o} vs ${s}`):a.push(`${n||"root"}: values differ (${o.length} chars vs ${s.length} chars)`)}return a}kn(En);const ir=new Oi({concurrency:100,timeout:1200*1e3,throwOnTimeout:!0,autoStart:!0}),Oa={retries:4,factor:2,minTimeout:1e3,maxTimeout:6e4,randomize:!0},lt={};async function fn({type:e,systemMessage:r,prompt:n,jsonResponse:a=!0,jsonSchema:o,model:s=is,attempts:i=0}){var N,A,_,$,D,I,k;if(process.env.CODEYAM_LLM_FIXTURES_DIR)return await ou(e,process.env.CODEYAM_LLM_FIXTURES_DIR,r);console.log(`CodeYam Debug: LLM Pool [queued=${ir.size}, running=${ir.pending}]`);const c=Date.now();let d,m=0;const u=Lr(s),p=process.env[u.provider.apiKeyEnvVar];if(!p)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 Fi({apiKey:p,baseURL:u.provider.baseURL}),f={type:e,messages:{system:r,prompt:n},model:s,responseType:o?"json_schema":a?"json_object":"text",jsonSchema:o},y=Xd(f),g=await ir.add(()=>(d=Date.now(),Ea(async()=>{const T=Date.now(),j=["Waiting for LLM response","Still waiting for LLM response","LLM call in progress","Processing LLM request","Awaiting LLM completion"],P=setInterval(()=>{const B=Math.floor((Date.now()-T)/1e3),L=Math.floor(B/10)%j.length;ka(1,`${j[L]} [type=${e}, model=${s}, elapsed=${B}s]`)},1e4);try{return await h.chat.completions.create(y,{timeout:300*1e3})}finally{clearInterval(P)}},{...Oa,onFailedAttempt:T=>{m++,console.log(`CodeYam Error: Completion call failed [model=${s}]`,{error:T,prompt:n,systemMessage:r,attempts:i,retryCount:m})}})),{throwOnTimeout:!0}),w=Date.now(),x=Zd({chatRequest:f,chatCompletion:g,model:s});if(!x)throw new Error("Failed to get LLM call stats");x.retries=m,x.wait_ms=d-c,x.duration_ms=w-c;const b=(N=g.choices)==null?void 0:N[0];let v=null;if(b){if(!b.finish_reason)throw console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({chatCompletion:g,chatRequest:f},null,2)),new Error("completionCall(): missing finish_reason in LLM response");v=(A=b.message)==null?void 0:A.content}let C=v;v&&(C=v.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const E=a?C&&(((_=C.match(/\{[\s\S]*\}/))==null?void 0:_[0])??C):C;if(!E){if(console.log(`CodeYam Error: completionCall(): empty completion from LLM, [type=${e}]`,JSON.stringify({completion:E,rawCompletion:v,chatCompletion:g,chatRequest:f},null,2)),i<3)return console.log("CodeYam Error: Retrying completion",{prompt:n,systemMessage:r,attempts:i}),await fn({type:e,systemMessage:r,prompt:n,jsonResponse:a,model:s,attempts:i+1});throw new Error("completionCall(): empty completion from LLM")}if(E.replace(/\s/g,"")==="")throw console.log("CodeYam Error: Empty Completion",{rawCompletion:v,prompt:n,systemMessage:r}),new Error("Empty completion");if(a)try{JSON.parse(E)}catch(T){if(console.log("CodeYam Error: Invalid JSON in completion",{error:T.message,model:s,completion:E.substring(0,500),rawCompletion:v==null?void 0:v.substring(0,500)}),i<3){console.log("CodeYam Error: Retrying with correction prompt",{attempts:i,parseError:T.message});const j=`Your previous response contained invalid JSON with the following error:
|
|
110
|
-
|
|
111
|
-
${T.message}
|
|
112
|
-
|
|
113
|
-
Here was your previous response:
|
|
114
|
-
\`\`\`
|
|
115
|
-
${E}
|
|
116
|
-
\`\`\`
|
|
117
|
-
|
|
118
|
-
Please provide a corrected version with valid JSON only. Do not include any explanatory text, just the valid JSON object.`,P=await ir.add(()=>Ea(async()=>{const O=Date.now(),F=["Waiting for LLM correction response","Still waiting for LLM correction","LLM correction in progress","Processing LLM correction request","Awaiting LLM correction completion"],R=setInterval(()=>{const S=Math.floor((Date.now()-O)/1e3),H=Math.floor(S/10)%F.length;ka(1,`${F[H]} [type=${e}, model=${s}, elapsed=${S}s]`)},1e4);try{return await h.chat.completions.create({...y,messages:[{role:"system",content:r},{role:"user",content:n},{role:"assistant",content:E},{role:"user",content:j}]},{timeout:300*1e3})}finally{clearInterval(R)}},{...Oa,onFailedAttempt:O=>{console.log("CodeYam Error: Correction call failed",{error:O,attempts:i})}}),{throwOnTimeout:!0}),B=(I=(D=($=P.choices)==null?void 0:$[0])==null?void 0:D.message)==null?void 0:I.content;let L=B;B&&(L=B.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const z=L&&(((k=L.match(/\{[\s\S]*\}/))==null?void 0:k[0])??L);if(!z)throw new Error("Correction attempt returned empty completion");try{JSON.parse(z),console.log("CodeYam: JSON correction successful");const O=Date.now();return x.duration_ms=O-c,{finishReason:P.choices[0].finish_reason,completion:z,stats:x}}catch(O){return console.log("CodeYam Error: Corrected JSON still invalid",{error:O.message,correctedCompletion:z.substring(0,500)}),await fn({type:e,systemMessage:r,prompt:n,jsonResponse:a,model:s,attempts:i+1})}}throw new Error(`Invalid JSON after ${i} attempts: ${T.message}`)}return ls(`completionCall_${e}`,{completion:E,finishReason:g.choices[0].finish_reason}),{finishReason:g.choices[0].finish_reason,completion:E,stats:x}}async function ou(e,r,n){var s,i,c,d,m;const a=await import("fs"),o=await import("path");console.log(`CodeYam Test: Replaying LLM call for type '${e}' from ${r}`);try{if(!a.existsSync(r))throw console.log(`CodeYam Test: Fixtures directory does not exist yet: ${r}`),new Error(`No LLM fixture files found - directory does not exist: ${r}`);const u=a.readdirSync(r).filter(b=>b.endsWith(".json"));if(u.length===0)throw new Error(`No LLM fixture files found in ${r}`);const p={};for(const b of u)try{const v=a.readFileSync(o.join(r,b),"utf-8"),C=JSON.parse(v);p[C.prompt_type]||(p[C.prompt_type]=[]),p[C.prompt_type].push(C)}catch(v){console.warn(`Failed to parse LLM fixture file ${b}:`,v)}for(const b of Object.keys(p))p[b].sort((v,C)=>{const E=v.created_at??0,N=C.created_at??0;return E-N});const h=p[e];if(!h||h.length===0){const b=Object.keys(p).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)&&n){const b=n.match(/Scenario name must match exactly: "([^"]+)"/),v=b==null?void 0:b[1];if(v){const C={};for(const N of h)try{const _=((s=JSON.parse(N.props||"{}").scenario)==null?void 0:s.name)||"__NO_SCENARIO__";C[_]||(C[_]=[]),C[_].push(N)}catch{}const E=C[v];if(E&&E.length>0){const N=`${r}::${e}::${v}`;lt[N]===void 0&&(lt[N]=0);const A=lt[N];lt[N]=(A+1)%E.length,f=E[A],console.log(`CodeYam Test: ✅ Matched fixture for scenario '${v}' [${A+1}/${E.length}]`)}else{const N=Object.keys(C).join(", ");console.warn(`CodeYam Test: ⚠️ No fixture found for scenario '${v}'. Available: [${N}]`)}}else console.warn(`CodeYam Test: ⚠️ Could not extract scenario name from system message for type '${e}'`)}if(!f){const b=`${r}::${e}`;lt[b]===void 0&&(lt[b]=0);const v=lt[b];lt[b]=(v+1)%h.length,f=h[v],console.log(`CodeYam Test: Replaying LLM response for '${e}' [${v+1}/${h.length}]`)}let g;try{g=((d=(c=(i=JSON.parse(f.response).choices)==null?void 0:i[0])==null?void 0:c.message)==null?void 0:d.content)||f.response}catch{g=f.response}let w=g;g&&(w=g.replace(/<think>[\s\S]*?<\/think>/g,"").trim());const x=w&&(((m=w.match(/\{[\s\S]*\}/))==null?void 0:m[0])??w);return ls(`completionCall_${e}`,{completion:x||"",finishReason:"stop"}),{finishReason:"stop",completion:x||"",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 za(){return process.env.DYNAMODB_PREFIX?`${process.env.DYNAMODB_PREFIX}-llm-calls`:null}async function su(e){const{propsJson:r,...n}=e,a=JSON.stringify(r,null,2),o=Vt(),s=Date.now(),i={...n,id:o,created_at:s,props:a};let c;const d=`${i.object_id}_${o}.json`;if(process.env.DYNAMODB_PATH?c=ee.join(process.env.DYNAMODB_PATH,d):process.env.CODEYAM_LOCAL_PROJECT_PATH&&(c=ee.join(process.env.CODEYAM_LOCAL_PROJECT_PATH,".codeyam","llm-calls",d)),c)try{const u=ee.dirname(c);return await Ie.mkdir(u,{recursive:!0}),await Ie.writeFile(c,JSON.stringify(i,null,2)),console.log(`CodeYam: Saved LLM call to local file: ${c}`),{id:o}}catch(u){return console.log("CodeYam Error: Failed to save LLM call to local file",u),{id:"-1"}}const m=za();if(!m)return console.log("[CodeYam] No DynamoDB table name for LLM calls, skipping save"),{id:"-1"};for(const[u,p]of Object.entries(i))typeof p>"u"&&console.log(`CodeYam Warning: LLM call ${o} property ${u} with explicit value 'undefined'`);try{return await new Pr().send(new zi({TableName:za(),Item:Bi(i,{removeUndefinedValues:!0})})),{id:o}}catch(u){return console.log(`CodeYam Error: Failed to save LLM call to DynamoDB table ${m}`,u),{id:"-1"}}}new Pr({});new Pr({});new Pr({});const iu=3,lu=2,Yn=()=>({max:1e4,maxSize:10*1e3*1e3,sizeCalculation:(e,r)=>16+iu*String(r).length*(1+lu)});new Pn(Yn());new Pn(Yn());new Pn(Yn());class cu{constructor(){this.byMethodName=new Map,this.byClassAndMethod=new Map}register(r,n,a){this.byMethodName.has(r)||this.byMethodName.set(r,[]),this.byMethodName.get(r).push(n),a&&(this.byClassAndMethod.has(a)||this.byClassAndMethod.set(a,new Map),this.byClassAndMethod.get(a).set(r,n))}getByMethodName(r){return this.byMethodName.get(r)}getByClassAndMethod(r,n){var a;return(a=this.byClassAndMethod.get(r))==null?void 0:a.get(n)}}class du{getReturnType(){return"array"}addEquivalences(r,n,a){a.addType(n,"array"),a.addType(r,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class uu{getReturnType(){return"boolean"}addEquivalences(r,n,a){a.addType(n,"array"),a.addType(r,"boolean");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class hu{getReturnType(){return"boolean"}addEquivalences(r,n,a){a.addType(n,"array"),a.addType(r,"boolean");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class mu{getReturnType(){return"unknown"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class pu{getReturnType(){return"unknown"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];if(a.addType(s,"function"),a.addEquivalence(s.withParameter(1),n.withElement("*")),o.args.length>1){const i=o.args[1];a.addEquivalence(s.withParameter(0),i)}}}isComplete(){return!0}}class fu{getReturnType(){return"unknown"}addEquivalences(r,n,a){a.addType(n,"unknown");const o=r.getLastFunctionCallSegment();o&&o.args.forEach(s=>{a.addEquivalence(r,s)}),a.addEquivalence(r,n.withElement("*"))}isComplete(){return!0}}class gu{getReturnType(){return"unknown"}addEquivalences(r,n,a){a.addType(n,"unknown");const o=r.withReturnValues();a.addType(o,"unknown")}isComplete(){return!0}}class yu{getReturnType(){return"array"}addEquivalences(r,n,a){a.addType(n,"array"),a.addType(r,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>2)for(let s=2;s<o.args.length;s++){const i=o.args[s];a.addEquivalence(n.withElement("*"),i)}}isComplete(){return!0}}class xu{getReturnType(){return"number"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0)for(let s=0;s<o.args.length;s++)a.addEquivalence(n.withElement("*"),r.withParameter(s))}isComplete(){return!0}}class bu{getReturnType(){return"string"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addEquivalence(r.withParameter(0),s)}}isComplete(){return!0}}class wu{getReturnType(){return"array"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class vu{getReturnType(){return"array"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class Cu{getReturnType(){return"unknown"}addEquivalences(r,n,a){a.addType(n,"unknown"),a.addEquivalence(r.withReturnValues(),n.withElement("*"))}isComplete(){return!0}}class Nu{getReturnType(){return"unknown"}addEquivalences(r,n,a){a.addType(n,"array");const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n.withElement("*"))}}isComplete(){return!0}}class Su{getReturnType(){return"object"}addEquivalences(r,n,a){const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"array")}}isComplete(){return!0}}class Eu{getReturnType(){return"string[]"}addEquivalences(r,n,a){a.addType(n,"string"),a.addType(r,"string[]"),a.addEquivalence(r.withReturnValues().withElement("*"),n)}isComplete(){return!0}}class Au{getReturnType(){return"unknown"}addEquivalences(r,n,a){const o=r.getLastFunctionCallSegment();if(o&&o.args.length>0){const s=o.args[0];a.addType(s,"function"),a.addEquivalence(s.withParameter(0),n),a.addEquivalence(r.withProperty("functionCallReturnValue"),s.withProperty("returnValue"))}}isComplete(){return!0}}class ku{getReturnType(){return"unknown"}addEquivalences(r,n,a){r.getLastFunctionCallSegment()}isComplete(){return!0}}class Pu{getReturnType(){return"array"}addEquivalences(r,n,a){const o=r.getLastFunctionCallSegment();if(a.addType(r.withParameter(1),"function"),o&&o.args.length>0){const s=o.args[0];a.addEquivalence(r.withParameter(0),s)}}isComplete(){return!0}}function _u(){const e=new cu;return e.register("filter",new du,"Array"),e.register("map",new wu,"Array"),e.register("flatMap",new vu,"Array"),e.register("join",new bu,"Array"),e.register("find",new mu,"Array"),e.register("findLast",new Nu,"Array"),e.register("at",new Cu,"Array"),e.register("reduce",new pu,"Array"),e.register("concat",new fu,"Array"),e.register("slice",new gu,"Array"),e.register("splice",new yu,"Array"),e.register("push",new xu,"Array"),e.register("some",new uu,"Array"),e.register("every",new hu,"Array"),e.register("fromEntries",new Su,"Object"),e.register("split",new Eu,"String"),e.register("then",new Au,"Promise"),e.register("useState",new Pu,"React"),e.register("useMemo",new ku,"React"),e}_u();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 Mu=new Set(["filter","sort","slice","splice","unshift","push","reverse","entries"]),Tu=new Set(["find","findLast","at","pop","shift"]),Iu=new Set(["map","reduce","flatMap","concat","join","some","every","findIndex","findLastIndex","indexOf","lastIndexOf","includes"]),$u=new Set([...Mu,...Tu,...Iu]),ju=new Set(["trim","concat","replace","replaceAll","toLowerCase","toUpperCase","trimStart","trimEnd","padStart","padEnd","normalize","slice","substring","substr","toString()","toLocaleLowerCase","toLocaleUpperCase"]),Ru=new Set(["split","match","endsWith","startsWith","includes","indexOf","lastIndexOf","charAt","charCodeAt","codePointAt","repeat","search","valueOf","localeCompare","length"]),Du=new Set([...ju,...Ru]);[...$u,...Du];class Lu{constructor(r){this.depth=0,this.traceCount=0,this.defaultOutput=(n,a)=>{const o=" ".repeat(this.depth),s=this.timestamps?`[${Date.now()}] `:"";a?console.info(`${s}${o}${n}`,JSON.stringify(a)):console.info(`${s}${o}${n}`)},this.enabled=r.enabled,this.pathPatterns=r.pathPatterns??[],this.scopePatterns=r.scopePatterns??[],this.maxDepth=r.maxDepth??50,this.output=r.output??this.defaultOutput,this.timestamps=r.timestamps??!1}shouldTrace(r){return!this.enabled||this.depth>=this.maxDepth?!1:!!(this.pathPatterns.length===0&&this.scopePatterns.length===0||r.path&&this.pathPatterns.length>0&&this.pathPatterns.some(n=>n.test(r.path))||r.scope&&this.scopePatterns.length>0&&this.scopePatterns.some(n=>n.test(r.scope)))}trace(r,n={}){this.shouldTrace(n)&&(this.traceCount++,this.output(`[TRACE] ${r}`,n))}traceEnter(r,n={}){this.shouldTrace(n)&&(this.traceCount++,this.output(`[ENTER] ${r}`,n),this.depth++)}traceExit(r,n={}){this.depth>0&&this.depth--,this.shouldTrace(n)&&this.output(`[EXIT] ${r}`,n)}traceWarn(r,n={}){this.shouldTrace(n)&&(this.traceCount++,this.output(`[WARN] ${r}`,n))}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 Lu({enabled:!1});function cs(e){if(e==null)return null;const r=e.match(/```json\s*([\s\S]*?)\s*```/);r&&(e=r[1]),e=e.replace(/"[^"]+"\s*:\s*undefined\s*,?\s*/g,""),e=e.replace(/,(\s*[}\]])/g,"$1");try{return Yi.parse(e)}catch(n){const o=n.message.match(/invalid character .* at (\d+):(\d+)/);if(o){const s=parseInt(o[2],10);if(e.substring(s-2,s-1)==='"')return e=e.substring(0,s-2)+"\\"+e.substring(s-2),cs(e)}return null}}function Fu({description:e,existingScenarios:r,scenariosDataStructure:n,flowSelections:a}){let o="";return a&&a.length>0&&(o=`
|
|
119
|
-
User-selected Execution Flow Values:
|
|
120
|
-
The user has specifically requested these values be used in the scenario:
|
|
121
|
-
${a.map(s=>` - ${s.path}: ${s.value}${s.isCustom?" (custom value)":""}`).join(`
|
|
122
|
-
`)}
|
|
123
|
-
|
|
124
|
-
IMPORTANT: The mockData MUST include these specific values for the specified paths. Generate a scenario name and description that reflects these choices.
|
|
125
|
-
`),`Mock Scenario Data Structure:
|
|
126
|
-
\`\`\`
|
|
127
|
-
${JSON.stringify(n,null,2)}
|
|
128
|
-
\`\`\`
|
|
129
|
-
Existing Mock Scenario Data:
|
|
130
|
-
\`\`\`
|
|
131
|
-
${JSON.stringify(r,null,2)}
|
|
132
|
-
\`\`\`
|
|
133
|
-
${o}
|
|
134
|
-
New Scenario user-created prompt: "${e||"(No additional description - generate based on selected execution flow values)"}"
|
|
135
|
-
`}function Ou({description:e,editingMockName:r,editingMockData:n,existingScenarios:a,scenariosDataStructure:o}){const s=a.find(i=>i.name===_r);return`Mock Scenario Data Structure:
|
|
136
|
-
\`\`\`
|
|
137
|
-
${JSON.stringify({props:o.arguments,dataVariables:o.dataForMocks},null,2)}
|
|
138
|
-
\`\`\`
|
|
139
|
-
|
|
140
|
-
Existing Mock Scenario Data:
|
|
141
|
-
\`\`\`
|
|
142
|
-
${JSON.stringify(a.map(i=>({name:i.name,data:Ot(s.metadata.data,i.metadata.data)})),null,2)}
|
|
143
|
-
\`\`\`
|
|
144
|
-
|
|
145
|
-
Mock Scenario that should be edited: "${r}"
|
|
146
|
-
${n?`The portion of the data that should be edited:
|
|
147
|
-
\`\`\`
|
|
148
|
-
${JSON.stringify(n,null,2)}
|
|
149
|
-
\`\`\``:""}
|
|
150
|
-
|
|
151
|
-
How this data should be changed: "${e}"
|
|
152
|
-
`}async function zu({description:e,editingMockName:r,editingMockData:n,existingScenarios:a,scenariosDataStructure:o,flowSelections:s,model:i}){const c=r?Ou({description:e,editingMockName:r,editingMockData:n,existingScenarios:a,scenariosDataStructure:o}):Fu({description:e,existingScenarios:a,scenariosDataStructure:o,flowSelections:s}),d=await fn({type:"guessScenarioDataFromDescription",systemMessage:r?Bu(n):Yu,prompt:c,model:i??qd});await su({object_type:"guessScenarioDataFromDescription",object_id:"new",propsJson:{description:e,editingMockName:r,editingMockData:n,existingScenarios:a,scenariosDataStructure:o,model:i},...d.stats});const{completion:m}=d;return m?cs(m):(console.log("CodeYam: guessing scenario data failed: No response from AI"),null)}const Yu=`
|
|
153
|
-
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.
|
|
154
|
-
|
|
155
|
-
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.
|
|
156
|
-
|
|
157
|
-
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.
|
|
158
|
-
|
|
159
|
-
You must respond with valid JSON following this format of this TS type definition:
|
|
160
|
-
\`\`\`
|
|
161
|
-
export type ScenarioData = {
|
|
162
|
-
name: string;
|
|
163
|
-
description: string;
|
|
164
|
-
data: {
|
|
165
|
-
mockData: { [key: string]: unknown };
|
|
166
|
-
argumentsData: { [key: string]: unknown };
|
|
167
|
-
};
|
|
168
|
-
};
|
|
169
|
-
|
|
170
|
-
\`\`\`
|
|
171
|
-
`,Bu=e=>`
|
|
172
|
-
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.
|
|
173
|
-
|
|
174
|
-
Your goal is to edit one of the scenarios, named as the "Mock Scenario that should be edited".
|
|
175
|
-
${e?`
|
|
176
|
-
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.`:""}
|
|
177
|
-
|
|
178
|
-
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.
|
|
179
|
-
|
|
180
|
-
You must respond with valid JSON following this type definition:
|
|
181
|
-
\`\`\`
|
|
182
|
-
{
|
|
183
|
-
data: {
|
|
184
|
-
mockData: { [key: string]: unknown };
|
|
185
|
-
argumentsData: { [key: string]: unknown };
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
\`\`\`
|
|
189
|
-
`;async function Uu({request:e}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});try{const r=await e.json(),{description:n,existingScenarios:a,scenariosDataStructure:o,editingMockName:s,editingMockData:i,flowSelections:c}=r;if(!n&&(!c||c.length===0))return G({error:"Missing required field: description or flowSelections"},{status:400});const d=await zu({description:n||"",existingScenarios:a??[],scenariosDataStructure:o,editingMockName:s,editingMockData:i,flowSelections:c}),m=(d==null?void 0:d.data)||d;return G({success:!0,data:m})}catch(r){return console.error("[Generate Scenario Data API] Error:",r),G({error:"Failed to generate scenario data",details:r instanceof Error?r.message:String(r)},{status:500})}}const Wu=Object.freeze(Object.defineProperty({__proto__:null,action:Uu},Symbol.toStringTag,{value:"Module"}));async function Hu(e,r){const n=pe();if(!n)return{entityCalls:[],analysisCalls:[]};const a=ee.join(n,".codeyam","llm-calls");try{await Ie.access(a)}catch{return{entityCalls:[],analysisCalls:[]}}const o=[],s=[];try{const c=(await Ie.readdir(a)).filter(x=>x.endsWith(".json")),d=`${e}_`,m=r?`${r}_`:null,u=[],p=[];for(const x of c)x.startsWith(d)||m&&x.startsWith(m)?u.push(x):p.push(x);const h=u.map(async x=>{try{const b=ee.join(a,x),v=await Ie.readFile(b,"utf-8");return JSON.parse(v)}catch{return null}}),f=p.map(async x=>{try{const b=ee.join(a,x),v=await Ie.readFile(b,"utf-8"),C=JSON.parse(v);return C.object_id===e||r&&C.object_id===r?C:null}catch{return null}}),[y,g]=await Promise.all([Promise.all(h),Promise.all(f)]),w=[...y,...g].filter(x=>x!==null);for(const x of w)x.object_id===e?o.push(x):r&&x.object_id===r&&s.push(x);o.sort((x,b)=>b.created_at-x.created_at),s.sort((x,b)=>b.created_at-x.created_at)}catch(i){console.error("Error loading LLM calls:",i)}return{entityCalls:o,analysisCalls:s}}async function qu({params:e,request:r}){const{entitySha:n}=e;if(!n)return G({error:"Entity SHA is required"},{status:400});const o=new URL(r.url).searchParams.get("analysisId")||void 0,s=await Hu(n,o);return G(s)}const Gu=Object.freeze(Object.defineProperty({__proto__:null,loader:qu},Symbol.toStringTag,{value:"Module"}));function Ju(e){const r=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const n=Me("git status --porcelain",{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"]});return Vu(n)}catch(n){return console.error("Failed to get git status:",n),[]}}function Vu(e){const r=e.trim().split(`
|
|
190
|
-
`).filter(a=>a.length>0),n=[];for(const a of r){const o=a[0],s=a[1];let i=a.slice(2).replace(/^[ \t]+/,""),c,d=!1,m;if(o==="A"||s==="A")c="added",d=o==="A";else if(o==="M"||s==="M")c="modified",d=o==="M";else if(o==="D"||s==="D")c="deleted",d=o==="D";else if(o==="R"||s==="R"){c="renamed",d=o==="R";const u=i.indexOf(" -> ");u!==-1&&(m=i.slice(0,u).trim(),i=i.slice(u+4).trim())}else s==="?"?(c="untracked",d=!1):(c="modified",d=o!==" "&&o!=="?");if(i.endsWith("/")){const u=process.env.CODEYAM_ROOT_PATH||process.cwd(),p=he.join(u,i);try{const h=(y,g)=>{const w=Nt.readdirSync(y,{withFileTypes:!0}),x=[];for(const b of w){const v=he.join(y,b.name),C=he.relative(u,v);b.isDirectory()?x.push(...h(v,g)):b.isFile()&&x.push(C)}return x},f=h(p,u);for(const y of f)n.push({path:y,status:c,staged:d,...m&&{oldPath:m}})}catch(h){console.error(`Failed to expand directory ${i}:`,h)}}else n.push({path:i,status:c,staged:d,...m&&{oldPath:m}})}return n}function Qu(e){const r=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me("git branch --show-current",{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch(n){return console.error("Failed to get current branch:",n),null}}function Ku(e){const r=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{const a=Me('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""',{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().match(/refs\/remotes\/origin\/(.+)/);if(a)return a[1];try{return Me("git show-ref --verify --quiet refs/heads/main",{cwd:r,stdio:["pipe","pipe","ignore"]}),"main"}catch{try{return Me("git show-ref --verify --quiet refs/heads/master",{cwd:r,stdio:["pipe","pipe","ignore"]}),"master"}catch{return"main"}}}catch(n){return console.error("Failed to get default branch:",n),"main"}}function Zu(e){const r=e||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me('git branch --format="%(refname:short)"',{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
191
|
-
`).filter(a=>a.length>0)}catch(n){return console.error("Failed to get branches:",n),[]}}function ds(){const e=pe();return e?Ju(e):[]}function Xu(){const e=pe();return e?Qu(e):null}function eh(){const e=pe();return e?Ku(e):"main"}function th(){const e=pe();return e?Zu(e):[]}function us(e,r){const n=pe();return n?rh(e,r,n):[]}function rh(e,r,n){const a=n||process.env.CODEYAM_ROOT_PATH||process.cwd();try{return Me(`git diff --name-status ${e}...${r}`,{cwd:a,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim().split(`
|
|
192
|
-
`).filter(i=>i.length>0).map(i=>{const c=i.split(" "),d=c[0];let m=c[1],u,p;return d==="A"?p="added":d==="M"?p="modified":d==="D"?p="deleted":d.startsWith("R")?(p="renamed",u=c[1],m=c[2]):p="modified",{path:m,status:p,...u&&{oldPath:u}}})}catch(o){return console.error("Failed to get branch diff:",o),[]}}function nh(e,r){const n=r||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let a="";try{a=Me(`git show HEAD:"${e}"`,{cwd:n,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{a=""}let o="";try{o=Nt.readFileSync(he.join(n,e),"utf8")}catch(s){console.error(`Failed to read current file ${e}:`,s),o=""}return{oldContent:a,newContent:o,fileName:e}}catch(a){return console.error(`Failed to get diff for ${e}:`,a),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function ah(e){const r=pe();return r?nh(e,r):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function oh(e,r,n,a){const o=a||process.env.CODEYAM_ROOT_PATH||process.cwd();try{let s="";try{s=Me(`git show ${r}:"${e}"`,{cwd:o,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{s=""}let i="";try{i=Me(`git show ${n}:"${e}"`,{cwd:o,encoding:"utf8",stdio:["pipe","pipe","ignore"],maxBuffer:1024*1024*10})}catch{i=""}return{oldContent:s,newContent:i,fileName:e}}catch(s){return console.error(`Failed to get branch diff for ${e}:`,s),{oldContent:"Error loading old content",newContent:"Error loading new content",fileName:e}}}function ur(e,r,n){const a=pe();return a?oh(e,r,n,a):{oldContent:"Error: No project root",newContent:"Error: No project root",fileName:e}}function Ya(e,r){var n,a;try{return((a=(n=Me(`git rev-parse ${e}`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","ignore"]}))==null?void 0:n.toString())==null?void 0:a.trim())??null}catch(o){return console.error(`Failed to get commit SHA for ${e}:`,o),""}}function sh(e,r,n,a){const o=Sn.createHash("sha256");return o.update(`${e}:${r}:${n}:${a}`),o.digest("hex").substring(0,16)}function hs(){const e=pe();if(!e)throw new Error("No project root found");const r=he.join(e,".codeyam","cache","branch-entity-diff");return Nt.existsSync(r)||Nt.mkdirSync(r,{recursive:!0}),r}function ih(e){try{const r=hs(),n=he.join(r,`${e}.json`);if(!Nt.existsSync(n))return null;const a=Nt.readFileSync(n,"utf8");return JSON.parse(a)}catch(r){return console.error("Failed to read cache:",r),null}}function lh(e,r){try{const n=hs(),a=he.join(n,`${e}.json`);Nt.writeFileSync(a,JSON.stringify(r,null,2))}catch(n){console.error("Failed to write cache:",n)}}function ch(e,r,n){const a=fr(r,e),o=fr(n,e),s=new Map(a.map(u=>[u.name,u])),i=new Map(o.map(u=>[u.name,u])),c=[],d=[],m=[];for(const[u,p]of i){const h=s.get(u);h?h.sha!==p.sha&&d.push({name:u,baseSha:h.sha,compareSha:p.sha,entityType:p.entityType}):c.push(p)}for(const[u,p]of s)i.has(u)||m.push(p);return{filePath:e,newEntities:c,modifiedEntities:d,deletedEntities:m}}function dh(e,r){const n=pe();if(!n)throw new Error("No project root found");const a=Ya(e,n),o=Ya(r,n);if(!a||!o)throw new Error(`Failed to get commit SHAs for branches: ${e}, ${r}`);const s=sh(e,r,a,o),i=ih(s);if(i)return console.log(`Using cached branch entity diff: ${s}`),i;const c=us(e,r),d=[];for(const u of c)if(u.path.match(/\.(tsx?|jsx?)$/))if(u.status==="deleted"){const p=ur(u.path,e,r),h=fr(p.oldContent,u.path);d.push({filePath:u.path,newEntities:[],modifiedEntities:[],deletedEntities:h})}else if(u.status==="added"){const p=ur(u.path,e,r),h=fr(p.newContent,u.path);d.push({filePath:u.path,newEntities:h,modifiedEntities:[],deletedEntities:[]})}else{const p=ur(u.path,e,r),h=ch(u.path,p.oldContent,p.newContent);(h.newEntities.length>0||h.modifiedEntities.length>0||h.deletedEntities.length>0)&&d.push(h)}const m={baseBranch:e,compareBranch:r,baseCommitSha:a,compareCommitSha:o,fileComparisons:d,cacheKey:s,computedAt:new Date().toISOString()};return lh(s,m),m}function uh({request:e}){try{const r=new URL(e.url),n=r.searchParams.get("base"),a=r.searchParams.get("compare");if(!n||!a)return G({error:"Missing required parameters: base and compare"},{status:400});const o=dh(n,a);return G(o)}catch(r){return console.error("Failed to compute branch entity diff:",r),G({error:"Failed to compute branch entity diff",details:r instanceof Error?r.message:String(r)},{status:500})}}const hh=Object.freeze(Object.defineProperty({__proto__:null,loader:uh},Symbol.toStringTag,{value:"Module"}));async function mh({request:e}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});try{const r=await e.json(),{serverUrl:n,scenarioId:a,projectId:o,viewportWidth:s=1440}=r;if(!n||!a||!o)return G({error:"Missing required fields: serverUrl, scenarioId, and projectId"},{status:400});console.log(`[Capture] URL to capture: ${n}`),console.log(`[Capture] Scenario ID from request: ${a}`);const i=pe();if(!i)return G({error:"Project root not found"},{status:500});const c=ee.join(i,"background","src","lib","virtualized","playwright","captureFromUrl.ts"),d=JSON.stringify({url:n,scenarioId:a,projectId:o,projectRoot:i,viewportWidth:s}),m=await new Promise(h=>{const f=ee.join(i,".codeyam","db.sqlite3"),y=kr("npx",["tsx",c,d],{cwd:i,env:{...process.env,SQLITE_PATH:f}});let g="",w="";y.stdout.on("data",x=>{const b=x.toString();g+=b;const v=b.trim().split(`
|
|
193
|
-
`);for(const C of v)C.includes("[Capture]")&&console.log(C)}),y.stderr.on("data",x=>{const b=x.toString();w+=b,console.error("[Capture:Error]",b.trim())}),y.on("close",x=>{h(x===0?{success:!0,output:g}:{success:!1,output:g,error:w||`Process exited with code ${x}`})}),y.on("error",x=>{console.error("[Capture] Failed to spawn child process:",x),h({success:!1,output:"",error:x.message})})});if(!m.success)return G({error:"Failed to capture screenshot",details:m.error},{status:500});const u=m.output.match(/\[Capture\] RESULT:(.+)/);if(!u)return G({error:"Failed to parse capture result"},{status:500});const p=JSON.parse(u[1]);return G(p)}catch(r){return console.error("[Capture] Error:",r),G({error:"Failed to capture screenshot",details:r instanceof Error?r.message:String(r)},{status:500})}}const ph=Object.freeze(Object.defineProperty({__proto__:null,action:mh},Symbol.toStringTag,{value:"Module"}));async function fh(e,r,n){var f;console.log(`[recapture] Starting recapture for analysis ${e} with width ${r}`),await $e();const a=await at({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);const o=ve(),s=a.entitySha,i=await o.selectFrom("entities").select(["metadata"]).where("sha","=",s).executeTakeFirst();let c={};if(i!=null&&i.metadata&&(typeof i.metadata=="string"?c=JSON.parse(i.metadata):c=i.metadata),c.defaultWidth=r,await o.updateTable("entities").set({metadata:JSON.stringify(c)}).where("sha","=",s).execute(),console.log(`[recapture] Updated defaultWidth for entity ${s} to ${r}`),!a.commit)throw new Error(`Commit not found for analysis ${e}`);console.log(`[recapture] Loaded analysis with ${((f=a.scenarios)==null?void 0:f.length)||0} scenarios`),await Tt(e,y=>{if(y){if(y.readyToBeCaptured=!0,y.scenarios)for(const g of y.scenarios)delete g.finishedAt,delete g.startedAt,delete g.screenshotStartedAt,delete g.screenshotFinishedAt,delete g.interactiveStartedAt,delete g.interactiveFinishedAt,delete g.error,delete g.errorStack;delete y.finishedAt}}),console.log(`[recapture] Marked analysis ${e} as ready to be captured`);const d=pe();if(!d)throw new Error("Project root not found");const m=ee.join(d,".codeyam","config.json"),u=JSON.parse(K.readFileSync(m,"utf8")),{projectSlug:p}=u;if(!p)throw new Error("Project slug not found in config");const{jobId:h}=n.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:p,analysisId:e,defaultWidth:r});return console.log(`[recapture] Recapture job queued with ID: ${h}`),{jobId:h}}async function gh(e,r,n){var u;console.log(`[recapture] Starting scenario recapture for analysis ${e}, scenario ${r}`),await $e();const a=await at({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw console.log(`[recapture] Analysis ${e} not found`),new Error(`Analysis ${e} not found`);if(!a.commit)throw new Error(`Commit not found for analysis ${e}`);const o=(u=a.scenarios)==null?void 0:u.find(p=>p.id===r);if(!o)throw console.log(`[recapture] Scenario ${r} not found in analysis ${e}`),new Error(`Scenario ${r} not found in analysis ${e}`);console.log(`[recapture] Found scenario: ${o.name}`),await Tt(e,p=>{if(p&&(p.readyToBeCaptured=!0,delete p.finishedAt,p.scenarios)){const h=p.scenarios.find(f=>f.name===o.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 ${o.name} for recapture`);const s=pe();if(!s)throw new Error("Project root not found");const i=ee.join(s,".codeyam","config.json"),c=JSON.parse(K.readFileSync(i,"utf8")),{projectSlug:d}=c;if(!d)throw new Error("Project slug not found in config");const{jobId:m}=n.enqueue({type:"recapture",commitSha:a.commit.sha,projectSlug:d,analysisId:e,scenarioId:r});return console.log(`[recapture] Scenario recapture job queued with ID: ${m}`),{jobId:m}}async function yh({request:e,context:r}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});let n=r.analysisQueue;if(n||(n=await st()),!n)return G({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("analysisId"),s=a.get("scenarioId");if(!o||!s)return G({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Starting scenario recapture for analysis ${o}, scenario ${s}`);const i=await gh(o,s,n);return console.log("[API] Scenario recapture queued",i),G({success:!0,message:"Scenario recapture queued",...i})}catch(a){return console.log("[API] Error during scenario recapture:",a),G({error:"Failed to recapture scenario",details:a instanceof Error?a.message:String(a)},{status:500})}}const xh=Object.freeze(Object.defineProperty({__proto__:null,action:yh},Symbol.toStringTag,{value:"Module"}));async function bh({params:e,request:r}){const{projectSlug:n}=e;if(!n)return new Response("Project slug is required",{status:400});if(r.method!=="DELETE")return new Response("Method not allowed",{status:405});const a=$r(n);try{return await _i(a,"","utf-8"),new Response("Logs cleared successfully",{status:200,headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(o){console.error("[api.logs] Error clearing log file:",o);const s=o instanceof Error?o.message:String(o);return new Response(`Error clearing log file: ${s}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}async function wh({params:e}){const{projectSlug:r}=e;if(!r)return new Response("Project slug is required",{status:400});const n=$r(r);try{if(!Ci(n))return new Response("No logs available yet. Analysis may not have started.",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});const a=await Mi(n,"utf-8");return!a||a.trim().length===0?new Response("Log file is empty. Waiting for analysis to start...",{headers:{"Content-Type":"text/plain; charset=utf-8"}}):new Response(a,{headers:{"Content-Type":"text/plain; charset=utf-8"}})}catch(a){console.error("[api.logs] Error reading log file:",a);const o=a instanceof Error?a.message:String(a);return new Response(`Error reading log file: ${o}`,{status:500,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}const vh=Object.freeze(Object.defineProperty({__proto__:null,action:bh,loader:wh},Symbol.toStringTag,{value:"Module"}));async function Ch(e,r){var s,i,c,d,m,u;console.log(`[executeLibraryFunction] Starting execution for analysis ${e}, scenario ${r}`),await $e();const n=await at({id:e,includeScenarios:!0,includeFile:!0});if(!n)throw new Error(`Analysis ${e} not found`);const a=(s=n.scenarios)==null?void 0:s.find(p=>p.id===r);if(!a)throw new Error(`Scenario ${r} not found in analysis ${e}`);console.log(`[executeLibraryFunction] Executing ${n.entityName} with scenario ${a.name}`);const o={returnValue:{status:"success",data:((d=(c=(i=a.metadata)==null?void 0:i.data)==null?void 0:c.argumentsData)==null?void 0:d[0])||{},timestamp:new Date().toISOString()},error:null,sideEffects:{consoleOutput:[{level:"log",args:[`Executing ${n.entityName}...`]},{level:"log",args:["Processing input:",JSON.stringify((u=(m=a.metadata)==null?void 0:m.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 ${n.entityName}`),o}async function Nh({request:e}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});try{const r=await e.formData(),n=r.get("analysisId"),a=r.get("scenarioId");if(!n||!a)return G({error:"Missing required fields: analysisId and scenarioId"},{status:400});console.log(`[API] Executing library function for analysis ${n}, scenario ${a}`);const o=await Ch(n,a);return console.log("[API] Function execution completed successfully"),G({success:!0,result:o})}catch(r){return console.log("[API] Error during function execution:",r),G({success:!1,error:"Failed to execute function",details:r instanceof Error?r.message:String(r)},{status:500})}}const Sh=Object.freeze(Object.defineProperty({__proto__:null,action:Nh},Symbol.toStringTag,{value:"Module"}));function Eh({request:e}){return G({status:"ok"})}async function Ah({request:e,context:r}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});let n=r.analysisQueue;if(n||(n=await st()),!n)return console.error("[Interactive Mode API] Queue not initialized"),G({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("action"),s=a.get("analysisId"),i=a.get("scenarioId");if(!o||!s)return G({error:"Missing required fields: action and analysisId"},{status:400});if(o!=="start"&&o!=="stop")return G({error:'Invalid action. Must be "start" or "stop"'},{status:400});const c=await ze();if(console.log("[Interactive Mode API] projectSlug:",c),!c)return G({error:"Project not initialized"},{status:500});if(o==="start"){const d=await n.enqueue({type:"interactive-start",analysisId:s,scenarioId:i,projectSlug:c});return G({success:!0,action:"start",message:"Interactive mode starting...",jobId:d})}else{const d=await n.enqueue({type:"interactive-stop",analysisId:s,projectSlug:c});return G({success:!0,action:"stop",message:"Interactive mode stopping...",jobId:d})}}catch(a){console.error("[Interactive Mode API] Error:",a);const o=a instanceof Error?a.message:String(a),s=a instanceof Error?a.stack:void 0;return console.error("[Interactive Mode API] Error stack:",s),G({error:"Failed to control interactive mode",details:o},{status:500})}}const kh=Object.freeze(Object.defineProperty({__proto__:null,action:Ah,loader:Eh},Symbol.toStringTag,{value:"Module"}));async function Ph({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const r=await e.json(),{scenarioId:n,screenshotPaths:a}=r;if(!n)return Response.json({error:"Missing required field: scenarioId"},{status:400});if(console.log(`[API] Deleting scenario ${n}`),a&&a.length>0){const o=pe();if(o)for(const s of a){const i=he.join(o,".codeyam","captures","screenshots",s);try{await xe.unlink(i),console.log(`[API] Deleted screenshot: ${i}`)}catch(c){console.log(`[API] Could not delete screenshot ${i}:`,c instanceof Error?c.message:c)}}}return await Ll({ids:[n]}),console.log(`[API] Scenario ${n} deleted successfully`),Response.json({success:!0,message:"Scenario deleted successfully"})}catch(r){return console.error("[API] Error deleting scenario:",r),Response.json({error:"Failed to delete scenario",details:r instanceof Error?r.message:String(r)},{status:500})}}const _h=Object.freeze(Object.defineProperty({__proto__:null,action:Ph},Symbol.toStringTag,{value:"Module"})),qt="/tmp/codeyam",gn=process.env.CODEYAM_API_BASE||"https://dev.codeyam.com",ms=500,Mh=ms*1024*1024;function wt(e,r){try{return Me(`git ${e}`,{cwd:r,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return null}}function hr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Th(e){return wt("config user.email",e)}function Ih(e){const r=ee.join(e,".codeyam","debug-report.md");if(!K.existsSync(r))return null;try{return K.readFileSync(r,"utf8")}catch{return null}}function $h(e,r=20){const n=ee.join(qt,"local-dev",e,"codeyam","log.txt");if(!K.existsSync(n))return[];try{return K.readFileSync(n,"utf8").split(`
|
|
194
|
-
`).filter(i=>i.includes("CodeYam Log Level 1")).slice(-r)}catch{return[]}}async function jh(e){try{const r=await fetch(`${gn}/api/reports/check-base`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({baseSha:e})});if(!r.ok)return!1;const{hasBase:n}=await r.json();return n}catch{return!1}}function Rh(e,r){try{Me(`git archive HEAD | gzip > "${r}"`,{cwd:e,stdio:"pipe",shell:"/bin/bash"})}catch(n){throw new Error(`Failed to create base archive: ${n.message}`)}}function Dh(e){const{projectRoot:r,projectSlug:n,outputPath:a,metadata:o,screenshot:s,onProgress:i}=e,c=i||(()=>{}),d=Date.now(),m=ee.join(qt,`delta-staging-${d}`),u=ee.join(m,"delta");K.mkdirSync(u,{recursive:!0});try{const p=wt("diff --binary HEAD",r)||"";K.writeFileSync(ee.join(u,"tracked.patch"),p?p+`
|
|
195
|
-
`:"");const h=wt("ls-files --others --exclude-standard",r);if(h){const w=ee.join(u,"untracked");K.mkdirSync(w,{recursive:!0});for(const x of h.split(`
|
|
196
|
-
`).filter(Boolean)){const b=ee.join(r,x),v=ee.join(w,x);if(K.existsSync(b)){const C=ee.dirname(v);K.mkdirSync(C,{recursive:!0}),K.statSync(b).isFile()&&K.copyFileSync(b,v)}}}const f=ee.join(r,".codeyam");if(K.existsSync(f)){const w=ee.join(u,"codeyam");K.cpSync(f,w,{recursive:!0})}K.writeFileSync(ee.join(u,"meta.json"),JSON.stringify(o,null,2));const y=ee.join(qt,"local-dev",n,"codeyam","log.txt");K.existsSync(y)?K.copyFileSync(y,ee.join(u,"codeyam-log.txt")):K.writeFileSync(ee.join(u,"codeyam-log.txt"),`# Log file not found
|
|
197
|
-
`);const g=ee.join(r,".codeyam","debug-report.md");K.existsSync(g)&&(K.copyFileSync(g,ee.join(u,"debug-report.md")),c("Debug report included")),s&&s.length>0&&(K.writeFileSync(ee.join(u,"screenshot.jpg"),s),c(`Screenshot included (${hr(s.length)})`));try{Me(`tar -czf "${a}" -C "${m}" delta`,{stdio:"pipe"})}catch(w){throw new Error(`tar failed: ${w.message}`)}}finally{K.rmSync(m,{recursive:!0,force:!0})}}async function Lh(e){const{projectRoot:r,projectSlug:n,feedback:a,screenshot:o,onProgress:s}=e,i=s||(()=>{});i("Gathering metadata...");const c=wt("rev-parse HEAD",r);if(!c)throw new Error("At least one commit is required to generate a bundle. Please commit your changes first.");const d=wt("rev-parse --abbrev-ref HEAD",r)||"unknown",m=wt("status --porcelain",r),u=wt("remote get-url origin",r),p=m!==null&&m.length>0,h=Zo(n),f=Ih(r);let y=a;f&&(y={...a||{issueType:"other",source:"cli"},debugReport:f},i("Found debug report from /codeyam:diagnose workflow"));const g={timestamp:new Date().toISOString(),projectSlug:n,git:{sha:c,branch:d,isDirty:p,remoteUrl:u},versions:{cli:h.cliVersion,webserver:h.webserverVersion,node:process.version},system:{platform:process.platform,arch:process.arch},feedback:y},w=Date.now(),x=ee.join(qt,`base-${c}-${w}.tar.gz`),b=ee.join(qt,`delta-${n}-${w}.tar.gz`);i("Checking for existing base...");const v=await jh(c);let C=null;v?i("Server already has base, skipping..."):(i("Generating base archive..."),Rh(r,x),C=K.statSync(x).size,i(`Base archive: ${hr(C)}`)),i("Generating delta archive..."),Dh({projectRoot:r,projectSlug:n,outputPath:b,metadata:g,screenshot:o,onProgress:s});const N=K.statSync(b).size;i(`Delta archive: ${hr(N)}`);const A=(C||0)+N;if(A>Mh)throw K.existsSync(x)&&K.unlinkSync(x),K.unlinkSync(b),new Error(`Bundle too large: ${hr(A)} (max: ${ms} MB). Try removing large files from the project or adding them to .gitignore`);return{basePath:v?null:x,deltaPath:b,metadata:g,baseSha:c,baseSize:C,deltaSize:N}}async function Fh(e){const{basePath:r,deltaPath:n,projectSlug:a,metadata:o,baseSha:s,deltaSize:i,onProgress:c}=e,d=c||(()=>{}),m=K.statSync(n),u=r?K.statSync(r):null,p=m.size+((u==null?void 0:u.size)||0);d("Requesting upload URLs...");const h=await fetch(`${gn}/api/reports/request-upload`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectSlug:a,fileSizeBytes:p,baseSha:s,needsBaseUpload:r!==null,deltaSizeBytes:i,metadata:{timestamp:o.timestamp,git:o.git,versions:o.versions,system:o.system,feedback:o.feedback}})});if(!h.ok){const v=await h.json();throw new Error(v.error||`Server returned ${h.status}`)}const{reportId:f,deltaUploadUrl:y,baseUploadUrl:g}=await h.json(),w=[];if(r&&g){d("Uploading base...");const v=K.readFileSync(r);w.push(fetch(g,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:v}).then(C=>{if(!C.ok)throw new Error(`Base upload failed: ${C.status}`)}))}d("Uploading delta...");const x=K.readFileSync(n);w.push(fetch(y,{method:"PUT",headers:{"Content-Type":"application/gzip"},body:x}).then(v=>{if(!v.ok)throw new Error(`Delta upload failed: ${v.status}`)})),await Promise.all(w),d("Confirming upload...");const b=await fetch(`${gn}/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 r&&K.existsSync(r)&&K.unlinkSync(r),K.unlinkSync(n),{bundleId:f}}async function Oh({request:e}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});try{const r=await e.formData(),n=r.get("issueType"),a=r.get("description"),o=r.get("email"),s=r.get("source"),i=r.get("entitySha"),c=r.get("scenarioId"),d=r.get("analysisId"),m=r.get("currentUrl"),u=r.get("entityName"),p=r.get("entityType"),h=r.get("scenarioName"),f=r.get("errorMessage"),y=r.get("screenshot");let g=a||void 0;!g&&u&&(h?g=`Issue on ${u} scenario "${h}"`:g=`Issue on ${u}`);let w;if(y&&y.size>0){const A=await y.arrayBuffer();w=Buffer.from(A),console.log(`[Bundle] Screenshot received: ${y.size} bytes`)}const x=pe();if(!x)return G({error:"Project root not found"},{status:500});const b=await ze();if(!b)return G({error:"Project slug not found"},{status:500});const v={issueType:n||"other",description:g,email:o||void 0,source:s||"navbar",entitySha:i||void 0,scenarioId:c||void 0,analysisId:d||void 0,currentUrl:m||void 0,recentActivity:$h(b,20),entityName:u||void 0,entityType:p||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 C=await Lh({projectRoot:x,projectSlug:b,feedback:v,screenshot:w,onProgress:A=>{console.log(`[Bundle] ${A}`)}}),E=(C.baseSize||0)+C.deltaSize;console.log(`[Bundle] Archives created: delta=${C.deltaSize} bytes${C.basePath?`, base=${C.baseSize} bytes`:" (base reused)"}`);const N=await Fh({basePath:C.basePath,deltaPath:C.deltaPath,projectSlug:b,metadata:C.metadata,baseSha:C.baseSha,deltaSize:C.deltaSize,onProgress:A=>{console.log(`[Bundle] ${A}`)}});return console.log(`[Bundle] Upload complete: ${N.bundleId}`),G({success:!0,reportId:N.bundleId,size:E})}catch(r){return console.error("[Bundle] Error:",r),G({error:r.message||"Failed to generate bundle"},{status:500})}}function zh(){const e=pe(),r=e?Th(e):null;return G({defaultEmail:r})}const Yh=Object.freeze(Object.defineProperty({__proto__:null,action:Oh,loader:zh},Symbol.toStringTag,{value:"Module"}));function Ct(){const e=process.memoryUsage(),r=Ui.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(r.total_heap_size/1024/1024),totalHeapSizeExecutable:Math.round(r.total_heap_size_executable/1024/1024),totalPhysicalSize:Math.round(r.total_physical_size/1024/1024),totalAvailableSize:Math.round(r.total_available_size/1024/1024),usedHeapSize:Math.round(r.used_heap_size/1024/1024),heapSizeLimit:Math.round(r.heap_size_limit/1024/1024),mallocedMemory:Math.round(r.malloced_memory/1024/1024),peakMallocedMemory:Math.round(r.peak_malloced_memory/1024/1024)},system:{totalMemory:Math.round(dn.totalmem()/1024/1024),freeMemory:Math.round(dn.freemem()/1024/1024)}}}function Bh(){const e=Ct();console.log(`
|
|
198
|
-
[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 r=(e.heap.usedHeapSize/e.heap.heapSizeLimit*100).toFixed(1);return console.log(` Heap Usage: ${r}% of limit`),e}function Uh(){if(global.gc){console.log("[Memory Profiler] Running garbage collection...");const e=Ct();global.gc();const r=Ct(),n=e.process.heapUsed-r.process.heapUsed;return console.log(`[Memory Profiler] GC freed ${n} MB`),console.log(`[Memory Profiler] Heap: ${r.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 Wh(){const e=Ct(),r=e.heap.usedHeapSize/e.heap.heapSizeLimit*100,n={highHeapUsage:r>80,highExternalMemory:e.process.external>200,highArrayBuffers:e.process.arrayBuffers>100,nearHeapLimit:e.heap.totalAvailableSize<100},a=[];return n.highHeapUsage&&a.push(`High heap usage: ${r.toFixed(1)}% of limit`),n.highExternalMemory&&a.push(`High external memory: ${e.process.external} MB`),n.highArrayBuffers&&a.push(`High ArrayBuffer usage: ${e.process.arrayBuffers} MB`),n.nearHeapLimit&&a.push(`Near heap limit: only ${e.heap.totalAvailableSize} MB available`),{indicators:n,warnings:a,hasIssues:a.length>0}}function Hh({request:e}){const n=new URL(e.url).searchParams.get("action");try{switch(n){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 a=Uh(),o=Ct();return Response.json({success:a,message:a?"Garbage collection completed":"GC not available. Restart server with --expose-gc flag.",stats:o})}case"detailed":{const a=Bh();return Response.json({success:!0,stats:a})}case"leaks":{const a=Wh(),o=Ct();return Response.json({success:!0,leakCheck:a,stats:o})}default:{const a=Ct();return Response.json({success:!0,stats:a,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(a){return console.error("[Memory API] Error:",a),Response.json({success:!1,error:a.message},{status:500})}}const qh=Object.freeze(Object.defineProperty({__proto__:null,loader:Hh},Symbol.toStringTag,{value:"Module"})),Ba=kn(En);async function Gh({request:e}){const n=new URL(e.url).searchParams.get("pids");if(!n)return Response.json({error:"Missing pids parameter"},{status:400});const a=n.split(",").map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s));if(a.length===0)return Response.json({error:"No valid PIDs provided"},{status:400});const o=await Promise.all(a.map(async s=>{const i=Jh(s),c=i?await Vh(s):null;return{pid:s,isRunning:i,processName:c}}));return Response.json({processes:o})}function Jh(e){try{return process.kill(e,0),!0}catch{return!1}}async function Vh(e){try{const{stdout:r}=await Ba(`ps -p ${e} -o comm=`);return r.trim()||null}catch{try{const{stdout:n}=await Ba(`ps -p ${e} -o args=`),a=n.trim(),o=a.match(/codeyam-(\w+)/);return o?`codeyam-${o[1]}`:a.split(" ")[0]||null}catch{return null}}}const Qh=Object.freeze(Object.defineProperty({__proto__:null,loader:Gh},Symbol.toStringTag,{value:"Module"})),Kh=An(import.meta.url),Zh=ee.dirname(Kh);function Xh({request:e}){if(e.method!=="POST")return new Response("Method not allowed",{status:405});try{const r=es(),n=pe()||(r==null?void 0:r.projectRoot);if(!n)throw new Error("Could not determine project root");const a=(r==null?void 0:r.port)||3111,o=ee.join(Zh,"..","..","..","..","webserver","bootstrap.js"),s=ee.join(n,".codeyam","logs");K.existsSync(s)||K.mkdirSync(s,{recursive:!0});const i=K.openSync(ee.join(s,"background-server.log"),"a"),c=K.openSync(ee.join(s,"background-server-error.log"),"a"),d=new Date().toISOString();K.appendFileSync(ee.join(s,"background-server.log"),`
|
|
199
|
-
[${d}] Server restart requested via dashboard
|
|
200
|
-
`),Fc();const m=kr("node",[o],{detached:!0,stdio:["ignore",i,c],env:{...process.env,CODEYAM_PORT:a.toString(),CODEYAM_ROOT_PATH:n,CODEYAM_PROCESS_NAME:"codeyam-server",CODEYAM_WAIT_FOR_PORT:"true"}});m.unref(),console.log(`[api.restart-server] Spawned new server process (pid: ${m.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(r){return console.error("[api.restart-server] Error restarting server:",r),new Response(JSON.stringify({success:!1,error:r instanceof Error?r.message:"Unknown error"}),{status:500,headers:{"Content-Type":"application/json"}})}}const em=Object.freeze(Object.defineProperty({__proto__:null,action:Xh},Symbol.toStringTag,{value:"Module"}));async function tm({request:e}){if(e.method!=="POST")return Response.json({error:"Method not allowed"},{status:405});try{const r=await e.json(),{analysis:n,scenarios:a}=r;if(!n||!a)return Response.json({error:"Missing required fields: analysis and scenarios"},{status:400});console.log(`[API] Saving scenarios for analysis ${n.id}`),console.log(`[API] Received ${a.length} scenarios to save`),a.forEach((c,d)=>{var p,h,f,y,g;const m=(h=(p=c.metadata)==null?void 0:p.data)==null?void 0:h.argumentsData,u=Array.isArray(m)&&m.length>0?JSON.stringify(m[0]).substring(0,200):"empty-or-not-array";console.log(`[API] Scenario ${d}: ${c.name}`,{id:c.id,projectId:c.projectId,analysisId:c.analysisId,hasMetadata:!!c.metadata,hasData:!!((f=c.metadata)!=null&&f.data),mockDataKeys:(g=(y=c.metadata)==null?void 0:y.data)!=null&&g.mockData?Object.keys(c.metadata.data.mockData):[],argumentsDataLength:Array.isArray(m)?m.length:"not-array",argumentsDataPreview:u})});const o=a.map(c=>({...c,projectId:c.projectId||n.projectId,analysisId:c.analysisId||n.id})),s=await ec(o);if(!s||s.length===0)throw new Error("Failed to save scenarios to database");console.log(`[API] Scenarios saved successfully for analysis ${n.id}`),console.log(`[API] Saved ${s.length} scenarios to database`),s.forEach((c,d)=>{var u,p;const m=(p=(u=c.metadata)==null?void 0:u.data)==null?void 0:p.argumentsData;console.log(`[API] Saved scenario ${d}: ${c.name}`,{id:c.id,argumentsDataLength:Array.isArray(m)?m.length:"not-array"})});const i={...n,scenarios:s};return Response.json({success:!0,analysis:i})}catch(r){return console.error("[API] Error saving scenarios:",r),Response.json({error:"Failed to save scenarios",details:r instanceof Error?r.message:String(r)},{status:500})}}const rm=Object.freeze(Object.defineProperty({__proto__:null,action:tm},Symbol.toStringTag,{value:"Module"}));async function nm({request:e}){try{const r=await e.json(),{pid:n,signal:a="SIGTERM",commitSha:o}=r;if(!n||typeof n!="number")return Response.json({error:"Missing or invalid pid parameter"},{status:400});if(!Ua(n))return Response.json({error:"Process not running",pid:n},{status:404});try{process.kill(n,a)}catch(u){return Response.json({error:"Failed to kill process",pid:n,details:u instanceof Error?u.message:String(u)},{status:500})}const i=3e4,c=500,d=Date.now();let m=!0;for(;m&&Date.now()-d<i;)await new Promise(u=>setTimeout(u,c)),m=Ua(n);if(m){console.warn(`Process ${n} didn't die after SIGTERM, sending SIGKILL`);try{process.kill(n,"SIGKILL"),await new Promise(u=>setTimeout(u,2e3))}catch(u){console.error(`Failed to SIGKILL process ${n}:`,u)}}if(o)try{await ct({commitSha:o,runStatusUpdate:{analyzerPid:void 0,capturePid:void 0,failedAt:new Date().toISOString(),failureReason:`Process ${n} killed by user`}})}catch(u){console.error("Failed to update database after killing process:",u)}return Response.json({success:!0,pid:n,signal:a,message:`Process ${n} killed successfully`,waitedMs:Date.now()-d})}catch(r){return console.error("Error in kill-process API:",r),Response.json({error:"Internal server error",details:r instanceof Error?r.message:String(r)},{status:500})}}function Ua(e){try{return process.kill(e,0),!0}catch{return!1}}const am=Object.freeze(Object.defineProperty({__proto__:null,action:nm},Symbol.toStringTag,{value:"Module"}));async function om({params:e}){const r=e["*"];if(!r)return new Response("Screenshot path is required",{status:400});const n=pe();if(!n)return console.error("[screenshot api] Project root not found"),new Response("Project root not found",{status:500});const a=he.join(n,".codeyam","captures","screenshots",r);try{await xe.access(a);const o=await xe.readFile(a),s=he.extname(a).toLowerCase(),i=s===".png"?"image/png":s===".jpg"||s===".jpeg"?"image/jpeg":"application/octet-stream";return new Response(o,{status:200,headers:{"Content-Type":i,"Cache-Control":"public, max-age=3600"}})}catch{return new Response("Screenshot not found",{status:404})}}const sm=Object.freeze(Object.defineProperty({__proto__:null,loader:om},Symbol.toStringTag,{value:"Module"})),Wa={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 Bn({type:e,className:r=""}){const n=Wa[e]||Wa.other;return t("div",{className:`inline-flex items-center justify-center px-[4px] rounded-[4px] ${r}`,style:{backgroundColor:n.bgColor,color:n.textColor,height:"15px"},children:t("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-semibold leading-[15px] uppercase",children:n.label})})}const im={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 lr({variant:e,pid:r,label:n,className:a=""}){const o=im[e],s=n||(e==="analyzer"&&r?`Analyzer: ${r}`:e==="capture"&&r?`Capture: ${r}`:e==="running"?"Running":e==="error"?"Error":"");return t("div",{className:`inline-flex items-center justify-center px-[8px] rounded-[4px] ${a}`,style:{backgroundColor:o.bgColor,borderWidth:"1px",borderStyle:"solid",borderColor:o.borderColor,height:"20px"},children:t("span",{className:"font-['IBM_Plex_Sans']",style:{fontSize:"10px",fontWeight:400,lineHeight:"15px",color:o.textColor},children:s})})}function De({screenshotPath:e,cacheBuster:r,alt:n,className:a="",title:o}){const[s,i]=M("loading"),[c,d]=M(!1),m=Ee(null),u=r?`/api/screenshot/${e}?cb=${r}`:`/api/screenshot/${e}`,p=()=>{i("success"),d(!0)},h=()=>{i("error"),d(!1)};return re(()=>{i("loading"),d(!1);const f=m.current;f!=null&&f.complete&&(f.naturalHeight!==0?(i("success"),d(!0)):(i("error"),d(!1)))},[u]),e?l("div",{className:"relative w-full h-full flex items-center justify-center",title:o,children:[t("img",{ref:m,src:u,alt:n,onLoad:p,onError:h,className:a||"max-w-full max-h-full object-contain",style:{visibility:c?"visible":"hidden",position:c?"relative":"absolute"}}),s==="loading"&&t("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:t("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t("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"})})}),s==="error"&&l("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:[t("span",{className:"text-2xl text-gray-400",children:"📷"}),t("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):t("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:o,children:t("span",{className:"text-2xl text-gray-400",children:"📷"})})}let Ha=!1;function lm(){if(Ha)return;const e=document.createElement("style");e.textContent=`
|
|
201
|
-
@keyframes strongPulse {
|
|
202
|
-
0%, 100% { opacity: 0.2; }
|
|
203
|
-
50% { opacity: 1; }
|
|
204
|
-
}
|
|
205
|
-
`,document.head.appendChild(e),Ha=!0}function Un({size:e="medium",className:r=""}){typeof document<"u"&&lm();const n={small:{sideDotSize:3,centerDotSize:4,gap:2},medium:{sideDotSize:4,centerDotSize:6,gap:2},large:{sideDotSize:6,centerDotSize:8,gap:3}},{sideDotSize:a,centerDotSize:o,gap:s}=n[e];return l("div",{className:`flex items-center justify-center ${r}`,style:{gap:`${s}px`},role:"status","aria-label":"Loading",children:[t("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0s"}}),t("div",{className:"rounded-full",style:{width:`${o}px`,height:`${o}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.3s"}}),t("div",{className:"rounded-full",style:{width:`${a}px`,height:`${a}px`,backgroundColor:"#005c75",animation:"strongPulse 1.5s ease-in-out infinite",animationDelay:"0.6s"}})]})}async function cm({request:e,context:r,params:n}){var O,F,R,S,H,q,J,ae;let a=r.analysisQueue;a||(a=await st());const o=new URL(e.url),s=parseInt(o.searchParams.get("page")||"1",10),i=20,c=n.tab||"current";if(!a)return G({error:"Queue not initialized",state:{paused:!1,jobs:[]},currentRun:void 0,historicalRuns:[],totalHistoricalRuns:0,currentPage:s,totalPages:0,projectSlug:null,commitSha:void 0,queueJobs:[],currentlyExecuting:null,currentEntities:[],tab:c,hasCurrentActivity:!1,queuedCount:0,recentCompletedEntities:[],hasMoreCompletedRuns:!1,currentEntityScenarios:[],currentEntityForScenarios:null,currentAnalysisStatus:null},{status:500});const d=a.getState(),m=await ze();let u=null;if(m&&((O=d==null?void 0:d.currentlyExecuting)!=null&&O.commitSha)){const{project:V,branch:Y}=await Fe(m),U=await gr({projectId:V.id,branchId:Y.id,shas:[d.currentlyExecuting.commitSha]});u=U&&U.length>0?U[0]:null}else u=await It();const p=async V=>{const Y=await _t(V);if(!Y)return null;const{getAnalysesForEntity:U}=await Promise.resolve().then(()=>pc),Q=await U(V,!1);return{...Y,analyses:Q||[]}},h=await Promise.all(((d==null?void 0:d.jobs)||[]).map(async V=>{const Y=[];if(V.entityShas&&V.entityShas.length>0){const U=V.entityShas.map(W=>p(W)),Q=await Promise.all(U);Y.push(...Q.filter(W=>W!==null))}return{...V,entities:Y}}));let f=null;if(d!=null&&d.currentlyExecuting){const V=d.currentlyExecuting,Y=[];if(V.entityShas&&V.entityShas.length>0){const U=V.entityShas.map(W=>p(W)),Q=await Promise.all(U);Y.push(...Q.filter(W=>W!==null))}f={...V,entities:Y}}const y=f?h.filter(V=>V.id!==f.id):h,g=((R=(F=u==null?void 0:u.metadata)==null?void 0:F.currentRun)==null?void 0:R.currentEntityShas)||[],x=(await Promise.all(g.map(V=>p(V)))).filter(V=>V!==null),b=[];if(m)try{const{project:V,branch:Y}=await Fe(m),U=await gr({projectId:V.id,branchId:Y.id,limit:100});for(const Q of U){const W=((S=Q.metadata)==null?void 0:S.historicalRuns)||[];b.push(...W)}}catch(V){console.error("[activity.tsx] Failed to load historical runs from commits:",V)}const v=[...b].sort((V,Y)=>{const U=V.lastCaptureAt||V.analysisCompletedAt||V.archivedAt||V.createdAt||"";return(Y.lastCaptureAt||Y.analysisCompletedAt||Y.archivedAt||Y.createdAt||"").localeCompare(U)}),C=(s-1)*i,E=C+i,N=v.slice(C,E),A=Math.ceil(v.length/i),_=await Promise.all(N.map(async V=>{const Y=V.currentEntityShas||[];if(Y.length===0)return{...V,entities:[]};const U=await Promise.all(Y.map(Q=>p(Q)));return{...V,entities:U.filter(Q=>Q!==null)}})),$=!!f,D=y.length,I=v.filter(V=>{const Y=!!V.failedAt,U=V.readyToBeCaptured,Q=V.capturesCompleted??0,W=U===void 0?!0:U===0||Q>=U;return!Y&&!!V.analysisCompletedAt&&W}),k=new Set(((H=f==null?void 0:f.entities)==null?void 0:H.map(V=>V.sha))||[]),T=I.filter(V=>!(V.currentEntityShas||[]).some(U=>k.has(U))),P=(await Promise.all(T.slice(0,3).map(async V=>{const Y=V.currentEntityShas||[];if(Y.length===0)return{run:V,entities:[]};const U=await Promise.all(Y.map(Q=>p(Q)));return{run:V,entities:U.filter(Q=>Q!==null)}}))).flatMap(({run:V,entities:Y})=>Y.map(U=>({...U,runId:V.id,completedAt:V.lastCaptureAt||V.analysisCompletedAt||V.archivedAt||V.createdAt})));let B=[],L=null,z=null;if((J=(q=u==null?void 0:u.metadata)==null?void 0:q.currentRun)!=null&&J.analysisCompletedAt&&x.length>0){const V=x[0].sha;L=x[0];const Y=await Tr(V);Y&&Y.length>0&&Y[0].scenarios&&(B=Y[0].scenarios,z=Y[0].status)}return G({state:{...d,jobs:y,currentlyExecuting:f},currentRun:(ae=u==null?void 0:u.metadata)==null?void 0:ae.currentRun,historicalRuns:_,totalHistoricalRuns:v.length,currentPage:s,totalPages:A,projectSlug:m,commitSha:u==null?void 0:u.sha,queueJobs:y,currentlyExecuting:f,currentEntities:x,tab:c,hasCurrentActivity:$,queuedCount:D,recentCompletedEntities:P,hasMoreCompletedRuns:T.length>3,currentEntityScenarios:B,currentEntityForScenarios:L,currentAnalysisStatus:z})}function dm({activeTab:e,hasCurrentActivity:r,queuedCount:n,historicCount:a}){const o=[{id:"current",label:"Current Activity",hasContent:r,count:r?1:null},{id:"queued",label:"Queued Activity",hasContent:n>0,count:n},{id:"historic",label:"Historic Activity",hasContent:a>0,count:a}];return t("div",{className:"border-b border-gray-200 mb-6",children:t("nav",{className:"flex gap-8",children:o.map(s=>{const i=e===s.id;return t(oe,{to:s.id==="current"?"/activity":`/activity/${s.id}`,className:`
|
|
206
|
-
relative pb-4 px-2 text-sm transition-colors cursor-pointer
|
|
207
|
-
${i?"font-medium border-b-2":"font-normal hover:text-gray-700"}
|
|
208
|
-
`,style:i?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[s.label,s.count!==null&&s.count>0&&t("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:s.count}),s.count===null&&s.hasContent&&t("span",{className:`
|
|
209
|
-
inline-block w-2 h-2 rounded-full
|
|
210
|
-
${i?"":"bg-gray-400"}
|
|
211
|
-
`,style:i?{backgroundColor:"#005C75"}:{}})]})},s.id)})})})}function um({currentlyExecuting:e,currentRun:r,state:n,projectSlug:a,commitSha:o,onShowLogs:s,recentCompletedEntities:i,hasMoreCompletedRuns:c,currentEntityScenarios:d,currentEntityForScenarios:m,currentAnalysisStatus:u}){var j,P,B,L;const[p,h]=M({}),[f,y]=M({isKilling:!1,current:0,total:0}),g=rt(),w=!!e,x=(e==null?void 0:e.entities)||[],b=!!(r!=null&&r.analysisCompletedAt),v=b&&!!(r!=null&&r.capturePid),C=!b,E=w,N=d||[],{lastLine:A}=pt(a,E);re(()=>{if(!r)return;const z=[r.analyzerPid,r.capturePid].filter(S=>!!S);if(z.length===0)return;let O=!0;const F=async()=>{try{const H=await(await fetch(`/api/process-status?pids=${z.join(",")}`)).json();if(H.processes&&O){const q={};H.processes.forEach(J=>{q[J.pid]={isRunning:J.isRunning,processName:J.processName}}),h(q)}}catch(S){O&&console.error("Failed to fetch process statuses:",S)}};F();const R=setInterval(()=>void F(),5e3);return()=>{O=!1,clearInterval(R)}},[r==null?void 0:r.analyzerPid,r==null?void 0:r.capturePid]);const[_,$]=M(!1),[D,I]=M(!1);re(()=>{x.length<=3&&_&&$(!1)},[x.length,_]),re(()=>{i.length<=3&&D&&I(!1)},[i.length,D]);const k=_?x:x.slice(0,3),T=x.length>3;return l("div",{className:"flex flex-col gap-[45px]",children:[E?l("div",{className:"rounded-[10px] p-[15px]",style:{backgroundColor:"#f6f9fc",border:"1px solid #e0e9ec"},children:[l("div",{className:"flex items-center gap-2 mb-[15px]",children:[t(Ze,{size:14,strokeWidth:2.5,className:"animate-spin",style:{color:"#005c75"}}),t("span",{className:"font-medium",style:{fontSize:"14px",lineHeight:"18px",color:"#005c75"},children:v?"Capturing...":"Analyzing..."})]}),k.map(z=>l("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:[l("div",{className:"flex items-center gap-3",children:[t("div",{children:t(Ue,{type:z.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col gap-[1px]",children:[l("div",{className:"flex items-center gap-[14px]",children:[t(oe,{to:`/entity/${z.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:z.name}),z.entityType&&t(Bn,{type:z.entityType})]}),t("div",{className:"truncate font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",width:"422px"},title:z.filePath,children:z.filePath})]})]}),t("button",{onClick:s,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"})]},z.sha)),T&&!_&&l("button",{onClick:()=>$(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",x.length-3," more"," ",x.length-3===1?"entity":"entities"]}),_&&T&&t("button",{onClick:()=>$(!1),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] mb-[15px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:"Show less"}),v&&N&&N.length>0&&m&&t("div",{className:"flex gap-[10px] overflow-x-auto mb-[15px]",children:N.map(z=>{var J,ae,V,Y;if(!z.id)return null;const O=(ae=(J=z.metadata)==null?void 0:J.screenshotPaths)==null?void 0:ae[0],F=(V=z.metadata)==null?void 0:V.noScreenshotSaved,R=O&&!F,S=(Y=u==null?void 0:u.scenarios)==null?void 0:Y.find(U=>U.name===z.name),q=S&&S.screenshotStartedAt&&!S.screenshotFinishedAt||!R&&!F;return t(oe,{to:`/entity/${m.sha}/scenarios/${z.id}`,className:"border border-solid rounded-[6px] overflow-hidden flex-shrink-0 cursor-pointer",style:{width:"160px",height:"90px",backgroundColor:q?"#f9f9f9":void 0,borderColor:q?"#efefef":"#ccc"},children:R?t(De,{screenshotPath:O,alt:z.name,className:"w-full h-full object-contain bg-gray-100"}):q?t("div",{className:"w-full h-full flex items-center justify-center",children:t(Un,{size:"medium"})}):t("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"})},z.id)})}),A&&t("div",{className:"mb-[15px] font-['IBM_Plex_Mono']",style:{fontSize:"12px",lineHeight:"20px",fontWeight:500,color:"#005c75"},children:A}),t("div",{className:"mb-[15px]",style:{height:"1px",backgroundColor:"#e0e9ec"}}),((r==null?void 0:r.analyzerPid)||(r==null?void 0:r.capturePid))&&l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-2",children:[l("span",{style:{fontSize:"12px",lineHeight:"15px",fontWeight:400,color:"#000"},children:["Running Processes:"," "]}),(r==null?void 0:r.analyzerPid)&&t(lr,{variant:"analyzer",pid:r.analyzerPid}),(r==null?void 0:r.analyzerPid)&&(C||((j=p[r.analyzerPid])==null?void 0:j.isRunning))&&t(lr,{variant:"running"}),(r==null?void 0:r.capturePid)&&t(lr,{variant:"capture",pid:r.capturePid}),(r==null?void 0:r.capturePid)&&(v||((P=p[r.capturePid])==null?void 0:P.isRunning))&&t(lr,{variant:"running"})]}),(((B=p[r==null?void 0:r.analyzerPid])==null?void 0:B.isRunning)||((L=p[r==null?void 0:r.capturePid])==null?void 0:L.isRunning))&&t("button",{onClick:()=>{const z=[r==null?void 0:r.analyzerPid,r==null?void 0:r.capturePid].filter(R=>{var S;return!!R&&((S=p[R])==null?void 0:S.isRunning)});if(z.length===0)return;const O=z.join(", ");if(!confirm(`Are you sure you want to kill all running processes (${O})?`))return;y({isKilling:!0,current:1,total:z.length}),(async()=>{for(let R=0;R<z.length;R++){const S=z[R];try{await fetch("/api/kill-process",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:S,commitSha:o||""})})}catch(H){console.error(`Failed to kill process ${S}:`,H)}R<z.length-1&&y({isKilling:!0,current:R+2,total:z.length})}y({isKilling:!1,current:0,total:0}),g.revalidate()})()},disabled:f.isKilling,className:"px-[8px] rounded-[4px] transition-colors whitespace-nowrap cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",style:{backgroundColor:"#991b1b",color:"white",fontSize:"12px",lineHeight:"15px",fontWeight:500,height:"27px",width:"114px"},children:f.isKilling?"Killing...":"Kill All Processes"})]})]}):l("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:[l("div",{className:"flex items-center gap-4",children:[t("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:t(ii,{size:24,style:{color:"#005C75"}})}),l("div",{children:[t("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Current Activity"}),l("p",{className:"text-sm",style:{color:"#8e8e8e"},children:["There are no analyses running. Trigger one from"," ",t(oe,{to:"/git",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Git"})," ","or"," ",t(oe,{to:"/files",className:"text-[#005C75] hover:underline font-medium cursor-pointer",children:"Files"}),"."]})]})]}),l(oe,{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:[t("span",{children:"+"}),t("span",{children:"New Analysis"})]})]}),i&&i.length>0&&l("div",{children:[t("h3",{className:"font-mono uppercase",style:{fontSize:"12px",lineHeight:"18px",color:"#8e8e8e",marginBottom:"16px",fontWeight:500,letterSpacing:"0.05em"},children:"Recently Completed Analyses"}),l("div",{className:"flex flex-col gap-4",children:[(D?i:i.slice(0,3)).map(z=>{var R;const O=(R=z.analyses)==null?void 0:R[0],F=(O==null?void 0:O.scenarios)||[];return O==null||O.status,t("div",{className:"rounded-[8px] p-[15px]",style:{backgroundColor:"#ffffff",border:"1px solid #aff1a9"},children:l("div",{className:"flex flex-col gap-[15px]",children:[l("div",{className:"flex items-center",children:[t("div",{className:"flex-shrink-0",children:t(Ue,{type:z.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[l("div",{className:"flex items-center gap-[5px]",children:[t(oe,{to:`/entity/${z.sha}`,className:"hover:underline cursor-pointer",title:z.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:z.name}),t("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:"#e8ffe6",color:"#00925d",fontSize:"12px",lineHeight:"16px",fontWeight:400},children:z.isUncommitted?"Modified":"Up to date"})]}),t("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e",fontWeight:400},className:"font-mono",title:z.filePath,children:z.filePath})]}),t("div",{className:"flex-1"}),t("div",{className:"flex-shrink-0",children:t("button",{onClick:s,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:S=>{S.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:S=>{S.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})})]}),t("div",{className:"border-t border-gray-200 mx-[-15px]"}),F.length>0?t("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:F.map(S=>{var ae,V,Y;if(!S.id)return null;const H=(V=(ae=S.metadata)==null?void 0:ae.screenshotPaths)==null?void 0:V[0],q=(Y=S.metadata)==null?void 0:Y.noScreenshotSaved,J=H&&!q;return l("div",{className:"shrink-0 flex flex-col gap-2",children:[t(oe,{to:`/entity/${z.sha}/scenarios/${S.id}`,className:"block cursor-pointer",children:t("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{backgroundColor:J?"#f3f4f6":"#FAFAFA",borderColor:J?"#d1d5db":"#BCCDD3",borderStyle:J?"solid":"dashed"},onMouseEnter:U=>{J&&(U.currentTarget.style.borderColor="#005C75",U.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:U=>{U.currentTarget.style.borderColor=J?"#d1d5db":"#BCCDD3",U.currentTarget.style.boxShadow="none"},children:J?t(De,{screenshotPath:H,alt:S.name,className:"max-w-full max-h-full object-contain"}):t("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"})})}),t("div",{className:"text-left text-xs text-gray-600 cursor-default",style:{fontSize:"11px",lineHeight:"14px",maxWidth:"144px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.name})]},S.id)})}):t("div",{className:"italic",style:{fontSize:"12px",color:"#646464",marginLeft:"49px"},children:"No scenarios available"})]})},z.sha)}),i.length>3&&!D&&l("button",{onClick:()=>I(!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"]}),D&&i.length>3&&t("button",{onClick:()=>I(!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 hm({queueJobs:e,state:r,currentRun:n}){if(!e||e.length===0)return l("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:[l("div",{className:"flex items-center gap-4",children:[t("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:t(li,{size:24,style:{color:"#005C75"}})}),l("div",{children:[t("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Queued Jobs"}),t("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Analysis jobs will appear here when they are queued but not yet started."})]})]}),l(oe,{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:[t("span",{children:"+"}),t("span",{children:"New Analysis"})]})]});const[a,o]=M(null),[s,i]=M(null),[c,d]=M(null),[m,u]=M(!1),[p,h]=M(!1),[f,y]=M(new Set),g=rt();re(()=>{e.length<=3&&p&&h(!1)},[e.length,p]);const w=N=>{o(N)},x=(N,A)=>{N.preventDefault(),i(A)},b=async(N,A)=>{if(N.preventDefault(),!a){i(null);return}const _=e.findIndex(I=>I.id===a);if(_===-1){o(null),i(null);return}if(_===A){o(null),i(null);return}const $=_<A?"down":"up",D=Math.abs(A-_);u(!0);try{for(let I=0;I<D;I++)await fetch("/api/queue",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"reorder",jobId:a,direction:$})});g.revalidate()}catch(I){console.error("Failed to reorder job:",I)}finally{u(!1),o(null),i(null)}},v=()=>{m||(o(null),i(null))},C=async N=>{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:N})}),window.location.reload()}catch(A){console.error("Failed to cancel job:",A)}},E=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(N){console.error("Failed to cancel jobs:",N)}};return l("div",{children:[l("div",{className:"flex items-center justify-between mb-4",children:[l("h3",{className:"font-semibold",style:{fontSize:"16px",lineHeight:"24px",color:"#343434"},children:[e.length," Queued Job",e.length!==1?"s":""]}),e.length>0&&t("button",{onClick:()=>void E(),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"})]}),l("div",{className:"flex flex-col gap-3",children:[(p?e:e.slice(0,3)).map(N=>{var T,j,P,B;const A=e.findIndex(L=>L.id===N.id),_=c===A,$=a===N.id,D=s===A,I=f.has(N.id),k=((T=N.entities)==null?void 0:T.length)>0?I?N.entities:N.entities.slice(0,3):[];return l("div",{className:"rounded-lg p-4 relative",style:{backgroundColor:"#f6f9fc",border:"1px solid #005C75",opacity:$||m?.5:1,transform:D&&a!==null&&!$?"translateY(-2px)":"translateY(0)",transition:"transform 0.2s ease, opacity 0.2s ease",cursor:m?"not-allowed":$?"grabbing":"grab"},onMouseEnter:()=>d(A),onMouseLeave:()=>d(null),draggable:!m,onDragStart:L=>{w(N.id),L.dataTransfer.effectAllowed="move"},onDragOver:L=>x(L,A),onDrop:L=>void b(L,A),onDragEnd:v,children:[l("div",{className:"absolute left-4 top-4 flex items-center gap-1.5 flex-shrink-0",children:[t(ci,{size:16,style:{color:"#005C75"}}),l("span",{style:{fontSize:"14px",fontWeight:500,lineHeight:"18px",color:"#005C75"},children:["Job ",A+1]})]}),l("div",{className:"flex flex-col gap-2 mt-8",children:[k.length>0?l(le,{children:[k.map(L=>t("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:t("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[t("div",{children:t(Ue,{type:L.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t(oe,{to:`/entity/${L.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:L.name}),L.entityType&&t(Bn,{type:L.entityType})]}),t("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:L.filePath})]})]})})},L.sha)),((j=N.entities)==null?void 0:j.length)>3&&t("button",{onClick:()=>{y(L=>{const z=new Set(L);return z.has(N.id)?z.delete(N.id):z.add(N.id),z})},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:I?"Show less":`+${N.entities.length-3} more ${N.entities.length-3===1?"entity":"entities"}`})]}):t("div",{className:"bg-white rounded",style:{border:"1px solid #e1e1e1",height:"60px"},children:t("div",{className:"flex items-center justify-between h-full px-[15px]",children:l("div",{className:"flex items-center gap-3 flex-1",children:[t("div",{style:{transform:"scale(1.0)"},children:t(lo,{size:18,style:{color:"#8e8e8e"}})}),l("div",{className:"flex-1",children:[t("div",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:((P=N.entityNames)==null?void 0:P[0])||(N.type==="analysis"?"Analysis Job":N.type==="recapture"?"Recapture Job":N.type==="debug-setup"?"Debug Setup":N.type.charAt(0).toUpperCase()+N.type.slice(1))}),t("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},children:((B=N.filePaths)==null?void 0:B[0])||(N.filePaths&&N.filePaths.length>1?`${N.filePaths.length} files`:N.entityShas&&N.entityShas.length>0?`${N.entityShas.length} ${N.entityShas.length===1?"entity":"entities"}`:"Queued for processing")})]})]})})}),l("div",{className:"flex items-center justify-end gap-2 mt-1",children:[_&&t("div",{className:"cursor-grab active:cursor-grabbing",style:{color:"#8e8e8e"},title:"Drag to reorder",children:t(di,{size:20})}),t("button",{onClick:()=>void C(N.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"})]})]})]},N.id)}),e.length>3&&!p&&l("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"]}),p&&e.length>3&&t("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 mm({historicalRuns:e,totalHistoricalRuns:r,currentPage:n,totalPages:a,tab:o,onShowLogs:s}){if(r===0)return l("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:[l("div",{className:"flex items-center gap-4",children:[t("div",{className:"w-12 h-12 bg-[#DEE3E5] border border-[#BBCCD3] rounded-full flex items-center justify-center flex-shrink-0",children:t(ui,{size:24,style:{color:"#005C75"}})}),l("div",{children:[t("h3",{className:"text-base font-medium mb-1",style:{color:"#3E3E3E"},children:"No Historic Activity"}),t("p",{className:"text-sm",style:{color:"#8e8e8e"},children:"Completed analyses will appear here for historical reference."})]})]}),l(oe,{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:[t("span",{children:"+"}),t("span",{children:"New Analysis"})]})]});const[i,c]=M(!1),d=[];e.forEach(u=>{u.entities&&u.entities.length>0&&u.entities.forEach(p=>{d.push({...p,runCreatedAt:u.createdAt})})});const m=i?d:d.slice(0,3);return l("div",{className:"flex flex-col gap-4",children:[m.map(u=>{var y;const p=(y=u.analyses)==null?void 0:y[0],h=(p==null?void 0:p.scenarios)||[],f=!u.isUncommitted;return l("div",{className:"rounded-lg p-4",style:{backgroundColor:f?"#ffffff":"#fef9e7",border:"1px solid",borderColor:f?"#aff1a9":"#f9d689"},children:[l("div",{className:"flex items-start justify-between mb-3",children:[l("div",{className:"flex items-start gap-3 flex-1",children:[t("div",{children:t(Ue,{type:u.entityType||"other",size:"large"})}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t(oe,{to:`/entity/${u.sha}`,className:"hover:underline cursor-pointer",style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#343434"},children:u.name}),t("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"})]}),t("div",{className:"font-mono",style:{fontSize:"12px",lineHeight:"15px",color:"#8e8e8e"},title:u.filePath,children:u.filePath})]})]}),t("button",{onClick:s,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&&l("div",{className:"flex gap-2 overflow-x-auto",style:{marginLeft:"44px"},children:[h.slice(0,8).map(g=>{var v,C,E;if(!g.id)return null;const w=(C=(v=g.metadata)==null?void 0:v.screenshotPaths)==null?void 0:C[0],x=(E=g.metadata)==null?void 0:E.noScreenshotSaved,b=w&&!x;return t(oe,{to:`/entity/${u.sha}/scenarios/${g.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?t(De,{screenshotPath:w,alt:g.name,className:"w-full h-full object-cover bg-gray-100"}):t("div",{className:"w-full h-full flex items-center justify-center font-mono",style:{backgroundColor:"#FAFAFA",backgroundImage:"radial-gradient(circle, rgba(0,0,0,0.02) 1px, transparent 1px)",backgroundSize:"20px 20px",color:"#b0b0b0",fontSize:"11px"},children:"No preview"})},g.id)}),h.length>8&&l("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}`)}),d.length>3&&!i&&l("button",{onClick:()=>c(!0),className:"flex items-center justify-center bg-gray-50 border border-gray-200 rounded-[4px] hover:bg-gray-100 hover:border-gray-300 transition-colors cursor-pointer w-full",style:{height:"60px",fontSize:"14px",color:"#646464",fontWeight:500},children:["+",d.length-3," more"," ",d.length-3===1?"entity":"entities"]}),i&&d.length>3&&t("button",{onClick:()=>c(!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 pm=Oe(function(){const r=We(),n=ao(),[a,o]=M(!1);mt({source:"activity-page"});const s=n.tab||"current";return r?l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Activity"}),t("p",{className:"text-[15px] text-gray-500",children:"View queued, current, and historical analysis activity."})]}),t(dm,{activeTab:s,hasCurrentActivity:r.hasCurrentActivity,queuedCount:r.queuedCount,historicCount:r.totalHistoricalRuns}),s==="current"&&t(um,{currentlyExecuting:r.currentlyExecuting,currentRun:r.currentRun,state:r.state,projectSlug:r.projectSlug,commitSha:r.commitSha,onShowLogs:()=>o(!0),recentCompletedEntities:r.recentCompletedEntities||[],hasMoreCompletedRuns:r.hasMoreCompletedRuns||!1,currentEntityScenarios:r.currentEntityScenarios||[],currentEntityForScenarios:r.currentEntityForScenarios,currentAnalysisStatus:r.currentAnalysisStatus}),s==="queued"&&t(hm,{queueJobs:r.queueJobs,state:r.state,currentRun:r.currentRun}),s==="historic"&&t(mm,{historicalRuns:r.historicalRuns,totalHistoricalRuns:r.totalHistoricalRuns,currentPage:r.currentPage,totalPages:r.totalPages,tab:s,onShowLogs:()=>o(!0)}),a&&r.projectSlug&&t(dt,{projectSlug:r.projectSlug,onClose:()=>o(!1)})]}):t("div",{className:"px-20 py-12",children:t("div",{className:"text-center",children:t("p",{className:"text-gray-600",children:"Loading..."})})})}),fm=Object.freeze(Object.defineProperty({__proto__:null,default:pm,loader:cm},Symbol.toStringTag,{value:"Module"}));async function ps(e,r,n){var C,E;await $e();const a=await at({id:e,includeScenarios:!0,includeCommitAndBranch:!0});if(!a)throw new Error(`Analysis ${e} not found`);if(!a.commit)throw new Error(`Commit not found for analysis ${e}`);const o=pe();if(!o)throw new Error("Project root not found");const s=ee.join(o,".codeyam","config.json"),i=JSON.parse(K.readFileSync(s,"utf8")),{projectSlug:c}=i;if(!c)throw new Error("Project slug not found in config");const d=$r(c);try{K.writeFileSync(d,"","utf8")}catch{}const{project:m}=await Fe(c),u=((C=m.metadata)==null?void 0:C.packageManager)||"npm",p=3112,h=ot(c),f=((E=m.metadata)==null?void 0:E.webapps)||[];if(f.length===0)throw new Error(`No webapps found in project metadata for project ${c}`);const y=i.environmentVariables||[],g=Rl({filePath:a.filePath,webapps:f,environmentVariables:y,port:p,packageManager:u});await Tt(e,N=>{if(N&&(N.readyToBeCaptured=!0,N.scenarios))for(const A of N.scenarios)(!r||A.name===r)&&(delete A.screenshotStartedAt,delete A.screenshotFinishedAt,delete A.interactiveStartedAt,delete A.interactiveFinishedAt,delete A.error,delete A.errorStack)});const{jobId:w}=n.enqueue({type:"debug-setup",commitSha:a.commit.sha,projectSlug:c,analysisId:e,scenarioId:r,prepOnly:!0}),x=g.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:x,isCode:!0},{label:"3. View the scenario in your browser",content:`http://localhost:${p}/static/codeyam-sample`,isLink:!0}]}]};return{success:!0,jobId:w,analysisId:e,scenarioId:r,projectPath:h,projectSlug:c,port:p,packageManager:u,framework:g.framework,instructions:b}}async function gm({request:e,context:r}){const n=new URL(e.url),a=n.searchParams.get("analysisId"),o=n.searchParams.get("scenarioId")||void 0;if(!a)return G({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 s=r.analysisQueue;if(s||(s=await st()),!s)return G({error:"Queue not initialized"},{status:500});console.log("[Debug Setup API] GET request for:",{analysisId:a,scenarioId:o});try{const i=await ps(a,o,s);return G({...i,success:!0,message:"Debug setup queued"})}catch(i){return console.error("[Debug Setup API] GET Error:",i),G({error:"Failed to setup debug environment",details:i.message},{status:500})}}async function ym({request:e,context:r}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});let n=r.analysisQueue;if(n||(n=await st()),!n)return G({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("analysisId"),s=a.get("scenarioId");if(!o)return G({error:"Missing required field: analysisId"},{status:400});const i=await ps(o,s,n);return G({...i,success:!0,message:"Debug setup queued"})}catch(a){console.error("[Debug Setup API] Error during debug setup:",a);const o=a instanceof Error?a.message:String(a),s=a instanceof Error?a.stack:void 0;return console.error("[Debug Setup API] Error stack:",s),G({error:"Failed to setup debug environment",details:o},{status:500})}}const xm=Object.freeze(Object.defineProperty({__proto__:null,action:ym,loader:gm},Symbol.toStringTag,{value:"Module"}));async function bm({request:e,context:r}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});let n=r.analysisQueue;if(n||(n=await st()),!n)return G({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("analysisId"),s=a.get("defaultWidth");if(!o||!s)return G({error:"Missing required fields: analysisId and defaultWidth"},{status:400});const i=parseInt(s,10);if(isNaN(i)||i<320||i>3840)return G({error:"Invalid defaultWidth: must be between 320 and 3840"},{status:400});console.log(`[API] Starting recapture for analysis ${o} with width ${i}`);const c=await fh(o,i,n);return console.log("[API] Recapture queued",c),G({success:!0,message:"Recapture queued",...c})}catch(a){return console.log("[API] Error during recapture:",a),G({error:"Failed to recapture screenshots",details:a instanceof Error?a.message:String(a)},{status:500})}}const wm=Object.freeze(Object.defineProperty({__proto__:null,action:bm},Symbol.toStringTag,{value:"Module"}));function vm(e,r){var i,c,d,m,u;const n=((i=e.metadata)==null?void 0:i.isUncommitted)===!0,a=e.analyses&&e.analyses.length>0&&e.analyses.some(p=>p.scenarios&&p.scenarios.length>0);if(!n){const p=!!((c=e.metadata)!=null&&c.previousVersionWithAnalyses),h=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha!==e.sha;return p||h?a?{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:"○"}}:a?{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 o=!!((d=e.metadata)!=null&&d.previousCommittedSha);if(!!((m=e.metadata)!=null&&m.previousVersionWithAnalyses)||o){const p=a&&e.analyses&&e.analyses.length>0&&e.analyses[0].entitySha===((u=e.metadata)==null?void 0:u.previousVersionWithAnalyses);return a&&!p?{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:"●"}}:a?{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 a?{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 Cm(e){return vm(e).hasOutdatedSimulations}function Fr(e,r,n,a,o){var L,z,O,F,R,S,H,q;const s=(L=r==null?void 0:r.scenarios)==null?void 0:L.find(J=>J.name===e.name),i=!!(s!=null&&s.startedAt),c=!!(s!=null&&s.screenshotStartedAt),d=!!(s!=null&&s.screenshotFinishedAt),m=!!(s!=null&&s.finishedAt),u=1800*1e3,p=c&&!d&&(s==null?void 0:s.screenshotStartedAt)&&Date.now()-new Date(s.screenshotStartedAt).getTime()>u,h=!!((O=(z=e.metadata)==null?void 0:z.screenshotPaths)!=null&&O[0])||!!((F=e.metadata)!=null&&F.executionResult),f=c&&!d,y=s==null?void 0:s.error,g=(S=(R=e.metadata)==null?void 0:R.executionResult)==null?void 0:S.error,w=[];if(r!=null&&r.errors&&r.errors.length>0)for(const J of r.errors)w.push({source:`${J.phase} phase`,message:J.message});if(r!=null&&r.steps)for(const J of r.steps)J.error&&w.push({source:J.name,message:J.error});const x=!h&&!y&&!g&&w.length>0,b=!!(y||g||p||x),v=p?"Capture timed out after 30 minutes":(typeof y=="string"?y:null)||(g==null?void 0:g.message)||(x?`Analysis error: ${w[0].message}`:null),C=p?"The capture process has been running for more than 30 minutes and likely got stuck. Consider re-running the analysis.":(s==null?void 0:s.errorStack)||(g==null?void 0:g.stack)||null,N=(a&&o?o.jobs.some(J=>{var ae;return((ae=J.entityShas)==null?void 0:ae.includes(a))||J.type==="analysis"&&J.entityShas&&J.entityShas.length===0})||((q=(H=o.currentlyExecuting)==null?void 0:H.entityShas)==null?void 0:q.includes(a)):!1)&&!i&&!b||!!(s!=null&&s.analyzing)&&!i&&!b,A=i&&!c&&!m&&!b,_=(N||A||f)&&!b,$=(N||A)&&n===!1&&!h;let D;$?D="crashed":b?D="error":h||m?D="completed":f?D="capturing":A?D="starting":N?D="queued":D="pending";let I="📷",k="pending",T=!1,j=`Not captured: ${e.name}`;const P="border-gray-300",B=b||$?"bg-red-50":"bg-white";return b||$?(I="⚠️",k="error",j=`Error: ${$?"Analysis process crashed":v||"Unknown error"}`):N?(I="⋯",k="queued",j=`Queued: ${e.name}`):A?(I="⋯",k="starting",T=!0,j=`Starting server for ${e.name}...`):f&&!b?(I="⋯",k="capturing",T=!0,j=`Capturing ${e.name}...`):h&&(I="✓",k="completed",j=e.name),{hasError:b||$,errorMessage:$?"Analysis process crashed":v,errorStack:$?"Process terminated unexpectedly before completing analysis":C,isCapturing:f,isCaptured:h,hasCrashed:$,isAnalyzing:_,isQueued:N,isServerStarting:A,status:D,icon:I,iconType:k,shouldSpin:T,title:j,borderColor:P,bgColor:B}}function fs({scenario:e,entitySha:r,size:n="medium",showBorder:a=!0,isOutdated:o=!1}){var C,E,N,A,_,$;const s=Fr(e,void 0,void 0,r,void 0),i=(C=e.metadata)==null?void 0:C.executionResult,c=!!i,m=(((N=(E=e.metadata)==null?void 0:E.data)==null?void 0:N.argumentsData)||[]).length,u=(i==null?void 0:i.returnValue)!==void 0&&(i==null?void 0:i.returnValue)!==null,p=((_=(A=i==null?void 0:i.sideEffects)==null?void 0:A.consoleOutput)==null?void 0:_.length)||0,h=(($=i==null?void 0:i.timing)==null?void 0:$.duration)||0;let f=0;m>0&&f++,m>2&&f++,u&&f++,p>0&&f++,f=Math.min(3,f);const y=n==="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]"},w=s.hasError?{border:"border-red-400",bg:"bg-red-50",icon:"text-red-600",badge:"bg-red-100 text-red-700"}:c?o?{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"},x=a?`border-2 ${w.border}`:"",b=Array.from({length:3},(D,I)=>t("div",{className:`w-1 h-1 rounded-full ${I<f?w.icon.replace("text-","bg-"):"bg-gray-300"}`},I)),v=s.hasError?`Error: ${s.errorMessage||"Unknown error"}`:c?`${e.name}
|
|
212
|
-
${m} args → ${u?"value":"void"}${p>0?` (${p} logs)`:""}
|
|
213
|
-
${h}ms`:`Not executed: ${e.name}`;return l(oe,{to:`/entity/${r}/scenarios/${e.id}`,className:`relative ${y.width} ${y.height} ${x} rounded ${w.bg} flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:scale-105 hover:shadow-md`,title:v,onClick:D=>D.stopPropagation(),children:[t("div",{className:`${w.icon} ${y.iconSize} font-mono font-bold`,children:s.hasError?"⚠":c?"ƒ":"○"}),c&&!s.hasError&&l("div",{className:`flex items-center gap-0.5 ${y.textSize} ${w.badge} px-1 rounded`,children:[t("span",{children:m}),t("span",{children:"→"}),t("span",{children:u?"✓":"∅"})]}),c&&!s.hasError&&n==="medium"&&t("div",{className:"flex gap-0.5 mt-0.5",children:b}),c&&!s.hasError&&h>100&&n==="medium"&&t("div",{className:`absolute top-0.5 right-0.5 ${y.textSize} ${w.badge} px-1 rounded`,children:h>1e3?`${Math.round(h/1e3)}s`:`${h}ms`}),c&&!s.hasError&&p>0&&n==="medium"&&l("div",{className:"absolute bottom-0.5 left-0.5 text-[8px] text-gray-500",children:["📝",p]})]})}function yn({size:e=24,className:r=""}){return l("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:r,"aria-hidden":"true",children:[t("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"}),t("line",{x1:"12",y1:"9",x2:"12",y2:"13",stroke:"#FFFFFF",strokeWidth:"2",strokeLinecap:"round"}),t("circle",{cx:"12",cy:"17",r:"1",fill:"#FFFFFF"})]})}function qa({scenario:e,entity:r,analysisStatus:n,queueState:a,processIsRunning:o,size:s="medium",cacheBuster:i,className:c="",viewMode:d}){var g,w;if(r.entityType==="library")return t(fs,{scenario:e,entitySha:r.sha,size:s==="small"?"small":"medium"});const u=Fr(e,n,o,r.sha,a),p=s==="small"?{containerClass:"w-16 h-12",iconSize:"text-xl"}:s==="large"?{containerClass:"w-full h-[67px]",iconSize:"text-2xl"}:{containerClass:"w-20 h-15",iconSize:"text-2xl"},h=`relative ${p.containerClass} ${c}`,f=()=>{const x=`/entity/${r.sha}/scenarios/${e.id}`;return d?`${x}/${d}`:x};if(u.isCaptured){const x=(w=(g=e.metadata)==null?void 0:g.screenshotPaths)==null?void 0:w[0];return t(oe,{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:t(De,{screenshotPath:x,cacheBuster:i,alt:e.name,title:e.name,className:"max-w-full max-h-full object-contain object-center"})})}const y=()=>{const x={size:s==="small"?16:s==="large"?24:20,strokeWidth:2},b=t(Un,{size:s});if(u.shouldSpin||u.iconType==="queued"||u.iconType==="pending")return b;switch(u.iconType){case"starting":case"capturing":return b;case"error":return l("div",{className:"flex flex-col items-center justify-center gap-1",children:[t(yn,{size:24}),t("span",{className:"text-[10px] text-[#ef4444] font-medium",children:"Capture Error"})]});case"completed":return t(hi,{...x});default:return b}};return t(oe,{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:t("div",{className:p.iconSize,children:y()})})}const kt=70;function Nm({scenarios:e,hiddenScenarios:r=[],analysis:n,selectedScenario:a,entitySha:o,cacheBuster:s,activeTab:i,entityType:c,entity:d,queueState:m,processIsRunning:u,isEntityAnalyzing:p,areScenariosStale:h,viewMode:f,setViewMode:y,isBreakdownView:g}){var T,j,P,B,L,z;const w=Ee(null),[x,b]=M(new Set),[v,C]=M(!1);re(()=>{w.current&&i==="scenarios"&&w.current.scrollIntoView({behavior:"smooth",block:"nearest"})},[a==null?void 0:a.id,i]);const E=O=>`/entity/${o}/scenarios/${O}`,N=O=>{b(F=>{const R=new Set(F);return R.has(O)?R.delete(O):R.add(O),R})},A=(O,F=2)=>{const S=O.split(`
|
|
214
|
-
`).slice(0,F).join(" ").trim();return S.length>kt?S.substring(0,kt-3):(O.split(`
|
|
215
|
-
`).length>F||O.length>S.length,S)},_=ne(()=>{var F;if(!((F=n==null?void 0:n.metadata)!=null&&F.executionFlows)||!(n!=null&&n.scenarios))return null;const O=n.scenarios.filter(R=>{var S;return!((S=R.metadata)!=null&&S.sameAsDefault)});return zn(n.metadata.executionFlows,O)},[n]),$=(_==null?void 0:_.totalFlows)||0,D=(_==null?void 0:_.coveredFlows)||0,I=(_==null?void 0:_.coveragePercentage)||0;(T=d==null?void 0:d.metadata)!=null&&T.defaultWidth||(j=n==null?void 0:n.metadata)!=null&&j.defaultWidth;const k=(P=n==null?void 0:n.status)!=null&&P.finishedAt?new Date(n.status.finishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null;return l("aside",{className:"w-[250px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-4",children:[n&&e.length>0&&l("div",{className:"flex flex-col gap-2",children:[t("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:"SCENARIOS"}),l("div",{className:"grid grid-cols-2 gap-2",children:[l(oe,{to:g?`/entity/${o}/scenarios/${(a==null?void 0:a.id)||((B=e[0])==null?void 0:B.id)}`:`/entity/${o}/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:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[Math.round(I),"%"]}),t("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1",children:"COVERAGE"})]}),l(oe,{to:g?`/entity/${o}/scenarios/${(a==null?void 0:a.id)||((L=e[0])==null?void 0:L.id)}`:`/entity/${o}/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:[l("div",{className:"text-xl font-semibold text-[#005c75] font-mono",children:[D,"/",$]}),t("div",{className:"text-[10px] text-[#9e9e9e] font-normal uppercase mt-1 whitespace-nowrap",children:"FLOWS COVERED"})]})]}),l(oe,{to:g?`/entity/${o}/scenarios/${(a==null?void 0:a.id)||((z=e[0])==null?void 0:z.id)}`:`/entity/${o}/scenarios/breakdown`,className:`border rounded px-3 py-2 no-underline hover:shadow-sm transition-shadow flex items-center justify-between ${g?"bg-[#CBF3FA] border-[#CBF3FA]":"bg-[#F6F9FC] border-[#E0E9EC]"}`,children:[t("div",{className:"text-[11px] text-[#005c75] font-normal uppercase font-mono underline",children:"EXECUTION FLOWS"}),g?t("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:t("path",{d:"M3 3L9 9M9 3L3 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}):t("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:t("path",{d:"M4.5 3L7.5 6L4.5 9",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]}),d&&d.filePath&&t("div",{children:t(oe,{to:`/entity/${o}/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&&l("div",{className:"py-3 flex items-center justify-between",children:[l("div",{className:"text-[10px] text-black font-normal uppercase font-mono",children:[e.length," AUTO-GENERATED"]}),k&&t("div",{className:"text-[10px] text-[#9e9e9e] font-normal font-mono",children:k})]}),p&&(h||e.length===0)?l("div",{className:"",children:[l("span",{className:"text-[12px] px-2 rounded inline-flex items-center gap-1.5",style:{backgroundColor:"#FFF4FC",color:"#FF2AB5",height:"23px"},children:[l("svg",{width:"9",height:"9",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[t("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),t("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..."]}),t("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?t("div",{className:"",children:t("p",{className:"text-[#8e8e8e] text-xs font-medium m-0 text-left leading-5",children:"No Scenarios"})}):t("div",{className:"overflow-y-auto flex-1",children:t("div",{className:"flex flex-col gap-[11.6px]",children:e.map((O,F)=>{const R=!g&&(a==null?void 0:a.id)===O.id,S=x.has(O.id||"");return O.id?l(oe,{to:E(O.id),ref:R?w:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${R?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[t("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:t(qa,{scenario:O,entity:{sha:o,entityType:c},analysisStatus:n==null?void 0:n.status,queueState:m,processIsRunning:u,size:"large",cacheBuster:s,viewMode:f})}),l("div",{className:"px-3 py-3",children:[t("div",{className:`text-xs font-semibold text-[#343434] ${S?"":"line-clamp-1"}`,children:O.name}),O.description&&t("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[S?O.description:A(O.description),!S&&O.description.length>kt&&l(le,{children:["...",t("button",{onClick:H=>{H.preventDefault(),H.stopPropagation(),N(O.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),S&&O.description.length>kt&&t("button",{onClick:H=>{H.preventDefault(),H.stopPropagation(),N(O.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},F):null})})}),r.length>0&&!(p&&h)&&l("div",{className:"border-t border-[#e1e1e1] pt-3",children:[l("button",{onClick:()=>C(!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:[t("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",className:`transition-transform ${v?"rotate-90":""}`,children:t("path",{d:"M3.5 2L6.5 5L3.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),"Hidden Scenarios (",r.length,")"]}),v&&l("div",{className:"mt-2",children:[t("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."}),t("div",{className:"flex flex-col gap-[11.6px]",children:r.map((O,F)=>{const R=!g&&(a==null?void 0:a.id)===O.id,S=x.has(O.id||"");return O.id?l(oe,{to:`/entity/${o}/scenarios/${O.id}`,ref:R?w:null,className:`group flex flex-col w-full border rounded-[5.155px] cursor-pointer transition-all no-underline overflow-hidden ${R?"border-[#005c75] bg-white":"border-[#e1e1e1] bg-white hover:border-[#005c75]"}`,children:[t("div",{className:"w-full flex justify-center border-b border-[#e1e1e1]",children:t(qa,{scenario:O,entity:{sha:o,entityType:c},analysisStatus:n==null?void 0:n.status,queueState:m,processIsRunning:u,size:"large",cacheBuster:s,viewMode:f})}),l("div",{className:"px-3 py-3",children:[t("div",{className:`text-xs font-semibold text-[#343434] ${S?"":"line-clamp-1"}`,children:O.name}),O.description&&t("div",{className:"mt-2",children:l("div",{className:"text-xs leading-[15px] text-[#808080] font-normal",children:[S?O.description:A(O.description),!S&&O.description.length>kt&&l(le,{children:["...",t("button",{onClick:H=>{H.preventDefault(),H.stopPropagation(),N(O.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read More"})]}),S&&O.description.length>kt&&t("button",{onClick:H=>{H.preventDefault(),H.stopPropagation(),N(O.id)},className:"text-[10px] text-[#005c75] font-medium cursor-pointer hover:underline ml-1",children:"Read Less"})]})})]})]},F):null})})]})]})]})}function Sm({scenario:e,entitySha:r,onApply:n,onSave:a,onEditMockData:o,onDelete:s,isApplying:i=!1,isSaving:c=!1,saveMessage:d=null,showDeleteConfirm:m=!1,onShowDeleteConfirm:u,isDeleting:p=!1,deleteError:h=null}){const[f,y]=M(""),g=async()=>{await n(f)},w=async x=>{await a(f,x),x||y("")};return l("aside",{className:"w-[220px] bg-white border-r border-[#e1e1e1] shrink-0 flex flex-col gap-2 p-3 h-full",children:[l("div",{className:"border-b border-[#e1e1e1] pb-3",children:[l("div",{className:"flex items-start justify-between mb-2",children:[t("div",{className:"text-[10px] text-[#626262] font-medium",children:"Edit Scenario"}),t(oe,{to:`/entity/${r}`,className:"text-[#626262] hover:text-[#3e3e3e] transition-colors text-sm leading-none no-underline cursor-pointer",title:"Close",children:"×"})]}),t("div",{className:"text-xs font-semibold text-[#626262]",children:e.name})]}),l("div",{className:"flex-1 overflow-y-auto flex flex-col gap-2",children:[l("div",{className:"pt-1",children:[t("label",{htmlFor:"ai-description",className:"block text-xs text-[#343434] font-semibold mb-[6px]",children:"Describe changes to the AI"}),t("textarea",{id:"ai-description",value:f,onChange:x=>y(x.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}),l("button",{onClick:()=>void g(),disabled:i||!f.trim(),className:"w-full mt-1 h-[22px] bg-[#005c75] text-white border border-[rgba(0,92,117,0.05)] rounded text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#004a5e] disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center justify-center gap-1",children:[i&&l("svg",{className:"animate-spin h-3 w-3",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("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"]})]}),t("div",{className:"border-t border-[#e1e1e1] my-1"}),l("div",{className:"pt-1",children:[t("div",{className:"text-xs text-[#343434] font-semibold mb-[6px]",children:"Change file"}),t("p",{className:"text-[10px] text-[#808080] mb-2",children:"You can edit the data used for this scenario directly."}),t("button",{onClick:o,className:"w-full h-[22px] bg-[#e0e9ec] text-[#005c75] border border-[#e0e9ec] rounded-[4px] text-[10px] font-normal cursor-pointer transition-colors hover:bg-[#cbf3fa]",children:"Edit Mock Data"})]}),d&&t("div",{className:`text-[10px] px-[7px] py-[6px] rounded-[4px] ${d.startsWith("Error")?"bg-red-50 text-red-600":"bg-green-50 text-green-600"}`,children:d}),d==="Recapture successful"&&t("div",{children:t(oe,{to:`/entity/${r}`,className:"text-[#005c75] hover:text-[#004a5e] hover:underline text-[10px] cursor-pointer",children:"View updated screenshot on entity page →"})})]}),l("div",{className:"border-t border-[#e1e1e1] pt-2 bg-white flex flex-col gap-1",children:[t("button",{onClick:()=>void w(!1),disabled:c||!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:c?"Saving...":"Save Scenario Data"}),t("button",{onClick:()=>void w(!0),disabled:c||!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"}),s&&l(le,{children:[m?l("div",{className:"flex flex-col gap-1",children:[l("div",{className:"text-[10px] text-red-600 font-medium",children:['Are you sure you want to delete "',e.name,'"?']}),l("div",{className:"flex gap-1",children:[t("button",{onClick:()=>void s(),disabled:p,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:p?"Deleting...":"Yes, Delete"}),t("button",{onClick:()=>u==null?void 0:u(!1),disabled:p,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"})]})]}):t("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&&t("div",{className:"text-[10px] text-red-600 bg-red-50 px-[7px] py-[6px] rounded-[4px]",children:h})]})]})]})}function Em({scenario:e,analysis:r,entity:n}){var i,c,d;const a=((i=e.metadata)==null?void 0:i.executionResult)||null,o=((d=(c=e.metadata)==null?void 0:c.data)==null?void 0:d.argumentsData)||[],s=m=>{var y,g,w;if(!m)return"No execution results available yet. Run the function to capture side effects including console output, file operations, and API calls.";const u=[],p=((y=m.sideEffects)==null?void 0:y.consoleOutput)||[];p.length>0&&(u.push(`Console Output: ${p.length} log ${p.length===1?"entry":"entries"} captured`),p.forEach(x=>{u.push(` [${x.level.toUpperCase()}] ${x.args.join(" ")}`)}));const h=((g=m.sideEffects)==null?void 0:g.fileWrites)||[];h.length>0&&(u.push(`
|
|
216
|
-
File System Operations: ${h.length} ${h.length===1?"operation":"operations"} detected`),h.forEach(x=>{u.push(` ${x.operation}: ${x.path}${x.size?` (${x.size} bytes)`:""}`)}));const f=((w=m.sideEffects)==null?void 0:w.apiCalls)||[];return f.length>0&&(u.push(`
|
|
217
|
-
API Calls: ${f.length} ${f.length===1?"call":"calls"} made`),f.forEach(x=>{u.push(` ${x.method} ${x.url}${x.status?` → ${x.status}`:""}${x.duration?` (${x.duration}ms)`:""}`)})),m.error&&u.push(`
|
|
218
|
-
Error: ${m.error.name||"Error"}: ${m.error.message}`),u.length===0?"No side effects detected. The function executed without console output, file operations, or API calls.":u.join(`
|
|
219
|
-
`)};return l("div",{className:"flex w-full h-full gap-0",children:[l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col",children:[t("div",{className:"px-4 pt-3.5 pb-2.5",children:t("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Input Data"})}),t("div",{className:"flex-1 overflow-auto px-4 pb-0",children:t("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:JSON.stringify(o,null,2)})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[t("div",{className:"px-4 pt-3.5 pb-2.5",children:t("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Returned Data"})}),t("div",{className:"flex-1 overflow-auto px-4 pb-0",children:a?t("pre",{className:"text-xs font-mono text-gray-800 whitespace-pre-wrap break-words m-0",children:a.returnValue!==void 0?JSON.stringify(a.returnValue,null,2):"undefined"}):t("div",{className:"text-sm text-gray-500 italic",children:"No execution results yet"})})]}),l("div",{className:"flex-1 border border-gray-200 bg-white rounded flex flex-col ml-[-1px]",children:[t("div",{className:"px-4 pt-3.5 pb-2.5",children:t("h3",{className:"text-[9px] font-semibold text-[#005c75] uppercase tracking-wide text-center m-0",children:"Side Effects"})}),t("div",{className:"flex-1 overflow-auto px-4 pb-4",children:t("p",{className:"text-sm text-gray-700 leading-[22px] m-0 whitespace-pre-wrap",children:s(a)})})]})]})}const bt={commandBoxBg:"#f6f9fc",commandBoxBorder:"#e1e1e1",commandBoxText:"#005c75",heading:"#000",subtext:"#646464",link:"#005c75"};function cr({scenarioId:e,analysisId:r}){const[n,a]=M(!1),[o,s]=M(!1),[i,c]=M(null),[d,m]=M(!1),u=e||r;if(!u)return null;const p=`/codeyam:diagnose ${u}`,h=async()=>{s(!0);try{const{default:y}=await import("html2canvas-pro"),w=(await y(document.body,{scale:.5})).toDataURL("image/jpeg",.8);c(w),a(!0)}catch(y){console.error("Screenshot capture failed:",y),a(!0)}finally{s(!1)}},f=()=>{a(!1),c(null)};return l(le,{children:[l("div",{className:"text-center p-6 bg-cywhite-100 rounded-lg border-cygray-30 border",children:[t("h3",{className:"font-semibold font-['IBM_Plex_Sans']",style:{fontSize:"18px",lineHeight:"26px",color:bt.heading},children:"Claude can help debug this error."}),t("p",{className:"m-0 mb-4 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"18px",color:bt.subtext},children:"Simply run this command in Claude Code:"}),l("div",{className:"flex items-center justify-between rounded mx-auto mb-3 border",style:{backgroundColor:bt.commandBoxBg,borderColor:bt.commandBoxBorder,maxWidth:"505px",height:"35px",paddingLeft:"13px",paddingRight:"13px",paddingTop:"6px",paddingBottom:"6px"},children:[t("code",{className:"font-mono font-['IBM_Plex_Mono'] flex-1 text-left",style:{fontSize:"12px",lineHeight:"20px",color:bt.commandBoxText},children:p}),t("button",{onClick:y=>{y.stopPropagation(),navigator.clipboard.writeText(p),m(!0),setTimeout(()=>m(!1),2e3)},className:"ml-3 cursor-pointer p-0 bg-transparent border-none hover:opacity-80 transition-opacity",style:{width:"14px",height:"14px",color:d?"#22c55e":bt.commandBoxText},title:d?"Copied!":"Copy command","aria-label":"Copy command to clipboard",children:d?t(so,{size:14}):t(vn,{size:14})})]}),l("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,"," ",t("button",{onClick:()=>void h(),disabled:o,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:bt.link},children:o?"capturing...":"please do so here"}),"."]})]}),t(Co,{isOpen:n,onClose:f,context:{source:e?"scenario-page":"entity-page",entitySha:void 0,scenarioId:e,analysisId:r,currentUrl:typeof window<"u"?window.location.pathname:"/"},screenshotDataUrl:i??void 0})]})}const Ga=1440,dr=[{name:"Mobile",width:375,height:667},{name:"Tablet",width:768,height:1024},{name:"Laptop",width:1024,height:768},{name:"Desktop",width:1440,height:900}],tt={background:"#ffdcd9",border:"#fda4a4",text:"#ef4444",link:"#991b1b"};function gs({selectedScenario:e,analysis:r,entity:n,viewMode:a,cacheBuster:o,hasScenarios:s,isAnalyzing:i=!1,projectSlug:c,hasAnApiKey:d=!0,processIsRunning:m,queueState:u}){var Q,W,Z,de,ue,ge,be,Ne,we,ke,Te;const p=Ae(),[h,f]=M(!1),[y,g]=M(!1),[w,x]=M({name:"Desktop",width:Ga,height:900}),[b,v]=M(Ga),[C,E]=M(1),{customSizes:N,addCustomSize:A,removeCustomSize:_}=ns(c),$=ne(()=>[...dr,...N],[N]),D=(ye,je)=>{v(ye);const Pe=$.find(Ce=>Ce.width===ye&&Ce.height===je);x({name:(Pe==null?void 0:Pe.name)||"Custom",width:ye,height:je})},I=ye=>{v(ye.width),x({name:ye.name,width:ye.width,height:ye.height})},k=ye=>{A(ye,w.width,w.height??900),g(!1),x(je=>({...je,name:ye}))},T=(ye,je)=>{v(ye);const Pe=$.find(Ce=>Ce.width===ye&&Ce.height===je);x(Ce=>({name:(Pe==null?void 0:Pe.name)||"Custom",width:ye,height:Ce.height}))},j=(W=(Q=e==null?void 0:e.metadata)==null?void 0:Q.screenshotPaths)==null?void 0:W[0],P=ne(()=>e?Fr(e,r==null?void 0:r.status,m,n==null?void 0:n.sha,u):null,[e,r==null?void 0:r.status,m,n==null?void 0:n.sha,u]),B=ne(()=>{var je,Pe;const ye=[];if((je=r==null?void 0:r.status)!=null&&je.errors&&r.status.errors.length>0)for(const Ce of r.status.errors)ye.push({source:`${Ce.phase} phase`,message:Ce.message,stack:Ce.stack});if((Pe=r==null?void 0:r.status)!=null&&Pe.steps)for(const Ce of r.status.steps)Ce.error&&ye.push({source:Ce.name,message:Ce.error,stack:Ce.errorStack});return ye},[(Z=r==null?void 0:r.status)==null?void 0:Z.errors,(de=r==null?void 0:r.status)==null?void 0:de.steps]),L=(P==null?void 0:P.errorMessage)||null,z=(P==null?void 0:P.errorStack)||null,{interactiveServerUrl:O,isStarting:F,isLoading:R,showIframe:S,iframeKey:H,onIframeLoad:q}=er({analysisId:r==null?void 0:r.id,scenarioId:e==null?void 0:e.id,scenarioName:e==null?void 0:e.name,projectSlug:c,enabled:a==="interactive"}),J=ne(()=>O||null,[O]),ae=!i&&s&&e&&!((ge=(ue=e.metadata)==null?void 0:ue.screenshotPaths)!=null&&ge[0])&&((Ne=(be=r==null?void 0:r.status)==null?void 0:be.scenarios)==null?void 0:Ne.some(ye=>ye.name===e.name&&ye.screenshotStartedAt&&!ye.screenshotFinishedAt)),{lastLine:V}=pt(c,i||a==="interactive"||ae||!1);if(!e){if(i&&n)return l(le,{children:[t("div",{className:"flex-1 flex flex-col items-center justify-center p-12 text-center bg-[#f6f9fc]",children:l("div",{className:"flex flex-col items-center gap-6 max-w-2xl",children:[t("div",{className:"w-12 h-12 mb-2",children:t("svg",{className:"animate-spin",viewBox:"0 0 50 50",children:t("circle",{cx:"25",cy:"25",r:"20",fill:"none",stroke:"#005c75",strokeWidth:"4",strokeDasharray:"31.4 31.4",strokeLinecap:"round"})})}),t("h2",{className:"text-2xl font-semibold text-[#005c75] leading-[30px] m-0 font-['IBM_Plex_Sans']",children:ae?"Capturing screenshots...":"Analyzing..."}),t("p",{className:"text-xs text-[#8e8e8e] text-center leading-5 m-0 font-['IBM_Plex_Mono']",children:"This may take a few minutes."}),V&&t("p",{className:"text-xs font-mono text-[#005c75] text-center leading-5 m-0 max-w-xl",children:V}),c&&t("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&&c&&t(dt,{projectSlug:c,onClose:()=>f(!1)})]});if(!s&&n&&!i){if(B.length>0){const ye=B.length===1?((we=B[0])==null?void 0:we.message)||"An error occurred during analysis.":`${B.length} errors occurred during analysis.`;return l(le,{children:[t("div",{className:"flex-1 flex flex-col justify-center items-center px-5",style:{minHeight:"75vh"},children:l("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[t("div",{className:"p-4 rounded",style:{backgroundColor:tt.background,border:`2px solid ${tt.border}`},role:"alert",children:l("div",{className:"flex items-center gap-3",children:[t(yn,{size:24,className:"shrink-0"}),t("div",{className:"flex-1 min-w-0",children:l("p",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:tt.text},children:[t("span",{className:"font-semibold",children:"Analysis Error."})," ",ye," ",t("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:tt.link},children:"See logs"})," ","for details."]})})]})}),t("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:t(cr,{analysisId:r==null?void 0:r.id})})]})}),h&&c&&t(dt,{projectSlug:c,onClose:()=>f(!1)})]})}return t("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center bg-[#f6f9fc]",children:l("div",{className:"max-w-[600px]",children:[t("h2",{className:"text-[28px] font-semibold text-[#343434] mb-4 m-0 leading-10",children:"No simulations yet"}),t("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."}),n.filePath&&t("button",{onClick:()=>{p.submit({entitySha:n.sha,filePath:n.filePath},{method:"post",action:"/api/analyze"})},disabled:p.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:p.state!=="idle"?"Analyzing...":"Analyze"})]})})}return t("div",{className:"flex-1 flex flex-col items-center justify-center p-6 text-center",children:t("p",{className:"text-base text-gray-500 m-0",children:"Select a scenario to view its screenshot"})})}return l(le,{children:[t("main",{className:"flex-1 overflow-auto flex flex-col min-w-0",style:{backgroundImage:`
|
|
220
|
-
linear-gradient(45deg, #ebebeb 25%, transparent 25%),
|
|
221
|
-
linear-gradient(-45deg, #ebebeb 25%, transparent 25%),
|
|
222
|
-
linear-gradient(45deg, transparent 75%, #ebebeb 75%),
|
|
223
|
-
linear-gradient(-45deg, transparent 75%, #ebebeb 75%)
|
|
224
|
-
`,backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px",backgroundColor:"#fafafa"},children:(i||ae&&!j)&&!L&&a==="screenshot"?t("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:l("div",{className:"max-w-2xl w-full bg-white rounded-t-2xl shadow-xl p-8",children:[l("div",{className:"mb-8",children:[t("div",{className:"inline-flex items-center justify-center w-24 h-24 bg-blue-100 rounded-full mb-6",children:t("span",{className:"text-5xl animate-spin",children:"⚙️"})}),t("h2",{className:"text-3xl font-bold text-gray-900 mb-4 m-0",children:ae?`Capturing ${n==null?void 0:n.name}`:`Analyzing ${n==null?void 0:n.name}`}),t("p",{className:"text-base text-gray-600 leading-relaxed m-0 mb-2",children:ae?`Taking screenshots for ${((ke=r==null?void 0:r.scenarios)==null?void 0:ke.length)||0} scenario${((Te=r==null?void 0:r.scenarios)==null?void 0:Te.length)!==1?"s":""}...`:`Generating simulations and scenarios for this ${n==null?void 0:n.entityType} entity...`}),e&&l("p",{className:"text-sm text-blue-600 font-semibold m-0",children:["Currently processing: ",e.name]})]}),V&&t("div",{className:"bg-[#f6f9fc] border-2 border-[#e1e1e1] rounded-lg p-6 mb-6",children:l("div",{className:"flex items-start gap-3",children:[t("span",{className:"text-xl shrink-0",children:"📝"}),l("div",{className:"flex-1 min-w-0",children:[t("h3",{className:"text-xs font-semibold text-gray-700 uppercase tracking-wide mb-2 m-0",children:"Current Progress"}),t("p",{className:"text-sm text-gray-900 font-mono wrap-break-word m-0",title:V,children:V})]})]})}),c&&t("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"}),t("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."})]})}):a==="screenshot"&&(j||L)||a==="interactive"&&(J||F)||a==="data"?l(le,{children:[L&&!j&&t("div",{className:"flex-1 flex flex-col justify-center items-center p-6",children:l("div",{className:"w-full flex flex-col gap-4",style:{maxWidth:"600px"},children:[t("div",{className:"p-4 rounded overflow-auto",style:{backgroundColor:tt.background,border:`2px solid ${tt.border}`,maxHeight:"50vh"},role:"alert",children:l("div",{className:"flex flex-col gap-3",children:[l("div",{className:"flex items-center justify-center gap-2 font-bold",style:{color:tt.text},children:[t(yn,{size:24,className:"shrink-0"}),t("div",{children:"Capture Error"})]}),l("div",{className:"text-center",children:[t("button",{onClick:()=>f(!0),className:"underline cursor-pointer bg-transparent border-none p-0 font-medium hover:opacity-80",style:{color:tt.link},children:"See logs"})," ","for details."]}),t("div",{className:"flex-1 min-w-0",children:t("div",{className:"m-0 font-['IBM_Plex_Sans']",style:{fontSize:"14px",lineHeight:"20px",color:tt.text},children:L})})]})}),t("div",{className:"bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:t(cr,{scenarioId:e==null?void 0:e.id,analysisId:r==null?void 0:r.id})})]})}),a==="interactive"?l("div",{className:"flex-1 flex flex-col min-h-0",children:[J&&l("div",{className:"bg-gray-50 border-b border-gray-200 px-6 py-3 shrink-0 flex justify-center items-center gap-4",children:[t(Cd,{presets:[...dr],customSizes:N,currentWidth:w.width,currentHeight:w.height??900,scale:C,onSizeChange:D,onSaveCustomSize:()=>g(!0),onRemoveCustomSize:_}),e&&n&&l(oe,{to:`/entity/${n.sha}/scenarios/${e.id}/fullscreen?from=${encodeURIComponent(`/entity/${n.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:[t("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:t("path",{d:"M2 5V2H5M11 2H14V5M14 11V14H11M5 14H2V11",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),"Fullscreen"]})]}),J&&t("div",{className:"bg-[#005c75] border-b border-[rgba(0,0,0,0.2)] flex justify-center",children:t("div",{style:{maxWidth:`${dr[dr.length-1].width}px`,width:"100%"},children:t(ts,{currentViewportWidth:b,currentPresetName:w.name,onDevicePresetClick:I,devicePresets:$})})}),t(Dr,{scenarioId:e.id,scenarioName:e.name,iframeUrl:J,isStarting:F,isLoading:R,showIframe:S,iframeKey:H,onIframeLoad:q,onScaleChange:E,onDimensionChange:T,projectSlug:c,defaultWidth:w.width,defaultHeight:w.height})]}):a==="data"?t("div",{className:"flex-1 min-h-0",children:t(Em,{scenario:e,analysis:r,entity:n})}):t("div",{className:"flex-1 flex flex-col",children:t("div",{className:"flex-1 p-6 flex items-center justify-center",children:t("div",{className:"transition-all duration-300",style:{maxWidth:`${b}px`},children:(j||!L)&&t(De,{screenshotPath:j,cacheBuster:o,alt:e.name,className:"w-full rounded-lg shadow-[0_10px_25px_rgba(0,0,0,0.1)] bg-white"})})})})]}):t("div",{className:"flex-1 flex flex-col",children:t("div",{className:"flex-1 flex flex-col items-center justify-center p-6 overflow-auto w-full",children:i&&!j?t("div",{className:"w-full h-full flex items-center justify-center",children:t("div",{className:"bg-blue-50 border-2 border-blue-200 rounded-lg p-8",children:l("div",{className:"flex items-start gap-4 mb-6",children:[t("span",{className:"animate-spin text-4xl shrink-0",children:"⚙️"}),l("div",{className:"flex-1",children:[t("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Capturing Screenshot"}),l("p",{className:"text-sm text-blue-800 m-0 mb-4",children:["Analysis is in progress for"," ",t("strong",{children:e.name}),". The screenshot will appear here once capture is complete."]}),V&&l("div",{className:"bg-white border border-blue-200 rounded p-4 mt-4",children:[t("h4",{className:"text-xs font-semibold text-blue-800 m-0 mb-2 uppercase tracking-wide",children:"Current Progress"}),t("p",{className:"text-sm text-blue-900 m-0 font-mono wrap-break-word",children:V})]}),c&&t("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"})]})]})})}):L?l("div",{className:"w-full h-full flex flex-col items-center justify-center overflow-auto gap-6",children:[!d&&t("div",{className:"bg-blue-50 border-2 border-blue-300 rounded-lg p-8",children:l("div",{className:"flex-1 flex flex-col gap-4 items-center justify-center",children:[l("div",{className:"flex items-start gap-4",children:[t("span",{className:"text-blue-600 text-2xl shrink-0",children:"🔑"}),t("h3",{className:"text-xl font-semibold text-blue-900 m-0 mb-3",children:"Improve Analysis Quality with an API Key"})]}),l("div",{className:"bg-white border border-blue-200 rounded p-4",children:[t("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."}),l("ul",{className:"text-sm text-blue-800 m-0 space-y-1 pl-5 list-disc",children:[t("li",{children:"You can use API keys for a variety of models"}),t("li",{children:"Faster analysis processing"}),t("li",{children:"Better handling of complex code structures"}),t("li",{children:"Improved scenario generation quality"})]})]}),t(oe,{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"})]})}),t("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[t("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[t("h3",{className:"text-xl font-semibold text-red-800 m-0 mb-3",children:"Capture Failed"}),t("p",{className:"text-sm text-red-700 m-0 mb-4",children:"An error occurred while capturing this scenario. No screenshot is available."}),l("div",{className:"bg-white border border-red-200 rounded p-4",children:[t("h4",{className:"text-xs font-semibold text-red-800 m-0 mb-2 uppercase tracking-wide",children:"Error Message"}),t("div",{className:"max-h-[300px] overflow-auto",children:t("p",{className:"text-sm text-red-900 m-0 font-mono whitespace-pre-wrap wrap-break-word",children:L})})]}),z&&l("details",{className:"mt-4",children:[t("summary",{className:"text-sm text-red-700 cursor-pointer hover:text-red-900 font-semibold",children:"📋 View full stack trace"}),t("div",{className:"mt-3 bg-white border border-red-200 rounded p-4 overflow-auto",children:t("pre",{className:"text-xs text-red-900 font-mono whitespace-pre-wrap wrap-break-word m-0",children:z})})]}),t("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:t(cr,{scenarioId:e==null?void 0:e.id,analysisId:r==null?void 0:r.id})})]})]})})]}):B.length>0?t("div",{className:"w-full h-full flex items-center justify-center overflow-auto",children:t("div",{className:"bg-red-50 border-2 border-red-300 rounded-lg p-8 w-full max-w-4xl my-auto",children:l("div",{className:"flex items-start gap-4 mb-6",children:[t("span",{className:"text-red-500 text-4xl shrink-0",children:"⚠️"}),l("div",{className:"flex-1 min-w-0",children:[t(AnalysisErrorDisplay,{errors:B,title:"Analysis Error",description:B.length===1?"An error occurred during analysis. Screenshot capture was not completed.":`${B.length} errors occurred during analysis. Screenshot capture was not completed.`}),t("div",{className:"mt-4 bg-white border rounded-lg",style:{borderColor:"#e1e1e1"},children:t(cr,{scenarioId:e==null?void 0:e.id,analysisId:r==null?void 0:r.id})})]})]})})}):l("div",{className:"flex flex-col items-center gap-4 text-center",children:[t("span",{className:"text-6xl text-gray-300",children:"📷"}),t("p",{className:"text-lg text-gray-500 m-0",children:"No screenshot available for this scenario"}),t("p",{className:"text-sm text-gray-400 m-0",children:"Try recapturing or debugging this scenario"})]})})})}),h&&c&&t(dt,{projectSlug:c,onClose:()=>f(!1)}),y&&t(rs,{width:w.width,height:w.height??900,onSave:k,onCancel:()=>g(!1)})]})}function Am({analysis:e,entitySha:r}){rt();const[n,a]=M(e);re(()=>{a(e)},[e]);const[o,s]=M(null),i=ne(()=>{var p;if(!((p=n==null?void 0:n.metadata)!=null&&p.executionFlows)||!(n!=null&&n.scenarios))return null;const u=n.scenarios.filter(h=>{var f;return!((f=h.metadata)!=null&&f.sameAsDefault)});return zn(n.metadata.executionFlows,u)},[n]),c=ne(()=>i?zd(i):[],[i]),d=ne(()=>n!=null&&n.scenarios?n.scenarios.filter(u=>{var p;return!((p=u.metadata)!=null&&p.sameAsDefault)}):[],[n]),m=u=>{var h;const p=((h=u.metadata)==null?void 0:h.coveredFlows)||[];return i?i.executionFlows.filter(f=>p.includes(f.id)):[]};return n?!i||i.executionFlows.length===0?t("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[t("p",{className:"text-lg font-medium mb-2",children:"No Execution Flows"}),t("p",{className:"text-sm",children:"Re-analyze this entity to generate execution flows."})]})}):t("div",{className:"flex-1 overflow-auto bg-[#fafafa]",children:l("div",{className:"p-6 space-y-6",children:[l("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[t("h2",{className:"text-lg font-semibold text-gray-900 m-0 mb-3",children:"Scenarios Breakdown"}),l("div",{className:"grid grid-cols-4 gap-4 text-center",children:[l("div",{className:"bg-gray-50 rounded-lg p-3",children:[t("div",{className:"text-2xl font-bold text-gray-900",children:d.length}),t("div",{className:"text-xs text-gray-500",children:"Scenarios"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[t("div",{className:"text-2xl font-bold text-gray-900",children:i.executionFlows.length}),t("div",{className:"text-xs text-gray-500",children:"Execution Flows"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[l("div",{className:"text-2xl font-bold text-gray-900",children:[i.coveredFlows,"/",i.totalFlows]}),t("div",{className:"text-xs text-gray-500",children:"Flows Covered"})]}),l("div",{className:"bg-gray-50 rounded-lg p-3",children:[l("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),"%"]}),t("div",{className:"text-xs text-gray-500",children:"Coverage"})]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[t("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Scenarios (",d.length,")"]})}),t("div",{className:"divide-y divide-gray-100",children:d.length===0?l("div",{className:"p-4 text-center text-gray-500 text-sm",children:["No scenarios yet."," ",t(oe,{to:`/entity/${r}/create-scenario`,className:"text-blue-600 hover:underline",children:"Create one"})]}):d.map(u=>{var f,y,g;const p=(y=(f=u.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0],h=m(u);return l("div",{className:"p-4 flex gap-4",children:[t("div",{className:"w-72 h-40 shrink-0 bg-gray-100 rounded overflow-hidden flex items-start justify-center",children:t(De,{screenshotPath:p,alt:u.name||"Scenario screenshot",className:"max-w-full max-h-full object-contain object-top"})}),l("div",{className:"flex-1 min-w-0",children:[t("div",{className:"flex items-start justify-between gap-2",children:l("div",{children:[t(oe,{to:`/entity/${r}/scenarios/${u.id}`,className:"font-medium text-gray-900 hover:text-blue-600 no-underline text-sm",children:u.name}),((g=u.metadata)==null?void 0:g.error)&&t("span",{className:"ml-2 text-xs px-1.5 py-0.5 bg-red-100 text-red-700 rounded",children:"Error"})]})}),t("p",{className:"text-xs text-gray-500 mt-1 line-clamp-2",children:u.description}),h.length>0&&t("div",{className:"flex flex-wrap gap-1 mt-2",children:h.map(w=>t("span",{className:`text-xs px-1.5 py-0.5 rounded ${w.isError?"bg-red-50 text-red-700":w.blocksOtherFlows?"bg-purple-50 text-purple-700":"bg-blue-50 text-blue-700"}`,children:w.name},w.id))})]})]},u.id)})}),t("div",{className:"px-4 py-3 border-t border-gray-100 bg-gray-50",children:l(oe,{to:`/entity/${r}/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:[t("span",{className:"text-lg leading-none",children:"+"}),"Add Scenario"]})})]}),c.length>0&&l("div",{className:"p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[l("p",{className:"text-sm text-amber-800 font-medium mb-2",children:[c.length," uncovered execution flow",c.length>1?"s":""," — consider adding scenarios to cover these"]}),l("div",{className:"flex flex-wrap gap-1",children:[c.slice(0,10).map(u=>l("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)),c.length>10&&l("span",{className:"text-xs text-amber-600",children:["+",c.length-10," more"]})]})]}),l("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[t("div",{className:"px-4 py-3 border-b border-gray-100 bg-gray-50",children:l("h3",{className:"text-sm font-semibold text-gray-900 m-0",children:["Execution Flows (",i.executionFlows.length,")"]})}),t("div",{className:"divide-y divide-gray-100",children:i.executionFlows.map(u=>{const p=o===u.id,h=u.usedInScenarios.length>0;return l("div",{children:[t("button",{onClick:()=>s(p?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:l("div",{className:"flex items-start gap-3 flex-1",children:[t("span",{className:"text-gray-400 text-sm mt-0.5 shrink-0",children:p?"▼":"▶"}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[t("span",{className:"font-medium text-sm text-gray-900",children:u.name}),h?t("span",{className:"text-xs px-2 py-0.5 rounded bg-green-100 text-green-700",children:"Covered"}):t("span",{className:"text-xs px-2 py-0.5 rounded bg-amber-100 text-amber-700",children:"Uncovered"}),u.blocksOtherFlows&&t("span",{className:"text-xs px-2 py-0.5 rounded bg-purple-100 text-purple-700",children:"Blocking"}),u.impact==="high"&&t("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"High Impact"}),u.isError&&t("span",{className:"text-xs px-2 py-0.5 rounded bg-red-100 text-red-700",children:"Error"})]}),u.description&&t("p",{className:"text-sm text-gray-600 mt-1 m-0",children:u.description})]})]})}),p&&l("div",{className:"border-t border-gray-100 px-4 py-3 bg-gray-50/50",children:[u.requiredValues.length>0&&l("div",{className:"mb-4",children:[t("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Required Values"}),t("div",{className:"space-y-1",children:u.requiredValues.map((f,y)=>l("div",{className:"flex items-center gap-2 text-xs",children:[t("code",{className:"font-mono text-gray-800 bg-gray-100 px-1 py-0.5 rounded",children:f.attributePath}),t("span",{className:"text-gray-400",children:f.comparison}),t("code",{className:"font-mono text-blue-700 bg-blue-50 px-1 py-0.5 rounded",children:f.value})]},y))})]}),h&&l("div",{children:[t("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Covered by Scenarios"}),t("div",{className:"flex flex-wrap gap-1",children:u.usedInScenarios.map(f=>t("span",{className:"text-xs px-1.5 py-0.5 bg-green-50 text-green-700 rounded",children:f.name},f.id))})]}),u.codeSnippet&&l("div",{className:"mt-4 pt-3 border-t border-gray-200",children:[t("p",{className:"text-xs font-medium text-gray-500 uppercase mb-2",children:"Code Location"}),t("pre",{className:"text-xs bg-gray-900 text-gray-100 p-2 rounded overflow-x-auto font-mono whitespace-pre-wrap",children:t("code",{children:u.codeSnippet})})]})]})]},u.id)})})]})]})}):t("div",{className:"flex-1 flex items-center justify-center p-8 bg-[#F8F7F6]",children:l("div",{className:"text-center text-gray-500",children:[t("p",{className:"text-lg font-medium mb-2",children:"No Analysis Found"}),t("p",{className:"text-sm",children:"Analyze this entity to see the scenarios breakdown."})]})})}function Ja({hasIndirectBadge:e,onAnalyze:r}){return l(le,{children:[t("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[e&&t("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),t("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"})]})}),l("div",{className:"px-5 py-5 bg-white rounded-bl-lg rounded-br-lg flex items-center justify-between",children:[t("p",{className:"text-sm font-normal text-[#8e8e8e] m-0 leading-[22px]",children:"No analyses available for this version."}),t("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:r,children:"Analyze"})]})]})}function km({entity:e,history:r}){const[n,a]=M("entity"),[o,s]=M(new Set),i=r.filter(u=>u.analyses.length>0).length,c=ne(()=>{const u=new Map;return r.forEach(p=>{p.analyses.forEach(h=>{(h.scenarios??[]).filter(y=>{var g;return!((g=y.metadata)!=null&&g.sameAsDefault)}).forEach(y=>{u.has(y.name)||u.set(y.name,[]),u.get(y.name).push({version:p,analysis:h,scenario:y})})})}),Array.from(u.entries()).map(([p,h])=>{var f;return{name:p,description:((f=h[0])==null?void 0:f.scenario.description)||"",versions:h.sort((y,g)=>{const w=new Date(y.analysis.createdAt||0).getTime();return new Date(g.analysis.createdAt||0).getTime()-w})}})},[r]),d=c.length,m=u=>{s(p=>{const h=new Set(p);return h.has(u)?h.delete(u):h.add(u),h})};return t("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto",children:l("div",{className:"max-w-[1400px] mx-auto px-8 py-8",children:[t("div",{className:"mb-8",children:l("div",{className:"flex items-center gap-6 border-b-2 border-[#e1e1e1]",children:[l("button",{onClick:()=>a("entity"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${n==="entity"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[t("span",{className:"text-base font-semibold leading-6",children:"Entity History"}),t("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${n==="entity"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:i})]}),l("button",{onClick:()=>a("scenarios"),className:`flex items-center gap-2 px-0 py-3 border-b-2 transition-colors bg-transparent cursor-pointer ${n==="scenarios"?"border-[#005c75] text-[#232323]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:[t("span",{className:"text-base font-normal leading-6",children:"Scenario Changes"}),t("span",{className:`flex items-center justify-center min-w-[22px] h-[22px] px-[5px] rounded-lg text-xs font-medium leading-5 ${n==="scenarios"?"bg-[#e0e9ec] text-[#005c75]":"bg-[#ebf0f2] text-[#626262]"}`,children:d})]})]})}),r.length===0?t("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:t("p",{className:"text-gray-500 text-base m-0",children:"No history available"})}):n==="entity"?l("div",{className:"relative pl-12",children:[r.length>1&&t("div",{className:"absolute left-[17.5px] top-10 bottom-10 w-px bg-[#c7c7c7]"}),r.map((u,p)=>l("div",{className:"relative mb-12 last:mb-0",children:[t("div",{className:"absolute left-[-35px] top-[19px] w-[11.5px] h-[11.5px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[t("div",{className:"px-5 py-3 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3",children:[u.sha===(e==null?void 0:e.sha)&&t("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"}),l(oe,{to:`/entity/${u.sha}/scenarios`,className:"text-xs font-mono text-[#646464] leading-5 hover:text-[#005c75] transition-colors",children:["SHA:"," ",t("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:u.sha.substring(0,8)})]})]}),t("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?t("div",{children:u.analyses.map((h,f)=>{var g;const y=(h.scenarios??[]).filter(w=>{var x;return!((x=w.metadata)!=null&&x.sameAsDefault)});return t("div",{children:y.length===0?t(Ja,{hasIndirectBadge:h.indirect,onAnalyze:()=>{console.log("Analyze version:",u.sha)}}):l(le,{children:[t("div",{className:"px-5 py-3 bg-white border-b border-[#e1e1e1]",children:l("div",{className:"flex items-center justify-end gap-2",children:[h.indirect&&t("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-xs font-medium leading-5",children:"Indirect"}),l("span",{className:"px-[5px] py-0 h-[25px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-xs font-medium leading-5",children:[y.length," scenario",y.length!==1?"s":""]})]})}),((g=h.metadata)==null?void 0:g.scenarioChangesOverview)&&t("div",{className:"p-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:l("p",{className:"text-sm text-[#005c75] m-0 leading-[22px]",children:[l("span",{className:"font-medium",children:["What Changed:"," "]}),h.metadata.scenarioChangesOverview]})}),y.length>0&&t("div",{className:"p-5 bg-white",children:t("div",{className:"flex gap-4 flex-wrap",children:y.map((w,x)=>{var C,E;const b=(E=(C=w.metadata)==null?void 0:C.screenshotPaths)==null?void 0:E[0],v=`${w.name}-${x}`;return l(oe,{to:`/entity/${u.sha}/scenarios/${w.id}`,className:"w-[187px] border border-[#e1e1e1] rounded bg-white overflow-hidden hover:border-[#005c75] hover:shadow-sm transition-all",children:[t("div",{className:"h-[110px] border-b border-[#e1e1e1] bg-gray-50 flex items-center justify-center p-[5.6px]",children:b?t(De,{screenshotPath:b,alt:w.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[t("span",{className:"text-gray-400 text-xl",children:"📷"}),t("span",{className:"text-gray-400 text-[10px]",children:"No Screenshot"})]})}),t("div",{className:"p-[5.6px]",children:t("p",{className:"text-[10.2px] font-medium text-[#343434] m-0 leading-[13px] line-clamp-3",children:w.name})})]},v)})})})]})},h.id||f)})}):t(Ja,{onAnalyze:()=>{console.log("Analyze version:",u.sha)}})]})]},u.sha))]}):t("div",{className:"relative pl-12",children:c.length===0?t("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:t("p",{className:"text-gray-500 text-base m-0",children:"No scenarios found"})}):c.map((u,p)=>{const h=o.has(u.name),f=h?u.versions:u.versions.slice(0,1),y=u.versions.length-1,g=u.versions[0];return g==null||g.version.sha,e==null||e.sha,l("div",{className:"relative mb-12 last:mb-0",children:[t("div",{className:"absolute left-[-35px] top-[42px] w-[13.26px] h-[13.26px] rounded-full bg-[#00925d]"}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-5 py-5 bg-[#f6f9fc] border-b border-[#e1e1e1]",children:[t("h3",{className:"text-base font-semibold text-[#232323] m-0 mb-1 leading-6",children:u.name}),u.description&&t("p",{className:"text-sm font-normal text-[#626262] m-0 leading-[22px]",children:u.description})]}),l("div",{className:"p-5 bg-white",children:[f.map((w,x)=>{var A,_;const{version:b,analysis:v,scenario:C}=w,E=(_=(A=C.metadata)==null?void 0:A.screenshotPaths)==null?void 0:_[0],N=x===0;return l("div",{className:`flex gap-5 items-start ${N?"":"mt-5 pt-5 border-t border-[#e1e1e1]"}`,children:[t(oe,{to:`/entity/${b.sha}/scenarios/${C.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:E?t(De,{screenshotPath:E,alt:C.name,className:"max-w-full max-h-full object-contain rounded-sm"}):l("div",{className:"flex flex-col items-center gap-1",children:[t("span",{className:"text-gray-400 text-xl",children:"📷"}),t("span",{className:"text-gray-400 text-[10px]",children:"No screenshot"})]})}),l("div",{className:"flex-1 flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-2 flex-wrap",children:[b.sha===(e==null?void 0:e.sha)&&t("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"}),N&&u.versions.length>1&&l("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"]})]}),l(oe,{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:"," ",t("span",{className:"text-[#3e3e3e] hover:text-[#005c75]",children:b.sha.substring(0,8)})]}),v.createdAt&&l("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&&t("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}-${x}`)}),y>0&&l("button",{onClick:()=>m(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:[t("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",className:`transition-transform ${h?"rotate-180":""}`,children:t("path",{d:"M4 6L8 10L12 6",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),h?"Hide":`${y} previous version${y!==1?"s":""}`]})]})]})]},u.name)})})]})})}function Va({entity:e,analysisInfo:r,from:n}){const a=Ae(),o=a.state!=="idle",s=e.entityType==="visual"||e.entityType==="library",i=c=>{c.preventDefault(),c.stopPropagation(),s&&a.submit({entitySha:e.sha,filePath:e.filePath},{method:"post",action:"/api/analyze"})};return t(oe,{to:`/entity/${e.sha}${n?`?from=${n}`:""}`,className:"block group cursor-pointer",children:l("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?t("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:t(De,{screenshotPath:e.screenshotPath,alt:e.name,className:"max-w-full max-h-full object-contain"})}):t("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:t("span",{className:"text-[40px]",children:t(Ue,{type:e.entityType})})}),l("div",{className:"flex-1 flex items-center justify-between px-4 min-w-0",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t(Ue,{type:e.entityType}),t("div",{className:"text-base font-medium text-black truncate group-hover:text-[#005c75] transition-colors",children:e.name})]}),t("div",{className:"text-[10px] text-[#8e8e8e] truncate mb-1 font-mono",title:e.filePath,children:e.filePath}),r.hasScenarios&&l("div",{className:"flex items-center gap-2 mt-2",children:[l("span",{className:"px-[5px] py-0 bg-[#efefef] text-[#3e3e3e] rounded text-[10px] font-medium",children:[r.scenarioCount," scenarios"]}),t("span",{className:"text-xs text-[#8e8e8e]",children:r.timestamp})]})]}),t("div",{className:"shrink-0 ml-4",children:r.status==="not_analyzed"?l(le,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f9f9f9] border border-[#e1e1e1] rounded mb-2",children:[t("div",{className:"w-2 h-2 rounded-full bg-[#c7c7c7]"}),t("span",{className:"text-[10px] font-semibold text-[#646464]",children:"Not analyzed"})]}),s&&t("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:o,children:o?"Analyzing...":"Analyze"})]}):r.status==="up_to_date"?l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#f2fcf9] border border-[#c8f2e3] rounded",children:[t("div",{className:"w-2 h-2 rounded-full bg-[#00925d]"}),t("span",{className:"text-[10px] font-semibold text-[#00925d]",children:"Up to date"})]}):l(le,{children:[l("div",{className:"flex items-center gap-1 px-3 py-1 bg-[#e0e9ec] border border-[#e0e9ec] rounded mb-2",children:[t("div",{className:"w-2 h-2 rounded-full bg-[#005c75]"}),t("span",{className:"text-[10px] font-semibold text-[#005c75]",children:"Out of date"})]}),s&&t("button",{className:`w-full px-3 py-1 bg-[#005c75] text-white border-none rounded text-[10px] font-medium transition-colors ${o?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,onClick:i,disabled:o,children:o?"Analyzing...":"Analyze"})]})})]})]})},e.sha)}const Qa=e=>{var o,s,i;const r=((o=e.analysisStatus)==null?void 0:o.status)||"not_analyzed",n=((s=e.analysisStatus)==null?void 0:s.scenarioCount)||0,a=(i=e.analysisStatus)==null?void 0:i.timestamp;return r==="not_analyzed"?{status:"not_analyzed",label:"Not analyzed",color:"gray"}:r==="up_to_date"?{status:"up_to_date",label:"Up to date",color:"green",hasScenarios:n>0,scenarioCount:n,timestamp:a}:{status:"out_of_date",label:"Out of date",color:"teal",hasScenarios:n>0,scenarioCount:n,timestamp:a}};function Pm({importedEntities:e,importingEntities:r}){const[n]=Jt(),a=n.get("from"),o=Ae(),s=o.state!=="idle",i=e.length>0,c=r.length>0,d=h=>h.filter(f=>f.entityType==="visual"||f.entityType==="library"),m=h=>{const f=d(h);f.length!==0&&o.submit({entityShas:f.map(y=>y.sha).join(",")},{method:"post",action:"/api/analyze"})},u=d(e).length>0,p=d(r).length>0;return t("div",{className:"max-w-[1400px] mx-auto",children:l("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-6 py-4 flex items-start justify-between",children:[l("div",{children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imports"}),t("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})]}),t("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities imported by this component."})]}),u&&t("button",{onClick:()=>m(e),disabled:s,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:s?"Analyzing...":"Analyze All"})]}),i?t("div",{className:"p-6 space-y-4",children:e.map(h=>t(Va,{entity:h,analysisInfo:Qa(h),from:a},h.sha))}):t("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:t("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"No imports."})})]}),l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[l("div",{className:"px-6 py-4 flex items-start justify-between",children:[l("div",{children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t("h3",{className:"text-base font-semibold text-black m-0 leading-6",children:"Imported By"}),t("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:r.length})]}),t("p",{className:"text-sm text-[#646464] m-0 leading-[22px]",children:"Entities that import this component."})]}),p&&t("button",{onClick:()=>m(r),disabled:s,className:`px-[10px] py-[5px] bg-[#005c75] text-white border-none rounded text-xs font-medium transition-colors ${s?"cursor-wait opacity-70":"cursor-pointer hover:bg-[#004a5c]"}`,children:s?"Analyzing...":"Analyze All"})]}),c?t("div",{className:"p-6 space-y-4",children:r.map(h=>t(Va,{entity:h,analysisInfo:Qa(h),from:a},h.sha))}):t("div",{className:"bg-[#f6f9fc] h-[339.923px] flex items-center justify-center",children:t("p",{className:"text-sm text-[#646464] m-0 leading-[22px] text-center",children:"Not imported by any entity."})})]})]})})}function _m({relatedEntities:e}){return t("div",{className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:t(Pm,{importedEntities:e.importedEntities,importingEntities:e.importingEntities})})}function Mm({data:e,defaultExpanded:r=!1,maxDepth:n=3}){return t("div",{className:"font-mono text-sm",children:t(Gt,{data:e,depth:0,defaultExpanded:r,maxDepth:n})})}function Gt({data:e,depth:r,defaultExpanded:n,maxDepth:a,objectKey:o,showInlineToggle:s=!1}){const[i,c]=M(n||r<2);if(re(()=>{c(n||r<2)},[n,r]),e===null)return t("span",{className:"text-gray-500",children:"null"});if(e===void 0)return t("span",{className:"text-gray-500",children:"undefined"});const d=typeof e;if(d==="string")return l("span",{className:"text-green-600",children:['"',e,'"']});if(d==="number")return t("span",{className:"text-blue-600",children:e});if(d==="boolean")return t("span",{className:"text-purple-600",children:e.toString()});if(Array.isArray(e))return e.length===0?t("span",{className:"text-gray-600",children:"[]"}):l("span",{children:[l("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:()=>c(!i),children:[l("span",{children:[i?"▼":"▶"," ","["]}),!i&&l("span",{children:[e.length,"]"]})]}),i?l(le,{children:[t("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:e.map((m,u)=>t("div",{className:"py-0.5",children:t(Gt,{data:m,depth:r+1,defaultExpanded:n,maxDepth:a})},u))}),t("div",{className:"text-gray-600",children:"]"})]}):null]});if(d==="object"){const m=Object.keys(e);if(m.length===0)return t("span",{className:"text-gray-600",children:"{}"});const u=h=>h!==null&&typeof h=="object"&&!Array.isArray(h)&&Object.keys(h).length>0,p=h=>Array.isArray(h)&&h.length>0;return l("span",{children:[l("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:()=>c(!i),children:[l("span",{children:[i?"▼":"▶"," ","{"]}),!i&&l("span",{children:[m.length,"}"]})]}),i?l(le,{children:[t("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:m.map(h=>{const f=e[h],y=u(f),g=p(f);return t("div",{className:"py-0.5",children:y?t(Wn,{propertyKey:h,value:f,depth:r,defaultExpanded:n,maxDepth:a}):g?t(Hn,{propertyKey:h,value:f,depth:r,defaultExpanded:n,maxDepth:a}):l(le,{children:[l("span",{className:"text-orange-600",children:[h,": "]}),t(Gt,{data:f,depth:r+1,defaultExpanded:n,maxDepth:a})]})},h)})}),t("div",{className:"text-gray-600",children:"}"})]}):null]})}return t("span",{className:"text-gray-500",children:String(e)})}function Wn({propertyKey:e,value:r,depth:n,defaultExpanded:a,maxDepth:o}){const[s,i]=M(a||n<2),c=Object.keys(r);return re(()=>{i(a||n<2)},[a,n]),l(le,{children:[l("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(!s),children:[t("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:s?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),t("span",{className:"text-gray-600 ml-0.5",children:"{"}),!s&&l("span",{className:"text-gray-600",children:[c.length,"}"]})]}),s&&l(le,{children:[t("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:c.map(d=>{const m=r[d],u=m!==null&&typeof m=="object"&&!Array.isArray(m)&&Object.keys(m).length>0,p=Array.isArray(m)&&m.length>0;return t("div",{className:"py-0.5",children:u?t(Wn,{propertyKey:d,value:m,depth:n+1,defaultExpanded:a,maxDepth:o}):p?t(Hn,{propertyKey:d,value:m,depth:n+1,defaultExpanded:a,maxDepth:o}):l(le,{children:[l("span",{className:"text-orange-600",children:[d,": "]}),t(Gt,{data:m,depth:n+2,defaultExpanded:a,maxDepth:o})]})},d)})}),t("div",{className:"text-gray-600",children:"}"})]})]})}function Hn({propertyKey:e,value:r,depth:n,defaultExpanded:a,maxDepth:o}){const[s,i]=M(a||n<2);return re(()=>{i(a||n<2)},[a,n]),l(le,{children:[l("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(!s),children:[t("span",{className:"text-gray-600 hover:text-gray-900 mr-1",children:s?"▼":"▶"}),l("span",{className:"text-orange-600",children:[e,": "]}),t("span",{className:"text-gray-600 ml-0.5",children:"["}),!s&&l("span",{className:"text-gray-600",children:[r.length,"]"]})]}),s&&l(le,{children:[t("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:r.map((c,d)=>{const m=c!==null&&typeof c=="object"&&!Array.isArray(c)&&Object.keys(c).length>0,u=Array.isArray(c)&&c.length>0;return t("div",{className:"py-0.5",children:m?t(Wn,{propertyKey:d.toString(),value:c,depth:n+1,defaultExpanded:a,maxDepth:o}):u?t(Hn,{propertyKey:d.toString(),value:c,depth:n+1,defaultExpanded:a,maxDepth:o}):t(Gt,{data:c,depth:n+2,defaultExpanded:a,maxDepth:o})},d)})}),t("div",{className:"text-gray-600",children:"]"})]})]})}function sn({label:e,count:r,isActive:n,onClick:a,badgeColorActive:o,badgeTextActive:s}){return l("button",{onClick:a,className:`px-6 py-3 text-sm font-medium relative transition-colors cursor-pointer ${n?"text-[#005c75]":"text-[#3e3e3e] hover:text-gray-900 hover:bg-gray-50"}`,children:[e,r!==void 0&&t("span",{className:`ml-2 px-2 py-0.5 rounded-full text-xs font-semibold ${n?`${o} ${s}`:"bg-gray-200 text-gray-700"}`,children:r}),n&&t("div",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-[#005c75]"})]})}function Ka({label:e,isActive:r,onClick:n,disabled:a=!1}){return t("button",{onClick:n,className:`w-full text-left px-3 py-2.5 rounded-md transition-all text-sm cursor-pointer ${r?"bg-[#f6f9fc] text-[#005c75] font-medium border-l-2 border-[#005c75] pl-[10px]":"text-[#3e3e3e] hover:bg-gray-50"}`,disabled:a,children:e})}function Za({call:e,scenarioName:r}){const[n,a]=M(!1),[o,s]=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}),c=h=>h?`$${h.toFixed(4)}`:null,d=(h,f)=>{if(!h&&!f)return null;const y=[];return h&&y.push(`${h.toLocaleString()} in`),f&&y.push(`${f.toLocaleString()} out`),y.join(" / ")},m=ne(()=>{var h,f,y,g,w;try{const x=JSON.parse(e.response);return(y=(f=(h=x.choices)==null?void 0:h[0])==null?void 0:f.message)!=null&&y.content?x.choices[0].message.content:(w=(g=x.content)==null?void 0:g[0])!=null&&w.text?x.content[0].text:e.response}catch{return e.response}},[e.response]),u=ne(()=>{try{return JSON.stringify(JSON.parse(e.props),null,2)}catch{return e.props}},[e.props]),p=ne(()=>{var h;if(r)return r;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,r]);return l("div",{className:"bg-white rounded-lg border border-[#e1e1e1] overflow-hidden",children:[t("div",{className:"px-5 py-4 bg-[#f6f9fc] border-b border-[#e1e1e1] cursor-pointer hover:bg-[#edf2f7] transition-colors",onClick:()=>a(!n),children:l("div",{className:"flex items-start justify-between gap-4",children:[l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[t("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}),t("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#efefef] text-[#3e3e3e] rounded text-[11px] font-medium",children:e.model}),p&&t("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#deeafc] text-[#2f80ed] rounded text-[11px] font-medium",children:p}),e.error&&t("span",{className:"px-2 py-0.5 h-[22px] flex items-center bg-[#fce8c5] text-[#ef4444] rounded text-[11px] font-medium",children:"Error"})]}),l("div",{className:"flex items-center gap-4 text-xs text-[#626262]",children:[t("span",{children:i(e.created_at)}),d(e.input_tokens,e.output_tokens)&&t("span",{children:d(e.input_tokens,e.output_tokens)}),c(e.cost)&&t("span",{className:"text-[#005c75] font-medium",children:c(e.cost)})]}),l("div",{className:"text-[11px] text-[#8a8a8a] font-mono mt-1",children:[".codeyam/llm-calls/",e.object_id,"_",e.id,".json"]})]}),t("svg",{width:"20",height:"20",viewBox:"0 0 16 16",fill:"none",className:`transition-transform shrink-0 ${n?"rotate-180":""}`,children:t("path",{d:"M4 6L8 10L12 6",stroke:"#626262",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})}),n&&l("div",{className:"border-t border-[#e1e1e1]",children:[l("div",{className:"flex border-b border-[#e1e1e1] bg-[#fafafa]",children:[t("button",{onClick:()=>s("system"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="system"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"System"}),t("button",{onClick:()=>s("prompt"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="prompt"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Prompt"}),t("button",{onClick:()=>s("response"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="response"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Response"}),t("button",{onClick:()=>s("props"),className:`px-4 py-2 text-[13px] font-medium border-b-2 transition-colors bg-transparent cursor-pointer ${o==="props"?"border-[#005c75] text-[#005c75]":"border-transparent text-[#626262] hover:text-[#232323]"}`,children:"Context"})]}),o&&l("div",{className:"p-4 bg-white max-h-[400px] overflow-auto",children:[o==="system"&&t("div",{children:e.system_message?t("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}):t("p",{className:"text-xs text-[#626262] italic m-0",children:"No system message"})}),o==="prompt"&&t("div",{children:t("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})}),o==="response"&&l("div",{children:[e.error&&l("div",{className:"mb-4 p-3 bg-[#fef2f2] border border-[#fecaca] rounded",children:[t("h4",{className:"text-xs font-semibold text-[#dc2626] uppercase mb-1",children:"Error"}),t("p",{className:"text-xs text-[#dc2626] m-0",children:e.error})]}),t("pre",{className:"text-xs font-mono text-[#3e3e3e] whitespace-pre-wrap bg-[#f6f9fc] p-3 rounded border border-[#e1e1e1] m-0 overflow-auto",children:m})]}),o==="props"&&t("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&&!o&&t("div",{className:"p-4 bg-[#fef2f2] border-t border-[#fecaca]",children:l("p",{className:"text-xs text-[#dc2626] m-0",children:[t("span",{className:"font-semibold",children:"Error: "}),e.error]})})]})]})}const Xa=["generateEntityScenarios","analyzeEntity","generateDataStructure","generateEntityDescription"];function Tm({entity:e,analysis:r,scenarios:n,onAnalyze:a,llmCalls:o}){var v,C,E,N,A,_,$,D,I;const[s,i]=M("entity"),[c,d]=M("analysis"),[m,u]=M(n.length>0?{scenarioId:n[0].id||n[0].name}:null),[p,h]=M("entity"),{entityLlmCalls:f,scenarioLlmCalls:y,totalLlmCalls:g}=ne(()=>{if(!o)return{entityLlmCalls:[],scenarioLlmCalls:[],totalLlmCalls:0};const k=[...o.entityCalls,...o.analysisCalls],T=k.filter(P=>P.object_type==="entity"||Xa.includes(P.prompt_type)),j=k.filter(P=>P.object_type!=="entity"&&!Xa.includes(P.prompt_type));return T.sort((P,B)=>B.created_at-P.created_at),j.sort((P,B)=>B.created_at-P.created_at),{entityLlmCalls:T,scenarioLlmCalls:j,totalLlmCalls:k.length}},[o]),w=[{id:"analysis",title:"Analysis",data:r?{id:r.id,status:r.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:(C=r==null?void 0:r.metadata)==null?void 0:C.mergedDataStructure,description:"Combined data structure including dependencies"},{id:"conditionalUsages",title:"Conditional Usages",data:(N=(E=e==null?void 0:e.metadata)==null?void 0:E.isolatedDataStructure)==null?void 0:N.conditionalUsages,description:"Attributes used in conditionals (if, ternary, switch, &&) - candidates for key attributes"},{id:"executionFlows",title:"Execution Flows",data:(A=r==null?void 0:r.metadata)==null?void 0:A.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":($=e==null?void 0:e.metadata)==null?void 0:$.nodeModuleImports},description:"Internal and external dependencies used by this entity"},{id:"scenariosDataStructure",title:"Scenarios Data Structure",data:(D=r==null?void 0:r.metadata)==null?void 0:D.scenariosDataStructure,description:"Structure template used across all scenarios"}],x=w.filter(k=>k.data!==void 0&&k.data!==null).length;let b=null;if(s==="entity"){const k=w.find(T=>T.id===c);k&&k.data!==void 0&&k.data!==null&&(b={title:k.title,description:k.description,data:k.data})}else if(s==="scenarios"&&m){const k=n.find(T=>(T.id||T.name)===m.scenarioId);k&&(b={title:k.name,description:k.description||"Scenario data and configuration",data:k.metadata})}return l("div",{className:"max-w-[1800px] mx-auto h-full flex flex-col",children:[t("div",{className:"mb-6 shrink-0",children:l("div",{className:"flex border-b border-gray-200 relative",children:[t(sn,{label:"Entity",isActive:s==="entity",onClick:()=>i("entity"),badgeColorActive:"bg-[#e0e9ec]",badgeTextActive:"text-[#005c75]"}),t(sn,{label:"Scenarios",count:n.length,isActive:s==="scenarios",onClick:()=>i("scenarios"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),t(sn,{label:"LLM Calls",count:g,isActive:s==="llm-calls",onClick:()=>i("llm-calls"),badgeColorActive:"bg-[#ebf0f2]",badgeTextActive:"text-[#626262]"}),((I=r==null?void 0:r.metadata)==null?void 0:I.analyzerVersion)&&l("div",{className:"ml-auto flex items-center text-xs text-gray-500",children:[t("span",{className:"font-medium",children:"Analyzer:"}),t("span",{className:"ml-1 font-mono",children:r.metadata.analyzerVersion})]})]})}),s==="llm-calls"?l("div",{className:"flex-1 min-h-0",children:[l("div",{className:"flex gap-4 mb-4",children:[l("button",{onClick:()=>h("entity"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${p==="entity"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Entity Calls (",f.length,")"]}),l("button",{onClick:()=>h("scenario"),className:`px-4 py-2 rounded-lg text-sm font-medium transition-colors cursor-pointer ${p==="scenario"?"bg-[#005c75] text-white":"bg-white border border-gray-200 text-gray-600 hover:bg-gray-50"}`,children:["Scenario Calls (",y.length,")"]})]}),t("div",{className:"space-y-4 overflow-y-auto",style:{maxHeight:"calc(100vh - 350px)"},children:p==="entity"?f.length===0?t("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:t("p",{className:"text-gray-500 text-sm m-0",children:"No entity-level LLM calls found"})}):f.map(k=>t(Za,{call:k},k.id)):y.length===0?t("div",{className:"bg-white rounded-lg border border-gray-200 p-8 text-center",children:t("p",{className:"text-gray-500 text-sm m-0",children:"No scenario-level LLM calls found"})}):y.map(k=>t(Za,{call:k},k.id))})]}):l("div",{className:"grid grid-cols-[340px_1fr] gap-6 flex-1 min-h-0",children:[t("div",{className:"bg-white rounded-lg border border-gray-200 p-4 overflow-y-auto",children:s==="entity"?l(le,{children:[t("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"ENTITY SECTIONS"}),x===0?t("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No entity data available."}):t("nav",{className:"space-y-1",children:w.map(k=>{const T=k.data!==void 0&&k.data!==null;return t(Ka,{label:k.title,isActive:c===k.id,onClick:()=>d(k.id),disabled:!T},k.id)})})]}):l(le,{children:[t("h3",{className:"text-xs font-medium text-black mb-3 uppercase tracking-wide",children:"SCENARIOS"}),n.length===0?t("p",{className:"text-sm text-[#646464] leading-[22px]",children:"No scenarios available."}):t("nav",{className:"space-y-1",children:n.map(k=>{const T=k.id||k.name,j=(m==null?void 0:m.scenarioId)===T;return t(Ka,{label:k.name,isActive:j,onClick:()=>u({scenarioId:T})},T)})})]})}),t("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden flex flex-col",children:b?t(Im,{title:b.title,description:b.description,data:b.data}):s==="scenarios"&&n.length===0?t(eo,{title:"No Simulations Yet",description:"Analyze the code to create simulations and create test scenarios automatically.",onAnalyze:a}):s==="entity"?t(eo,{title:"No Entity Data Yet",description:"Entity data structures will appear here after analysis is complete.",onAnalyze:a}):t("div",{className:"p-6 text-center py-12 text-gray-500",children:"Select a section to view data"})})]})]})}function eo({title:e,description:r,onAnalyze:n}){return l("div",{className:"flex flex-col items-center justify-center h-full bg-[#f6f9fc]",children:[t("h2",{className:"text-[28px] font-semibold text-[#646464] leading-[40px] mb-2 text-center",children:e}),t("p",{className:"text-base text-[#646464] leading-6 mb-6 text-center max-w-[600px]",children:r}),n&&t("button",{onClick:n,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 Im({title:e,description:r,data:n}){const[a,o]=M(!0),[s,i]=M("Copy JSON");return l(le,{children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50",children:[t("h3",{className:"text-base font-semibold text-black m-0",children:e}),t("p",{className:"text-sm text-[#646464] mt-1 m-0",children:r})]}),l("div",{className:"px-6 py-4 bg-white flex justify-between items-center",children:[l("div",{className:"flex gap-2",children:[t("button",{onClick:()=>o(!0),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#005c75] text-white":"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]"}`,children:"Expand All"}),t("button",{onClick:()=>o(!1),className:`px-4 h-8 text-sm font-medium rounded border-none cursor-pointer transition-colors ${a?"bg-[#e0e9ec] hover:bg-[#d0dfe4] text-[#005c75]":"bg-[#005c75] text-white"}`,children:"Collapse All"})]}),t("button",{onClick:()=>{const d=JSON.stringify(n,null,2);navigator.clipboard.writeText(d),i("Copied!"),setTimeout(()=>i("Copy JSON"),2e3)},className:"px-4 h-8 bg-[#343434] hover:bg-[#232323] text-white text-sm font-medium rounded border-none cursor-pointer transition-colors whitespace-nowrap",children:s})]}),t("div",{className:"overflow-y-auto flex-1",children:t("div",{className:"p-6",children:n?t("div",{className:"bg-gray-50 rounded-lg p-3 overflow-x-auto",children:t(Mm,{data:n,defaultExpanded:a,maxDepth:99})}):t("div",{className:"text-center py-12 text-gray-500",children:"No data available for this section"})})})]})}function $m({entity:e,analysis:r,scenarios:n,onAnalyze:a}){const o=Ae();return re(()=>{if(e!=null&&e.sha&&o.state==="idle"&&!o.data){const s=r!=null&&r.id?`/api/llm-calls/${e.sha}?analysisId=${r.id}`:`/api/llm-calls/${e.sha}`;o.load(s)}},[e==null?void 0:e.sha,r==null?void 0:r.id,o.state,o.data]),t("div",{className:"flex-1 min-h-0 bg-[#f9f9f9] overflow-auto p-8",children:t(Tm,{entity:e,analysis:r,scenarios:n,onAnalyze:a,llmCalls:o.data})})}function jm({content:e,label:r="Copy",copiedLabel:n="✓ Copied!",className:a="",duration:o=2e3,ariaLabel:s}){const[i,c]=M(!1),d=se(()=>{navigator.clipboard.writeText(e).then(()=>{c(!0),setTimeout(()=>c(!1),o)}).catch(m=>{console.error("Failed to copy:",m)})},[e,o]);return t("button",{onClick:d,className:`cursor-pointer ${a}`,disabled:i,"aria-label":s||(i?"Copied to clipboard":"Copy to clipboard"),"aria-live":"polite",children:i?n:r})}const Rm={margin:0,padding:"24px",backgroundColor:"#101827",fontSize:"14px",lineHeight:"1.5"},Dm={minWidth:"3em",paddingRight:"1em",color:"#6b7280",userSelect:"none"},Lm=2e3,Fm=e=>{var n;if(!e)return"typescript";switch((n=e.split(".").pop())==null?void 0:n.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 Om({entity:e,entityCode:r}){const n=Er(),a=Ee(null);return re(()=>{const o=n.hash;if(!o||!a.current)return;const s=o.match(/^#L(\d+)$/);if(!s)return;const i=parseInt(s[1],10);setTimeout(()=>{if(!a.current)return;const c=a.current.querySelector(`[data-line-number="${i}"]`);if(c&&c instanceof HTMLElement){c.scrollIntoView({behavior:"smooth",block:"center"});const d=c.style.backgroundColor;c.style.backgroundColor="rgba(255, 255, 0, 0.2)",setTimeout(()=>{c.style.backgroundColor=d},2e3)}},300)},[n.hash,r]),t("div",{ref:a,className:"flex-1 bg-[#f9f9f9] overflow-auto p-8",children:l("div",{className:"bg-white rounded-tl-lg rounded-tr-lg border border-gray-200 overflow-hidden",children:[l("div",{className:"px-6 py-4 border-b border-gray-200 bg-gray-50 flex justify-between items-center",children:[l("div",{children:[t("h2",{className:"text-lg font-semibold text-gray-900 m-0",children:"Source Code"}),t("p",{className:"text-xs text-[#646464] font-mono mt-1 m-0",children:e==null?void 0:e.filePath})]}),r&&t(jm,{content:r,label:"Copy Code",duration:Lm,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"})]}),t("div",{className:"p-0",children:r?t("div",{className:"relative",children:t(Wi,{language:Fm(e==null?void 0:e.filePath),style:Hi,showLineNumbers:!0,customStyle:Rm,lineNumberStyle:Dm,wrapLines:!0,lineProps:o=>({"data-line-number":o,style:{display:"block"}}),children:r})}):t("div",{className:"p-12 text-center text-gray-500",children:"No code available"})})]})})}const zm=({data:e})=>[{title:e!=null&&e.entity?`${e.entity.name} - CodeYam`:"Entity - CodeYam"},{name:"description",content:"View entity scenarios and screenshots"}];function Ym({currentParams:e,nextParams:r,currentUrl:n,nextUrl:a,formMethod:o,defaultShouldRevalidate:s}){return n.pathname===a.pathname&&n.search===a.search?s:!!(e.sha!==r.sha||o)}async function Bm({params:e,request:r,context:n}){const{sha:a}=e;if(!a)throw new Response("Entity SHA is required",{status:400});const s=new URL(r.url).searchParams.get("from"),c=(e["*"]||"").split("/").filter(Boolean),d=c[0]||"scenarios",m=c[1]||null,u=c[2]||null,p=n.analysisQueue,h=p?p.getState():{paused:!1,jobs:[]},[f,y,g,w]=await Promise.all([_t(a),ze(),It(),gc(pe()||process.cwd())]),x=f?await jn(f):null,b=f?await Fo(f.sha):null;let v={importedEntities:[],importingEntities:[]},C=null,E=[];f&&(v=await Oo(f),C=await zo(f),E=await Bo(f));const N=!!(f&&E.length>0&&E[0].sha!==f.sha),A=E.length>0?E[0].sha:null,_=!!(E.length>0&&E[0].analyses&&E[0].analyses.length>0),$=f?await Yo(f):!1;return G({entity:f??void 0,analysis:x??void 0,currentEntityAnalysis:b??void 0,projectSlug:y,from:s,relatedEntities:v,entityCode:C??void 0,hasNewerVersion:N,newestEntitySha:A,newestVersionHasAnalysis:_,fileModifiedSinceEntity:$,history:E,tab:d,scenarioId:m,viewModeFromUrl:u,currentCommit:g,hasAnApiKey:w,queueState:h})}const Um=Oe(function(){var ra,na,aa,oa,sa,ia,la,ca,da,ua,ha,ma,pa,fa,ga;const r=We(),o=(ao()["*"]||"").split("/").filter(Boolean),s=o[0]||"scenarios",i=o[1]||null,c=o[2]||null,d=r.entity,m=r.analysis,u=r.currentEntityAnalysis,p=u||m,h=r.projectSlug;r.from;const f=r.relatedEntities,y=r.entityCode,g=r.hasNewerVersion,w=r.newestEntitySha,x=r.newestVersionHasAnalysis,b=r.fileModifiedSinceEntity,v=r.history,C=r.currentCommit,E=r.hasAnApiKey,N=r.queueState;(ra=p==null?void 0:p.status)==null||ra.errors;const A=(p==null?void 0:p.scenarios)||[],_=A.filter(te=>{var me;return!((me=te.metadata)!=null&&me.sameAsDefault)}),$=A.filter(te=>{var me;return(me=te.metadata)==null?void 0:me.sameAsDefault}),D=Mt(),I=Ee(null);re(()=>{I.current===null&&(I.current=window.history.length)},[]);const k=()=>{if(typeof window>"u")return;const te=window.history.state;if(te===null||(te==null?void 0:te.idx)===void 0||(te==null?void 0:te.idx)===0)D("/");else{const me=window.history.length,Be=I.current;if(Be!==null&&me>Be){const Se=me-Be+1;D(-Se)}else D(-1)}},T=!!N.currentlyExecuting,j=s,P=(na=C==null?void 0:C.metadata)==null?void 0:na.currentRun,B=!!(P!=null&&P.createdAt)&&!(P!=null&&P.analysisCompletedAt),L=!!(d!=null&&d.sha&&((aa=P==null?void 0:P.currentEntityShas)!=null&&aa.includes(d.sha))),z=!!(d!=null&&d.sha&&((sa=(oa=N.currentlyExecuting)==null?void 0:oa.entityShas)!=null&&sa.includes(d.sha))),O=!!(d!=null&&d.sha&&((ia=N.jobs)!=null&&ia.some(te=>{var me;return(me=te.entityShas)==null?void 0:me.includes(d.sha)}))),F=L||z||O,R=F&&((la=p==null?void 0:p.status)==null?void 0:la.finishedAt)!=null&&_.length>0&&p.entitySha!==(d==null?void 0:d.sha),S=ne(()=>{if(j!=="scenarios")return null;if(i){const te=_.find(me=>me.id===i);if(te)return te}return _.length>0&&!F?_[0]:null},[j,i,_,F]),H=((ua=(da=(ca=S==null?void 0:S.metadata)==null?void 0:ca.executionResult)==null?void 0:da.error)==null?void 0:ua.message)||((pa=(ma=(ha=p==null?void 0:p.status)==null?void 0:ha.errors)==null?void 0:ma[0])==null?void 0:pa.message);mt({source:S?"scenario-page":"entity-page",entitySha:d==null?void 0:d.sha,scenarioId:S==null?void 0:S.id,analysisId:p==null?void 0:p.id,entityName:d==null?void 0:d.name,entityType:d==null?void 0:d.entityType,scenarioName:S==null?void 0:S.name,errorMessage:H});const[q,J]=M(()=>c&&c!=="edit"?c:(d==null?void 0:d.entityType)==="library"?"data":"screenshot");re(()=>{c&&c!==q&&c!=="edit"&&J(c)},[c]);const ae=c==="edit",[V,Y]=M(!1),[U,Q]=M(!1),[W,Z]=M(null),[de,ue]=M(!1),[ge,be]=M(!1),[Ne,we]=M(null),[ke,Te]=M(null),[ye,je]=M(0),{interactiveServerUrl:Pe,isStarting:Ce,isLoading:tr,showIframe:ce,iframeKey:qe,onIframeLoad:Ge}=er({analysisId:p==null?void 0:p.id,scenarioId:S==null?void 0:S.id,scenarioName:S==null?void 0:S.name,projectSlug:h,enabled:ae&&!!S,refreshTrigger:ye}),[zr,uf]=M(!1),[hf,mf]=M(""),[rr,Rt]=M(!1),[Zn,Yr]=M(Date.now()),[Ss,Br]=M(!1),Xe=Ae(),yt=Ae(),Ye=Ae(),Re=rt(),Es=N.jobs.some(te=>{var me;return(d==null?void 0:d.sha)&&((me=te.entityShas)==null?void 0:me.includes(d.sha))||te.type==="analysis"&&te.commitSha===(C==null?void 0:C.sha)&&te.entityShas&&te.entityShas.length===0}),Ur=F,Xn=((fa=d==null?void 0:d.metadata)==null?void 0:fa.defaultWidth)||((ga=p==null?void 0:p.metadata)==null?void 0:ga.defaultWidth)||1440,As=Math.round(Xn*(900/1440));Xe.state==="submitting"||Xe.state,ne(()=>{var te;return!!((te=S==null?void 0:S.metadata)!=null&&te.interactiveExamplePath)},[S]);const{isCompleted:ea}=pt(h,rr);re(()=>{Xe.state==="idle"&&Xe.data&&(Xe.data.success?setTimeout(()=>{Yr(Date.now()),Re.revalidate(),Rt(!1)},1500):Xe.data.error&&(Rt(!1),alert(`Recapture failed: ${Xe.data.error}`)))},[Xe.state,Xe.data,Re]),re(()=>{rr&&ea&&setTimeout(()=>{Yr(Date.now()),Re.revalidate(),Rt(!1)},1500)},[rr,ea,Re]),re(()=>{yt.state==="idle"&&yt.data&&(yt.data.success?setTimeout(()=>{Yr(Date.now()),Re.revalidate(),Rt(!1)},1500):yt.data.error&&(Rt(!1),alert(`Recapture failed: ${yt.data.error}`)))},[yt.state,yt.data,Re]);const ta=()=>{d&&(g&&w&&w!==d.sha?(D(`/entity/${w}/scenarios`),setTimeout(()=>{Ye.submit({entitySha:w,filePath:d.filePath||""},{method:"post",action:"/api/analyze"})},100)):Ye.submit({entitySha:d.sha,filePath:d.filePath||""},{method:"post",action:"/api/analyze"}))};re(()=>{Ye.state==="idle"&&Ye.data&&(Ye.data.success?Re.revalidate():Ye.data.error&&alert(`Analysis failed: ${Ye.data.error}`))},[Ye.state,Ye.data,d==null?void 0:d.sha,Re]),re(()=>{const te=setTimeout(()=>{Re.revalidate()},500);return()=>clearTimeout(te)},[]),re(()=>{if(B||Ur){const te=setInterval(()=>{Re.revalidate()},3e3);return()=>clearInterval(te)}else{const te=setInterval(()=>{Re.revalidate()},5e3),me=setTimeout(()=>{clearInterval(te)},3e4);return()=>{clearInterval(te),clearTimeout(me)}}},[B,Ur,Re]);const ks=(te,me)=>te==="scenarios"?`/entity/${d==null?void 0:d.sha}/scenarios`:`/entity/${d==null?void 0:d.sha}/${te}`,Ps=(te,me)=>`/entity/${d==null?void 0:d.sha}/scenarios/${te}/${me}`,_s=te=>{J(te),S!=null&&S.id&&(te==="interactive"?D(`/entity/${d==null?void 0:d.sha}/scenarios/${S.id}/fullscreen`,{replace:!0}):D(Ps(S.id,te),{replace:!0}))},Ms=async te=>{var me,Be;if(console.log("[EntityDetail] ===== APPLY CHANGES CALLED =====",{description:te,hasSelectedScenario:!!S,hasAnalysis:!!p}),!S||!p){const Se="Error: No scenario or analysis available";console.error("[EntityDetail]",Se),Z(Se);return}Y(!0),Z(null),console.log("[EntityDetail] Applying changes (preview mode)",{description:te,scenarioId:S.id,scenarioName:S.name,currentData:S.data});try{const Se=await fetch("/api/generate-scenario-data",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:te,existingScenarios:p.scenarios,scenariosDataStructure:(me=p.metadata)==null?void 0:me.scenariosDataStructure,editingMockName:S.name,editingMockData:ke||((Be=S.metadata)==null?void 0:Be.data)})}),et=await Se.json();if(!Se.ok||!et.success)throw new Error(et.error||"Failed to generate scenario data");console.log("[EntityDetail] Generated data:",et.data),Te(et.data);const nr=(p.scenarios||[]).map(Le=>Le.id===S.id?{...Le,metadata:{...Le.metadata,data:et.data}}:Le),Dt=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:p,scenarios:nr})}),Je=await Dt.json();if(!Dt.ok||!Je.success)throw console.error("[EntityDetail] Temp save failed:",Je),new Error(Je.error||"Failed to apply preview");if(Z("Generating preview. Capturing screenshot..."),Pe){console.log("[EntityDetail] Using direct capture from running server",{serverUrl:Pe});const Le=await fetch("/api/capture-screenshot",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:Pe,scenarioId:S.id,projectId:p.projectId,viewportWidth:1440})}),Lt=await Le.json();!Le.ok||!Lt.success?(console.error("[EntityDetail] Direct capture failed:",Lt),Z("Preview applied. Screenshot capture failed.")):(console.log("[EntityDetail] Direct capture successful"),Z('Preview applied. Click "Save Scenario Data" to persist.'))}else{console.log("[EntityDetail] No server running, using queued recapture");const Le=new FormData;Le.append("analysisId",p.id||""),Le.append("scenarioId",S.id||"");const Lt=await fetch("/api/recapture-scenario",{method:"POST",body:Le}),Hr=await Lt.json();!Lt.ok||!Hr.success?(console.warn("[EntityDetail] Recapture failed:",Hr.error),Z("Preview applied. Screenshot recapture failed.")):(console.log("[EntityDetail] Recapture queued:",Hr.jobId),Z('Preview applied. Screenshot will update shortly. Click "Save Scenario Data" to persist.'))}je(Le=>Le+1),Re.revalidate()}catch(Se){console.error("Error applying changes:",Se),Z(`Error: ${Se instanceof Error?Se.message:String(Se)}`)}finally{Y(!1)}},Ts=async(te,me)=>{var Be;if(!S||!p){Z("Error: No scenario or analysis available");return}Q(!0),Z(null),console.log("[EntityDetail] Saving scenario to database",{description:te,saveAsNew:me});try{const Se=ke||((Be=S.metadata)==null?void 0:Be.data);let et;if(me){const Je={...S,id:`${S.name}-${Date.now()}`,name:`${S.name} (Copy)`,metadata:{...S.metadata,data:Se},description:te||S.description};et=[...p.scenarios||[],Je]}else et=(p.scenarios||[]).map(Je=>Je.id===S.id?{...Je,metadata:{...Je.metadata,data:Se},description:te||Je.description}:Je);const nr=await fetch("/api/save-scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({analysis:p,scenarios:et})}),Dt=await nr.json();if(!nr.ok||!Dt.success)throw new Error(Dt.error||"Failed to save scenarios");console.log("[EntityDetail] Scenarios saved successfully"),Z(me?"New scenario created successfully":"Scenario saved successfully"),Te(null),Re.revalidate()}catch(Se){console.error("Error saving scenario:",Se),Z(`Error: ${Se instanceof Error?Se.message:String(Se)}`)}finally{Q(!1)}},Is=()=>{console.log("[EntityDetail] Edit mock data clicked"),Z("Mock data editor coming soon")},$s=async()=>{var te;if(!(S!=null&&S.id)){we("Cannot delete scenario without ID");return}ue(!0),we(null);try{const me=await fetch("/api/delete-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scenarioId:S.id,screenshotPaths:((te=S.metadata)==null?void 0:te.screenshotPaths)||[]})}),Be=await me.json();if(!me.ok||!Be.success)throw new Error(Be.error||"Failed to delete scenario");D(`/entity/${d==null?void 0:d.sha}/scenarios`)}catch(me){console.error("[EntityDetail] Error deleting scenario:",me),we(me instanceof Error?me.message:"Failed to delete scenario"),be(!1)}finally{ue(!1)}},Wr=p&&d&&p.entitySha!==d.sha,js=d?Cm(d):!1;return t(Rr,{children:l("div",{className:"h-screen bg-white flex flex-col overflow-hidden",children:[t("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-end h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0 flex-1 pb-[14px]",children:[t("button",{onClick:k,className:"no-underline shrink-0 bg-transparent border-none cursor-pointer p-0 flex items-center",title:"Back",children:t("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",children:t("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),t("h1",{className:"text-base font-semibold text-black m-0 leading-[20px] shrink-0",children:d==null?void 0:d.name}),t("span",{className:"text-xs text-[#9e9e9e] font-mono font-normal whitespace-nowrap overflow-hidden text-ellipsis min-w-0",title:d==null?void 0:d.filePath,children:d==null?void 0:d.filePath})]}),t("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(te=>t(oe,{to:ks(te.id),className:`relative pb-[17px] px-2 text-sm transition-colors cursor-pointer no-underline ${j===te.id?"font-medium border-b-2":"font-normal hover:text-gray-700"}`,style:j===te.id?{color:"#005C75",borderColor:"#005C75"}:{color:"#9ca3af"},children:l("span",{className:"flex items-center gap-2",children:[te.label,te.count!==void 0&&te.count>0&&t("span",{className:`inline-flex items-center justify-center px-2 py-0.5 text-xs font-semibold rounded-full ${j===te.id?"bg-[#cbf3fa] text-[#005c75]":"bg-[#e1e1e1] text-[#3e3e3e]"}`,children:te.count})]})},te.id))})]})}),(g||Wr&&!u||b&&js)&&!F&&!Es&&t("div",{className:"border-b border-[#FEE585] px-6 py-3 flex items-center justify-center shrink-0",style:{backgroundColor:"#FEE585"},children:l("div",{className:"flex items-center gap-3",children:[t("svg",{className:"w-4 h-4",style:{color:"#714A25"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:t("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"})}),t("span",{className:"text-sm font-semibold",style:{color:"#714A25"},children:Wr&&!g?"This entity version has not been analyzed yet.":"This entity has been recently changed."}),t("span",{className:"text-sm",style:{color:"#714A25"},children:g?"You are viewing an older version. A newer version is available.":Wr?"Showing scenarios from a previous version.":"The file on disk has been modified since this entity was analyzed."}),g&&w&&x?t(oe,{to:`/entity/${w}/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:te=>{te.currentTarget.style.backgroundColor="#B58530"},onMouseLeave:te=>{te.currentTarget.style.backgroundColor="#C69538"},children:"View Latest Version"}):t("button",{onClick:ta,disabled:Ye.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:te=>{Ye.state==="idle"&&(te.currentTarget.style.backgroundColor="#B58530")},onMouseLeave:te=>{Ye.state==="idle"&&(te.currentTarget.style.backgroundColor="#C69538")},children:"Re-analyze"})]})}),l("div",{className:"flex grow items-stretch justify-center gap-0 min-h-0",children:[j==="scenarios"&&l(le,{children:[ae&&S?t(Sm,{scenario:S,entitySha:(d==null?void 0:d.sha)||"",onApply:Ms,onSave:Ts,onEditMockData:Is,onDelete:$s,isApplying:V,isSaving:U,saveMessage:W,showDeleteConfirm:ge,onShowDeleteConfirm:be,isDeleting:de,deleteError:Ne}):t(Nm,{scenarios:_,hiddenScenarios:$,analysis:p,selectedScenario:S,entitySha:(d==null?void 0:d.sha)||"",cacheBuster:Zn,activeTab:j,entityType:d==null?void 0:d.entityType,entity:d,queueState:N,processIsRunning:T,isEntityAnalyzing:F,areScenariosStale:R,viewMode:q,setViewMode:_s,isBreakdownView:i==="breakdown"}),i==="breakdown"?t(Am,{analysis:p??null,entitySha:(d==null?void 0:d.sha)||""}):ae&&S?t(Dr,{scenarioId:S.id||S.name,scenarioName:S.name,iframeUrl:Pe,isStarting:Ce,isLoading:tr,showIframe:ce,iframeKey:qe,onIframeLoad:Ge,projectSlug:h,defaultWidth:1440,defaultHeight:900}):l("div",{className:"flex flex-col flex-1 min-h-0",children:[S&&l("div",{className:"bg-[#f5f5f5] border-b border-gray-200 px-4 py-2 flex items-center justify-between shrink-0",children:[l("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-xs font-semibold text-[#343434]",children:S.name}),l("span",{className:"text-xs text-[#9e9e9e] font-normal",children:[Xn," × ",As]})]}),l("div",{className:"flex items-center gap-2",children:[t(oe,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${S.id}/edit`,className:"px-3 py-1.5 bg-white text-[#343434] rounded text-[11px] font-medium font-mono border border-gray-300 cursor-pointer hover:bg-gray-50 transition-colors no-underline flex items-center",title:"Edit Scenario Data",children:"Edit Scenario"}),l("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:[t("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:t("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"})}),"Download"]}),l(oe,{to:`/entity/${d==null?void 0:d.sha}/scenarios/${S.id}/fullscreen`,className:"px-3 py-1.5 bg-[#005c75] text-white rounded text-[11px] font-medium font-mono border-none cursor-pointer hover:bg-[#004a5e] transition-colors no-underline flex items-center gap-1.5",title:"Interactive Mode",children:[t("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:t("path",{d:"M8 5v14l11-7z"})}),"Interactive Mode"]})]})]}),t(gs,{selectedScenario:S,analysis:p,entity:d,viewMode:q,cacheBuster:Zn,hasScenarios:_.length>0,isAnalyzing:Ur,projectSlug:h,hasAnApiKey:E,processIsRunning:T,queueState:N})]})]}),j==="related"&&t(_m,{relatedEntities:f}),j==="data"&&t($m,{entity:d,analysis:p,scenarios:_,onAnalyze:ta}),j==="code"&&t(Om,{entity:d,entityCode:y}),j==="history"&&t(km,{entity:d,history:v})]}),Ss&&h&&t("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-1000 p-5",onClick:()=>Br(!1),children:l("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:te=>te.stopPropagation(),children:[l("div",{className:"px-6 py-6 border-b border-gray-200 flex justify-between items-center",children:[t("h2",{className:"m-0 text-xl font-semibold text-gray-900",children:"Analysis Logs"}),t("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:()=>Br(!1),children:"×"})]}),t("div",{className:"flex-1 overflow-hidden",children:t(dt,{projectSlug:h,onClose:()=>Br(!1)})})]})})]})})}),Wm=Object.freeze(Object.defineProperty({__proto__:null,default:Um,loader:Bm,meta:zm,shouldRevalidate:Ym},Symbol.toStringTag,{value:"Module"}));async function Hm(e){const{entityShas:r,filePaths:n,context:a,scenarioCount:o,queue:s}=e;console.log(`[analyzeEntities] Starting analysis for ${r.length} entities`);try{console.log("[analyzeEntities] Initializing environment..."),await $e();const i=pe();if(!i)throw new Error("Project root not found");console.log(`[analyzeEntities] Project root: ${i}`);const c=he.join(i,".codeyam","config.json"),d=JSON.parse(await xe.readFile(c,"utf8")),{projectSlug:m,branchId:u}=d;if(!m||!u)throw new Error("Invalid project configuration - missing projectSlug or branchId");console.log(`[analyzeEntities] Project: ${m}, Branch: ${u}`);const p=$r(m);try{await xe.writeFile(p,"","utf8"),console.log("[analyzeEntities] Cleared log file")}catch{}const{project:h,branch:f}=await Fe(m);console.log("[analyzeEntities] Loading entities to determine file paths and names...");const y=await ht({shas:r});if(!y||y.length===0)throw new Error(`No entities found for SHAs: ${r.join(", ")}`);let g=n;if((!g||g.length===0)&&(g=[...new Set(y.map(b=>b.filePath).filter(b=>!!b))],console.log(`[analyzeEntities] Found ${g.length} unique files`)),!g||g.length===0)throw new Error("No file paths available for analysis");console.log(`[analyzeEntities] Creating fake commit for ${g.length} files...`);const w=await mc(h,f,g);console.log(`[analyzeEntities] Created commit ${w.sha.substring(0,8)}`),console.log("[analyzeEntities] Initializing progress tracking..."),await ct({commitSha:w.sha,runStatusUpdate:{queuedAt:new Date().toISOString(),entityCount:r.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)&&Cc(b)}}),console.log("[analyzeEntities] Enqueueing analysis job...");const{jobId:x}=s.enqueue({type:"analysis",commitSha:w.sha,projectSlug:m,filePaths:g,entityShas:r,entityNames:y.map(b=>b.name),...a?{context:a}:{},...o?{scenarioCount:o}:{}});return console.log(`[analyzeEntities] Job queued with ID: ${x} for ${r.length} entities`),{jobId:x}}catch(i){throw console.error("[analyzeEntities] Failed:",i),i}}async function qm({request:e,context:r}){if(e.method!=="POST")return G({error:"Method not allowed"},{status:405});let n=r.analysisQueue;if(n||(n=await st()),!n)return G({error:"Queue not initialized"},{status:500});try{const a=await e.formData(),o=a.get("entitySha"),s=a.get("entityShas"),i=a.get("filePath"),c=a.get("context"),d=a.get("scenarioCount");let m;if(s)m=s.split(",").filter(Boolean);else if(o)m=[o];else return G({error:"Missing required field: entitySha or entityShas"},{status:400});if(m.length===0)return G({error:"No entities to analyze"},{status:400});console.log(`[API] Starting analysis for ${m.length} entity(ies)`);const u=await ht({shas:m}),h=[...new Set(u.map(y=>y.filePath).filter(y=>!!y))].length,{jobId:f}=await Hm({entityShas:m,filePaths:i?[i]:void 0,context:c||void 0,scenarioCount:d?parseInt(d,10):void 0,queue:n});return console.log(`[API] Analysis queued with job ID: ${f}`),G({success:!0,message:`Analysis queued for ${m.length} entity(ies)`,entityCount:m.length,fileCount:h,jobId:f})}catch(a){return console.error("[API] Error starting analysis:",a),G({error:"Failed to start analysis",details:a.message},{status:500})}}const Gm=Object.freeze(Object.defineProperty({__proto__:null,action:qm},Symbol.toStringTag,{value:"Module"}));function Jm(e){switch(e){case"queued":return{text:"Queued",bgColor:"#cbf3fa",textColor:"#3098b4",icon:l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("polyline",{points:"12,6 12,12 16,14"})]})};case"analyzing":return{text:"Analyzing...",bgColor:"#ffdbf6",textColor:"#ff2ab5",icon:l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[t("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),t("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 ys(e){if(!e)return"Never";const r=new Date(e),n=new Date;if(r.getDate()===n.getDate()&&r.getMonth()===n.getMonth()&&r.getFullYear()===n.getFullYear()){const o=r.getHours(),s=r.getMinutes(),i=o>=12?"pm":"am",c=o%12||12,d=s.toString().padStart(2,"0");return`Today, ${c}:${d} ${i}`}return r.toLocaleString("en-US",{month:"numeric",day:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!0})}function Ve(e,r=[],n=!1){var u,p;if(r.some(h=>{var f,y;return!!((f=h.entityShas)!=null&&f.includes(e.sha)||(y=h.entities)!=null&&y.some(g=>g.sha===e.sha))}))return n?"analyzing":"queued";if(!e.analyses||e.analyses.length===0)return"not-analyzed";const o=e.analyses[0];if(!(((u=o.status)==null?void 0:u.scenarios)&&o.status.scenarios.length>0&&o.status.scenarios.some(h=>h.screenshotFinishedAt||h.finishedAt))||o.entitySha!==e.sha)return"not-analyzed";const i=o.createdAt?new Date(o.createdAt).getTime():0,c=(p=e.metadata)!=null&&p.editedAt?new Date(e.metadata.editedAt).getTime():0,d=o.scenarios||[],m=d.some(h=>{var f,y,g;return((y=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0])||((g=h.metadata)==null?void 0:g.executionResult)});return i>=c?d.length>0&&m?d.every(f=>{var y,g,w;return((g=(y=f.metadata)==null?void 0:y.screenshotPaths)==null?void 0:g[0])||((w=f.metadata)==null?void 0:w.executionResult)})?"up-to-date":"incomplete":d.length>0?"incomplete":"not-analyzed":"out-of-date"}const Vm=()=>[{title:"Simulations - CodeYam"},{name:"description",content:"A visual gallery of your recently captured component screenshots"}];async function Qm({request:e,context:r}){try{const n=r.analysisQueue,a=n?n.getState():{paused:!1,jobs:[]},o=await Zt();return G({entities:o||[],queueState:a})}catch(n){return console.error("Failed to load simulations:",n),G({entities:[],queueState:{paused:!1,jobs:[]},error:"Failed to load simulations"})}}const Km=Oe(function(){const r=We(),n=r.entities,a=r.queueState;mt({source:"simulations-page"});const[o,s]=M(""),[i,c]=M("visual"),d=ne(()=>{const g=[];return n.forEach(w=>{var b;const x=(b=w.analyses)==null?void 0:b[0];if(x!=null&&x.scenarios){const v=x.scenarios.filter(C=>{var E;return!((E=C.metadata)!=null&&E.sameAsDefault)}).map(C=>{var I,k,T,j,P;const E=(k=(I=C.metadata)==null?void 0:I.screenshotPaths)==null?void 0:k[0],N=(T=C.metadata)==null?void 0:T.noScreenshotSaved,A=E&&!N,_=(P=(j=x.status)==null?void 0:j.scenarios)==null?void 0:P.find(B=>B.name===C.name),$=_&&_.screenshotStartedAt&&!_.screenshotFinishedAt;let D;return A?D="completed":$?D="capturing":D="error",{scenarioName:C.name,scenarioDescription:C.description||"",screenshotPath:E||"",scenarioId:C.id,state:D}}).filter(C=>C.state==="completed"||C.state==="capturing");v.length>0&&g.push({entity:w,screenshots:v,createdAt:x.createdAt||""})}}),g.sort((w,x)=>new Date(x.createdAt).getTime()-new Date(w.createdAt).getTime()),g},[n]),m=ne(()=>n.filter(g=>{var b,v;const w=(b=g.analyses)==null?void 0:b[0];return!((v=w==null?void 0:w.scenarios)==null?void 0:v.some(C=>{var E,N;return(N=(E=C.metadata)==null?void 0:E.screenshotPaths)==null?void 0:N[0]}))}),[n]),u=ne(()=>d.filter(({entity:g})=>{const w=!o||g.name.toLowerCase().includes(o.toLowerCase()),x=i==="all"||g.entityType===i;return w&&x}),[d,o,i]),p=ne(()=>m.filter(g=>{const w=!o||g.name.toLowerCase().includes(o.toLowerCase()),x=i==="all"||g.entityType===i;return w&&x}),[m,o,i]),h=se(g=>{s(g.target.value)},[]),f=se(g=>{c(g.target.value)},[]),y=d.length>0;return t("div",{className:"bg-[#F8F7F6] min-h-screen overflow-y-auto",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Simulations"}),t("p",{className:"text-[15px] text-gray-500",children:"A visual gallery of your recently captured simulations."})]}),!y&&t("div",{className:"bg-[#D1F3F9] border border-[#A5E8F0] rounded-lg p-4 mb-6",children:l("p",{className:"text-sm text-gray-700 m-0",children:["This page will display a visual gallery of your recently captured component simulations."," ",t("strong",{children:"Start by analyzing your first component below."})]})}),l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[t("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),l("div",{className:"flex gap-3",children:[l("div",{className:"relative",children:[l("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:[t("option",{value:"all",children:"All Types"}),t("option",{value:"visual",children:"Visual"}),t("option",{value:"library",children:"Library"})]}),t(Wt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"flex-1 relative",children:[t(Cn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),t("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:o,onChange:h})]})]})]}),y&&u.length>0&&t("div",{className:"mb-2",children:l("div",{className:"flex items-center py-3",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[t("span",{style:{color:"#000000"},children:u.length})," ",u.length===1?"entity":"entities"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[t("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:t("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"})}),t("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("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.",t("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),t("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[t("span",{style:{color:"#000000"},children:u.reduce((g,{screenshots:w})=>g+w.length,0)})," ","scenarios"]})]})}),l("div",{className:"flex flex-col gap-3",children:[y&&(u.length===0?t("div",{className:"bg-white border border-gray-200 rounded-lg p-8 text-center text-gray-500",children:"No simulations match your filters."}):t(le,{children:u.map(({entity:g,screenshots:w})=>t(Zm,{entity:g,screenshots:w,queueJobs:(a==null?void 0:a.jobs)||[]},g.sha))})),!y&&(p.length===0?t("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."}):p.map(g=>t(Xm,{entity:g},g.sha)))]})]})})});function Zm({entity:e,screenshots:r,queueJobs:n}){var f,y,g;const a=Mt(),o=Ae(),[s,i]=M(!1),c=r.length||(((g=(y=(f=e.analyses)==null?void 0:f[0])==null?void 0:y.scenarios)==null?void 0:g.length)??0),d=w=>{a(`/entity/${e.sha}/scenarios/${w}?from=simulations`)},m=()=>{i(!0),o.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};re(()=>{o.state==="idle"&&s&&i(!1)},[o.state,s]);const u=Ve(e,n),p=Jm(u),h=u==="out-of-date";return t("div",{className:"rounded-[8px]",style:{backgroundColor:"#ffffff",border:"1px solid #e1e1e1"},children:l("div",{className:"flex flex-col",children:[l("div",{className:"flex items-center px-[15px] py-[15px]",children:[t("div",{className:"flex-shrink-0",children:t(Ue,{type:e.entityType||"other",size:"large"})}),l("div",{className:"flex flex-col flex-shrink-0",style:{marginLeft:"15px",gap:"4px"},children:[l("div",{className:"flex items-center gap-[5px]",children:[l(oe,{to:`/entity/${e.sha}`,className:"hover:underline cursor-pointer",title:e.name,style:{fontSize:"14px",lineHeight:"18px",color:"#343434",fontWeight:500},children:[e.name," (",c,")"]}),t("div",{className:"flex items-center justify-center px-2 rounded",style:{height:"20px",backgroundColor:p.bgColor,color:p.textColor,fontSize:"12px",lineHeight:"16px",fontWeight:400},children:p.text})]}),t("div",{style:{fontSize:"12px",lineHeight:"15px",color:"#b0b0b0",fontWeight:400},className:"font-mono",title:e.filePath,children:e.filePath})]}),t("div",{className:"flex-1"}),l("div",{className:"flex-shrink-0 flex items-center gap-2",children:[h&&t(le,{children:s||o.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded flex items-center gap-1.5",children:[t(Ze,{size:14,className:"animate-spin",style:{color:"#be185d"}}),t("span",{style:{color:"#be185d",fontSize:"10px",lineHeight:"20px",fontWeight:600},children:"Analyzing..."})]}):t("button",{onClick:m,className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#005c75",color:"#ffffff",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:w=>{w.currentTarget.style.backgroundColor="#004d5e"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="#005c75"},children:"Re-analyze"})}),t("button",{onClick:()=>void a(`/entity/${e.sha}/logs`),className:"px-[10px] rounded transition-colors whitespace-nowrap",style:{backgroundColor:"#e0e9ec",color:"#005c75",fontSize:"10px",lineHeight:"22px",fontWeight:600},onMouseEnter:w=>{w.currentTarget.style.backgroundColor="#d0dfe3"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="#e0e9ec"},children:"View Logs"})]})]}),t("div",{className:"border-t border-gray-200"}),t("div",{className:"flex gap-2.5 overflow-x-auto pb-3 px-[15px] pt-3",style:{paddingLeft:"47px"},children:r.length>0?r.map(w=>l("div",{className:"shrink-0 flex flex-col gap-2",children:[t("button",{onClick:()=>d(w.scenarioId||""),className:"block cursor-pointer bg-transparent border-none p-0",children:t("div",{className:"w-36 h-24 rounded-md border overflow-hidden flex items-center justify-center transition-all",style:{"--hover-border":"#005C75",backgroundColor:w.state==="capturing"?"#f9f9f9":"#f3f4f6",borderColor:w.state==="capturing"?"#efefef":"#d1d5db"},onMouseEnter:x=>{w.state==="completed"&&(x.currentTarget.style.borderColor="#005C75",x.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.15)")},onMouseLeave:x=>{x.currentTarget.style.borderColor=w.state==="capturing"?"#efefef":"#d1d5db",x.currentTarget.style.boxShadow="none"},children:w.state==="completed"?t(De,{screenshotPath:w.screenshotPath,alt:w.scenarioName,className:"max-w-full max-h-full object-contain"}):w.state==="capturing"?t(Un,{size:"medium"}):null})}),l("div",{className:"relative group",children:[t("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:w.scenarioName}),t("div",{className:"fixed hidden group-hover:block pointer-events-none",style:{zIndex:1e4,transform:"translateY(8px)"},children:l("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:[w.scenarioName,w.scenarioDescription&&l(le,{children:[": ",w.scenarioDescription]}),t("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-100 border-l border-t border-gray-200 transform rotate-45"})]})})]})]},w.scenarioId)):t("div",{className:"text-xs text-gray-400 py-4",children:"No screenshots available"})})]})})}function Xm({entity:e}){const r=Ae(),[n,a]=M(!1),o=()=>{a(!0),r.submit({entitySha:e.sha,filePath:e.filePath||""},{method:"post",action:"/api/analyze"})};return re(()=>{r.state==="idle"&&n&&a(!1)},[r.state,n]),t("div",{className:"bg-white rounded hover:bg-gray-100 transition-colors cursor-pointer border-b border-[#e1e1e1]",onClick:o,children:l("div",{className:"px-5 py-4 flex items-center",children:[l("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[t(Ue,{type:e.entityType}),l("div",{className:"min-w-0",children:[l("div",{className:"flex items-center gap-3 mb-0.5",children:[t(oe,{to:`/entity/${e.sha}`,className:"text-sm font-medium text-gray-900 no-underline",children:e.name}),t("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"})]}),t("div",{className:"text-xs text-gray-400 truncate",children:e.filePath})]})]}),t("div",{className:"w-32 flex justify-center",children:t("span",{className:"text-[10px] text-gray-500 bg-gray-100 px-2 py-1 rounded",children:"Not analyzed"})}),t("div",{className:"w-32 text-center text-[10px] text-gray-500",children:ys(e.createdAt||null)}),t("div",{className:"w-24 flex justify-end",children:n||r.state!=="idle"?l("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[t(Ze,{size:14,className:"animate-spin"}),"Analyzing..."]}):t("button",{onClick:o,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 ep=Object.freeze(Object.defineProperty({__proto__:null,default:Km,loader:Qm,meta:Vm},Symbol.toStringTag,{value:"Module"}));function tp({request:e,context:r}){const n=r.dbNotifier||un;if(!n)return console.error("[SSE] ERROR: dbNotifier not found in context or global!"),new Response("Server configuration error",{status:500});n.start().catch(()=>{});const a=new ReadableStream({start(o){const s=new TextEncoder;o.enqueue(s.encode(`data: ${JSON.stringify({type:"connected"})}
|
|
225
|
-
|
|
226
|
-
`)),Math.random().toString(36).substring(7);let i=!1;const c=()=>{if(!i){i=!0,n.off("change",d),clearInterval(m);try{o.close()}catch{}}},d=u=>{try{o.enqueue(s.encode(`data: ${JSON.stringify({type:"db-change",changeType:u.type,timestamp:u.timestamp})}
|
|
227
|
-
|
|
228
|
-
`))}catch{c()}};n.on("change",d);const m=setInterval(()=>{try{o.enqueue(s.encode(`data: ${JSON.stringify({type:"keepalive"})}
|
|
229
|
-
|
|
230
|
-
`))}catch{c()}},3e4);e.signal.addEventListener("abort",c)}});return new Response(a,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}const rp=Object.freeze(Object.defineProperty({__proto__:null,loader:tp},Symbol.toStringTag,{value:"Module"}));function np(){return new Response(JSON.stringify({status:"ok",version:Fn,message:"CodeYam Remix server is running"}),{status:200,headers:{"Content-Type":"application/json"}})}const ap=Object.freeze(Object.defineProperty({__proto__:null,loader:np},Symbol.toStringTag,{value:"Module"}));function qn(e){const r=/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/,n=e.match(r);if(!n)return{frontmatter:{},body:e};const a=n[1],o=n[2],s={},i=a.match(/paths:\s*\n((?:\s+-\s+[^\n]+\n?)*)/);i&&(s.paths=i[1].split(`
|
|
231
|
-
`).filter(m=>m.trim().startsWith("-")).map(m=>m.replace(/^\s*-\s*/,"").replace(/['"]/g,"").trim()).filter(Boolean));const c=a.match(/category:\s*([^\n]+)/);if(c){const m=c[1].trim().replace(/['"]/g,"");(m==="architecture"||m==="testing"||m==="faq")&&(s.category=m)}const d=a.match(/timestamp:\s*([^\n]+)/);return d&&(s.timestamp=d[1].trim().replace(/['"]/g,"")),{frontmatter:s,body:o}}async function Or(e,r=""){const n=[];try{const a=await xe.readdir(e,{withFileTypes:!0});for(const o of a){const s=r?`${r}/${o.name}`:o.name;if(o.isDirectory()){const i=await Or(he.join(e,o.name),s);n.push(...i)}else o.isFile()&&o.name.endsWith(".md")&&n.push(s)}}catch{}return n}async function op(e){const r=await Or(e),n=[];for(const a of r){const o=he.join(e,a);try{const s=await xe.readFile(o,"utf-8"),{frontmatter:i,body:c}=qn(s);n.push({filePath:a,absolutePath:o,frontmatter:i,body:c})}catch{}}return n}function sp(e,r){return!r.frontmatter.paths||r.frontmatter.paths.length===0?!1:r.frontmatter.paths.some(n=>yo(e,n,{matchBase:!0}))}async function ip({request:e}){const r=pe();if(!r)return Response.json({error:"Project root not found"},{status:500});const n=new URL(e.url),a=n.searchParams.get("action"),o=he.join(r,".claude","rules");if(a==="recent-changes")return cp(r);if(a==="audit")return dp(r,o);if(a==="source-files")return up(r);if(a==="rules-for-path"){const s=n.searchParams.get("path");return s?hp(o,s):Response.json({error:"Missing required parameter: path"},{status:400})}try{const s=await Or(o),i=[];for(const c of s){const d=he.join(o,c);try{const m=await xe.readFile(d,"utf-8"),u=await xe.stat(d),{frontmatter:p,body:h}=qn(m);i.push({filePath:c,content:m,frontmatter:p,body:h,lastModified:u.mtime.toISOString()})}catch{}}return i.sort((c,d)=>new Date(d.lastModified).getTime()-new Date(c.lastModified).getTime()),Response.json({memories:i})}catch(s){return console.error("[API] Error loading memories:",s),Response.json({error:"Failed to load memories",details:s instanceof Error?s.message:String(s)},{status:500})}}async function lp(e,r){const n=[];try{const a=r("git status --porcelain -- .claude/rules/ 2>/dev/null || true",{cwd:e,encoding:"utf-8"});for(const o of a.split(`
|
|
232
|
-
`).filter(Boolean)){const s=o.substring(0,2);let i=o.substring(3);if(i.includes(" -> ")&&(i=i.split(" -> ")[1]),!i.startsWith(".claude/rules/"))continue;const c=i.replace(".claude/rules/","");let d="modified";const m=s[0],u=s[1];m==="A"||m==="?"?d="added":m==="D"||u==="D"?d="deleted":(m==="M"||u==="M")&&(d="modified");let p="";try{if(d==="deleted")p=r(`git diff HEAD -- "${i}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});else if(d==="added"&&m==="?"){const h=`${e}/${i}`;try{const f=await xe.readFile(h,"utf-8");p=`diff --git a/${i} b/${i}
|
|
233
|
-
new file mode 100644
|
|
234
|
-
--- /dev/null
|
|
235
|
-
+++ b/${i}
|
|
236
|
-
@@ -0,0 +1,${f.split(`
|
|
237
|
-
`).length} @@
|
|
238
|
-
${f.split(`
|
|
239
|
-
`).map(y=>"+"+y).join(`
|
|
240
|
-
`)}`}catch{p="(content not available)"}}else p=r(`git diff HEAD -- "${i}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024});p.length>5e3&&(p=p.substring(0,5e3)+`
|
|
241
|
-
... (truncated)`)}catch{p="(diff not available)"}n.push({filePath:c,changeType:d,diff:p})}}catch{}return n}async function cp(e){try{const{execSync:r}=await import("child_process"),n=[],a=await lp(e,r);a.length>0&&n.push({commitHash:"uncommitted",date:new Date().toISOString(),message:"Uncommitted changes",files:a});const s=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(`
|
|
242
|
-
`).filter(Boolean).slice(0,20);for(const i of s){const[c,d,...m]=i.split("|"),u=m.join("|");if(!c||!d)continue;const p=r(`git diff-tree --no-commit-id --name-status -r ${c} -- .claude/rules/ 2>/dev/null || true`,{cwd:e,encoding:"utf-8"}),h=[];for(const f of p.split(`
|
|
243
|
-
`).filter(Boolean)){const[y,g]=f.split(" ");if(!g||!g.startsWith(".claude/rules/"))continue;const w=g.replace(".claude/rules/","");let x="modified";y==="A"?x="added":y==="D"&&(x="deleted");let b="";try{b=r(`git show ${c} --format="" -- "${g}" 2>/dev/null || true`,{cwd:e,encoding:"utf-8",maxBuffer:1024*1024}),b.length>5e3&&(b=b.substring(0,5e3)+`
|
|
244
|
-
... (truncated)`)}catch{b="(diff not available)"}h.push({filePath:w,changeType:x,diff:b})}h.length>0&&n.push({commitHash:c.substring(0,8),date:d,message:u,files:h})}return Response.json({changes:n})}catch(r){return console.error("[API] Error getting recent changes:",r),Response.json({changes:[]})}}async function xs(e){const r=[],n=[".ts",".tsx",".js",".jsx",".vue",".svelte"];async function a(o,s){try{const i=await xe.readdir(o,{withFileTypes:!0});for(const c of i){const d=he.join(o,c.name),m=s?`${s}/${c.name}`:c.name;if(!(c.isDirectory()&&(c.name==="node_modules"||c.name===".git"||c.name==="dist"||c.name===".codeyam"||c.name===".claude"||c.name==="build"||c.name==="coverage"))){if(c.isDirectory())await a(d,m);else if(c.isFile()){const u=he.extname(c.name);n.includes(u)&&r.push(m)}}}}catch{}}return await a(e,""),r}async function dp(e,r){try{const n=await op(r),a=await xs(e),o=[];for(const s of a){const i=n.filter(c=>sp(s,c));if(i.length>0){const c=i.reduce((d,m)=>d+m.body.length,0);o.push({filePath:s,matchingRules:i.map(d=>({filePath:d.filePath,patterns:d.frontmatter.paths||[],bodyLength:d.body.length})),totalTextLength:c})}}return o.sort((s,i)=>i.totalTextLength-s.totalTextLength),Response.json({topPaths:o.slice(0,10),totalFilesWithCoverage:o.length})}catch(n){return console.error("[API] Error getting audit data:",n),Response.json({error:"Failed to get audit data",details:n instanceof Error?n.message:String(n)},{status:500})}}async function up(e){try{const r=await xs(e);return Response.json({files:r})}catch(r){return console.error("[API] Error getting source files:",r),Response.json({error:"Failed to get source files",details:r instanceof Error?r.message:String(r)},{status:500})}}async function hp(e,r){try{const n=await Or(e),a=[];for(const s of n){const i=he.join(e,s);try{const c=await xe.readFile(i,"utf-8"),d=await xe.stat(i),{frontmatter:m,body:u}=qn(c);m.paths&&m.paths.some(p=>yo(r,p,{matchBase:!0}))&&a.push({filePath:s,content:c,frontmatter:m,body:u,lastModified:d.mtime.toISOString()})}catch{}}const o=a.reduce((s,i)=>s+i.body.length,0);return Response.json({rules:a,totalTextLength:o})}catch(n){return console.error("[API] Error getting rules for path:",n),Response.json({error:"Failed to get rules for path",details:n instanceof Error?n.message:String(n)},{status:500})}}async function mp({request:e}){const r=pe();if(!r)return Response.json({error:"Project root not found"},{status:500});const n=he.join(r,".claude","rules");try{const a=await e.json(),{action:o,filePath:s,content:i}=a;if(!s)return Response.json({error:"Missing required field: filePath"},{status:400});const c=he.normalize(s);if(c.includes("..")||he.isAbsolute(c))return Response.json({error:"Invalid file path"},{status:400});const d=he.join(n,c);switch(o){case"create":case"update":return i?(await xe.mkdir(he.dirname(d),{recursive:!0}),await xe.writeFile(d,i,"utf-8"),console.log(`[API] Memory ${o}d: ${s}`),Response.json({success:!0,message:`Memory ${o}d successfully`,filePath:s})):Response.json({error:"Missing required field: content"},{status:400});case"delete":try{await xe.unlink(d),console.log(`[API] Memory deleted: ${s}`);const m=he.dirname(d);try{(await xe.readdir(m)).length===0&&m!==n&&await xe.rmdir(m)}catch{}return Response.json({success:!0,message:"Memory deleted successfully"})}catch(m){if(m.code==="ENOENT")return Response.json({error:"Memory not found"},{status:404});throw m}default:return Response.json({error:"Invalid action. Must be create, update, or delete"},{status:400})}}catch(a){return console.error("[API] Error managing memory:",a),Response.json({error:"Failed to manage memory",details:a instanceof Error?a.message:String(a)},{status:500})}}const pp=Object.freeze(Object.defineProperty({__proto__:null,action:mp,loader:ip},Symbol.toStringTag,{value:"Module"}));async function fp({request:e,context:r}){var s;let n=r.analysisQueue;if(n||(n=await st()),!n)return G({error:"Queue not initialized"},{status:500});const a=new URL(e.url),o=a.searchParams.get("queryType");if(!o)return G({error:"Missing queryType parameter for GET request"},{status:400});if(o==="job"){const i=a.searchParams.get("jobId");if(!i)return G({error:"Missing jobId parameter for job query"},{status:400});const c=n.getState();if(((s=c.currentlyExecuting)==null?void 0:s.id)===i)return G({jobId:i,status:"running",job:c.currentlyExecuting});const d=c.jobs.find(u=>u.id===i);if(d){const u=c.jobs.indexOf(d);return G({jobId:i,status:"queued",position:u,job:d})}const m=n.getJobResult(i);return m?G({jobId:i,status:m.status==="error"?"failed":"completed",error:m.error}):G({jobId:i,status:"completed"})}if(o==="full"){const i=n.getState(),c=await Promise.all(i.jobs.map(async m=>{const u=[];if(m.entityShas&&m.entityShas.length>0){const p=m.entityShas.map(f=>_t(f)),h=await Promise.all(p);u.push(...h.filter(f=>f!==null))}return{id:m.id,type:m.type,commitSha:m.commitSha,projectSlug:m.projectSlug,queuedAt:m.queuedAt,entities:u,filePaths:m.filePaths}}));let d;if(i.currentlyExecuting){const m=i.currentlyExecuting,u=[];if(m.entityShas&&m.entityShas.length>0){const p=m.entityShas.map(f=>_t(f)),h=await Promise.all(p);u.push(...h.filter(f=>f!==null))}d={id:m.id,type:m.type,commitSha:m.commitSha,projectSlug:m.projectSlug,queuedAt:m.queuedAt,entities:u,filePaths:m.filePaths}}return G({state:{...i,jobsWithEntities:c,currentlyExecutingWithEntities:d}})}return G({error:"Unknown queryType"},{status:400})}async function gp({request:e,context:r}){console.log("[Queue API] Received request"),console.log("[Queue API] Context keys:",Object.keys(r||{})),console.log("[Queue API] analysisQueue exists:",!!(r!=null&&r.analysisQueue));let n=r.analysisQueue;if(n||(n=await st(),console.log("[Queue API] Using global queue")),!n)return console.error("[Queue API] ERROR: Queue not initialized in context"),G({error:"Queue not initialized"},{status:500});const a=await e.json(),{action:o,...s}=a;if(console.log("[Queue API] Action:",o,"Params:",Object.keys(s)),o==="enqueue"){const{jobId:i,completion:c}=n.enqueue(s);return c.catch(d=>{console.error(`[Queue API] Job ${i} failed:`,d)}),G({jobId:i,status:"queued"})}if(o==="resume")return n.resume(),G({status:"resumed"});if(o==="pause")return n.pause(),G({status:"paused"});if(o==="remove"){const{jobId:i}=s;return i?n.removeJob(i)?G({status:"removed",jobId:i}):G({error:"Job not found in queue"},{status:404}):G({error:"Missing jobId parameter"},{status:400})}if(o==="clear"){const i=n.clearQueue();return G({status:"cleared",count:i})}if(o==="reorder"){const{jobId:i,direction:c}=s;return!i||!c?G({error:"Missing jobId or direction parameter"},{status:400}):c!=="up"&&c!=="down"?G({error:'Invalid direction: must be "up" or "down"'},{status:400}):n.reorderJob(i,c)?G({status:"reordered",jobId:i,direction:c}):G({error:"Could not reorder job (not found or at boundary)"},{status:400})}return G({error:"Unknown action"},{status:400})}const yp=Object.freeze(Object.defineProperty({__proto__:null,action:gp,loader:fp},Symbol.toStringTag,{value:"Module"})),xp=()=>[{title:"Empty State - CodeYam"},{name:"description",content:"Simulations empty state development view"}],bp=Oe(function(){return Ae(),t(Rr,{children:l("div",{className:"h-screen bg-[#F8F7F6] flex flex-col overflow-hidden",children:[t("header",{className:"bg-white border-b border-gray-200 shrink-0 relative h-[54px]",children:l("div",{className:"flex items-center h-full px-6 gap-6",children:[l("div",{className:"flex items-center gap-3 min-w-0",children:[t("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:t("path",{d:"M13 8.5H4M4 8.5L8.5 4M4 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),t("h1",{className:"text-lg font-semibold text-black m-0 leading-[26px] shrink-0",children:"Dashboard"}),t("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"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[l("div",{className:"flex items-center gap-2 px-[15px] py-0 h-[26px] bg-[#efefef] border border-[#e1e1e1] rounded",children:[t("div",{className:"w-2 h-2 rounded-full bg-[#626262]"}),t("span",{className:"text-xs font-semibold text-[#626262]",children:"Not analyzed"})]}),t("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"})]}),l("div",{className:"flex items-center gap-1 text-[10px] text-[#626262] ml-auto",children:[t("span",{className:"leading-[22px]",children:"Next Entity"}),t("svg",{width:"17",height:"17",viewBox:"0 0 17 17",fill:"none",className:"shrink-0",children:t("path",{d:"M4 8.5H13M13 8.5L8.5 4M13 8.5L8.5 13",stroke:"#005c75",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]})]})}),t("div",{className:"bg-[#efefef] border-b border-[#efefef] shrink-0",children:l("div",{className:"flex items-center gap-3 h-11 px-[15px]",children:[l("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",t("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#cbf3fa] text-[#005c75] min-w-[25px] text-center",children:"0"})]}),l("div",{className:"px-4 flex items-center justify-center gap-3 shrink-0 text-sm rounded-[9px] text-[#3e3e3e] font-normal",children:["Related Entities",t("span",{className:"px-2 py-0.5 rounded-[9px] text-xs font-semibold bg-[#e1e1e1] text-[#3e3e3e] min-w-[25px] text-center",children:"5"})]}),t("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Code"}),t("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"Data Structure"}),t("div",{className:"px-4 shrink-0 text-sm text-[#3e3e3e] font-normal",children:"History"})]})}),l("div",{className:"flex flex-1 gap-0 min-h-0",children:[t("div",{className:"w-[165px] bg-[#e1e1e1] border-r border-[#c7c7c7] flex items-center justify-center shrink-0",children:t("span",{className:"text-xs font-medium text-[#8e8e8e] leading-5",children:"No Scenarios"})}),t(gs,{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})]})]})})}),wp=Object.freeze(Object.defineProperty({__proto__:null,default:bp,meta:xp},Symbol.toStringTag,{value:"Module"})),vp=()=>[{title:"CodeYam - Settings"},{name:"description",content:"Configure project settings"}];async function Cp({request:e}){try{const r=await Rn();if(!r)return G({config:null,secrets:null,versionInfo:null,error:"Project configuration not found"});const n=pe()||process.cwd(),a=await Ir(n),o=Zo(r.projectSlug);return G({config:r,secrets:{GROQ_API_KEY:a.GROQ_API_KEY||"",ANTHROPIC_API_KEY:a.ANTHROPIC_API_KEY||"",OPENAI_API_KEY:a.OPENAI_API_KEY||""},versionInfo:o,error:null})}catch(r){return console.error("Failed to load config:",r),G({config:null,secrets:null,versionInfo:null,error:"Failed to load configuration"})}}function Np(e){if(!e||!e.trim())return;const r=e.trim().split(/\s+/);if(r.length===0)return;const n=r[0],a=r.length>1?r.slice(1):void 0;return{command:n,args:a}}async function Sp({request:e}){try{const r=await e.formData(),n=r.get("universalMocks"),a=r.get("startCommands"),o=r.get("groqApiKey"),s=r.get("anthropicApiKey"),i=r.get("openAiApiKey"),c=r.get("pathsToIgnore");let d;if(n)try{d=JSON.parse(n)}catch{return G({success:!1,error:"Invalid universalMocks JSON format",requiresRestart:!1},{status:400})}let m;if(a)try{m=JSON.parse(a)}catch{return G({success:!1,error:"Invalid startCommands JSON format",requiresRestart:!1},{status:400})}let u;c&&(u=c.split(",").map(y=>y.trim()).map(y=>y.startsWith('"')&&y.endsWith('"')||y.startsWith("'")&&y.endsWith("'")?y.slice(1,-1):y).filter(y=>y.length>0));let p;if(m){const y=await Rn();y!=null&&y.webapps&&(p=y.webapps.map((g,w)=>{if(m[w]!==void 0){const x=Np(m[w]);return{...g,startCommand:x}}return g}))}if(!await Uo({universalMocks:d,pathsToIgnore:u,webapps:p}))return G({success:!1,error:"Failed to update configuration",requiresRestart:!1},{status:500});let f=!1;if(o!==void 0||s!==void 0||i!==void 0){const y=pe()||process.cwd(),g=await Ir(y);f=o!==void 0&&o!==(g.GROQ_API_KEY||"")||s!==void 0&&s!==(g.ANTHROPIC_API_KEY||"")||i!==void 0&&i!==(g.OPENAI_API_KEY||""),await fc(y,{...g,GROQ_API_KEY:o||void 0,ANTHROPIC_API_KEY:s||void 0,OPENAI_API_KEY:i||void 0},!0)}return G({success:!0,error:null,requiresRestart:f})}catch(r){return console.log("[Settings Action] Failed to save config:",r),G({success:!1,error:"Failed to save configuration",requiresRestart:!1},{status:500})}}function to(e){if(!e)return"";const r=[e.command];return e.args&&e.args.length>0&&r.push(...e.args),r.join(" ")}function ro({mock:e,onSave:r,onCancel:n}){const[a,o]=M(e.entityName),[s,i]=M(e.filePath),[c,d]=M(e.content);return l("div",{className:"space-y-3",children:[l("div",{children:[t("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Entity Name"}),t("input",{type:"text",value:a,onChange:u=>o(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"})]}),l("div",{children:[t("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path"}),t("input",{type:"text",value:s,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"})]}),l("div",{children:[t("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),t("textarea",{value:c,onChange:u=>d(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' }"})]}),l("div",{className:"flex gap-2 justify-end",children:[t("button",{type:"button",onClick:n,className:"px-4 py-2 bg-gray-200 text-gray-800 border-none rounded text-sm cursor-pointer hover:bg-gray-300",children:"Cancel"}),t("button",{type:"button",onClick:()=>{if(!a.trim()||!s.trim()||!c.trim()){alert("All fields are required");return}r({entityName:a,filePath:s,content:c})},className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Save"})]})]})}function Ep(e){try{return new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"})}catch{return e}}const Ap=Oe(function(){var U,Q;const{config:r,secrets:n,versionInfo:a,error:o}=We(),s=qs(),i=Ae(),c=rt(),[d,m]=M("project-metadata");mt({source:"settings-page"});const[u,p]=M((r==null?void 0:r.universalMocks)||[]),[h,f]=M(((r==null?void 0:r.pathsToIgnore)||[]).join(", ")),[y,g]=M(((r==null?void 0:r.pathsToIgnore)||[]).join(", ")),[w,x]=M((n==null?void 0:n.GROQ_API_KEY)||""),[b,v]=M((n==null?void 0:n.ANTHROPIC_API_KEY)||""),[C,E]=M((n==null?void 0:n.OPENAI_API_KEY)||""),[N,A]=M(!1),[_,$]=M(!1),[D,I]=M(!1),[k,T]=M(!1),[j,P]=M(!1),[B,L]=M(!1),[z,O]=M(null),[F,R]=M(!1),[S,H]=M({});re(()=>{var W;if(r){p(r.universalMocks||[]);const Z=(r.pathsToIgnore||[]).join(", ");f(Z),g(Z);const de={};(W=r.webapps)==null||W.forEach((ue,ge)=>{ue.startCommand&&(de[ge]=to(ue.startCommand))}),H(de)}n&&(x(n.GROQ_API_KEY||""),v(n.ANTHROPIC_API_KEY||""),E(n.OPENAI_API_KEY||""))},[r,n]),re(()=>{if(s!=null&&s.success){T(!0);const W=setTimeout(()=>T(!1),3e3);return()=>clearTimeout(W)}},[s]),re(()=>{if(i.state==="idle"&&i.data&&!B){console.log("[Settings] Fetcher data:",i.data);const W=i.data;if(W.success){console.log("[Settings] Save successful, revalidating..."),T(!0),L(!0),(h!==y||W.requiresRestart)&&P(!0),c.revalidate();const Z=setTimeout(()=>{T(!1),L(!1)},3e3);return()=>clearTimeout(Z)}}},[i.state,i.data,B,c,h,y]);const q=W=>{W.preventDefault();const Z=new FormData(W.currentTarget);Z.set("universalMocks",JSON.stringify(u)),Z.set("startCommands",JSON.stringify(S)),console.log("[Settings] Submitting form data:",{universalMocks:Z.get("universalMocks"),startCommands:Z.get("startCommands"),openAiApiKey:Z.get("openAiApiKey")?"***":"(empty)"}),i.submit(Z,{method:"post"})},J=W=>{p([...u,W]),R(!1)},ae=(W,Z)=>{const de=[...u];de[W]=Z,p(de),O(null)},V=W=>{p(u.filter((Z,de)=>de!==W))};if(o)return l("div",{className:"max-w-6xl mx-auto p-8 font-sans",children:[t("header",{className:"mb-6 pb-4 border-b border-gray-200",children:t("div",{className:"flex justify-between items-center",children:t("h1",{className:"text-4xl font-bold text-gray-900",children:"Settings"})})}),t("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4",children:t("p",{className:"text-red-700",children:o})})]});const Y=[{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:"current-configuration",label:"Current Configuration"}];return t("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12 font-sans",children:[l("div",{className:"mb-8 flex justify-between items-start",children:[l("div",{children:[t("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Settings"}),t("p",{className:"text-[15px] text-gray-500",children:"Project Configuration"})]}),t("button",{type:"submit",form:"settings-form",disabled:i.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:i.state==="submitting"?"Saving...":"Save Settings"})]}),l("div",{className:"flex gap-8 items-start",children:[t("nav",{className:"w-64 flex-shrink-0",children:t("ul",{className:"space-y-1",children:Y.map(W=>t("li",{children:t("button",{type:"button",onClick:()=>m(W.id),className:`w-full text-left px-0 py-2.5 text-sm transition-colors cursor-pointer ${d===W.id?"text-[#005C75] font-medium":"text-gray-600 hover:text-gray-900"}`,children:W.label})},W.id))})}),t("div",{className:"flex-1 min-w-0 -mt-2",children:l("form",{id:"settings-form",onSubmit:q,className:"space-y-6",children:[d==="project-metadata"&&l("div",{children:[t("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Project Metadata"}),l("div",{className:"mb-6",children:[t("label",{className:"block mb-2 font-medium text-gray-700",children:"Web Applications"}),r!=null&&r.webapps&&r.webapps.length>0?t("div",{className:"space-y-3",children:r.webapps.map((W,Z)=>{var de;return t("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Path:"})," ",t("span",{className:"text-gray-900",children:W.path==="."?"Root":W.path})]}),W.appDirectory&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",t("span",{className:"text-gray-900",children:W.appDirectory})]}),l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",t("span",{className:"text-gray-900",children:W.framework})]}),W.startCommand&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",l("span",{className:"text-gray-900 font-mono text-xs",children:[W.startCommand.command," ",(de=W.startCommand.args)==null?void 0:de.join(" ")]})]})]})},Z)})}):t("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"}),t("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`."})]})]}),d==="ai-provider"&&l("div",{children:[t("h3",{className:"text-lg font-semibold text-gray-800 mb-4",children:"AI Provider API Keys"}),t("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."}),l("div",{className:"space-y-6",children:[l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[t("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[t("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Groq"}),t("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."}),l("div",{className:"flex gap-3 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[t("span",{className:"font-medium",children:"Cost:"})," ","$0.10/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[t("span",{className:"font-medium",children:"Speed:"})," 850 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[t("span",{className:"font-medium",children:"Reliability:"})," ","Less reliable, but capable of producing reasonable results"]})]})]})}),l("div",{className:"mt-4",children:[t("label",{htmlFor:"groqApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[t("input",{type:N?"text":"password",id:"groqApiKey",name:"groqApiKey",value:w,onChange:W=>x(W.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]"}),t("button",{type:"button",onClick:()=>A(!N),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:N?"Hide":"Show"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[t("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[t("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"Anthropic Claude"}),t("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."}),l("div",{className:"flex gap-3 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[t("span",{className:"font-medium",children:"Cost:"})," ","$3.00/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[t("span",{className:"font-medium",children:"Speed:"})," 120 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[t("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[t("label",{htmlFor:"anthropicApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[t("input",{type:_?"text":"password",id:"anthropicApiKey",name:"anthropicApiKey",value:b,onChange:W=>v(W.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]"}),t("button",{type:"button",onClick:()=>$(!_),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"})]})]})]}),l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[t("div",{className:"flex items-start justify-between mb-3",children:l("div",{children:[t("h4",{className:"text-base font-semibold text-gray-900 mb-1",children:"OpenAI GPT"}),t("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."}),l("div",{className:"flex gap-3 text-xs",children:[l("div",{className:"px-2 py-1 bg-green-100 text-green-800 rounded",children:[t("span",{className:"font-medium",children:"Cost:"})," ","$2.50/1M tokens"]}),l("div",{className:"px-2 py-1 bg-cyan-100 text-cyan-800 rounded",children:[t("span",{className:"font-medium",children:"Speed:"})," 150 tokens/s"]}),l("div",{className:"px-2 py-1 bg-purple-100 text-purple-800 rounded",children:[t("span",{className:"font-medium",children:"Reliability:"})," ","Consistent, high quality results"]})]})]})}),l("div",{className:"mt-4",children:[t("label",{htmlFor:"openAiApiKey",className:"block text-sm font-medium text-gray-700 mb-2",children:"API Key"}),l("div",{className:"relative",children:[t("input",{type:D?"text":"password",id:"openAiApiKey",name:"openAiApiKey",value:C,onChange:W=>E(W.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]"}),t("button",{type:"button",onClick:()=>I(!D),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:D?"Hide":"Show"})]})]})]})]})]}),d==="commands"&&l("div",{children:[t("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Commands"}),t("p",{className:"text-sm text-gray-600 mb-6",children:"Configure start commands for your web applications"}),r!=null&&r.webapps&&r.webapps.length>0?t("div",{className:"space-y-4",children:r.webapps.map((W,Z)=>l("div",{className:"border border-gray-200 rounded-lg p-5 bg-white",children:[l("div",{className:"mb-4",children:[t("div",{className:"text-base font-semibold text-gray-900 mb-1",children:W.path==="."?"Root":W.path}),t("div",{className:"text-sm text-gray-600",children:W.framework})]}),l("div",{children:[t("label",{htmlFor:`startCommand-${Z}`,className:"block text-sm font-medium text-gray-700 mb-2",children:"Start Command"}),t("input",{type:"text",id:`startCommand-${Z}`,name:`startCommand-${Z}`,value:S[Z]||"",onChange:de=>H({...S,[Z]:de.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]"}),t("p",{className:"mt-2 text-xs text-gray-500",children:"Use $PORT as a placeholder for the dynamic port number"})]})]},Z))}):t("p",{className:"text-sm text-gray-600 italic",children:"No web applications configured"})]}),d==="paths-to-ignore"&&l("div",{children:[t("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Paths To Ignore"}),t("input",{type:"text",id:"pathsToIgnore",name:"pathsToIgnore",value:h,onChange:W=>f(W.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"}),l("p",{className:"mt-2 text-sm text-gray-600",children:["Comma-separated list of regex patterns for paths to ignore during file watching. Examples:"," ",t("code",{className:"bg-gray-100 px-1 rounded",children:"__tests__"}),","," ",t("code",{className:"bg-gray-100 px-1 rounded",children:"\\.test\\.tsx?$"}),","," ",t("code",{className:"bg-gray-100 px-1 rounded",children:"^background"}),t("br",{}),t("span",{className:"text-xs text-gray-500 mt-1 inline-block",children:"Note: Files matching patterns in .gitignore are also automatically ignored"})]})]}),d==="universal-mocks"&&l("div",{children:[t("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Universal Mocks"}),t("p",{className:"mb-3 text-sm text-gray-600",children:"Mock functions that will be applied across all entity simulations"}),u.length===0?l("div",{className:"mb-4",children:[t("div",{className:"text-sm text-gray-500 mb-3",children:"No universal mocks configured"}),t("button",{type:"button",onClick:()=>R(!0),className:"px-4 py-2 bg-[#005C75] text-white border-none rounded text-sm cursor-pointer hover:bg-[#004a5d]",children:"Add Mock"})]}):t("div",{className:"space-y-3",children:u.map((W,Z)=>t("div",{className:"p-4 bg-gray-50 rounded border border-gray-200",children:z===Z?t(ro,{mock:W,onSave:de=>ae(Z,de),onCancel:()=>O(null)}):t(le,{children:l("div",{className:"flex justify-between items-start mb-2",children:[l("div",{className:"flex-1",children:[t("div",{className:"font-medium text-gray-800 mb-1",children:W.entityName}),t("div",{className:"text-sm text-gray-600 mb-2",children:W.filePath}),t("pre",{className:"text-xs bg-white p-2 rounded border border-gray-200 overflow-x-auto",children:W.content})]}),l("div",{className:"flex gap-2 ml-3",children:[t("button",{type:"button",onClick:()=>O(Z),className:"px-3 py-1 bg-teal-600 text-white border-none rounded text-sm cursor-pointer hover:bg-teal-700",children:"Edit"}),t("button",{type:"button",onClick:()=>V(Z),className:"px-3 py-1 bg-red-600 text-white border-none rounded text-sm cursor-pointer hover:bg-red-700",children:"Delete"})]})]})})},Z))}),u.length>0&&t("button",{type:"button",onClick:()=>R(!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"})]}),d==="current-configuration"&&l("div",{className:"space-y-6",children:[r&&l("div",{children:[t("h2",{className:"text-lg font-semibold text-gray-800 mb-4",children:"Current Configuration"}),t("div",{className:"p-4 bg-white border border-gray-200 rounded mb-6",children:l("div",{className:"space-y-2 text-sm",children:[r.projectSlug&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Project Slug:"})," ",t("span",{className:"text-gray-900",children:r.projectSlug})]}),r.packageManager&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Package Manager:"})," ",t("span",{className:"text-gray-900",children:r.packageManager})]})]})}),r.webapps&&r.webapps.length>0&&l("div",{children:[t("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Web Applications"}),t("div",{className:"space-y-3",children:r.webapps.map((W,Z)=>t("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Path:"})," ",t("span",{className:"text-gray-900",children:W.path==="."?"Root":W.path})]}),W.appDirectory&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"App Directory:"})," ",t("span",{className:"text-gray-900",children:W.appDirectory})]}),l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Framework:"})," ",t("span",{className:"text-gray-900",children:W.framework})]}),W.startCommand&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Start Command:"})," ",t("span",{className:"text-gray-900 font-mono text-xs",children:to(W.startCommand)})]})]})},Z))})]})]}),a&&l("div",{className:"mt-6",children:[t("h3",{className:"text-base font-semibold text-gray-800 mb-3",children:"Version Information"}),t("div",{className:"p-4 bg-white border border-gray-200 rounded",children:l("div",{className:"space-y-2 text-sm",children:[a.webserverVersion&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Webserver:"})," ",t("span",{className:"text-gray-900 font-mono",children:a.webserverVersion.version||"unknown"})]}),a.templateVersion&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Analyzer Template:"})," ",t("span",{className:"font-mono text-gray-900",children:a.templateVersion.version||((U=a.templateVersion.gitCommit)==null?void 0:U.slice(0,7))||"unknown"}),a.templateVersion.buildTimestamp&&l("span",{className:"text-gray-500 ml-2",children:["(built"," ",Ep(a.templateVersion.buildTimestamp),")"]})]}),a.cachedAnalyzerVersion&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",t("span",{className:"font-mono text-gray-900",children:a.cachedAnalyzerVersion.version||((Q=a.cachedAnalyzerVersion.gitCommit)==null?void 0:Q.slice(0,7))||"unknown"}),a.isCacheStale?t("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"}):t("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-800 rounded text-xs",children:"Up to date"})]}),!a.cachedAnalyzerVersion&&(r==null?void 0:r.projectSlug)&&l("div",{children:[t("span",{className:"font-medium text-gray-700",children:"Cached Analyzer:"})," ",t("span",{className:"text-gray-500 italic",children:"Not initialized - will be created on first analysis"})]})]})})]})]})]})})]}),(k||j||(s==null?void 0:s.error)||i.data&&typeof i.data=="object"&&"error"in i.data)&&l("div",{className:"mt-6 max-w-5xl mx-auto space-y-3",children:[k&&t("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!"}),j&&l("div",{className:"text-amber-700 text-sm font-medium bg-amber-50 border border-amber-200 rounded px-4 py-2",children:[t("div",{children:"⚠️ Settings changed. Please restart CodeYam for changes to take effect:"}),t("code",{className:"ml-2 bg-amber-100 px-2 py-1 rounded text-xs",children:"codeyam stop && codeyam"})]}),(s==null?void 0:s.error)&&t("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:s.error}),(()=>{if(i.data&&typeof i.data=="object"&&"error"in i.data){const W=i.data;return typeof W.error=="string"?t("div",{className:"text-red-600 text-sm font-medium bg-red-50 border border-red-200 rounded px-4 py-2",children:W.error}):null}return null})()]}),F&&t("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50",children:l("div",{className:"bg-white rounded-lg max-w-2xl w-full p-6",children:[t("h2",{className:"text-2xl font-bold mb-4 text-gray-900",children:"Add Universal Mock"}),t(ro,{mock:{entityName:"",filePath:"",content:""},onSave:J,onCancel:()=>R(!1)})]})})]})})}),kp=Object.freeze(Object.defineProperty({__proto__:null,action:Sp,default:Ap,loader:Cp,meta:vp},Symbol.toStringTag,{value:"Module"}));async function Pp({params:e}){const r=e["*"];if(!r)return new Response("Static path is required",{status:400});const n=pe();if(!n)return new Response("Project root not found",{status:500});const o=he.extname(r)!==""?r:`${r}.html`,s=he.join(n,".codeyam","captures","static",o);try{await xe.access(s);let i=await xe.readFile(s);const c=he.extname(s).toLowerCase();let d="application/octet-stream";if(c===".html"){d="text/html";let m=i.toString("utf-8");const u=m.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 y=`<script>window.__remixContext = ${JSON.stringify(f)};<\/script>`;m=m.replace(u[0],y)}}catch(p){console.error("[Static] Failed to parse Remix context:",p)}i=Buffer.from(m,"utf-8")}else c===".js"||c===".mjs"?d="application/javascript":c===".css"?d="text/css":c===".json"?d="application/json":c===".png"?d="image/png":c===".jpg"||c===".jpeg"?d="image/jpeg":c===".svg"?d="image/svg+xml":c===".woff"?d="font/woff":c===".woff2"?d="font/woff2":c===".ttf"&&(d="font/ttf");return new Response(i,{status:200,headers:{"Content-Type":d,"Cache-Control":"public, max-age=3600","X-Frame-Options":"SAMEORIGIN"}})}catch{return new Response("Static file not found",{status:404})}}const _p=Object.freeze(Object.defineProperty({__proto__:null,loader:Pp},Symbol.toStringTag,{value:"Module"}));function Mp(e,r,n=10){var d;const a=new Map,o=m=>m.entityType==="visual"||m.entityType==="library";for(const m of e)o(m)&&a.set(m.sha,{entity:m,depth:0});const s=new Map;for(const m of r){const u=(d=m.metadata)==null?void 0:d.importedBy;if(u)for(const p of Object.keys(u))for(const h of Object.keys(u[p])){const{shas:f}=u[p][h];for(const y of f)s.has(m.sha)||s.set(m.sha,new Set),s.get(m.sha).add(y)}}const i=[],c=new Set;for(const m of e)i.push({sha:m.sha,depth:0}),c.add(m.sha);for(;i.length>0;){const{sha:m,depth:u}=i.shift();if(u>=n)continue;const p=s.get(m);if(p)for(const h of p){if(c.has(h))continue;c.add(h);const f=r.find(y=>y.sha===h);if(f){if(o(f)){const y=u+1,g=a.get(h);(!g||y<g.depth)&&a.set(h,{entity:f,depth:y})}i.push({sha:h,depth:u+1})}}}return Array.from(a.values()).sort((m,u)=>m.depth!==u.depth?m.depth-u.depth:m.entity.name.localeCompare(u.entity.name))}function Nr(e){const r=new Map;for(const a of e)r.has(a.name)||r.set(a.name,[]),r.get(a.name).push(a);const n=[];for(const a of r.values())if(a.length===1)n.push(a[0]);else{const o=a.sort((s,i)=>{var m,u;const c=((m=s.metadata)==null?void 0:m.editedAt)||s.createdAt||"";return(((u=i.metadata)==null?void 0:u.editedAt)||i.createdAt||"").localeCompare(c)});n.push(o[0])}return n}function bs(e,r){const n=new Map,a=new Set(e.map(o=>o.path));for(const o of e)o.status==="renamed"&&o.oldPath&&a.add(o.oldPath);for(const o of e){const s=r.filter(d=>d.filePath===o.path||o.status==="renamed"&&o.oldPath&&d.filePath===o.oldPath),i=s.filter(d=>{var m,u;return a.has(d.filePath)&&((m=d.metadata)==null?void 0:m.isUncommitted)&&!((u=d.metadata)!=null&&u.isSuperseded)}),c=Nr(i);n.set(o.path,{status:o,entities:s,editedEntities:c})}return n}function Tp(e,r,n){const a=new Map;if(!n){for(const s of e)if(s.status==="deleted")a.set(s.path,{status:s,entities:[]});else{const i=r.filter(d=>d.filePath===s.path||s.status==="renamed"&&s.oldPath&&d.filePath===s.oldPath),c=Nr(i);a.set(s.path,{status:s,entities:c})}return a}const o=new Map;for(const s of n.fileComparisons){const i=new Set;for(const c of s.newEntities)i.add(c.name);for(const c of s.modifiedEntities)i.add(c.name);for(const c of s.deletedEntities)i.add(c.name);i.size>0&&o.set(s.filePath,i)}for(const s of e){const i=o.get(s.path);if(s.status==="deleted")a.set(s.path,{status:s,entities:[]});else{const c=i?r.filter(m=>(m.filePath===s.path||s.status==="renamed"&&s.oldPath&&m.filePath===s.oldPath)&&i.has(m.name)):[],d=Nr(c);a.set(s.path,{status:s,entities:d})}}return a}function Ip(e,r){const n=new Map,a=ws(e,r);for(const o of a){const i=Mp([o],r).filter(({depth:c})=>c>0);n.set(o.sha,i)}return n}function ws(e,r){const n=new Set(e.map(o=>o.path));for(const o of e)o.status==="renamed"&&o.oldPath&&n.add(o.oldPath);const a=r.filter(o=>{var s,i;return n.has(o.filePath)&&((s=o.metadata)==null?void 0:s.isUncommitted)&&!((i=o.metadata)!=null&&i.isSuperseded)});return Nr(a)}function $p({recentSimulations:e}){const r=ne(()=>{const n=new Map;return e.forEach(a=>{const o=a.entitySha,s=n.get(o);s?s.push(a):n.set(o,[a])}),Array.from(n.entries()).map(([a,o])=>({entitySha:a,entityName:o[0].entityName,scenarios:o}))},[e]);return l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[t("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[t("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),t("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?l(le,{children:[t("div",{className:"space-y-6 mb-5",children:r.map(n=>l("div",{children:[l("div",{className:"mb-3 flex items-center gap-2",children:[t("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center bg-purple-100",children:t(Ut,{size:16,style:{color:"#8B5CF6"}})}),t(oe,{to:`/entity/${n.entitySha}`,className:"text-sm font-semibold text-gray-900 no-underline hover:text-gray-700 transition-colors",children:n.entityName})]}),t("div",{className:"grid grid-cols-4 gap-3",children:n.scenarios.map((a,o)=>t(oe,{to:a.scenarioId?`/entity/${a.entitySha}/scenarios/${a.scenarioId}`:`/entity/${a.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:s=>{s.currentTarget.style.borderColor="#005C75",s.currentTarget.style.boxShadow="0 4px 12px rgba(0, 92, 117, 0.2)"},onMouseLeave:s=>{s.currentTarget.style.borderColor="#E5E7EB",s.currentTarget.style.boxShadow="none"},title:a.scenarioName,children:t(De,{screenshotPath:a.screenshotPath,alt:a.scenarioName,className:"max-w-full max-h-full object-contain object-center"})},a.scenarioId||`${a.entitySha}-${o}`))})]},n.entitySha))}),t(oe,{to:"/simulations",className:"block text-center p-3 rounded-lg no-underline font-semibold text-sm transition-all",style:{color:"#005C75",backgroundColor:"#F6F9FC"},onMouseEnter:n=>n.currentTarget.style.backgroundColor="#EEF4F8",onMouseLeave:n=>n.currentTarget.style.backgroundColor="#F6F9FC",children:"View All Recent Simulations →"})]}):l("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:[t("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:t(Ut,{size:24,style:{color:"#7A9BA5"},strokeWidth:1.5})}),t("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No simulations captured yet."}),l("p",{className:"text-xs m-0 mt-2",style:{color:"#7A9BA5"},children:["Trigger an analysis from the"," ",t(oe,{to:"/git",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Git"})," ","or"," ",t(oe,{to:"/files",className:"underline hover:no-underline",style:{color:"#7A9BA5"},children:"Files"})," ","page."]})]})]})}const jp="/assets/codeyam-name-logo-CvKwUgHo.svg",Rp=()=>[{title:"Dashboard - CodeYam"},{name:"description",content:"CodeYam project dashboard"}];async function Dp({request:e,context:r}){var n,a;try{const o=r.analysisQueue,s=o?o.getState():{paused:!1,jobs:[]},[i,c,d]=await Promise.all([Zt(),ze(),It()]),m=ds(),u=i?bs(m,i):new Map,p=Array.from(u.entries()).sort((D,I)=>D[0].localeCompare(I[0])),h=(i==null?void 0:i.length)||0,f=(i==null?void 0:i.filter(D=>D.entityType==="visual").length)||0,y=(i==null?void 0:i.filter(D=>D.entityType==="library").length)||0,g=i?ws(m,i):[],w=g.length,x=(i==null?void 0:i.filter(D=>(D.analyses??[]).filter(I=>I.scenarios&&I.scenarios.length>0).length>0).length)||0,b=(i==null?void 0:i.reduce((D,I)=>{var T,j,P;const k=((P=(j=(T=I.analyses)==null?void 0:T[0])==null?void 0:j.scenarios)==null?void 0:P.length)||0;return D+k},0))||0,v=(i==null?void 0:i.reduce((D,I)=>{var j,P;const T=(((P=(j=I.analyses)==null?void 0:j[0])==null?void 0:P.scenarios)||[]).filter(B=>{var L,z;return(z=(L=B.metadata)==null?void 0:L.screenshotPaths)==null?void 0:z[0]}).length;return D+T},0))||0,C=[];i==null||i.forEach(D=>{var k;const I=(k=D.analyses)==null?void 0:k[0];I!=null&&I.scenarios&&I.scenarios.filter(j=>{var P;return!((P=j.metadata)!=null&&P.sameAsDefault)}).forEach(j=>{var B,L;const P=(L=(B=j.metadata)==null?void 0:B.screenshotPaths)==null?void 0:L[0];P&&C.push({entitySha:D.sha,entityName:D.name,scenarioId:j.id,scenarioName:j.name,screenshotPath:P,createdAt:I.createdAt||""})})}),C.sort((D,I)=>new Date(I.createdAt).getTime()-new Date(D.createdAt).getTime());const E=C.slice(0,16),N=(i==null?void 0:i.filter(D=>D.entityType==="visual").filter(D=>{var T,j;const I=(T=D.analyses)==null?void 0:T[0];return!((j=I==null?void 0:I.scenarios)==null?void 0:j.some(P=>{var B,L;return(L=(B=P.metadata)==null?void 0:B.screenshotPaths)==null?void 0:L[0]}))}).slice(0,8))||[],A=(n=d==null?void 0:d.metadata)==null?void 0:n.currentRun,_=((a=A==null?void 0:A.currentEntityShas)==null?void 0:a.length)||0,$=s.jobs.length||0;return G({stats:{totalEntities:h,visualEntities:f,libraryEntities:y,uncommittedEntities:w,entitiesWithAnalyses:x,totalScenarios:b,capturedScreenshots:v,currentlyAnalyzing:_,filesOnQueue:$},uncommittedFiles:p,uncommittedEntitiesList:g,recentSimulations:E,visualEntitiesForSimulation:N,projectSlug:c,queueState:s,currentCommit:d})}catch(o){return console.error("Failed to load dashboard data:",o),G({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 Lp=Oe(function(){var O,F;const{stats:r,uncommittedFiles:n,uncommittedEntitiesList:a,recentSimulations:o,visualEntitiesForSimulation:s,projectSlug:i,queueState:c,currentCommit:d}=We(),m=Ae(),u=rt(),{showToast:p}=Mn();mt({source:"dashboard"});const[h,f]=M(new Set),[y,g]=M(null),[w,x]=M(!1),[b,v]=M(!1),{lastLine:C,isCompleted:E}=pt(i,!!y),{simulatingEntity:N,scenarios:A,scenarioStatuses:_,allScenariosCaptured:$}=ne(()=>{var Y,U;const R={simulatingEntity:null,scenarios:[],scenarioStatuses:[],allScenariosCaptured:!1};if(!y)return R;const S=s==null?void 0:s.find(Q=>Q.sha===y);if(!S)return R;const H=(Y=S.analyses)==null?void 0:Y[0],q=(H==null?void 0:H.scenarios)||[],J=((U=H==null?void 0:H.status)==null?void 0:U.scenarios)||[],ae=J.filter(Q=>Q.screenshotFinishedAt).length,V=q.length>0&&ae===q.length;return{simulatingEntity:S,scenarios:q,scenarioStatuses:J,allScenariosCaptured:V}},[y,s]);re(()=>{(E||$)&&g(null)},[E,$]);const D=(O=d==null?void 0:d.metadata)==null?void 0:O.currentRun,I=new Set((D==null?void 0:D.currentEntityShas)||[]),k=new Set(c.jobs.flatMap(R=>R.entityShas||[])),T=new Set(((F=c.currentlyExecuting)==null?void 0:F.entityShas)||[]),j=a.filter(R=>R.entityType==="visual"||R.entityType==="library"),P=j.filter(R=>!I.has(R.sha)&&!k.has(R.sha)&&!T.has(R.sha)),B=()=>{if(P.length===0){p("All entities are already queued or analyzing","info",3e3);return}const R=P.map(S=>S.sha);v(!0),p(`Starting analysis for ${P.length} entities...`,"info",3e3),m.submit({entityShas:R.join(",")},{method:"post",action:"/api/analyze"})};re(()=>{if(m.state==="idle"&&m.data){const R=m.data;R.success?(console.log("[Analyze All] Success:",R.message),p(`Analysis started for ${R.entityCount} entities in ${R.fileCount} files. Watch the logs for progress.`,"success",6e3),v(!1)):R.error&&(console.error("[Analyze All] Error:",R.error),p(`Error: ${R.error}`,"error",8e3),v(!1))}},[m.state,m.data,p]);const L=R=>{f(S=>{const H=new Set(S);return H.has(R)?H.delete(R):H.add(R),H})},z=[{label:"Total Entities",value:r.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:r.entitiesWithAnalyses,iconType:"check",link:"/simulations",color:"#10B981",tooltip:"Entities that have been analyzed by CodeYam and have generated scenarios."},{label:"Visual Components",value:r.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:r.libraryEntities,iconType:"code-xml",link:"/files?entityType=library",color:"#0DBFE9",tooltip:"Reusable functions and utilities that can be independently tested."}];return t("div",{className:"bg-cygray-10 min-h-screen",children:l("div",{className:"px-20 pt-8 pb-12",children:[l("header",{className:"mb-8 flex justify-between items-center",children:[l("div",{className:"flex items-center gap-4",children:[t("img",{src:jp,alt:"CodeYam",className:"h-3.5"}),t("span",{className:"text-gray-400 text-sm",children:"|"}),t("h1",{className:"text-sm font-mono font-normal text-gray-400 m-0",children:i?i.replace(/-/g," ").replace(/\b\w/g,R=>R.toUpperCase()):"Project"})]}),u.state==="loading"&&t("div",{className:"text-blue-600 text-sm font-medium animate-pulse",children:"🔄 Updating..."})]}),t("div",{className:"flex items-center justify-between gap-3",children:z.map((R,S)=>t(oe,{to:R.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 ${R.color}`},children:l("div",{className:"px-6 py-6 flex flex-col gap-3 flex-1",children:[l("div",{className:"flex md:justify-between md:items-start md:flex-row flex-col",children:[l("div",{className:"flex items-center gap-1.5 group relative",children:[t("span",{className:"text-xs text-gray-700 font-medium font-mono uppercase",children:R.label}),l("svg",{className:"w-3 h-3 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("circle",{cx:"12",cy:"12",r:"10",strokeWidth:"2"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 16v-4m0-4h.01"})]}),t("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("div",{className:"bg-gray-900 text-white text-xs rounded-lg px-3 py-2 shadow-lg",children:[R.tooltip,t("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),t("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 sm:hidden md:flex",style:{color:R.color},children:"View All →"})]}),l("div",{className:"flex flex-col gap-2",children:[l("div",{className:"flex items-center gap-3",children:[l("div",{className:"rounded-lg p-2 leading-none shrink-0",style:{backgroundColor:`${R.color}15`},children:[R.iconType==="folder"&&t(mi,{size:20,style:{color:R.color}}),R.iconType==="check"&&t(wn,{size:20,style:{color:R.color}}),R.iconType==="image"&&t(Ut,{size:20,style:{color:R.color}}),R.iconType==="code-xml"&&t(pi,{size:20,style:{color:R.color}})]}),t("div",{className:"text-3xl font-semibold font-mono text-gray-900 leading-none",children:R.value.toLocaleString("en-US")})]}),t("div",{className:"text-xs font-medium transition-colors flex items-center gap-1 md:hidden",style:{color:R.color},children:"View All →"})]})]})},S))}),l("div",{className:"mt-12 grid gap-8 items-start",style:{gridTemplateColumns:"repeat(auto-fit, minmax(500px, 1fr))"},children:[l("section",{id:"uncommitted",className:"bg-white border border-gray-200 rounded-xl p-6",children:[l("div",{className:"flex justify-between items-start mb-5",children:[l("div",{children:[t("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Uncommitted Changes"}),t("p",{className:"text-sm text-gray-500 m-0",children:n.length>0?`${n.length} file${n.length!==1?"s":""} with ${a.length} uncommitted entit${a.length!==1?"ies":"y"}`:"No uncommitted changes detected"})]}),j.length>0&&t("button",{onClick:B,disabled:m.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:R=>R.currentTarget.style.backgroundColor="#004560",onMouseLeave:R=>R.currentTarget.style.backgroundColor="#005C75",children:m.state!=="idle"||b?"Starting analysis...":P.length===0?"All Queued":"Analyze All"})]}),n.length>0?t("div",{className:"flex flex-col gap-3",children:n.map(([R,S])=>{const H=h.has(R),q=S.editedEntities||[];return l("div",{className:"bg-white border border-gray-200 border-l-4 rounded-lg overflow-hidden",style:{borderLeftColor:"#005C75"},children:[t("div",{className:"p-4 cursor-pointer select-none transition-colors hover:bg-gray-50",onClick:()=>L(R),role:"button",tabIndex:0,children:l("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-gray-500 text-xs w-4 shrink-0",children:H?"▼":"▶"}),l("svg",{width:"16",height:"20",viewBox:"0 0 12 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:[l("g",{clipPath:"url(#clip0_784_10666)",children:[t("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"}),t("path",{d:"M8.72656 3.3307H11.9906L8.72656 0V3.3307Z",fill:"#306AFF"}),t("line",{x1:"1.8125",y1:"5.94825",x2:"10.0235",y2:"5.94825",stroke:"#306AFF",strokeWidth:"1.27929"}),t("line",{x1:"1.8125",y1:"8.82715",x2:"6.01207",y2:"8.82715",stroke:"#306AFF",strokeWidth:"1.27929"}),t("line",{x1:"1.8125",y1:"11.7061",x2:"10.0235",y2:"11.7061",stroke:"#306AFF",strokeWidth:"1.27929"})]}),t("defs",{children:t("clipPath",{id:"clip0_784_10666",children:t("rect",{width:"12",height:"16",fill:"white"})})})]}),l("div",{className:"flex-1 min-w-0",children:[t("span",{className:"font-normal text-gray-900 text-sm block truncate",children:R}),l("span",{className:"text-xs text-gray-500",children:[q.length," entit",q.length!==1?"ies":"y"]})]})]})}),H&&t("div",{className:"border-t border-gray-200 bg-gray-50 p-3 flex flex-col gap-2",children:q.length>0?q.map(J=>{const ae=I.has(J.sha),V=k.has(J.sha)||T.has(J.sha);return l(oe,{to:`/entity/${J.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:Y=>Y.currentTarget.style.borderColor="#005C75",onMouseLeave:Y=>Y.currentTarget.style.borderColor="inherit",children:[l("div",{className:"shrink-0 rounded-lg p-1.5 flex items-center justify-center",style:{backgroundColor:J.entityType==="visual"?"#8B5CF615":J.entityType==="library"?"#6366F1":"#EC4899"},children:[J.entityType==="visual"&&t(Ut,{size:16,style:{color:"#8B5CF6"}}),J.entityType==="library"&&t(io,{size:16,className:"text-white"}),J.entityType==="other"&&t(fi,{size:16,className:"text-white"})]}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"flex items-center gap-2 mb-0.5",children:[t("div",{className:"font-semibold text-gray-900 text-sm",children:J.name}),J.entityType==="visual"&&t("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#8B5CF60D",color:"#8B5CF6"},children:"Visual"}),J.entityType==="library"&&t("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#0DBFE90D",color:"#0DBFE9"},children:"Library"}),J.entityType==="other"&&t("div",{className:"px-2 py-0.5 rounded-sm text-[10px] uppercase font-bold",style:{backgroundColor:"#EC48990D",color:"#EC4899"},children:"Other"})]}),J.description&&t("div",{className:"text-sm text-gray-500 mt-1 overflow-hidden text-ellipsis whitespace-nowrap",children:J.description})]}),l("div",{className:"flex items-center gap-2 shrink-0",children:[ae&&l("div",{className:"px-2 py-1 bg-pink-100 rounded text-xs text-pink-700 font-semibold flex items-center gap-1.5",children:[t(Ze,{size:14,className:"animate-spin"}),"Analyzing..."]}),!ae&&V&&t("div",{className:"px-2 py-1 bg-purple-50 border border-purple-300 rounded text-xs text-purple-700 font-semibold",children:"⏳ Queued"}),!ae&&!V&&t("button",{onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),p(`Starting analysis for ${J.name}...`,"info",3e3),m.submit({entityShas:J.sha},{method:"post",action:"/api/analyze"})},disabled:m.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:Y=>Y.currentTarget.style.backgroundColor="#004560",onMouseLeave:Y=>Y.currentTarget.style.backgroundColor="#005C75",children:"Analyze"})]})]},J.sha)}):t("div",{className:"text-sm text-gray-500 italic p-2",children:"No entity changes detected in this file"})})]},R)})}):l("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:[t("div",{className:"mb-4 rounded-full flex items-center justify-center",style:{width:"48px",height:"48px",backgroundColor:"#E5EFF1"},children:l("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#7A9BA5",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t("polyline",{points:"14 2 14 8 20 8"}),t("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),t("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}),t("p",{className:"text-sm font-medium m-0",style:{color:"#5A7380"},children:"No Uncommitted Changes."})]})]}),!y&&t($p,{recentSimulations:o}),y&&l("section",{className:"bg-white border border-gray-200 rounded-xl p-6",children:[t("div",{className:"flex justify-between items-start mb-5",children:l("div",{children:[t("h2",{className:"text-[22px] font-semibold text-gray-900 m-0 mb-1",children:"Recent Simulations"}),t("p",{className:"text-sm text-gray-500 m-0",children:o.length>0?`Latest ${o.length} captured screenshot${o.length!==1?"s":""}`:"No simulations captured yet"})]})}),y&&l("div",{className:"p-0 bg-white rounded-lg flex flex-col gap-0",children:[N&&t("div",{className:"p-4 rounded-t-lg",style:{backgroundColor:"#F0F5F8",borderBottom:"2px solid #005C75"},children:l("div",{className:"flex items-center gap-3",children:[t("span",{className:"text-[32px] leading-none",children:t(Ue,{type:"visual"})}),l("div",{className:"flex-1 min-w-0",children:[l("div",{className:"text-base font-bold mb-1",style:{color:"#005C75"},children:["Generating Simulations for ",N.name]}),t("div",{className:"text-[13px] text-gray-500 font-mono overflow-hidden text-ellipsis whitespace-nowrap",children:N.filePath})]})]})}),$?l("div",{className:"flex items-center gap-2 text-sm text-emerald-600 font-medium p-4 bg-emerald-50",children:[t("span",{className:"text-lg",children:"✅"}),l("span",{children:["Complete (",A.length," scenario",A.length!==1?"s":"",")"]})]}):C?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[t(Ze,{size:18,className:"animate-spin shrink-0"}),t("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap font-mono text-xs",title:C,children:C}),i&&t("button",{onClick:()=>x(!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"})]}):m.state!=="idle"?l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[t(Ze,{size:18,className:"animate-spin shrink-0"}),t("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Initializing analysis..."})]}):l("div",{className:"flex items-center justify-between gap-1.5 text-sm font-medium p-4 bg-gray-50",style:{color:"#005C75"},children:[t(Ze,{size:18,className:"animate-spin shrink-0"}),t("span",{className:"flex-1 overflow-hidden text-ellipsis whitespace-nowrap",children:"Starting analysis..."})]}),A.length>0&&t("div",{className:"flex gap-2 flex-wrap p-4 bg-white border-t border-gray-200",children:A.slice(0,8).map((R,S)=>{var U,Q,W;const H=(U=N==null?void 0:N.analyses)==null?void 0:U[0],q=Fr(R,H==null?void 0:H.status,void 0,y||void 0,void 0),J=(W=(Q=R.metadata)==null?void 0:Q.screenshotPaths)==null?void 0:W[0],ae=q.isCaptured,V=q.status==="capturing"||q.status==="starting",Y=q.hasError;return ae?t(oe,{to:`/entity/${y}`,className:"w-20 h-15 border-2 border-gray-200 rounded overflow-hidden bg-gray-50 cursor-pointer transition-all flex items-center justify-center no-underline hover:border-blue-600 hover:scale-105 hover:shadow-md",children:t(De,{screenshotPath:J,alt:R.name,title:R.name,className:"max-w-full max-h-full object-contain object-center"})},S):Y?t("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:q.errorMessage||"Capture error",children:t("span",{className:"text-red-500",children:"⚠️"})},S):t("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:`${V?"Capturing":"Pending"} ${R.name}...`,children:t("span",{className:V?"animate-pulse":"text-gray-400",children:V?"⋯":"⏹️"})},S)})})]})]})]}),w&&i&&t(dt,{projectSlug:i,onClose:()=>x(!1)})]})})}),Fp=Object.freeze(Object.defineProperty({__proto__:null,default:Lp,loader:Dp,meta:Rp},Symbol.toStringTag,{value:"Module"})),Op=()=>[{title:"CodeYam - Memory"},{name:"description",content:"Manage Claude Memory documentation"}];async function zp({request:e}){try{const[r,n]=await Promise.all([fetch(new URL("/api/memory",e.url).toString()),fetch(new URL("/api/memory?action=recent-changes",e.url).toString())]),a=await r.json(),o=await n.json();return a.error?G({memories:[],recentChanges:[],error:a.error}):G({memories:a.memories||[],recentChanges:o.changes||[],error:null})}catch(r){return console.error("Failed to load memories:",r),G({memories:[],recentChanges:[],error:"Failed to load memories"})}}const vs={architecture:"text-[#080096]",testing:"bg-green-100 text-green-800",faq:"text-[#080096]"},Gn={architecture:"Architecture",testing:"Testing",faq:"FAQ"};function xn(e){return Math.round(e/3.5)}function Cs({rule:e,onEdit:r,onDelete:n}){const[a,o]=M(!1),s=e.frontmatter.category||"faq",i=ne(()=>{var f;const h=e.body.match(/^#+ (.+)$/m);return h?h[1]:(f=e.filePath.split("/").pop())==null?void 0:f.replace(".md","")},[e.body,e.filePath]);ne(()=>{const f=e.body.replace(/^---[\s\S]*?---\n/m,"").replace(/^#+ .+$/m,"").trim().split(/\n+/).map(w=>w.trim().replace(/\*\*/g,"").replace(/\*/g,"").replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").trim()).filter(w=>w.length>15&&!w.startsWith("#")),y=f.join(" ").toLowerCase();let g="";if(y.includes("architecture")||y.includes("pattern")||y.includes("structure")){const w=f.find(x=>x.toLowerCase().includes("use")||x.toLowerCase().includes("should")||x.toLowerCase().includes("pattern"));w&&(g=w)}if(!g&&(y.includes("test")||y.includes("jest")||y.includes("expect"))){const w=f.find(x=>x.toLowerCase().includes("test")||x.toLowerCase().includes("write")||x.toLowerCase().includes("ensure"));w&&(g=w)}if(!g&&(y.includes("gotcha")||y.includes("issue")||y.includes("problem")||y.includes("avoid"))){const w=f.find(x=>x.toLowerCase().includes("avoid")||x.toLowerCase().includes("issue")||x.toLowerCase().includes("problem")||x.toLowerCase().includes("gotcha"));w&&(g=w)}if(!g){const w=f.find(x=>!x.toLowerCase().includes("learned:")&&!x.toLowerCase().includes("example:")&&x.length>30&&(x.includes(".")||x.length>50));w&&(g=w)}if(g||(g=f.slice(0,2).join(" ")),g.length>140){const w=g.lastIndexOf(" ",137);g=g.slice(0,w>100?w:137)+"..."}return g||"No description available."},[e.body]);const c=()=>{switch(s){case"architecture":return l("svg",{width:"11",height:"11",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"24",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"24",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"24",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"18",y:"6",width:"3",height:"3",transform:"rotate(90 18 6)",fill:"#080096"}),t("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#080096"}),t("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(90 3 6)",fill:"#080096"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(90 3 24)",fill:"#080096"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(90 21 6)",fill:"#080096"}),t("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#080096"}),t("rect",{x:"6",y:"6",width:"3",height:"3",transform:"rotate(90 6 6)",fill:"#080096"}),t("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#080096"}),t("rect",{x:"24",y:"6",width:"3",height:"3",transform:"rotate(90 24 6)",fill:"#080096"}),t("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#080096"}),t("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#080096"}),t("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#080096"}),t("rect",{x:"27",y:"6",width:"3",height:"3",transform:"rotate(90 27 6)",fill:"#080096"}),t("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(90 27 24)",fill:"#080096"}),t("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#080096"}),t("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#080096"}),t("rect",{x:"19",y:"3",width:"3",height:"3",transform:"rotate(90 19 3)",fill:"#080096"}),t("rect",{x:"11",y:"3",width:"3",height:"3",transform:"rotate(90 11 3)",fill:"#080096"})]});case"testing":return l("svg",{width:"11",height:"11",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"24",y:"24",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"21",y:"21",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"18",y:"18",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"15",y:"15",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"12",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"9",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"21",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"18",y:"12",width:"3",height:"3",transform:"rotate(90 18 12)",fill:"#15803d"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#15803d"}),t("rect",{x:"21",y:"12",width:"3",height:"3",transform:"rotate(90 21 12)",fill:"#15803d"}),t("rect",{x:"6",y:"12",width:"3",height:"3",transform:"rotate(90 6 12)",fill:"#15803d"}),t("rect",{x:"24",y:"12",width:"3",height:"3",transform:"rotate(90 24 12)",fill:"#15803d"}),t("rect",{x:"9",y:"12",width:"3",height:"3",transform:"rotate(90 9 12)",fill:"#15803d"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#15803d"}),t("rect",{x:"12",y:"12",width:"3",height:"3",transform:"rotate(90 12 12)",fill:"#15803d"}),t("rect",{x:"12",y:"15",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"9",y:"9",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"6",y:"6",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"3",y:"3",width:"3",height:"3",fill:"#15803d"}),t("rect",{width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(90 3 24)",fill:"#15803d"}),t("rect",{x:"6",y:"21",width:"3",height:"3",transform:"rotate(90 6 21)",fill:"#15803d"}),t("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#15803d"}),t("rect",{x:"12",y:"15",width:"3",height:"3",transform:"rotate(90 12 15)",fill:"#15803d"}),t("rect",{x:"18",y:"9",width:"3",height:"3",transform:"rotate(90 18 9)",fill:"#15803d"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(90 21 6)",fill:"#15803d"}),t("rect",{x:"24",y:"3",width:"3",height:"3",transform:"rotate(90 24 3)",fill:"#15803d"}),t("rect",{x:"27",width:"3",height:"3",transform:"rotate(90 27 0)",fill:"#15803d"})]});case"faq":return l("svg",{width:"8",height:"11",viewBox:"0 0 18 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"6",y:"24",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"3",width:"3",height:"3",transform:"rotate(-90 12 3)",fill:"#080096"}),t("rect",{x:"15",y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(-90 9 3)",fill:"#080096"}),t("rect",{y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"3",width:"3",height:"3",transform:"rotate(-90 6 3)",fill:"#080096"}),t("rect",{x:"3",y:"3",width:"3",height:"3",transform:"rotate(-90 3 3)",fill:"#080096"})]});default:return l("svg",{width:"8",height:"11",viewBox:"0 0 18 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"6",y:"24",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"3",width:"3",height:"3",transform:"rotate(-90 12 3)",fill:"#080096"}),t("rect",{x:"15",y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(-90 9 3)",fill:"#080096"}),t("rect",{y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"3",width:"3",height:"3",transform:"rotate(-90 6 3)",fill:"#080096"}),t("rect",{x:"3",y:"3",width:"3",height:"3",transform:"rotate(-90 3 3)",fill:"#080096"})]})}},d=()=>{switch(s){case"architecture":return"";case"testing":return"bg-green-100";case"faq":return"";default:return""}},m=()=>s==="faq"?{backgroundColor:"#D4D4FF"}:s==="architecture"?{backgroundColor:"#DBE9FF"}:{},u=()=>s==="faq"?{backgroundColor:"#E7E7FC"}:s==="architecture"?{backgroundColor:"#DBE9FF"}:{},p=xn(e.body.length);return l("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden",children:[t("div",{className:"p-4 cursor-pointer hover:bg-gray-50",onClick:()=>o(!a),children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex items-center gap-3",children:[t("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:a?"rotate(90deg)":"none",transition:"transform 0.2s"},children:t("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:a?"#3e3e3e":"#c7c7c7"})})}),t("div",{className:`w-10 h-10 rounded-lg ${d()} flex items-center justify-center flex-shrink-0`,style:m(),children:c()}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t("h3",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:"#000"},children:i}),t("span",{className:`px-2 py-0.5 rounded font-medium uppercase tracking-wider ${vs[s]}`,style:{fontSize:"10px",...u()},children:Gn[s]}),l("span",{className:"text-xs text-gray-400",children:["~",p.toLocaleString()," tokens"]})]}),t("div",{className:"flex items-center gap-2 text-xs text-gray-500 flex-wrap",children:e.frontmatter.paths&&e.frontmatter.paths.length>0&&l(le,{children:[e.frontmatter.paths.slice(0,4).map((h,f)=>t("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-500 rounded font-mono",children:h},f)),e.frontmatter.paths.length>4&&l("span",{className:"text-gray-400 whitespace-nowrap",children:["+",e.frontmatter.paths.length-4," more"]})]})})]})]}),t("div",{className:"flex items-center gap-2 flex-shrink-0",children:e.frontmatter.timestamp&&l("span",{className:"text-xs text-gray-400",children:["Updated"," ",new Date(e.frontmatter.timestamp).toLocaleDateString()]})})]})}),a&&t("div",{className:"border-t border-gray-100",children:l("div",{className:"p-4 bg-gray-50",children:[t("div",{className:"bg-white p-4 rounded border border-gray-200 max-h-[500px] overflow-auto",children:t(xo,{remarkPlugins:[bo],components:{h1:({children:h})=>t("h1",{className:"text-lg font-bold text-gray-900 mb-3 mt-6 first:mt-0 pb-1 border-b border-gray-200",children:h}),h2:({children:h})=>t("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:h}),h3:({children:h})=>t("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:h}),p:({children:h})=>t("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:h}),ul:({children:h})=>t("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:h}),ol:({children:h})=>t("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:h}),li:({children:h})=>t("li",{className:"leading-relaxed",children:h}),code:({children:h,className:f})=>(f==null?void 0:f.includes("language-"))?t("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:t("code",{children:h})}):t("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:h}),pre:({children:h})=>t(le,{children:h}),strong:({children:h})=>t("strong",{className:"font-semibold text-gray-900",children:h}),blockquote:({children:h})=>t("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:h}),table:({children:h})=>t("div",{className:"overflow-x-auto mb-3",children:t("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:h})}),thead:({children:h})=>t("thead",{className:"bg-gray-50",children:h}),th:({children:h})=>t("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:h}),td:({children:h})=>t("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:h}),a:({children:h,href:f})=>t("a",{href:f,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:h})},children:e.body.trim().replace(/^#+ .+$/m,"").trim()})}),l("div",{className:"flex justify-end gap-2 mt-3",children:[l("button",{onClick:h=>{h.stopPropagation(),r(e)},className:"flex items-center gap-1 px-3 py-1.5 text-sm text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded cursor-pointer",children:[t(ho,{className:"w-4 h-4"}),"Edit"]}),l("button",{onClick:h=>{h.stopPropagation(),n(e)},className:"flex items-center gap-1 px-3 py-1.5 text-sm text-red-600 hover:text-red-700 hover:bg-red-50 rounded cursor-pointer",children:[t(bi,{className:"w-4 h-4"}),"Delete"]})]})]})})]})}function no({rule:e,onSave:r,onCancel:n}){const[a,o]=M((e==null?void 0:e.filePath)||""),[s,i]=M((e==null?void 0:e.content)||m()),[c,d]=M(!!e);function m(){return`---
|
|
245
|
-
paths:
|
|
246
|
-
- '**/*.ts'
|
|
247
|
-
category: faq
|
|
248
|
-
timestamp: ${new Date().toISOString().split(".")[0]+"Z"}
|
|
249
|
-
---
|
|
250
|
-
|
|
251
|
-
## Title
|
|
252
|
-
|
|
253
|
-
Description here.
|
|
254
|
-
|
|
255
|
-
**Learned:** ${new Date().toISOString().split("T")[0]} from [context]
|
|
256
|
-
`}const u=!e;return l("div",{className:"p-6",children:[l("div",{className:"flex items-center justify-between mb-4",children:[t("h3",{className:"text-lg font-semibold",style:{fontFamily:"Sora"},children:e?"Edit Rule":"Create New Rule"}),t("button",{onClick:n,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:t(co,{className:"w-5 h-5"})})]}),u&&l("div",{className:"mb-6",children:[t("div",{className:"bg-[#f0f9ff] border border-[#bae6fd] rounded-lg p-4 mb-4",children:l("div",{className:"flex items-start gap-3",children:[t(uo,{className:"w-5 h-5 text-[#0284c7] mt-0.5 flex-shrink-0"}),l("div",{children:[t("h4",{className:"font-medium text-[#0c4a6e] mb-1",children:"Recommended: Use Claude Code"}),t("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:"}),t("code",{className:"block bg-white px-3 py-2 rounded border border-[#bae6fd] font-mono text-sm text-[#0c4a6e]",children:"/codeyam:new-rule"})]})]})}),l("button",{onClick:()=>d(!c),className:"flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 cursor-pointer",children:[t("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:c?"rotate(90deg)":"none",transition:"transform 0.2s"},children:t("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:c?"#3e3e3e":"#c7c7c7"})})}),"Or create manually"]})]}),(c||!u)&&l("div",{className:"space-y-4",children:[l("div",{children:[t("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"File Path (relative to .claude/rules/)"}),l("div",{className:"relative",children:[t("input",{type:"text",value:a,onChange:p=>o(p.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}),t("button",{onClick:()=>{navigator.clipboard.writeText(a)},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:t(vn,{className:"w-4 h-4"})})]})]}),l("div",{children:[t("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Content"}),t("textarea",{value:s,onChange:p=>i(p.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"})]}),l("div",{className:"flex justify-end gap-2",children:[t("button",{onClick:n,className:"px-4 py-2 text-[#001f3f] hover:text-[#001530] rounded-md cursor-pointer font-mono uppercase text-xs font-semibold",children:"Cancel"}),t("button",{onClick:()=>r(a,s),disabled:!a.trim()||!s.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 Yp({memories:e,selectedPath:r,onSelectPath:n,expandedFolders:a,onToggleFolder:o}){const s=ne(()=>{const u={name:"root",path:"",memories:[],children:new Map};for(const p of e){const h=p.filePath.split("/");h.pop();let f=u,y="";for(const g of h)y=y?`${y}/${g}`:g,f.children.has(g)||f.children.set(g,{name:g,path:y,memories:[],children:new Map}),f=f.children.get(g);h.length===0?u.memories.push(p):f.memories.push(p)}return u},[e]),i=u=>{let p=u.memories.length;for(const h of u.children.values())p+=i(h);return p},c=(u,p,h)=>{if(u.target.closest(".chevron-toggle")){h&&o(p||"root");return}const y=p||null;n(r===y?null:y),h&&!a.has(p||"root")&&o(p||"root")},d=u=>{n(r===u?null:u)},m=(u,p=0)=>{const h=a.has(u.path||"root"),f=i(u),y=u.children.size>0,g=u.name==="root"?"(root)":u.name,w=u.memories.length>0||y,x=u.path||"",b=r===x||r===null&&x==="";return l("div",{children:[l("div",{className:`flex items-center gap-2 py-2.5 cursor-pointer rounded px-2 relative ${b?"bg-[#E0E9EC]":"hover:bg-gray-100"}`,style:{paddingLeft:`${p*12+8}px`},onClick:v=>c(v,u.path,w),children:[w&&t("span",{className:"chevron-toggle p-0.5 -m-0.5 hover:bg-gray-200 rounded",onClick:v=>{v.stopPropagation(),o(u.path||"root")},children:t(Nn,{className:`w-3 h-3 text-gray-500 transition-transform ${h?"rotate-90":""}`})}),!w&&t("div",{className:"w-3"}),t(mo,{className:"w-3.5 h-3.5 text-[#005C75]"}),t("span",{className:`text-xs font-mono font-semibold ${b?"text-[#005C75]":""}`,style:{color:"#005C75"},children:g}),l("span",{className:"text-xs ml-auto",style:{color:"#005C75"},children:[f," rules"]})]}),h&&l("div",{className:"relative",children:[(u.memories.length>0||y)&&t("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:`${p*12+8+6}px`}}),u.memories.length>0&&t("div",{style:{paddingLeft:`${(p+1)*12+8}px`},children:u.memories.map(v=>{var E;const C=r===v.filePath;return t("div",{className:`flex items-center gap-2 py-1 px-2 text-sm rounded cursor-pointer relative ${C?"bg-[#E0E9EC] text-[#005C75]":"text-gray-600 hover:bg-gray-50"}`,onClick:()=>d(v.filePath),children:t("span",{className:"text-xs",children:(E=v.filePath.split("/").pop())==null?void 0:E.replace(".md","")})},v.filePath)})}),y&&t("div",{children:Array.from(u.children.values()).sort((v,C)=>v.name.localeCompare(C.name)).map(v=>m(v,p+1))})]})]},u.path||"root")};return t("div",{className:"bg-white rounded-lg border border-gray-200 p-4 mb-8",children:m(s)})}function Bp({memories:e,onEdit:r,onDelete:n,expandedFolders:a,onToggleFolder:o}){const s=ne(()=>{const c={name:"root",path:"",memories:[],children:new Map};for(const d of e){const m=d.filePath.split("/");m.pop();let u=c,p="";for(const h of m)p=p?`${p}/${h}`:h,u.children.has(h)||u.children.set(h,{name:h,path:p,memories:[],children:new Map}),u=u.children.get(h);m.length===0?c.memories.push(d):u.memories.push(d)}return c},[e]),i=(c,d=0)=>{const m=a.has(c.path||"root"),u=c.children.size>0,p=c.name==="root"?"root":c.name,h=c.memories.length>0||u;return l("div",{children:[l("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:()=>h&&o(c.path||"root"),children:[h&&t(Nn,{className:`w-4 h-4 text-gray-500 transition-transform ${m?"rotate-90":""}`}),!h&&t("div",{className:"w-4"}),t(mo,{className:"w-4 h-4 text-[#005C75]"}),t("span",{className:"text-sm font-mono font-semibold",style:{color:"#001f3f"},children:p})]}),m&&l("div",{className:"ml-10 space-y-4 relative",children:[(c.memories.length>0||u)&&t("div",{className:"absolute top-0 bottom-0 w-px bg-gray-300",style:{left:"-24px"}}),c.memories.length>0&&t("div",{className:"space-y-2",children:c.memories.map(f=>t(Cs,{rule:f,onEdit:r,onDelete:n},f.filePath))}),u&&t("div",{className:"space-y-4",children:Array.from(c.children.values()).sort((f,y)=>f.name.localeCompare(y.name)).map(f=>i(f,d+1))})]})]},c.path||"root")};return t("div",{children:i(s)})}function Up({changes:e,memories:r,onEditRule:n}){const[a,o]=M(!1),[s,i]=M(new Set),[c,d]=M(new Set),m=ne(()=>{const x=new Map;for(const b of e){const v=b.commitHash==="uncommitted";for(const C of b.files){if(x.has(C.filePath))continue;const E=r.find(N=>N.filePath===C.filePath);E&&x.set(C.filePath,{rule:E,changeType:C.changeType,date:b.date,isUncommitted:v,diff:C.diff})}}return Array.from(x.values()).sort((b,v)=>b.isUncommitted&&!v.isUncommitted?-1:!b.isUncommitted&&v.isUncommitted?1:new Date(v.date).getTime()-new Date(b.date).getTime())},[e,r]),u=ne(()=>m.some(x=>x.isUncommitted),[m]),p=ne(()=>{const x=new Date;return x.setDate(x.getDate()-5),x},[]),h=ne(()=>m.some(x=>new Date(x.date)>=p),[m,p]),f=ne(()=>a?m:!h&&!u?[]:m.slice(0,3),[m,a,h,u]),y=x=>{i(b=>{const v=new Set(b);return v.has(x)?v.delete(x):v.add(x),v})},g=x=>{d(b=>{const v=new Set(b);return v.has(x)?v.delete(x):v.add(x),v})},w=x=>{const b=new Date(x),C=new Date().getTime()-b.getTime(),E=Math.floor(C/(1e3*60*60*24));return E===0?"Today":E===1?"Yesterday":E<7?`${E} days ago`:b.toLocaleDateString()};return m.length===0?null:!h&&!u&&!a?t("div",{className:"mb-8",children:l("button",{onClick:()=>o(!0),className:"flex items-center gap-2 text-xs text-gray-500 hover:text-gray-700 cursor-pointer font-mono uppercase font-semibold",children:["View ",m.length," older change",m.length!==1?"s":""]})}):l("div",{className:"mb-8",children:[l("div",{className:"flex items-center justify-between mb-4",children:[t("h2",{className:"text-base font-semibold text-gray-900",style:{fontFamily:"Sora"},children:"Recently Changed Rules"}),m.length>3&&t("button",{onClick:()=>o(!a),className:"text-xs text-[#005C75] hover:underline flex items-center gap-1 cursor-pointer font-mono uppercase font-semibold",children:a?t(le,{children:"Show Less"}):l(le,{children:["View All (",m.length,")"]})})]}),t("div",{className:"space-y-2",children:f.map(x=>{const{rule:b,changeType:v,date:C,isUncommitted:E,diff:N}=x,A=b.frontmatter.category||"faq",_=s.has(b.filePath),$=(()=>{var B;const P=b.body.match(/^#+ (.+)$/m);return P?P[1]:(B=b.filePath.split("/").pop())==null?void 0:B.replace(".md","")})(),D=()=>{switch(A){case"architecture":return l("svg",{width:"11",height:"11",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"24",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"24",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"24",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"18",y:"6",width:"3",height:"3",transform:"rotate(90 18 6)",fill:"#080096"}),t("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#080096"}),t("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(90 3 6)",fill:"#080096"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(90 3 24)",fill:"#080096"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(90 21 6)",fill:"#080096"}),t("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#080096"}),t("rect",{x:"6",y:"6",width:"3",height:"3",transform:"rotate(90 6 6)",fill:"#080096"}),t("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#080096"}),t("rect",{x:"24",y:"6",width:"3",height:"3",transform:"rotate(90 24 6)",fill:"#080096"}),t("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#080096"}),t("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#080096"}),t("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#080096"}),t("rect",{x:"27",y:"6",width:"3",height:"3",transform:"rotate(90 27 6)",fill:"#080096"}),t("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(90 27 24)",fill:"#080096"}),t("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#080096"}),t("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#080096"}),t("rect",{x:"19",y:"3",width:"3",height:"3",transform:"rotate(90 19 3)",fill:"#080096"}),t("rect",{x:"11",y:"3",width:"3",height:"3",transform:"rotate(90 11 3)",fill:"#080096"})]});case"testing":return l("svg",{width:"11",height:"11",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"24",y:"24",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"21",y:"21",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"18",y:"18",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"15",y:"15",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"12",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"9",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"21",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"18",y:"12",width:"3",height:"3",transform:"rotate(90 18 12)",fill:"#15803d"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#15803d"}),t("rect",{x:"21",y:"12",width:"3",height:"3",transform:"rotate(90 21 12)",fill:"#15803d"}),t("rect",{x:"6",y:"12",width:"3",height:"3",transform:"rotate(90 6 12)",fill:"#15803d"}),t("rect",{x:"24",y:"12",width:"3",height:"3",transform:"rotate(90 24 12)",fill:"#15803d"}),t("rect",{x:"9",y:"12",width:"3",height:"3",transform:"rotate(90 9 12)",fill:"#15803d"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#15803d"}),t("rect",{x:"12",y:"12",width:"3",height:"3",transform:"rotate(90 12 12)",fill:"#15803d"}),t("rect",{x:"12",y:"15",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"9",y:"9",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"6",y:"6",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"3",y:"3",width:"3",height:"3",fill:"#15803d"}),t("rect",{width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(90 3 24)",fill:"#15803d"}),t("rect",{x:"6",y:"21",width:"3",height:"3",transform:"rotate(90 6 21)",fill:"#15803d"}),t("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#15803d"}),t("rect",{x:"12",y:"15",width:"3",height:"3",transform:"rotate(90 12 15)",fill:"#15803d"}),t("rect",{x:"18",y:"9",width:"3",height:"3",transform:"rotate(90 18 9)",fill:"#15803d"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(90 21 6)",fill:"#15803d"}),t("rect",{x:"24",y:"3",width:"3",height:"3",transform:"rotate(90 24 3)",fill:"#15803d"}),t("rect",{x:"27",width:"3",height:"3",transform:"rotate(90 27 0)",fill:"#15803d"})]});case"faq":return l("svg",{width:"8",height:"11",viewBox:"0 0 18 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"6",y:"24",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"3",width:"3",height:"3",transform:"rotate(-90 12 3)",fill:"#080096"}),t("rect",{x:"15",y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(-90 9 3)",fill:"#080096"}),t("rect",{y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"3",width:"3",height:"3",transform:"rotate(-90 6 3)",fill:"#080096"}),t("rect",{x:"3",y:"3",width:"3",height:"3",transform:"rotate(-90 3 3)",fill:"#080096"})]});default:return l("svg",{width:"8",height:"11",viewBox:"0 0 18 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"6",y:"24",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"3",width:"3",height:"3",transform:"rotate(-90 12 3)",fill:"#080096"}),t("rect",{x:"15",y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(-90 9 3)",fill:"#080096"}),t("rect",{y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"3",width:"3",height:"3",transform:"rotate(-90 6 3)",fill:"#080096"}),t("rect",{x:"3",y:"3",width:"3",height:"3",transform:"rotate(-90 3 3)",fill:"#080096"})]})}},I=()=>{switch(A){case"architecture":return"";case"testing":return"bg-green-100";case"faq":return"";default:return""}},k=()=>A==="faq"?{backgroundColor:"#D4D4FF"}:A==="architecture"?{backgroundColor:"#DBE9FF"}:{},T=()=>A==="faq"?{backgroundColor:"#E7E7FC"}:A==="architecture"?{backgroundColor:"#DBE9FF"}:{};return l("div",{className:`rounded-lg border overflow-hidden ${E?"bg-amber-50 border-amber-300":"bg-white border-gray-200"}`,style:{borderLeft:`2px solid ${(()=>{switch(A){case"architecture":return"#3B82F6";case"testing":return"#10B981";case"faq":return"#080096";default:return"#080096"}})()}`},children:[t("div",{className:`p-4 cursor-pointer ${E?"hover:bg-amber-100":"hover:bg-gray-50"}`,onClick:()=>y(b.filePath),children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex items-center gap-3",children:[t("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:_?"rotate(90deg)":"none",transition:"transform 0.2s"},children:t("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:_?"#3e3e3e":E?"#d97706":"#c7c7c7"})})}),t("div",{className:`w-10 h-10 rounded-lg ${I()} flex items-center justify-center flex-shrink-0`,style:k(),children:D()}),l("div",{className:"flex-1",children:[l("div",{className:"flex items-center gap-2 mb-1",children:[t("p",{style:{fontSize:"14px",lineHeight:"18px",fontWeight:500,color:E?"#78350f":"#000"},children:$}),t("span",{className:`px-2 py-0.5 rounded font-medium uppercase tracking-wider ${vs[A]}`,style:{fontSize:"10px",...T()},children:Gn[A]}),t("span",{className:`px-2 py-0.5 rounded uppercase font-medium tracking-wider ${v==="deleted"?"bg-red-100 text-red-700":""}`,style:{fontSize:"10px",...v==="added"&&{backgroundColor:"#CBF3FA",color:"#005C75"},...v==="modified"&&{backgroundColor:"#FFE8C1",color:"#C67E06"}},children:v}),E&&t("span",{className:"px-2 py-0.5 bg-amber-200 text-amber-800 rounded font-medium uppercase tracking-wider",style:{fontSize:"10px"},children:"Uncommitted"})]}),t("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:t("span",{className:"font-mono",children:b.filePath})})]})]}),t("div",{className:"flex items-center gap-2 flex-shrink-0",children:t("span",{className:"text-xs text-gray-400",children:w(C)})})]})}),_&&l("div",{className:`border-t ${E?"border-amber-200":"border-gray-100"}`,children:[l("div",{className:`px-4 py-3 flex items-center justify-between ${E?"bg-amber-50":"bg-white"}`,children:[t("div",{className:"flex items-center gap-2",children:v==="modified"&&N&&l("button",{onClick:P=>{P.stopPropagation(),g(b.filePath)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${c.has(b.filePath)?E?"bg-amber-200 text-amber-900":"bg-gray-200 text-gray-900":E?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[t(uo,{className:"w-3 h-3"}),c.has(b.filePath)?"Hide Diff":"Show Diff"]})}),v!=="deleted"&&l("button",{onClick:P=>{P.stopPropagation(),n(b)},className:`flex items-center gap-1 px-2 py-1 text-sm rounded cursor-pointer ${E?"text-amber-700 hover:text-amber-900 hover:bg-amber-100":"text-gray-600 hover:text-gray-900 hover:bg-gray-100"}`,children:[t(ho,{className:"w-3 h-3"}),"Edit"]})]}),c.has(b.filePath)&&N&&t("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:N.split(`
|
|
257
|
-
`).map((P,B)=>{let L="";return P.startsWith("+")&&!P.startsWith("+++")?L="text-green-400":P.startsWith("-")&&!P.startsWith("---")?L="text-red-400":P.startsWith("@@")&&(L="text-cyan-400"),t("div",{className:L,children:P},B)})}),!c.has(b.filePath)&&t("div",{className:"mx-4 mb-4 p-4 rounded border max-h-[400px] overflow-auto bg-white border-gray-200",children:t(xo,{remarkPlugins:[bo],components:{h1:({children:P})=>t("h1",{className:"text-lg font-bold text-gray-900 mb-3 mt-6 first:mt-0 pb-1 border-b border-gray-200",children:P}),h2:({children:P})=>t("h2",{className:"text-base font-semibold text-gray-900 mb-2 mt-5 first:mt-0",children:P}),h3:({children:P})=>t("h3",{className:"text-sm font-semibold text-gray-800 mb-2 mt-4 first:mt-0",children:P}),p:({children:P})=>t("p",{className:"text-sm text-gray-700 mb-3 leading-relaxed",children:P}),ul:({children:P})=>t("ul",{className:"list-disc ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:P}),ol:({children:P})=>t("ol",{className:"list-decimal ml-5 text-sm text-gray-700 mb-3 space-y-1.5",children:P}),li:({children:P})=>t("li",{className:"leading-relaxed",children:P}),code:({children:P,className:B})=>(B==null?void 0:B.includes("language-"))?t("pre",{className:"bg-gray-100 rounded p-3 text-xs font-mono overflow-x-auto mb-3",children:t("code",{children:P})}):t("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs font-mono text-gray-800",children:P}),pre:({children:P})=>t(le,{children:P}),strong:({children:P})=>t("strong",{className:"font-semibold text-gray-900",children:P}),blockquote:({children:P})=>t("blockquote",{className:"border-l-4 border-gray-300 pl-4 italic text-gray-600 mb-3",children:P}),table:({children:P})=>t("div",{className:"overflow-x-auto mb-3",children:t("table",{className:"min-w-full text-sm border-collapse border border-gray-200",children:P})}),thead:({children:P})=>t("thead",{className:"bg-gray-50",children:P}),th:({children:P})=>t("th",{className:"border border-gray-200 px-3 py-2 text-left font-semibold text-gray-900",children:P}),td:({children:P})=>t("td",{className:"border border-gray-200 px-3 py-2 text-gray-700",children:P}),a:({children:P,href:B})=>t("a",{href:B,className:"text-[#005C75] hover:underline",target:"_blank",rel:"noopener noreferrer",children:P})},children:b.body.trim().replace(/^#+ .+$/m,"").trim()})})]})]},b.filePath)})})]})}function Wp({onEditRule:e,onDeleteRule:r,refreshKey:n}){const[a,o]=M(""),[s,i]=M(null),[c,d]=M(!1),[m,u]=M(null),[p,h]=M(0),[f,y]=M(!1),[g,w]=M({topPaths:[],totalFilesWithCoverage:0}),[x,b]=M([]),[v,C]=M(!0);re(()=>{(async()=>{C(!0);try{const[k,T]=await Promise.all([fetch("/api/memory?action=audit"),fetch("/api/memory?action=source-files")]),j=await k.json(),P=await T.json();w({topPaths:j.topPaths||[],totalFilesWithCoverage:j.totalFilesWithCoverage||0}),b(P.files||[])}catch(k){console.error("Failed to load audit data:",k)}finally{C(!1)}})()},[n]),re(()=>{s&&n>0&&(async()=>{y(!0);try{const T=await(await fetch(`/api/memory?action=rules-for-path&path=${encodeURIComponent(s)}`)).json();u(T.rules||[]),h(T.totalTextLength||0)}catch{u([]),h(0)}finally{y(!1)}})()},[n,s]);const E=ne(()=>{if(!a.trim())return[];const I=a.toLowerCase();return x.filter(k=>k.toLowerCase().includes(I)).slice(0,10)},[a,x]),N=async I=>{y(!0);try{const T=await(await fetch(`/api/memory?action=rules-for-path&path=${encodeURIComponent(I)}`)).json();u(T.rules||[]),h(T.totalTextLength||0)}catch{u([]),h(0)}finally{y(!1)}},A=I=>{i(I),o(I),d(!1),N(I)},_=()=>{i(null),o(""),u(null),h(0)};return l("div",{className:"mb-6",children:[l("div",{className:"flex items-center justify-between gap-4 mb-1",children:[t("h2",{className:"text-base font-semibold text-gray-900 flex-shrink-0",style:{fontFamily:"Sora"},children:"Rules Audit"}),l("div",{className:"relative flex-1 max-w-md",children:[t(Cn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),t("input",{type:"text",value:a,onChange:I=>{const k=I.target.value;o(k),d(k.length>0),s&&k!==s&&(i(null),u(null))},onFocus:()=>d(a.length>0),onKeyDown:I=>{I.key==="Enter"&&E.length>0&&A(E[0])},placeholder:"Search for a file path...",className:"w-full pl-10 pr-10 py-2 border border-gray-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-[#005C75] focus:border-transparent font-mono text-xs"}),s&&t("button",{onClick:_,className:"absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 cursor-pointer",children:t(co,{className:"w-4 h-4"})}),c&&E.length>0&&!s&&t("div",{className:"absolute z-10 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto",children:E.map((I,k)=>l("button",{onClick:()=>A(I),className:"w-full px-4 py-2 text-left text-sm font-mono hover:bg-gray-100 flex items-center gap-2 cursor-pointer",children:[t(lo,{className:"w-4 h-4 text-gray-400 flex-shrink-0"}),t("span",{className:"truncate",children:I})]},k))})]})]}),t("p",{className:"text-sm text-gray-500 mb-4",children:"View all rules that apply to any folder or file in this repo (displaying the files that have the most rules — by total token count — applied to them)"}),f&&t("div",{className:"bg-white rounded-lg border border-gray-200 p-6 text-center",children:t("div",{className:"text-gray-500",children:"Loading rules..."})}),s&&m!==null&&!f&&l("div",{children:[t("div",{className:"text-sm text-gray-600 mb-3",style:{fontFamily:"Sora"},children:"Showing rules for:"}),l("div",{className:"flex items-stretch gap-3 mb-4",children:[t("button",{onClick:_,className:"flex-shrink-0 px-3 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors flex items-center justify-center","aria-label":"Back to all files",children:t(xi,{className:"w-5 h-5 text-gray-600"})}),l("div",{className:"flex-1 bg-white rounded-lg border p-4",style:{borderColor:"#CBF3FA"},children:[l("div",{className:"flex items-center gap-3 mb-2",children:[t("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),t("div",{className:"font-mono text-sm font-semibold text-gray-900 break-all",children:s})]}),l("div",{className:"flex items-center gap-2",children:[l("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-700 rounded uppercase font-medium tracking-wider",style:{fontSize:"10px"},children:[m.length," RULE",m.length!==1?"S":""]}),l("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-700 rounded uppercase font-medium tracking-wider",style:{fontSize:"10px"},children:[xn(p).toLocaleString()," TOKENS"]})]})]})]}),m.length===0?t("div",{className:"bg-white rounded-lg border border-gray-200 p-6 text-center text-gray-500 text-sm",children:"No rules match this path"}):t("div",{className:"space-y-3",children:m.map(I=>t(Cs,{rule:I,onEdit:e,onDelete:r},I.filePath))})]}),!s&&!f&&!v&&g.topPaths.length>0&&l("div",{className:"bg-white rounded-lg border border-gray-200 overflow-hidden",children:[l("div",{className:"px-4 py-3 bg-gray-50 border-b border-gray-200",children:[t("div",{className:"font-medium text-gray-900 text-sm",children:"File paths that consume the most rules (by total tokens)"}),l("div",{className:"text-xs text-gray-500 mt-1",children:[g.totalFilesWithCoverage," file",g.totalFilesWithCoverage!==1?"s":""," with rule coverage"]})]}),t("div",{className:"divide-y divide-gray-100",children:g.topPaths.slice(0,3).map((I,k)=>t("button",{onClick:()=>A(I.filePath),className:"w-full px-4 py-3 text-left hover:bg-gray-50 cursor-pointer",children:l("div",{className:"flex items-start justify-between",children:[l("div",{className:"flex items-center gap-2",children:[l("span",{className:"text-gray-400 font-medium w-5 text-sm",children:[k+1,"."]}),t("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),l("div",{children:[t("div",{className:"font-mono text-xs text-gray-900",children:I.filePath}),l("div",{className:"flex gap-2 mt-1",children:[l("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-700 text-[11px] rounded uppercase font-medium",children:[I.matchingRules.length," rule",I.matchingRules.length!==1?"s":""]}),l("span",{className:"px-2 py-0.5 bg-gray-100 text-gray-700 text-[11px] rounded uppercase font-medium",children:["~",xn(I.totalTextLength).toLocaleString()," ","tokens"]})]})]})]}),t(Nn,{className:"w-4 h-4 text-gray-400 mt-1"})]})},k))})]}),!s&&v&&t("div",{className:"bg-white rounded-lg border border-gray-200 p-6",children:l("div",{className:"animate-pulse space-y-3",children:[t("div",{className:"h-4 bg-gray-200 rounded w-3/4"}),t("div",{className:"h-3 bg-gray-100 rounded w-1/2"}),t("div",{className:"h-4 bg-gray-200 rounded w-2/3 mt-4"}),t("div",{className:"h-3 bg-gray-100 rounded w-1/3"})]})}),!s&&!f&&!v&&g.topPaths.length===0&&t("div",{className:"bg-white rounded-lg border border-gray-200 p-6 text-center text-gray-500 text-sm",children:"No files have rule coverage yet"})]})}const Hp=Oe(function(){const{memories:r,recentChanges:n,error:a}=We(),o=Ae(),s=rt(),[i,c]=M(null),[d,m]=M(""),[u,p]=M(null),[h,f]=M(new Set(["root"])),[y,g]=M(null),[w,x]=M(!1),[b,v]=M(null),[C,E]=M(0),N=P=>{f(B=>{const L=new Set(B);return L.has(P)?L.delete(P):L.add(P),L})};mt({source:"memory-page"}),re(()=>{o.state==="idle"&&o.data&&(s.revalidate(),g(null),x(!1),E(P=>P+1))},[o.state,o.data,s]);const A=ne(()=>{let P=r;if(i&&(P=P.filter(B=>(B.frontmatter.category||"faq")===i)),d.trim()){const B=d.toLowerCase();P=P.filter(L=>{var O;return(((O=L.filePath.split("/").pop())==null?void 0:O.replace(".md",""))||"").toLowerCase().includes(B)||L.body.toLowerCase().includes(B)})}return P},[r,i,d]),_=ne(()=>u?A.some(B=>B.filePath===u)?A.filter(B=>B.filePath===u):A.filter(B=>B.filePath.startsWith(u+"/")||B.filePath===u):A,[A,u]);ne(()=>{const P={};for(const B of A){const L=B.filePath.includes("/")?B.filePath.split("/").slice(0,-1).join("/"):"(root)";P[L]||(P[L]=[]),P[L].push(B)}return Object.entries(P).sort(([B],[L])=>B.localeCompare(L))},[A]);const $=(P,B)=>{const L=y?"update":"create";o.submit({action:L,filePath:P,content:B},{method:"POST",action:"/api/memory",encType:"application/json"})},D=P=>{o.submit({action:"delete",filePath:P.filePath},{method:"POST",action:"/api/memory",encType:"application/json"}),v(null)},I=ne(()=>{const P={architecture:0,testing:0,faq:0};for(const B of r){const L=B.frontmatter.category||"faq";P[L]++}return P},[r]),k=ne(()=>{const P=new Set(["root"]);for(const B of A){const L=B.filePath.split("/");L.pop();let z="";for(const O of L)z=z?`${z}/${O}`:O,P.add(z)}return P},[A]),T=k.size===h.size&&[...k].every(P=>h.has(P)),j=()=>{f(T?new Set(["root"]):new Set(k))};return a?t("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),t("p",{className:"text-base text-gray-500",children:a})]})}):t("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[l("div",{className:"flex items-center justify-between mb-6",children:[l("div",{children:[l("div",{className:"flex items-center gap-3 mb-2",children:[l("svg",{width:"24",height:"24",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#232323"}),t("rect",{x:"12",width:"3",height:"3",fill:"#232323"}),t("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#232323"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#232323"}),t("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#232323"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#232323"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#232323"}),t("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#232323"}),t("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#232323"}),t("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#232323"}),t("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#232323"}),t("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#232323"}),t("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#232323"}),t("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#232323"}),t("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#232323"}),t("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#232323"}),t("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#232323"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#232323"}),t("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#232323"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#232323"}),t("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#232323"}),t("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#232323"}),t("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#232323"}),t("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#232323"}),t("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#232323"}),t("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#232323"}),t("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#232323"}),t("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#232323"}),t("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#232323"}),t("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#232323"}),t("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#232323"}),t("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#232323"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#232323"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#232323"})]}),t("h1",{className:"text-[24px] font-semibold mb-0",style:{fontFamily:"Sora",color:"#232323"},children:"Memory"})]}),t("p",{className:"text-[15px] text-gray-500",children:"Documentation that helps Claude understand your codebase patterns and conventions."})]}),l("button",{onClick:()=>x(!0),className:"flex items-center gap-2 px-4 py-2 bg-[#005C75] text-white rounded-md hover:bg-[#004a5e] cursor-pointer font-mono uppercase text-xs font-semibold",children:[t(Sa,{className:"w-4 h-4"}),"New Rule"]})]}),l("div",{className:"grid grid-cols-4 gap-4",children:[t("div",{className:`rounded-lg p-4 cursor-pointer hover:opacity-80 transition-opacity ${i===null?"ring-1 ring-[#005C75]":""}`,style:{backgroundColor:"#EDF1F3",border:"1px solid #EFEFEF"},onClick:()=>c(null),children:l("div",{className:"flex items-start gap-3",children:[t("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:"#E0E9EC"},children:l("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#005C75"}),t("rect",{x:"12",width:"3",height:"3",fill:"#005C75"}),t("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#005C75"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#005C75"}),t("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#005C75"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#005C75"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#005C75"}),t("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#005C75"}),t("rect",{x:"18",width:"3",height:"3",transform:"rotate(90 18 0)",fill:"#005C75"}),t("rect",{x:"3",y:"18",width:"3",height:"3",transform:"rotate(-180 3 18)",fill:"#005C75"}),t("rect",{x:"27",y:"18",width:"3",height:"3",transform:"rotate(-180 27 18)",fill:"#005C75"}),t("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#005C75"}),t("rect",{x:"3",y:"21",width:"3",height:"3",transform:"rotate(-180 3 21)",fill:"#005C75"}),t("rect",{x:"27",y:"21",width:"3",height:"3",transform:"rotate(-180 27 21)",fill:"#005C75"}),t("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#005C75"}),t("rect",{x:"6",width:"3",height:"3",transform:"rotate(90 6 0)",fill:"#005C75"}),t("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(-180 3 6)",fill:"#005C75"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(-180 21 6)",fill:"#005C75"}),t("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#005C75"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(-180 3 24)",fill:"#005C75"}),t("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(-180 27 24)",fill:"#005C75"}),t("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#005C75"}),t("rect",{x:"9",width:"3",height:"3",transform:"rotate(90 9 0)",fill:"#005C75"}),t("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(90 9 3)",fill:"#005C75"}),t("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#005C75"}),t("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#005C75"}),t("rect",{x:"3",y:"9",width:"3",height:"3",transform:"rotate(-180 3 9)",fill:"#005C75"}),t("rect",{x:"24",y:"9",width:"3",height:"3",transform:"rotate(-180 24 9)",fill:"#005C75"}),t("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#005C75"}),t("rect",{x:"12",width:"3",height:"3",transform:"rotate(90 12 0)",fill:"#005C75"}),t("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#005C75"}),t("rect",{x:"12",y:"18",width:"3",height:"3",transform:"rotate(90 12 18)",fill:"#005C75"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(-180 3 12)",fill:"#005C75"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(-180 27 12)",fill:"#005C75"})]})}),l("div",{className:"flex-1",children:[t("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:"#005C75"},children:r.length}),t("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:"#005C75"},children:"Total Rules"})]})]})}),t("div",{className:`rounded-lg p-4 cursor-pointer transition-colors ${i==="architecture"?"ring-1 ring-[#080096]":""}`,style:{backgroundColor:"#E9F0FB",border:"1px solid #EFEFEF"},onClick:()=>c(i==="architecture"?null:"architecture"),children:l("div",{className:"flex items-start gap-3",children:[t("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:"#DBE9FF"},children:l("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"24",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"24",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"24",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"16",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"8",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"18",y:"6",width:"3",height:"3",transform:"rotate(90 18 6)",fill:"#080096"}),t("rect",{x:"18",y:"24",width:"3",height:"3",transform:"rotate(90 18 24)",fill:"#080096"}),t("rect",{x:"3",y:"6",width:"3",height:"3",transform:"rotate(90 3 6)",fill:"#080096"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(90 3 24)",fill:"#080096"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(90 21 6)",fill:"#080096"}),t("rect",{x:"21",y:"24",width:"3",height:"3",transform:"rotate(90 21 24)",fill:"#080096"}),t("rect",{x:"6",y:"6",width:"3",height:"3",transform:"rotate(90 6 6)",fill:"#080096"}),t("rect",{x:"6",y:"24",width:"3",height:"3",transform:"rotate(90 6 24)",fill:"#080096"}),t("rect",{x:"24",y:"6",width:"3",height:"3",transform:"rotate(90 24 6)",fill:"#080096"}),t("rect",{x:"24",y:"24",width:"3",height:"3",transform:"rotate(90 24 24)",fill:"#080096"}),t("rect",{x:"9",y:"6",width:"3",height:"3",transform:"rotate(90 9 6)",fill:"#080096"}),t("rect",{x:"9",y:"24",width:"3",height:"3",transform:"rotate(90 9 24)",fill:"#080096"}),t("rect",{x:"27",y:"6",width:"3",height:"3",transform:"rotate(90 27 6)",fill:"#080096"}),t("rect",{x:"27",y:"24",width:"3",height:"3",transform:"rotate(90 27 24)",fill:"#080096"}),t("rect",{x:"12",y:"6",width:"3",height:"3",transform:"rotate(90 12 6)",fill:"#080096"}),t("rect",{x:"12",y:"24",width:"3",height:"3",transform:"rotate(90 12 24)",fill:"#080096"}),t("rect",{x:"19",y:"3",width:"3",height:"3",transform:"rotate(90 19 3)",fill:"#080096"}),t("rect",{x:"11",y:"3",width:"3",height:"3",transform:"rotate(90 11 3)",fill:"#080096"})]})}),l("div",{className:"flex-1",children:[t("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:"#080096"},children:I.architecture}),t("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:"#080096"},children:"Architecture"})]})]})}),t("div",{className:`rounded-lg p-4 cursor-pointer transition-colors ${i==="testing"?"ring-1 ring-[#15803d]":""}`,style:{backgroundColor:"#EAFBEF",border:"1px solid #EFEFEF"},onClick:()=>c(i==="testing"?null:"testing"),children:l("div",{className:"flex items-start gap-3",children:[t("div",{className:"w-12 h-12 rounded-lg bg-green-200 flex items-center justify-center flex-shrink-0",children:l("svg",{width:"20",height:"20",viewBox:"0 0 27 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"24",y:"24",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"21",y:"21",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"18",y:"18",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"15",y:"15",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"12",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"9",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"24",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"6",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"21",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"3",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",y:"18",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"12",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"18",y:"12",width:"3",height:"3",transform:"rotate(90 18 12)",fill:"#15803d"}),t("rect",{x:"3",y:"12",width:"3",height:"3",transform:"rotate(90 3 12)",fill:"#15803d"}),t("rect",{x:"21",y:"12",width:"3",height:"3",transform:"rotate(90 21 12)",fill:"#15803d"}),t("rect",{x:"6",y:"12",width:"3",height:"3",transform:"rotate(90 6 12)",fill:"#15803d"}),t("rect",{x:"24",y:"12",width:"3",height:"3",transform:"rotate(90 24 12)",fill:"#15803d"}),t("rect",{x:"9",y:"12",width:"3",height:"3",transform:"rotate(90 9 12)",fill:"#15803d"}),t("rect",{x:"27",y:"12",width:"3",height:"3",transform:"rotate(90 27 12)",fill:"#15803d"}),t("rect",{x:"12",y:"12",width:"3",height:"3",transform:"rotate(90 12 12)",fill:"#15803d"}),t("rect",{x:"12",y:"15",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"9",y:"9",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"6",y:"6",width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"3",y:"3",width:"3",height:"3",fill:"#15803d"}),t("rect",{width:"3",height:"3",fill:"#15803d"}),t("rect",{x:"3",y:"24",width:"3",height:"3",transform:"rotate(90 3 24)",fill:"#15803d"}),t("rect",{x:"6",y:"21",width:"3",height:"3",transform:"rotate(90 6 21)",fill:"#15803d"}),t("rect",{x:"9",y:"18",width:"3",height:"3",transform:"rotate(90 9 18)",fill:"#15803d"}),t("rect",{x:"12",y:"15",width:"3",height:"3",transform:"rotate(90 12 15)",fill:"#15803d"}),t("rect",{x:"18",y:"9",width:"3",height:"3",transform:"rotate(90 18 9)",fill:"#15803d"}),t("rect",{x:"21",y:"6",width:"3",height:"3",transform:"rotate(90 21 6)",fill:"#15803d"}),t("rect",{x:"24",y:"3",width:"3",height:"3",transform:"rotate(90 24 3)",fill:"#15803d"}),t("rect",{x:"27",width:"3",height:"3",transform:"rotate(90 27 0)",fill:"#15803d"})]})}),l("div",{className:"flex-1",children:[t("div",{className:"text-[32px] font-semibold text-green-700 leading-none mb-1",children:I.testing}),t("div",{className:"text-[11px] text-green-700 uppercase tracking-wider font-medium",children:"Testing"})]})]})}),t("div",{className:`rounded-lg p-4 cursor-pointer transition-colors ${i==="faq"?"ring-1 ring-[#080096]":""}`,style:{backgroundColor:"#E7E7FC",border:"1px solid #EFEFEF"},onClick:()=>c(i==="faq"?null:"faq"),children:l("div",{className:"flex items-start gap-3",children:[t("div",{className:"w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",style:{backgroundColor:"#D4D4FF"},children:l("svg",{width:"13",height:"20",viewBox:"0 0 18 27",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[t("rect",{x:"6",y:"24",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"18",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"15",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"12",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"9",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"15",y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"12",y:"3",width:"3",height:"3",transform:"rotate(-90 12 3)",fill:"#080096"}),t("rect",{x:"15",y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{y:"6",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"9",y:"3",width:"3",height:"3",transform:"rotate(-90 9 3)",fill:"#080096"}),t("rect",{y:"3",width:"3",height:"3",fill:"#080096"}),t("rect",{x:"6",y:"3",width:"3",height:"3",transform:"rotate(-90 6 3)",fill:"#080096"}),t("rect",{x:"3",y:"3",width:"3",height:"3",transform:"rotate(-90 3 3)",fill:"#080096"})]})}),l("div",{className:"flex-1",children:[t("div",{className:"text-[32px] font-semibold leading-none mb-1",style:{color:"#080096"},children:I.faq}),t("div",{className:"text-[11px] uppercase tracking-wider font-medium",style:{color:"#080096"},children:"FAQ"})]})]})})]})]}),w&&t("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),children:t("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:P=>P.stopPropagation(),children:t(no,{rule:null,onSave:$,onCancel:()=>{x(!1)}})})}),y&&t("div",{className:"fixed inset-0 flex items-center justify-center z-[9999] p-4",style:{backgroundColor:"rgba(0, 0, 0, 0.8)"},onClick:()=>g(null),children:t("div",{className:"bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-auto",onClick:P=>P.stopPropagation(),children:t(no,{rule:y,onSave:$,onCancel:()=>{g(null)}})})}),t(Up,{changes:n,memories:A,onEditRule:g}),t(Wp,{onEditRule:g,onDeleteRule:v,refreshKey:C}),l("div",{className:"flex items-center justify-between mb-4",children:[t("h2",{className:"text-base font-semibold text-gray-900",style:{fontFamily:"Sora"},children:"All Rules"}),l("div",{className:"flex items-center gap-4",children:[l("div",{className:"relative",children:[l("select",{value:i||"all",onChange:P=>{const B=P.target.value;c(B==="all"?null:B)},className:"appearance-none bg-white border border-gray-200 rounded px-3 pr-8 text-sm h-9 cursor-pointer focus:outline-none focus:ring-2 focus:ring-[#005c75] hover:border-gray-300 transition-colors",children:[t("option",{value:"all",children:"All Types"}),t("option",{value:"architecture",children:"Architecture"}),t("option",{value:"testing",children:"Testing"}),t("option",{value:"faq",children:"FAQ"})]}),t(Wt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 pointer-events-none"})]}),k.size>1&&t("button",{onClick:j,className:"text-xs text-[#005C75] hover:underline cursor-pointer font-mono uppercase font-semibold",children:T?"Collapse All":"Expand All"})]})]}),l("div",{className:"flex gap-6",children:[t("div",{className:"w-80 flex-shrink-0",children:t(Yp,{memories:A,selectedPath:u,onSelectPath:p,expandedFolders:h,onToggleFolder:N})}),t("div",{className:"flex-1 min-w-0",children:r.length===0?l("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:[t(gi,{className:"w-12 h-12 text-gray-300 mx-auto mb-4"}),t("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Rules Yet"}),l("p",{className:"text-gray-500 mb-4",children:["Run"," ",t("code",{className:"bg-gray-100 px-2 py-1 rounded",children:"/codeyam:power-memories"})," ","to generate initial memories for your codebase."]}),l("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:[t(Sa,{className:"w-4 h-4"}),"Create Your First Memory"]})]}):l("div",{children:[(i||u)&&l("div",{className:"flex items-center gap-2 text-sm text-gray-600 mb-4",children:[t(yi,{className:"w-4 h-4"}),i&&l(le,{children:["Showing"," ",Gn[i]," ","memories"]}),i&&u&&" in ",u&&t("span",{className:"font-mono bg-gray-100 px-1.5 py-0.5 rounded",children:u||"(root)"}),t("button",{onClick:()=>{c(null),p(null)},className:"text-[#005C75] hover:underline cursor-pointer",children:"Clear filter"})]}),t(Bp,{memories:_,onEdit:g,onDelete:v,expandedFolders:h,onToggleFolder:N})]})})]}),b&&t("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:l("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[t("h3",{className:"text-lg font-semibold mb-2",children:"Delete Memory?"}),l("p",{className:"text-gray-600 mb-4",children:["Are you sure you want to delete"," ",t("span",{className:"font-mono text-sm",children:b.filePath}),"? This cannot be undone."]}),l("div",{className:"flex justify-end gap-2",children:[t("button",{onClick:()=>v(null),className:"px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-md cursor-pointer",children:"Cancel"}),t("button",{onClick:()=>D(b),className:"px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 cursor-pointer",children:"Delete"})]})]})})]})})}),qp=Object.freeze(Object.defineProperty({__proto__:null,default:Hp,loader:zp,meta:Op},Symbol.toStringTag,{value:"Module"}));function ln(e){return`${e.filePath||""}::${e.name}`}function Ns(e,r){const n=Ae(),{showToast:a}=Mn(),[o,s]=M(new Map);re(()=>{if(n.state==="idle"&&n.data){const h=n.data;h!=null&&h.error&&a(`Error: ${h.error}`,"error",6e3)}},[n.state,n.data,a]),re(()=>{var f;if(o.size===0)return;const h=new Set;(f=r==null?void 0:r.jobs)==null||f.forEach(y=>{var g;(g=y.entityShas)==null||g.forEach(w=>{o.forEach((x,b)=>{x===w&&h.add(b)})})}),e==null||e.forEach(y=>{o.forEach((g,w)=>{g===y&&h.add(w)})}),h.size>0&&s(y=>{const g=new Map(y);return h.forEach(w=>g.delete(w)),g})},[r,e,o]);const i=se(h=>{console.log("Generate analysis clicked for entity:",h.sha,h.name);const f=ln(h);s(g=>new Map(g).set(f,h.sha));const y=new FormData;y.append("entitySha",h.sha),y.append("filePath",h.filePath||""),n.submit(y,{method:"post",action:"/api/analyze"})},[n]),c=se(h=>{const f=h.filter(w=>w.entityType==="visual"||w.entityType==="library");console.log("Generate analysis for all entities:",f.length),s(w=>{const x=new Map(w);return f.forEach(b=>x.set(ln(b),b.sha)),x});const y=f.map(w=>w.sha).join(","),g=new FormData;g.append("entityShas",y),n.submit(g,{method:"post",action:"/api/analyze"})},[n]),d=se(h=>(e==null?void 0:e.includes(h))??!1,[e]),m=se(h=>{const f=ln(h);return o.has(f)},[o]),u=se(h=>{var f;return((f=r==null?void 0:r.jobs)==null?void 0:f.some(y=>{var g;return(g=y.entityShas)==null?void 0:g.includes(h)}))??!1},[r]),p=ne(()=>Array.from(o.keys()),[o]);return{isAnalyzing:n.state!=="idle",handleGenerateSimulation:i,handleGenerateAllSimulations:c,isEntityBeingAnalyzed:d,isEntityPending:m,isEntityInQueue:u,pendingEntityKeys:p}}function Jn({showActions:e=!1,sortOrder:r="desc",onSortChange:n,onAnalyzeAll:a,analyzeAllDisabled:o=!1,analyzeAllText:s="Analyze All"}){return t("div",{className:"bg-[#efefef] rounded-lg mb-2 text-[11px] font-normal leading-[16px] text-[#3e3e3e] uppercase",children:l("div",{className:"flex justify-between items-center px-3 py-2",children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t("span",{className:"w-4"}),t("span",{children:"FILE"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[t("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:t("span",{children:"STATE"})}),t("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:t("span",{children:"SIMULATIONS"})}),l("div",{className:"flex gap-4 items-center",children:[t("span",{className:"text-center",style:{width:"70px"},children:"ENTITIES"}),l("div",{className:"flex items-center justify-center gap-1 cursor-pointer hover:text-[#232323] transition-colors",style:{width:"116px"},onClick:n,role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),n==null||n())},children:[t("span",{children:"MODIFIED"}),t("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",style:{transform:r==="asc"?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease"},children:t("path",{d:"M3 5L6 8L9 5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),e&&t("div",{className:"text-center",style:{width:"127px"},children:a&&t("button",{onClick:a,disabled:o,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:o?s:"Analyze all entities",children:s})})]})]})]})})}function Gp({status:e,variant:r="compact"}){const n={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"}},a={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(r==="full"){const s=a[e]||{label:"UNKNOWN",textColor:"#6B7280"};return t("div",{className:"bg-[#f9f9f9] inline-flex items-center justify-center px-[5px] py-0 rounded",style:{height:"22px"},children:t("span",{className:"text-[10px] font-['IBM_Plex_Sans'] font-medium leading-[22px]",style:{color:s.textColor},children:s.label})})}const o=n[e]||{label:"?",bgColor:"bg-gray-500"};return l("div",{className:"inline-flex items-center gap-1",children:[t("span",{className:`inline-flex items-center justify-center w-5 h-5 text-[11px] font-bold text-white rounded ${o.bgColor}`,title:e,children:o.label}),o.showWarning&&t("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 Vn({filePath:e,isExpanded:r,onToggle:n,fileStatus:a,simulationPreviews:o,entityCount:s,state:i,lastModified:c,actionButton:d,uncommittedCount:m,children:u,isNotAnalyzable:p=!1,isUncommitted:h=!1}){return l("div",{className:"bg-white overflow-hidden",style:r?{border:"1px solid #e1e1e1",borderLeft:"4px solid #005C75",borderRadius:"8px"}:{borderBottom:"1px solid #e1e1e1"},children:[l("div",{className:`flex justify-between items-center p-3 cursor-pointer select-none transition-colors ${p?"opacity-50":"hover:bg-gray-200"}`,style:{outlineColor:"#005C75"},onClick:n,role:"button",tabIndex:0,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),n())},children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t("span",{className:"w-4 inline-flex items-center justify-center shrink-0",style:{transform:r?"rotate(90deg)":"none"},children:t("svg",{width:"10",height:"12",viewBox:"0 0 10 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:t("path",{d:"M1.5 1.268L8.5 6L1.5 10.732V1.268Z",fill:r?"#3e3e3e":"#c7c7c7"})})}),t("img",{src:"/icons/file-icon.svg",alt:"file",className:"w-4 h-5 shrink-0"}),t(So,{filePath:e}),a&&t(Gp,{status:typeof a=="string"?a:a.status,variant:"full"}),h&&i==="out-of-date"&&t("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"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[t("div",{className:"flex items-center justify-center h-[38px]",style:{width:"100px"},children:(h||i==="out-of-date")&&l("div",{className:"flex gap-1.5 items-center",children:[h&&t("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&&t("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"})]})}),t("div",{className:"flex items-center justify-center h-[38px]",style:{width:"70px"},children:o}),l("div",{className:"flex gap-4 items-center",children:[t("div",{className:"flex items-center justify-center",style:{width:"70px"},children:t("div",{className:"bg-[#f9f9f9] flex items-center justify-center px-2 rounded whitespace-nowrap",style:{height:"26px"},children:l("span",{className:"text-[13px] text-[#3e3e3e]",children:[s," ",s===1?"entity":"entities"]})})}),t("div",{className:"text-[12px] text-gray-600 text-center",style:{width:"116px"},children:ys(c)}),t("div",{style:{width:"127px"},className:"flex justify-center",children:d})]})]})]}),r&&u&&t("div",{className:"bg-gray-50 py-2 rounded-bl-[4px] rounded-br-[4px] flex flex-col gap-1",children:u})]})}function Qn({entities:e,maxPreviews:r=3}){var a,o,s,i,c;const n=[];for(const d of e){if(n.length>=r)break;const m=((o=(a=d.analyses)==null?void 0:a[0])==null?void 0:o.scenarios)||[];if(d.entityType==="library"){const u=m.find(p=>{var h,f;return((h=p.metadata)==null?void 0:h.executionResult)||((f=p.metadata)==null?void 0:f.error)});u&&n.push({type:"library",scenario:u,entitySha:d.sha})}else if(d.entityType==="visual"){const u=m.find(p=>{var h,f;return(f=(h=p.metadata)==null?void 0:h.screenshotPaths)==null?void 0:f[0]});if(u){const p=(i=(s=u.metadata)==null?void 0:s.screenshotPaths)==null?void 0:i[0],h=!!((c=u.metadata)!=null&&c.error);p&&n.push({type:"screenshot",screenshot:p,hasError:h,scenario:u,entitySha:d.sha})}}}return n.length===0?t("span",{className:"text-gray-400 font-light text-[14px]",children:"—"}):t(le,{children:n.map((d,m)=>{if(d.type==="screenshot"&&d.screenshot){const u=d.hasError?"border-red-400":"border-gray-200";return l(oe,{to:d.scenario?`/entity/${d.entitySha}/scenarios/${d.scenario.id}`:`/entity/${d.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:p=>p.stopPropagation(),children:[t(De,{screenshotPath:d.screenshot,alt:`Preview ${m+1}`,className:"max-w-full max-h-full object-contain object-center"}),d.hasError&&t("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:t(cn,{size:12,color:"white"})})]},`screenshot-${m}`)}return d.type==="library"&&d.scenario&&d.entitySha?t(fs,{scenario:d.scenario,entitySha:d.entitySha,size:"small",showBorder:!0},`library-${m}`):null})})}function Kn({entity:e,isActivelyAnalyzing:r,isQueued:n,onGenerateSimulation:a}){var u,p;const o=r||n?[{entityShas:[e.sha]}]:[],s=Ve(e,o,r),i=e.entityType==="visual"||e.entityType==="library",c=i&&(s==="not-analyzed"||s==="out-of-date")&&!r&&!n,m=(((p=(u=e.analyses)==null?void 0:u[0])==null?void 0:p.scenarios)||[]).filter(h=>{var f,y;return(y=(f=h.metadata)==null?void 0:f.screenshotPaths)==null?void 0:y[0]});return l("div",{className:"bg-white rounded-lg",children:[l(oe,{to:`/entity/${e.sha}`,className:"flex items-center justify-between p-3 transition-colors hover:bg-gray-100 cursor-pointer",children:[l("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t("span",{className:"w-4 shrink-0"}),e.entityType==="type"?t("div",{className:"bg-[#ffe1e1] inline-flex items-center justify-center px-[4px] rounded-[4px]",style:{height:"18px",width:"18px"},children:t("div",{className:"w-[10px] h-[10px] flex items-center justify-center",children:t(Ue,{type:"type"})})}):t(Ue,{type:e.entityType||"other"}),t("span",{className:`font-['IBM_Plex_Sans'] text-[14px] leading-[18px] text-black ${i?"font-medium":"font-normal"}`,children:e.name}),t(Bn,{type:e.entityType||"other"})]}),l("div",{className:"flex items-center gap-3 shrink-0",children:[t("div",{style:{width:"160px"}}),l("div",{className:"flex gap-4 items-center",children:[t("div",{style:{width:"70px"}}),t("div",{style:{width:"116px"}}),t("div",{style:{width:"127px"},className:"flex justify-center items-center",children:i?s==="queued"?l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#cbf3fa",color:"#3098b4",height:"26px"},children:[l("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"#3098b4",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[t("circle",{cx:"12",cy:"12",r:"10"}),t("polyline",{points:"12,6 12,12 16,14"})]}),"Queued"]}):s==="analyzing"?l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[t("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),t("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..."]}):s==="up-to-date"?t("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"}):s==="out-of-date"?t("button",{onClick:h=>{h.preventDefault(),h.stopPropagation(),a(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"}):c&&t("button",{onClick:h=>{h.preventDefault(),h.stopPropagation(),a(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"}):t("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"})})]})]})]}),m.length>0&&t("div",{className:"px-3 pb-3 pt-0 flex items-center gap-2 pl-[52px]",children:m.map((h,f)=>{var g,w;const y=(w=(g=h.metadata)==null?void 0:g.screenshotPaths)==null?void 0:w[0];return y?t(oe,{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:x=>x.stopPropagation(),children:t(De,{screenshotPath:y,alt:h.name,className:"max-w-full max-h-full object-contain object-center"})},h.id):null})})]})}function Jp({entities:e,page:r,itemsPerPage:n=50,currentRun:a,filter:o,entityType:s,queueState:i,isEntityPending:c,pendingEntityKeys:d,onGenerateSimulation:m,onGenerateAllSimulations:u,totalFilesCount:p,totalEntitiesCount:h,uncommittedFilesCount:f,showOnlyUncommitted:y,onToggleUncommitted:g}){const[w,x]=Jt(),[b,v]=M(new Set),[C,E]=M(""),[N,A]=M(!1),[_,$]=M("all"),[D,I]=M("desc"),k=s||"all",T=ne(()=>{let S=e;return k!=="all"&&(S=S.filter(H=>H.entityType===k)),o==="analyzed"&&(S=S.filter(H=>H.analyses&&H.analyses.length>0)),S},[e,k,o]),j=ne(()=>{const S=new Map,H=new Map,q=new Map;T.forEach(Y=>{var W,Z;const U=`${Y.filePath}::${Y.name}`,Q=H.get(U);if(!Q)H.set(U,Y),q.set(U,[]);else{const de=((W=Q.metadata)==null?void 0:W.editedAt)||Q.createdAt||"",ue=((Z=Y.metadata)==null?void 0:Z.editedAt)||Y.createdAt||"";let ge=!1;if(ue>de)ge=!0;else if(ue===de){const be=Q.createdAt||"";ge=(Y.createdAt||"")>be}ge?(q.get(U).push(Q),H.set(U,Y)):q.get(U).push(Y)}}),H.forEach((Y,U)=>{var W;if(!(Y.analyses&&Y.analyses.length>0)&&((W=Y.metadata)!=null&&W.previousVersionWithAnalyses)){const de=(q.get(U)||[]).find(ue=>{var ge;return ue.sha===((ge=Y.metadata)==null?void 0:ge.previousVersionWithAnalyses)});de&&de.analyses&&de.analyses.length>0&&(Y.analyses=de.analyses)}}),Array.from(H.values()).sort((Y,U)=>{var Z,de,ue,ge;const Q=!((Z=Y.metadata)!=null&&Z.notExported)&&!((de=Y.metadata)!=null&&de.namedExport),W=!((ue=U.metadata)!=null&&ue.notExported)&&!((ge=U.metadata)!=null&&ge.namedExport);return Q&&!W?-1:!Q&&W?1:0}).forEach(Y=>{var de,ue,ge,be,Ne;const U=Y.filePath??"No File Path";S.has(U)||S.set(U,{filePath:U,entities:[],totalCount:0,uncommittedCount:0,lastUpdated:null,previewScreenshots:[],previewScreenshotErrors:[],previewLibraryScenarios:[],state:"up-to-date",simulationCount:0});const Q=S.get(U);Q.entities.push(Y),Q.totalCount++,(de=Y.metadata)!=null&&de.isUncommitted&&Q.uncommittedCount++;const W=((be=(ge=(ue=Y.analyses)==null?void 0:ue[0])==null?void 0:ge.scenarios)==null?void 0:be.length)||0;Q.simulationCount+=W;const Z=((Ne=Y.metadata)==null?void 0:Ne.editedAt)||Y.updatedAt;Z&&(!Q.lastUpdated||new Date(Z)>new Date(Q.lastUpdated))&&(Q.lastUpdated=Z)});const J=(i==null?void 0:i.jobs)||[],ae=Y=>{const U=`${Y.filePath||""}::${Y.name}`;return(d==null?void 0:d.includes(U))||!1};S.forEach(Y=>{const U=Y.entities.map(Q=>ae(Q)?"queued":Ve(Q,J));U.includes("analyzing")||U.includes("queued")?Y.state="analyzing":U.includes("incomplete")?Y.state="incomplete":U.includes("out-of-date")?Y.state="out-of-date":U.includes("not-analyzed")?Y.state="not-analyzed":Y.state="up-to-date"}),S.forEach(Y=>{var U,Q,W,Z,de;for(const ue of Y.entities){if(Y.previewScreenshots.length+Y.previewLibraryScenarios.length>=3)break;const be=((Q=(U=ue.analyses)==null?void 0:U[0])==null?void 0:Q.scenarios)||[];if(ue.entityType==="library"){const Ne=be.find(we=>{var ke,Te;return((ke=we.metadata)==null?void 0:ke.executionResult)||((Te=we.metadata)==null?void 0:Te.error)});Ne&&Y.previewLibraryScenarios.push({scenario:Ne,entitySha:ue.sha})}else{const Ne=be.find(we=>{var ke,Te;return(Te=(ke=we.metadata)==null?void 0:ke.screenshotPaths)==null?void 0:Te[0]});if(Ne){const we=(Z=(W=Ne.metadata)==null?void 0:W.screenshotPaths)==null?void 0:Z[0],ke=!!((de=Ne.metadata)!=null&&de.error);we&&!Y.previewScreenshots.includes(we)&&(Y.previewScreenshots.push(we),Y.previewScreenshotErrors.push(ke))}}}});const V=Array.from(S.values());return V.sort((Y,U)=>{if(o==="analyzed"){const Z=Math.max(...Y.entities.filter(ue=>{var ge,be;return(be=(ge=ue.analyses)==null?void 0:ge[0])==null?void 0:be.createdAt}).map(ue=>new Date(ue.analyses[0].createdAt).getTime()),0),de=Math.max(...U.entities.filter(ue=>{var ge,be;return(be=(ge=ue.analyses)==null?void 0:ge[0])==null?void 0:be.createdAt}).map(ue=>new Date(ue.analyses[0].createdAt).getTime()),0);return D==="desc"?de-Z:Z-de}if(Y.uncommittedCount>0&&U.uncommittedCount===0)return-1;if(Y.uncommittedCount===0&&U.uncommittedCount>0)return 1;const Q=Y.lastUpdated?new Date(Y.lastUpdated).getTime():0,W=U.lastUpdated?new Date(U.lastUpdated).getTime():0;return D==="desc"?W-Q:Q-W}),V},[T,o,D,i,d]),P=ne(()=>{let S=j;if(_!=="all"&&(S=S.filter(H=>H.state===_)),C.trim()){const H=C.toLowerCase();S=S.filter(q=>q.filePath.toLowerCase().includes(H))}return S},[j,C,_]),B=(r-1)*n,L=B+n,z=P.slice(B,L),O=Math.ceil(P.length/n),F=S=>{v(H=>{const q=new Set(H);return q.has(S)?q.delete(S):q.add(S),q})},R=()=>{I(S=>S==="desc"?"asc":"desc")};return l("div",{children:[l("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:[t("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Filters"}),l("div",{className:"flex gap-3",children:[l("div",{className:"relative w-[130px]",children:[l("select",{value:k,onChange:S=>{const H=S.target.value,q=new URLSearchParams(w);H==="all"?q.delete("entityType"):q.set("entityType",H),q.set("page","1"),x(q)},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:[t("option",{value:"all",children:"All Types"}),t("option",{value:"visual",children:"Visual"}),t("option",{value:"library",children:"Library"})]}),t(Wt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"relative w-[130px]",children:[l("select",{value:_,onChange:S=>$(S.target.value),className:"appearance-none bg-gray-50 border border-gray-200 rounded px-[10px] pr-6 text-[13px] h-[39px] w-full cursor-pointer focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] hover:border-gray-300 transition-colors",children:[t("option",{value:"all",children:"All States"}),t("option",{value:"analyzing",children:"Analyzing..."}),t("option",{value:"up-to-date",children:"Up to date"}),t("option",{value:"incomplete",children:"Incomplete"}),t("option",{value:"out-of-date",children:"Out of date"}),t("option",{value:"not-analyzed",children:"Not analyzed"})]}),t(Wt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-3 h-3 text-gray-500 pointer-events-none"})]}),l("div",{className:"flex-1 relative",children:[t(Cn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"}),t("input",{type:"text",placeholder:"Search component",value:C,onChange:S=>E(S.target.value),className:"w-full bg-gray-50 border border-gray-200 rounded pl-9 pr-[10px] text-[13px] h-[39px] placeholder:text-gray-400 focus:outline-none focus:ring-0 focus:border-2 focus:border-[#005c75] transition-colors"})]})]})]}),p!==void 0&&h!==void 0&&f!==void 0&&t("div",{className:"mb-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[t("span",{style:{color:"#000000"},children:P.length})," ",P.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[t("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:t("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"})}),t("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("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.",t("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),t("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[t("span",{style:{color:"#000000"},children:P.reduce((S,H)=>S+H.totalCount,0)})," ",P.reduce((S,H)=>S+H.totalCount,0)===1?"entity":"entities"]}),t("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),y?l("button",{onClick:g,className:"flex items-center gap-2 text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase cursor-pointer",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[P.filter(S=>S.uncommittedCount>0).length," ","uncommitted"," ",P.filter(S=>S.uncommittedCount>0).length===1?"file":"files",t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})]}):l("button",{onClick:g,className:"text-[#005c75] underline hover:text-[#004a5e] transition-colors ml-2 font-mono uppercase",style:{fontSize:"11px",fontWeight:500,letterSpacing:"0.05em"},children:[f," uncommitted"," ",f===1?"file":"files"]})]}),z.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:()=>{v(new Set(z.map(S=>S.filePath))),A(!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:[t(po,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:()=>{v(new Set),A(!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:[t(fo,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),t(Jn,{showActions:!0,sortOrder:D,onSortChange:R}),t("div",{className:"flex flex-col gap-[3px]",children:z.map(S=>{const H=b.has(S.filePath),J=S.entities.filter(U=>(U.entityType==="visual"||U.entityType==="library")&&(Ve(U,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Ve(U,(i==null?void 0:i.jobs)||[])==="out-of-date"||Ve(U,(i==null?void 0:i.jobs)||[])==="incomplete")).length>0,ae=U=>{var Q;return((Q=a==null?void 0:a.currentEntityShas)==null?void 0:Q.includes(U))||!1},V=U=>{var Q;return c!=null&&c(U)?!0:((Q=i==null?void 0:i.jobs)==null?void 0:Q.some(W=>{var Z;return(Z=W.entityShas)==null?void 0:Z.includes(U.sha)}))||!1},Y=U=>{m==null||m(U)};return t(Vn,{filePath:S.filePath,isExpanded:H,onToggle:()=>F(S.filePath),simulationPreviews:t(Qn,{entities:S.entities,maxPreviews:1}),entityCount:S.totalCount,state:S.state,lastModified:S.lastUpdated,uncommittedCount:S.uncommittedCount,isUncommitted:S.uncommittedCount>0,actionButton:J?t("button",{onClick:U=>{U.stopPropagation();const Q=S.entities.filter(W=>(W.entityType==="visual"||W.entityType==="library")&&(Ve(W,(i==null?void 0:i.jobs)||[])==="not-analyzed"||Ve(W,(i==null?void 0:i.jobs)||[])==="out-of-date"||Ve(W,(i==null?void 0:i.jobs)||[])==="incomplete"));u==null||u(Q)},className:"bg-[#005c75] text-white rounded text-[12px] font-['IBM_Plex_Sans'] font-normal hover:bg-[#004a5e] transition-colors cursor-pointer px-[15px] py-0 h-[28px]",children:S.state==="out-of-date"?"Re-analyze":"Analyze"}):void 0,children:S.entities.sort((U,Q)=>{var ge,be,Ne,we;const W=!((ge=U.metadata)!=null&&ge.notExported)&&!((be=U.metadata)!=null&&be.namedExport),Z=!((Ne=Q.metadata)!=null&&Ne.notExported)&&!((we=Q.metadata)!=null&&we.namedExport);if(W&&!Z)return-1;if(!W&&Z)return 1;const de=U.entityType==="visual"||U.entityType==="library",ue=Q.entityType==="visual"||Q.entityType==="library";return de&&!ue?-1:!de&&ue?1:U.name.localeCompare(Q.name)}).map(U=>t(Kn,{entity:U,isActivelyAnalyzing:ae(U.sha),isQueued:V(U),onGenerateSimulation:Y},U.sha))},S.filePath)})}),O>1&&l("div",{className:"flex justify-center items-center gap-4 mt-6 p-4",children:[r>1&&t("a",{href:`?${new URLSearchParams({...Object.fromEntries(w),page:String(r-1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"← Previous"}),l("span",{children:["Page ",r," of ",O]}),r<O&&t("a",{href:`?${new URLSearchParams({...Object.fromEntries(w),page:String(r+1)}).toString()}`,className:"no-underline font-medium hover:underline",style:{color:"#005C75"},children:"Next →"})]})]})}const Vp=()=>[{title:"CodeYam - Files & Entities"},{name:"description",content:"Browse your codebase files and entities"}];async function Qp({request:e,context:r}){try{const n=new URL(e.url),a=parseInt(n.searchParams.get("page")||"1"),o=n.searchParams.get("filter")||null,s=n.searchParams.get("entityType"),i=r.analysisQueue,c=i?i.getState():{paused:!1,jobs:[]},[d,m]=await Promise.all([Zt(),It()]);return G({entities:d,currentCommit:m,page:a,filter:o,entityType:s,queueState:c})}catch(n){return console.error("Failed to load entities:",n),G({entities:[],currentCommit:null,page:1,filter:null,entityType:null,queueState:{paused:!1,jobs:[]},error:"Failed to load entities"})}}const Kp=Oe(function(){var C,E,N;const{entities:r,currentCommit:n,page:a,filter:o,entityType:s,queueState:i,error:c}=We();rt();const[d,m]=Jt(),[u,p]=M(!1);mt({source:"files-page"});const{handleGenerateSimulation:h,handleGenerateAllSimulations:f,isEntityPending:y,pendingEntityKeys:g}=Ns((E=(C=n==null?void 0:n.metadata)==null?void 0:C.currentRun)==null?void 0:E.currentEntityShas,i),w=r||[],x=ne(()=>{const A=new Set([]);for(const _ of w)A.add(_.filePath??"No File Path");return Array.from(A)},[w]),b=ne(()=>{let A=w;return u&&(A=A.filter(_=>{var $;return($=_.metadata)==null?void 0:$.isUncommitted})),A.sort((_,$)=>{var D,I,k,T,j,P;return(D=_.metadata)!=null&&D.isUncommitted&&!((I=$.metadata)!=null&&I.isUncommitted)?-1:!((k=_.metadata)!=null&&k.isUncommitted)&&((T=$.metadata)!=null&&T.isUncommitted)?1:new Date(((j=$.metadata)==null?void 0:j.editedAt)||0).getTime()-new Date(((P=_.metadata)==null?void 0:P.editedAt)||0).getTime()})},[w,u]),v=ne(()=>{var _;const A=new Set([]);for(const $ of w)(_=$.metadata)!=null&&_.isUncommitted&&A.add($.filePath??"No File Path");return Array.from(A)},[w]);return c?t("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-12 py-6 font-sans",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900",children:"Error"}),t("p",{className:"text-base text-gray-500",children:c})]})}):w.length===0?t("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),t("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),t("div",{className:"bg-white rounded-lg border border-gray-200 p-12 text-center",children:l("div",{className:"max-w-md mx-auto",children:[t("h2",{className:"text-xl font-semibold text-gray-900 mb-3",children:"No entities found"}),l("p",{className:"text-[15px] text-gray-600 mb-6",children:["Your project hasn't been analyzed yet. Run"," ",t("code",{className:"px-2 py-1 bg-gray-100 rounded text-sm font-mono",children:"codeyam analyze"})," ","to extract entities from your codebase."]}),t("p",{className:"text-sm text-gray-500",children:"Entities include React components, functions, and other analyzable code elements."})]})})]})}):t("div",{className:"bg-[#f9f9f9] min-h-screen",children:l("div",{className:"px-20 py-12 font-sans",children:[l("div",{className:"mb-8",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Files & Entities"}),t("p",{className:"text-[15px] text-gray-500",children:"This is a list of all the files in your app."})]}),t(Jp,{entities:b,page:a,itemsPerPage:50,currentRun:(N=n==null?void 0:n.metadata)==null?void 0:N.currentRun,filter:o,entityType:s,queueState:i,isEntityPending:y,pendingEntityKeys:g,onGenerateSimulation:h,onGenerateAllSimulations:f,totalFilesCount:x.length,totalEntitiesCount:w.length,uncommittedFilesCount:v.length,showOnlyUncommitted:u,onToggleUncommitted:()=>p(!u)})]})})}),Zp=Object.freeze(Object.defineProperty({__proto__:null,default:Kp,loader:Qp,meta:Vp},Symbol.toStringTag,{value:"Module"}));function Xp(e,r,n){const[a,o]=M(()=>new Set),[s,i]=M(()=>new Set),c=Ee([]),d=Ee([]);return re(()=>{(r.length!==c.current.length||r.some((g,w)=>g!==c.current[w]))&&(c.current=r,o(g=>{const w=new Set;return r.forEach(x=>{g.has(x)&&w.add(x)}),w}))},[r]),re(()=>{(n.length!==d.current.length||n.some((g,w)=>g!==d.current[w]))&&(d.current=n,i(g=>{const w=new Set;return n.forEach(x=>{g.has(x)&&w.add(x)}),w}))},[n]),{expandedUncommitted:a,expandedBranch:s,setExpandedUncommitted:o,setExpandedBranch:i,toggleFile:(y,g,w)=>{w(x=>{const b=new Set(x);return b.has(y)?b.delete(y):b.add(y),b})},expandAllUncommitted:()=>{o(new Set(r))},collapseAllUncommitted:()=>{o(new Set)},expandAllBranch:()=>{i(new Set(n))},collapseAllBranch:()=>{i(new Set)}}}function ef(e,r,n){const[a,o]=M(null),[s,i]=M(null),c=Ae();re(()=>{var p,h;((p=c.data)==null?void 0:p.oldContent)!==void 0&&((h=c.data)==null?void 0:h.newContent)!==void 0&&i({oldContent:c.data.oldContent,newContent:c.data.newContent,fileName:c.data.fileName})},[c.data]);const d=p=>{o({type:"file",path:p}),i(null);const h=new FormData;h.append("actionType","getDiff"),h.append("filePath",p),h.append("diffType","branch"),h.append("baseBranch",e),h.append("currentBranch",r||""),c.submit(h,{method:"post"})},m=(p,h)=>{o({type:"entity",path:p,entitySha:h}),i(null);const f=new FormData;f.append("actionType","getDiff"),f.append("filePath",p),f.append("diffType","branch"),f.append("baseBranch",e),f.append("currentBranch",r||""),f.append("entitySha",h),c.submit(f,{method:"post"})},u=()=>{o(null),i(null)};return{diffView:a,diffContent:s,isLoading:c.state==="loading"||c.state==="submitting",handleShowFileDiff:d,handleShowEntityDiff:m,handleCloseDiff:u}}function tf({diffView:e,diffContent:r,isLoading:n,entities:a,onClose:o}){var m;const[s,i]=M(!1),[c,d]=M(!1);return re(()=>{d(!0)},[]),t("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center p-8 z-50",children:l("div",{className:"bg-white rounded-xl shadow-2xl max-w-6xl w-full max-h-[90vh] flex flex-col",children:[l("div",{className:"p-6 border-b border-[#e1e1e1] flex items-center justify-between",children:[l("div",{children:[t("h2",{className:"font-['IBM_Plex_Sans'] text-2xl font-semibold text-[#232323]",children:e.type==="file"?"File Diff":"Entity Diff"}),t("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e] mt-1",children:e.path}),e.type==="entity"&&e.entitySha&&l("p",{className:"font-['IBM_Plex_Mono'] text-sm text-[#8e8e8e]",children:["Entity:"," ",((m=a.find(u=>u.sha===e.entitySha))==null?void 0:m.name)||e.entitySha]})]}),l("div",{className:"flex items-center gap-3",children:[t("button",{onClick:()=>i(!s),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:s?"Show changes only":"Show full file",children:s?"Show Changes Only":"Show Full File"}),t("button",{onClick:o,className:"text-[#8e8e8e] hover:text-[#626262] transition-colors cursor-pointer",children:t("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),t("div",{className:"flex-1 overflow-auto",children:n?t("div",{className:"p-6 text-center",children:t("div",{className:"text-[#8e8e8e]",children:"Loading diff..."})}):r?t("div",{className:"diff-viewer-wrapper",children:c&&t(Gi,{oldValue:r.oldContent,newValue:r.newContent,splitView:!0,useDarkTheme:!1,showDiffOnly:!s,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"}}})}):t("div",{className:"p-6 text-center",children:t("div",{className:"text-[#8e8e8e]",children:"No diff available"})})}),t("div",{className:"p-6 border-t border-[#e1e1e1] flex justify-end gap-3",children:t("button",{onClick:o,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 rf({files:e,currentBranch:r,defaultBranch:n,baseBranch:a,allBranches:o,expandedFiles:s,isEntityBeingAnalyzed:i,isEntityQueued:c,sortOrder:d,onToggleFile:m,onBranchChange:u,onGenerateSimulation:p,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const w=e.flatMap(([v,{entities:C}])=>{const E=C.filter(N=>i(N.sha)||c(N)).map(N=>N.sha);return E.length>0?[{entityShas:E}]:[]}),x=v=>{const C=v.map(E=>Ve(E,w));return C.includes("analyzing")||C.includes("queued")?"analyzing":C.includes("out-of-date")?"out-of-date":C.includes("not-analyzed")?"not-analyzed":"up-to-date"},b=ne(()=>[...e].sort((v,C)=>{const E=v[1].entities.reduce(($,D)=>{var k;const I=((k=D.metadata)==null?void 0:k.editedAt)||D.updatedAt;return I?$?new Date(I)>new Date($)?I:$:I:$},null),N=C[1].entities.reduce(($,D)=>{var k;const I=((k=D.metadata)==null?void 0:k.editedAt)||D.updatedAt;return I?$?new Date(I)>new Date($)?I:$:I:$},null);if(!E&&!N)return 0;if(!E)return 1;if(!N)return-1;const A=new Date(E).getTime(),_=new Date(N).getTime();return d==="desc"?_-A:A-_}),[e,d]);return t("div",{children:e.length>0?l("div",{children:[t(Jn,{showActions:!0,sortOrder:d,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),t("div",{className:"flex flex-col gap-[3px]",children:b.map(([v,{status:C,entities:E,isUncommitted:N}])=>{const A=s.has(v),_=x(E),$=E.reduce((T,j)=>{var B;const P=((B=j.metadata)==null?void 0:B.editedAt)||j.updatedAt;return P?T?new Date(P)>new Date(T)?P:T:P:T},null),I=E.filter(T=>T.entityType==="visual"||T.entityType==="library").length===0;let k;return I?k=t("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):_==="analyzing"?k=l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[t("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),t("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"?k=t("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"?k=t("button",{onClick:T=>{T.stopPropagation(),E.filter(j=>(j.entityType==="visual"||j.entityType==="library")&&!i(j.sha)&&!c(j)).forEach(j=>p(j))},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"&&(k=t("button",{onClick:T=>{T.stopPropagation(),E.filter(j=>(j.entityType==="visual"||j.entityType==="library")&&!i(j.sha)&&!c(j)).forEach(j=>p(j))},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"})),t(Vn,{filePath:v,isExpanded:A,onToggle:()=>m(v),fileStatus:C,isUncommitted:N,simulationPreviews:t(Qn,{entities:E,maxPreviews:1}),entityCount:E.length,state:_,lastModified:$,isNotAnalyzable:I,actionButton:k,children:E.sort((T,j)=>{const P=T.entityType==="visual"||T.entityType==="library",B=j.entityType==="visual"||j.entityType==="library";return P&&!B?-1:!P&&B?1:0}).map(T=>t(Kn,{entity:T,isActivelyAnalyzing:i(T.sha),isQueued:c(T),onGenerateSimulation:p},T.sha))},v)})})]}):l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[t("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Changes"}),t("p",{className:"font-['IBM_Plex_Sans'] font-normal text-[14px] text-[#3e3e3e] leading-[18px]",children:"No files have been modified in this branch."})]})})}function nf({files:e,entityImpactMap:r,expandedFiles:n,isEntityBeingAnalyzed:a,isEntityQueued:o,projectSlug:s,baseBranch:i,currentBranch:c,sortOrder:d,onToggleFile:m,onShowFileDiff:u,onGenerateSimulation:p,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}){const w=ne(()=>{const v=[];return e.forEach(([C,{editedEntities:E}])=>{const N=E.filter(A=>a(A.sha)||o(A)).map(A=>A.sha);N.length>0&&v.push({entityShas:N})}),v},[e,a,o]),x=ne(()=>{const v=new Map;return e.forEach(([C,{editedEntities:E}])=>{const N=E.map(D=>Ve(D,w));let A;N.includes("analyzing")||N.includes("queued")?A="analyzing":N.includes("out-of-date")?A="out-of-date":N.includes("not-analyzed")?A="not-analyzed":A="up-to-date";const _=E.reduce((D,I)=>{var T;const k=((T=I.metadata)==null?void 0:T.editedAt)||I.updatedAt;return k&&(!D||new Date(k)>new Date(D))?k:D},null),$=E.filter(D=>D.entityType==="visual"||D.entityType==="library").length;v.set(C,{state:A,lastModified:_,analyzableCount:$})}),v},[e,w]),b=ne(()=>[...e].sort((v,C)=>{const E=x.get(v[0]),N=x.get(C[0]),A=E==null?void 0:E.lastModified,_=N==null?void 0:N.lastModified;if(!A&&!_)return 0;if(!A)return 1;if(!_)return-1;const $=new Date(A).getTime(),D=new Date(_).getTime();return d==="desc"?D-$:$-D}),[e,x,d]);return e.length===0?l("div",{className:"bg-[#efefef] rounded-[10px] flex flex-col items-center justify-center text-center",style:{height:"190px"},children:[t("p",{className:"font-['IBM_Plex_Sans'] font-medium text-[16px] text-[#3e3e3e] leading-[24px] mb-2",children:"No Uncommitted Changes"}),t("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."})]}):l("div",{children:[t(Jn,{showActions:!0,sortOrder:d,onSortChange:h,onAnalyzeAll:f,analyzeAllDisabled:y,analyzeAllText:g}),t("div",{className:"flex flex-col gap-[3px]",children:b.map(([v,{status:C,editedEntities:E}])=>{const N=n.has(v),A=x.get(v),{state:_,lastModified:$,analyzableCount:D}=A,I=D===0;let k;return I?k=t("span",{className:"text-[12px] text-gray-400",children:"Not Analyzable"}):_==="analyzing"?k=l("span",{className:"text-[13px] px-2 rounded inline-flex items-center gap-1.5 whitespace-nowrap",style:{backgroundColor:"#ffdbf6",color:"#ff2ab5",height:"26px"},children:[l("svg",{width:"8",height:"8",viewBox:"0 0 9 9",fill:"none",className:"animate-spin",children:[t("circle",{cx:"4.5",cy:"4.5",r:"3.5",stroke:"#FFF4FC",strokeWidth:"1",fill:"none"}),t("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"?k=t("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"?k=t("button",{onClick:T=>{T.stopPropagation(),E.filter(j=>(j.entityType==="visual"||j.entityType==="library")&&!a(j.sha)&&!o(j)).forEach(j=>p(j))},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"&&(k=t("button",{onClick:T=>{T.stopPropagation(),E.filter(j=>(j.entityType==="visual"||j.entityType==="library")&&!a(j.sha)&&!o(j)).forEach(j=>p(j))},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"})),t(Vn,{filePath:v,isExpanded:N,onToggle:()=>m(v),fileStatus:C,simulationPreviews:t(Qn,{entities:E,maxPreviews:1}),entityCount:E.length,state:_,lastModified:$,isNotAnalyzable:I,isUncommitted:!0,actionButton:k,children:E.sort((T,j)=>{const P=T.entityType==="visual"||T.entityType==="library",B=j.entityType==="visual"||j.entityType==="library";return P&&!B?-1:!P&&B?1:0}).map(T=>t(Kn,{entity:T,isActivelyAnalyzing:a(T.sha),isQueued:o(T),onGenerateSimulation:p},T.sha))},v)})})]})}function af({activeTab:e,onTabChange:r,uncommittedCount:n,branchCount:a}){return t("div",{className:"border-b border-gray-200",children:l("nav",{className:"flex gap-8 items-center",children:[l("button",{onClick:()=>r("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:[l("span",{className:"flex items-center gap-2",children:["Branch Changes",a>0&&t("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:a})]}),e==="branch"&&t("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]}),l("button",{onClick:()=>r("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:[l("span",{className:"flex items-center gap-2",children:["Uncommitted Changes",n>0&&t("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:n})]}),e==="uncommitted"&&t("span",{className:"absolute -bottom-px left-0 right-0 h-0.5 bg-primary-100"})]})]})})}const of=()=>[{title:"Git - CodeYam"},{name:"description",content:"Git status and impact analysis"}];async function sf({request:e}){const r=await e.formData();if(r.get("actionType")==="getDiff"){const a=r.get("filePath"),o=r.get("diffType"),s=r.get("baseBranch"),i=r.get("currentBranch"),c=r.get("entitySha");let d;return o==="branch"?d=ur(a,s,i):d=ah(a),G({...d,entitySha:c})}return G({error:"Unknown action"},{status:400})}async function lf({request:e,context:r}){try{const n=new URL(e.url),a=n.searchParams.get("compare"),o=n.searchParams.get("viewBranch"),s=r.analysisQueue,i=s?s.getState():{paused:!1,jobs:[]},[c,d,m]=await Promise.all([Zt(),It(),ze()]),u=ds(),p=Xu(),h=eh(),f=th(),y=o||p,g=a||h;let w=[];return y&&y!==g&&(w=us(g,y)),G({entities:c||[],gitStatus:u,currentBranch:y,actualCurrentBranch:p,defaultBranch:h,allBranches:f,baseBranch:g,branchDiff:w,currentCommit:d,projectSlug:m,queueState:i})}catch(n){return console.error("Failed to load git data:",n),G({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 cf=Oe(function(){var Ce,tr;const{entities:r,gitStatus:n,currentBranch:a,actualCurrentBranch:o,defaultBranch:s,allBranches:i,baseBranch:c,branchDiff:d,currentCommit:m,projectSlug:u,queueState:p}=We();mt({source:"git-page"});const[h,f]=Jt(),[y,g]=M(null),[w,x]=M("desc"),[b,v]=M("branch"),C=h.get("expanded")==="true",E=()=>{x(ce=>ce==="desc"?"asc":"desc")},N=Ae(),A=N.data;re(()=>{a&&c&&a!==c&&N.state==="idle"&&!A&&N.load(`/api/branch-entity-diff?base=${encodeURIComponent(c)}&compare=${encodeURIComponent(a)}`)},[a,c,N,A]);const _=ne(()=>{const ce=bs(n,r);return Array.from(ce.entries()).sort((qe,Ge)=>qe[0].localeCompare(Ge[0]))},[n,r]),$=ne(()=>{const ce=Tp(d,r,A);return Array.from(ce.entries()).sort((qe,Ge)=>qe[0].localeCompare(Ge[0]))},[d,r,A]),D=ne(()=>Ip(n,r),[n,r]),I=ne(()=>b==="uncommitted"?_:$,[b,_,$]),k=ne(()=>I.map(([ce])=>ce),[I]),{expandedUncommitted:T,setExpandedUncommitted:j,toggleFile:P,expandAllUncommitted:B,collapseAllUncommitted:L}=Xp(C,k,[]),{diffView:z,diffContent:O,isLoading:F,handleShowFileDiff:R,handleCloseDiff:S}=ef(c,a),H=(Ce=m==null?void 0:m.metadata)==null?void 0:Ce.currentRun,q=new Set((H==null?void 0:H.currentEntityShas)||[]),J=new Set(p.jobs.flatMap(ce=>ce.entityShas||[])),ae=new Set(((tr=p.currentlyExecuting)==null?void 0:tr.entityShas)||[]),{isAnalyzing:V,handleGenerateSimulation:Y,handleGenerateAllSimulations:U,isEntityBeingAnalyzed:Q,isEntityPending:W}=Ns(H==null?void 0:H.currentEntityShas,p),Z=ce=>W(ce)||J.has(ce.sha)||ae.has(ce.sha),de=ce=>{ce===(o||a)?h.delete("viewBranch"):h.set("viewBranch",ce),f(h)},ue=ce=>{ce===s?h.delete("compare"):h.set("compare",ce),f(h)},ge=()=>{const qe=I.flatMap(([Ge,zr])=>zr.editedEntities||zr.entities||[]).filter(Ge=>!q.has(Ge.sha)&&!J.has(Ge.sha)&&!ae.has(Ge.sha)&&!W(Ge));U(qe)},be=_.length,Ne=$.length,we=I.flatMap(([ce,qe])=>qe.editedEntities||qe.entities||[]),ke=we.filter(ce=>ce.entityType==="visual"||ce.entityType==="library"),Te=ke.length>0&&ke.every(ce=>q.has(ce.sha)),ye=ke.length>0&&!Te&&ke.every(ce=>J.has(ce.sha)||ae.has(ce.sha)),je=V||Te||ye,Pe=Te?"Analyzing...":ye?"Queued...":V?"Analyzing...":"Analyze All";return t("div",{className:"bg-[#F8F7F6] min-h-screen",children:l("div",{className:"px-20 py-12",children:[l("div",{className:"mb-8",children:[t("h1",{className:"text-[28px] font-semibold text-gray-900 mb-2",children:"Git Changes"}),l("p",{className:"text-[15px] text-gray-500",children:["This is a list of all the files that are affected by your local changes. ",t("strong",{children:"Analyze a file to get simulations."})]})]}),t("div",{className:"mb-6",children:t(af,{activeTab:b,onTabChange:v,uncommittedCount:be,branchCount:Ne})}),a&&b==="branch"&&t("div",{className:"bg-white border-b border-gray-200 rounded-t-lg px-5 py-4 mb-3",children:a===s?l("div",{className:"text-gray-700",children:["You are currently on the primary branch,"," ",t("span",{className:"text-cyblack-75",children:s}),"."]}):l("div",{className:"flex gap-6 items-center",children:[l("div",{className:"shrink-0",children:[t("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Changes in Branch:"}),i.length>0?l("div",{className:"relative w-50",children:[t("select",{value:a,onChange:ce=>de(ce.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(ce=>t("option",{value:ce,children:ce},ce))}),t("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:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}):t("span",{className:"text-gray-900 font-medium text-[12px]",children:a})]}),l("div",{className:"flex-shrink-0",children:[t("div",{className:"text-[11px] text-gray-500 mb-2 uppercase",children:"Compared To:"}),l("div",{className:"relative w-[200px]",children:[t("select",{value:c,onChange:ce=>ue(ce.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(ce=>ce!==a).map(ce=>t("option",{value:ce,children:ce},ce))}),t("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:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]})]}),t("div",{className:"flex-1 mt-6",children:l("div",{className:"relative flex items-center",children:[t("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:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),t("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"})]})})]})}),t("div",{className:"mb-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center",children:[l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em"},children:[t("span",{style:{color:"#000000"},children:I.length})," ","modified ",I.length===1?"file":"files"]}),l("div",{className:"relative group inline-flex items-center ml-1.5",children:[t("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:t("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"})}),t("div",{className:"absolute left-0 top-full mt-2 hidden group-hover:block z-50 w-80",children:l("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.",t("div",{className:"absolute -top-1 left-4 w-2 h-2 bg-gray-900 transform rotate-45"})]})})]}),t("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#d1d5db",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:"|"}),l("span",{className:"font-mono uppercase",style:{fontSize:"11px",color:"#8b8b8b",fontWeight:500,letterSpacing:"0.05em",marginLeft:"8px"},children:[t("span",{style:{color:"#000000"},children:we.length})," ",we.length===1?"entity":"entities"]})]}),I.length>0&&l("div",{className:"flex gap-6",children:[l("button",{onClick:B,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:[t(po,{className:"w-3.5 h-3.5"}),"Expand All"]}),l("button",{onClick:L,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:[t(fo,{className:"w-3.5 h-3.5"}),"Collapse All"]})]})]})}),l("div",{className:"overflow-hidden",children:[b==="branch"&&a&&t(rf,{files:$,currentBranch:a,defaultBranch:s,baseBranch:c,allBranches:i,expandedFiles:T,isEntityBeingAnalyzed:Q,isEntityQueued:Z,sortOrder:w,onToggleFile:ce=>P(ce,T,j),onBranchChange:ue,onGenerateSimulation:Y,onSortChange:E,onAnalyzeAll:ge,analyzeAllDisabled:je,analyzeAllText:Pe}),b==="uncommitted"&&t(nf,{files:_,entityImpactMap:D,expandedFiles:T,isEntityBeingAnalyzed:Q,isEntityQueued:Z,projectSlug:u,baseBranch:c,currentBranch:a,sortOrder:w,onToggleFile:ce=>P(ce,T,j),onShowFileDiff:R,onGenerateSimulation:Y,onSortChange:E,onAnalyzeAll:ge,analyzeAllDisabled:je,analyzeAllText:Pe})]}),z&&t(tf,{diffView:z,diffContent:O,isLoading:F,entities:r,onClose:S}),y&&u&&t(dt,{projectSlug:u,onClose:()=>g(null)})]})})}),df=Object.freeze(Object.defineProperty({__proto__:null,action:sf,default:cf,loader:lf,meta:of},Symbol.toStringTag,{value:"Module"})),ag={entry:{module:"/assets/entry.client-CS2cb_eZ.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/index-B1h680n5.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,hasErrorBoundary:!1,module:"/assets/root-eVAaavTS.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/index-B1h680n5.js","/assets/preload-helper-ckwbz45p.js","/assets/cy-logo-cli-DcX-ZS3p.js","/assets/ReportIssueModal-OApQuNyq.js","/assets/useReportContext-DYxHZQuP.js","/assets/loader-circle-B7B9V-bu.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/useToast-mBRpZPiu.js","/assets/useLastLogLine-aSv48UbS.js","/assets/LogViewer-xgeCVgSM.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/TruncatedFilePath-DyFZkK0l.js","/assets/chevron-down-Cx24_aWc.js","/assets/circle-check-BOARzkeR.js","/assets/triangle-alert-B6LgvRJg.js","/assets/copy-Bb-80kDT.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,hasErrorBoundary:!1,module:"/assets/entity._sha.scenarios._scenarioId.fullscreen-DavjRmOY.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useCustomSizes-C1v1PQzo.js","/assets/cy-logo-cli-DcX-ZS3p.js"],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,hasErrorBoundary:!1,module:"/assets/entity._sha_.edit._scenarioId-CTBG2mmz.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/InteractivePreview-aht4aafF.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-aSv48UbS.js"],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,hasErrorBoundary:!1,module:"/assets/entity._sha_.create-scenario-D1T4TGjf.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/InteractivePreview-aht4aafF.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/preload-helper-ckwbz45p.js","/assets/useLastLogLine-aSv48UbS.js"],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,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.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,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.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,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,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.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,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.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,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.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,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,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,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.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,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.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,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,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,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,hasErrorBoundary:!1,module:"/assets/api.save-scenarios-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,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.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,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,hasErrorBoundary:!1,module:"/assets/activity.(_tab)-BwavGCpm.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/LogViewer-xgeCVgSM.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useReportContext-DYxHZQuP.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/EntityTypeBadge-DLqD3qNt.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LoadingDots-B0GLXMsr.js","/assets/loader-circle-B7B9V-bu.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/file-code-Dhef1kWN.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,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.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,hasErrorBoundary:!1,module:"/assets/api.recapture-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,hasErrorBoundary:!1,module:"/assets/entity._sha._-BJUiQqZF.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useLastLogLine-aSv48UbS.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/InteractivePreview-aht4aafF.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LibraryFunctionPreview-CVtiBnY5.js","/assets/LoadingDots-B0GLXMsr.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/ScenarioViewer-DzccYyI8.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/executionFlowCoverage-BWhdfn70.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/LogViewer-xgeCVgSM.js","/assets/useReportContext-DYxHZQuP.js","/assets/preload-helper-ckwbz45p.js","/assets/useCustomSizes-C1v1PQzo.js","/assets/ReportIssueModal-OApQuNyq.js","/assets/circle-check-BOARzkeR.js","/assets/triangle-alert-B6LgvRJg.js","/assets/copy-Bb-80kDT.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,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,hasErrorBoundary:!1,module:"/assets/simulations-DwFIBT09.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LoadingDots-B0GLXMsr.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/fileTableUtils-DMJ7zii9.js","/assets/chevron-down-Cx24_aWc.js","/assets/search-CxXUmBSd.js","/assets/loader-circle-B7B9V-bu.js","/assets/createLucideIcon-BdhJEx6B.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,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,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,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,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,hasErrorBoundary:!1,module:"/assets/dev.empty-BBnGWYga.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/ScenarioViewer-DzccYyI8.js","/assets/InteractivePreview-aht4aafF.js","/assets/useCustomSizes-C1v1PQzo.js","/assets/LogViewer-xgeCVgSM.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/useLastLogLine-aSv48UbS.js","/assets/InlineSpinner-C8lyxW9k.js","/assets/preload-helper-ckwbz45p.js","/assets/ReportIssueModal-OApQuNyq.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/circle-check-BOARzkeR.js","/assets/triangle-alert-B6LgvRJg.js","/assets/copy-Bb-80kDT.js","/assets/scenarioStatus-B_8jpV3e.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,hasErrorBoundary:!1,module:"/assets/settings-CS5f3WzT.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.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,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,hasErrorBoundary:!1,module:"/assets/_index-BwqWJOgH.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useLastLogLine-aSv48UbS.js","/assets/useToast-mBRpZPiu.js","/assets/useReportContext-DYxHZQuP.js","/assets/LogViewer-xgeCVgSM.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/circle-check-BOARzkeR.js","/assets/loader-circle-B7B9V-bu.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,hasErrorBoundary:!1,module:"/assets/memory-yxFcrxBX.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/chevron-down-Cx24_aWc.js","/assets/copy-Bb-80kDT.js","/assets/search-CxXUmBSd.js","/assets/file-code-Dhef1kWN.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,hasErrorBoundary:!1,module:"/assets/files-CJ6lTdTA.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js","/assets/EntityItem-DsN1wKrm.js","/assets/fileTableUtils-DMJ7zii9.js","/assets/chevron-down-Cx24_aWc.js","/assets/search-CxXUmBSd.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/useToast-mBRpZPiu.js","/assets/TruncatedFilePath-DyFZkK0l.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LibraryFunctionPreview-CVtiBnY5.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-B6LgvRJg.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/EntityTypeBadge-DLqD3qNt.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,hasErrorBoundary:!1,module:"/assets/git-CPTZZ-JZ.js",imports:["/assets/chunk-EPOLDU6W-CXRTFQ3F.js","/assets/useReportContext-DYxHZQuP.js","/assets/EntityItem-DsN1wKrm.js","/assets/LogViewer-xgeCVgSM.js","/assets/fileTableUtils-DMJ7zii9.js","/assets/createLucideIcon-BdhJEx6B.js","/assets/useToast-mBRpZPiu.js","/assets/TruncatedFilePath-DyFZkK0l.js","/assets/SafeScreenshot-DuDvi0jm.js","/assets/LibraryFunctionPreview-CVtiBnY5.js","/assets/scenarioStatus-B_8jpV3e.js","/assets/triangle-alert-B6LgvRJg.js","/assets/EntityTypeIcon-Ba2JVPzP.js","/assets/EntityTypeBadge-DLqD3qNt.js"],css:[],clientActionModule:void 0,clientLoaderModule:void 0,clientMiddlewareModule:void 0,hydrateFallbackModule:void 0}},url:"/assets/manifest-7522edd4.js",version:"7522edd4",sri:void 0},og="build/client",sg="/",ig={unstable_optimizeDeps:!1,unstable_subResourceIntegrity:!1,v8_middleware:!1,v8_splitRouteModules:!1,v8_viteEnvironmentApi:!1},lg=!0,cg=!1,dg=[],ug={mode:"lazy",manifestPath:"/__manifest"},hg="/",mg={module:Vi},pg={root:{id:"root",parentId:void 0,path:"",index:void 0,caseSensitive:void 0,module:ud},"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:gd},"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:Fd},"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:Hd},"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:Wu},"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:Gu},"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:hh},"routes/api.capture-screenshot":{id:"routes/api.capture-screenshot",parentId:"root",path:"api/capture-screenshot",index:void 0,caseSensitive:void 0,module:ph},"routes/api.recapture-scenario":{id:"routes/api.recapture-scenario",parentId:"root",path:"api/recapture-scenario",index:void 0,caseSensitive:void 0,module:xh},"routes/api.logs.$projectSlug":{id:"routes/api.logs.$projectSlug",parentId:"root",path:"api/logs/:projectSlug",index:void 0,caseSensitive:void 0,module:vh},"routes/api.execute-function":{id:"routes/api.execute-function",parentId:"root",path:"api/execute-function",index:void 0,caseSensitive:void 0,module:Sh},"routes/api.interactive-mode":{id:"routes/api.interactive-mode",parentId:"root",path:"api/interactive-mode",index:void 0,caseSensitive:void 0,module:kh},"routes/api.delete-scenario":{id:"routes/api.delete-scenario",parentId:"root",path:"api/delete-scenario",index:void 0,caseSensitive:void 0,module:_h},"routes/api.generate-report":{id:"routes/api.generate-report",parentId:"root",path:"api/generate-report",index:void 0,caseSensitive:void 0,module:Yh},"routes/api.memory-profile":{id:"routes/api.memory-profile",parentId:"root",path:"api/memory-profile",index:void 0,caseSensitive:void 0,module:qh},"routes/api.process-status":{id:"routes/api.process-status",parentId:"root",path:"api/process-status",index:void 0,caseSensitive:void 0,module:Qh},"routes/api.restart-server":{id:"routes/api.restart-server",parentId:"root",path:"api/restart-server",index:void 0,caseSensitive:void 0,module:em},"routes/api.save-scenarios":{id:"routes/api.save-scenarios",parentId:"root",path:"api/save-scenarios",index:void 0,caseSensitive:void 0,module:rm},"routes/api.kill-process":{id:"routes/api.kill-process",parentId:"root",path:"api/kill-process",index:void 0,caseSensitive:void 0,module:am},"routes/api.screenshot.$":{id:"routes/api.screenshot.$",parentId:"root",path:"api/screenshot/*",index:void 0,caseSensitive:void 0,module:sm},"routes/activity.($tab)":{id:"routes/activity.($tab)",parentId:"root",path:"activity/:tab?",index:void 0,caseSensitive:void 0,module:fm},"routes/api.debug-setup":{id:"routes/api.debug-setup",parentId:"root",path:"api/debug-setup",index:void 0,caseSensitive:void 0,module:xm},"routes/api.recapture":{id:"routes/api.recapture",parentId:"root",path:"api/recapture",index:void 0,caseSensitive:void 0,module:wm},"routes/entity.$sha.$":{id:"routes/entity.$sha.$",parentId:"root",path:"entity/:sha/*",index:void 0,caseSensitive:void 0,module:Wm},"routes/api.analyze":{id:"routes/api.analyze",parentId:"root",path:"api/analyze",index:void 0,caseSensitive:void 0,module:Gm},"routes/simulations":{id:"routes/simulations",parentId:"root",path:"simulations",index:void 0,caseSensitive:void 0,module:ep},"routes/api.events":{id:"routes/api.events",parentId:"root",path:"api/events",index:void 0,caseSensitive:void 0,module:rp},"routes/api.health":{id:"routes/api.health",parentId:"root",path:"api/health",index:void 0,caseSensitive:void 0,module:ap},"routes/api.memory":{id:"routes/api.memory",parentId:"root",path:"api/memory",index:void 0,caseSensitive:void 0,module:pp},"routes/api.queue":{id:"routes/api.queue",parentId:"root",path:"api/queue",index:void 0,caseSensitive:void 0,module:yp},"routes/dev.empty":{id:"routes/dev.empty",parentId:"root",path:"dev/empty",index:void 0,caseSensitive:void 0,module:wp},"routes/settings":{id:"routes/settings",parentId:"root",path:"settings",index:void 0,caseSensitive:void 0,module:kp},"routes/static.$":{id:"routes/static.$",parentId:"root",path:"static/*",index:void 0,caseSensitive:void 0,module:_p},"routes/_index":{id:"routes/_index",parentId:"root",path:void 0,index:!0,caseSensitive:void 0,module:Fp},"routes/memory":{id:"routes/memory",parentId:"root",path:"memory",index:void 0,caseSensitive:void 0,module:qp},"routes/files":{id:"routes/files",parentId:"root",path:"files",index:void 0,caseSensitive:void 0,module:Zp},"routes/git":{id:"routes/git",parentId:"root",path:"git",index:void 0,caseSensitive:void 0,module:df}};export{rc as A,ec as B,ve as C,Al as D,kl as E,At as F,fl as G,Ao as H,ko as I,Po as J,wl as K,Cl as L,og as M,sg as N,ig as O,ml as P,lg as Q,cg as R,pr as S,dg as T,ug as U,hg as V,mg as W,pg as X,ag as Y,ll as a,Pt as b,St as c,nt as d,Qt as e,Tn as f,In as g,Eo as h,sl as i,Ll as j,Fl as k,ut as l,at as m,To as n,ql as o,gr as p,ht as q,Io as r,$o as s,Kl as t,ct as u,jo as v,Tt as w,Zl as x,_a as y,ac as z};
|